summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--config.tests/arch/arch.cpp42
-rw-r--r--config.tests/common/c++11/c++11.cpp10
-rw-r--r--config.tests/common/c++default/c++default.cpp1
-rw-r--r--config.tests/common/c++default/c++default.pro14
-rw-r--r--config.tests/qpa/mirclient/mirclient.cpp47
-rw-r--r--config.tests/qpa/mirclient/mirclient.pro4
-rw-r--r--config.tests/unix/cloexec/cloexec.cpp49
-rw-r--r--config.tests/unix/cloexec/cloexec.pro3
-rw-r--r--config.tests/unix/freetype/freetype.pri1
-rwxr-xr-xconfig.tests/unix/ptrsize.test5
-rw-r--r--config.tests/unix/syslog/syslog.c42
-rw-r--r--config.tests/unix/syslog/syslog.pro3
-rw-r--r--config.tests/win/directwrite/directwrite.cpp44
-rw-r--r--config.tests/win/directwrite/directwrite.pro4
-rwxr-xr-xconfigure178
-rw-r--r--doc/global/html-header-online.qdocconf2
-rw-r--r--doc/global/qt-cpp-defines.qdocconf5
-rw-r--r--doc/global/template/scripts/extras.js72
-rw-r--r--doc/global/template/style/list_expand.pngbin0 -> 710 bytes
-rw-r--r--doc/global/template/style/online.css54
-rw-r--r--doc/src/images/recentfiles-example.pngbin5400 -> 0 bytes
-rw-r--r--examples/opengl/hellogl2/mainwindow.cpp2
-rw-r--r--examples/opengl/hellogl2/window.cpp14
-rw-r--r--examples/opengl/hellogles3/glwindow.cpp281
-rw-r--r--examples/opengl/hellogles3/glwindow.h (renamed from examples/widgets/mainwindows/recentfiles/mainwindow.h)88
-rw-r--r--examples/opengl/hellogles3/hellogles3.pro11
-rw-r--r--examples/opengl/hellogles3/hellogles3.qrc5
-rw-r--r--examples/opengl/hellogles3/main.cpp78
-rw-r--r--examples/opengl/hellogles3/qtlogo.pngbin0 -> 5402 bytes
-rw-r--r--examples/opengl/opengl.pro3
-rw-r--r--examples/qtconcurrent/map/main.cpp2
-rw-r--r--examples/sql/books/books.pro2
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/anim_accord.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/anim_gallery.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/anim_panel.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/anim_skew.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_backgrounds.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_border-img.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_grad-radial.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_mask-grad.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_mask-img.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/css3_text-overflow.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/form_tapper.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/mob_condjs.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/mobile.js0
-rw-r--r--[-rwxr-xr-x]examples/webkit/webkit-guide/js/storage.js0
-rw-r--r--examples/widgets/dialogs/classwizard/classwizard.cpp20
-rw-r--r--examples/widgets/dialogs/configdialog/configdialog.cpp6
-rw-r--r--examples/widgets/dialogs/extension/finddialog.cpp2
-rw-r--r--examples/widgets/dialogs/findfiles/window.cpp19
-rw-r--r--examples/widgets/dialogs/findfiles/window.h1
-rw-r--r--examples/widgets/dialogs/licensewizard/licensewizard.cpp10
-rw-r--r--examples/widgets/dialogs/sipdialog/dialog.cpp7
-rw-r--r--examples/widgets/dialogs/standarddialogs/dialog.cpp47
-rw-r--r--examples/widgets/dialogs/standarddialogs/main.cpp5
-rw-r--r--examples/widgets/dialogs/tabdialog/tabdialog.cpp4
-rw-r--r--examples/widgets/doc/images/regularexpression-example.pngbin0 -> 78860 bytes
-rw-r--r--examples/widgets/doc/src/application.qdoc75
-rw-r--r--examples/widgets/doc/src/findfiles.qdoc7
-rw-r--r--examples/widgets/doc/src/imageviewer.qdoc11
-rw-r--r--examples/widgets/doc/src/regularexpression.qdoc (renamed from examples/widgets/doc/src/recentfiles.qdoc)23
-rw-r--r--examples/widgets/doc/src/tablet.qdoc24
-rw-r--r--examples/widgets/draganddrop/puzzle/puzzle.pro2
-rw-r--r--examples/widgets/itemviews/addressbook/adddialog.cpp4
-rw-r--r--examples/widgets/itemviews/addressbook/addresswidget.cpp10
-rw-r--r--examples/widgets/itemviews/addressbook/addresswidget.h2
-rw-r--r--examples/widgets/itemviews/addressbook/mainwindow.cpp16
-rw-r--r--examples/widgets/itemviews/addressbook/newaddresstab.cpp2
-rw-r--r--examples/widgets/itemviews/basicsortfiltermodel/window.cpp22
-rw-r--r--examples/widgets/itemviews/chart/mainwindow.cpp25
-rw-r--r--examples/widgets/itemviews/chart/mainwindow.h3
-rw-r--r--examples/widgets/itemviews/combowidgetmapper/window.cpp12
-rw-r--r--examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp6
-rw-r--r--examples/widgets/itemviews/customsortfiltermodel/window.cpp14
-rw-r--r--examples/widgets/itemviews/editabletreemodel/mainwindow.cpp30
-rw-r--r--examples/widgets/itemviews/editabletreemodel/mainwindow.h4
-rw-r--r--examples/widgets/itemviews/fetchmore/window.cpp12
-rw-r--r--examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp18
-rw-r--r--examples/widgets/itemviews/pixelator/mainwindow.cpp17
-rw-r--r--examples/widgets/itemviews/puzzle/main.cpp2
-rw-r--r--examples/widgets/itemviews/puzzle/mainwindow.cpp45
-rw-r--r--examples/widgets/itemviews/puzzle/mainwindow.h3
-rw-r--r--examples/widgets/itemviews/simpledommodel/mainwindow.cpp4
-rw-r--r--examples/widgets/itemviews/simplewidgetmapper/window.cpp6
-rw-r--r--examples/widgets/itemviews/spreadsheet/spreadsheet.cpp50
-rw-r--r--examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp2
-rw-r--r--examples/widgets/itemviews/stardelegate/stardelegate.cpp4
-rw-r--r--examples/widgets/mainwindows/application/main.cpp16
-rw-r--r--examples/widgets/mainwindows/application/mainwindow.cpp196
-rw-r--r--examples/widgets/mainwindows/application/mainwindow.h21
-rw-r--r--examples/widgets/mainwindows/dockwidgets/mainwindow.cpp95
-rw-r--r--examples/widgets/mainwindows/dockwidgets/mainwindow.h14
-rw-r--r--examples/widgets/mainwindows/mainwindow/colorswatch.cpp211
-rw-r--r--examples/widgets/mainwindows/mainwindow/colorswatch.h78
-rw-r--r--examples/widgets/mainwindows/mainwindow/main.cpp67
-rw-r--r--examples/widgets/mainwindows/mainwindow/mainwindow.cpp215
-rw-r--r--examples/widgets/mainwindows/mainwindow/mainwindow.h31
-rw-r--r--examples/widgets/mainwindows/mainwindow/toolbar.cpp88
-rw-r--r--examples/widgets/mainwindows/mainwindow/toolbar.h66
-rw-r--r--examples/widgets/mainwindows/mainwindows.pro1
-rw-r--r--examples/widgets/mainwindows/mdi/main.cpp2
-rw-r--r--examples/widgets/mainwindows/mdi/mainwindow.cpp334
-rw-r--r--examples/widgets/mainwindows/mdi/mainwindow.h31
-rw-r--r--examples/widgets/mainwindows/mdi/mdichild.cpp39
-rw-r--r--examples/widgets/mainwindows/menus/mainwindow.cpp44
-rw-r--r--examples/widgets/mainwindows/recentfiles/mainwindow.cpp251
-rw-r--r--examples/widgets/mainwindows/recentfiles/recentfiles.pro9
-rw-r--r--examples/widgets/mainwindows/sdi/main.cpp25
-rw-r--r--examples/widgets/mainwindows/sdi/mainwindow.cpp350
-rw-r--r--examples/widgets/mainwindows/sdi/mainwindow.h41
-rw-r--r--examples/widgets/painting/fontsampler/mainwindow.cpp2
-rw-r--r--examples/widgets/richtext/syntaxhighlighter/syntaxhighlighter.pro2
-rw-r--r--examples/widgets/tools/regularexpression/images/copy.pngbin0 -> 1338 bytes
-rw-r--r--examples/widgets/tools/regularexpression/main.cpp (renamed from examples/widgets/mainwindows/recentfiles/main.cpp)10
-rw-r--r--examples/widgets/tools/regularexpression/regularexpression.pro11
-rw-r--r--examples/widgets/tools/regularexpression/regularexpression.qrc5
-rw-r--r--examples/widgets/tools/regularexpression/regularexpressiondialog.cpp349
-rw-r--r--examples/widgets/tools/regularexpression/regularexpressiondialog.h100
-rw-r--r--examples/widgets/tools/tools.pro1
-rw-r--r--examples/widgets/tutorials/addressbook/part7/addressbook.cpp1
-rw-r--r--examples/widgets/widgets/icons/icons.pro2
-rw-r--r--examples/widgets/widgets/imageviewer/imageviewer.cpp214
-rw-r--r--examples/widgets/widgets/imageviewer/imageviewer.h17
-rw-r--r--examples/widgets/widgets/movie/movie.pro2
-rw-r--r--examples/widgets/widgets/tablet/images.qrc8
-rw-r--r--examples/widgets/widgets/tablet/images/cursor-airbrush.pngbin0 -> 823 bytes
-rw-r--r--examples/widgets/widgets/tablet/images/cursor-eraser.pngbin0 -> 1454 bytes
-rw-r--r--examples/widgets/widgets/tablet/images/cursor-felt-marker.pngbin0 -> 513 bytes
-rw-r--r--examples/widgets/widgets/tablet/images/cursor-pencil.pngbin0 -> 1307 bytes
-rw-r--r--examples/widgets/widgets/tablet/mainwindow.cpp11
-rw-r--r--examples/widgets/widgets/tablet/mainwindow.h1
-rw-r--r--examples/widgets/widgets/tablet/tablet.pro11
-rw-r--r--examples/widgets/widgets/tablet/tabletapplication.cpp3
-rw-r--r--examples/widgets/widgets/tablet/tabletcanvas.cpp151
-rw-r--r--examples/widgets/widgets/tablet/tabletcanvas.h15
-rw-r--r--examples/xml/dombookmarks/dombookmarks.pro2
-rw-r--r--examples/xml/htmlinfo/htmlinfo.pro2
-rw-r--r--examples/xml/saxbookmarks/saxbookmarks.pro2
-rw-r--r--mkspecs/common/clang-mac.conf5
-rw-r--r--mkspecs/common/clang.conf1
-rw-r--r--mkspecs/common/g++-base.conf1
-rw-r--r--mkspecs/common/mac/qplatformdefs.h1
-rw-r--r--mkspecs/common/msvc-desktop.conf2
-rw-r--r--mkspecs/common/wince/qmake.conf2
-rw-r--r--mkspecs/common/winrt_winphone/qmake.conf2
-rw-r--r--mkspecs/common/winrt_winphone/qplatformdefs.h10
-rw-r--r--mkspecs/cygwin-g++/qmake.conf2
-rw-r--r--mkspecs/devices/common/linux_device_post.conf4
-rw-r--r--mkspecs/devices/linux-beagleboard-g++/qmake.conf7
-rw-r--r--mkspecs/devices/linux-nuc-g++/qmake.conf20
-rw-r--r--mkspecs/devices/linux-nuc-g++/qplatformdefs.h34
-rw-r--r--mkspecs/features/c++11.prf17
-rw-r--r--mkspecs/features/c++14.prf12
-rw-r--r--mkspecs/features/lex.prf21
-rw-r--r--mkspecs/features/plugin_bundle.prf2
-rw-r--r--mkspecs/features/qt.prf11
-rw-r--r--mkspecs/features/qt_common.prf2
-rw-r--r--mkspecs/features/resources.prf60
-rw-r--r--mkspecs/features/yacc.prf12
-rw-r--r--mkspecs/linux-icc/qmake.conf1
-rw-r--r--mkspecs/macx-icc/qmake.conf1
-rw-r--r--[-rwxr-xr-x]mkspecs/macx-ios-clang/Info.plist.app0
-rw-r--r--mkspecs/macx-ios-clang/features/default_post.prf183
-rw-r--r--mkspecs/macx-ios-clang/features/exclusive_builds_post.prf8
-rw-r--r--mkspecs/macx-ios-clang/features/qt.prf34
-rw-r--r--mkspecs/macx-ios-clang/features/resolve_config.prf64
-rw-r--r--mkspecs/macx-ios-clang/features/testcase.prf12
-rw-r--r--mkspecs/macx-ios-clang/features/testcase_targets.prf3
-rw-r--r--mkspecs/macx-ios-clang/features/xcodebuild.prf49
-rwxr-xr-xmkspecs/macx-ios-clang/ios_destinations.sh (renamed from mkspecs/macx-ios-clang/rename_main.sh)61
-rw-r--r--mkspecs/macx-ios-clang/qmake.conf2
-rw-r--r--mkspecs/macx-ios-clang/xcodebuild.mk96
-rw-r--r--mkspecs/win32-g++/qmake.conf3
-rw-r--r--mkspecs/win32-icc/qmake.conf2
-rw-r--r--qmake/Makefile.unix6
-rw-r--r--qmake/Makefile.win321
-rw-r--r--qmake/doc/snippets/code/doc_src_qmake-manual.pro21
-rw-r--r--qmake/doc/src/qmake-manual.qdoc97
-rw-r--r--qmake/generators/unix/unixmake2.cpp14
-rw-r--r--qmake/generators/win32/cesdkhandler.cpp22
-rw-r--r--qmake/generators/win32/mingw_make.cpp7
-rw-r--r--qmake/generators/win32/msvc_vcproj.cpp10
-rw-r--r--qmake/generators/win32/winmakefile.cpp17
-rw-r--r--qmake/library/qmakeevaluator.cpp3
-rw-r--r--qmake/library/qmakeevaluator.h1
-rwxr-xr-x[-rw-r--r--]src/3rdparty/angle/src/libANGLE/renderer/d3d/SurfaceD3D.cpp1
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp46
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp21
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h4
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp21
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h10
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp30
-rw-r--r--src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h7
-rw-r--r--src/3rdparty/forkfd/forkfd.c133
-rw-r--r--src/3rdparty/harfbuzz-ng/src/hb-private.hh9
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-32-rvk.macros0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-32.macros0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-64.macros0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-int-set.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-interface.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-opt32-settings.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-opt32.c0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-opt64-settings.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakF-1600-unrolling.macros0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakNISTInterface.c0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakNISTInterface.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakSponge.c0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/KeccakSponge.h0
-rw-r--r--[-rwxr-xr-x]src/3rdparty/sha3/brg_endian.h0
-rw-r--r--src/3rdparty/sqlite/sqlite3.c2
-rw-r--r--src/3rdparty/zlib/0001-Fix-WEC2013-build-of-zlib.patch26
-rw-r--r--src/3rdparty/zlib/zutil.h2
-rw-r--r--src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java42
-rw-r--r--src/android/jar/src/org/qtproject/qt5/android/QtNative.java69
-rw-r--r--src/angle/patches/0008-ANGLE-Use-pixel-sizes-in-the-XAML-swap-chain.patch361
-rw-r--r--src/angle/src/common/common.pri2
-rw-r--r--src/corelib/animation/qabstractanimation.h8
-rw-r--r--src/corelib/animation/qanimationgroup.h2
-rw-r--r--src/corelib/animation/qparallelanimationgroup.h2
-rw-r--r--src/corelib/animation/qpauseanimation.h4
-rw-r--r--src/corelib/animation/qpropertyanimation.h4
-rw-r--r--src/corelib/animation/qsequentialanimationgroup.h2
-rw-r--r--src/corelib/animation/qsequentialanimationgroup_p.h2
-rw-r--r--src/corelib/animation/qvariantanimation.h4
-rw-r--r--src/corelib/codecs/qtextcodec.cpp1
-rw-r--r--src/corelib/codecs/qtextcodec.h6
-rw-r--r--src/corelib/corelib.pro6
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_codecs_qtextcodec.cpp10
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp6
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp19
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp19
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_tools_qvector.cpp17
-rw-r--r--src/corelib/doc/src/external-resources.qdoc9
-rw-r--r--src/corelib/doc/src/objectmodel/properties.qdoc9
-rw-r--r--src/corelib/global/global.pri4
-rw-r--r--src/corelib/global/qflags.h2
-rw-r--r--src/corelib/global/qglobal.cpp148
-rw-r--r--src/corelib/global/qglobal.h75
-rw-r--r--src/corelib/global/qlogging.cpp32
-rw-r--r--src/corelib/global/qlogging.h3
-rw-r--r--src/corelib/global/qnamespace.h29
-rw-r--r--src/corelib/global/qnamespace.qdoc71
-rw-r--r--src/corelib/global/qsysinfo.h28
-rw-r--r--src/corelib/global/qtypeinfo.h72
-rw-r--r--src/corelib/io/forkfd_qt.cpp7
-rw-r--r--src/corelib/io/qabstractfileengine.cpp1
-rw-r--r--src/corelib/io/qbuffer.h4
-rw-r--r--src/corelib/io/qdatastream.cpp1
-rw-r--r--src/corelib/io/qdatastream.h5
-rw-r--r--src/corelib/io/qdebug.cpp27
-rw-r--r--src/corelib/io/qdebug.h25
-rw-r--r--src/corelib/io/qdir.cpp12
-rw-r--r--src/corelib/io/qdir.h16
-rw-r--r--src/corelib/io/qfile.h2
-rw-r--r--src/corelib/io/qfiledevice.cpp2
-rw-r--r--src/corelib/io/qfiledevice.h2
-rw-r--r--src/corelib/io/qfileinfo.h5
-rw-r--r--src/corelib/io/qfileselector.h2
-rw-r--r--src/corelib/io/qfilesystemengine_win.cpp5
-rw-r--r--src/corelib/io/qfilesystemwatcher.h4
-rw-r--r--src/corelib/io/qfilesystemwatcher_fsevents.mm31
-rw-r--r--src/corelib/io/qfsfileengine_win.cpp4
-rw-r--r--src/corelib/io/qiodevice.cpp64
-rw-r--r--src/corelib/io/qiodevice.h2
-rw-r--r--src/corelib/io/qiodevice_p.h1
-rw-r--r--src/corelib/io/qlockfile_unix.cpp1
-rw-r--r--src/corelib/io/qloggingcategory.cpp9
-rw-r--r--src/corelib/io/qloggingregistry.cpp68
-rw-r--r--src/corelib/io/qloggingregistry_p.h1
-rw-r--r--src/corelib/io/qprocess.cpp146
-rw-r--r--src/corelib/io/qprocess.h27
-rw-r--r--src/corelib/io/qprocess_p.h2
-rw-r--r--src/corelib/io/qprocess_unix.cpp49
-rw-r--r--src/corelib/io/qprocess_win.cpp44
-rw-r--r--src/corelib/io/qprocess_wince.cpp9
-rw-r--r--src/corelib/io/qresource.cpp2
-rw-r--r--src/corelib/io/qsavefile.h2
-rw-r--r--src/corelib/io/qsettings.cpp28
-rw-r--r--src/corelib/io/qsettings.h10
-rw-r--r--src/corelib/io/qsettings_mac.cpp9
-rw-r--r--src/corelib/io/qsettings_p.h3
-rw-r--r--src/corelib/io/qsettings_win.cpp8
-rw-r--r--src/corelib/io/qstandardpaths.cpp10
-rw-r--r--src/corelib/io/qstandardpaths_win.cpp6
-rw-r--r--src/corelib/io/qstorageinfo.cpp12
-rw-r--r--src/corelib/io/qstorageinfo.h6
-rw-r--r--src/corelib/io/qstorageinfo_mac.cpp1
-rw-r--r--src/corelib/io/qstorageinfo_p.h3
-rw-r--r--src/corelib/io/qstorageinfo_unix.cpp10
-rw-r--r--src/corelib/io/qtemporarydir.cpp47
-rw-r--r--src/corelib/io/qtemporarydir.h1
-rw-r--r--src/corelib/io/qtemporaryfile.cpp4
-rw-r--r--src/corelib/io/qtemporaryfile_p.h2
-rw-r--r--src/corelib/io/qtextstream.h4
-rw-r--r--src/corelib/io/qtldurl.cpp1
-rw-r--r--src/corelib/io/qurlquery.cpp22
-rw-r--r--src/corelib/io/qurlquery.h8
-rw-r--r--src/corelib/io/qwindowspipereader.cpp6
-rw-r--r--src/corelib/io/qwindowspipereader_p.h2
-rw-r--r--src/corelib/itemmodels/qabstractitemmodel.cpp6
-rw-r--r--src/corelib/itemmodels/qabstractitemmodel.h16
-rw-r--r--src/corelib/itemmodels/qabstractitemmodel_p.h3
-rw-r--r--src/corelib/itemmodels/qabstractproxymodel.cpp1
-rw-r--r--src/corelib/itemmodels/qabstractproxymodel.h2
-rw-r--r--src/corelib/itemmodels/qidentityproxymodel.cpp3
-rw-r--r--src/corelib/itemmodels/qidentityproxymodel.h2
-rw-r--r--src/corelib/itemmodels/qitemselectionmodel.cpp10
-rw-r--r--src/corelib/itemmodels/qitemselectionmodel.h36
-rw-r--r--src/corelib/itemmodels/qsortfilterproxymodel.cpp33
-rw-r--r--src/corelib/itemmodels/qsortfilterproxymodel.h2
-rw-r--r--src/corelib/itemmodels/qstringlistmodel.cpp4
-rw-r--r--src/corelib/itemmodels/qstringlistmodel.h4
-rw-r--r--src/corelib/json/qjsonarray.cpp1
-rw-r--r--src/corelib/json/qjsonarray.h8
-rw-r--r--src/corelib/json/qjsondocument.h2
-rw-r--r--src/corelib/json/qjsonobject.cpp2
-rw-r--r--src/corelib/json/qjsonobject.h4
-rw-r--r--src/corelib/kernel/qabstracteventdispatcher.h4
-rw-r--r--src/corelib/kernel/qcore_mac_objc.mm17
-rw-r--r--src/corelib/kernel/qcore_unix_p.h64
-rw-r--r--src/corelib/kernel/qcoreapplication.cpp242
-rw-r--r--src/corelib/kernel/qcoreapplication.h17
-rw-r--r--src/corelib/kernel/qcoreapplication_p.h8
-rw-r--r--src/corelib/kernel/qcoreevent.cpp2
-rw-r--r--src/corelib/kernel/qcoreevent.h2
-rw-r--r--src/corelib/kernel/qeventdispatcher_glib.cpp1
-rw-r--r--src/corelib/kernel/qeventdispatcher_glib_p.h2
-rw-r--r--src/corelib/kernel/qeventdispatcher_win.cpp4
-rw-r--r--src/corelib/kernel/qeventdispatcher_winrt.cpp108
-rw-r--r--src/corelib/kernel/qeventdispatcher_winrt_p.h4
-rw-r--r--src/corelib/kernel/qeventloop.cpp2
-rw-r--r--src/corelib/kernel/qeventloop.h2
-rw-r--r--src/corelib/kernel/qfunctions_wince.cpp8
-rw-r--r--src/corelib/kernel/qfunctions_wince.h15
-rw-r--r--src/corelib/kernel/qjni.cpp10
-rw-r--r--src/corelib/kernel/qjni_p.h8
-rw-r--r--src/corelib/kernel/qjnihelpers.cpp39
-rw-r--r--src/corelib/kernel/qjnihelpers_p.h13
-rw-r--r--src/corelib/kernel/qmath.h10
-rw-r--r--src/corelib/kernel/qmetaobject.cpp1
-rw-r--r--src/corelib/kernel/qmetaobject.h36
-rw-r--r--src/corelib/kernel/qmetaobjectbuilder.cpp20
-rw-r--r--src/corelib/kernel/qmetatype.cpp28
-rw-r--r--src/corelib/kernel/qmetatype.h113
-rw-r--r--src/corelib/kernel/qmimedata.cpp4
-rw-r--r--src/corelib/kernel/qobject.cpp12
-rw-r--r--src/corelib/kernel/qobject.h46
-rw-r--r--src/corelib/kernel/qobject_impl.h10
-rw-r--r--src/corelib/kernel/qobject_p.h6
-rw-r--r--src/corelib/kernel/qobjectdefs.h24
-rw-r--r--src/corelib/kernel/qpointer.cpp8
-rw-r--r--src/corelib/kernel/qpointer.h12
-rw-r--r--src/corelib/kernel/qsharedmemory.h4
-rw-r--r--src/corelib/kernel/qsignalmapper.h2
-rw-r--r--src/corelib/kernel/qsocketnotifier.h2
-rw-r--r--src/corelib/kernel/qsystemerror.cpp2
-rw-r--r--src/corelib/kernel/qsystemerror_p.h10
-rw-r--r--src/corelib/kernel/qsystemsemaphore_win.cpp2
-rw-r--r--src/corelib/kernel/qtimer.h10
-rw-r--r--src/corelib/kernel/qtranslator.cpp1
-rw-r--r--src/corelib/kernel/qtranslator.h4
-rw-r--r--src/corelib/kernel/qvariant.cpp8
-rw-r--r--src/corelib/kernel/qvariant.h30
-rw-r--r--src/corelib/mimetypes/qmimedatabase.cpp1
-rw-r--r--src/corelib/mimetypes/qmimedatabase_p.h1
-rw-r--r--src/corelib/mimetypes/qmimeprovider.cpp1
-rw-r--r--src/corelib/mimetypes/qmimetype.cpp13
-rw-r--r--src/corelib/mimetypes/qmimetype.h12
-rw-r--r--src/corelib/plugin/plugin.pri1
-rw-r--r--src/corelib/plugin/qfactoryinterface.cpp (renamed from src/plugins/platforms/cocoa/qcocoaautoreleasepool.mm)13
-rw-r--r--src/corelib/plugin/qfactoryinterface.h2
-rw-r--r--src/corelib/plugin/qlibrary.h8
-rw-r--r--src/corelib/plugin/qpluginloader.cpp30
-rw-r--r--src/corelib/plugin/qpluginloader.h4
-rw-r--r--src/corelib/statemachine/qabstractstate.cpp12
-rw-r--r--src/corelib/statemachine/qabstractstate.h2
-rw-r--r--src/corelib/statemachine/qabstractstate_p.h9
-rw-r--r--src/corelib/statemachine/qabstracttransition.cpp18
-rw-r--r--src/corelib/statemachine/qabstracttransition.h2
-rw-r--r--src/corelib/statemachine/qabstracttransition_p.h6
-rw-r--r--src/corelib/statemachine/qeventtransition.cpp3
-rw-r--r--src/corelib/statemachine/qeventtransition.h4
-rw-r--r--src/corelib/statemachine/qeventtransition_p.h4
-rw-r--r--src/corelib/statemachine/qfinalstate.h2
-rw-r--r--src/corelib/statemachine/qhistorystate.cpp64
-rw-r--r--src/corelib/statemachine/qhistorystate.h10
-rw-r--r--src/corelib/statemachine/qhistorystate_p.h25
-rw-r--r--src/corelib/statemachine/qsignaltransition.cpp5
-rw-r--r--src/corelib/statemachine/qsignaltransition.h4
-rw-r--r--src/corelib/statemachine/qsignaltransition_p.h3
-rw-r--r--src/corelib/statemachine/qstate.cpp10
-rw-r--r--src/corelib/statemachine/qstate.h4
-rw-r--r--src/corelib/statemachine/qstate_p.h3
-rw-r--r--src/corelib/statemachine/qstatemachine.cpp188
-rw-r--r--src/corelib/statemachine/qstatemachine.h4
-rw-r--r--src/corelib/statemachine/qstatemachine_p.h18
-rw-r--r--src/corelib/thread/qexception.cpp20
-rw-r--r--src/corelib/thread/qexception.h16
-rw-r--r--src/corelib/thread/qfuture.qdoc1
-rw-r--r--src/corelib/thread/qfutureinterface.h2
-rw-r--r--src/corelib/thread/qfuturewatcher.h4
-rw-r--r--src/corelib/thread/qgenericatomic.h81
-rw-r--r--src/corelib/thread/qmutex.h8
-rw-r--r--src/corelib/thread/qmutex_win.cpp6
-rw-r--r--src/corelib/thread/qresultstore.h4
-rw-r--r--src/corelib/thread/qrunnable.cpp11
-rw-r--r--src/corelib/thread/qrunnable.h9
-rw-r--r--src/corelib/thread/qthread.cpp28
-rw-r--r--src/corelib/thread/qthread.h4
-rw-r--r--src/corelib/thread/qthread_p.h10
-rw-r--r--src/corelib/thread/qthread_unix.cpp15
-rw-r--r--src/corelib/thread/qthread_win.cpp6
-rw-r--r--src/corelib/thread/qthreadpool.h2
-rw-r--r--src/corelib/thread/qwaitcondition_unix.cpp2
-rw-r--r--src/corelib/thread/qwaitcondition_win.cpp6
-rw-r--r--src/corelib/tools/qalgorithms.h125
-rwxr-xr-x[-rw-r--r--]src/corelib/tools/qalgorithms.qdoc70
-rw-r--r--src/corelib/tools/qarraydata.cpp4
-rw-r--r--src/corelib/tools/qarraydata.h6
-rw-r--r--src/corelib/tools/qarraydatapointer.h11
-rw-r--r--src/corelib/tools/qbytearray.cpp90
-rw-r--r--src/corelib/tools/qbytearray.h48
-rw-r--r--src/corelib/tools/qbytearray_p.h (renamed from src/plugins/platforms/kms/main.cpp)41
-rw-r--r--src/corelib/tools/qbytearraylist.h2
-rw-r--r--src/corelib/tools/qchar.cpp61
-rw-r--r--src/corelib/tools/qchar.h269
-rw-r--r--src/corelib/tools/qcollator.h2
-rw-r--r--src/corelib/tools/qcommandlineoption.cpp114
-rw-r--r--src/corelib/tools/qcommandlineoption.h8
-rw-r--r--src/corelib/tools/qcommandlineparser.cpp50
-rw-r--r--src/corelib/tools/qcommandlineparser.h6
-rw-r--r--src/corelib/tools/qdatetime.h7
-rw-r--r--src/corelib/tools/qdatetimeparser_p.h1
-rw-r--r--src/corelib/tools/qeasingcurve.cpp2
-rw-r--r--src/corelib/tools/qeasingcurve.h2
-rw-r--r--src/corelib/tools/qharfbuzz.cpp3
-rw-r--r--src/corelib/tools/qhash.cpp148
-rw-r--r--src/corelib/tools/qhash.h164
-rw-r--r--src/corelib/tools/qhashfunctions.h156
-rw-r--r--src/corelib/tools/qlinkedlist.h2
-rw-r--r--src/corelib/tools/qlist.cpp303
-rw-r--r--src/corelib/tools/qlist.h141
-rw-r--r--src/corelib/tools/qlocale.cpp18
-rw-r--r--src/corelib/tools/qlocale.h39
-rw-r--r--src/corelib/tools/qlocale_mac.mm14
-rw-r--r--src/corelib/tools/qlocale_p.h3
-rw-r--r--src/corelib/tools/qmap.cpp160
-rw-r--r--src/corelib/tools/qmap.h140
-rw-r--r--src/corelib/tools/qqueue.cpp13
-rw-r--r--src/corelib/tools/qqueue.h3
-rw-r--r--src/corelib/tools/qrect.cpp4
-rw-r--r--src/corelib/tools/qregexp.cpp44
-rw-r--r--src/corelib/tools/qregexp.h5
-rw-r--r--src/corelib/tools/qregularexpression.cpp19
-rw-r--r--src/corelib/tools/qregularexpression.h4
-rw-r--r--src/corelib/tools/qringbuffer.cpp314
-rw-r--r--src/corelib/tools/qringbuffer_p.h246
-rw-r--r--src/corelib/tools/qscopedpointer.h14
-rw-r--r--src/corelib/tools/qset.h42
-rw-r--r--src/corelib/tools/qset.qdoc46
-rw-r--r--src/corelib/tools/qshareddata.h11
-rw-r--r--src/corelib/tools/qsharedpointer_impl.h81
-rw-r--r--src/corelib/tools/qsimd.cpp4
-rw-r--r--src/corelib/tools/qsimd_p.h5
-rw-r--r--src/corelib/tools/qstack.cpp13
-rw-r--r--src/corelib/tools/qstack.h3
-rw-r--r--src/corelib/tools/qstring.cpp386
-rw-r--r--src/corelib/tools/qstring.h139
-rw-r--r--src/corelib/tools/qtextboundaryfinder.h2
-rw-r--r--src/corelib/tools/qtimeline.h2
-rw-r--r--src/corelib/tools/qtimezone.cpp4
-rw-r--r--src/corelib/tools/qtimezoneprivate.cpp1
-rw-r--r--src/corelib/tools/qtimezoneprivate_p.h1
-rw-r--r--src/corelib/tools/qtimezoneprivate_tz.cpp1
-rw-r--r--src/corelib/tools/qvarlengtharray.h39
-rw-r--r--src/corelib/tools/qvarlengtharray.qdoc108
-rw-r--r--src/corelib/tools/qvector.cpp244
-rw-r--r--src/corelib/tools/qvector.h122
-rw-r--r--src/corelib/tools/qversionnumber.cpp136
-rw-r--r--src/corelib/tools/qversionnumber.h313
-rw-r--r--src/corelib/tools/qversionnumber_p.h193
-rw-r--r--src/corelib/tools/tools.pri5
-rw-r--r--src/corelib/xml/qxmlstream.h22
-rw-r--r--src/dbus/qdbus_symbols.cpp12
-rw-r--r--src/dbus/qdbusabstractadaptor.cpp4
-rw-r--r--src/dbus/qdbusabstractadaptor_p.h2
-rw-r--r--src/dbus/qdbusargument.h11
-rw-r--r--src/dbus/qdbusconnection.h12
-rw-r--r--src/dbus/qdbusconnection_p.h2
-rw-r--r--src/dbus/qdbuserror.cpp2
-rw-r--r--src/dbus/qdbuserror.h15
-rw-r--r--src/dbus/qdbusextratypes.h38
-rw-r--r--src/dbus/qdbusintegrator.cpp14
-rw-r--r--src/dbus/qdbusintegrator_p.h12
-rw-r--r--src/dbus/qdbusinterface.cpp1
-rw-r--r--src/dbus/qdbusinterface.h2
-rw-r--r--src/dbus/qdbusintrospection_p.h4
-rw-r--r--src/dbus/qdbusmacros.h2
-rw-r--r--src/dbus/qdbusmessage.cpp30
-rw-r--r--src/dbus/qdbusmessage.h8
-rw-r--r--src/dbus/qdbuspendingcall.h7
-rw-r--r--src/dbus/qdbusreply.h2
-rw-r--r--src/dbus/qdbusserver.h4
-rw-r--r--src/dbus/qdbusservicewatcher.h4
-rw-r--r--src/dbus/qdbusunixfiledescriptor.h10
-rw-r--r--src/dbus/qdbusvirtualobject.h2
-rw-r--r--src/gui/accessible/qaccessible.cpp130
-rw-r--r--src/gui/accessible/qaccessible.h42
-rw-r--r--src/gui/accessible/qaccessiblebridge.h2
-rw-r--r--src/gui/accessible/qaccessibleplugin.h2
-rw-r--r--src/gui/image/qbitmap.h2
-rw-r--r--src/gui/image/qicon.cpp41
-rw-r--r--src/gui/image/qicon.h9
-rw-r--r--src/gui/image/qicon_p.h1
-rw-r--r--src/gui/image/qiconengineplugin.h2
-rw-r--r--src/gui/image/qiconloader.cpp11
-rw-r--r--src/gui/image/qiconloader_p.h2
-rw-r--r--src/gui/image/qimage.cpp121
-rw-r--r--src/gui/image/qimage.h37
-rw-r--r--src/gui/image/qimageiohandler.h2
-rw-r--r--src/gui/image/qimagereader.cpp44
-rw-r--r--src/gui/image/qimagereader.h3
-rw-r--r--src/gui/image/qimagewriter.cpp4
-rw-r--r--src/gui/image/qmovie.h6
-rw-r--r--src/gui/image/qpaintengine_pic.cpp1
-rw-r--r--src/gui/image/qpicture.cpp7
-rw-r--r--src/gui/image/qpicture.h8
-rw-r--r--src/gui/image/qpicture_p.h5
-rw-r--r--src/gui/image/qpictureformatplugin.h2
-rw-r--r--src/gui/image/qpixmap.h16
-rw-r--r--src/gui/image/qpixmap_blitter.cpp2
-rw-r--r--src/gui/image/qpixmap_raster.cpp3
-rw-r--r--src/gui/image/qpixmapcache.cpp38
-rw-r--r--src/gui/image/qpixmapcache.h12
-rw-r--r--src/gui/image/qpnghandler.cpp22
-rw-r--r--src/gui/itemmodels/qstandarditemmodel.cpp83
-rw-r--r--src/gui/itemmodels/qstandarditemmodel.h22
-rw-r--r--src/gui/itemmodels/qstandarditemmodel_p.h2
-rw-r--r--src/gui/kernel/kernel.pri8
-rw-r--r--src/gui/kernel/qcursor.cpp18
-rw-r--r--src/gui/kernel/qdnd.cpp8
-rw-r--r--src/gui/kernel/qevent.cpp37
-rw-r--r--src/gui/kernel/qevent.h13
-rw-r--r--src/gui/kernel/qgenericplugin.h2
-rw-r--r--src/gui/kernel/qguiapplication.cpp42
-rw-r--r--src/gui/kernel/qhighdpiscaling.cpp322
-rw-r--r--src/gui/kernel/qhighdpiscaling_p.h514
-rw-r--r--src/gui/kernel/qinputmethod.h2
-rw-r--r--src/gui/kernel/qkeymapper_p.h1
-rw-r--r--src/gui/kernel/qkeysequence.cpp80
-rw-r--r--src/gui/kernel/qkeysequence.h12
-rw-r--r--src/gui/kernel/qkeysequence_p.h13
-rw-r--r--src/gui/kernel/qoffscreensurface.h2
-rw-r--r--src/gui/kernel/qopenglcontext.cpp32
-rw-r--r--src/gui/kernel/qopenglcontext.h7
-rw-r--r--src/gui/kernel/qopenglwindow.cpp5
-rw-r--r--src/gui/kernel/qopenglwindow.h4
-rw-r--r--src/gui/kernel/qpaintdevicewindow.cpp6
-rw-r--r--src/gui/kernel/qplatformcursor.cpp2
-rw-r--r--src/gui/kernel/qplatformcursor.h2
-rw-r--r--src/gui/kernel/qplatformdialoghelper.cpp14
-rw-r--r--src/gui/kernel/qplatformdialoghelper.h3
-rw-r--r--src/gui/kernel/qplatforminputcontextfactory.cpp44
-rw-r--r--src/gui/kernel/qplatforminputcontextfactory_p.h1
-rw-r--r--src/gui/kernel/qplatformintegration.cpp8
-rw-r--r--src/gui/kernel/qplatformintegrationfactory.cpp7
-rw-r--r--src/gui/kernel/qplatformscreen.cpp75
-rw-r--r--src/gui/kernel/qplatformscreen.h17
-rw-r--r--src/gui/kernel/qplatformthemefactory.cpp4
-rw-r--r--src/gui/kernel/qplatformwindow.cpp95
-rw-r--r--src/gui/kernel/qplatformwindow.h12
-rw-r--r--src/gui/kernel/qrasterwindow.cpp2
-rw-r--r--src/gui/kernel/qrasterwindow.h2
-rw-r--r--src/gui/kernel/qscreen.cpp79
-rw-r--r--src/gui/kernel/qscreen.h8
-rw-r--r--src/gui/kernel/qscreen_p.h25
-rw-r--r--src/gui/kernel/qsimpledrag.cpp47
-rw-r--r--src/gui/kernel/qsimpledrag_p.h10
-rw-r--r--src/gui/kernel/qtouchdevice.cpp14
-rw-r--r--src/gui/kernel/qtouchdevice_p.h5
-rw-r--r--src/gui/kernel/qwindow.cpp94
-rw-r--r--src/gui/kernel/qwindow.h13
-rw-r--r--src/gui/kernel/qwindow_p.h1
-rw-r--r--src/gui/kernel/qwindowsysteminterface.cpp205
-rw-r--r--src/gui/kernel/qwindowsysteminterface.h6
-rw-r--r--src/gui/kernel/qwindowsysteminterface_p.h27
-rw-r--r--src/gui/math3d/qmatrix4x4.h2
-rw-r--r--src/gui/math3d/qquaternion.h28
-rw-r--r--src/gui/math3d/qvector2d.h2
-rw-r--r--src/gui/math3d/qvector3d.h2
-rw-r--r--src/gui/math3d/qvector4d.h2
-rw-r--r--src/gui/opengl/opengl.pri3
-rw-r--r--src/gui/opengl/qopengl.cpp120
-rw-r--r--src/gui/opengl/qopengl.h12
-rw-r--r--src/gui/opengl/qopengl_p.h12
-rw-r--r--src/gui/opengl/qopenglbuffer.h2
-rw-r--r--src/gui/opengl/qopengldebug.h10
-rw-r--r--src/gui/opengl/qopenglengineshadermanager.cpp3
-rw-r--r--src/gui/opengl/qopenglextensions_p.h259
-rw-r--r--src/gui/opengl/qopenglextrafunctions.h1990
-rw-r--r--src/gui/opengl/qopenglframebufferobject.cpp495
-rw-r--r--src/gui/opengl/qopenglframebufferobject.h22
-rw-r--r--src/gui/opengl/qopenglframebufferobject_p.h27
-rw-r--r--src/gui/opengl/qopenglfunctions.cpp4283
-rw-r--r--src/gui/opengl/qopenglfunctions.h5
-rw-r--r--src/gui/opengl/qopenglgradientcache.cpp78
-rw-r--r--src/gui/opengl/qopenglgradientcache_p.h6
-rw-r--r--src/gui/opengl/qopenglpaintdevice.cpp7
-rw-r--r--src/gui/opengl/qopenglpaintdevice_p.h2
-rw-r--r--src/gui/opengl/qopenglpixeltransferoptions.h9
-rw-r--r--src/gui/opengl/qopenglshaderprogram.cpp2
-rw-r--r--src/gui/opengl/qopenglshaderprogram.h8
-rw-r--r--src/gui/opengl/qopengltexture.cpp289
-rw-r--r--src/gui/opengl/qopengltexture.h33
-rw-r--r--src/gui/opengl/qopengltexture_p.h2
-rw-r--r--src/gui/opengl/qopengltexturehelper_p.h37
-rw-r--r--src/gui/opengl/qopengltimerquery.h4
-rw-r--r--src/gui/opengl/qopenglversionfunctions.h5
-rw-r--r--src/gui/opengl/qopenglvertexarrayobject.h2
-rw-r--r--src/gui/opengl/qtriangulatingstroker.cpp4
-rw-r--r--src/gui/painting/painting.pri3
-rw-r--r--src/gui/painting/qbackingstore.cpp49
-rw-r--r--src/gui/painting/qbackingstore.h2
-rw-r--r--src/gui/painting/qblendfunctions.cpp187
-rw-r--r--src/gui/painting/qbrush.cpp1
-rw-r--r--src/gui/painting/qcolor.cpp92
-rw-r--r--src/gui/painting/qcolor.h42
-rw-r--r--src/gui/painting/qcompositionfunctions.cpp2197
-rw-r--r--src/gui/painting/qcosmeticstroker.cpp3
-rw-r--r--src/gui/painting/qdrawhelper.cpp3575
-rw-r--r--src/gui/painting/qdrawhelper_neon.cpp7
-rw-r--r--src/gui/painting/qdrawhelper_neon_p.h2
-rw-r--r--src/gui/painting/qdrawhelper_p.h243
-rw-r--r--src/gui/painting/qdrawhelper_sse2.cpp103
-rw-r--r--src/gui/painting/qdrawhelper_x86_p.h6
-rw-r--r--src/gui/painting/qimagescale.cpp152
-rw-r--r--src/gui/painting/qimagescale_sse4.cpp42
-rw-r--r--src/gui/painting/qmatrix.cpp24
-rw-r--r--src/gui/painting/qmatrix.h4
-rw-r--r--src/gui/painting/qpagedpaintdevice.cpp4
-rw-r--r--src/gui/painting/qpagedpaintdevice_p.h4
-rw-r--r--src/gui/painting/qpagelayout.h11
-rw-r--r--src/gui/painting/qpagesize.h10
-rw-r--r--src/gui/painting/qpaintdevice.cpp6
-rw-r--r--src/gui/painting/qpaintdevice.h6
-rw-r--r--src/gui/painting/qpaintdevice.qdoc21
-rw-r--r--src/gui/painting/qpaintengine.cpp4
-rw-r--r--src/gui/painting/qpaintengine.h4
-rw-r--r--src/gui/painting/qpaintengine_p.h3
-rw-r--r--src/gui/painting/qpaintengine_raster.cpp104
-rw-r--r--src/gui/painting/qpainter.cpp15
-rw-r--r--src/gui/painting/qpainter.h10
-rw-r--r--src/gui/painting/qpainter_p.h3
-rw-r--r--src/gui/painting/qpathclipper.cpp6
-rw-r--r--src/gui/painting/qpdf.cpp39
-rw-r--r--src/gui/painting/qpdf_p.h4
-rw-r--r--src/gui/painting/qpen.cpp1
-rw-r--r--src/gui/painting/qplatformbackingstore.cpp6
-rw-r--r--src/gui/painting/qpolygon.h22
-rw-r--r--src/gui/painting/qrgba64.h228
-rw-r--r--src/gui/painting/qrgba64.qdoc241
-rw-r--r--src/gui/painting/qrgba64_p.h120
-rw-r--r--src/gui/painting/qtextureglyphcache.cpp29
-rw-r--r--src/gui/painting/qtextureglyphcache_p.h4
-rw-r--r--src/gui/painting/qtransform.cpp28
-rw-r--r--src/gui/painting/qtransform.h4
-rw-r--r--src/gui/text/qabstracttextdocumentlayout.cpp9
-rw-r--r--src/gui/text/qabstracttextdocumentlayout.h4
-rw-r--r--src/gui/text/qabstracttextdocumentlayout_p.h3
-rw-r--r--src/gui/text/qcssparser.cpp1
-rw-r--r--src/gui/text/qfont.cpp7
-rw-r--r--src/gui/text/qfontdatabase.cpp24
-rw-r--r--src/gui/text/qfontengine_ft.cpp31
-rw-r--r--src/gui/text/qfontengine_ft_p.h3
-rw-r--r--src/gui/text/qfontengine_p.h13
-rw-r--r--src/gui/text/qfontengineglyphcache.cpp (renamed from src/plugins/platforms/cocoa/qcocoaautoreleasepool.h)22
-rw-r--r--src/gui/text/qfontengineglyphcache_p.h4
-rw-r--r--src/gui/text/qfontmetrics.h10
-rw-r--r--src/gui/text/qfontsubset.cpp41
-rw-r--r--src/gui/text/qfontsubset_p.h2
-rw-r--r--src/gui/text/qglyphrun.cpp1
-rw-r--r--src/gui/text/qglyphrun.h8
-rw-r--r--src/gui/text/qplatformfontdatabase.cpp15
-rw-r--r--src/gui/text/qplatformfontdatabase.h2
-rw-r--r--src/gui/text/qrawfont.cpp1
-rw-r--r--src/gui/text/qrawfont.h10
-rw-r--r--src/gui/text/qstatictext.cpp8
-rw-r--r--src/gui/text/qstatictext.h7
-rw-r--r--src/gui/text/qstatictext_p.h5
-rw-r--r--src/gui/text/qsyntaxhighlighter.cpp8
-rw-r--r--src/gui/text/qtextcursor.h5
-rw-r--r--src/gui/text/qtextdocument.cpp22
-rw-r--r--src/gui/text/qtextdocument.h18
-rw-r--r--src/gui/text/qtextdocumentlayout.cpp18
-rw-r--r--src/gui/text/qtextengine.cpp30
-rw-r--r--src/gui/text/qtextengine_p.h12
-rw-r--r--src/gui/text/qtextformat.cpp8
-rw-r--r--src/gui/text/qtextformat_p.h1
-rw-r--r--src/gui/text/qtextimagehandler.cpp4
-rw-r--r--src/gui/text/qtextlayout.cpp69
-rw-r--r--src/gui/text/qtextlayout.h24
-rw-r--r--src/gui/text/qtextobject.h6
-rw-r--r--src/gui/text/qtextodfwriter.cpp2
-rw-r--r--src/gui/text/qtextodfwriter_p.h2
-rw-r--r--src/gui/text/qtextoption.cpp6
-rw-r--r--src/gui/text/qtexttable.h4
-rw-r--r--src/gui/text/qzip.cpp71
-rw-r--r--src/gui/text/qzipreader_p.h18
-rw-r--r--src/gui/text/text.pri2
-rw-r--r--src/gui/util/qvalidator.h18
-rw-r--r--src/network/access/qabstractnetworkcache.h7
-rw-r--r--src/network/access/qftp.cpp1
-rw-r--r--src/network/access/qhttpmultipart.h9
-rw-r--r--src/network/access/qhttpnetworkconnection.cpp55
-rw-r--r--src/network/access/qhttpnetworkconnection_p.h1
-rw-r--r--src/network/access/qhttpnetworkconnectionchannel.cpp14
-rw-r--r--src/network/access/qhttpnetworkheader.cpp12
-rw-r--r--src/network/access/qhttpnetworkreply.cpp30
-rw-r--r--src/network/access/qhttpnetworkreply_p.h10
-rw-r--r--src/network/access/qhttpnetworkrequest.cpp24
-rw-r--r--src/network/access/qhttpnetworkrequest_p.h8
-rw-r--r--src/network/access/qhttpthreaddelegate.cpp3
-rw-r--r--src/network/access/qhttpthreaddelegate_p.h2
-rw-r--r--src/network/access/qnetworkaccessauthenticationmanager_p.h2
-rw-r--r--src/network/access/qnetworkaccessbackend.cpp1
-rw-r--r--src/network/access/qnetworkaccessmanager.cpp2
-rw-r--r--src/network/access/qnetworkaccessmanager.h6
-rw-r--r--src/network/access/qnetworkcookie.h5
-rw-r--r--src/network/access/qnetworkcookiejar.h2
-rw-r--r--src/network/access/qnetworkdiskcache.h2
-rw-r--r--src/network/access/qnetworkreply.cpp32
-rw-r--r--src/network/access/qnetworkreply.h5
-rw-r--r--src/network/access/qnetworkreply_p.h1
-rw-r--r--src/network/access/qnetworkreplyfileimpl.cpp7
-rw-r--r--src/network/access/qnetworkreplyhttpimpl.cpp195
-rw-r--r--src/network/access/qnetworkreplyhttpimpl_p.h13
-rw-r--r--src/network/access/qnetworkreplyimpl.cpp15
-rw-r--r--src/network/access/qnetworkreplyimpl_p.h3
-rw-r--r--src/network/access/qnetworkrequest.cpp45
-rw-r--r--src/network/access/qnetworkrequest.h10
-rw-r--r--src/network/access/qspdyprotocolhandler.cpp19
-rw-r--r--src/network/bearer/qnetworkconfigmanager.h4
-rw-r--r--src/network/bearer/qnetworkconfigmanager_p.cpp3
-rw-r--r--src/network/bearer/qnetworkconfiguration.h5
-rw-r--r--src/network/bearer/qnetworksession.h2
-rw-r--r--src/network/kernel/qdnslookup.h46
-rw-r--r--src/network/kernel/qhostaddress.cpp136
-rw-r--r--src/network/kernel/qhostaddress.h8
-rw-r--r--src/network/kernel/qhostinfo.cpp16
-rw-r--r--src/network/kernel/qhostinfo_unix.cpp9
-rw-r--r--src/network/kernel/qhostinfo_win.cpp19
-rw-r--r--src/network/kernel/qhostinfo_winrt.cpp39
-rw-r--r--src/network/kernel/qnetworkinterface.cpp16
-rw-r--r--src/network/kernel/qnetworkinterface.h10
-rw-r--r--src/network/kernel/qnetworkinterface_unix.cpp52
-rw-r--r--src/network/kernel/qnetworkinterface_win.cpp69
-rw-r--r--src/network/kernel/qnetworkinterface_win_p.h11
-rw-r--r--src/network/kernel/qnetworkproxy.cpp1
-rw-r--r--src/network/kernel/qnetworkproxy.h14
-rw-r--r--src/network/socket/qabstractsocket.cpp21
-rw-r--r--src/network/socket/qabstractsocket.h4
-rw-r--r--src/network/socket/qabstractsocket_p.h2
-rw-r--r--src/network/socket/qabstractsocketengine_p.h48
-rw-r--r--src/network/socket/qhttpsocketengine.cpp6
-rw-r--r--src/network/socket/qhttpsocketengine_p.h7
-rw-r--r--src/network/socket/qlocalserver.h4
-rw-r--r--src/network/socket/qlocalsocket.h2
-rw-r--r--src/network/socket/qnativesocketengine.cpp76
-rw-r--r--src/network/socket/qnativesocketengine_p.h126
-rw-r--r--src/network/socket/qnativesocketengine_unix.cpp321
-rw-r--r--src/network/socket/qnativesocketengine_win.cpp333
-rw-r--r--src/network/socket/qnativesocketengine_winrt.cpp27
-rw-r--r--src/network/socket/qnativesocketengine_winrt_p.h9
-rw-r--r--src/network/socket/qnet_unix_p.h35
-rw-r--r--src/network/socket/qsocks5socketengine.cpp18
-rw-r--r--src/network/socket/qsocks5socketengine_p.h7
-rw-r--r--src/network/socket/qtcpserver.cpp38
-rw-r--r--src/network/socket/qtcpserver.h6
-rw-r--r--src/network/socket/qtcpserver_p.h2
-rw-r--r--src/network/socket/qtcpsocket.cpp9
-rw-r--r--src/network/socket/qtcpsocket.h6
-rw-r--r--src/network/socket/qudpsocket.cpp17
-rw-r--r--src/network/socket/qudpsocket.h4
-rw-r--r--src/network/ssl/qssl.cpp4
-rw-r--r--src/network/ssl/qssl.h3
-rw-r--r--src/network/ssl/qsslcertificate.h7
-rw-r--r--src/network/ssl/qsslcertificate_openssl.cpp3
-rw-r--r--src/network/ssl/qsslcertificateextension.h8
-rw-r--r--src/network/ssl/qsslcipher.h7
-rw-r--r--src/network/ssl/qsslconfiguration.h5
-rw-r--r--src/network/ssl/qsslellipticcurve.h3
-rw-r--r--src/network/ssl/qsslerror.h5
-rw-r--r--src/network/ssl/qsslkey.h7
-rw-r--r--src/network/ssl/qsslkey_openssl.cpp49
-rw-r--r--src/network/ssl/qsslkey_p.h19
-rw-r--r--src/network/ssl/qsslpresharedkeyauthenticator.h8
-rw-r--r--src/network/ssl/qsslsocket.h2
-rw-r--r--src/network/ssl/qsslsocket_openssl.cpp44
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols.cpp105
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols_p.h25
-rw-r--r--src/opengl/gl2paintengineex/qglcustomshaderstage.cpp1
-rw-r--r--src/opengl/qgl.cpp7
-rw-r--r--src/opengl/qgl.h24
-rw-r--r--src/opengl/qgl_p.h2
-rw-r--r--src/opengl/qglbuffer.h2
-rw-r--r--src/opengl/qglcolormap.h2
-rw-r--r--src/opengl/qglframebufferobject.cpp3
-rw-r--r--src/opengl/qglfunctions.h6
-rw-r--r--src/opengl/qglpaintdevice.cpp2
-rw-r--r--src/opengl/qglpixelbuffer.cpp3
-rw-r--r--src/opengl/qglpixelbuffer.h4
-rw-r--r--src/opengl/qglshaderprogram.cpp2
-rw-r--r--src/opengl/qglshaderprogram.h12
-rw-r--r--src/platformheaders/cocoafunctions/cocoafunctions.pri1
-rw-r--r--src/platformheaders/cocoafunctions/qcocoawindowfunctions.h (renamed from src/plugins/platforms/kms/qkmscursor.h)35
-rw-r--r--src/platformheaders/cocoafunctions/qcocoawindowfunctions.qdoc58
-rw-r--r--src/platformheaders/helper/helper.pri2
-rw-r--r--src/platformheaders/helper/qplatformheaderhelper.h87
-rw-r--r--src/platformheaders/platformheaders.pro2
-rw-r--r--src/platformheaders/xcbfunctions/qxcbintegrationfunctions.h (renamed from src/plugins/platforms/kms/qkmswindow.h)25
-rw-r--r--src/platformheaders/xcbfunctions/qxcbwindowfunctions.h36
-rw-r--r--src/platformheaders/xcbfunctions/qxcbwindowfunctions.qdoc133
-rw-r--r--src/platformheaders/xcbfunctions/xcbfunctions.pri4
-rw-r--r--src/platformsupport/dbusmenu/qdbusmenutypes.cpp1
-rw-r--r--src/platformsupport/dbusmenu/qdbusmenutypes_p.h15
-rw-r--r--src/platformsupport/dbustray/qdbustraytypes.cpp2
-rw-r--r--src/platformsupport/dbustray/qdbustraytypes_p.h2
-rw-r--r--src/platformsupport/eglconvenience/eglconvenience.pri25
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformcontext.cpp17
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformcontext_p.h1
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformintegration.cpp366
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformintegration_p.h122
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformscreen.cpp146
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformscreen_p.h79
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformwindow.cpp138
-rw-r--r--src/platformsupport/eglconvenience/qeglplatformwindow_p.h85
-rw-r--r--src/platformsupport/fbconvenience/qfbscreen.cpp5
-rw-r--r--src/platformsupport/fontdatabases/basic/qbasicfontdatabase.cpp22
-rw-r--r--src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp5
-rw-r--r--src/platformsupport/fontdatabases/mac/coretext.pri7
-rw-r--r--src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm154
-rw-r--r--src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h7
-rw-r--r--src/platformsupport/input/evdevtablet/qevdevtablet.cpp2
-rw-r--r--src/platformsupport/input/evdevtablet/qevdevtablet_p.h3
-rw-r--r--src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp12
-rw-r--r--src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h3
-rw-r--r--src/platformsupport/input/libinput/qlibinputhandler.cpp6
-rw-r--r--src/platformsupport/input/libinput/qlibinputkeyboard.cpp17
-rw-r--r--src/platformsupport/linuxaccessibility/atspiadaptor.cpp10
-rw-r--r--src/platformsupport/linuxaccessibility/cache.cpp3
-rw-r--r--src/platformsupport/linuxaccessibility/dbusconnection.cpp26
-rw-r--r--src/platformsupport/linuxaccessibility/dbusconnection_p.h1
-rw-r--r--src/platformsupport/linuxaccessibility/struct_marshallers_p.h32
-rw-r--r--src/platformsupport/themes/genericunix/qgenericunixthemes.cpp69
-rw-r--r--src/plugins/bearer/connman/main.cpp2
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.cpp6
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.h2
-rw-r--r--src/plugins/bearer/connman/qconnmanservice_linux.cpp12
-rw-r--r--src/plugins/bearer/connman/qconnmanservice_linux_p.h2
-rw-r--r--src/plugins/bearer/corewlan/qcorewlanengine.mm30
-rw-r--r--src/plugins/bearer/generic/main.cpp4
-rw-r--r--src/plugins/bearer/generic/qgenericengine.cpp16
-rw-r--r--src/plugins/bearer/generic/qgenericengine.h4
-rw-r--r--src/plugins/bearer/linux_common/qofonoservice_linux.cpp6
-rw-r--r--src/plugins/bearer/linux_common/qofonoservice_linux_p.h2
-rw-r--r--src/plugins/bearer/networkmanager/main.cpp2
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp2
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.h2
-rw-r--r--src/plugins/bearer/qbearerengine_impl.h4
-rw-r--r--src/plugins/bearer/qnetworksession_impl.cpp4
-rw-r--r--src/plugins/bearer/qnetworksession_impl.h4
-rw-r--r--src/plugins/generic/tuiotouch/qtuiohandler.cpp1
-rw-r--r--src/plugins/imageformats/gif/main.cpp4
-rw-r--r--src/plugins/imageformats/gif/main.h4
-rw-r--r--src/plugins/imageformats/ico/main.cpp4
-rw-r--r--src/plugins/imageformats/ico/main.h4
-rw-r--r--src/plugins/imageformats/ico/qicohandler.cpp16
-rw-r--r--src/plugins/imageformats/jpeg/main.cpp4
-rw-r--r--src/plugins/imageformats/jpeg/main.h4
-rw-r--r--src/plugins/platforminputcontexts/compose/compose.pro2
-rw-r--r--src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp235
-rw-r--r--src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h4
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp124
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h38
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibustypes.cpp6
-rw-r--r--src/plugins/platforms/android/androidjniinput.cpp57
-rw-r--r--src/plugins/platforms/android/androidjniinput.h2
-rw-r--r--src/plugins/platforms/android/androidjnimain.cpp5
-rw-r--r--src/plugins/platforms/android/qandroidinputcontext.cpp4
-rw-r--r--src/plugins/platforms/cocoa/cocoa.pro2
-rw-r--r--src/plugins/platforms/cocoa/main.mm6
-rw-r--r--src/plugins/platforms/cocoa/qcocoaaccessibility.h8
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h1
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm5
-rw-r--r--src/plugins/platforms/cocoa/qcocoabackingstore.h12
-rw-r--r--src/plugins/platforms/cocoa/qcocoaclipboard.h8
-rw-r--r--src/plugins/platforms/cocoa/qcocoacolordialoghelper.h12
-rw-r--r--src/plugins/platforms/cocoa/qcocoacursor.h6
-rw-r--r--src/plugins/platforms/cocoa/qcocoacursor.mm1
-rw-r--r--src/plugins/platforms/cocoa/qcocoadrag.h10
-rw-r--r--src/plugins/platforms/cocoa/qcocoaeventdispatcher.h1
-rw-r--r--src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm12
-rw-r--r--src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm7
-rw-r--r--src/plugins/platforms/cocoa/qcocoafontdialoghelper.h10
-rw-r--r--src/plugins/platforms/cocoa/qcocoaglcontext.h14
-rw-r--r--src/plugins/platforms/cocoa/qcocoaglcontext.mm5
-rw-r--r--src/plugins/platforms/cocoa/qcocoahelpers.mm15
-rw-r--r--src/plugins/platforms/cocoa/qcocoainputcontext.h4
-rw-r--r--src/plugins/platforms/cocoa/qcocoainputcontext.mm3
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.h51
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.mm50
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenu.h42
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenu.mm19
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenubar.h12
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenubar.mm27
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuitem.h34
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuitem.mm5
-rw-r--r--src/plugins/platforms/cocoa/qcocoanativeinterface.h2
-rw-r--r--src/plugins/platforms/cocoa/qcocoanativeinterface.mm12
-rw-r--r--src/plugins/platforms/cocoa/qcocoaprintdevice.mm4
-rw-r--r--src/plugins/platforms/cocoa/qcocoaservices.h4
-rw-r--r--src/plugins/platforms/cocoa/qcocoasystemsettings.mm3
-rw-r--r--[-rwxr-xr-x]src/plugins/platforms/cocoa/qcocoasystemtrayicon.h20
-rw-r--r--[-rwxr-xr-x]src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm1
-rw-r--r--src/plugins/platforms/cocoa/qcocoatheme.mm3
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.h8
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.mm97
-rw-r--r--src/plugins/platforms/cocoa/qmacclipboard.mm3
-rw-r--r--src/plugins/platforms/cocoa/qmultitouch_mac.mm4
-rw-r--r--src/plugins/platforms/cocoa/qnsview.mm11
-rw-r--r--src/plugins/platforms/cocoa/qprintengine_mac.mm6
-rw-r--r--src/plugins/platforms/cocoa/qt_mac_p.h11
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dpaintdevice.cpp3
-rw-r--r--src/plugins/platforms/directfb/qdirectfbconvenience.cpp2
-rw-r--r--[-rwxr-xr-x]src/plugins/platforms/eglfs/cursor-atlas.pngbin2236 -> 2236 bytes
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.cpp20
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.h1
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsintegration.cpp4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.cpp30
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.h6
-rw-r--r--src/plugins/platforms/eglfs/eglfs_device_lib.pro2
-rw-r--r--src/plugins/platforms/eglfs/qeglfscontext.cpp8
-rw-r--r--src/plugins/platforms/eglfs/qeglfscursor.cpp (renamed from src/platformsupport/eglconvenience/qeglplatformcursor.cpp)188
-rw-r--r--src/plugins/platforms/eglfs/qeglfscursor.h (renamed from src/platformsupport/eglconvenience/qeglplatformcursor_p.h)29
-rw-r--r--src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp8
-rw-r--r--src/plugins/platforms/eglfs/qeglfsintegration.cpp337
-rw-r--r--src/plugins/platforms/eglfs/qeglfsintegration.h65
-rw-r--r--src/plugins/platforms/eglfs/qeglfsscreen.cpp94
-rw-r--r--src/plugins/platforms/eglfs/qeglfsscreen.h16
-rw-r--r--src/plugins/platforms/eglfs/qeglfswindow.cpp79
-rw-r--r--src/plugins/platforms/eglfs/qeglfswindow.h33
-rw-r--r--src/plugins/platforms/haiku/qhaikuclipboard.cpp45
-rw-r--r--src/plugins/platforms/haiku/qhaikuclipboard.h4
-rw-r--r--src/plugins/platforms/haiku/qhaikuwindow.cpp17
-rw-r--r--src/plugins/platforms/ios/qiosapplicationstate.mm12
-rw-r--r--src/plugins/platforms/ios/qiosclipboard.mm4
-rw-r--r--src/plugins/platforms/ios/qioseventdispatcher.mm23
-rw-r--r--src/plugins/platforms/ios/qiosglobal.h2
-rw-r--r--src/plugins/platforms/ios/qiosglobal.mm4
-rw-r--r--src/plugins/platforms/ios/qiosinputcontext.mm2
-rw-r--r--src/plugins/platforms/ios/qiosintegration.mm4
-rw-r--r--src/plugins/platforms/ios/qiosmenu.mm4
-rw-r--r--src/plugins/platforms/ios/qiosscreen.mm8
-rw-r--r--src/plugins/platforms/ios/qiostextresponder.mm49
-rw-r--r--src/plugins/platforms/ios/qiosviewcontroller.mm6
-rw-r--r--src/plugins/platforms/ios/quiaccessibilityelement.h4
-rw-r--r--src/plugins/platforms/ios/quiaccessibilityelement.mm26
-rw-r--r--src/plugins/platforms/ios/quiview.mm4
-rw-r--r--src/plugins/platforms/kms/kms.json3
-rw-r--r--src/plugins/platforms/kms/kms.pro37
-rw-r--r--src/plugins/platforms/kms/qkmsbackingstore.cpp217
-rw-r--r--src/plugins/platforms/kms/qkmsbackingstore.h72
-rw-r--r--src/plugins/platforms/kms/qkmscontext.cpp136
-rw-r--r--src/plugins/platforms/kms/qkmscontext.h71
-rw-r--r--src/plugins/platforms/kms/qkmscursor.cpp116
-rw-r--r--src/plugins/platforms/kms/qkmsdevice.cpp118
-rw-r--r--src/plugins/platforms/kms/qkmsdevice.h81
-rw-r--r--src/plugins/platforms/kms/qkmsintegration.cpp204
-rw-r--r--src/plugins/platforms/kms/qkmsintegration.h108
-rw-r--r--src/plugins/platforms/kms/qkmsnativeinterface.cpp135
-rw-r--r--src/plugins/platforms/kms/qkmsnativeinterface.h64
-rw-r--r--src/plugins/platforms/kms/qkmsscreen.cpp275
-rw-r--r--src/plugins/platforms/kms/qkmsscreen.h122
-rw-r--r--src/plugins/platforms/kms/qkmswindow.cpp66
-rw-r--r--src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp11
-rw-r--r--src/plugins/platforms/mirclient/mirclient.json3
-rw-r--r--src/plugins/platforms/mirclient/mirclient.pro47
-rw-r--r--src/plugins/platforms/mirclient/qmirclientbackingstore.cpp146
-rw-r--r--src/plugins/platforms/mirclient/qmirclientbackingstore.h70
-rw-r--r--src/plugins/platforms/mirclient/qmirclientclipboard.cpp305
-rw-r--r--src/plugins/platforms/mirclient/qmirclientclipboard.h88
-rw-r--r--src/plugins/platforms/mirclient/qmirclientglcontext.cpp156
-rw-r--r--src/plugins/platforms/mirclient/qmirclientglcontext.h66
-rw-r--r--src/plugins/platforms/mirclient/qmirclientinput.cpp520
-rw-r--r--src/plugins/platforms/mirclient/qmirclientinput.h78
-rw-r--r--src/plugins/platforms/mirclient/qmirclientintegration.cpp264
-rw-r--r--src/plugins/platforms/mirclient/qmirclientintegration.h99
-rw-r--r--src/plugins/platforms/mirclient/qmirclientlogging.h60
-rw-r--r--src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp134
-rw-r--r--src/plugins/platforms/mirclient/qmirclientnativeinterface.h66
-rw-r--r--src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h66
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplatformservices.cpp72
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplatformservices.h54
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplugin.cpp61
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplugin.h53
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreen.cpp296
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreen.h84
-rw-r--r--src/plugins/platforms/mirclient/qmirclienttheme.cpp64
-rw-r--r--src/plugins/platforms/mirclient/qmirclienttheme.h54
-rw-r--r--src/plugins/platforms/mirclient/qmirclientwindow.cpp452
-rw-r--r--src/plugins/platforms/mirclient/qmirclientwindow.h80
-rw-r--r--src/plugins/platforms/platforms.pro2
-rw-r--r--src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.cpp21
-rw-r--r--src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.h2
-rw-r--r--src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp6
-rw-r--r--src/plugins/platforms/qnx/qqnxinputcontext_noimf.cpp6
-rw-r--r--src/plugins/platforms/qnx/qqnxintegration.cpp1
-rw-r--r--src/plugins/platforms/windows/openglblacklists/default.json27
-rw-r--r--src/plugins/platforms/windows/qwindowsbackingstore.cpp40
-rw-r--r--src/plugins/platforms/windows/qwindowsbackingstore.h8
-rw-r--r--src/plugins/platforms/windows/qwindowscontext.cpp5
-rw-r--r--src/plugins/platforms/windows/qwindowscursor.cpp6
-rw-r--r--src/plugins/platforms/windows/qwindowsdrag.cpp41
-rw-r--r--src/plugins/platforms/windows/qwindowsinputcontext.cpp6
-rw-r--r--src/plugins/platforms/windows/qwindowsintegration.cpp19
-rw-r--r--src/plugins/platforms/windows/qwindowskeymapper.cpp8
-rw-r--r--src/plugins/platforms/windows/qwindowsmousehandler.cpp24
-rw-r--r--src/plugins/platforms/windows/qwindowsnativeimage.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsopengltester.cpp10
-rw-r--r--src/plugins/platforms/windows/qwindowsopengltester.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsscaling.cpp71
-rw-r--r--src/plugins/platforms/windows/qwindowsscaling.h106
-rw-r--r--src/plugins/platforms/windows/qwindowsscreen.cpp41
-rw-r--r--src/plugins/platforms/windows/qwindowsscreen.h14
-rw-r--r--src/plugins/platforms/windows/qwindowstabletsupport.cpp26
-rw-r--r--src/plugins/platforms/windows/qwindowstheme.cpp9
-rw-r--r--src/plugins/platforms/windows/qwindowswindow.cpp127
-rw-r--r--src/plugins/platforms/windows/qwindowswindow.h30
-rw-r--r--src/plugins/platforms/windows/windows.pri2
-rw-r--r--src/plugins/platforms/winrt/qwinrtcursor.cpp23
-rw-r--r--src/plugins/platforms/winrt/qwinrteglcontext.cpp133
-rw-r--r--src/plugins/platforms/winrt/qwinrteglcontext.h22
-rw-r--r--src/plugins/platforms/winrt/qwinrtfontdatabase.cpp15
-rw-r--r--src/plugins/platforms/winrt/qwinrtfontdatabase.h6
-rw-r--r--src/plugins/platforms/winrt/qwinrtinputcontext.cpp157
-rw-r--r--src/plugins/platforms/winrt/qwinrtinputcontext.h29
-rw-r--r--src/plugins/platforms/winrt/qwinrtintegration.cpp173
-rw-r--r--src/plugins/platforms/winrt/qwinrtintegration.h43
-rw-r--r--src/plugins/platforms/winrt/qwinrtscreen.cpp335
-rw-r--r--src/plugins/platforms/winrt/qwinrtscreen.h33
-rw-r--r--src/plugins/platforms/winrt/qwinrtwindow.cpp160
-rw-r--r--src/plugins/platforms/winrt/qwinrtwindow.h8
-rw-r--r--src/plugins/platforms/winrt/winrt.pro22
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/qxcbglintegrationfactory.cpp4
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp12
-rw-r--r--src/plugins/platforms/xcb/qxcbbackingstore.cpp46
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection.cpp24
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection.h4
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection_xi2.cpp33
-rw-r--r--src/plugins/platforms/xcb/qxcbcursor.cpp15
-rw-r--r--src/plugins/platforms/xcb/qxcbcursor.h2
-rw-r--r--src/plugins/platforms/xcb/qxcbdrag.cpp65
-rw-r--r--src/plugins/platforms/xcb/qxcbdrag.h18
-rw-r--r--src/plugins/platforms/xcb/qxcbintegration.cpp5
-rw-r--r--src/plugins/platforms/xcb/qxcbkeyboard.cpp12
-rw-r--r--src/plugins/platforms/xcb/qxcbnativeinterface.cpp119
-rw-r--r--src/plugins/platforms/xcb/qxcbnativeinterface.h7
-rw-r--r--src/plugins/platforms/xcb/qxcbscreen.cpp82
-rw-r--r--src/plugins/platforms/xcb/qxcbscreen.h11
-rw-r--r--src/plugins/platforms/xcb/qxcbsessionmanager.cpp1
-rw-r--r--src/plugins/platforms/xcb/qxcbsystemtraytracker.cpp45
-rw-r--r--src/plugins/platforms/xcb/qxcbsystemtraytracker.h4
-rw-r--r--src/plugins/platforms/xcb/qxcbwindow.cpp279
-rw-r--r--src/plugins/platforms/xcb/qxcbwindow.h17
-rw-r--r--src/plugins/platforms/xcb/qxlibconvenience.cpp63
-rw-r--r--src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.h5
-rw-r--r--src/plugins/plugins.pro13
-rw-r--r--src/plugins/printsupport/cocoa/main.cpp4
-rw-r--r--src/plugins/printsupport/cups/main.cpp4
-rw-r--r--src/plugins/printsupport/cups/qcupsprintengine.cpp8
-rw-r--r--src/plugins/printsupport/cups/qcupsprintengine_p.h4
-rw-r--r--src/plugins/printsupport/cups/qcupsprintersupport.cpp5
-rw-r--r--src/plugins/printsupport/cups/qcupsprintersupport_p.h3
-rw-r--r--src/plugins/printsupport/cups/qppdprintdevice.cpp7
-rw-r--r--src/plugins/printsupport/cups/qppdprintdevice.h5
-rw-r--r--src/plugins/printsupport/printsupport.pro5
-rw-r--r--src/plugins/printsupport/windows/qwindowsprintdevice.cpp4
-rw-r--r--src/plugins/printsupport/windows/qwindowsprintdevice.h3
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/button/core_button_inactive.pngbin2428 -> 2428 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/button/core_button_pressed.pngbin3221 -> 3221 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/checkbox/core_checkbox_pressed.pngbin2776 -> 2776 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg.pngbin1315 -> 1315 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg_highlight.pngbin394 -> 394 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/listitem/core_listitem_active.pngbin164 -> 164 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/listitem/core_listitem_divider.pngbin135 -> 135 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/progressbar/core_progressindicator_bg.pngbin1802 -> 1802 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_inactive.pngbin4245 -> 4245 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_pressed.pngbin5460 -> 5460 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/scrollbar/core_scrollbar.pngbin1242 -> 1242 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/bright/slider/core_slider_handle_pressed.pngbin6577 -> 6577 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/button/core_button_inactive.pngbin2262 -> 2262 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/button/core_button_pressed.pngbin2853 -> 2853 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/checkbox/core_checkbox_pressed.pngbin2478 -> 2478 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg.pngbin1315 -> 1315 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg_highlight.pngbin394 -> 394 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/listitem/core_listitem_active.pngbin164 -> 164 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/listitem/core_listitem_divider.pngbin136 -> 136 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/progressbar/core_progressindicator_bg.pngbin1724 -> 1724 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_inactive.pngbin3968 -> 3968 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_pressed.pngbin4777 -> 4777 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/scrollbar/core_scrollbar.pngbin1245 -> 1245 bytes
-rw-r--r--[-rwxr-xr-x]src/plugins/styles/bb10style/dark/slider/core_slider_handle_pressed.pngbin6593 -> 6593 bytes
-rw-r--r--src/printsupport/dialogs/qabstractprintdialog.h4
-rw-r--r--src/printsupport/dialogs/qpagesetupdialog.h4
-rw-r--r--src/printsupport/dialogs/qpagesetupdialog_mac.mm3
-rw-r--r--src/printsupport/dialogs/qprintdialog.h4
-rw-r--r--src/printsupport/dialogs/qprintdialog_mac.mm4
-rw-r--r--src/printsupport/dialogs/qprintpreviewdialog.h5
-rw-r--r--src/printsupport/kernel/qcups.cpp16
-rw-r--r--src/printsupport/kernel/qcups_p.h6
-rw-r--r--src/printsupport/kernel/qpaintengine_alpha.cpp3
-rw-r--r--src/printsupport/kernel/qplatformprintplugin.cpp4
-rw-r--r--src/printsupport/kernel/qprint_p.h4
-rw-r--r--src/printsupport/kernel/qprinter.cpp6
-rw-r--r--src/printsupport/kernel/qprinterinfo.cpp16
-rw-r--r--src/printsupport/widgets/qcupsjobwidget.cpp4
-rw-r--r--src/printsupport/widgets/qcupsjobwidget_p.h4
-rw-r--r--src/printsupport/widgets/qprintpreviewwidget.h5
-rw-r--r--src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp2
-rw-r--r--src/sql/drivers/mysql/qsql_mysql.cpp131
-rw-r--r--src/sql/kernel/qsqldatabase.cpp6
-rw-r--r--src/sql/kernel/qsqldriver.h4
-rw-r--r--src/sql/kernel/qsqldriverplugin.h2
-rw-r--r--src/sql/kernel/qsqlindex.cpp3
-rw-r--r--src/sql/kernel/qsqlindex.h5
-rw-r--r--src/sql/models/qsqlquerymodel.h4
-rw-r--r--src/sql/models/qsqlrelationaltablemodel.h2
-rw-r--r--src/sql/models/qsqltablemodel.h4
-rw-r--r--src/src.pro2
-rw-r--r--src/testlib/qbenchmark_p.h2
-rw-r--r--src/testlib/qsignalspy.h2
-rw-r--r--src/testlib/qtest.h22
-rw-r--r--src/testlib/qtest_gui.h14
-rw-r--r--src/testlib/qtestaccessible.h8
-rw-r--r--src/testlib/qtestblacklist.cpp94
-rw-r--r--src/testlib/qtestblacklist_p.h7
-rw-r--r--src/testlib/qtestcase.cpp326
-rw-r--r--src/testlib/qtestcase.h52
-rw-r--r--src/testlib/qtestevent.h10
-rw-r--r--src/testlib/qtesteventloop.h6
-rw-r--r--src/testlib/qtestkeyboard.h4
-rw-r--r--src/testlib/qtestmouse.cpp (renamed from src/plugins/platforms/xcb/qxlibconvenience.h)20
-rw-r--r--src/testlib/qtestmouse.h108
-rw-r--r--src/testlib/qtestsystem.h6
-rw-r--r--src/testlib/qtesttouch.h16
-rw-r--r--src/testlib/testlib.pro1
-rw-r--r--src/tools/bootstrap/bootstrap.pro7
-rw-r--r--src/tools/moc/preprocessor.cpp25
-rw-r--r--src/tools/moc/preprocessor.h2
-rw-r--r--src/tools/moc/symbols.h6
-rw-r--r--src/tools/qdoc/atom.cpp24
-rw-r--r--src/tools/qdoc/atom.h26
-rw-r--r--src/tools/qdoc/codemarker.cpp23
-rw-r--r--src/tools/qdoc/codemarker.h15
-rw-r--r--src/tools/qdoc/codeparser.cpp36
-rw-r--r--src/tools/qdoc/codeparser.h1
-rw-r--r--src/tools/qdoc/config.cpp12
-rw-r--r--src/tools/qdoc/config.h2
-rw-r--r--src/tools/qdoc/cppcodemarker.cpp68
-rw-r--r--src/tools/qdoc/cppcodemarker.h4
-rw-r--r--src/tools/qdoc/cppcodeparser.cpp472
-rw-r--r--src/tools/qdoc/cppcodeparser.h41
-rw-r--r--src/tools/qdoc/doc.cpp63
-rw-r--r--src/tools/qdoc/doc.h3
-rw-r--r--src/tools/qdoc/doc/examples/examples.qdoc7
-rw-r--r--src/tools/qdoc/doc/qdoc-guide/qdoc-guide.qdoc37
-rw-r--r--src/tools/qdoc/doc/qdoc-manual-cmdindex.qdoc2
-rw-r--r--src/tools/qdoc/doc/qdoc-manual-contextcmds.qdoc79
-rw-r--r--src/tools/qdoc/doc/qdoc-manual-markupcmds.qdoc67
-rw-r--r--src/tools/qdoc/doc/qdoc-manual-qdocconf.qdoc296
-rw-r--r--src/tools/qdoc/doc/qdoc-manual-topiccmds.qdoc6
-rw-r--r--src/tools/qdoc/doc/qdoc-manual.qdoc2
-rw-r--r--src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc25
-rw-r--r--src/tools/qdoc/doc/qtgui-qdocconf.qdoc117
-rw-r--r--src/tools/qdoc/generator.cpp302
-rw-r--r--src/tools/qdoc/generator.h23
-rw-r--r--src/tools/qdoc/helpprojectwriter.cpp125
-rw-r--r--src/tools/qdoc/helpprojectwriter.h5
-rw-r--r--src/tools/qdoc/htmlgenerator.cpp412
-rw-r--r--src/tools/qdoc/htmlgenerator.h24
-rw-r--r--src/tools/qdoc/jscodemarker.cpp6
-rw-r--r--src/tools/qdoc/jscodemarker.h2
-rw-r--r--src/tools/qdoc/location.cpp21
-rw-r--r--src/tools/qdoc/location.h4
-rw-r--r--src/tools/qdoc/main.cpp15
-rw-r--r--src/tools/qdoc/node.cpp770
-rw-r--r--src/tools/qdoc/node.h400
-rw-r--r--src/tools/qdoc/openedlist.h1
-rw-r--r--src/tools/qdoc/plaincodemarker.cpp4
-rw-r--r--src/tools/qdoc/plaincodemarker.h4
-rw-r--r--src/tools/qdoc/puredocparser.cpp14
-rw-r--r--src/tools/qdoc/qdoc.pro3
-rw-r--r--src/tools/qdoc/qdocdatabase.cpp130
-rw-r--r--src/tools/qdoc/qdocdatabase.h62
-rw-r--r--src/tools/qdoc/qdocindexfiles.cpp650
-rw-r--r--src/tools/qdoc/qdocindexfiles.h8
-rw-r--r--src/tools/qdoc/qdoctagfiles.cpp15
-rw-r--r--src/tools/qdoc/qdoctagfiles.h6
-rw-r--r--src/tools/qdoc/qmlcodemarker.cpp8
-rw-r--r--src/tools/qdoc/qmlcodemarker.h4
-rw-r--r--src/tools/qdoc/qmlcodeparser.cpp6
-rw-r--r--src/tools/qdoc/qmlmarkupvisitor.cpp15
-rw-r--r--src/tools/qdoc/qmlmarkupvisitor.h7
-rw-r--r--src/tools/qdoc/qmlparser/qqmljsastfwd_p.h45
-rw-r--r--src/tools/qdoc/qmlparser/qqmljsengine_p.cpp3
-rw-r--r--src/tools/qdoc/qmlparser/qqmljsengine_p.h6
-rw-r--r--src/tools/qdoc/qmlvisitor.cpp29
-rw-r--r--src/tools/qdoc/qmlvisitor.h2
-rw-r--r--src/tools/qdoc/quoter.cpp20
-rw-r--r--src/tools/qdoc/quoter.h2
-rw-r--r--src/tools/qdoc/text.cpp4
-rw-r--r--src/tools/qdoc/text.h4
-rw-r--r--src/tools/qdoc/tokenizer.cpp3
-rw-r--r--src/tools/qdoc/tokenizer.h1
-rw-r--r--src/tools/qdoc/tree.cpp92
-rw-r--r--src/tools/qdoc/tree.h31
-rw-r--r--src/tools/qlalr/compress.cpp2
-rw-r--r--src/tools/qlalr/cppgenerator.cpp4
-rw-r--r--src/tools/qlalr/lalr.cpp8
-rw-r--r--src/tools/qlalr/lalr.h6
-rw-r--r--src/tools/qlalr/parsetable.cpp2
-rw-r--r--src/tools/rcc/rcc.cpp15
-rw-r--r--src/tools/uic/cpp/cppwriteincludes.h1
-rw-r--r--src/tools/uic/uic.h1
-rw-r--r--src/widgets/accessible/complexwidgets.cpp2
-rw-r--r--src/widgets/accessible/itemviews.cpp23
-rw-r--r--src/widgets/accessible/itemviews.h14
-rw-r--r--src/widgets/accessible/qaccessiblewidgets.cpp3
-rw-r--r--src/widgets/dialogs/dialogs.pri1
-rw-r--r--src/widgets/dialogs/qcolordialog.cpp149
-rw-r--r--src/widgets/dialogs/qcolordialog.h11
-rw-r--r--src/widgets/dialogs/qcolordialog_p.h179
-rw-r--r--src/widgets/dialogs/qdialog.h4
-rw-r--r--src/widgets/dialogs/qerrormessage.cpp81
-rw-r--r--src/widgets/dialogs/qerrormessage.h2
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp103
-rw-r--r--src/widgets/dialogs/qfiledialog.h46
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.cpp31
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.h4
-rw-r--r--src/widgets/dialogs/qfilesystemmodel_p.h7
-rw-r--r--src/widgets/dialogs/qfontdialog.cpp1
-rw-r--r--src/widgets/dialogs/qfontdialog.h10
-rw-r--r--src/widgets/dialogs/qinputdialog.cpp1
-rw-r--r--src/widgets/dialogs/qinputdialog.h18
-rw-r--r--src/widgets/dialogs/qmessagebox.h6
-rw-r--r--src/widgets/dialogs/qprogressdialog.cpp3
-rw-r--r--src/widgets/dialogs/qprogressdialog.h5
-rw-r--r--src/widgets/dialogs/qsidebar.cpp16
-rw-r--r--src/widgets/dialogs/qwizard.cpp3
-rw-r--r--src/widgets/dialogs/qwizard.h8
-rw-r--r--[-rwxr-xr-x]src/widgets/doc/images/listview.pngbin9695 -> 9695 bytes
-rw-r--r--[-rwxr-xr-x]src/widgets/doc/images/modelview-combobox.pngbin5022 -> 5022 bytes
-rw-r--r--[-rwxr-xr-x]src/widgets/doc/images/tableview.pngbin10102 -> 10102 bytes
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp10
-rw-r--r--[-rwxr-xr-x]src/widgets/doc/snippets/macmainwindow.mm0
-rw-r--r--src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc6
-rw-r--r--src/widgets/effects/qgraphicseffect.cpp4
-rw-r--r--src/widgets/effects/qgraphicseffect.h14
-rw-r--r--src/widgets/effects/qgraphicseffect_p.h1
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp6
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.h1
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayout.h6
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.cpp4
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.h64
-rw-r--r--src/widgets/graphicsview/qgraphicsitem_p.h4
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.cpp62
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.h2
-rw-r--r--src/widgets/graphicsview/qgraphicslayout.h2
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutitem.h2
-rw-r--r--src/widgets/graphicsview/qgraphicslinearlayout.h4
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.cpp3
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.h10
-rw-r--r--src/widgets/graphicsview/qgraphicssceneevent.h2
-rw-r--r--src/widgets/graphicsview/qgraphicssceneindex.cpp4
-rw-r--r--src/widgets/graphicsview/qgraphicstransform.cpp5
-rw-r--r--src/widgets/graphicsview/qgraphicstransform.h6
-rw-r--r--src/widgets/graphicsview/qgraphicstransform_p.h4
-rw-r--r--src/widgets/graphicsview/qgraphicsview.cpp10
-rw-r--r--src/widgets/graphicsview/qgraphicsview.h6
-rw-r--r--src/widgets/graphicsview/qgraphicsview_p.h1
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.cpp1
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.h8
-rw-r--r--src/widgets/itemviews/itemviews.pri1
-rw-r--r--src/widgets/itemviews/qabstractitemdelegate.h4
-rw-r--r--src/widgets/itemviews/qabstractitemview.cpp13
-rw-r--r--src/widgets/itemviews/qabstractitemview.h6
-rw-r--r--src/widgets/itemviews/qabstractitemview_p.h2
-rw-r--r--src/widgets/itemviews/qcolumnview.cpp12
-rw-r--r--src/widgets/itemviews/qcolumnview.h4
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.cpp2
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.h2
-rw-r--r--src/widgets/itemviews/qdirmodel.cpp1
-rw-r--r--src/widgets/itemviews/qdirmodel.h6
-rw-r--r--src/widgets/itemviews/qfileiconprovider.cpp1
-rw-r--r--src/widgets/itemviews/qheaderview.h4
-rw-r--r--src/widgets/itemviews/qheaderview_p.h1
-rw-r--r--src/widgets/itemviews/qitemdelegate.h2
-rw-r--r--src/widgets/itemviews/qlistview.cpp31
-rw-r--r--src/widgets/itemviews/qlistview.h7
-rw-r--r--src/widgets/itemviews/qlistview_p.h2
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp22
-rw-r--r--src/widgets/itemviews/qlistwidget.h10
-rw-r--r--src/widgets/itemviews/qstyleditemdelegate.h2
-rw-r--r--src/widgets/itemviews/qtableview.cpp6
-rw-r--r--src/widgets/itemviews/qtableview.h2
-rw-r--r--src/widgets/itemviews/qtablewidget.cpp25
-rw-r--r--src/widgets/itemviews/qtablewidget.h6
-rw-r--r--src/widgets/itemviews/qtreeview.h4
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp16
-rw-r--r--src/widgets/itemviews/qtreewidget.h6
-rw-r--r--src/widgets/itemviews/qwidgetitemdata_p.h1
-rw-r--r--src/widgets/kernel/qaction.cpp5
-rw-r--r--src/widgets/kernel/qaction.h2
-rw-r--r--src/widgets/kernel/qapplication.cpp9
-rw-r--r--src/widgets/kernel/qapplication.h4
-rw-r--r--src/widgets/kernel/qboxlayout.h6
-rw-r--r--src/widgets/kernel/qdesktopwidget.h2
-rw-r--r--src/widgets/kernel/qformlayout.h2
-rw-r--r--src/widgets/kernel/qgesture.h12
-rw-r--r--src/widgets/kernel/qgesturemanager.cpp13
-rw-r--r--src/widgets/kernel/qgridlayout.h10
-rw-r--r--src/widgets/kernel/qlayout.cpp3
-rw-r--r--src/widgets/kernel/qlayoutitem.h2
-rw-r--r--src/widgets/kernel/qopenglwidget.cpp41
-rw-r--r--src/widgets/kernel/qopenglwidget.h2
-rw-r--r--src/widgets/kernel/qshortcut.h2
-rw-r--r--src/widgets/kernel/qsizepolicy.cpp9
-rw-r--r--src/widgets/kernel/qsizepolicy.h6
-rw-r--r--src/widgets/kernel/qtooltip.cpp1
-rw-r--r--src/widgets/kernel/qtooltip.h2
-rw-r--r--src/widgets/kernel/qwhatsthis.cpp1
-rw-r--r--src/widgets/kernel/qwhatsthis.h4
-rw-r--r--src/widgets/kernel/qwidget.cpp118
-rw-r--r--src/widgets/kernel/qwidget.h17
-rw-r--r--src/widgets/kernel/qwidgetbackingstore.cpp3
-rw-r--r--src/widgets/kernel/qwidgetbackingstore_p.h2
-rw-r--r--src/widgets/kernel/qwidgetwindow.cpp20
-rw-r--r--src/widgets/statemachine/qkeyeventtransition.cpp2
-rw-r--r--src/widgets/statemachine/qkeyeventtransition.h4
-rw-r--r--src/widgets/statemachine/qmouseeventtransition.h4
-rw-r--r--src/widgets/styles/qcommonstyle.h32
-rw-r--r--src/widgets/styles/qdrawutil.h22
-rw-r--r--src/widgets/styles/qfusionstyle.cpp1
-rw-r--r--src/widgets/styles/qgtk2painter.cpp2
-rw-r--r--src/widgets/styles/qgtkstyle_p.cpp4
-rw-r--r--src/widgets/styles/qmacstyle_mac.mm37
-rw-r--r--src/widgets/styles/qmacstyle_mac_p_p.h4
-rw-r--r--src/widgets/styles/qproxystyle.h20
-rw-r--r--src/widgets/styles/qstyle.h34
-rw-r--r--src/widgets/styles/qstylepainter.h2
-rw-r--r--src/widgets/styles/qstyleplugin.h2
-rw-r--r--src/widgets/styles/qstylesheetstyle.cpp50
-rw-r--r--src/widgets/styles/qwindowsstyle.cpp2
-rw-r--r--src/widgets/styles/qwindowsstyle_p_p.h3
-rw-r--r--src/widgets/util/qcompleter.h6
-rw-r--r--src/widgets/util/qflickgesture.cpp14
-rw-r--r--src/widgets/util/qscroller_mac.mm3
-rw-r--r--src/widgets/util/qscroller_p.h3
-rw-r--r--src/widgets/util/qsystemtrayicon.h4
-rw-r--r--src/widgets/util/qsystemtrayicon_x11.cpp32
-rw-r--r--src/widgets/util/qundogroup.h2
-rw-r--r--src/widgets/util/qundostack.h6
-rw-r--r--src/widgets/util/qundoview.h6
-rw-r--r--src/widgets/widgets/qabstractbutton.cpp13
-rw-r--r--src/widgets/widgets/qabstractbutton.h4
-rw-r--r--src/widgets/widgets/qabstractscrollarea.cpp6
-rw-r--r--src/widgets/widgets/qabstractscrollarea.h4
-rw-r--r--src/widgets/widgets/qabstractscrollarea_p.h3
-rw-r--r--src/widgets/widgets/qabstractslider.h4
-rw-r--r--src/widgets/widgets/qabstractspinbox.h4
-rw-r--r--src/widgets/widgets/qbuttongroup.h2
-rw-r--r--src/widgets/widgets/qcalendarwidget.h2
-rw-r--r--src/widgets/widgets/qcheckbox.h4
-rw-r--r--src/widgets/widgets/qcombobox.cpp4
-rw-r--r--src/widgets/widgets/qcombobox.h2
-rw-r--r--src/widgets/widgets/qcombobox_p.h1
-rw-r--r--src/widgets/widgets/qcommandlinkbutton.h6
-rw-r--r--src/widgets/widgets/qdatetimeedit.h18
-rw-r--r--src/widgets/widgets/qdial.h2
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.h8
-rw-r--r--src/widgets/widgets/qdockarealayout.cpp153
-rw-r--r--src/widgets/widgets/qdockarealayout_p.h8
-rw-r--r--src/widgets/widgets/qdockwidget.cpp160
-rw-r--r--src/widgets/widgets/qdockwidget.h5
-rw-r--r--src/widgets/widgets/qdockwidget_p.h3
-rw-r--r--src/widgets/widgets/qfocusframe.h2
-rw-r--r--src/widgets/widgets/qfontcombobox.cpp8
-rw-r--r--src/widgets/widgets/qfontcombobox.h2
-rw-r--r--src/widgets/widgets/qframe.cpp6
-rw-r--r--src/widgets/widgets/qframe.h4
-rw-r--r--src/widgets/widgets/qframe_p.h4
-rw-r--r--src/widgets/widgets/qgroupbox.h4
-rw-r--r--src/widgets/widgets/qkeysequenceedit.h4
-rw-r--r--src/widgets/widgets/qlabel.cpp83
-rw-r--r--src/widgets/widgets/qlabel.h4
-rw-r--r--src/widgets/widgets/qlabel_p.h72
-rw-r--r--src/widgets/widgets/qlcdnumber.h4
-rw-r--r--src/widgets/widgets/qlineedit.h4
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp2
-rw-r--r--src/widgets/widgets/qlineedit_p.h3
-rw-r--r--src/widgets/widgets/qmaccocoaviewcontainer_mac.h2
-rw-r--r--src/widgets/widgets/qmacnativewidget_mac.h2
-rw-r--r--src/widgets/widgets/qmainwindow.cpp54
-rw-r--r--src/widgets/widgets/qmainwindow.h8
-rw-r--r--src/widgets/widgets/qmainwindowlayout.cpp675
-rw-r--r--src/widgets/widgets/qmainwindowlayout_p.h46
-rw-r--r--src/widgets/widgets/qmdiarea.h4
-rw-r--r--src/widgets/widgets/qmdiarea_p.h4
-rw-r--r--src/widgets/widgets/qmdisubwindow.cpp4
-rw-r--r--src/widgets/widgets/qmdisubwindow.h2
-rw-r--r--src/widgets/widgets/qmenu.cpp111
-rw-r--r--src/widgets/widgets/qmenu.h80
-rw-r--r--src/widgets/widgets/qmenu_p.h4
-rw-r--r--src/widgets/widgets/qmenubar.cpp4
-rw-r--r--src/widgets/widgets/qmenubar.h2
-rw-r--r--src/widgets/widgets/qplaintextedit.cpp2
-rw-r--r--src/widgets/widgets/qplaintextedit.h8
-rw-r--r--src/widgets/widgets/qprogressbar.h2
-rw-r--r--src/widgets/widgets/qpushbutton.h8
-rw-r--r--src/widgets/widgets/qradiobutton.h4
-rw-r--r--src/widgets/widgets/qrubberband.h2
-rw-r--r--src/widgets/widgets/qscrollarea.h4
-rw-r--r--src/widgets/widgets/qscrollbar.h4
-rw-r--r--src/widgets/widgets/qslider.h4
-rw-r--r--src/widgets/widgets/qspinbox.h4
-rw-r--r--src/widgets/widgets/qsplashscreen.h4
-rw-r--r--src/widgets/widgets/qsplitter.cpp13
-rw-r--r--src/widgets/widgets/qsplitter.h4
-rw-r--r--src/widgets/widgets/qsplitter_p.h1
-rw-r--r--src/widgets/widgets/qstackedwidget.h2
-rw-r--r--src/widgets/widgets/qstatusbar.h2
-rw-r--r--src/widgets/widgets/qtabbar.h2
-rw-r--r--src/widgets/widgets/qtabwidget.h2
-rw-r--r--src/widgets/widgets/qtextbrowser.cpp1
-rw-r--r--src/widgets/widgets/qtextbrowser.h2
-rw-r--r--src/widgets/widgets/qtextedit.h8
-rw-r--r--src/widgets/widgets/qtoolbar.cpp76
-rw-r--r--src/widgets/widgets/qtoolbar.h50
-rw-r--r--src/widgets/widgets/qtoolbox.h2
-rw-r--r--src/widgets/widgets/qtoolbutton.h2
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol.cpp7
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp21
-rw-r--r--src/winmain/qtmain_winrt.cpp263
-rw-r--r--src/xml/dom/qdom.h16
-rw-r--r--src/xml/sax/qxml.h8
-rw-r--r--src/xml/sax/qxml_p.h4
-rw-r--r--sync.profile2
-rw-r--r--tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp28
-rw-r--r--tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp24
-rw-r--r--tests/auto/corelib/animation/qpauseanimation/BLACKLIST4
-rw-r--r--tests/auto/corelib/animation/qpropertyanimation/BLACKLIST4
-rw-r--r--tests/auto/corelib/animation/qsequentialanimationgroup/BLACKLIST4
-rw-r--r--tests/auto/corelib/global/qglobal/tst_qglobal.cpp2
-rw-r--r--tests/auto/corelib/global/qglobalstatic/tst_qglobalstatic.cpp21
-rw-r--r--tests/auto/corelib/io/qdebug/tst_qdebug.cpp34
-rw-r--r--tests/auto/corelib/io/qdir/qdir.pro2
-rw-r--r--tests/auto/corelib/io/qdiriterator/qdiriterator.pro2
-rw-r--r--tests/auto/corelib/io/qfileinfo/qfileinfo.pro2
-rw-r--r--tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp3
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+haiku/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+haiku/test20
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+haiku/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/qfileselector.qrc3
-rw-r--r--tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp2
-rw-r--r--tests/auto/corelib/io/qfilesystemwatcher/BLACKLIST1
-rw-r--r--tests/auto/corelib/io/qfilesystemwatcher/tst_qfilesystemwatcher.cpp2
-rw-r--r--tests/auto/corelib/io/qiodevice/BLACKLIST2
-rw-r--r--tests/auto/corelib/io/qprocess/BLACKLIST2
-rw-r--r--tests/auto/corelib/io/qprocess/tst_qprocess.cpp168
-rw-r--r--tests/auto/corelib/io/qprocessenvironment/tst_qprocessenvironment.cpp19
-rw-r--r--tests/auto/corelib/io/qsettings/BLACKLIST2
-rw-r--r--tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp8
-rw-r--r--tests/auto/corelib/io/qtextstream/BLACKLIST2
-rw-r--r--tests/auto/corelib/io/qurlquery/tst_qurlquery.cpp3
-rw-r--r--tests/auto/corelib/itemmodels/qabstractitemmodel/tst_qabstractitemmodel.cpp2
-rw-r--r--tests/auto/corelib/itemmodels/qitemselectionmodel/tst_qitemselectionmodel.cpp2
-rw-r--r--tests/auto/corelib/itemmodels/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp27
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro1
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp77
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h3
-rw-r--r--tests/auto/corelib/kernel/qeventdispatcher/BLACKLIST4
-rw-r--r--tests/auto/corelib/kernel/qeventloop/BLACKLIST2
-rw-r--r--tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp12
-rw-r--r--tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp40
-rw-r--r--tests/auto/corelib/kernel/qobject/BLACKLIST2
-rw-r--r--tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp17
-rw-r--r--tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST3
-rw-r--r--tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp3
-rw-r--r--tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp3
-rw-r--r--tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp12
-rw-r--r--tests/auto/corelib/plugin/qpluginloader/tst_qpluginloader.cpp19
-rw-r--r--tests/auto/corelib/statemachine/qstate/tst_qstate.cpp31
-rw-r--r--tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp61
-rw-r--r--tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp58
-rw-r--r--tests/auto/corelib/thread/qfuture/tst_qfuture.cpp34
-rw-r--r--tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp8
-rw-r--r--tests/auto/corelib/thread/qsemaphore/BLACKLIST3
-rw-r--r--tests/auto/corelib/thread/qthread/BLACKLIST2
-rw-r--r--tests/auto/corelib/thread/qthreadpool/BLACKLIST5
-rw-r--r--tests/auto/corelib/tools/collections/tst_collections.cpp2
-rwxr-xr-x[-rw-r--r--]tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp107
-rw-r--r--tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp15
-rw-r--r--tests/auto/corelib/tools/qbytearray/tst_qbytearray_mac.mm12
-rw-r--r--tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp6
-rw-r--r--tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp39
-rw-r--r--tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm6
-rw-r--r--tests/auto/corelib/tools/qhash/tst_qhash.cpp29
-rw-r--r--tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp4
-rw-r--r--tests/auto/corelib/tools/qlist/tst_qlist.cpp228
-rw-r--r--tests/auto/corelib/tools/qlocale/tst_qlocale.cpp2
-rw-r--r--tests/auto/corelib/tools/qmap/tst_qmap.cpp63
-rw-r--r--tests/auto/corelib/tools/qregexp/tst_qregexp.cpp3
-rw-r--r--tests/auto/corelib/tools/qregularexpression/tst_qregularexpression.cpp5
-rw-r--r--tests/auto/corelib/tools/qringbuffer/tst_qringbuffer.cpp129
-rw-r--r--tests/auto/corelib/tools/qset/tst_qset.cpp27
-rw-r--r--tests/auto/corelib/tools/qstring/tst_qstring.cpp544
-rw-r--r--tests/auto/corelib/tools/qstring/tst_qstring_mac.mm8
-rw-r--r--tests/auto/corelib/tools/qstringref/tst_qstringref.cpp25
-rw-r--r--tests/auto/corelib/tools/qtimeline/BLACKLIST4
-rw-r--r--tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp2
-rw-r--r--tests/auto/corelib/tools/qtimezone/BLACKLIST2
-rw-r--r--tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp60
-rw-r--r--tests/auto/corelib/tools/qvector/qvector.pro1
-rw-r--r--tests/auto/corelib/tools/qvector/tst_qvector.cpp261
-rw-r--r--tests/auto/corelib/tools/qversionnumber/tst_qversionnumber.cpp2
-rw-r--r--tests/auto/dbus/qdbusabstractadaptor/BLACKLIST2
-rw-r--r--tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp45
-rw-r--r--tests/auto/dbus/qdbusmarshall/BLACKLIST3
-rw-r--r--tests/auto/dbus/qdbusmarshall/tst_qdbusmarshall.cpp10
-rw-r--r--tests/auto/dbus/qdbustype/tst_qdbustype.cpp4
-rw-r--r--tests/auto/gui/image/qicon/tst_qicon.cpp16
-rw-r--r--tests/auto/gui/image/qimage/tst_qimage.cpp10
-rw-r--r--tests/auto/gui/image/qimagereader/tst_qimagereader.cpp8
-rw-r--r--tests/auto/gui/image/qmovie/tst_qmovie.cpp6
-rw-r--r--tests/auto/gui/image/qpixmap/tst_qpixmap.cpp24
-rw-r--r--tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp10
-rw-r--r--tests/auto/gui/itemmodels/qstandarditem/tst_qstandarditem.cpp26
-rw-r--r--tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp2
-rw-r--r--tests/auto/gui/kernel/qguieventloop/BLACKLIST2
-rw-r--r--tests/auto/gui/kernel/qguivariant/no_application/main.cpp2
-rw-r--r--tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp12
-rw-r--r--tests/auto/gui/kernel/qinputmethod/tst_qinputmethod.cpp3
-rw-r--r--tests/auto/gui/kernel/qopenglwindow/tst_qopenglwindow.cpp4
-rw-r--r--tests/auto/gui/kernel/qpixelformat/tst_qpixelformat.cpp2
-rw-r--r--tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp136
-rw-r--r--tests/auto/gui/kernel/qwindow/tst_qwindow.cpp107
-rw-r--r--tests/auto/gui/math3d/qmatrixnxn/tst_qmatrixnxn.cpp48
-rw-r--r--tests/auto/gui/math3d/qquaternion/tst_qquaternion.cpp20
-rw-r--r--tests/auto/gui/math3d/qvectornd/tst_qvectornd.cpp74
-rw-r--r--tests/auto/gui/painting/qbrush/tst_qbrush.cpp4
-rw-r--r--tests/auto/gui/painting/qcolor/tst_qcolor.cpp114
-rw-r--r--tests/auto/gui/painting/qpagelayout/tst_qpagelayout.cpp2
-rw-r--r--tests/auto/gui/painting/qpainter/qpainter.pro2
-rw-r--r--tests/auto/gui/painting/qpainter/tst_qpainter.cpp278
-rw-r--r--tests/auto/gui/painting/qpainterpath/tst_qpainterpath.cpp34
-rw-r--r--tests/auto/gui/painting/qregion/tst_qregion.cpp2
-rw-r--r--tests/auto/gui/painting/qtransform/tst_qtransform.cpp37
-rw-r--r--tests/auto/gui/qopengl/BLACKLIST8
-rw-r--r--tests/auto/gui/qopengl/tst_qopengl.cpp201
-rw-r--r--tests/auto/gui/qopenglconfig/buglist.json22
-rw-r--r--tests/auto/gui/qopenglconfig/tst_qopenglconfig.cpp42
-rw-r--r--tests/auto/gui/text/qcssparser/tst_qcssparser.cpp38
-rw-r--r--tests/auto/gui/text/qfont/BLACKLIST2
-rw-r--r--tests/auto/gui/text/qfont/tst_qfont.cpp70
-rw-r--r--tests/auto/gui/text/qrawfont/BLACKLIST4
-rw-r--r--tests/auto/gui/text/qsyntaxhighlighter/tst_qsyntaxhighlighter.cpp31
-rw-r--r--tests/auto/gui/text/qtextblock/tst_qtextblock.cpp4
-rw-r--r--tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp186
-rw-r--r--tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp37
-rw-r--r--tests/auto/gui/text/qtextdocumentfragment/tst_qtextdocumentfragment.cpp224
-rw-r--r--tests/auto/gui/text/qtextdocumentlayout/BLACKLIST2
-rw-r--r--tests/auto/gui/text/qtextformat/tst_qtextformat.cpp4
-rw-r--r--tests/auto/gui/text/qtextlayout/tst_qtextlayout.cpp29
-rw-r--r--tests/auto/gui/text/qtextlist/tst_qtextlist.cpp46
-rw-r--r--tests/auto/gui/text/qtextpiecetable/tst_qtextpiecetable.cpp336
-rw-r--r--tests/auto/gui/text/qtexttable/tst_qtexttable.cpp188
-rw-r--r--tests/auto/gui/text/qzip/tst_qzip.cpp19
-rw-r--r--tests/auto/gui/util/qdoublevalidator/tst_qdoublevalidator.cpp32
-rw-r--r--tests/auto/gui/util/qintvalidator/tst_qintvalidator.cpp16
-rw-r--r--tests/auto/network/access/qabstractnetworkcache/BLACKLIST9
-rw-r--r--tests/auto/network/access/qftp/BLACKLIST11
-rw-r--r--tests/auto/network/access/qftp/qftp.pro1
-rw-r--r--tests/auto/network/access/qftp/tst_qftp.cpp3
-rw-r--r--tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp4
-rw-r--r--tests/auto/network/access/qnetworkreply/element.xml1
-rw-r--r--tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp251
-rw-r--r--tests/auto/network/access/spdy/BLACKLIST4
-rw-r--r--tests/auto/network/access/spdy/spdy.pro2
-rw-r--r--tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp38
-rw-r--r--tests/auto/network/bearer/qnetworkconfigurationmanager/tst_qnetworkconfigurationmanager.cpp4
-rw-r--r--tests/auto/network/bearer/qnetworksession/test/tst_qnetworksession.cpp99
-rw-r--r--tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp6
-rw-r--r--tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp74
-rw-r--r--tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp6
-rw-r--r--tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp2
-rw-r--r--tests/auto/network/kernel/qnetworkinterface/BLACKLIST2
-rw-r--r--tests/auto/network/socket/platformsocketengine/BLACKLIST1
-rw-r--r--tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp138
-rw-r--r--tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp53
-rw-r--r--tests/auto/network/socket/qhttpsocketengine/BLACKLIST1
-rw-r--r--tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp62
-rw-r--r--tests/auto/network/socket/qlocalsocket/BLACKLIST2
-rw-r--r--tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp25
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/BLACKLIST2
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp116
-rw-r--r--tests/auto/network/socket/qtcpserver/BLACKLIST13
-rw-r--r--tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp10
-rw-r--r--tests/auto/network/socket/qtcpsocket/test/test.pro2
-rw-r--r--tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp112
-rw-r--r--tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp4
-rw-r--r--tests/auto/network/ssl/qsslcertificate/BLACKLIST3
-rw-r--r--tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp81
-rw-r--r--tests/auto/network/ssl/qsslkey/BLACKLIST1
-rw-r--r--tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp2
-rw-r--r--tests/auto/network/ssl/qsslsocket/BLACKLIST1
-rw-r--r--tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp124
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST2
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST2
-rw-r--r--tests/auto/opengl/qgl/BLACKLIST16
-rw-r--r--tests/auto/opengl/qgl/tst_qgl.cpp128
-rw-r--r--tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp10
-rw-r--r--tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp4
-rw-r--r--tests/auto/other/compiler/tst_compiler.cpp16
-rw-r--r--tests/auto/other/gestures/BLACKLIST2
-rw-r--r--tests/auto/other/gestures/tst_gestures.cpp2
-rw-r--r--tests/auto/other/macgui/tst_macgui.cpp4
-rw-r--r--tests/auto/other/macnativeevents/BLACKLIST13
-rw-r--r--tests/auto/other/macnativeevents/tst_macnativeevents.cpp8
-rw-r--r--tests/auto/other/modeltest/modeltest.cpp2
-rw-r--r--tests/auto/other/networkselftest/tst_networkselftest.cpp56
-rw-r--r--tests/auto/other/qaccessibility/tst_qaccessibility.cpp57
-rw-r--r--tests/auto/other/qcomplextext/tst_qcomplextext.cpp2
-rw-r--r--tests/auto/other/windowsmobile/test/tst_windowsmobile.cpp2
-rw-r--r--tests/auto/printsupport/kernel/qprintdevice/tst_qprintdevice.cpp5
-rw-r--r--tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp6
-rw-r--r--[-rwxr-xr-x]tests/auto/sql/kernel/qsqldatabase/testdata/qtest.mdbbin65536 -> 65536 bytes
-rw-r--r--tests/auto/sql/kernel/qsqldatabase/tst_databases.h4
-rw-r--r--tests/auto/sql/kernel/qsqldatabase/tst_qsqldatabase.cpp30
-rw-r--r--tests/auto/sql/kernel/qsqlerror/tst_qsqlerror.cpp2
-rw-r--r--tests/auto/sql/kernel/qsqlquery/tst_qsqlquery.cpp64
-rw-r--r--tests/auto/sql/models/qsqlrelationaltablemodel/tst_qsqlrelationaltablemodel.cpp30
-rw-r--r--tests/auto/sql/models/qsqltablemodel/tst_qsqltablemodel.cpp18
-rw-r--r--tests/auto/testlib/selftests/cmptest/tst_cmptest.cpp51
-rw-r--r--tests/auto/testlib/selftests/expected_cmptest.lightxml98
-rw-r--r--tests/auto/testlib/selftests/expected_cmptest.txt58
-rw-r--r--tests/auto/testlib/selftests/expected_cmptest.xml98
-rw-r--r--tests/auto/testlib/selftests/expected_cmptest.xunitxml22
-rw-r--r--tests/auto/testlib/selftests/tst_selftests.cpp8
-rw-r--r--tests/auto/tools/moc/tst_moc.cpp64
-rw-r--r--tests/auto/tools/qmake/qmake.pro6
-rw-r--r--tests/auto/tools/qmake/testdata/resources/main.cpp (renamed from tests/auto/widgets/kernel/qapplication/wincmdline/main.cpp)18
-rw-r--r--tests/auto/tools/qmake/testdata/resources/resources.pro10
-rw-r--r--tests/auto/tools/qmake/testdata/resources/subdir/file.txt0
-rw-r--r--tests/auto/tools/qmake/testdata/resources/test.qrc5
-rw-r--r--tests/auto/tools/qmake/tst_qmake.cpp42
-rw-r--r--tests/auto/widgets/dialogs/qcolordialog/qcolordialog.pro3
-rw-r--r--tests/auto/widgets/dialogs/qcolordialog/tst_qcolordialog.cpp2
-rw-r--r--tests/auto/widgets/dialogs/qdialog/BLACKLIST2
-rw-r--r--tests/auto/widgets/dialogs/qfiledialog/qfiledialog.pro2
-rw-r--r--tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp8
-rw-r--r--tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp22
-rw-r--r--tests/auto/widgets/dialogs/qfontdialog/BLACKLIST4
-rw-r--r--tests/auto/widgets/dialogs/qfontdialog/tst_qfontdialog_mac_helpers.mm2
-rw-r--r--tests/auto/widgets/dialogs/qmessagebox/tst_qmessagebox.cpp30
-rw-r--r--tests/auto/widgets/dialogs/qprogressdialog/BLACKLIST2
-rw-r--r--tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp96
-rw-r--r--tests/auto/widgets/effects/qgraphicseffect/tst_qgraphicseffect.cpp4
-rw-r--r--tests/auto/widgets/gestures/qgesturerecognizer/BLACKLIST2
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsanchorlayout/tst_qgraphicsanchorlayout.cpp11
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsanchorlayout1/tst_qgraphicsanchorlayout1.cpp8
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp32
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicslayout/tst_qgraphicslayout.cpp2
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicslinearlayout/tst_qgraphicslinearlayout.cpp4
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsobject/tst_qgraphicsobject.cpp38
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp44
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp47
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsview/BLACKLIST18
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp2
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp18
-rw-r--r--tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp4
-rw-r--r--tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp4
-rw-r--r--tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp40
-rw-r--r--tests/auto/widgets/itemviews/qitemdelegate/tst_qitemdelegate.cpp16
-rw-r--r--tests/auto/widgets/itemviews/qitemview/tst_qitemview.cpp17
-rw-r--r--tests/auto/widgets/itemviews/qlistview/qlistview.pro1
-rw-r--r--tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp51
-rw-r--r--tests/auto/widgets/itemviews/qlistwidget/tst_qlistwidget.cpp10
-rw-r--r--tests/auto/widgets/itemviews/qtableview/BLACKLIST2
-rw-r--r--tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp12
-rw-r--r--tests/auto/widgets/itemviews/qtablewidget/tst_qtablewidget.cpp6
-rw-r--r--tests/auto/widgets/itemviews/qtreeview/qtreeview.pro2
-rw-r--r--tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp2
-rw-r--r--tests/auto/widgets/itemviews/qtreewidget/tst_qtreewidget.cpp18
-rw-r--r--tests/auto/widgets/itemviews/qtreewidgetitemiterator/tst_qtreewidgetitemiterator.cpp4
-rw-r--r--tests/auto/widgets/kernel/qaction/BLACKLIST2
-rw-r--r--tests/auto/widgets/kernel/qaction/tst_qaction.cpp2
-rw-r--r--tests/auto/widgets/kernel/qactiongroup/BLACKLIST2
-rw-r--r--tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp3
-rw-r--r--tests/auto/widgets/kernel/qapplication/BLACKLIST4
-rw-r--r--tests/auto/widgets/kernel/qapplication/qapplication.pro1
-rw-r--r--tests/auto/widgets/kernel/qapplication/test/BLACKLIST2
-rw-r--r--tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp159
-rw-r--r--tests/auto/widgets/kernel/qapplication/wincmdline/wincmdline.pro5
-rw-r--r--tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp103
-rw-r--r--tests/auto/widgets/kernel/qdesktopwidget/tst_qdesktopwidget.cpp1
-rw-r--r--tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp429
-rw-r--r--tests/auto/widgets/kernel/qgridlayout/tst_qgridlayout.cpp160
-rw-r--r--tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp7
-rw-r--r--tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp1
-rw-r--r--tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp21
-rw-r--r--tests/auto/widgets/kernel/qtooltip/BLACKLIST4
-rw-r--r--tests/auto/widgets/kernel/qwidget/BLACKLIST78
-rw-r--r--tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp112
-rw-r--r--tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp45
-rw-r--r--tests/auto/widgets/kernel/qwidgetaction/tst_qwidgetaction.cpp33
-rw-r--r--tests/auto/widgets/kernel/qwidgetsvariant/tst_qwidgetsvariant.cpp6
-rw-r--r--tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp2
-rw-r--r--tests/auto/widgets/styles/qstyle/tst_qstyle.cpp10
-rw-r--r--tests/auto/widgets/styles/qstylesheetstyle/BLACKLIST2
-rw-r--r--tests/auto/widgets/styles/qstylesheetstyle/tst_qstylesheetstyle.cpp188
-rw-r--r--tests/auto/widgets/util/qcompleter/BLACKLIST2
-rw-r--r--tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp22
-rw-r--r--tests/auto/widgets/util/qscroller/tst_qscroller.cpp2
-rw-r--r--tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp2
-rw-r--r--tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp6
-rw-r--r--tests/auto/widgets/widgets/qbuttongroup/tst_qbuttongroup.cpp36
-rw-r--r--tests/auto/widgets/widgets/qcheckbox/tst_qcheckbox.cpp4
-rw-r--r--tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp45
-rw-r--r--tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp8
-rw-r--r--tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp8
-rw-r--r--tests/auto/widgets/widgets/qdialogbuttonbox/tst_qdialogbuttonbox.cpp6
-rw-r--r--tests/auto/widgets/widgets/qdockwidget/BLACKLIST2
-rw-r--r--tests/auto/widgets/widgets/qdockwidget/tst_qdockwidget.cpp32
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_0.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_1.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_2.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_0.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_1.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_2.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_0.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_1.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_2.pngbin148 -> 148 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_0.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_1.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_2.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_0.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_1.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_2.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_0.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_1.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_2.pngbin154 -> 154 bytes
-rw-r--r--tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp5
-rw-r--r--tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp62
-rw-r--r--tests/auto/widgets/widgets/qmainwindow/tst_qmainwindow.cpp159
-rw-r--r--tests/auto/widgets/widgets/qmdiarea/BLACKLIST3
-rw-r--r--tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp28
-rw-r--r--tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp37
-rw-r--r--tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp120
-rw-r--r--tests/auto/widgets/widgets/qopenglwidget/BLACKLIST2
-rw-r--r--tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp4
-rw-r--r--tests/auto/widgets/widgets/qplaintextedit/tst_qplaintextedit.cpp30
-rw-r--r--tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp4
-rw-r--r--tests/auto/widgets/widgets/qscrollarea/tst_qscrollarea.cpp4
-rw-r--r--tests/auto/widgets/widgets/qsizegrip/BLACKLIST2
-rw-r--r--tests/auto/widgets/widgets/qspinbox/BLACKLIST3
-rw-r--r--tests/auto/widgets/widgets/qtabbar/BLACKLIST2
-rw-r--r--tests/auto/widgets/widgets/qtabwidget/tst_qtabwidget.cpp42
-rw-r--r--tests/auto/widgets/widgets/qtextbrowser/tst_qtextbrowser.cpp60
-rw-r--r--tests/auto/widgets/widgets/qtextedit/tst_qtextedit.cpp48
-rw-r--r--tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp32
-rw-r--r--tests/auto/widgets/widgets/qtoolbutton/tst_qtoolbutton.cpp4
-rw-r--r--tests/auto/xml/dom/qdom/tst_qdom.cpp10
-rw-r--r--tests/auto/xml/sax/qxmlinputsource/tst_qxmlinputsource.cpp2
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/001.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/002.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/004.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/005.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/006.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/007.entbin4 -> 4 bytes
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/008.entbin54 -> 54 bytes
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/009.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/011.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/012.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/013.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/014.entbin12 -> 12 bytes
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/002.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/003-1.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-1.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-2.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-1.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-2.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/006.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/007.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/008.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/009.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/010.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/011.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/012.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/013.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/014.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/015.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/016.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/017.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/018.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/019.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/020.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/021.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/022.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/023.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/024.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/025.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/026.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/027.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/028.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/029.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/030.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-1.ent0
-rw-r--r--[-rwxr-xr-x]tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-2.ent0
-rw-r--r--tests/benchmarks/corelib/io/qdiriterator/main.cpp4
-rw-r--r--tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.cpp4
-rw-r--r--tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.h3
-rw-r--r--tests/benchmarks/corelib/tools/qringbuffer/main.cpp4
-rw-r--r--tests/benchmarks/gui/text/qtext/main.cpp14
-rw-r--r--tests/benchmarks/sql/kernel/qsqlquery/main.cpp40
-rw-r--r--tests/manual/cocoa/qt_on_cocoa/main.mm168
-rw-r--r--tests/manual/cocoa/qt_on_cocoa/qt_on_cocoa.pro10
-rw-r--r--tests/manual/cocoa/qt_on_cocoa/rasterwindow.cpp (renamed from tests/manual/cocoa/qt_on_cocoa/window.cpp)37
-rw-r--r--tests/manual/cocoa/qt_on_cocoa/rasterwindow.h (renamed from tests/manual/cocoa/qt_on_cocoa/window.h)7
-rw-r--r--tests/manual/highdpi/dragwidget.cpp223
-rw-r--r--tests/manual/highdpi/dragwidget.h68
-rw-r--r--tests/manual/highdpi/highdpi.pro13
-rw-r--r--tests/manual/highdpi/main.cpp725
-rw-r--r--tests/manual/qscreen/main.cpp139
-rw-r--r--tests/manual/qscreen/propertywatcher.cpp81
-rw-r--r--tests/manual/qscreen/propertywatcher.h14
-rw-r--r--tests/manual/qscreen/qscreen.pro1
-rw-r--r--tests/manual/qsysinfo/main.cpp1
-rw-r--r--tests/manual/qtabletevent/device_information/tabletwidget.cpp3
-rw-r--r--tests/manual/qtabletevent/device_information/tabletwidget.h1
-rw-r--r--tests/manual/qtabletevent/regular_widgets/main.cpp34
-rw-r--r--tests/manual/touch/main.cpp433
-rw-r--r--tools/configure/Makefile.mingw1
-rw-r--r--tools/configure/Makefile.win322
-rw-r--r--tools/configure/configure.pro2
-rw-r--r--tools/configure/configureapp.cpp39
-rw-r--r--tools/configure/configureapp.h3
1858 files changed, 47789 insertions, 22003 deletions
diff --git a/config.tests/arch/arch.cpp b/config.tests/arch/arch.cpp
index 854228cc9c..7e481d4cf5 100644
--- a/config.tests/arch/arch.cpp
+++ b/config.tests/arch/arch.cpp
@@ -57,6 +57,10 @@ const char msg2[] = "==Qt=magic=Qt== Sub-architecture:"
// Advanced Bit Manipulation, AMD Barcelona (family 10h)
" abm"
#endif
+#ifdef __ADX__
+// Multi-Precision Add-Carry Instruction Extensions, Intel Core 5th generation ("Broadwell")
+" adx"
+#endif
#ifdef __AES__
// AES New Instructions, Intel Core-i7 second generation ("Sandy Bridge")
" aes"
@@ -70,19 +74,19 @@ const char msg2[] = "==Qt=magic=Qt== Sub-architecture:"
" avx2"
#endif
#ifdef __AVX512F__
-// AVX512 Foundation, Intel Xeon Phi codename "Knights Landing"
+// AVX512 Foundation, Intel Xeon Phi codename "Knights Landing" and Intel Xeon codename "Skylake"
" avx512f"
#endif
#ifdef __AVX512CD__
-// AVX512 Conflict Detection, Intel Xeon Phi codename "Knights Landing"
+// AVX512 Conflict Detection, Intel Xeon Phi codename "Knights Landing" and Intel Xeon codename "Skylake"
" avx512cd"
#endif
#ifdef __AVX512DQ__
-// AVX512 Double & Quadword, future Intel Xeon processor
+// AVX512 Double & Quadword, Intel Xeon processor codename "Skylake"
" avx512dq"
#endif
#ifdef __AVX512BW__
-// AVX512 Byte & Word, future Intel Xeon processor
+// AVX512 Byte & Word, Intel Xeon processor codename "Skylake"
" avx512bw"
#endif
#ifdef __AVX512ER__
@@ -94,9 +98,17 @@ const char msg2[] = "==Qt=magic=Qt== Sub-architecture:"
" avx512pf"
#endif
#ifdef __AVX512VL__
-// AVX512 Vector Length, future Intel Xeon processor
+// AVX512 Vector Length, Intel Xeon processor codename "Skylake"
" avx512vl"
#endif
+#ifdef __AVX512IFMA__
+// AVX512 Integer Fused Multiply-Add, Intel processor codename "Cannonlake"
+" avx512ifma"
+#endif
+#ifdef __AVX512VBMI__
+// AVX512 Vector Byte Manipulation Instructions, Intel processor codename "Cannonlake"
+" avx512vbmi"
+#endif
#ifdef __BMI__
// Bit Manipulation Instructions 1, Intel Core 4th Generation ("Haswell"), AMD "Bulldozer 2"
" bmi"
@@ -143,6 +155,10 @@ const char msg2[] = "==Qt=magic=Qt== Sub-architecture:"
// Move Big Endian, Intel Atom & "Haswell"
" movbe"
#endif
+#ifdef __MPX__
+// Memory Protection Extensions, Intel Core processor codename "Skylake"
+" mpx"
+#endif
#ifdef __NO_SAHF__
// missing SAHF instruction in 64-bit, up to Intel Pentium 4 64-bit ("Nocona"), AMD Athlon FX
// Note: the macro is not defined, so this will never show up
@@ -156,10 +172,26 @@ const char msg2[] = "==Qt=magic=Qt== Sub-architecture:"
// Population Count (count of set bits), Intel Core-i7 second generation ("Sandy Bridge")
" popcnt"
#endif
+#ifdef __PREFETCHWT1__
+// Prefetch data for writing with T1 hint, Intel processor TBA
+" prefetchwt1"
+#endif
+#ifdef __PRFCHW__
+// Prefetch data for writing, Intel Core 5th Generation ("Broadwell")
+" prfchw"
+#endif
#ifdef __RDRND__
// Random number generator, Intel Core 3rd Generation ("Ivy Bridge")
" rdrnd"
#endif
+#ifdef __RDSEED__
+// Random number generator, Intel Core 5th Generation ("Broadwell")
+" rdseed"
+#endif
+#ifdef __RTM__
+// Restricted Transactional Memory, Intel Core 4th Generation ("Haswell")
+" rtm"
+#endif
#ifdef __SHA__
// SHA-1 and SHA-256 instructions, Intel processor TBA
" sha"
diff --git a/config.tests/common/c++11/c++11.cpp b/config.tests/common/c++11/c++11.cpp
index 30934951d7..04a83390af 100644
--- a/config.tests/common/c++11/c++11.cpp
+++ b/config.tests/common/c++11/c++11.cpp
@@ -38,12 +38,6 @@
#endif
#include <utility>
-#if defined(__clang__)
-# if __has_feature(cxx_generalized_initializers)
-// On OS X, the libstdc++ headers don't include <initializer_list>
-// This #include here forces a failure unless we're using libc++
-# include <initializer_list>
-# endif
-#endif
+#include <initializer_list>
-int main(int, char **) { return 0; }
+int main(int, char **) { return std::move(0); }
diff --git a/config.tests/common/c++default/c++default.cpp b/config.tests/common/c++default/c++default.cpp
new file mode 100644
index 0000000000..018963beb3
--- /dev/null
+++ b/config.tests/common/c++default/c++default.cpp
@@ -0,0 +1 @@
+__cplusplus
diff --git a/config.tests/common/c++default/c++default.pro b/config.tests/common/c++default/c++default.pro
new file mode 100644
index 0000000000..7e6bcefe69
--- /dev/null
+++ b/config.tests/common/c++default/c++default.pro
@@ -0,0 +1,14 @@
+TEMPLATE = aux
+CONFIG -= qt c++11
+PREPROCESSOR_SOURCES += c++default.cpp
+
+preprocessor.commands = $(CXX) $(CXXFLAGS) $(INCPATH) -o $@ -E $<
+msvc:preprocessor.commands = $(CXX) $(CXXFLAGS) $(INCPATH) -E ${QMAKE_FILE_IN} > ${QMAKE_FILE_OUT}
+preprocessor.output = ${QMAKE_FILE_BASE}.ii
+preprocessor.input = PREPROCESSOR_SOURCES
+preprocessor.variable_out = GENERATED_FILES
+QMAKE_EXTRA_COMPILERS += preprocessor
+
+all.target = all
+all.depends += c++default.ii
+QMAKE_EXTRA_TARGETS += all
diff --git a/config.tests/qpa/mirclient/mirclient.cpp b/config.tests/qpa/mirclient/mirclient.cpp
new file mode 100644
index 0000000000..c7148e82f9
--- /dev/null
+++ b/config.tests/qpa/mirclient/mirclient.cpp
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the config.tests of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <mir_toolkit/mir_client_library.h>
+#include <ubuntu/application/lifecycle_delegate.h>
+#include <EGL/egl.h>
+
+static void surfaceCreateCallback(MirSurface*, void*)
+{
+}
+
+
+int main(int, char **)
+{
+ u_application_lifecycle_delegate_new();
+ mir_surface_create(0, surfaceCreateCallback, 0);
+}
diff --git a/config.tests/qpa/mirclient/mirclient.pro b/config.tests/qpa/mirclient/mirclient.pro
new file mode 100644
index 0000000000..b397c2d08a
--- /dev/null
+++ b/config.tests/qpa/mirclient/mirclient.pro
@@ -0,0 +1,4 @@
+SOURCES = mirclient.cpp
+CONFIG += link_pkgconfig
+PKGCONFIG += egl mirclient ubuntu-platform-api
+CONFIG -= qt
diff --git a/config.tests/unix/cloexec/cloexec.cpp b/config.tests/unix/cloexec/cloexec.cpp
new file mode 100644
index 0000000000..3f127d8d3f
--- /dev/null
+++ b/config.tests/unix/cloexec/cloexec.cpp
@@ -0,0 +1,49 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the configuration module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#define _GNU_SOURCE 1
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+int main()
+{
+ int pipes[2];
+ (void) pipe2(pipes, O_CLOEXEC | O_NONBLOCK);
+ (void) fcntl(0, F_DUPFD_CLOEXEC, 0);
+ (void) dup3(0, 3, O_CLOEXEC);
+ (void) accept4(0, 0, 0, SOCK_CLOEXEC | SOCK_NONBLOCK);
+ return 0;
+}
diff --git a/config.tests/unix/cloexec/cloexec.pro b/config.tests/unix/cloexec/cloexec.pro
new file mode 100644
index 0000000000..bc735f9b1f
--- /dev/null
+++ b/config.tests/unix/cloexec/cloexec.pro
@@ -0,0 +1,3 @@
+SOURCES = cloexec.cpp
+CONFIG -= qt
+QT =
diff --git a/config.tests/unix/freetype/freetype.pri b/config.tests/unix/freetype/freetype.pri
index be2fc33265..05299ed2fd 100644
--- a/config.tests/unix/freetype/freetype.pri
+++ b/config.tests/unix/freetype/freetype.pri
@@ -2,6 +2,7 @@
TRY_INCLUDEPATHS = /include /usr/include $$QMAKE_INCDIR $$QMAKE_INCDIR_X11 $$INCLUDEPATH
# LSB doesn't allow using headers from /include or /usr/include
linux-lsb-g++:TRY_INCLUDEPATHS = $$QMAKE_INCDIR $$QMAKE_INCDIR_X11 $$INCLUDEPATH
+ haiku:TRY_INCLUDEPATHS += /system/develop/headers
for(p, TRY_INCLUDEPATHS) {
p = $$join(p, "", "", "/freetype2")
exists($$p):INCLUDEPATH *= $$p
diff --git a/config.tests/unix/ptrsize.test b/config.tests/unix/ptrsize.test
index 4f42c6d11d..7d7bde57e5 100755
--- a/config.tests/unix/ptrsize.test
+++ b/config.tests/unix/ptrsize.test
@@ -5,12 +5,15 @@ VERBOSE=$2
SRCDIR=$3
OUTDIR=$4
+LFLAGS=$SYSROOT_FLAG
+CXXFLAGS=$SYSROOT_FLAG
+
# debuggery
[ "$VERBOSE" = "yes" ] && echo "Testing size of pointers ... ($*)"
# build and run a test program
test -d "$OUTDIR/config.tests/unix/ptrsize" || mkdir -p "$OUTDIR/config.tests/unix/ptrsize"
-"$OUTDIR/bin/qmake" -nocache -spec "$QMKSPEC" "CONFIG-=app_bundle" "$SRCDIR/config.tests/unix/ptrsize/ptrsizetest.pro" -o "$OUTDIR/config.tests/unix/ptrsize/Makefile" >/dev/null 2>&1
+"$OUTDIR/bin/qmake" -nocache -spec "$QMKSPEC" "CONFIG-=app_bundle" "QMAKE_LFLAGS*=$LFLAGS" "QMAKE_CXXFLAGS*=$CXXFLAGS" "$SRCDIR/config.tests/unix/ptrsize/ptrsizetest.pro" -o "$OUTDIR/config.tests/unix/ptrsize/Makefile" >/dev/null 2>&1
cd "$OUTDIR/config.tests/unix/ptrsize"
if [ "$VERBOSE" = "yes" ]; then
diff --git a/config.tests/unix/syslog/syslog.c b/config.tests/unix/syslog/syslog.c
new file mode 100644
index 0000000000..01e4bbaf8c
--- /dev/null
+++ b/config.tests/unix/syslog/syslog.c
@@ -0,0 +1,42 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Tasuku Suzuki <stasuku@gmail.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the config.tests of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <syslog.h>
+
+int main(int argc, char **argv)
+{
+ openlog("qt", 0, LOG_USER);
+ syslog(LOG_INFO, "configure");
+ closelog();
+ return 0;
+}
diff --git a/config.tests/unix/syslog/syslog.pro b/config.tests/unix/syslog/syslog.pro
new file mode 100644
index 0000000000..abe8cc9cd7
--- /dev/null
+++ b/config.tests/unix/syslog/syslog.pro
@@ -0,0 +1,3 @@
+SOURCES = syslog.c
+
+CONFIG -= qt
diff --git a/config.tests/win/directwrite/directwrite.cpp b/config.tests/win/directwrite/directwrite.cpp
new file mode 100644
index 0000000000..01bea19faf
--- /dev/null
+++ b/config.tests/win/directwrite/directwrite.cpp
@@ -0,0 +1,44 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the config.tests of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <dwrite.h>
+#include <d2d1.h>
+
+int main(int, char**)
+{
+ IDWriteFactory *factory = 0;
+ DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
+ __uuidof(IDWriteFactory),
+ reinterpret_cast<IUnknown **>(&factory));
+ return 0;
+}
diff --git a/config.tests/win/directwrite/directwrite.pro b/config.tests/win/directwrite/directwrite.pro
new file mode 100644
index 0000000000..9a4612ca11
--- /dev/null
+++ b/config.tests/win/directwrite/directwrite.pro
@@ -0,0 +1,4 @@
+SOURCES = directwrite.cpp
+LIBS += -ldwrite
+CONFIG -= qt
+CONFIG += console
diff --git a/configure b/configure
index cea62fbc0c..afe741c303 100755
--- a/configure
+++ b/configure
@@ -621,6 +621,7 @@ CFG_XFIXES=runtime
CFG_ZLIB=auto
CFG_MTDEV=auto
CFG_JOURNALD=no
+CFG_SYSLOG=no
CFG_SQLITE=qt
CFG_GIF=auto
CFG_PNG=yes
@@ -688,6 +689,7 @@ CFG_EGLFS_VIV=no
CFG_DIRECTFB=auto
CFG_LINUXFB=auto
CFG_KMS=auto
+CFG_MIRCLIENT=auto
CFG_LIBUDEV=auto
CFG_LIBINPUT=auto
CFG_OBSOLETE_WAYLAND=no
@@ -728,6 +730,7 @@ CFG_IPV6IFNAME=auto
CFG_GETIFADDRS=auto
CFG_INOTIFY=auto
CFG_EVENTFD=auto
+CFG_CLOEXEC=no
CFG_RPATH=yes
CFG_FRAMEWORK=auto
CFG_USE_GOLD_LINKER=auto
@@ -1155,7 +1158,7 @@ while [ "$#" -gt 0 ]; do
fi
;;
force-pkg-config)
- CFG_PKGCONFIG="force"
+ CFG_PKGCONFIG="yes"
;;
docdir)
QT_INSTALL_DOCS="$VAL"
@@ -1699,6 +1702,13 @@ while [ "$#" -gt 0 ]; do
UNKNOWN_OPT=yes
fi
;;
+ syslog)
+ if [ "$VAL" = "yes" ] || [ "$VAL" = "no" ]; then
+ CFG_SYSLOG="$VAL"
+ else
+ UNKNOWN_OPT=yes
+ fi
+ ;;
sqlite)
if [ "$VAL" = "system" ]; then
CFG_SQLITE=system
@@ -1841,6 +1851,13 @@ while [ "$#" -gt 0 ]; do
UNKNOWN_OPT=yes
fi
;;
+ mirclient)
+ if [ "$VAL" = "yes" ] || [ "$VAL" = "no" ]; then
+ CFG_MIRCLIENT="$VAL"
+ else
+ UNKNOWN_OPT=yes
+ fi
+ ;;
libudev)
if [ "$VAL" = "yes" ] || [ "$VAL" = "no" ]; then
CFG_LIBUDEV="$VAL"
@@ -2471,6 +2488,9 @@ Third Party Libraries:
+ -no-journald ........ Do not send logging output to journald.
-journald ........... Send logging output to journald.
+ + -no-syslog .......... Do not send logging output to syslog.
+ -syslog ............. Send logging output to syslog.
+
-no-gif ............. Do not compile GIF reading support.
-no-libpng .......... Do not compile PNG support.
@@ -2629,14 +2649,17 @@ Additional options:
-no-eglfs .......... Do not compile EGLFS (EGL Full Screen/Single Surface) support.
* -eglfs ............. Compile EGLFS support.
+ -no-kms ............ Do not compile EGLFS KMS backend.
+ * -kms ............... Compile EGLFS KMS backend.
+
-no-directfb ....... Do not compile DirectFB support.
* -directfb .......... Compile DirectFB support.
-no-linuxfb ........ Do not compile Linux Framebuffer support.
* -linuxfb ........... Compile Linux Framebuffer support.
- -no-kms ............ Do not compile KMS support.
- * -kms ............... Compile KMS support (Requires EGL).
+ * -no-mirclient....... Do not compile Mir client support.
+ -mirclient.......... Compile Mir client support.
-qpa <name> ......... Sets the default QPA platform (e.g xcb, cocoa, windows).
@@ -2700,7 +2723,10 @@ MacOS/iOS options:
link tools against those frameworks.
-no-framework ...... Do not build Qt as a series of frameworks.
- -securetransport ... Use SecureTransport instead of OpenSSL (requires -no-openssl)
+ * -securetransport ... Use SecureTransport instead of OpenSSL
+
+ -no-securetransport Do not use SecureTransport, either use OpenSSL or do not use any SSL backend
+ at all (if combined with -no-openssl).
-sdk <sdk> ......... Build Qt using Apple provided SDK <sdk>. The argument should be
one of the available SDKs as listed by 'xcodebuild -showsdks'.
@@ -3610,9 +3636,6 @@ if [ -z "$QT_INSTALL_PREFIX" ]; then
else
QT_INSTALL_PREFIX="/usr/local/Qt-${QT_VERSION}" # the default install prefix is /usr/local/Qt-$QT_VERSION
fi
- HAVE_INSTALL_PATH=false
-else
- HAVE_INSTALL_PATH=true
fi
QT_INSTALL_PREFIX=`makeabs "$QT_INSTALL_PREFIX"`
@@ -4139,11 +4162,6 @@ fi
if [ "$CFG_PKGCONFIG" = "no" ]; then
PKG_CONFIG=
[ "$OPT_VERBOSE" = "yes" ] && echo "pkg-config support disabled."
-elif [ "$CFG_PKGCONFIG" = "force" ]; then
- echo >&2 ""
- echo >&2 "You have asked to use pkg-config. Please make sure you have"
- echo >&2 "a correctly setup pkg-config environment!"
- echo >&2 ""
elif [ -n "$PKG_CONFIG" ]; then
# found a pkg-config
if [ "$QT_CROSS_COMPILE" = "yes" ]; then
@@ -4156,16 +4174,13 @@ elif [ -n "$PKG_CONFIG" ]; then
fi
export PKG_CONFIG_LIBDIR
echo >&2 "Note: PKG_CONFIG_LIBDIR automatically set to $PKG_CONFIG_LIBDIR"
- elif [ "$CFG_PKGCONFIG" = "yes" ]; then
- echo >&2 "Error: PKG_CONFIG_LIBDIR has not been set. This could mean"
- echo >&2 "the host's .pc files will be used (even if you set PKG_CONFIG_PATH)."
+ elif [ "$CFG_PKGCONFIG" = "auto" ]; then
+ PKG_CONFIG=
+ echo >&2 "Warning: Disabling pkg-config since PKG_CONFIG_LIBDIR is not set and"
+ echo >&2 "the host's .pc files would be used (even if you set PKG_CONFIG_PATH)."
echo >&2 "Set this variable to the directory that contains target .pc files"
echo >&2 "for pkg-config to function correctly when cross-compiling or"
- echo >&2 "use -force-pkg-config to override this test."
- exit 101
- else
- PKG_CONFIG=
- echo >&2 "Warning: Disabling pkg-config since PKG_CONFIG_LIBDIR is not set."
+ echo >&2 "use -pkg-config to override this test."
fi
fi
if [ -z "$PKG_CONFIG_SYSROOT_DIR" ]; then
@@ -4173,17 +4188,19 @@ elif [ -n "$PKG_CONFIG" ]; then
PKG_CONFIG_SYSROOT_DIR=$CFG_SYSROOT
export PKG_CONFIG_SYSROOT_DIR
echo >&2 "Note: PKG_CONFIG_SYSROOT_DIR automatically set to $PKG_CONFIG_SYSROOT_DIR"
- elif [ "$CFG_PKGCONFIG" = "yes" ]; then
- echo >&2 "Error: PKG_CONFIG_SYSROOT_DIR has not been set. Set this variable"
- echo >&2 "to your sysroot for pkg-config to function correctly when cross-compiling"
- echo >&2 "or use -force-pkg-config to override this test."
- exit 101
- else
+ elif [ "$CFG_PKGCONFIG" = "auto" ]; then
PKG_CONFIG=
echo >&2 "Warning: Disabling pkg-config since PKG_CONFIG_SYSROOT_DIR is not set."
+ echo >&2 "Set this variable to your sysroot for pkg-config to function correctly when"
+ echo >&2 "cross-compiling or use -pkg-config to override this test."
fi
fi
fi
+ if [ -n "$PKG_CONFIG" ]; then
+ CFG_PKGCONFIG=yes
+ else
+ CFG_PKGCONFIG=no
+ fi
elif [ "$CFG_PKGCONFIG" = "yes" ]; then
echo >&2 "Could not detect pkg-config from mkspec or PATH."
exit 101
@@ -4326,6 +4343,21 @@ if [ "$CFG_CXX11" != "no" ]; then
fi
fi
+# Detect which edition of the C++ standard the compiler defaults to
+CFG_STDCXX_DEFAULT=199711
+if compileTest common/c++default "default C++ standard edition"; then
+ if [ -e "$outpath/config.tests/common/c++default/c++default.ii" ]; then
+ CFG_STDCXX_DEFAULT=`sed -n '/^[0-9]/s/L//p' "$outpath/config.tests/common/c++default/c++default.ii"`
+ else
+ if [ "$OPT_VERBOSE" = "yes" ]; then
+ echo "Failed to run the preprocessor, something is wrong with your compiler"
+ fi
+ if [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
+ exit 101
+ fi
+ fi
+fi
+
# detect sse2 support
if [ "${CFG_SSE2}" = "auto" ]; then
if compileTest common/sse2 "sse2"; then
@@ -4562,6 +4594,23 @@ if [ "$CFG_JOURNALD" != "no" ]; then
fi
fi
+if [ "$CFG_SYSLOG" != "no" ]; then
+ if compileTest unix/syslog "syslog"; then
+ CFG_SYSLOG=yes
+ QMAKE_CONFIG="$QMAKE_CONFIG syslog"
+ else
+ if [ "$CFG_SYSLOG" != "auto" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
+ echo "syslog support cannot be enabled due to functionality tests!"
+ echo " Turn on verbose messaging (-v) to $0 to see the final report."
+ echo " If you believe this message is in error you may use the continue"
+ echo " switch (-continue) to $0 to continue."
+ exit 101
+ else
+ CFG_SYSLOG=no
+ fi
+ fi
+fi
+
if [ "$CFG_LARGEFILE" = "auto" ]; then
#Large files should be enabled for all Linux systems
CFG_LARGEFILE=yes
@@ -4955,7 +5004,7 @@ if [ "$CFG_DBUS" = "linked" ]; then
else
if [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "The Qt D-Bus module cannot be enabled because libdbus-1 version $MIN_DBUS_1_VERSION was not found."
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -4995,7 +5044,7 @@ if [ "$CFG_GLIB" != "no" ]; then
else
if [ "$CFG_GLIB" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "Glib support cannot be enabled due to functionality tests!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -5023,7 +5072,7 @@ if [ "$CFG_GLIB" = "yes" -a "$CFG_QGTKSTYLE" != "no" ]; then
else
if [ "$CFG_QGTKSTYLE" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "GTK theme support cannot be enabled due to functionality tests!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the fin al report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -5068,7 +5117,7 @@ if [ "$CFG_PULSEAUDIO" != "no" ]; then
else
if [ "$CFG_PULSEAUDIO" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "PulseAudio support cannot be enabled due to functionality tests!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -5186,7 +5235,7 @@ elif [ "$CFG_OPENGL" = "es2" ]; then
compileTestWithPkgConfig glesv2 unix/opengles2 "OpenGL ES 2.0" OPENGL_ES2
if [ $? != "0" ]; then
echo "The OpenGL ES 2.0 functionality test failed!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " You might need to modify the include and library search paths by editing"
echo " QMAKE_INCDIR_OPENGL_ES2, QMAKE_LIBDIR_OPENGL_ES2 and QMAKE_LIBS_OPENGL_ES2 in"
echo " ${XQMAKESPEC}."
@@ -5246,6 +5295,7 @@ ORIG_CFG_EGLFS="$CFG_EGLFS"
ORIG_CFG_DIRECTFB="$CFG_DIRECTFB"
ORIG_CFG_LINUXFB="$CFG_LINUXFB"
ORIG_CFG_KMS="$CFG_KMS"
+ORIG_CFG_MIRCLIENT="$CFG_MIRCLIENT"
if [ "$CFG_LIBUDEV" != "no" ]; then
if [ -n "$PKG_CONFIG" ] && $PKG_CONFIG --exists libudev 2>/dev/null; then
@@ -5260,7 +5310,7 @@ if [ "$CFG_LIBUDEV" != "no" ]; then
QT_CONFIG="$QT_CONFIG libudev"
elif [ "$CFG_LIBUDEV" = "yes" ]; then
echo "The libudev functionality test failed!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
exit 1
else
CFG_LIBUDEV=no
@@ -5470,7 +5520,7 @@ if [ "$CFG_XCB" != "no" ]; then
else
if [ "$CFG_XCB" != "auto" ]; then
echo "The test for linking against libxcb failed!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " You might need to install dependency packages for libxcb."
echo " See src/plugins/platforms/xcb/README."
exit 1
@@ -5487,7 +5537,7 @@ if [ "$CFG_DIRECTFB" != "no" ]; then
CFG_DIRECTFB=yes
elif [ "$CFG_DIRECTFB" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo " DirectFB support cannot be enabled due to functionality tests!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -5528,6 +5578,20 @@ if [ "$CFG_KMS" != "no" ]; then
fi
fi
+if [ "$CFG_MIRCLIENT" != "no" ]; then
+ if compileTest qpa/mirclient "Mir client"; then
+ CFG_MIRCLIENT=yes
+ elif [ "$CFG_MIRCLIENT" = "yes" ]; then
+ echo " Mir client support cannot be enabled due to functionality tests!"
+ echo " Turn on verbose messaging (-v) to $0 to see the final report."
+ echo " If you believe this message is in error you may use the continue"
+ echo " switch (-continue) to $0 to continue."
+ exit 101
+ else
+ CFG_MIRCLIENT=no
+ fi
+fi
+
# Detect libxkbcommon
MIN_REQ_XKBCOMMON="0.4.1"
# currently only xcb platform plugin supports building xkbcommon
@@ -5544,7 +5608,7 @@ if [ "$CFG_XCB" != "no" ]; then
elif [ "$CFG_XKBCOMMON" = "system" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo " xkbcommon support cannot be enabled because either xkbcommon or "
echo " xkbcommon-x11 >= $MIN_REQ_XKBCOMMON was not found via pkg-config!"
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
@@ -5605,7 +5669,7 @@ if [ "$CFG_EGL" != "no" ]; then
fi
elif [ "$CFG_EGL" = "yes" ]; then
echo " The EGL functionality test failed; EGL is required by some QPA plugins to manage contexts & surfaces."
- [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -force-pkg-config?"
+ [ -z "$PKG_CONFIG" ] && echo " Use of pkg-config is not enabled, maybe you want to pass -pkg-config?"
echo " You might need to modify the include and library search paths by editing"
echo " QMAKE_INCDIR_EGL, QMAKE_LIBDIR_EGL and QMAKE_LIBS_EGL in ${XQMAKESPEC}."
exit 1
@@ -5698,11 +5762,14 @@ fi
if [ "$CFG_KMS" = "yes" ]; then
QT_CONFIG="$QT_CONFIG kms"
fi
+if [ "$CFG_MIRCLIENT" = "yes" ]; then
+ QT_CONFIG="$QT_CONFIG mirclient"
+fi
if [ "$XPLATFORM_MAC" = "no" ] && [ "$XPLATFORM_MINGW" = "no" ] && [ "$XPLATFORM_QNX" = "no" ] && [ "$XPLATFORM_ANDROID" = "no" ] && [ "$XPLATFORM_HAIKU" = "no" ]; then
- if [ "$CFG_XCB" = "no" ] && [ "$CFG_EGLFS" = "no" ] && [ "$CFG_DIRECTFB" = "no" ] && [ "$CFG_LINUXFB" = "no" ] && [ "$CFG_KMS" = "no" ]; then
+ if [ "$CFG_XCB" = "no" ] && [ "$CFG_EGLFS" = "no" ] && [ "$CFG_DIRECTFB" = "no" ] && [ "$CFG_LINUXFB" = "no" ] && [ "$CFG_KMS" = "no" ] && [ "$CFG_MIRCLIENT" = "no" ]; then
if [ "$QPA_PLATFORM_GUARD" = "yes" ] &&
- ( [ "$ORIG_CFG_XCB" = "auto" ] || [ "$ORIG_CFG_EGLFS" = "auto" ] || [ "$ORIG_CFG_DIRECTFB" = "auto" ] || [ "$ORIG_CFG_LINUXFB" = "auto" ] || [ "$ORIG_CFG_KMS" = "auto" ] ); then
+ ( [ "$ORIG_CFG_XCB" = "auto" ] || [ "$ORIG_CFG_EGLFS" = "auto" ] || [ "$ORIG_CFG_DIRECTFB" = "auto" ] || [ "$ORIG_CFG_LINUXFB" = "auto" ] || [ "$ORIG_CFG_KMS" = "auto" ] || [ "$ORIG_CFG_MIRCLIENT" = "auto" ] ); then
echo "No QPA platform plugin enabled!"
echo " If you really want to build without a QPA platform plugin you must pass"
echo " -no-qpa-platform-guard to configure. Doing this will"
@@ -5875,6 +5942,18 @@ if [ "$CFG_GETIFADDRS" != "no" ]; then
fi
fi
+# find if the platform provides thread-safe CLOEXEC support
+if compileTest unix/cloexec "cloexec"; then
+ CFG_CLOEXEC=yes
+fi
+
+if [ "$XPLATFORM_MAC" = "yes" ] && [ "$CFG_SECURETRANSPORT" != "no" ] && ([ "$CFG_OPENSSL" = "no" ] || [ "$CFG_OPENSSL" = "auto" ]); then
+ CFG_SECURETRANSPORT=yes
+ CFG_OPENSSL=no
+else
+ CFG_SECURETRANSPORT=no
+fi
+
# detect OpenSSL
if [ "$CFG_OPENSSL" != "no" ]; then
if compileTest unix/openssl "OpenSSL"; then
@@ -5894,11 +5973,6 @@ if [ "$CFG_OPENSSL" != "no" ]; then
fi
fi
-if [ "$CFG_SECURETRANSPORT" != "no" ] && [ "$CFG_OPENSSL" = "no" ] && [ "$XPLATFORM_MAC" = "yes" ]; then
- CFG_SECURETRANSPORT=yes
-else
- CFG_SECURETRANSPORT=no
-fi
# detect PCRE
if [ "$CFG_PCRE" != "qt" ]; then
@@ -6153,6 +6227,9 @@ fi
if [ "$CFG_EVENTFD" = "yes" ]; then
QT_CONFIG="$QT_CONFIG eventfd"
fi
+if [ "$CFG_CLOEXEC" = "yes" ]; then
+ QT_CONFIG="$QT_CONFIG threadsafe-cloexec"
+fi
if [ "$CFG_LIBJPEG" = "no" ]; then
CFG_JPEG="no"
elif [ "$CFG_LIBJPEG" = "system" ]; then
@@ -6466,7 +6543,7 @@ fi
# ### Vestige
if [ "$CFG_QML_DEBUG" = "no" ]; then
- QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_QML_DEBUGGER"
+ QT_CONFIG="$QT_CONFIG no-qml-debug"
fi
case "$QMAKE_CONF_COMPILER" in
@@ -6633,6 +6710,7 @@ QMakeVar set sql-plugins "$SQL_PLUGINS"
[ "$CFG_GETIFADDRS" = "no" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_GETIFADDRS"
[ "$CFG_INOTIFY" = "no" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_INOTIFY"
[ "$CFG_EVENTFD" = "no" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_EVENTFD"
+[ "$CFG_CLOEXEC" = "yes" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_THREADSAFE_CLOEXEC=1"
[ "$CFG_NIS" = "no" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_NIS"
[ "$CFG_OPENSSL" = "no" ] && QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_OPENSSL"
[ "$CFG_OPENSSL" = "linked" ]&& QCONFIG_FLAGS="$QCONFIG_FLAGS QT_LINKED_OPENSSL"
@@ -6831,6 +6909,7 @@ fi
if [ -n "$RPATH_FLAGS" ]; then
echo "QMAKE_RPATHDIR += $RPATH_FLAGS" >> "$QTCONFIG.tmp"
fi
+echo "QT_COMPILER_STDCXX = $CFG_STDCXX_DEFAULT" >> "$QTCONFIG.tmp"
if [ -n "$QT_GCC_MAJOR_VERSION" ]; then
echo "QT_GCC_MAJOR_VERSION = $QT_GCC_MAJOR_VERSION" >> "$QTCONFIG.tmp"
echo "QT_GCC_MINOR_VERSION = $QT_GCC_MINOR_VERSION" >> "$QTCONFIG.tmp"
@@ -7074,8 +7153,10 @@ report_support " Image formats:"
report_support_plugin " GIF .................." "$CFG_GIF" qt QtGui
report_support_plugin " JPEG ................." "$CFG_JPEG" "$CFG_LIBJPEG" QtGui
report_support_plugin " PNG .................." "$CFG_PNG" "$CFG_LIBPNG" QtGui
-report_support " journald ..............." "$CFG_JOURNALD"
report_support " libinput................" "$CFG_LIBINPUT"
+report_support " Logging backends:"
+report_support " journald ..............." "$CFG_JOURNALD"
+report_support " syslog ..............." "$CFG_SYSLOG"
report_support " mtdev .................." "$CFG_MTDEV" yes "system library"
report_support " Networking:"
[ "$XPLATFORM_MAC" = "yes" ] && \
@@ -7108,6 +7189,7 @@ report_support " EGLFS Mali ........." "$CFG_EGLFS_MALI"
report_support " EGLFS Raspberry Pi ." "$CFG_EGLFS_BRCM"
report_support " EGLFS X11 .........." "$CFG_EGL_X"
report_support " LinuxFB .............." "$CFG_LINUXFB"
+report_support " Mir client............" "$CFG_MIRCLIENT"
report_support " XCB .................." "$CFG_XCB" system "system library" qt "bundled copy"
if [ "$CFG_XCB" != "no" ]; then
report_support " EGL on X ..........." "$CFG_EGL_X"
@@ -7165,12 +7247,12 @@ if [ "$CFG_OPENSSL" = "linked" ] && [ "$OPENSSL_LIBS" = "" ]; then
echo "For example:"
echo " OPENSSL_LIBS='-L/opt/ssl/lib -lssl -lcrypto' ./configure -openssl-linked"
fi
-if [ "$CFG_JOURNALD" = "yes" ] || [ "$CFG_SLOG2" = "yes" ]; then
+if [ "$CFG_JOURNALD" = "yes" ] || [ "$CFG_SYSLOG" = "yes" ] || [ "$CFG_SLOG2" = "yes" ]; then
echo
- echo "NOTE: journald or slog2 integration is enabled."
+ echo "NOTE: journald, syslog or slog2 integration is enabled."
echo "If your users intend on developing applications against this build,"
echo "ensure that the IDEs they use either set QT_LOGGING_TO_CONSOLE to 1"
- echo "or the IDE is able to read the logged output from journald or slog2."
+ echo "or the IDE is able to read the logged output from journald, syslog or slog2."
fi
if [ "$CFG_XKBCOMMON" = "qt" ] && [ "$CFG_XKB_CONFIG_ROOT" = "not found" ]; then
echo
diff --git a/doc/global/html-header-online.qdocconf b/doc/global/html-header-online.qdocconf
index aa67c43947..450eb1120b 100644
--- a/doc/global/html-header-online.qdocconf
+++ b/doc/global/html-header-online.qdocconf
@@ -3,6 +3,7 @@
HTML.stylesheets = template/style/online.css \
template/style/gsc.css \
template/style/list_arrow.png \
+ template/style/list_expand.png \
template/style/icomoon.eot \
template/style/icomoon.svg \
template/style/icomoon.ttf \
@@ -15,6 +16,7 @@ HTML.stylesheets = template/style/online.css \
qhp.extraFiles += style/online.css \
style/gsc.css \
style/list_arrow.png \
+ style/list_expand.png \
style/icomoon.eot \
style/icomoon.svg \
style/icomoon.ttf \
diff --git a/doc/global/qt-cpp-defines.qdocconf b/doc/global/qt-cpp-defines.qdocconf
index 7cc9e0f317..8649a14582 100644
--- a/doc/global/qt-cpp-defines.qdocconf
+++ b/doc/global/qt-cpp-defines.qdocconf
@@ -37,6 +37,8 @@ Cpp.ignoretokens += \
Q_DECL_NOTHROW \
Q_DECL_PURE_FUNCTION \
Q_DECL_UNUSED \
+ Q_DECL_CF_RETURNS_RETAINED \
+ Q_DECL_NS_RETURNS_AUTORELEASED \
Q_DECLARATIVE_EXPORT \
Q_EXPLICIT \
Q_EXPORT \
@@ -66,6 +68,7 @@ Cpp.ignoretokens += \
Q_POSITIONING_EXPORT \
Q_MULTIMEDIA_EXPORT \
Q_NETWORK_EXPORT \
+ Q_NEVER_INLINE \
Q_NORETURN \
Q_OPENGL_EXPORT \
Q_OPENVG_EXPORT \
@@ -134,6 +137,7 @@ Cpp.ignoredirectives += \
Q_DECLARE_PRIVATE_D \
Q_DECLARE_PUBLIC \
Q_DECLARE_SHARED \
+ Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6 \
Q_DECLARE_TR_FUNCTIONS \
Q_DECLARE_TYPEINFO \
Q_DECL_NOEXCEPT_EXPR \
@@ -153,4 +157,5 @@ Cpp.ignoredirectives += \
QT_WARNING_DISABLE_GCC \
QT_WARNING_DISABLE_INTEL \
QT_WARNING_DISABLE_MSVC \
+ Q_ATTRIBUTE_FORMAT_PRINTF \
Q_MV_IOS
diff --git a/doc/global/template/scripts/extras.js b/doc/global/template/scripts/extras.js
index 8a623a037e..ba7a4a50fb 100644
--- a/doc/global/template/scripts/extras.js
+++ b/doc/global/template/scripts/extras.js
@@ -1,8 +1,25 @@
-var vOffset = 65;
+var vOffset_init = 65;
+var vOffset = vOffset_init;
+var c = 'collapsed';
+
+function toggleList(toggle, content, maxItems) {
+ if (toggle.css('display') == 'none') {
+ vOffset = vOffset_init;
+ toggle.removeClass(c);
+ content.show();
+ return;
+ } else
+ vOffset = 8;
+
+ if (maxItems > content.children().length)
+ return;
+ content.hide();
+ toggle.addClass(c);
+}
$(function () {
$('a[href*=#]:not([href=#])').on('click', function (e) {
- if (e.which == 2)
+ if (e.which == 2 || e.metaKey || e.ctrlKey || e.shiftKey)
return true;
var target = $(this.hash.replace(/(\.)/g, "\\$1"));
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
@@ -14,11 +31,50 @@ $(function () {
});
$(window).load(function () {
- var h = window.location.hash;
- var re = /[^a-z0-9_\.\#\-]/i
- if (h.length > 1 && !re.test(h)) {
- setTimeout(function () {
- $(window).scrollTop($(h.replace(/(\.)/g, "\\$1")).offset().top - vOffset);
- }, 0);
+ var hashChanged = function() {
+ var h = window.location.hash;
+ var re = /[^a-z0-9_\.\#\-]/i
+ if (h.length > 1 && !re.test(h)) {
+ setTimeout(function () {
+ var tgt = $(h.replace(/(\.)/g, "\\$1"));
+ tgt = tgt.length ? tgt : $('[name=' + h.slice(1) + ']');
+ $(window).scrollTop(tgt.offset().top - vOffset);
+ }, 0);
+ }
+ }
+ $(window).bind('hashchange', hashChanged);
+ hashChanged.call();
+
+ if (!$('.sidebar toc').is(':empty')) {
+ $('<div id="toc-toggle"></div>').prependTo('.sidebar .toc');
+ var toc = $('.sidebar .toc ul');
+ var tocToggle = $('#toc-toggle');
+ var tocCallback = function() { toggleList(tocToggle, toc, 4); };
+
+ $('#toc-toggle').on('click', function(e) {
+ e.stopPropagation();
+ toc.toggle();
+ tocToggle.toggleClass(c);
+ });
+
+ tocCallback.call();
+ $(window).resize(tocCallback);
+ }
+
+ if (!$('#sidebar-content').is(':empty')) {
+ $('#sidebar-content h2').first().clone().prependTo('#sidebar-content');
+ $('<div id="sidebar-toggle"></div>').prependTo('#sidebar-content');
+ var sb = $('#sidebar-content .sectionlist');
+ var sbToggle = $('#sidebar-toggle');
+ var sbCallback = function() { toggleList(sbToggle, sb, 0); };
+
+ $('#sidebar-toggle').on('click', function(e) {
+ e.stopPropagation();
+ sb.toggle();
+ sbToggle.toggleClass(c);
+ });
+
+ sbCallback.call();
+ $(window).resize(sbCallback);
}
});
diff --git a/doc/global/template/style/list_expand.png b/doc/global/template/style/list_expand.png
new file mode 100644
index 0000000000..d2145145fd
--- /dev/null
+++ b/doc/global/template/style/list_expand.png
Binary files differ
diff --git a/doc/global/template/style/online.css b/doc/global/template/style/online.css
index 8775719be6..cfd0da0f4b 100644
--- a/doc/global/template/style/online.css
+++ b/doc/global/template/style/online.css
@@ -525,6 +525,21 @@ body.qt-account #navbar .navbar-oneQt h2 {
position:absolute;
transition:none;
}
+#sidebar-toggle,#toc-toggle {
+ width:24px;
+ height:14px;
+ background-size:24px 28px;
+ cursor:pointer;
+ background-image:url("list_expand.png");
+ float:right
+}
+#sidebar-toggle.collapsed,
+#toc-toggle.collapsed {
+ background-position:bottom left
+}
+#sidebar-content > h2 {
+ display:none
+}
.cookies_yum .close:hover {
background-position:bottom left
}
@@ -1128,7 +1143,7 @@ dd {
.mainContent b {
font-weight:600
}
-.context ul {
+.context ul,.context ol {
margin-bottom:1.5em
}
.mainContent ul ul {
@@ -1282,6 +1297,9 @@ div.main_index .row:after {
div.table {
overflow-x:auto
}
+.context tr > td > pre {
+ font-size:0.85em
+}
p.qt_commercial {
border:3px solid #5caa15;
margin:0 auto;
@@ -1312,7 +1330,6 @@ pre {
line-height:1.5;
overflow-x:auto;
margin-bottom:25px;
- overflow-x:auto;
padding:25px;
margin-top:0.75em
}
@@ -1376,6 +1393,9 @@ pre:hover>.copy_text {
margin:0;
border:none
}
+#sidebar-toggle,#toc-toggle {
+ display:none
+}
@media (max-width: 980px) {
body {
font-size:calc-em(14px)
@@ -1413,7 +1433,8 @@ pre:hover>.copy_text {
visibility:hidden
}
.col-2 h2,.toc h3,.sidebar-content h2,.sidebar-content h3,.sectionlist h2 {
- text-align:center
+ text-align:center;
+ margin-bottom:0
}
div.main_index .row:after {
content:none
@@ -1438,6 +1459,12 @@ pre:hover>.copy_text {
margin-bottom:1em;
padding:20px
}
+ #sidebar-toggle,#toc-toggle {
+ display:block
+ }
+ #sidebar-toggle.collapsed + h2 {
+ display:block
+ }
.mainContent p {
line-height:1.56em;
margin-bottom:1em;
@@ -1446,6 +1473,9 @@ pre:hover>.copy_text {
table td,table th {
padding:5px 5px
}
+ .sectionlist {
+ padding:0
+ }
}
[id]:target,[name]:target,[name]:target+* {
-webkit-animation:highlighter 3s;
@@ -1453,22 +1483,22 @@ pre:hover>.copy_text {
}
@-webkit-keyframes highlighter {
25% {
- background-color:#46a2da;
- color:#fff
+ background-color:#d1e8f6;
+ color:#444
}
75% {
- background-color:#46a2da;
- color:#fff
+ background-color:#d1e8f6;
+ color:#444
}
}
@keyframes highlighter {
25% {
- background-color:#46a2da;
- color:#fff
+ background-color:#d1e8f6;
+ color:#444
}
75% {
- background-color:#46a2da;
- color:#fff
+ background-color:#d1e8f6;
+ color:#444
}
}
@-webkit-keyframes copypaste {
@@ -1580,7 +1610,7 @@ img.gsc-branding-img {
input.gsc-search-button {
background-color: white !important;
height: 35px !important;
- width: 35px !important;
+ width: 25px !important;
color: transparent !important;
background-image: url("doc_search.png") !important;
background-size: 25px auto;
diff --git a/doc/src/images/recentfiles-example.png b/doc/src/images/recentfiles-example.png
deleted file mode 100644
index 8a1f2e5509..0000000000
--- a/doc/src/images/recentfiles-example.png
+++ /dev/null
Binary files differ
diff --git a/examples/opengl/hellogl2/mainwindow.cpp b/examples/opengl/hellogl2/mainwindow.cpp
index 104cf24b37..b938300349 100644
--- a/examples/opengl/hellogl2/mainwindow.cpp
+++ b/examples/opengl/hellogl2/mainwindow.cpp
@@ -51,7 +51,7 @@ MainWindow::MainWindow()
QAction *addNew = new QAction(menuWindow);
addNew->setText(tr("Add new"));
menuWindow->addAction(addNew);
- connect(addNew, SIGNAL(triggered()), this, SLOT(onAddNew()));
+ connect(addNew, &QAction::triggered, this, &MainWindow::onAddNew);
setMenuBar(menuBar);
onAddNew();
diff --git a/examples/opengl/hellogl2/window.cpp b/examples/opengl/hellogl2/window.cpp
index e60de3b05b..11a5ae68a9 100644
--- a/examples/opengl/hellogl2/window.cpp
+++ b/examples/opengl/hellogl2/window.cpp
@@ -59,12 +59,12 @@ Window::Window(MainWindow *mw)
ySlider = createSlider();
zSlider = createSlider();
- connect(xSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setXRotation(int)));
- connect(glWidget, SIGNAL(xRotationChanged(int)), xSlider, SLOT(setValue(int)));
- connect(ySlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setYRotation(int)));
- connect(glWidget, SIGNAL(yRotationChanged(int)), ySlider, SLOT(setValue(int)));
- connect(zSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setZRotation(int)));
- connect(glWidget, SIGNAL(zRotationChanged(int)), zSlider, SLOT(setValue(int)));
+ connect(xSlider, &QSlider::valueChanged, glWidget, &GLWidget::setXRotation);
+ connect(glWidget, &GLWidget::xRotationChanged, xSlider, &QSlider::setValue);
+ connect(ySlider, &QSlider::valueChanged, glWidget, &GLWidget::setYRotation);
+ connect(glWidget, &GLWidget::yRotationChanged, ySlider, &QSlider::setValue);
+ connect(zSlider, &QSlider::valueChanged, glWidget, &GLWidget::setZRotation);
+ connect(glWidget, &GLWidget::zRotationChanged, zSlider, &QSlider::setValue);
QVBoxLayout *mainLayout = new QVBoxLayout;
QHBoxLayout *container = new QHBoxLayout;
@@ -77,7 +77,7 @@ Window::Window(MainWindow *mw)
w->setLayout(container);
mainLayout->addWidget(w);
dockBtn = new QPushButton(tr("Undock"), this);
- connect(dockBtn, SIGNAL(clicked()), this, SLOT(dockUndock()));
+ connect(dockBtn, &QPushButton::clicked, this, &Window::dockUndock);
mainLayout->addWidget(dockBtn);
setLayout(mainLayout);
diff --git a/examples/opengl/hellogles3/glwindow.cpp b/examples/opengl/hellogles3/glwindow.cpp
new file mode 100644
index 0000000000..ad654b854c
--- /dev/null
+++ b/examples/opengl/hellogles3/glwindow.cpp
@@ -0,0 +1,281 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "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 The Qt Company Ltd 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."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "glwindow.h"
+#include <QImage>
+#include <QOpenGLTexture>
+#include <QOpenGLShaderProgram>
+#include <QOpenGLBuffer>
+#include <QOpenGLContext>
+#include <QOpenGLVertexArrayObject>
+#include <QOpenGLExtraFunctions>
+#include <QPropertyAnimation>
+#include <QPauseAnimation>
+#include <QSequentialAnimationGroup>
+#include <QTimer>
+
+GLWindow::GLWindow()
+ : m_texture(0),
+ m_program(0),
+ m_vbo(0),
+ m_vao(0),
+ m_target(0, 0, -1),
+ m_uniformsDirty(true),
+ m_r(0),
+ m_r2(0)
+{
+ m_world.setToIdentity();
+ m_world.translate(0, 0, -1);
+ m_world.rotate(180, 1, 0, 0);
+
+ QSequentialAnimationGroup *animGroup = new QSequentialAnimationGroup(this);
+ animGroup->setLoopCount(-1);
+ QPropertyAnimation *zAnim0 = new QPropertyAnimation(this, QByteArrayLiteral("z"));
+ zAnim0->setStartValue(1.5f);
+ zAnim0->setEndValue(10.0f);
+ zAnim0->setDuration(2000);
+ animGroup->addAnimation(zAnim0);
+ QPropertyAnimation *zAnim1 = new QPropertyAnimation(this, QByteArrayLiteral("z"));
+ zAnim1->setStartValue(10.0f);
+ zAnim1->setEndValue(50.0f);
+ zAnim1->setDuration(4000);
+ zAnim1->setEasingCurve(QEasingCurve::OutElastic);
+ animGroup->addAnimation(zAnim1);
+ QPropertyAnimation *zAnim2 = new QPropertyAnimation(this, QByteArrayLiteral("z"));
+ zAnim2->setStartValue(50.0f);
+ zAnim2->setEndValue(1.5f);
+ zAnim2->setDuration(2000);
+ animGroup->addAnimation(zAnim2);
+ animGroup->start();
+
+ QPropertyAnimation* rAnim = new QPropertyAnimation(this, QByteArrayLiteral("r"));
+ rAnim->setStartValue(0.0f);
+ rAnim->setEndValue(360.0f);
+ rAnim->setDuration(2000);
+ rAnim->setLoopCount(-1);
+ rAnim->start();
+
+ QTimer::singleShot(4000, this, SLOT(startSecondStage()));
+}
+
+GLWindow::~GLWindow()
+{
+ makeCurrent();
+ delete m_texture;
+ delete m_program;
+ delete m_vbo;
+ delete m_vao;
+}
+
+void GLWindow::startSecondStage()
+{
+ QPropertyAnimation* r2Anim = new QPropertyAnimation(this, QByteArrayLiteral("r2"));
+ r2Anim->setStartValue(0.0f);
+ r2Anim->setEndValue(360.0f);
+ r2Anim->setDuration(20000);
+ r2Anim->setLoopCount(-1);
+ r2Anim->start();
+}
+
+void GLWindow::setZ(float v)
+{
+ m_eye.setZ(v);
+ m_uniformsDirty = true;
+ update();
+}
+
+void GLWindow::setR(float v)
+{
+ m_r = v;
+ m_uniformsDirty = true;
+ update();
+}
+
+void GLWindow::setR2(float v)
+{
+ m_r2 = v;
+ m_uniformsDirty = true;
+ update();
+}
+
+static const char *vertexShaderSource =
+ "layout(location = 0) in vec4 vertex;\n"
+ "layout(location = 1) in vec3 normal;\n"
+ "out vec3 vert;\n"
+ "out vec3 vertNormal;\n"
+ "out vec3 color;\n"
+ "uniform mat4 projMatrix;\n"
+ "uniform mat4 camMatrix;\n"
+ "uniform mat4 worldMatrix;\n"
+ "uniform mat4 myMatrix;\n"
+ "uniform sampler2D sampler;\n"
+ "void main() {\n"
+ " ivec2 pos = ivec2(gl_InstanceID % 32, gl_InstanceID / 32);\n"
+ " vec2 t = vec2(float(-16 + pos.x) * 0.8, float(-18 + pos.y) * 0.6);\n"
+ " float val = 2.0 * length(texelFetch(sampler, pos, 0).rgb);\n"
+ " mat4 wm = myMatrix * mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, val, 1) * worldMatrix;\n"
+ " color = texelFetch(sampler, pos, 0).rgb * vec3(0.4, 1.0, 0.0);\n"
+ " vert = vec3(wm * vertex);\n"
+ " vertNormal = mat3(transpose(inverse(wm))) * normal;\n"
+ " gl_Position = projMatrix * camMatrix * wm * vertex;\n"
+ "}\n";
+
+static const char *fragmentShaderSource =
+ "in highp vec3 vert;\n"
+ "in highp vec3 vertNormal;\n"
+ "in highp vec3 color;\n"
+ "out highp vec4 fragColor;\n"
+ "uniform highp vec3 lightPos;\n"
+ "void main() {\n"
+ " highp vec3 L = normalize(lightPos - vert);\n"
+ " highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
+ " highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
+ " fragColor = vec4(col, 1.0);\n"
+ "}\n";
+
+QByteArray versionedShaderCode(const char *src)
+{
+ QByteArray versionedSrc;
+
+ if (QOpenGLContext::currentContext()->isOpenGLES())
+ versionedSrc.append(QByteArrayLiteral("#version 300 es\n"));
+ else
+ versionedSrc.append(QByteArrayLiteral("#version 330\n"));
+
+ versionedSrc.append(src);
+ return versionedSrc;
+}
+
+void GLWindow::initializeGL()
+{
+ QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
+
+ if (m_texture) {
+ delete m_texture;
+ m_texture = 0;
+ }
+ QImage img(":/qtlogo.png");
+ Q_ASSERT(!img.isNull());
+ m_texture = new QOpenGLTexture(img.scaled(32, 36).mirrored());
+
+ if (m_program) {
+ delete m_program;
+ m_program = 0;
+ }
+ m_program = new QOpenGLShaderProgram;
+ // Prepend the correct version directive to the sources. The rest is the
+ // same, thanks to the common GLSL syntax.
+ m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, versionedShaderCode(vertexShaderSource));
+ m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, versionedShaderCode(fragmentShaderSource));
+ m_program->link();
+
+ m_projMatrixLoc = m_program->uniformLocation("projMatrix");
+ m_camMatrixLoc = m_program->uniformLocation("camMatrix");
+ m_worldMatrixLoc = m_program->uniformLocation("worldMatrix");
+ m_myMatrixLoc = m_program->uniformLocation("myMatrix");
+ m_lightPosLoc = m_program->uniformLocation("lightPos");
+
+ // Create a VAO. Not strictly required for ES 3, but it is for plain OpenGL.
+ if (m_vao) {
+ delete m_vao;
+ m_vao = 0;
+ }
+ m_vao = new QOpenGLVertexArrayObject;
+ if (m_vao->create())
+ m_vao->bind();
+
+ if (m_vbo) {
+ delete m_vbo;
+ m_vbo = 0;
+ }
+ m_program->bind();
+ m_vbo = new QOpenGLBuffer;
+ m_vbo->create();
+ m_vbo->bind();
+ m_vbo->allocate(m_logo.constData(), m_logo.count() * sizeof(GLfloat));
+ f->glEnableVertexAttribArray(0);
+ f->glEnableVertexAttribArray(1);
+ f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
+ f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<void *>(3 * sizeof(GLfloat)));
+ m_vbo->release();
+
+ f->glEnable(GL_DEPTH_TEST);
+ f->glEnable(GL_CULL_FACE);
+}
+
+void GLWindow::resizeGL(int w, int h)
+{
+ m_proj.setToIdentity();
+ m_proj.perspective(45.0f, GLfloat(w) / h, 0.01f, 100.0f);
+ m_uniformsDirty = true;
+}
+
+void GLWindow::paintGL()
+{
+ // Now use QOpenGLExtraFunctions instead of QOpenGLFunctions as we want to
+ // do more than what GL(ES) 2.0 offers.
+ QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions();
+
+ f->glClearColor(0, 0, 0, 1);
+ f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ m_program->bind();
+ m_texture->bind();
+
+ if (m_uniformsDirty) {
+ m_uniformsDirty = false;
+ QMatrix4x4 camera;
+ camera.lookAt(m_eye, m_eye + m_target, QVector3D(0, 1, 0));
+ m_program->setUniformValue(m_projMatrixLoc, m_proj);
+ m_program->setUniformValue(m_camMatrixLoc, camera);
+ QMatrix4x4 wm = m_world;
+ wm.rotate(m_r, 1, 1, 0);
+ m_program->setUniformValue(m_worldMatrixLoc, wm);
+ QMatrix4x4 mm;
+ mm.setToIdentity();
+ mm.rotate(-m_r2, 1, 0, 0);
+ m_program->setUniformValue(m_myMatrixLoc, mm);
+ m_program->setUniformValue(m_lightPosLoc, QVector3D(0, 0, 70));
+ }
+
+ // Now call a function introduced in OpenGL 3.1 / OpenGL ES 3.0. We
+ // requested a 3.3 or ES 3.0 context, so we know this will work.
+ f->glDrawArraysInstanced(GL_TRIANGLES, 0, m_logo.vertexCount(), 32 * 36);
+}
diff --git a/examples/widgets/mainwindows/recentfiles/mainwindow.h b/examples/opengl/hellogles3/glwindow.h
index 95252ca525..fe5d5383e9 100644
--- a/examples/widgets/mainwindows/recentfiles/mainwindow.h
+++ b/examples/opengl/hellogles3/glwindow.h
@@ -38,59 +38,61 @@
**
****************************************************************************/
-#ifndef MAINWINDOW_H
-#define MAINWINDOW_H
+#ifndef GLWIDGET_H
+#define GLWIDGET_H
-#include <QList>
-#include <QMainWindow>
+#include <QOpenGLWindow>
+#include <QMatrix4x4>
+#include <QVector3D>
+#include "../hellogl2/logo.h"
-QT_BEGIN_NAMESPACE
-class QAction;
-class QMenu;
-class QTextEdit;
-QT_END_NAMESPACE
+class QOpenGLTexture;
+class QOpenGLShaderProgram;
+class QOpenGLBuffer;
+class QOpenGLVertexArrayObject;
-class MainWindow : public QMainWindow
+class GLWindow : public QOpenGLWindow
{
Q_OBJECT
+ Q_PROPERTY(float z READ z WRITE setZ)
+ Q_PROPERTY(float r READ r WRITE setR)
+ Q_PROPERTY(float r2 READ r2 WRITE setR2)
public:
- MainWindow();
+ GLWindow();
+ ~GLWindow();
-private slots:
- void newFile();
- void open();
- void save();
- void saveAs();
- void openRecentFile();
- void about();
-
-private:
- void createActions();
- void createMenus();
- void loadFile(const QString &fileName);
- void saveFile(const QString &fileName);
- void setCurrentFile(const QString &fileName);
- void updateRecentFileActions();
- QString strippedName(const QString &fullFileName);
+ void initializeGL();
+ void resizeGL(int w, int h);
+ void paintGL();
- QString curFile;
+ float z() const { return m_eye.z(); }
+ void setZ(float v);
- QTextEdit *textEdit;
- QMenu *fileMenu;
- QMenu *recentFilesMenu;
- QMenu *helpMenu;
- QAction *newAct;
- QAction *openAct;
- QAction *saveAct;
- QAction *saveAsAct;
- QAction *exitAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
- QAction *separatorAct;
-
- enum { MaxRecentFiles = 5 };
- QAction *recentFileActs[MaxRecentFiles];
+ float r() const { return m_r; }
+ void setR(float v);
+ float r2() const { return m_r2; }
+ void setR2(float v);
+private slots:
+ void startSecondStage();
+private:
+ QOpenGLTexture *m_texture;
+ QOpenGLShaderProgram *m_program;
+ QOpenGLBuffer *m_vbo;
+ QOpenGLVertexArrayObject *m_vao;
+ Logo m_logo;
+ int m_projMatrixLoc;
+ int m_camMatrixLoc;
+ int m_worldMatrixLoc;
+ int m_myMatrixLoc;
+ int m_lightPosLoc;
+ QMatrix4x4 m_proj;
+ QMatrix4x4 m_world;
+ QVector3D m_eye;
+ QVector3D m_target;
+ bool m_uniformsDirty;
+ float m_r;
+ float m_r2;
};
#endif
diff --git a/examples/opengl/hellogles3/hellogles3.pro b/examples/opengl/hellogles3/hellogles3.pro
new file mode 100644
index 0000000000..e0d4c25ca6
--- /dev/null
+++ b/examples/opengl/hellogles3/hellogles3.pro
@@ -0,0 +1,11 @@
+HEADERS = $$PWD/glwindow.h \
+ $$PWD/../hellogl2/logo.h
+
+SOURCES = $$PWD/glwindow.cpp \
+ $$PWD/main.cpp \
+ $$PWD/../hellogl2/logo.cpp
+
+RESOURCES += hellogles3.qrc
+
+target.path = $$[QT_INSTALL_EXAMPLES]/opengl/hellogles3
+INSTALLS += target
diff --git a/examples/opengl/hellogles3/hellogles3.qrc b/examples/opengl/hellogles3/hellogles3.qrc
new file mode 100644
index 0000000000..f3a0978084
--- /dev/null
+++ b/examples/opengl/hellogles3/hellogles3.qrc
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource>
+ <file>qtlogo.png</file>
+ </qresource>
+</RCC>
diff --git a/examples/opengl/hellogles3/main.cpp b/examples/opengl/hellogles3/main.cpp
new file mode 100644
index 0000000000..f0de28bdc4
--- /dev/null
+++ b/examples/opengl/hellogles3/main.cpp
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "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 The Qt Company Ltd 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."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QGuiApplication>
+#include <QSurfaceFormat>
+#include <QOpenGLContext>
+
+#include "glwindow.h"
+
+// This example demonstrates easy, cross-platform usage of OpenGL ES 3.0 functions via
+// QOpenGLExtraFunctions in an application that works identically on desktop platforms
+// with OpenGL 3.3 and mobile/embedded devices with OpenGL ES 3.0.
+
+// The code is always the same, with the exception of two places: (1) the OpenGL context
+// creation has to have a sufficiently high version number for the features that are in
+// use, and (2) the shader code's version directive is different.
+
+int main(int argc, char *argv[])
+{
+ QSurfaceFormat fmt;
+ fmt.setDepthBufferSize(24);
+
+ // Request OpenGL 3.3 compatibility or OpenGL ES 3.0.
+ if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) {
+ qDebug("Requesting 3.3 compatibility context");
+ fmt.setVersion(3, 3);
+ fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
+ } else {
+ qDebug("Requesting 3.0 context");
+ fmt.setVersion(3, 0);
+ }
+
+ QSurfaceFormat::setDefaultFormat(fmt);
+
+ QGuiApplication app(argc, argv);
+
+ GLWindow glWindow;
+ glWindow.showMaximized();
+
+ return app.exec();
+}
diff --git a/examples/opengl/hellogles3/qtlogo.png b/examples/opengl/hellogles3/qtlogo.png
new file mode 100644
index 0000000000..868fcea860
--- /dev/null
+++ b/examples/opengl/hellogles3/qtlogo.png
Binary files differ
diff --git a/examples/opengl/opengl.pro b/examples/opengl/opengl.pro
index cf5329c55d..ed8134743b 100644
--- a/examples/opengl/opengl.pro
+++ b/examples/opengl/opengl.pro
@@ -13,5 +13,6 @@ qtHaveModule(widgets) {
!wince: SUBDIRS += \
qopenglwidget \
cube \
- textures
+ textures \
+ hellogles3
}
diff --git a/examples/qtconcurrent/map/main.cpp b/examples/qtconcurrent/map/main.cpp
index 75b1da4e6f..eaa7c911cb 100644
--- a/examples/qtconcurrent/map/main.cpp
+++ b/examples/qtconcurrent/map/main.cpp
@@ -64,7 +64,7 @@ int main(int argc, char *argv[])
// Use QtConcurrentBlocking::mapped to apply the scale function to all the
// images in the list.
- QList<QImage> thumbnails = QtConcurrent::blockingMapped<QList<QImage> >(images, scale);
+ QList<QImage> thumbnails = QtConcurrent::blockingMapped(images, scale);
return 0;
}
diff --git a/examples/sql/books/books.pro b/examples/sql/books/books.pro
index 94f8104414..c64766c29f 100644
--- a/examples/sql/books/books.pro
+++ b/examples/sql/books/books.pro
@@ -16,5 +16,5 @@ wince {
CONFIG(debug, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*d4.dll
CONFIG(release, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*[^d]4.dll
sqlPlugins.path = sqldrivers
- DEPLOYMENT += sqlPlugins
+ INSTALLS += sqlPlugins
}
diff --git a/examples/webkit/webkit-guide/js/anim_accord.js b/examples/webkit/webkit-guide/js/anim_accord.js
index cc95b7f7c9..cc95b7f7c9 100755..100644
--- a/examples/webkit/webkit-guide/js/anim_accord.js
+++ b/examples/webkit/webkit-guide/js/anim_accord.js
diff --git a/examples/webkit/webkit-guide/js/anim_gallery.js b/examples/webkit/webkit-guide/js/anim_gallery.js
index 050f113bb4..050f113bb4 100755..100644
--- a/examples/webkit/webkit-guide/js/anim_gallery.js
+++ b/examples/webkit/webkit-guide/js/anim_gallery.js
diff --git a/examples/webkit/webkit-guide/js/anim_panel.js b/examples/webkit/webkit-guide/js/anim_panel.js
index e6cc5e6d8f..e6cc5e6d8f 100755..100644
--- a/examples/webkit/webkit-guide/js/anim_panel.js
+++ b/examples/webkit/webkit-guide/js/anim_panel.js
diff --git a/examples/webkit/webkit-guide/js/anim_skew.js b/examples/webkit/webkit-guide/js/anim_skew.js
index 8b1300fd1f..8b1300fd1f 100755..100644
--- a/examples/webkit/webkit-guide/js/anim_skew.js
+++ b/examples/webkit/webkit-guide/js/anim_skew.js
diff --git a/examples/webkit/webkit-guide/js/css3_backgrounds.js b/examples/webkit/webkit-guide/js/css3_backgrounds.js
index 29004c7b53..29004c7b53 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_backgrounds.js
+++ b/examples/webkit/webkit-guide/js/css3_backgrounds.js
diff --git a/examples/webkit/webkit-guide/js/css3_border-img.js b/examples/webkit/webkit-guide/js/css3_border-img.js
index a8bfd9132d..a8bfd9132d 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_border-img.js
+++ b/examples/webkit/webkit-guide/js/css3_border-img.js
diff --git a/examples/webkit/webkit-guide/js/css3_grad-radial.js b/examples/webkit/webkit-guide/js/css3_grad-radial.js
index f194ddaa6c..f194ddaa6c 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_grad-radial.js
+++ b/examples/webkit/webkit-guide/js/css3_grad-radial.js
diff --git a/examples/webkit/webkit-guide/js/css3_mask-grad.js b/examples/webkit/webkit-guide/js/css3_mask-grad.js
index 911212dcf4..911212dcf4 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_mask-grad.js
+++ b/examples/webkit/webkit-guide/js/css3_mask-grad.js
diff --git a/examples/webkit/webkit-guide/js/css3_mask-img.js b/examples/webkit/webkit-guide/js/css3_mask-img.js
index a8bfd9132d..a8bfd9132d 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_mask-img.js
+++ b/examples/webkit/webkit-guide/js/css3_mask-img.js
diff --git a/examples/webkit/webkit-guide/js/css3_text-overflow.js b/examples/webkit/webkit-guide/js/css3_text-overflow.js
index 58af80d6d1..58af80d6d1 100755..100644
--- a/examples/webkit/webkit-guide/js/css3_text-overflow.js
+++ b/examples/webkit/webkit-guide/js/css3_text-overflow.js
diff --git a/examples/webkit/webkit-guide/js/form_tapper.js b/examples/webkit/webkit-guide/js/form_tapper.js
index d4d87a2c1a..d4d87a2c1a 100755..100644
--- a/examples/webkit/webkit-guide/js/form_tapper.js
+++ b/examples/webkit/webkit-guide/js/form_tapper.js
diff --git a/examples/webkit/webkit-guide/js/mob_condjs.js b/examples/webkit/webkit-guide/js/mob_condjs.js
index 32bf550d20..32bf550d20 100755..100644
--- a/examples/webkit/webkit-guide/js/mob_condjs.js
+++ b/examples/webkit/webkit-guide/js/mob_condjs.js
diff --git a/examples/webkit/webkit-guide/js/mobile.js b/examples/webkit/webkit-guide/js/mobile.js
index 51c94d4080..51c94d4080 100755..100644
--- a/examples/webkit/webkit-guide/js/mobile.js
+++ b/examples/webkit/webkit-guide/js/mobile.js
diff --git a/examples/webkit/webkit-guide/js/storage.js b/examples/webkit/webkit-guide/js/storage.js
index b5a374f39d..b5a374f39d 100755..100644
--- a/examples/webkit/webkit-guide/js/storage.js
+++ b/examples/webkit/webkit-guide/js/storage.js
diff --git a/examples/widgets/dialogs/classwizard/classwizard.cpp b/examples/widgets/dialogs/classwizard/classwizard.cpp
index 0f1a2a0869..c913d7b592 100644
--- a/examples/widgets/dialogs/classwizard/classwizard.cpp
+++ b/examples/widgets/dialogs/classwizard/classwizard.cpp
@@ -252,8 +252,8 @@ ClassInfoPage::ClassInfoPage(QWidget *parent)
defaultCtorRadioButton->setChecked(true);
- connect(defaultCtorRadioButton, SIGNAL(toggled(bool)),
- copyCtorCheckBox, SLOT(setEnabled(bool)));
+ connect(defaultCtorRadioButton, &QAbstractButton::toggled,
+ copyCtorCheckBox, &QWidget::setEnabled);
//! [11] //! [12]
registerField("className*", classNameLineEdit);
@@ -311,14 +311,14 @@ CodeStylePage::CodeStylePage(QWidget *parent)
baseIncludeLineEdit = new QLineEdit;
baseIncludeLabel->setBuddy(baseIncludeLineEdit);
- connect(protectCheckBox, SIGNAL(toggled(bool)),
- macroNameLabel, SLOT(setEnabled(bool)));
- connect(protectCheckBox, SIGNAL(toggled(bool)),
- macroNameLineEdit, SLOT(setEnabled(bool)));
- connect(includeBaseCheckBox, SIGNAL(toggled(bool)),
- baseIncludeLabel, SLOT(setEnabled(bool)));
- connect(includeBaseCheckBox, SIGNAL(toggled(bool)),
- baseIncludeLineEdit, SLOT(setEnabled(bool)));
+ connect(protectCheckBox, &QAbstractButton::toggled,
+ macroNameLabel, &QWidget::setEnabled);
+ connect(protectCheckBox, &QAbstractButton::toggled,
+ macroNameLineEdit, &QWidget::setEnabled);
+ connect(includeBaseCheckBox, &QAbstractButton::toggled,
+ baseIncludeLabel, &QWidget::setEnabled);
+ connect(includeBaseCheckBox, &QAbstractButton::toggled,
+ baseIncludeLineEdit, &QWidget::setEnabled);
registerField("comment", commentCheckBox);
registerField("protect", protectCheckBox);
diff --git a/examples/widgets/dialogs/configdialog/configdialog.cpp b/examples/widgets/dialogs/configdialog/configdialog.cpp
index 8e68940227..c4565a6407 100644
--- a/examples/widgets/dialogs/configdialog/configdialog.cpp
+++ b/examples/widgets/dialogs/configdialog/configdialog.cpp
@@ -62,7 +62,7 @@ ConfigDialog::ConfigDialog()
createIcons();
contentsWidget->setCurrentRow(0);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
+ connect(closeButton, &QAbstractButton::clicked, this, &QWidget::close);
QHBoxLayout *horizontalLayout = new QHBoxLayout;
horizontalLayout->addWidget(contentsWidget);
@@ -102,9 +102,7 @@ void ConfigDialog::createIcons()
queryButton->setTextAlignment(Qt::AlignHCenter);
queryButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
- connect(contentsWidget,
- SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
- this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*)));
+ connect(contentsWidget, &QListWidget::currentItemChanged, this, &ConfigDialog::changePage);
}
void ConfigDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous)
diff --git a/examples/widgets/dialogs/extension/finddialog.cpp b/examples/widgets/dialogs/extension/finddialog.cpp
index 19eab195cb..895b0cf2ce 100644
--- a/examples/widgets/dialogs/extension/finddialog.cpp
+++ b/examples/widgets/dialogs/extension/finddialog.cpp
@@ -78,7 +78,7 @@ FindDialog::FindDialog(QWidget *parent)
buttonBox->addButton(findButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(moreButton, QDialogButtonBox::ActionRole);
- connect(moreButton, SIGNAL(toggled(bool)), extension, SLOT(setVisible(bool)));
+ connect(moreButton, &QAbstractButton::toggled, extension, &QWidget::setVisible);
QVBoxLayout *extensionLayout = new QVBoxLayout;
extensionLayout->setMargin(0);
diff --git a/examples/widgets/dialogs/findfiles/window.cpp b/examples/widgets/dialogs/findfiles/window.cpp
index 86c34a6352..780c398ad5 100644
--- a/examples/widgets/dialogs/findfiles/window.cpp
+++ b/examples/widgets/dialogs/findfiles/window.cpp
@@ -46,8 +46,10 @@
Window::Window(QWidget *parent)
: QWidget(parent)
{
- browseButton = createButton(tr("&Browse..."), SLOT(browse()));
- findButton = createButton(tr("&Find"), SLOT(find()));
+ browseButton = new QPushButton(tr("&Browse..."), this);
+ connect(browseButton, &QAbstractButton::clicked, this, &Window::browse);
+ findButton = new QPushButton(tr("&Find"), this);
+ connect(findButton, &QAbstractButton::clicked, this, &Window::find);
fileComboBox = createComboBox(tr("*"));
textComboBox = createComboBox();
@@ -195,15 +197,6 @@ void Window::showFiles(const QStringList &files)
}
//! [8]
-//! [9]
-QPushButton *Window::createButton(const QString &text, const char *member)
-{
- QPushButton *button = new QPushButton(text);
- connect(button, SIGNAL(clicked()), this, member);
- return button;
-}
-//! [9]
-
//! [10]
QComboBox *Window::createComboBox(const QString &text)
{
@@ -228,8 +221,8 @@ void Window::createFilesTable()
filesTable->verticalHeader()->hide();
filesTable->setShowGrid(false);
- connect(filesTable, SIGNAL(cellActivated(int,int)),
- this, SLOT(openFileOfItem(int,int)));
+ connect(filesTable, &QTableWidget::cellActivated,
+ this, &Window::openFileOfItem);
}
//! [11]
diff --git a/examples/widgets/dialogs/findfiles/window.h b/examples/widgets/dialogs/findfiles/window.h
index 281c932e2f..89dd87b83b 100644
--- a/examples/widgets/dialogs/findfiles/window.h
+++ b/examples/widgets/dialogs/findfiles/window.h
@@ -68,7 +68,6 @@ private slots:
private:
QStringList findFiles(const QStringList &files, const QString &text);
void showFiles(const QStringList &files);
- QPushButton *createButton(const QString &text, const char *member);
QComboBox *createComboBox(const QString &text = QString());
void createFilesTable();
diff --git a/examples/widgets/dialogs/licensewizard/licensewizard.cpp b/examples/widgets/dialogs/licensewizard/licensewizard.cpp
index ace2e1229a..0f11f3ab7b 100644
--- a/examples/widgets/dialogs/licensewizard/licensewizard.cpp
+++ b/examples/widgets/dialogs/licensewizard/licensewizard.cpp
@@ -70,7 +70,7 @@ LicenseWizard::LicenseWizard(QWidget *parent)
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo.png"));
//! [7]
- connect(this, SIGNAL(helpRequested()), this, SLOT(showHelp()));
+ connect(this, &QWizard::helpRequested, this, &LicenseWizard::showHelp);
//! [7]
setWindowTitle(tr("License Wizard"));
@@ -339,13 +339,13 @@ void ConclusionPage::setVisible(bool visible)
//! [29]
wizard()->setButtonText(QWizard::CustomButton1, tr("&Print"));
wizard()->setOption(QWizard::HaveCustomButton1, true);
- connect(wizard(), SIGNAL(customButtonClicked(int)),
- this, SLOT(printButtonClicked()));
+ connect(wizard(), &QWizard::customButtonClicked,
+ this, &ConclusionPage::printButtonClicked);
//! [29]
} else {
wizard()->setOption(QWizard::HaveCustomButton1, false);
- disconnect(wizard(), SIGNAL(customButtonClicked(int)),
- this, SLOT(printButtonClicked()));
+ disconnect(wizard(), &QWizard::customButtonClicked,
+ this, &ConclusionPage::printButtonClicked);
}
}
//! [28]
diff --git a/examples/widgets/dialogs/sipdialog/dialog.cpp b/examples/widgets/dialogs/sipdialog/dialog.cpp
index f57cd094ae..48859ec5ff 100644
--- a/examples/widgets/dialogs/sipdialog/dialog.cpp
+++ b/examples/widgets/dialogs/sipdialog/dialog.cpp
@@ -89,10 +89,9 @@ Dialog::Dialog()
//! [Dialog constructor part4]
//! [Dialog constructor part5]
- connect(button, SIGNAL(clicked()),
- qApp, SLOT(closeAllWindows()));
- connect(QApplication::desktop(), SIGNAL(workAreaResized(int)),
- this, SLOT(desktopResized(int)));
+ connect(button, &QAbstractButton::clicked, qApp, &QApplication::closeAllWindows);
+ connect(QApplication::desktop(), &QDesktopWidget::workAreaResized,
+ this, &Dialog::desktopResized);
}
//! [Dialog constructor part5]
diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp
index 0a1532616c..b4232c36f6 100644
--- a/examples/widgets/dialogs/standarddialogs/dialog.cpp
+++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp
@@ -180,27 +180,27 @@ Dialog::Dialog(QWidget *parent)
QPushButton *errorButton =
new QPushButton(tr("QErrorMessage::showM&essage()"));
- connect(integerButton, SIGNAL(clicked()), this, SLOT(setInteger()));
- connect(doubleButton, SIGNAL(clicked()), this, SLOT(setDouble()));
- connect(itemButton, SIGNAL(clicked()), this, SLOT(setItem()));
- connect(textButton, SIGNAL(clicked()), this, SLOT(setText()));
- connect(multiLineTextButton, SIGNAL(clicked()), this, SLOT(setMultiLineText()));
- connect(colorButton, SIGNAL(clicked()), this, SLOT(setColor()));
- connect(fontButton, SIGNAL(clicked()), this, SLOT(setFont()));
- connect(directoryButton, SIGNAL(clicked()),
- this, SLOT(setExistingDirectory()));
- connect(openFileNameButton, SIGNAL(clicked()),
- this, SLOT(setOpenFileName()));
- connect(openFileNamesButton, SIGNAL(clicked()),
- this, SLOT(setOpenFileNames()));
- connect(saveFileNameButton, SIGNAL(clicked()),
- this, SLOT(setSaveFileName()));
- connect(criticalButton, SIGNAL(clicked()), this, SLOT(criticalMessage()));
- connect(informationButton, SIGNAL(clicked()),
- this, SLOT(informationMessage()));
- connect(questionButton, SIGNAL(clicked()), this, SLOT(questionMessage()));
- connect(warningButton, SIGNAL(clicked()), this, SLOT(warningMessage()));
- connect(errorButton, SIGNAL(clicked()), this, SLOT(errorMessage()));
+ connect(integerButton, &QAbstractButton::clicked, this, &Dialog::setInteger);
+ connect(doubleButton, &QAbstractButton::clicked, this, &Dialog::setDouble);
+ connect(itemButton, &QAbstractButton::clicked, this, &Dialog::setItem);
+ connect(textButton, &QAbstractButton::clicked, this, &Dialog::setText);
+ connect(multiLineTextButton, &QAbstractButton::clicked, this, &Dialog::setMultiLineText);
+ connect(colorButton, &QAbstractButton::clicked, this, &Dialog::setColor);
+ connect(fontButton, &QAbstractButton::clicked, this, &Dialog::setFont);
+ connect(directoryButton, &QAbstractButton::clicked,
+ this, &Dialog::setExistingDirectory);
+ connect(openFileNameButton, &QAbstractButton::clicked,
+ this, &Dialog::setOpenFileName);
+ connect(openFileNamesButton, &QAbstractButton::clicked,
+ this, &Dialog::setOpenFileNames);
+ connect(saveFileNameButton, &QAbstractButton::clicked,
+ this, &Dialog::setSaveFileName);
+ connect(criticalButton, &QAbstractButton::clicked, this, &Dialog::criticalMessage);
+ connect(informationButton, &QAbstractButton::clicked,
+ this, &Dialog::informationMessage);
+ connect(questionButton, &QAbstractButton::clicked, this, &Dialog::questionMessage);
+ connect(warningButton, &QAbstractButton::clicked, this, &Dialog::warningMessage);
+ connect(errorButton, &QAbstractButton::clicked, this, &Dialog::errorMessage);
QWidget *page = new QWidget;
QGridLayout *layout = new QGridLayout(page);
@@ -242,6 +242,10 @@ Dialog::Dialog(QWidget *parent)
layout->addWidget(fontLabel, 0, 1);
fontDialogOptionsWidget = new DialogOptionsWidget;
fontDialogOptionsWidget->addCheckBox(doNotUseNativeDialog, QFontDialog::DontUseNativeDialog);
+ fontDialogOptionsWidget->addCheckBox(tr("Show scalable fonts"), QFontDialog::ScalableFonts);
+ fontDialogOptionsWidget->addCheckBox(tr("Show non scalable fonts"), QFontDialog::NonScalableFonts);
+ fontDialogOptionsWidget->addCheckBox(tr("Show monospaced fonts"), QFontDialog::MonospacedFonts);
+ fontDialogOptionsWidget->addCheckBox(tr("Show proportional fonts"), QFontDialog::ProportionalFonts);
fontDialogOptionsWidget->addCheckBox(tr("No buttons") , QFontDialog::NoButtons);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 1, 0);
layout->addWidget(fontDialogOptionsWidget, 2, 0, 1 ,2);
@@ -266,6 +270,7 @@ Dialog::Dialog(QWidget *parent)
fileDialogOptionsWidget->addCheckBox(tr("Do not use sheet"), QFileDialog::DontUseSheet);
fileDialogOptionsWidget->addCheckBox(tr("Readonly"), QFileDialog::ReadOnly);
fileDialogOptionsWidget->addCheckBox(tr("Hide name filter details"), QFileDialog::HideNameFilterDetails);
+ fileDialogOptionsWidget->addCheckBox(tr("Do not use custom directory icons (Windows)"), QFileDialog::DontUseCustomDirectoryIcons);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 4, 0);
layout->addWidget(fileDialogOptionsWidget, 5, 0, 1 ,2);
toolbox->addItem(page, tr("File Dialogs"));
diff --git a/examples/widgets/dialogs/standarddialogs/main.cpp b/examples/widgets/dialogs/standarddialogs/main.cpp
index eafd2271df..a13e37905c 100644
--- a/examples/widgets/dialogs/standarddialogs/main.cpp
+++ b/examples/widgets/dialogs/standarddialogs/main.cpp
@@ -39,6 +39,7 @@
****************************************************************************/
#include <QApplication>
+#include <QDesktopWidget>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
@@ -58,6 +59,10 @@ int main(int argc, char *argv[])
#endif
Dialog dialog;
+ const QRect availableGeometry = QApplication::desktop()->availableGeometry(&dialog);
+ dialog.resize(availableGeometry.width() / 3, availableGeometry.height() * 2 / 3);
+ dialog.move((availableGeometry.width() - dialog.width()) / 2,
+ (availableGeometry.height() - dialog.height()) / 2);
dialog.show();
return app.exec();
diff --git a/examples/widgets/dialogs/tabdialog/tabdialog.cpp b/examples/widgets/dialogs/tabdialog/tabdialog.cpp
index ec1a6efbc8..75a7b85e3b 100644
--- a/examples/widgets/dialogs/tabdialog/tabdialog.cpp
+++ b/examples/widgets/dialogs/tabdialog/tabdialog.cpp
@@ -59,8 +59,8 @@ TabDialog::TabDialog(const QString &fileName, QWidget *parent)
//! [1] //! [3]
| QDialogButtonBox::Cancel);
- connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
- connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
//! [2] //! [3]
//! [4]
diff --git a/examples/widgets/doc/images/regularexpression-example.png b/examples/widgets/doc/images/regularexpression-example.png
new file mode 100644
index 0000000000..d426d8514a
--- /dev/null
+++ b/examples/widgets/doc/images/regularexpression-example.png
Binary files differ
diff --git a/examples/widgets/doc/src/application.qdoc b/examples/widgets/doc/src/application.qdoc
index ac32c592fc..cd284ecba0 100644
--- a/examples/widgets/doc/src/application.qdoc
+++ b/examples/widgets/doc/src/application.qdoc
@@ -50,11 +50,10 @@
To keep the example simple, recently opened files aren't shown in
the \uicontrol{File} menu, even though this feature is desired in 90%
- of applications. The \l{mainwindows/recentfiles}{Recent Files}
- example shows how to implement this. Furthermore, this example
- can only load one file at a time. The \l{mainwindows/sdi}{SDI}
- and \l{mainwindows/mdi}{MDI} examples shows how to lift these
- restrictions.
+ of applications. Furthermore, this example can only load one file at a
+ time. The \l{mainwindows/sdi}{SDI} and \l{mainwindows/mdi}{MDI} examples
+ show how to lift these restrictions and how to implement recently opened files
+ handling.
\section1 MainWindow Class Definition
@@ -96,8 +95,7 @@
the widget that occupies the central area of the main window,
between the toolbars and the status bar.
- Then we call \c createActions(), \c createMenus(), \c
- createToolBars(), and \c createStatusBar(), four private
+ Then we call \c createActions() and \c createStatusBar(), two private
functions that set up the user interface. After that, we call \c
readSettings() to restore the user's preferences.
@@ -184,7 +182,8 @@
\snippet mainwindows/application/mainwindow.cpp 22
The \c createActions() private function, which is called from the
- \c MainWindow constructor, creates \l{QAction}s. The code is very
+ \c MainWindow constructor, creates \l{QAction}s and populates
+ the menus and two toolbars. The code is very
repetitive, so we show only the actions corresponding to
\uicontrol{File|New}, \uicontrol{File|Open}, and \uicontrol{Help|About Qt}.
@@ -198,13 +197,27 @@
a "What's This?" text, and more. It emits a
\l{QAction::triggered()}{triggered()} signal whenever the user
invokes the action (e.g., by clicking the associated menu item or
- toolbar button). We connect this signal to a slot that performs
- the actual action.
+ toolbar button).
+
+ Instances of QAction can be created by passing a parent QObject or
+ by using one of the convenience functions of QMenu, QMenuBar or QToolBar.
+ We create the actions that are in a menu as well as in a toolbar
+ parented on the window to prevent ownership issues. For actions
+ that are only in the menu, we use the convenience function
+ QMenu::addAction(), which allows us to pass text, icon and the
+ target object and its slot member function.
+
+ Creating toolbars is very similar to creating menus. The same
+ actions that we put in the menus can be reused in the toolbars.
+ After creating the action, we add it to the toolbar using
+ QToolBar::addAction().
The code above contains one more idiom that must be explained.
For some of the actions, we specify an icon as a QIcon to the
- QAction constructor. The QIcon constructor takes the file name
- of an image that it tries to load. Here, the file name starts
+ QAction constructor. We use QIcon::fromTheme() to obtain
+ the correct standard icon from the underlying window system.
+ If that fails due to the platform not supporting it, we
+ pass a file name as fallback. Here, the file name starts
with \c{:}. Such file names aren't ordinary file names, but
rather path in the executable's stored resources. We'll come back
to this when we review the \c application.qrc file that's part of
@@ -219,30 +232,12 @@
the QAction::setEnabled() slot, ensuring that the actions are
disabled when the text editor has no selection.
- \snippet mainwindows/application/mainwindow.cpp 25
- \snippet mainwindows/application/mainwindow.cpp 27
-
- Creating actions isn't sufficient to make them available to the
- user; we must also add them to the menu system. This is what \c
- createMenus() does. We create a \uicontrol{File}, an \uicontrol{Edit}, and
- a \uicontrol{Help} menu. QMainWindow::menuBar() lets us access the
- window's menu bar widget. We don't have to worry about creating
- the menu bar ourselves; the first time we call this function, the
- QMenuBar is created.
-
Just before we create the \uicontrol{Help} menu, we call
QMenuBar::addSeparator(). This has no effect for most widget
styles (e.g., Windows and OS X styles), but for some
styles this makes sure that \uicontrol{Help} is pushed to the right
side of the menu bar.
- Let's now review the toolbars:
-
- \snippet mainwindows/application/mainwindow.cpp 30
-
- Creating toolbars is very similar to creating menus. The same
- actions that we put in the menus can be reused in the toolbars.
-
\snippet mainwindows/application/mainwindow.cpp 32
\snippet mainwindows/application/mainwindow.cpp 33
@@ -265,15 +260,15 @@
company and the name of the product. This ensures that the
settings for different applications are kept separately.
- We use QSettings::value() to extract the value of the "pos" and
- "size" settings. The second argument to QSettings::value() is
+ We use QSettings::value() to extract the value of the geometry setting.
+ The second argument to QSettings::value() is
optional and specifies a default value for the setting if there
exists none. This value is used the first time the application is
run.
- When restoring the position and size of a window, it's important
- to call QWidget::resize() before QWidget::move(). The reason why
- is given in the \l{Window Geometry} overview.
+ We use QWidget::saveGeometry() and Widget::restoreGeometry() to
+ save the position. They use an opaque QByteArray to store
+ screen number, geometry and window state.
\snippet mainwindows/application/mainwindow.cpp 37
\snippet mainwindows/application/mainwindow.cpp 39
@@ -297,9 +292,9 @@
QMessageBox::Escape flag.
The \c maybeSave() function returns \c true in all cases, except
- when the user clicks \uicontrol{Cancel}. The caller must check the
- return value and stop whatever it was doing if the return value
- is \c false.
+ when the user clicks \uicontrol{Cancel} or saving the file fails.
+ The caller must check the return value and stop whatever it was
+ doing if the return value is \c false.
\snippet mainwindows/application/mainwindow.cpp 42
\snippet mainwindows/application/mainwindow.cpp 43
@@ -361,6 +356,10 @@
\snippet mainwindows/application/main.cpp 0
+ The main function uses QCommandLineParser to check whether some file
+ argument was passed to the application and loads it via
+ MainWindow::loadFile().
+
\section1 The Resource File
As you will probably recall, for some of the actions, we
diff --git a/examples/widgets/doc/src/findfiles.qdoc b/examples/widgets/doc/src/findfiles.qdoc
index 0a4fb8268d..dd06ed8bb4 100644
--- a/examples/widgets/doc/src/findfiles.qdoc
+++ b/examples/widgets/doc/src/findfiles.qdoc
@@ -200,13 +200,6 @@
We also update the total number of files found.
- \snippet dialogs/findfiles/window.cpp 9
-
- The private \c createButton() function is called from the
- constructor. We create a QPushButton with the provided text,
- connect it to the provided slot, and return a pointer to the
- button.
-
\snippet dialogs/findfiles/window.cpp 10
The private \c createComboBox() function is also called from the
diff --git a/examples/widgets/doc/src/imageviewer.qdoc b/examples/widgets/doc/src/imageviewer.qdoc
index 91ae56b5d7..4457da9d6f 100644
--- a/examples/widgets/doc/src/imageviewer.qdoc
+++ b/examples/widgets/doc/src/imageviewer.qdoc
@@ -287,7 +287,8 @@
\snippet widgets/imageviewer/imageviewer.cpp 18
In the private \c createAction() function, we create the
- actions providing the application features.
+ actions providing the application features and populate
+ a menu with them.
We assign a short-cut key to each action and connect them to the
appropriate slots. We only enable the \c openAct and \c exitAct at
@@ -295,16 +296,10 @@
been loaded into the application. In addition we make the \c
fitToWindowAct \l {QAction::checkable}{checkable}.
- \snippet widgets/imageviewer/imageviewer.cpp 19
- \snippet widgets/imageviewer/imageviewer.cpp 20
-
- In the private \c createMenu() function, we add the previously
- created actions to the \uicontrol File, \uicontrol View and \uicontrol Help menus.
-
The QMenu class provides a menu widget for use in menu bars,
context menus, and other popup menus. The QMenuBar class provides
a horizontal menu bar that consists of a list of pull-down menu
- items. So at the end we put the menus in the \c {ImageViewer}'s
+ items. So we put the menus in the \c {ImageViewer}'s
menu bar which we retrieve with the QMainWindow::menuBar()
function.
diff --git a/examples/widgets/doc/src/recentfiles.qdoc b/examples/widgets/doc/src/regularexpression.qdoc
index b58c9a1f76..804867fb58 100644
--- a/examples/widgets/doc/src/recentfiles.qdoc
+++ b/examples/widgets/doc/src/regularexpression.qdoc
@@ -26,12 +26,23 @@
****************************************************************************/
/*!
- \example mainwindows/recentfiles
- \title Recent Files Example
- \ingroup examples-mainwindow
+ \example tools/regularexpression
+ \title QRegularExpression Example
+ \ingroup examples-widgets-tools
- \brief The Recent Files example shows how a standard File menu can be extended to show
- the most recent files loaded by a main window application.
+ \brief The QRegularExpression example shows how regular expressions in Qt are
+ applied to text by providing an environment in which new regular expressions can be
+ created and tested on custom text strings.
- \image recentfiles-example.png
+ The example makes usage of the QRegularExpression class, which has been
+ introduced in Qt 5.0. QRegularExpression implements Perl-compatible regular
+ expressions, supporting a number of advanced matching features, such as
+ case insensitive matching, multiline matching, Unicode properties selectors
+ and partial/incremental matching.
+
+ QRegularExpression is a big improvement over QRegExp in terms of features
+ and performance and should be used in all new code.
+
+ \image regularexpression-example.png
*/
+
diff --git a/examples/widgets/doc/src/tablet.qdoc b/examples/widgets/doc/src/tablet.qdoc
index 1ab2917b7e..bc03d46332 100644
--- a/examples/widgets/doc/src/tablet.qdoc
+++ b/examples/widgets/doc/src/tablet.qdoc
@@ -259,24 +259,18 @@
\snippet widgets/tablet/tabletcanvas.cpp 5
- In this function we draw on the pixmap based on the movement of the
- device. If the device used on the tablet is a stylus we want to draw a
- line between the positions of the stylus recorded in \c polyLine. We
- also assume that this is a reasonable handling of any unknown device,
- but update the statusbar with a warning so that the user can see that
- for his tablet he might have to implement special handling.
- If it is an airbrush we want to draw a circle of points with a
- point density based on the tangential pressure, which is the position
- of the finger wheel on the airbrush. We use the Qt::BrushStyle to
- draw the points as it has styles that draw points with different
- density; we select the style based on the tangential pressure in
- \c brushPattern().
+ In this function we draw on the pixmap based on the movement of the device.
+ If the device used on the tablet is a stylus, we want to draw a line from
+ the last-known position to the current position. We also assume that this
+ is a reasonable handling of any unknown device, but update the status bar
+ with a warning. If it is an airbrush, we want to draw a circle filled with
+ a soft gradient, whose density can depend on various event parameters.
+ By default it depends on the tangential pressure, which is the position of
+ the finger wheel on the airbrush. If it is a rotation stylus, we simulate
+ a felt marker by drawing trapezoidal strokes.
\snippet widgets/tablet/tabletcanvas.cpp 6
- We return a brush style with a point density that increases with
- the tangential pressure.
-
In \c updateBrush() we set the pen and brush used for drawing
to match \c alphaChannelType, \c lineWidthType, \c
colorSaturationType, and \c myColor. We will examine the code to
diff --git a/examples/widgets/draganddrop/puzzle/puzzle.pro b/examples/widgets/draganddrop/puzzle/puzzle.pro
index 67fff21a26..404b75187d 100644
--- a/examples/widgets/draganddrop/puzzle/puzzle.pro
+++ b/examples/widgets/draganddrop/puzzle/puzzle.pro
@@ -18,5 +18,5 @@ INSTALLS += target
wince {
addFile.files = example.jpg
addFile.path = .
- DEPLOYMENT += addFile
+ INSTALLS += addFile
}
diff --git a/examples/widgets/itemviews/addressbook/adddialog.cpp b/examples/widgets/itemviews/addressbook/adddialog.cpp
index de5c7eaf87..d153381b56 100644
--- a/examples/widgets/itemviews/addressbook/adddialog.cpp
+++ b/examples/widgets/itemviews/addressbook/adddialog.cpp
@@ -72,8 +72,8 @@ AddDialog::AddDialog(QWidget *parent)
mainLayout->addLayout(gLayout);
setLayout(mainLayout);
- connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
- connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
+ connect(okButton, &QAbstractButton::clicked, this, &QDialog::accept);
+ connect(cancelButton, &QAbstractButton::clicked, this, &QDialog::reject);
setWindowTitle(tr("Add a Contact"));
}
diff --git a/examples/widgets/itemviews/addressbook/addresswidget.cpp b/examples/widgets/itemviews/addressbook/addresswidget.cpp
index 20589a9417..792d626a4e 100644
--- a/examples/widgets/itemviews/addressbook/addresswidget.cpp
+++ b/examples/widgets/itemviews/addressbook/addresswidget.cpp
@@ -49,8 +49,8 @@ AddressWidget::AddressWidget(QWidget *parent)
{
table = new TableModel(this);
newAddressTab = new NewAddressTab(this);
- connect(newAddressTab, SIGNAL(sendDetails(QString, QString)),
- this, SLOT(addEntry(QString, QString)));
+ connect(newAddressTab, &NewAddressTab::sendDetails,
+ this, &AddressWidget::addEntry);
addTab(newAddressTab, "Address Book");
@@ -59,7 +59,7 @@ AddressWidget::AddressWidget(QWidget *parent)
//! [0]
//! [2]
-void AddressWidget::addEntry()
+void AddressWidget::showAddEntryDialog()
{
AddDialog aDialog;
@@ -182,8 +182,8 @@ void AddressWidget::setupTabs()
tableView->setSortingEnabled(true);
connect(tableView->selectionModel(),
- SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SIGNAL(selectionChanged(QItemSelection)));
+ &QItemSelectionModel::selectionChanged,
+ this, &AddressWidget::selectionChanged);
addTab(tableView, str);
}
diff --git a/examples/widgets/itemviews/addressbook/addresswidget.h b/examples/widgets/itemviews/addressbook/addresswidget.h
index b990c47911..a2fc4bc03b 100644
--- a/examples/widgets/itemviews/addressbook/addresswidget.h
+++ b/examples/widgets/itemviews/addressbook/addresswidget.h
@@ -63,7 +63,7 @@ public:
void writeToFile(const QString &fileName);
public slots:
- void addEntry();
+ void showAddEntryDialog();
void addEntry(QString name, QString address);
void editEntry();
void removeEntry();
diff --git a/examples/widgets/itemviews/addressbook/mainwindow.cpp b/examples/widgets/itemviews/addressbook/mainwindow.cpp
index f729f43604..94b38ea2f6 100644
--- a/examples/widgets/itemviews/addressbook/mainwindow.cpp
+++ b/examples/widgets/itemviews/addressbook/mainwindow.cpp
@@ -61,40 +61,40 @@ void MainWindow::createMenus()
openAct = new QAction(tr("&Open..."), this);
fileMenu->addAction(openAct);
- connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));
+ connect(openAct, &QAction::triggered, this, &MainWindow::openFile);
//! [1a]
saveAct = new QAction(tr("&Save As..."), this);
fileMenu->addAction(saveAct);
- connect(saveAct, SIGNAL(triggered()), this, SLOT(saveFile()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::saveFile);
fileMenu->addSeparator();
exitAct = new QAction(tr("E&xit"), this);
fileMenu->addAction(exitAct);
- connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
+ connect(exitAct, &QAction::triggered, this, &QWidget::close);
toolMenu = menuBar()->addMenu(tr("&Tools"));
addAct = new QAction(tr("&Add Entry..."), this);
toolMenu->addAction(addAct);
- connect(addAct, SIGNAL(triggered()), addressWidget, SLOT(addEntry()));
+ connect(addAct, &QAction::triggered, addressWidget, &AddressWidget::showAddEntryDialog);
//! [1b]
editAct = new QAction(tr("&Edit Entry..."), this);
editAct->setEnabled(false);
toolMenu->addAction(editAct);
- connect(editAct, SIGNAL(triggered()), addressWidget, SLOT(editEntry()));
+ connect(editAct, &QAction::triggered, addressWidget, &AddressWidget::editEntry);
toolMenu->addSeparator();
removeAct = new QAction(tr("&Remove Entry"), this);
removeAct->setEnabled(false);
toolMenu->addAction(removeAct);
- connect(removeAct, SIGNAL(triggered()), addressWidget, SLOT(removeEntry()));
+ connect(removeAct, &QAction::triggered, addressWidget, &AddressWidget::removeEntry);
- connect(addressWidget, SIGNAL(selectionChanged(QItemSelection)),
- this, SLOT(updateActions(QItemSelection)));
+ connect(addressWidget, &AddressWidget::selectionChanged,
+ this, &MainWindow::updateActions);
}
//! [1b]
diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.cpp b/examples/widgets/itemviews/addressbook/newaddresstab.cpp
index 012a19991c..af66636995 100644
--- a/examples/widgets/itemviews/addressbook/newaddresstab.cpp
+++ b/examples/widgets/itemviews/addressbook/newaddresstab.cpp
@@ -53,7 +53,7 @@ NewAddressTab::NewAddressTab(QWidget *parent)
addButton = new QPushButton(tr("Add"));
- connect(addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
+ connect(addButton, &QAbstractButton::clicked, this, &NewAddressTab::addEntry);
mainLayout = new QVBoxLayout;
mainLayout->addWidget(descriptionLabel);
diff --git a/examples/widgets/itemviews/basicsortfiltermodel/window.cpp b/examples/widgets/itemviews/basicsortfiltermodel/window.cpp
index b518460230..0f5a434bcc 100644
--- a/examples/widgets/itemviews/basicsortfiltermodel/window.cpp
+++ b/examples/widgets/itemviews/basicsortfiltermodel/window.cpp
@@ -77,16 +77,18 @@ Window::Window()
filterColumnLabel = new QLabel(tr("Filter &column:"));
filterColumnLabel->setBuddy(filterColumnComboBox);
- connect(filterPatternLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(filterRegExpChanged()));
- connect(filterSyntaxComboBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(filterRegExpChanged()));
- connect(filterColumnComboBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(filterColumnChanged()));
- connect(filterCaseSensitivityCheckBox, SIGNAL(toggled(bool)),
- this, SLOT(filterRegExpChanged()));
- connect(sortCaseSensitivityCheckBox, SIGNAL(toggled(bool)),
- this, SLOT(sortChanged()));
+ connect(filterPatternLineEdit, &QLineEdit::textChanged,
+ this, &Window::filterRegExpChanged);
+
+ typedef void (QComboBox::*QComboIntSignal)(int);
+ connect(filterSyntaxComboBox, static_cast<QComboIntSignal>(&QComboBox::currentIndexChanged),
+ this, &Window::filterRegExpChanged);
+ connect(filterColumnComboBox, static_cast<QComboIntSignal>(&QComboBox::currentIndexChanged),
+ this, &Window::filterColumnChanged);
+ connect(filterCaseSensitivityCheckBox, &QAbstractButton::toggled,
+ this, &Window::filterRegExpChanged);
+ connect(sortCaseSensitivityCheckBox, &QAbstractButton::toggled,
+ this, &Window::sortChanged);
sourceGroupBox = new QGroupBox(tr("Original Model"));
proxyGroupBox = new QGroupBox(tr("Sorted/Filtered Model"));
diff --git a/examples/widgets/itemviews/chart/mainwindow.cpp b/examples/widgets/itemviews/chart/mainwindow.cpp
index 646b8a293a..9a3b372233 100644
--- a/examples/widgets/itemviews/chart/mainwindow.cpp
+++ b/examples/widgets/itemviews/chart/mainwindow.cpp
@@ -56,14 +56,14 @@ MainWindow::MainWindow()
setupModel();
setupViews();
- connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
- connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
- connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
+ connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
+ connect(saveAction, &QAction::triggered, this, &MainWindow::saveFile);
+ connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
menuBar()->addMenu(fileMenu);
statusBar();
- openFile(":/Charts/qtdata.cht");
+ loadFile(":/Charts/qtdata.cht");
setWindowTitle(tr("Chart"));
resize(870, 550);
@@ -99,17 +99,16 @@ void MainWindow::setupViews()
setCentralWidget(splitter);
}
-void MainWindow::openFile(const QString &path)
+void MainWindow::openFile()
{
- QString fileName;
- if (path.isNull())
- fileName = QFileDialog::getOpenFileName(this, tr("Choose a data file"), "", "*.cht");
- else
- fileName = path;
-
- if (fileName.isEmpty())
- return;
+ const QString fileName =
+ QFileDialog::getOpenFileName(this, tr("Choose a data file"), "", "*.cht");
+ if (!fileName.isEmpty())
+ loadFile(fileName);
+}
+void MainWindow::loadFile(const QString &fileName)
+{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text))
return;
diff --git a/examples/widgets/itemviews/chart/mainwindow.h b/examples/widgets/itemviews/chart/mainwindow.h
index 2fc47bb75b..523ad70441 100644
--- a/examples/widgets/itemviews/chart/mainwindow.h
+++ b/examples/widgets/itemviews/chart/mainwindow.h
@@ -57,12 +57,13 @@ public:
MainWindow();
private slots:
- void openFile(const QString &path = QString());
+ void openFile();
void saveFile();
private:
void setupModel();
void setupViews();
+ void loadFile(const QString &path);
QAbstractItemModel *model;
QAbstractItemView *pieChart;
diff --git a/examples/widgets/itemviews/combowidgetmapper/window.cpp b/examples/widgets/itemviews/combowidgetmapper/window.cpp
index d135ffb33f..3a6f649856 100644
--- a/examples/widgets/itemviews/combowidgetmapper/window.cpp
+++ b/examples/widgets/itemviews/combowidgetmapper/window.cpp
@@ -72,12 +72,12 @@ Window::Window(QWidget *parent)
//! [Set up the mapper]
//! [Set up connections and layouts]
- connect(previousButton, SIGNAL(clicked()),
- mapper, SLOT(toPrevious()));
- connect(nextButton, SIGNAL(clicked()),
- mapper, SLOT(toNext()));
- connect(mapper, SIGNAL(currentIndexChanged(int)),
- this, SLOT(updateButtons(int)));
+ connect(previousButton, &QAbstractButton::clicked,
+ mapper, &QDataWidgetMapper::toPrevious);
+ connect(nextButton, &QAbstractButton::clicked,
+ mapper, &QDataWidgetMapper::toNext);
+ connect(mapper, &QDataWidgetMapper::currentIndexChanged,
+ this, &Window::updateButtons);
QGridLayout *layout = new QGridLayout();
layout->addWidget(nameLabel, 0, 0, 1, 1);
diff --git a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp
index 6b5896f3c1..12019e606a 100644
--- a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp
+++ b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp
@@ -55,12 +55,12 @@ FilterWidget::FilterWidget(QWidget *parent)
, m_patternGroup(new QActionGroup(this))
{
setClearButtonEnabled(true);
- connect(this, SIGNAL(textChanged(QString)), this, SIGNAL(filterChanged()));
+ connect(this, &QLineEdit::textChanged, this, &FilterWidget::filterChanged);
QMenu *menu = new QMenu(this);
m_caseSensitivityAction = menu->addAction(tr("Case Sensitive"));
m_caseSensitivityAction->setCheckable(true);
- connect(m_caseSensitivityAction, SIGNAL(toggled(bool)), this, SIGNAL(filterChanged()));
+ connect(m_caseSensitivityAction, &QAction::toggled, this, &FilterWidget::filterChanged);
menu->addSeparator();
m_patternGroup->setExclusive(true);
@@ -77,7 +77,7 @@ FilterWidget::FilterWidget(QWidget *parent)
patternAction->setCheckable(true);
patternAction->setData(QVariant(int(QRegExp::Wildcard)));
m_patternGroup->addAction(patternAction);
- connect(m_patternGroup, SIGNAL(triggered(QAction*)), this, SIGNAL(filterChanged()));
+ connect(m_patternGroup, &QActionGroup::triggered, this, &FilterWidget::filterChanged);
const QIcon icon = QIcon(QPixmap(":/images/find.png"));
QToolButton *optionsButton = new QToolButton;
diff --git a/examples/widgets/itemviews/customsortfiltermodel/window.cpp b/examples/widgets/itemviews/customsortfiltermodel/window.cpp
index 8653df2a61..ff07dfe79c 100644
--- a/examples/widgets/itemviews/customsortfiltermodel/window.cpp
+++ b/examples/widgets/itemviews/customsortfiltermodel/window.cpp
@@ -66,7 +66,7 @@ Window::Window()
//! [3]
filterWidget = new FilterWidget;
filterWidget->setText("Grace|Sports");
- connect(filterWidget, SIGNAL(filterChanged()), this, SLOT(textFilterChanged()));
+ connect(filterWidget, &FilterWidget::filterChanged, this, &Window::textFilterChanged);
filterPatternLabel = new QLabel(tr("&Filter pattern:"));
filterPatternLabel->setBuddy(filterWidget);
@@ -81,13 +81,13 @@ Window::Window()
toLabel = new QLabel(tr("&To:"));
toLabel->setBuddy(toDateEdit);
- connect(filterWidget, SIGNAL(textChanged(QString)),
- this, SLOT(textFilterChanged()));
- connect(fromDateEdit, SIGNAL(dateChanged(QDate)),
- this, SLOT(dateFilterChanged()));
- connect(toDateEdit, SIGNAL(dateChanged(QDate)),
+ connect(filterWidget, &QLineEdit::textChanged,
+ this, &Window::textFilterChanged);
+ connect(fromDateEdit, &QDateTimeEdit::dateChanged,
+ this, &Window::dateFilterChanged);
+ connect(toDateEdit, &QDateTimeEdit::dateChanged,
//! [3] //! [4]
- this, SLOT(dateFilterChanged()));
+ this, &Window::dateFilterChanged);
//! [4]
//! [5]
diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp
index c7abe59c77..f138e27095 100644
--- a/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp
+++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp
@@ -60,19 +60,17 @@ MainWindow::MainWindow(QWidget *parent)
for (int column = 0; column < model->columnCount(); ++column)
view->resizeColumnToContents(column);
- connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
+ connect(exitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
- connect(view->selectionModel(),
- SIGNAL(selectionChanged(const QItemSelection &,
- const QItemSelection &)),
- this, SLOT(updateActions()));
+ connect(view->selectionModel(), &QItemSelectionModel::selectionChanged,
+ this, &MainWindow::updateActions);
- connect(actionsMenu, SIGNAL(aboutToShow()), this, SLOT(updateActions()));
- connect(insertRowAction, SIGNAL(triggered()), this, SLOT(insertRow()));
- connect(insertColumnAction, SIGNAL(triggered()), this, SLOT(insertColumn()));
- connect(removeRowAction, SIGNAL(triggered()), this, SLOT(removeRow()));
- connect(removeColumnAction, SIGNAL(triggered()), this, SLOT(removeColumn()));
- connect(insertChildAction, SIGNAL(triggered()), this, SLOT(insertChild()));
+ connect(actionsMenu, &QMenu::aboutToShow, this, &MainWindow::updateActions);
+ connect(insertRowAction, &QAction::triggered, this, &MainWindow::insertRow);
+ connect(insertColumnAction, &QAction::triggered, this, &MainWindow::insertColumn);
+ connect(removeRowAction, &QAction::triggered, this, &MainWindow::removeRow);
+ connect(removeColumnAction, &QAction::triggered, this, &MainWindow::removeColumn);
+ connect(insertChildAction, &QAction::triggered, this, &MainWindow::insertChild);
updateActions();
}
@@ -102,13 +100,13 @@ void MainWindow::insertChild()
updateActions();
}
-bool MainWindow::insertColumn(const QModelIndex &parent)
+bool MainWindow::insertColumn()
{
QAbstractItemModel *model = view->model();
int column = view->selectionModel()->currentIndex().column();
// Insert a column in the parent item.
- bool changed = model->insertColumn(column + 1, parent);
+ bool changed = model->insertColumn(column + 1);
if (changed)
model->setHeaderData(column + 1, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole);
@@ -133,15 +131,15 @@ void MainWindow::insertRow()
}
}
-bool MainWindow::removeColumn(const QModelIndex &parent)
+bool MainWindow::removeColumn()
{
QAbstractItemModel *model = view->model();
int column = view->selectionModel()->currentIndex().column();
// Insert columns in each child of the parent item.
- bool changed = model->removeColumn(column, parent);
+ bool changed = model->removeColumn(column);
- if (!parent.isValid() && changed)
+ if (changed)
updateActions();
return changed;
diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.h b/examples/widgets/itemviews/editabletreemodel/mainwindow.h
index 4626ecbc2a..4c164f88c1 100644
--- a/examples/widgets/itemviews/editabletreemodel/mainwindow.h
+++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.h
@@ -58,9 +58,9 @@ public slots:
private slots:
void insertChild();
- bool insertColumn(const QModelIndex &parent = QModelIndex());
+ bool insertColumn();
void insertRow();
- bool removeColumn(const QModelIndex &parent = QModelIndex());
+ bool removeColumn();
void removeRow();
};
diff --git a/examples/widgets/itemviews/fetchmore/window.cpp b/examples/widgets/itemviews/fetchmore/window.cpp
index eefa09622d..aa4e0adc90 100644
--- a/examples/widgets/itemviews/fetchmore/window.cpp
+++ b/examples/widgets/itemviews/fetchmore/window.cpp
@@ -59,12 +59,12 @@ Window::Window(QWidget *parent)
logViewer = new QTextBrowser;
logViewer->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
- connect(lineEdit, SIGNAL(textChanged(QString)),
- model, SLOT(setDirPath(QString)));
- connect(lineEdit, SIGNAL(textChanged(QString)),
- logViewer, SLOT(clear()));
- connect(model, SIGNAL(numberPopulated(int)),
- this, SLOT(updateLog(int)));
+ connect(lineEdit, &QLineEdit::textChanged,
+ model, &FileListModel::setDirPath);
+ connect(lineEdit, &QLineEdit::textChanged,
+ logViewer, &QTextEdit::clear);
+ connect(model, &FileListModel::numberPopulated,
+ this, &Window::updateLog);
QGridLayout *layout = new QGridLayout;
layout->addWidget(label, 0, 0);
diff --git a/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp b/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp
index 254786b16e..c2233abcc2 100644
--- a/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp
+++ b/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp
@@ -52,15 +52,15 @@ FreezeTableWidget::FreezeTableWidget(QAbstractItemModel * model)
init();
//connect the headers and scrollbars of both tableviews together
- connect(horizontalHeader(),SIGNAL(sectionResized(int,int,int)), this,
- SLOT(updateSectionWidth(int,int,int)));
- connect(verticalHeader(),SIGNAL(sectionResized(int,int,int)), this,
- SLOT(updateSectionHeight(int,int,int)));
-
- connect(frozenTableView->verticalScrollBar(), SIGNAL(valueChanged(int)),
- verticalScrollBar(), SLOT(setValue(int)));
- connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
- frozenTableView->verticalScrollBar(), SLOT(setValue(int)));
+ connect(horizontalHeader(),&QHeaderView::sectionResized, this,
+ &FreezeTableWidget::updateSectionWidth);
+ connect(verticalHeader(),&QHeaderView::sectionResized, this,
+ &FreezeTableWidget::updateSectionHeight);
+
+ connect(frozenTableView->verticalScrollBar(), &QAbstractSlider::valueChanged,
+ verticalScrollBar(), &QAbstractSlider::setValue);
+ connect(verticalScrollBar(), &QAbstractSlider::valueChanged,
+ frozenTableView->verticalScrollBar(), &QAbstractSlider::setValue);
}
diff --git a/examples/widgets/itemviews/pixelator/mainwindow.cpp b/examples/widgets/itemviews/pixelator/mainwindow.cpp
index a05880225b..bab130a2b2 100644
--- a/examples/widgets/itemviews/pixelator/mainwindow.cpp
+++ b/examples/widgets/itemviews/pixelator/mainwindow.cpp
@@ -98,15 +98,16 @@ MainWindow::MainWindow()
menuBar()->addSeparator();
menuBar()->addMenu(helpMenu);
- connect(openAction, SIGNAL(triggered()), this, SLOT(chooseImage()));
- connect(printAction, SIGNAL(triggered()), this, SLOT(printImage()));
- connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
- connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAboutBox()));
+ connect(openAction, &QAction::triggered, this, &MainWindow::chooseImage);
+ connect(printAction, &QAction::triggered, this, &MainWindow::printImage);
+ connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
+ connect(aboutAction, &QAction::triggered, this, &MainWindow::showAboutBox);
//! [4]
- connect(pixelSizeSpinBox, SIGNAL(valueChanged(int)),
- delegate, SLOT(setPixelSize(int)));
- connect(pixelSizeSpinBox, SIGNAL(valueChanged(int)),
- this, SLOT(updateView()));
+ typedef void (QSpinBox::*QSpinBoxIntSignal)(int);
+ connect(pixelSizeSpinBox, static_cast<QSpinBoxIntSignal>(&QSpinBox::valueChanged),
+ delegate, &PixelDelegate::setPixelSize);
+ connect(pixelSizeSpinBox, static_cast<QSpinBoxIntSignal>(&QSpinBox::valueChanged),
+ this, &MainWindow::updateView);
//! [4]
QHBoxLayout *controlsLayout = new QHBoxLayout;
diff --git a/examples/widgets/itemviews/puzzle/main.cpp b/examples/widgets/itemviews/puzzle/main.cpp
index 866c6f0d8b..a7980489a8 100644
--- a/examples/widgets/itemviews/puzzle/main.cpp
+++ b/examples/widgets/itemviews/puzzle/main.cpp
@@ -48,7 +48,7 @@ int main(int argc, char *argv[])
QApplication app(argc, argv);
MainWindow window;
- window.openImage(":/images/example.jpg");
+ window.loadImage(":/images/example.jpg");
window.show();
return app.exec();
}
diff --git a/examples/widgets/itemviews/puzzle/mainwindow.cpp b/examples/widgets/itemviews/puzzle/mainwindow.cpp
index 2e2a1d0ab5..5cd9a7f0df 100644
--- a/examples/widgets/itemviews/puzzle/mainwindow.cpp
+++ b/examples/widgets/itemviews/puzzle/mainwindow.cpp
@@ -57,26 +57,27 @@ MainWindow::MainWindow(QWidget *parent)
setWindowTitle(tr("Puzzle"));
}
-void MainWindow::openImage(const QString &path)
+void MainWindow::openImage()
{
- QString fileName = path;
-
- if (fileName.isNull()) {
- fileName = QFileDialog::getOpenFileName(this,
- tr("Open Image"), "", tr("Image Files (*.png *.jpg *.bmp)"));
- }
+ const QString fileName =
+ QFileDialog::getOpenFileName(this,
+ tr("Open Image"), QString(),
+ tr("Image Files (*.png *.jpg *.bmp)"));
+ if (!fileName.isEmpty())
+ loadImage(fileName);
+}
- if (!fileName.isEmpty()) {
- QPixmap newImage;
- if (!newImage.load(fileName)) {
- QMessageBox::warning(this, tr("Open Image"),
- tr("The image file could not be loaded."),
- QMessageBox::Cancel);
- return;
- }
- puzzleImage = newImage;
- setupPuzzle();
+void MainWindow::loadImage(const QString &fileName)
+{
+ QPixmap newImage;
+ if (!newImage.load(fileName)) {
+ QMessageBox::warning(this, tr("Open Image"),
+ tr("The image file could not be loaded."),
+ QMessageBox::Cancel);
+ return;
}
+ puzzleImage = newImage;
+ setupPuzzle();
}
void MainWindow::setCompleted()
@@ -116,9 +117,9 @@ void MainWindow::setupMenus()
QAction *restartAction = gameMenu->addAction(tr("&Restart"));
- connect(openAction, SIGNAL(triggered()), this, SLOT(openImage()));
- connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
- connect(restartAction, SIGNAL(triggered()), this, SLOT(setupPuzzle()));
+ connect(openAction, &QAction::triggered, this, &MainWindow::openImage);
+ connect(exitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
+ connect(restartAction, &QAction::triggered, this, &MainWindow::setupPuzzle);
}
void MainWindow::setupWidgets()
@@ -141,8 +142,8 @@ void MainWindow::setupWidgets()
PiecesModel *model = new PiecesModel(puzzleWidget->pieceSize(), this);
piecesList->setModel(model);
- connect(puzzleWidget, SIGNAL(puzzleCompleted()),
- this, SLOT(setCompleted()), Qt::QueuedConnection);
+ connect(puzzleWidget, &PuzzleWidget::puzzleCompleted,
+ this, &MainWindow::setCompleted, Qt::QueuedConnection);
frameLayout->addWidget(piecesList);
frameLayout->addWidget(puzzleWidget);
diff --git a/examples/widgets/itemviews/puzzle/mainwindow.h b/examples/widgets/itemviews/puzzle/mainwindow.h
index 86daf0af2d..440dd46377 100644
--- a/examples/widgets/itemviews/puzzle/mainwindow.h
+++ b/examples/widgets/itemviews/puzzle/mainwindow.h
@@ -58,7 +58,8 @@ public:
MainWindow(QWidget *parent = 0);
public slots:
- void openImage(const QString &path = QString());
+ void openImage();
+ void loadImage(const QString &path);
void setupPuzzle();
private slots:
diff --git a/examples/widgets/itemviews/simpledommodel/mainwindow.cpp b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp
index 4dc87dac1a..c11fb40a0e 100644
--- a/examples/widgets/itemviews/simpledommodel/mainwindow.cpp
+++ b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp
@@ -49,8 +49,8 @@
MainWindow::MainWindow() : QMainWindow(), model(0)
{
fileMenu = menuBar()->addMenu(tr("&File"));
- fileMenu->addAction(tr("&Open..."), this, SLOT(openFile()), QKeySequence::Open);
- fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit);
+ fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
+ fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);
model = new DomModel(QDomDocument(), this);
view = new QTreeView(this);
diff --git a/examples/widgets/itemviews/simplewidgetmapper/window.cpp b/examples/widgets/itemviews/simplewidgetmapper/window.cpp
index 9df004430b..0d99acc603 100644
--- a/examples/widgets/itemviews/simplewidgetmapper/window.cpp
+++ b/examples/widgets/itemviews/simplewidgetmapper/window.cpp
@@ -69,9 +69,9 @@ Window::Window(QWidget *parent)
mapper->addMapping(addressEdit, 1);
mapper->addMapping(ageSpinBox, 2);
- connect(previousButton, SIGNAL(clicked()), mapper, SLOT(toPrevious()));
- connect(nextButton, SIGNAL(clicked()), mapper, SLOT(toNext()));
- connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtons(int)));
+ connect(previousButton, &QAbstractButton::clicked, mapper, &QDataWidgetMapper::toPrevious);
+ connect(nextButton, &QAbstractButton::clicked, mapper, &QDataWidgetMapper::toNext);
+ connect(mapper, &QDataWidgetMapper::currentIndexChanged, this, &Window::updateButtons);
//! [Set up the mapper]
//! [Set up the layout]
diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp
index 02e635b87a..41b51c1071 100644
--- a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp
+++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp
@@ -73,17 +73,17 @@ SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent)
setCentralWidget(table);
statusBar();
- connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
- this, SLOT(updateStatus(QTableWidgetItem*)));
- connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
- this, SLOT(updateColor(QTableWidgetItem*)));
- connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
- this, SLOT(updateLineEdit(QTableWidgetItem*)));
- connect(table, SIGNAL(itemChanged(QTableWidgetItem*)),
- this, SLOT(updateStatus(QTableWidgetItem*)));
- connect(formulaInput, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
- connect(table, SIGNAL(itemChanged(QTableWidgetItem*)),
- this, SLOT(updateLineEdit(QTableWidgetItem*)));
+ connect(table, &QTableWidget::currentItemChanged,
+ this, &SpreadSheet::updateStatus);
+ connect(table, &QTableWidget::currentItemChanged,
+ this, &SpreadSheet::updateColor);
+ connect(table, &QTableWidget::currentItemChanged,
+ this, &SpreadSheet::updateLineEdit);
+ connect(table, &QTableWidget::itemChanged,
+ this, &SpreadSheet::updateStatus);
+ connect(formulaInput, &QLineEdit::returnPressed, this, &SpreadSheet::returnPressed);
+ connect(table, &QTableWidget::itemChanged,
+ this, &SpreadSheet::updateLineEdit);
setWindowTitle(tr("Spreadsheet"));
}
@@ -91,43 +91,43 @@ SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent)
void SpreadSheet::createActions()
{
cell_sumAction = new QAction(tr("Sum"), this);
- connect(cell_sumAction, SIGNAL(triggered()), this, SLOT(actionSum()));
+ connect(cell_sumAction, &QAction::triggered, this, &SpreadSheet::actionSum);
cell_addAction = new QAction(tr("&Add"), this);
cell_addAction->setShortcut(Qt::CTRL | Qt::Key_Plus);
- connect(cell_addAction, SIGNAL(triggered()), this, SLOT(actionAdd()));
+ connect(cell_addAction, &QAction::triggered, this, &SpreadSheet::actionAdd);
cell_subAction = new QAction(tr("&Subtract"), this);
cell_subAction->setShortcut(Qt::CTRL | Qt::Key_Minus);
- connect(cell_subAction, SIGNAL(triggered()), this, SLOT(actionSubtract()));
+ connect(cell_subAction, &QAction::triggered, this, &SpreadSheet::actionSubtract);
cell_mulAction = new QAction(tr("&Multiply"), this);
cell_mulAction->setShortcut(Qt::CTRL | Qt::Key_multiply);
- connect(cell_mulAction, SIGNAL(triggered()), this, SLOT(actionMultiply()));
+ connect(cell_mulAction, &QAction::triggered, this, &SpreadSheet::actionMultiply);
cell_divAction = new QAction(tr("&Divide"), this);
cell_divAction->setShortcut(Qt::CTRL | Qt::Key_division);
- connect(cell_divAction, SIGNAL(triggered()), this, SLOT(actionDivide()));
+ connect(cell_divAction, &QAction::triggered, this, &SpreadSheet::actionDivide);
fontAction = new QAction(tr("Font..."), this);
fontAction->setShortcut(Qt::CTRL | Qt::Key_F);
- connect(fontAction, SIGNAL(triggered()), this, SLOT(selectFont()));
+ connect(fontAction, &QAction::triggered, this, &SpreadSheet::selectFont);
colorAction = new QAction(QPixmap(16, 16), tr("Background &Color..."), this);
- connect(colorAction, SIGNAL(triggered()), this, SLOT(selectColor()));
+ connect(colorAction, &QAction::triggered, this, &SpreadSheet::selectColor);
clearAction = new QAction(tr("Clear"), this);
clearAction->setShortcut(Qt::Key_Delete);
- connect(clearAction, SIGNAL(triggered()), this, SLOT(clear()));
+ connect(clearAction, &QAction::triggered, this, &SpreadSheet::clear);
aboutSpreadSheet = new QAction(tr("About Spreadsheet"), this);
- connect(aboutSpreadSheet, SIGNAL(triggered()), this, SLOT(showAbout()));
+ connect(aboutSpreadSheet, &QAction::triggered, this, &SpreadSheet::showAbout);
exitAction = new QAction(tr("E&xit"), this);
- connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
+ connect(exitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
printAction = new QAction(tr("&Print"), this);
- connect(printAction, SIGNAL(triggered()), this, SLOT(print()));
+ connect(printAction, &QAction::triggered, this, &SpreadSheet::print);
firstSeparator = new QAction(this);
firstSeparator->setSeparator(true);
@@ -309,11 +309,11 @@ bool SpreadSheet::runInputDialog(const QString &title,
outColInput.setCurrentIndex(outCol);
QPushButton cancelButton(tr("Cancel"), &addDialog);
- connect(&cancelButton, SIGNAL(clicked()), &addDialog, SLOT(reject()));
+ connect(&cancelButton, &QAbstractButton::clicked, &addDialog, &QDialog::reject);
QPushButton okButton(tr("OK"), &addDialog);
okButton.setDefault(true);
- connect(&okButton, SIGNAL(clicked()), &addDialog, SLOT(accept()));
+ connect(&okButton, &QAbstractButton::clicked, &addDialog, &QDialog::accept);
QHBoxLayout *buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch(1);
@@ -625,7 +625,7 @@ void SpreadSheet::print()
QPrintPreviewDialog dlg(&printer);
PrintView view;
view.setModel(table->model());
- connect(&dlg, SIGNAL(paintRequested(QPrinter*)), &view, SLOT(print(QPrinter*)));
+ connect(&dlg, &QPrintPreviewDialog::paintRequested, &view, &PrintView::print);
dlg.exec();
#endif
}
diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
index d056e3f8e4..a7404fe159 100644
--- a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
+++ b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
@@ -63,7 +63,7 @@ QWidget *SpreadSheetDelegate::createEditor(QWidget *parent,
QCompleter *autoComplete = new QCompleter(allStrings);
editor->setCompleter(autoComplete);
- connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
+ connect(editor, &QLineEdit::editingFinished, this, &SpreadSheetDelegate::commitAndCloseEditor);
return editor;
}
diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.cpp b/examples/widgets/itemviews/stardelegate/stardelegate.cpp
index 48f6eb543b..a9e8f71699 100644
--- a/examples/widgets/itemviews/stardelegate/stardelegate.cpp
+++ b/examples/widgets/itemviews/stardelegate/stardelegate.cpp
@@ -83,8 +83,8 @@ QWidget *StarDelegate::createEditor(QWidget *parent,
{
if (index.data().canConvert<StarRating>()) {
StarEditor *editor = new StarEditor(parent);
- connect(editor, SIGNAL(editingFinished()),
- this, SLOT(commitAndCloseEditor()));
+ connect(editor, &StarEditor::editingFinished,
+ this, &StarDelegate::commitAndCloseEditor);
return editor;
} else {
return QStyledItemDelegate::createEditor(parent, option, index);
diff --git a/examples/widgets/mainwindows/application/main.cpp b/examples/widgets/mainwindows/application/main.cpp
index 41913db07e..73c1cf57d3 100644
--- a/examples/widgets/mainwindows/application/main.cpp
+++ b/examples/widgets/mainwindows/application/main.cpp
@@ -40,6 +40,8 @@
//! [0]
#include <QApplication>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
#include "mainwindow.h"
@@ -48,9 +50,19 @@ int main(int argc, char *argv[])
Q_INIT_RESOURCE(application);
QApplication app(argc, argv);
- app.setOrganizationName("QtProject");
- app.setApplicationName("Application Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationName("Application Example");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ parser.addPositionalArgument("file", "The file to open.");
+ parser.process(app);
+
MainWindow mainWin;
+ if (!parser.positionalArguments().isEmpty())
+ mainWin.loadFile(parser.positionalArguments().first());
mainWin.show();
return app.exec();
}
diff --git a/examples/widgets/mainwindows/application/mainwindow.cpp b/examples/widgets/mainwindows/application/mainwindow.cpp
index d3f9c7645e..86dfae166f 100644
--- a/examples/widgets/mainwindows/application/mainwindow.cpp
+++ b/examples/widgets/mainwindows/application/mainwindow.cpp
@@ -46,22 +46,20 @@
//! [1]
MainWindow::MainWindow()
+ : textEdit(new QPlainTextEdit)
//! [1] //! [2]
{
- textEdit = new QPlainTextEdit;
setCentralWidget(textEdit);
createActions();
- createMenus();
- createToolBars();
createStatusBar();
readSettings();
- connect(textEdit->document(), SIGNAL(contentsChanged()),
- this, SLOT(documentWasModified()));
+ connect(textEdit->document(), &QTextDocument::contentsChanged,
+ this, &MainWindow::documentWasModified);
- setCurrentFile("");
+ setCurrentFile(QString());
setUnifiedTitleAndToolBarOnMac(true);
}
//! [2]
@@ -85,7 +83,7 @@ void MainWindow::newFile()
{
if (maybeSave()) {
textEdit->clear();
- setCurrentFile("");
+ setCurrentFile(QString());
}
}
//! [6]
@@ -121,13 +119,9 @@ bool MainWindow::saveAs()
QFileDialog dialog(this);
dialog.setWindowModality(Qt::WindowModal);
dialog.setAcceptMode(QFileDialog::AcceptSave);
- QStringList files;
- if (dialog.exec())
- files = dialog.selectedFiles();
- else
+ if (dialog.exec() != QDialog::Accepted)
return false;
-
- return saveFile(files.at(0));
+ return saveFile(dialog.selectedFiles().first());
}
//! [12]
@@ -154,121 +148,108 @@ void MainWindow::documentWasModified()
void MainWindow::createActions()
//! [17] //! [18]
{
- newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
+
+ QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
+ QToolBar *fileToolBar = addToolBar(tr("File"));
+ const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(":/images/new.png"));
+ QAction *newAct = new QAction(newIcon, tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
- connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
+ connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
+ fileMenu->addAction(newAct);
+ fileToolBar->addAction(newAct);
//! [19]
- openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
+ const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png"));
+ QAction *openAct = new QAction(openIcon, tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
+ connect(openAct, &QAction::triggered, this, &MainWindow::open);
+ fileMenu->addAction(openAct);
+ fileToolBar->addAction(openAct);
//! [18] //! [19]
- saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
+ const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png"));
+ QAction *saveAct = new QAction(saveIcon, tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::save);
+ fileMenu->addAction(saveAct);
+ fileToolBar->addAction(saveAct);
- saveAsAct = new QAction(tr("Save &As..."), this);
+ const QIcon saveAsIcon = QIcon::fromTheme("document-save-as");
+ QAction *saveAsAct = fileMenu->addAction(saveAsIcon, tr("Save &As..."), this, &MainWindow::saveAs);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
- connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
//! [20]
- exitAct = new QAction(tr("E&xit"), this);
+
+ fileMenu->addSeparator();
+
+ const QIcon exitIcon = QIcon::fromTheme("application-exit");
+ QAction *exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), this, &QWidget::close);
exitAct->setShortcuts(QKeySequence::Quit);
//! [20]
exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
//! [21]
- cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
+ QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
+ QToolBar *editToolBar = addToolBar(tr("Edit"));
+//!
+#ifndef QT_NO_CLIPBOARD
+ const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(":/images/cut.png"));
+ QAction *cutAct = new QAction(cutIcon, tr("Cu&t"), this);
//! [21]
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
- connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));
+ connect(cutAct, &QAction::triggered, textEdit, &QPlainTextEdit::cut);
+ editMenu->addAction(cutAct);
+ editToolBar->addAction(cutAct);
- copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
+ const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(":/images/copy.png"));
+ QAction *copyAct = new QAction(copyIcon, tr("&Copy"), this);
copyAct->setShortcuts(QKeySequence::Copy);
copyAct->setStatusTip(tr("Copy the current selection's contents to the "
"clipboard"));
- connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));
+ connect(copyAct, &QAction::triggered, textEdit, &QPlainTextEdit::copy);
+ editMenu->addAction(copyAct);
+ editToolBar->addAction(copyAct);
- pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
+ const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(":/images/paste.png"));
+ QAction *pasteAct = new QAction(pasteIcon, tr("&Paste"), this);
pasteAct->setShortcuts(QKeySequence::Paste);
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
"selection"));
- connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));
+ connect(pasteAct, &QAction::triggered, textEdit, &QPlainTextEdit::paste);
+ editMenu->addAction(pasteAct);
+ editToolBar->addAction(pasteAct);
+
+ menuBar()->addSeparator();
+
+#endif // !QT_NO_CLIPBOARD
- aboutAct = new QAction(tr("&About"), this);
+ QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
+ QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about);
aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
//! [22]
- aboutQtAct = new QAction(tr("About &Qt"), this);
+
+ QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
//! [22]
//! [23]
+#ifndef QT_NO_CLIPBOARD
cutAct->setEnabled(false);
//! [23] //! [24]
copyAct->setEnabled(false);
- connect(textEdit, SIGNAL(copyAvailable(bool)),
- cutAct, SLOT(setEnabled(bool)));
- connect(textEdit, SIGNAL(copyAvailable(bool)),
- copyAct, SLOT(setEnabled(bool)));
+ connect(textEdit, &QPlainTextEdit::copyAvailable, cutAct, &QAction::setEnabled);
+ connect(textEdit, &QPlainTextEdit::copyAvailable, copyAct, &QAction::setEnabled);
+#endif // !QT_NO_CLIPBOARD
}
//! [24]
-//! [25] //! [26]
-void MainWindow::createMenus()
-//! [25] //! [27]
-{
- fileMenu = menuBar()->addMenu(tr("&File"));
- fileMenu->addAction(newAct);
-//! [28]
- fileMenu->addAction(openAct);
-//! [28]
- fileMenu->addAction(saveAct);
-//! [26]
- fileMenu->addAction(saveAsAct);
- fileMenu->addSeparator();
- fileMenu->addAction(exitAct);
-
- editMenu = menuBar()->addMenu(tr("&Edit"));
- editMenu->addAction(cutAct);
- editMenu->addAction(copyAct);
- editMenu->addAction(pasteAct);
-
- menuBar()->addSeparator();
-
- helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-}
-//! [27]
-
-//! [29] //! [30]
-void MainWindow::createToolBars()
-{
- fileToolBar = addToolBar(tr("File"));
- fileToolBar->addAction(newAct);
-//! [29] //! [31]
- fileToolBar->addAction(openAct);
-//! [31]
- fileToolBar->addAction(saveAct);
-
- editToolBar = addToolBar(tr("Edit"));
- editToolBar->addAction(cutAct);
- editToolBar->addAction(copyAct);
- editToolBar->addAction(pasteAct);
-}
-//! [30]
-
//! [32]
void MainWindow::createStatusBar()
//! [32] //! [33]
@@ -281,11 +262,16 @@ void MainWindow::createStatusBar()
void MainWindow::readSettings()
//! [34] //! [36]
{
- QSettings settings("QtProject", "Application Example");
- QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
- QSize size = settings.value("size", QSize(400, 400)).toSize();
- resize(size);
- move(pos);
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
+ if (geometry.isEmpty()) {
+ const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
+ resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
+ move((availableGeometry.width() - width()) / 2,
+ (availableGeometry.height() - height()) / 2);
+ } else {
+ restoreGeometry(geometry);
+ }
}
//! [35] //! [36]
@@ -293,9 +279,8 @@ void MainWindow::readSettings()
void MainWindow::writeSettings()
//! [37] //! [39]
{
- QSettings settings("QtProject", "Application Example");
- settings.setValue("pos", pos());
- settings.setValue("size", size());
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ settings.setValue("geometry", saveGeometry());
}
//! [38] //! [39]
@@ -303,16 +288,20 @@ void MainWindow::writeSettings()
bool MainWindow::maybeSave()
//! [40] //! [41]
{
- if (textEdit->document()->isModified()) {
- QMessageBox::StandardButton ret;
- ret = QMessageBox::warning(this, tr("Application"),
- tr("The document has been modified.\n"
- "Do you want to save your changes?"),
- QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
- if (ret == QMessageBox::Save)
- return save();
- else if (ret == QMessageBox::Cancel)
- return false;
+ if (!textEdit->document()->isModified())
+ return true;
+ const QMessageBox::StandardButton ret
+ = QMessageBox::warning(this, tr("Application"),
+ tr("The document has been modified.\n"
+ "Do you want to save your changes?"),
+ QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
+ switch (ret) {
+ case QMessageBox::Save:
+ return save();
+ case QMessageBox::Cancel:
+ return false;
+ default:
+ break;
}
return true;
}
@@ -326,8 +315,7 @@ void MainWindow::loadFile(const QString &fileName)
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Application"),
tr("Cannot read file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName), file.errorString()));
return;
}
@@ -353,8 +341,8 @@ bool MainWindow::saveFile(const QString &fileName)
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Application"),
tr("Cannot write file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName),
+ file.errorString()));
return false;
}
diff --git a/examples/widgets/mainwindows/application/mainwindow.h b/examples/widgets/mainwindows/application/mainwindow.h
index cb791abf00..08b4aa17f5 100644
--- a/examples/widgets/mainwindows/application/mainwindow.h
+++ b/examples/widgets/mainwindows/application/mainwindow.h
@@ -57,6 +57,8 @@ class MainWindow : public QMainWindow
public:
MainWindow();
+ void loadFile(const QString &fileName);
+
protected:
void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;
@@ -70,35 +72,16 @@ private slots:
private:
void createActions();
- void createMenus();
- void createToolBars();
void createStatusBar();
void readSettings();
void writeSettings();
bool maybeSave();
- void loadFile(const QString &fileName);
bool saveFile(const QString &fileName);
void setCurrentFile(const QString &fileName);
QString strippedName(const QString &fullFileName);
QPlainTextEdit *textEdit;
QString curFile;
-
- QMenu *fileMenu;
- QMenu *editMenu;
- QMenu *helpMenu;
- QToolBar *fileToolBar;
- QToolBar *editToolBar;
- QAction *newAct;
- QAction *openAct;
- QAction *saveAct;
- QAction *saveAsAct;
- QAction *exitAct;
- QAction *cutAct;
- QAction *copyAct;
- QAction *pasteAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
};
//! [0]
diff --git a/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp b/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp
index 20c2bd1c70..c0472b537c 100644
--- a/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp
+++ b/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp
@@ -49,13 +49,11 @@
//! [1]
MainWindow::MainWindow()
+ : textEdit(new QTextEdit)
{
- textEdit = new QTextEdit;
setCentralWidget(textEdit);
createActions();
- createMenus();
- createToolBars();
createStatusBar();
createDockWindows();
@@ -135,17 +133,17 @@ void MainWindow::print()
//! [4]
void MainWindow::save()
{
+ QMimeDatabase mimeDatabase;
QString fileName = QFileDialog::getSaveFileName(this,
tr("Choose a file name"), ".",
- tr("HTML (*.html *.htm)"));
+ mimeDatabase.mimeTypeForName("text/html").filterString());
if (fileName.isEmpty())
return;
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Dock Widgets"),
tr("Cannot write file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName), file.errorString()));
return;
}
@@ -222,71 +220,60 @@ void MainWindow::about()
void MainWindow::createActions()
{
- newLetterAct = new QAction(QIcon(":/images/new.png"), tr("&New Letter"),
- this);
+ QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
+ QToolBar *fileToolBar = addToolBar(tr("File"));
+
+ const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(":/images/new.png"));
+ QAction *newLetterAct = new QAction(newIcon, tr("&New Letter"), this);
newLetterAct->setShortcuts(QKeySequence::New);
newLetterAct->setStatusTip(tr("Create a new form letter"));
- connect(newLetterAct, SIGNAL(triggered()), this, SLOT(newLetter()));
+ connect(newLetterAct, &QAction::triggered, this, &MainWindow::newLetter);
+ fileMenu->addAction(newLetterAct);
+ fileToolBar->addAction(newLetterAct);
- saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save..."), this);
+ const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png"));
+ QAction *saveAct = new QAction(saveIcon, tr("&Save..."), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the current form letter"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::save);
+ fileMenu->addAction(saveAct);
+ fileToolBar->addAction(saveAct);
- printAct = new QAction(QIcon(":/images/print.png"), tr("&Print..."), this);
+ const QIcon printIcon = QIcon::fromTheme("document-print", QIcon(":/images/print.png"));
+ QAction *printAct = new QAction(printIcon, tr("&Print..."), this);
printAct->setShortcuts(QKeySequence::Print);
printAct->setStatusTip(tr("Print the current form letter"));
- connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
+ connect(printAct, &QAction::triggered, this, &MainWindow::print);
+ fileMenu->addAction(printAct);
+ fileToolBar->addAction(printAct);
- undoAct = new QAction(QIcon(":/images/undo.png"), tr("&Undo"), this);
- undoAct->setShortcuts(QKeySequence::Undo);
- undoAct->setStatusTip(tr("Undo the last editing action"));
- connect(undoAct, SIGNAL(triggered()), this, SLOT(undo()));
+ fileMenu->addSeparator();
- quitAct = new QAction(tr("&Quit"), this);
+ QAction *quitAct = fileMenu->addAction(tr("&Quit"), this, &QWidget::close);
quitAct->setShortcuts(QKeySequence::Quit);
quitAct->setStatusTip(tr("Quit the application"));
- connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));
-
- aboutAct = new QAction(tr("&About"), this);
- aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
-
- aboutQtAct = new QAction(tr("About &Qt"), this);
- aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
-}
-
-void MainWindow::createMenus()
-{
- fileMenu = menuBar()->addMenu(tr("&File"));
- fileMenu->addAction(newLetterAct);
- fileMenu->addAction(saveAct);
- fileMenu->addAction(printAct);
- fileMenu->addSeparator();
- fileMenu->addAction(quitAct);
- editMenu = menuBar()->addMenu(tr("&Edit"));
+ QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
+ QToolBar *editToolBar = addToolBar(tr("Edit"));
+ const QIcon undoIcon = QIcon::fromTheme("edit-undo", QIcon(":/images/undo.png"));
+ QAction *undoAct = new QAction(undoIcon, tr("&Undo"), this);
+ undoAct->setShortcuts(QKeySequence::Undo);
+ undoAct->setStatusTip(tr("Undo the last editing action"));
+ connect(undoAct, &QAction::triggered, this, &MainWindow::undo);
editMenu->addAction(undoAct);
+ editToolBar->addAction(undoAct);
viewMenu = menuBar()->addMenu(tr("&View"));
menuBar()->addSeparator();
- helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-}
+ QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
-void MainWindow::createToolBars()
-{
- fileToolBar = addToolBar(tr("File"));
- fileToolBar->addAction(newLetterAct);
- fileToolBar->addAction(saveAct);
- fileToolBar->addAction(printAct);
+ QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about);
+ aboutAct->setStatusTip(tr("Show the application's About box"));
- editToolBar = addToolBar(tr("Edit"));
- editToolBar->addAction(undoAct);
+ QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
+ aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
}
//! [8]
@@ -337,9 +324,9 @@ void MainWindow::createDockWindows()
addDockWidget(Qt::RightDockWidgetArea, dock);
viewMenu->addAction(dock->toggleViewAction());
- connect(customerList, SIGNAL(currentTextChanged(QString)),
- this, SLOT(insertCustomer(QString)));
- connect(paragraphsList, SIGNAL(currentTextChanged(QString)),
- this, SLOT(addParagraph(QString)));
+ connect(customerList, &QListWidget::currentTextChanged,
+ this, &MainWindow::insertCustomer);
+ connect(paragraphsList, &QListWidget::currentTextChanged,
+ this, &MainWindow::addParagraph);
}
//! [9]
diff --git a/examples/widgets/mainwindows/dockwidgets/mainwindow.h b/examples/widgets/mainwindows/dockwidgets/mainwindow.h
index 2fb161a20b..c244febf9a 100644
--- a/examples/widgets/mainwindows/dockwidgets/mainwindow.h
+++ b/examples/widgets/mainwindows/dockwidgets/mainwindow.h
@@ -69,8 +69,6 @@ private slots:
private:
void createActions();
- void createMenus();
- void createToolBars();
void createStatusBar();
void createDockWindows();
@@ -78,19 +76,7 @@ private:
QListWidget *customerList;
QListWidget *paragraphsList;
- QMenu *fileMenu;
- QMenu *editMenu;
QMenu *viewMenu;
- QMenu *helpMenu;
- QToolBar *fileToolBar;
- QToolBar *editToolBar;
- QAction *newLetterAct;
- QAction *saveAct;
- QAction *printAct;
- QAction *undoAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
- QAction *quitAct;
};
//! [0]
diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp
index 408f6c4b0f..d746bbe8d3 100644
--- a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp
+++ b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp
@@ -42,6 +42,7 @@
#include <QImage>
#include <QColor>
#include <QDialog>
+#include <QDialogButtonBox>
#include <QGridLayout>
#include <QSpinBox>
#include <QLabel>
@@ -57,15 +58,15 @@ QColor bgColorForName(const QString &name)
{
if (name == "Black")
return QColor("#D8D8D8");
- else if (name == "White")
+ if (name == "White")
return QColor("#F1F1F1");
- else if (name == "Red")
+ if (name == "Red")
return QColor("#F1D8D8");
- else if (name == "Green")
+ if (name == "Green")
return QColor("#D8E4D8");
- else if (name == "Blue")
+ if (name == "Blue")
return QColor("#D8D8F1");
- else if (name == "Yellow")
+ if (name == "Yellow")
return QColor("#F1F0D8");
return QColor(name).light(110);
}
@@ -74,15 +75,15 @@ QColor fgColorForName(const QString &name)
{
if (name == "Black")
return QColor("#6C6C6C");
- else if (name == "White")
+ if (name == "White")
return QColor("#F8F8F8");
- else if (name == "Red")
+ if (name == "Red")
return QColor("#F86C6C");
- else if (name == "Green")
+ if (name == "Green")
return QColor("#6CB26C");
- else if (name == "Blue")
+ if (name == "Blue")
return QColor("#6C6CF8");
- else if (name == "Yellow")
+ if (name == "Yellow")
return QColor("#F8F76C");
return QColor(name);
}
@@ -91,10 +92,10 @@ class ColorDock : public QFrame
{
Q_OBJECT
public:
- ColorDock(const QString &c, QWidget *parent);
+ explicit ColorDock(const QString &c, QWidget *parent);
- virtual QSize sizeHint() const Q_DECL_OVERRIDE;
- virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE;
+ QSize sizeHint() const Q_DECL_OVERRIDE { return szHint; }
+ QSize minimumSizeHint() const Q_DECL_OVERRIDE { return minSzHint; }
void setCustomSizeHint(const QSize &size);
@@ -103,28 +104,22 @@ public slots:
protected:
void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
- QString color;
- QSize szHint, minSzHint;
+
+private:
+ const QString color;
+ QSize szHint;
+ QSize minSzHint;
};
ColorDock::ColorDock(const QString &c, QWidget *parent)
- : QFrame(parent) , color(c)
+ : QFrame(parent)
+ , color(c)
+ , szHint(-1, -1)
+ , minSzHint(125, 75)
{
QFont font = this->font();
font.setPointSize(8);
setFont(font);
- szHint = QSize(-1, -1);
- minSzHint = QSize(125, 75);
-}
-
-QSize ColorDock::sizeHint() const
-{
- return szHint;
-}
-
-QSize ColorDock::minimumSizeHint() const
-{
- return minSzHint;
}
void ColorDock::paintEvent(QPaintEvent *)
@@ -178,6 +173,7 @@ static QSpinBox *createSpinBox(int value, QWidget *parent, int max = 1000)
void ColorDock::changeSizeHints()
{
QDialog dialog(this);
+ dialog.setWindowFlags(dialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
dialog.setWindowTitle(color);
QVBoxLayout *topLayout = new QVBoxLayout(&dialog);
@@ -188,7 +184,7 @@ void ColorDock::changeSizeHints()
inputLayout->addWidget(new QLabel(tr("Size Hint:"), &dialog), 0, 0);
inputLayout->addWidget(new QLabel(tr("Min Size Hint:"), &dialog), 1, 0);
inputLayout->addWidget(new QLabel(tr("Max Size:"), &dialog), 2, 0);
- inputLayout->addWidget(new QLabel(tr("Dockwgt Max Size:"), &dialog), 3, 0);
+ inputLayout->addWidget(new QLabel(tr("Dock Widget Max Size:"), &dialog), 3, 0);
QSpinBox *szHintW = createSpinBox(szHint.width(), &dialog);
inputLayout->addWidget(szHintW, 0, 1);
@@ -217,19 +213,13 @@ void ColorDock::changeSizeHints()
topLayout->addStretch();
- QHBoxLayout *buttonBox = new QHBoxLayout();
- topLayout->addLayout(buttonBox);
+ QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
+ connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::reject);
- QPushButton *okButton = new QPushButton(tr("Ok"), &dialog);
- QPushButton *cancelButton = new QPushButton(tr("Cancel"), &dialog);
- connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept()));
- connect(cancelButton, SIGNAL(clicked()), &dialog, SLOT(reject()));
- buttonBox->addStretch();
- buttonBox->addWidget(cancelButton);
- buttonBox->addWidget(okButton);
+ topLayout->addWidget(buttonBox);
-
- if (!dialog.exec())
+ if (dialog.exec() != QDialog::Accepted)
return;
szHint = QSize(szHintW->value(), szHintH->value());
@@ -244,63 +234,62 @@ void ColorDock::changeSizeHints()
void ColorDock::setCustomSizeHint(const QSize &size)
{
- szHint = size;
- updateGeometry();
+ if (szHint != size) {
+ szHint = size;
+ updateGeometry();
+ }
}
-ColorSwatch::ColorSwatch(const QString &colorName, QWidget *parent, Qt::WindowFlags flags)
- : QDockWidget(parent, flags)
+ColorSwatch::ColorSwatch(const QString &colorName, QMainWindow *parent, Qt::WindowFlags flags)
+ : QDockWidget(parent, flags), mainWindow(parent)
{
setObjectName(colorName + QLatin1String(" Dock Widget"));
setWindowTitle(objectName() + QLatin1String(" [*]"));
- QFrame *swatch = new ColorDock(colorName, this);
+ ColorDock *swatch = new ColorDock(colorName, this);
swatch->setFrameStyle(QFrame::Box | QFrame::Sunken);
setWidget(swatch);
- changeSizeHintsAction = new QAction(tr("Change Size Hints"), this);
- connect(changeSizeHintsAction, SIGNAL(triggered()), swatch, SLOT(changeSizeHints()));
-
closableAction = new QAction(tr("Closable"), this);
closableAction->setCheckable(true);
- connect(closableAction, SIGNAL(triggered(bool)), SLOT(changeClosable(bool)));
+ connect(closableAction, &QAction::triggered, this, &ColorSwatch::changeClosable);
movableAction = new QAction(tr("Movable"), this);
movableAction->setCheckable(true);
- connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool)));
+ connect(movableAction, &QAction::triggered, this, &ColorSwatch::changeMovable);
floatableAction = new QAction(tr("Floatable"), this);
floatableAction->setCheckable(true);
- connect(floatableAction, SIGNAL(triggered(bool)), SLOT(changeFloatable(bool)));
+ connect(floatableAction, &QAction::triggered, this, &ColorSwatch::changeFloatable);
verticalTitleBarAction = new QAction(tr("Vertical title bar"), this);
verticalTitleBarAction->setCheckable(true);
- connect(verticalTitleBarAction, SIGNAL(triggered(bool)),
- SLOT(changeVerticalTitleBar(bool)));
+ connect(verticalTitleBarAction, &QAction::triggered,
+ this, &ColorSwatch::changeVerticalTitleBar);
floatingAction = new QAction(tr("Floating"), this);
floatingAction->setCheckable(true);
- connect(floatingAction, SIGNAL(triggered(bool)), SLOT(changeFloating(bool)));
+ connect(floatingAction, &QAction::triggered, this, &ColorSwatch::changeFloating);
allowedAreasActions = new QActionGroup(this);
allowedAreasActions->setExclusive(false);
allowLeftAction = new QAction(tr("Allow on Left"), this);
allowLeftAction->setCheckable(true);
- connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool)));
+ connect(allowLeftAction, &QAction::triggered, this, &ColorSwatch::allowLeft);
allowRightAction = new QAction(tr("Allow on Right"), this);
allowRightAction->setCheckable(true);
- connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool)));
+ connect(allowRightAction, &QAction::triggered, this, &ColorSwatch::allowRight);
allowTopAction = new QAction(tr("Allow on Top"), this);
allowTopAction->setCheckable(true);
- connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool)));
+ connect(allowTopAction, &QAction::triggered, this, &ColorSwatch::allowTop);
allowBottomAction = new QAction(tr("Allow on Bottom"), this);
allowBottomAction->setCheckable(true);
- connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool)));
+ connect(allowBottomAction, &QAction::triggered, this, &ColorSwatch::allowBottom);
allowedAreasActions->addAction(allowLeftAction);
allowedAreasActions->addAction(allowRightAction);
@@ -312,56 +301,56 @@ ColorSwatch::ColorSwatch(const QString &colorName, QWidget *parent, Qt::WindowFl
leftAction = new QAction(tr("Place on Left") , this);
leftAction->setCheckable(true);
- connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool)));
+ connect(leftAction, &QAction::triggered, this, &ColorSwatch::placeLeft);
rightAction = new QAction(tr("Place on Right") , this);
rightAction->setCheckable(true);
- connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool)));
+ connect(rightAction, &QAction::triggered, this, &ColorSwatch::placeRight);
topAction = new QAction(tr("Place on Top") , this);
topAction->setCheckable(true);
- connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool)));
+ connect(topAction, &QAction::triggered, this, &ColorSwatch::placeTop);
bottomAction = new QAction(tr("Place on Bottom") , this);
bottomAction->setCheckable(true);
- connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool)));
+ connect(bottomAction, &QAction::triggered, this, &ColorSwatch::placeBottom);
areaActions->addAction(leftAction);
areaActions->addAction(rightAction);
areaActions->addAction(topAction);
areaActions->addAction(bottomAction);
- connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool)));
+ connect(movableAction, &QAction::triggered, areaActions, &QActionGroup::setEnabled);
- connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool)));
+ connect(movableAction, &QAction::triggered, allowedAreasActions, &QActionGroup::setEnabled);
- connect(floatableAction, SIGNAL(triggered(bool)), floatingAction, SLOT(setEnabled(bool)));
+ connect(floatableAction, &QAction::triggered, floatingAction, &QAction::setEnabled);
- connect(floatingAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setDisabled(bool)));
- connect(movableAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setEnabled(bool)));
+ connect(floatingAction, &QAction::triggered, floatableAction, &QAction::setDisabled);
+ connect(movableAction, &QAction::triggered, floatableAction, &QAction::setEnabled);
tabMenu = new QMenu(this);
tabMenu->setTitle(tr("Tab into"));
- connect(tabMenu, SIGNAL(triggered(QAction*)), this, SLOT(tabInto(QAction*)));
+ connect(tabMenu, &QMenu::triggered, this, &ColorSwatch::tabInto);
splitHMenu = new QMenu(this);
splitHMenu->setTitle(tr("Split horizontally into"));
- connect(splitHMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*)));
+ connect(splitHMenu, &QMenu::triggered, this, &ColorSwatch::splitInto);
splitVMenu = new QMenu(this);
splitVMenu->setTitle(tr("Split vertically into"));
- connect(splitVMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*)));
+ connect(splitVMenu, &QMenu::triggered, this, &ColorSwatch::splitInto);
- windowModifiedAction = new QAction(tr("Modified"), this);
+ QAction *windowModifiedAction = new QAction(tr("Modified"), this);
windowModifiedAction->setCheckable(true);
windowModifiedAction->setChecked(false);
- connect(windowModifiedAction, SIGNAL(toggled(bool)), this, SLOT(setWindowModified(bool)));
+ connect(windowModifiedAction, &QAction::toggled, this, &QWidget::setWindowModified);
menu = new QMenu(colorName, this);
menu->addAction(toggleViewAction());
- QAction *action = menu->addAction(tr("Raise"));
- connect(action, SIGNAL(triggered()), this, SLOT(raise()));
- menu->addAction(changeSizeHintsAction);
+ menu->addAction(tr("Raise"), this, &QWidget::raise);
+ menu->addAction(tr("Change Size Hints..."), swatch, &ColorDock::changeSizeHints);
+
menu->addSeparator();
menu->addAction(closableAction);
menu->addAction(movableAction);
@@ -379,18 +368,17 @@ ColorSwatch::ColorSwatch(const QString &colorName, QWidget *parent, Qt::WindowFl
menu->addSeparator();
menu->addAction(windowModifiedAction);
- connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateContextMenu()));
+ connect(menu, &QMenu::aboutToShow, this, &ColorSwatch::updateContextMenu);
- if(colorName == "Black") {
- leftAction->setShortcut(Qt::CTRL|Qt::Key_W);
- rightAction->setShortcut(Qt::CTRL|Qt::Key_E);
- toggleViewAction()->setShortcut(Qt::CTRL|Qt::Key_R);
+ if (colorName == QLatin1String("Black")) {
+ leftAction->setShortcut(Qt::CTRL | Qt::Key_W);
+ rightAction->setShortcut(Qt::CTRL | Qt::Key_E);
+ toggleViewAction()->setShortcut(Qt::CTRL | Qt::Key_R);
}
}
void ColorSwatch::updateContextMenu()
{
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
const Qt::DockWidgetArea area = mainWindow->dockWidgetArea(this);
const Qt::DockWidgetAreas areas = allowedAreas();
@@ -448,48 +436,36 @@ void ColorSwatch::updateContextMenu()
splitVMenu->clear();
QList<ColorSwatch*> dock_list = mainWindow->findChildren<ColorSwatch*>();
foreach (ColorSwatch *dock, dock_list) {
-// if (!dock->isVisible() || dock->isFloating())
-// continue;
tabMenu->addAction(dock->objectName());
splitHMenu->addAction(dock->objectName());
splitVMenu->addAction(dock->objectName());
}
}
-void ColorSwatch::splitInto(QAction *action)
+static ColorSwatch *findByName(const QMainWindow *mainWindow, const QString &name)
{
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
- QList<ColorSwatch*> dock_list = mainWindow->findChildren<ColorSwatch*>();
- ColorSwatch *target = 0;
- foreach (ColorSwatch *dock, dock_list) {
- if (action->text() == dock->objectName()) {
- target = dock;
- break;
- }
+ foreach (ColorSwatch *dock, mainWindow->findChildren<ColorSwatch*>()) {
+ if (name == dock->objectName())
+ return dock;
}
- if (target == 0)
+ return Q_NULLPTR;
+}
+
+void ColorSwatch::splitInto(QAction *action)
+{
+ ColorSwatch *target = findByName(mainWindow, action->text());
+ if (!target)
return;
- Qt::Orientation o = action->parent() == splitHMenu
- ? Qt::Horizontal : Qt::Vertical;
+ const Qt::Orientation o = action->parent() == splitHMenu
+ ? Qt::Horizontal : Qt::Vertical;
mainWindow->splitDockWidget(target, this, o);
}
void ColorSwatch::tabInto(QAction *action)
{
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
- QList<ColorSwatch*> dock_list = mainWindow->findChildren<ColorSwatch*>();
- ColorSwatch *target = 0;
- foreach (ColorSwatch *dock, dock_list) {
- if (action->text() == dock->objectName()) {
- target = dock;
- break;
- }
- }
- if (target == 0)
- return;
-
- mainWindow->tabifyDockWidget(target, this);
+ if (ColorSwatch *target = findByName(mainWindow, action->text()))
+ mainWindow->tabifyDockWidget(target, this);
}
void ColorSwatch::contextMenuEvent(QContextMenuEvent *event)
@@ -506,7 +482,6 @@ void ColorSwatch::resizeEvent(QResizeEvent *e)
QDockWidget::resizeEvent(e);
}
-
void ColorSwatch::allow(Qt::DockWidgetArea area, bool a)
{
Qt::DockWidgetAreas areas = allowedAreas();
@@ -523,9 +498,9 @@ void ColorSwatch::allow(Qt::DockWidgetArea area, bool a)
void ColorSwatch::place(Qt::DockWidgetArea area, bool p)
{
- if (!p) return;
+ if (!p)
+ return;
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
mainWindow->addDockWidget(area, this);
if (allowedAreasActions->isEnabled()) {
@@ -596,10 +571,10 @@ QSize BlueTitleBar::minimumSizeHint() const
BlueTitleBar::BlueTitleBar(QWidget *parent)
: QWidget(parent)
+ , leftPm(QPixmap(":/res/titlebarLeft.png"))
+ , centerPm(QPixmap(":/res/titlebarCenter.png"))
+ , rightPm(QPixmap(":/res/titlebarRight.png"))
{
- leftPm = QPixmap(":/res/titlebarLeft.png");
- centerPm = QPixmap(":/res/titlebarCenter.png");
- rightPm = QPixmap(":/res/titlebarRight.png");
}
void BlueTitleBar::paintEvent(QPaintEvent*)
@@ -687,7 +662,7 @@ void BlueTitleBar::updateMask()
{
QPainter painter(&bitmap);
- ///initialize to transparent
+ // initialize to transparent
painter.fillRect(rect, Qt::color0);
QRect contents = rect;
@@ -696,10 +671,7 @@ void BlueTitleBar::updateMask()
contents.setBottom(contents.bottom()-y());
painter.fillRect(contents, Qt::color1);
-
-
- //let's pait the titlebar
-
+ // let's paint the titlebar
QRect titleRect = this->geometry();
if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) {
@@ -722,7 +694,6 @@ void BlueTitleBar::updateMask()
QRect rect = titleRect;
-
painter.drawPixmap(rect.topLeft(), leftPm.mask());
painter.fillRect(rect.left() + leftPm.width(), rect.top(),
rect.width() - leftPm.width() - rightPm.width(),
diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.h b/examples/widgets/mainwindows/mainwindow/colorswatch.h
index 6d02592b22..8827a7dca7 100644
--- a/examples/widgets/mainwindows/mainwindow/colorswatch.h
+++ b/examples/widgets/mainwindows/mainwindow/colorswatch.h
@@ -44,45 +44,15 @@ class ColorSwatch : public QDockWidget
{
Q_OBJECT
- QAction *closableAction;
- QAction *movableAction;
- QAction *floatableAction;
- QAction *floatingAction;
- QAction *verticalTitleBarAction;
-
- QActionGroup *allowedAreasActions;
- QAction *allowLeftAction;
- QAction *allowRightAction;
- QAction *allowTopAction;
- QAction *allowBottomAction;
-
- QActionGroup *areaActions;
- QAction *leftAction;
- QAction *rightAction;
- QAction *topAction;
- QAction *bottomAction;
-
- QAction *changeSizeHintsAction;
-
- QMenu *tabMenu;
- QMenu *splitHMenu;
- QMenu *splitVMenu;
-
- QAction *windowModifiedAction;
-
public:
- explicit ColorSwatch(const QString &colorName, QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit ColorSwatch(const QString &colorName, QMainWindow *parent = Q_NULLPTR, Qt::WindowFlags flags = 0);
- QMenu *menu;
void setCustomSizeHint(const QSize &size);
+ QMenu *colorSwatchMenu() const { return menu; }
protected:
- virtual void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE;
- virtual void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE;
-
-private:
- void allow(Qt::DockWidgetArea area, bool allow);
- void place(Qt::DockWidgetArea area, bool place);
+ void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE;
+ void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE;
private slots:
void changeClosable(bool on);
@@ -104,25 +74,57 @@ private slots:
void splitInto(QAction *action);
void tabInto(QAction *action);
+
+private:
+ void allow(Qt::DockWidgetArea area, bool allow);
+ void place(Qt::DockWidgetArea area, bool place);
+
+ QAction *closableAction;
+ QAction *movableAction;
+ QAction *floatableAction;
+ QAction *floatingAction;
+ QAction *verticalTitleBarAction;
+
+ QActionGroup *allowedAreasActions;
+ QAction *allowLeftAction;
+ QAction *allowRightAction;
+ QAction *allowTopAction;
+ QAction *allowBottomAction;
+
+ QActionGroup *areaActions;
+ QAction *leftAction;
+ QAction *rightAction;
+ QAction *topAction;
+ QAction *bottomAction;
+
+ QMenu *tabMenu;
+ QMenu *splitHMenu;
+ QMenu *splitVMenu;
+ QMenu *menu;
+
+ QMainWindow *mainWindow;
};
class BlueTitleBar : public QWidget
{
Q_OBJECT
public:
- BlueTitleBar(QWidget *parent = 0);
+ explicit BlueTitleBar(QWidget *parent = Q_NULLPTR);
QSize sizeHint() const Q_DECL_OVERRIDE { return minimumSizeHint(); }
QSize minimumSizeHint() const Q_DECL_OVERRIDE;
+
protected:
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
+
public slots:
void updateMask();
private:
- QPixmap leftPm, centerPm, rightPm;
+ const QPixmap leftPm;
+ const QPixmap centerPm;
+ const QPixmap rightPm;
};
-
-#endif
+#endif // COLORSWATCH_H
diff --git a/examples/widgets/mainwindows/mainwindow/main.cpp b/examples/widgets/mainwindows/mainwindow/main.cpp
index 2192074791..b32b595a2d 100644
--- a/examples/widgets/mainwindows/mainwindow/main.cpp
+++ b/examples/widgets/mainwindows/mainwindow/main.cpp
@@ -37,9 +37,10 @@
#include <QPainterPath>
#include <QPainter>
#include <QMap>
-#include <qdebug.h>
+#include <QDebug>
-void render_qt_text(QPainter *painter, int w, int h, const QColor &color) {
+void render_qt_text(QPainter *painter, int w, int h, const QColor &color)
+{
QPainterPath path;
path.moveTo(-0.083695, 0.283849);
path.cubicTo(-0.049581, 0.349613, -0.012720, 0.397969, 0.026886, 0.428917);
@@ -108,47 +109,67 @@ void render_qt_text(QPainter *painter, int w, int h, const QColor &color) {
painter->drawPath(path);
}
-void usage()
+static void usage()
{
qWarning() << "Usage: mainwindow [-SizeHint<color> <width>x<height>] ...";
exit(1);
}
-QMap<QString, QSize> parseCustomSizeHints(int argc, char **argv)
-{
- QMap<QString, QSize> result;
-
- for (int i = 1; i < argc; ++i) {
- QString arg = QString::fromLocal8Bit(argv[i]);
+enum ParseCommandLineArgumentsResult {
+ CommandLineArgumentsOk,
+ CommandLineArgumentsError,
+ HelpRequested
+};
+static ParseCommandLineArgumentsResult
+ parseCustomSizeHints(const QStringList &arguments, MainWindow::CustomSizeHintMap *result)
+{
+ result->clear();
+ const int argumentCount = arguments.size();
+ for (int i = 1; i < argumentCount; ++i) {
+ const QString &arg = arguments.at(i);
if (arg.startsWith(QLatin1String("-SizeHint"))) {
- QString name = arg.mid(9);
+ const QString name = arg.mid(9);
if (name.isEmpty())
- usage();
- if (++i == argc)
- usage();
- QString sizeStr = QString::fromLocal8Bit(argv[i]);
- int idx = sizeStr.indexOf(QLatin1Char('x'));
+ return CommandLineArgumentsError;
+ if (++i == argumentCount)
+ return CommandLineArgumentsError;
+ const QString sizeStr = arguments.at(i);
+ const int idx = sizeStr.indexOf(QLatin1Char('x'));
if (idx == -1)
- usage();
+ return CommandLineArgumentsError;
bool ok;
- int w = sizeStr.left(idx).toInt(&ok);
+ const int w = sizeStr.leftRef(idx).toInt(&ok);
if (!ok)
- usage();
- int h = sizeStr.mid(idx + 1).toInt(&ok);
+ return CommandLineArgumentsError;
+ const int h = sizeStr.midRef(idx + 1).toInt(&ok);
if (!ok)
- usage();
- result[name] = QSize(w, h);
+ return CommandLineArgumentsError;
+ result->insert(name, QSize(w, h));
+ } else if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
+ return HelpRequested;
+ } else {
+ return CommandLineArgumentsError;
}
}
- return result;
+ return CommandLineArgumentsOk;
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
- QMap<QString, QSize> customSizeHints = parseCustomSizeHints(argc, argv);
+ MainWindow::CustomSizeHintMap customSizeHints;
+ switch (parseCustomSizeHints(QCoreApplication::arguments(), &customSizeHints)) {
+ case CommandLineArgumentsOk:
+ break;
+ case CommandLineArgumentsError:
+ usage();
+ return -1;
+ case HelpRequested:
+ usage();
+ return 0;
+ }
MainWindow mainWin(customSizeHints);
mainWin.resize(800, 600);
mainWin.show();
diff --git a/examples/widgets/mainwindows/mainwindow/mainwindow.cpp b/examples/widgets/mainwindows/mainwindow/mainwindow.cpp
index 6349f7aa2e..91579ae611 100644
--- a/examples/widgets/mainwindows/mainwindow/mainwindow.cpp
+++ b/examples/widgets/mainwindows/mainwindow/mainwindow.cpp
@@ -44,6 +44,7 @@
#include <QFile>
#include <QDataStream>
#include <QFileDialog>
+#include <QDialogButtonBox>
#include <QMessageBox>
#include <QSignalMapper>
#include <QApplication>
@@ -53,9 +54,10 @@
#include <QComboBox>
#include <QLabel>
#include <QPushButton>
-#include <qdebug.h>
+#include <QTextEdit>
+#include <QDebug>
-static const char * const message =
+static const char message[] =
"<p><b>Qt Main Window Example</b></p>"
"<p>This is a demonstration of the QMainWindow, QToolBar and "
@@ -75,14 +77,14 @@ static const char * const message =
Q_DECLARE_METATYPE(QDockWidget::DockWidgetFeatures)
-MainWindow::MainWindow(const QMap<QString, QSize> &customSizeHints,
- QWidget *parent, Qt::WindowFlags flags)
+MainWindow::MainWindow(const CustomSizeHintMap &customSizeHints,
+ QWidget *parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
{
setObjectName("MainWindow");
setWindowTitle("Qt Main Window Example");
- center = new QTextEdit(this);
+ QTextEdit *center = new QTextEdit(this);
center->setReadOnly(true);
center->setMinimumSize(400, 205);
setCentralWidget(center);
@@ -116,49 +118,48 @@ void MainWindow::setupMenuBar()
{
QMenu *menu = menuBar()->addMenu(tr("&File"));
- QAction *action = menu->addAction(tr("Save layout..."));
- connect(action, SIGNAL(triggered()), this, SLOT(saveLayout()));
-
- action = menu->addAction(tr("Load layout..."));
- connect(action, SIGNAL(triggered()), this, SLOT(loadLayout()));
-
- action = menu->addAction(tr("Switch layout direction"));
- connect(action, SIGNAL(triggered()), this, SLOT(switchLayoutDirection()));
+ menu->addAction(tr("Save layout..."), this, &MainWindow::saveLayout);
+ menu->addAction(tr("Load layout..."), this, &MainWindow::loadLayout);
+ menu->addAction(tr("Switch layout direction"),this, &MainWindow::switchLayoutDirection);
menu->addSeparator();
-
- menu->addAction(tr("&Quit"), this, SLOT(close()));
+ menu->addAction(tr("&Quit"), this, &QWidget::close);
mainWindowMenu = menuBar()->addMenu(tr("Main window"));
- action = mainWindowMenu->addAction(tr("Animated docks"));
+ QAction *action = mainWindowMenu->addAction(tr("Animated docks"));
action->setCheckable(true);
action->setChecked(dockOptions() & AnimatedDocks);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions()));
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
action = mainWindowMenu->addAction(tr("Allow nested docks"));
action->setCheckable(true);
action->setChecked(dockOptions() & AllowNestedDocks);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions()));
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
action = mainWindowMenu->addAction(tr("Allow tabbed docks"));
action->setCheckable(true);
action->setChecked(dockOptions() & AllowTabbedDocks);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions()));
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
action = mainWindowMenu->addAction(tr("Force tabbed docks"));
action->setCheckable(true);
action->setChecked(dockOptions() & ForceTabbedDocks);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions()));
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
action = mainWindowMenu->addAction(tr("Vertical tabs"));
action->setCheckable(true);
action->setChecked(dockOptions() & VerticalTabs);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions()));
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
+
+ action = mainWindowMenu->addAction(tr("Grouped dragging"));
+ action->setCheckable(true);
+ action->setChecked(dockOptions() & GroupedDragging);
+ connect(action, &QAction::toggled, this, &MainWindow::setDockOptions);
QMenu *toolBarMenu = menuBar()->addMenu(tr("Tool bars"));
for (int i = 0; i < toolBars.count(); ++i)
- toolBarMenu->addMenu(toolBars.at(i)->menu);
+ toolBarMenu->addMenu(toolBars.at(i)->toolbarMenu());
#ifdef Q_OS_OSX
toolBarMenu->addSeparator();
@@ -166,7 +167,7 @@ void MainWindow::setupMenuBar()
action = toolBarMenu->addAction(tr("Unified"));
action->setCheckable(true);
action->setChecked(unifiedTitleAndToolBarOnMac());
- connect(action, SIGNAL(toggled(bool)), this, SLOT(setUnifiedTitleAndToolBarOnMac(bool)));
+ connect(action, &QAction::toggled, this, &QMainWindow::setUnifiedTitleAndToolBarOnMac);
#endif
dockWidgetMenu = menuBar()->addMenu(tr("&Dock Widgets"));
@@ -187,6 +188,8 @@ void MainWindow::setDockOptions()
opts |= ForceTabbedDocks;
if (actions.at(4)->isChecked())
opts |= VerticalTabs;
+ if (actions.at(5)->isChecked())
+ opts |= GroupedDragging;
QMainWindow::setDockOptions(opts);
}
@@ -200,8 +203,7 @@ void MainWindow::saveLayout()
QFile file(fileName);
if (!file.open(QFile::WriteOnly)) {
QString msg = tr("Failed to open %1\n%2")
- .arg(fileName)
- .arg(file.errorString());
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
QMessageBox::warning(this, tr("Error"), msg);
return;
}
@@ -217,8 +219,7 @@ void MainWindow::saveLayout()
if (!ok) {
QString msg = tr("Error writing to %1\n%2")
- .arg(fileName)
- .arg(file.errorString());
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
QMessageBox::warning(this, tr("Error"), msg);
return;
}
@@ -233,8 +234,7 @@ void MainWindow::loadLayout()
QFile file(fileName);
if (!file.open(QFile::ReadOnly)) {
QString msg = tr("Failed to open %1\n%2")
- .arg(fileName)
- .arg(file.errorString());
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
QMessageBox::warning(this, tr("Error"), msg);
return;
}
@@ -259,56 +259,65 @@ void MainWindow::loadLayout()
ok = restoreState(layout_data);
if (!ok) {
- QString msg = tr("Error reading %1")
- .arg(fileName);
+ QString msg = tr("Error reading %1").arg(QDir::toNativeSeparators(fileName));
QMessageBox::warning(this, tr("Error"), msg);
return;
}
}
-QAction *addAction(QMenu *menu, const QString &text, QActionGroup *group, QSignalMapper *mapper,
- int id)
+class DockWidgetAreaCornerFunctor {
+public:
+ explicit DockWidgetAreaCornerFunctor(QMainWindow *mw, Qt::Corner c, Qt::DockWidgetArea a)
+ : m_mainWindow(mw), m_area(a), m_corner(c) {}
+
+ void operator()() const { m_mainWindow->setCorner(m_corner, m_area); }
+
+private:
+ QMainWindow *m_mainWindow;
+ Qt::DockWidgetArea m_area;
+ Qt::Corner m_corner;
+};
+
+static QAction *addCornerAction(const QString &text, QMainWindow *mw, QMenu *menu, QActionGroup *group,
+ Qt::Corner c, Qt::DockWidgetArea a)
{
- bool first = group->actions().isEmpty();
- QAction *result = menu->addAction(text);
+ QAction *result = menu->addAction(text, mw, DockWidgetAreaCornerFunctor(mw, c, a));
result->setCheckable(true);
- result->setChecked(first);
group->addAction(result);
- QObject::connect(result, SIGNAL(triggered()), mapper, SLOT(map()));
- mapper->setMapping(result, id);
return result;
}
-void MainWindow::setupDockWidgets(const QMap<QString, QSize> &customSizeHints)
+void MainWindow::setupDockWidgets(const CustomSizeHintMap &customSizeHints)
{
qRegisterMetaType<QDockWidget::DockWidgetFeatures>();
- mapper = new QSignalMapper(this);
- connect(mapper, SIGNAL(mapped(int)), this, SLOT(setCorner(int)));
-
- QMenu *corner_menu = dockWidgetMenu->addMenu(tr("Top left corner"));
+ QMenu *cornerMenu = dockWidgetMenu->addMenu(tr("Top left corner"));
QActionGroup *group = new QActionGroup(this);
group->setExclusive(true);
- ::addAction(corner_menu, tr("Top dock area"), group, mapper, 0);
- ::addAction(corner_menu, tr("Left dock area"), group, mapper, 1);
+ QAction *cornerAction = addCornerAction(tr("Top dock area"), this, cornerMenu, group, Qt::TopLeftCorner, Qt::TopDockWidgetArea);
+ cornerAction->setChecked(true);
+ addCornerAction(tr("Left dock area"), this, cornerMenu, group, Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
- corner_menu = dockWidgetMenu->addMenu(tr("Top right corner"));
+ cornerMenu = dockWidgetMenu->addMenu(tr("Top right corner"));
group = new QActionGroup(this);
group->setExclusive(true);
- ::addAction(corner_menu, tr("Top dock area"), group, mapper, 2);
- ::addAction(corner_menu, tr("Right dock area"), group, mapper, 3);
+ cornerAction = addCornerAction(tr("Top dock area"), this, cornerMenu, group, Qt::TopRightCorner, Qt::TopDockWidgetArea);
+ cornerAction->setChecked(true);
+ addCornerAction(tr("Right dock area"), this, cornerMenu, group, Qt::TopRightCorner, Qt::RightDockWidgetArea);
- corner_menu = dockWidgetMenu->addMenu(tr("Bottom left corner"));
+ cornerMenu = dockWidgetMenu->addMenu(tr("Bottom left corner"));
group = new QActionGroup(this);
group->setExclusive(true);
- ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 4);
- ::addAction(corner_menu, tr("Left dock area"), group, mapper, 5);
+ cornerAction = addCornerAction(tr("Bottom dock area"), this, cornerMenu, group, Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
+ cornerAction->setChecked(true);
+ addCornerAction(tr("Left dock area"), this, cornerMenu, group, Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
- corner_menu = dockWidgetMenu->addMenu(tr("Bottom right corner"));
+ cornerMenu = dockWidgetMenu->addMenu(tr("Bottom right corner"));
group = new QActionGroup(this);
group->setExclusive(true);
- ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 6);
- ::addAction(corner_menu, tr("Right dock area"), group, mapper, 7);
+ cornerAction = addCornerAction(tr("Bottom dock area"), this, cornerMenu, group, Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
+ cornerAction->setChecked(true);
+ addCornerAction(tr("Right dock area"), this, cornerMenu, group, Qt::BottomRightCorner, Qt::RightDockWidgetArea);
dockWidgetMenu->addSeparator();
@@ -330,16 +339,16 @@ void MainWindow::setupDockWidgets(const QMap<QString, QSize> &customSizeHints)
};
const int setCount = sizeof(sets) / sizeof(Set);
+ const QIcon qtIcon(QPixmap(":/res/qt.png"));
for (int i = 0; i < setCount; ++i) {
ColorSwatch *swatch = new ColorSwatch(tr(sets[i].name), this, Qt::WindowFlags(sets[i].flags));
- if (i%2)
- swatch->setWindowIcon(QIcon(QPixmap(":/res/qt.png")));
+ if (i % 2)
+ swatch->setWindowIcon(qtIcon);
if (qstrcmp(sets[i].name, "Blue") == 0) {
BlueTitleBar *titlebar = new BlueTitleBar(swatch);
swatch->setTitleBarWidget(titlebar);
- connect(swatch, SIGNAL(topLevelChanged(bool)), titlebar, SLOT(updateMask()));
- connect(swatch, SIGNAL(featuresChanged(QDockWidget::DockWidgetFeatures)), titlebar, SLOT(updateMask()), Qt::QueuedConnection);
-
+ connect(swatch, &QDockWidget::topLevelChanged, titlebar, &BlueTitleBar::updateMask);
+ connect(swatch, &QDockWidget::featuresChanged, titlebar, &BlueTitleBar::updateMask, Qt::QueuedConnection);
}
QString name = QString::fromLatin1(sets[i].name);
@@ -347,69 +356,32 @@ void MainWindow::setupDockWidgets(const QMap<QString, QSize> &customSizeHints)
swatch->setCustomSizeHint(customSizeHints.value(name));
addDockWidget(sets[i].area, swatch);
- dockWidgetMenu->addMenu(swatch->menu);
+ dockWidgetMenu->addMenu(swatch->colorSwatchMenu());
}
- createDockWidgetAction = new QAction(tr("Add dock widget..."), this);
- connect(createDockWidgetAction, SIGNAL(triggered()), this, SLOT(createDockWidget()));
destroyDockWidgetMenu = new QMenu(tr("Destroy dock widget"), this);
destroyDockWidgetMenu->setEnabled(false);
- connect(destroyDockWidgetMenu, SIGNAL(triggered(QAction*)), this, SLOT(destroyDockWidget(QAction*)));
+ connect(destroyDockWidgetMenu, &QMenu::triggered, this, &MainWindow::destroyDockWidget);
dockWidgetMenu->addSeparator();
- dockWidgetMenu->addAction(createDockWidgetAction);
+ dockWidgetMenu->addAction(tr("Add dock widget..."), this, &MainWindow::createDockWidget);
dockWidgetMenu->addMenu(destroyDockWidgetMenu);
}
-void MainWindow::setCorner(int id)
-{
- switch (id) {
- case 0:
- QMainWindow::setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
- break;
- case 1:
- QMainWindow::setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
- break;
- case 2:
- QMainWindow::setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
- break;
- case 3:
- QMainWindow::setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
- break;
- case 4:
- QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
- break;
- case 5:
- QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
- break;
- case 6:
- QMainWindow::setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
- break;
- case 7:
- QMainWindow::setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
- break;
- }
-}
-
-void MainWindow::showEvent(QShowEvent *event)
-{
- QMainWindow::showEvent(event);
-}
-
void MainWindow::switchLayoutDirection()
{
if (layoutDirection() == Qt::LeftToRight)
- qApp->setLayoutDirection(Qt::RightToLeft);
+ QApplication::setLayoutDirection(Qt::RightToLeft);
else
- qApp->setLayoutDirection(Qt::LeftToRight);
+ QApplication::setLayoutDirection(Qt::LeftToRight);
}
class CreateDockWidgetDialog : public QDialog
{
public:
- CreateDockWidgetDialog(QWidget *parent = 0);
+ explicit CreateDockWidgetDialog(QWidget *parent = Q_NULLPTR);
- QString objectName() const;
+ QString enteredObjectName() const { return m_objectName->text(); }
Qt::DockWidgetArea location() const;
private:
@@ -419,15 +391,17 @@ private:
CreateDockWidgetDialog::CreateDockWidgetDialog(QWidget *parent)
: QDialog(parent)
+ , m_objectName(new QLineEdit(this))
+ , m_location(new QComboBox(this))
{
+ setWindowTitle(tr("Add Dock Widget"));
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(new QLabel(tr("Object name:")), 0, 0);
- m_objectName = new QLineEdit;
layout->addWidget(m_objectName, 0, 1);
layout->addWidget(new QLabel(tr("Location:")), 1, 0);
- m_location = new QComboBox;
m_location->setEditable(false);
m_location->addItem(tr("Top"));
m_location->addItem(tr("Left"));
@@ -436,23 +410,10 @@ CreateDockWidgetDialog::CreateDockWidgetDialog(QWidget *parent)
m_location->addItem(tr("Restore"));
layout->addWidget(m_location, 1, 1);
- QHBoxLayout *buttonLayout = new QHBoxLayout;
- layout->addLayout(buttonLayout, 2, 0, 1, 2);
- buttonLayout->addStretch();
-
- QPushButton *cancelButton = new QPushButton(tr("Cancel"));
- connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
- buttonLayout->addWidget(cancelButton);
- QPushButton *okButton = new QPushButton(tr("Ok"));
- connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
- buttonLayout->addWidget(okButton);
-
- okButton->setDefault(true);
-}
-
-QString CreateDockWidgetDialog::objectName() const
-{
- return m_objectName->text();
+ QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::reject);
+ layout->addWidget(buttonBox, 2, 0, 1, 2);
}
Qt::DockWidgetArea CreateDockWidgetDialog::location() const
@@ -471,13 +432,13 @@ Qt::DockWidgetArea CreateDockWidgetDialog::location() const
void MainWindow::createDockWidget()
{
CreateDockWidgetDialog dialog(this);
- int ret = dialog.exec();
- if (ret == QDialog::Rejected)
+ if (dialog.exec() == QDialog::Rejected)
return;
QDockWidget *dw = new QDockWidget;
- dw->setObjectName(dialog.objectName());
- dw->setWindowTitle(dialog.objectName());
+ const QString name = dialog.enteredObjectName();
+ dw->setObjectName(name);
+ dw->setWindowTitle(name);
dw->setWidget(new QTextEdit);
Qt::DockWidgetArea area = dialog.location();
@@ -499,7 +460,7 @@ void MainWindow::createDockWidget()
extraDockWidgets.append(dw);
destroyDockWidgetMenu->setEnabled(true);
- destroyDockWidgetMenu->addAction(new QAction(dialog.objectName(), this));
+ destroyDockWidgetMenu->addAction(new QAction(name, this));
}
void MainWindow::destroyDockWidget(QAction *action)
diff --git a/examples/widgets/mainwindows/mainwindow/mainwindow.h b/examples/widgets/mainwindows/mainwindow/mainwindow.h
index f9a6176b2d..162e977520 100644
--- a/examples/widgets/mainwindows/mainwindow/mainwindow.h
+++ b/examples/widgets/mainwindows/mainwindow/mainwindow.h
@@ -35,37 +35,25 @@
#define MAINWINDOW_H
#include <QMainWindow>
-#include <QTextEdit>
class ToolBar;
QT_FORWARD_DECLARE_CLASS(QMenu)
-QT_FORWARD_DECLARE_CLASS(QSignalMapper)
class MainWindow : public QMainWindow
{
Q_OBJECT
- QTextEdit *center;
- QList<ToolBar*> toolBars;
- QMenu *dockWidgetMenu;
- QMenu *mainWindowMenu;
- QSignalMapper *mapper;
- QList<QDockWidget*> extraDockWidgets;
- QAction *createDockWidgetAction;
- QMenu *destroyDockWidgetMenu;
-
public:
- MainWindow(const QMap<QString, QSize> &customSizeHints,
- QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ typedef QMap<QString, QSize> CustomSizeHintMap;
-protected:
- void showEvent(QShowEvent *event) Q_DECL_OVERRIDE;
+ explicit MainWindow(const CustomSizeHintMap &customSizeHints,
+ QWidget *parent = Q_NULLPTR,
+ Qt::WindowFlags flags = 0);
public slots:
void actionTriggered(QAction *action);
void saveLayout();
void loadLayout();
- void setCorner(int id);
void switchLayoutDirection();
void setDockOptions();
@@ -75,8 +63,13 @@ public slots:
private:
void setupToolBar();
void setupMenuBar();
- void setupDockWidgets(const QMap<QString, QSize> &customSizeHints);
-};
+ void setupDockWidgets(const CustomSizeHintMap &customSizeHints);
+ QList<ToolBar*> toolBars;
+ QMenu *dockWidgetMenu;
+ QMenu *mainWindowMenu;
+ QList<QDockWidget *> extraDockWidgets;
+ QMenu *destroyDockWidgetMenu;
+};
-#endif
+#endif // MAINWINDOW_H
diff --git a/examples/widgets/mainwindows/mainwindow/toolbar.cpp b/examples/widgets/mainwindows/mainwindow/toolbar.cpp
index 280ba965d6..a9b308370a 100644
--- a/examples/widgets/mainwindows/mainwindow/toolbar.cpp
+++ b/examples/widgets/mainwindows/mainwindow/toolbar.cpp
@@ -63,15 +63,15 @@ static QPixmap genIcon(const QSize &iconSize, int number, const QColor &color)
{ return genIcon(iconSize, QString::number(number), color); }
ToolBar::ToolBar(const QString &title, QWidget *parent)
- : QToolBar(parent), spinbox(0), spinboxAction(0)
+ : QToolBar(parent)
+ , spinbox(Q_NULLPTR)
+ , spinboxAction(Q_NULLPTR)
{
- tip = 0;
setWindowTitle(title);
setObjectName(title);
setIconSize(QSize(32, 32));
- QColor bg(palette().background().color());
menu = new QMenu("One", this);
menu->setIcon(genIcon(iconSize(), 1, Qt::black));
menu->addAction(genIcon(iconSize(), "A", Qt::blue), "A");
@@ -90,43 +90,43 @@ ToolBar::ToolBar(const QString &title, QWidget *parent)
addAction(genIcon(iconSize(), 6, Qt::yellow), "Six");
orderAction = new QAction(this);
orderAction->setText(tr("Order Items in Tool Bar"));
- connect(orderAction, SIGNAL(triggered()), SLOT(order()));
+ connect(orderAction, &QAction::triggered, this, &ToolBar::order);
randomizeAction = new QAction(this);
randomizeAction->setText(tr("Randomize Items in Tool Bar"));
- connect(randomizeAction, SIGNAL(triggered()), SLOT(randomize()));
+ connect(randomizeAction, &QAction::triggered, this, &ToolBar::randomize);
addSpinBoxAction = new QAction(this);
addSpinBoxAction->setText(tr("Add Spin Box"));
- connect(addSpinBoxAction, SIGNAL(triggered()), SLOT(addSpinBox()));
+ connect(addSpinBoxAction, &QAction::triggered, this, &ToolBar::addSpinBox);
removeSpinBoxAction = new QAction(this);
removeSpinBoxAction->setText(tr("Remove Spin Box"));
removeSpinBoxAction->setEnabled(false);
- connect(removeSpinBoxAction, SIGNAL(triggered()), SLOT(removeSpinBox()));
+ connect(removeSpinBoxAction, &QAction::triggered, this, &ToolBar::removeSpinBox);
movableAction = new QAction(tr("Movable"), this);
movableAction->setCheckable(true);
- connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool)));
+ connect(movableAction, &QAction::triggered, this, &ToolBar::changeMovable);
allowedAreasActions = new QActionGroup(this);
allowedAreasActions->setExclusive(false);
allowLeftAction = new QAction(tr("Allow on Left"), this);
allowLeftAction->setCheckable(true);
- connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool)));
+ connect(allowLeftAction, &QAction::triggered, this, &ToolBar::allowLeft);
allowRightAction = new QAction(tr("Allow on Right"), this);
allowRightAction->setCheckable(true);
- connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool)));
+ connect(allowRightAction, &QAction::triggered, this, &ToolBar::allowRight);
allowTopAction = new QAction(tr("Allow on Top"), this);
allowTopAction->setCheckable(true);
- connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool)));
+ connect(allowTopAction, &QAction::triggered, this, &ToolBar::allowTop);
allowBottomAction = new QAction(tr("Allow on Bottom"), this);
allowBottomAction->setCheckable(true);
- connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool)));
+ connect(allowBottomAction, &QAction::triggered, this, &ToolBar::allowBottom);
allowedAreasActions->addAction(allowLeftAction);
allowedAreasActions->addAction(allowRightAction);
@@ -138,31 +138,28 @@ ToolBar::ToolBar(const QString &title, QWidget *parent)
leftAction = new QAction(tr("Place on Left") , this);
leftAction->setCheckable(true);
- connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool)));
+ connect(leftAction, &QAction::triggered, this, &ToolBar::placeLeft);
rightAction = new QAction(tr("Place on Right") , this);
rightAction->setCheckable(true);
- connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool)));
+ connect(rightAction, &QAction::triggered, this, &ToolBar::placeRight);
topAction = new QAction(tr("Place on Top") , this);
topAction->setCheckable(true);
- connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool)));
+ connect(topAction, &QAction::triggered, this, &ToolBar::placeTop);
bottomAction = new QAction(tr("Place on Bottom") , this);
bottomAction->setCheckable(true);
- connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool)));
+ connect(bottomAction, &QAction::triggered, this, &ToolBar::placeBottom);
areaActions->addAction(leftAction);
areaActions->addAction(rightAction);
areaActions->addAction(topAction);
areaActions->addAction(bottomAction);
- toolBarBreakAction = new QAction(tr("Insert break"), this);
- connect(toolBarBreakAction, SIGNAL(triggered(bool)), this, SLOT(insertToolBarBreak()));
+ connect(movableAction, &QAction::triggered, areaActions, &QActionGroup::setEnabled);
- connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool)));
-
- connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool)));
+ connect(movableAction, &QAction::triggered, allowedAreasActions, &QActionGroup::setEnabled);
menu = new QMenu(title, this);
menu->addAction(toggleViewAction());
@@ -179,9 +176,9 @@ ToolBar::ToolBar(const QString &title, QWidget *parent)
menu->addSeparator();
menu->addActions(areaActions->actions());
menu->addSeparator();
- menu->addAction(toolBarBreakAction);
+ menu->addAction(tr("Insert break"), this, &ToolBar::insertToolBarBreak);
- connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateMenu()));
+ connect(menu, &QMenu::aboutToShow, this, &ToolBar::updateMenu);
randomize();
}
@@ -223,10 +220,9 @@ void ToolBar::updateMenu()
void ToolBar::order()
{
- QList<QAction *> ordered, actions1 = actions(),
- actions2 = findChildren<QAction *>();
- while (!actions2.isEmpty()) {
- QAction *action = actions2.takeFirst();
+ QList<QAction *> ordered;
+ QList<QAction *> actions1 = actions();
+ foreach (QAction *action, findChildren<QAction *>()) {
if (!actions1.contains(action))
continue;
actions1.removeAll(action);
@@ -241,7 +237,8 @@ void ToolBar::order()
void ToolBar::randomize()
{
- QList<QAction *> randomized, actions = this->actions();
+ QList<QAction *> randomized;
+ QList<QAction *> actions = this->actions();
while (!actions.isEmpty()) {
QAction *action = actions.takeAt(rand() % actions.size());
randomized.append(action);
@@ -254,9 +251,8 @@ void ToolBar::randomize()
void ToolBar::addSpinBox()
{
- if (!spinbox) {
+ if (!spinbox)
spinbox = new QSpinBox(this);
- }
if (!spinboxAction)
spinboxAction = addWidget(spinbox);
else
@@ -341,35 +337,3 @@ void ToolBar::insertToolBarBreak()
mainWindow->insertToolBarBreak(this);
}
-
-void ToolBar::enterEvent(QEvent*)
-{
-/*
- These labels on top of toolbars look darn ugly
-
- if (tip == 0) {
- tip = new QLabel(windowTitle(), this);
- QPalette pal = tip->palette();
- QColor c = Qt::black;
- c.setAlpha(100);
- pal.setColor(QPalette::Window, c);
- pal.setColor(QPalette::Foreground, Qt::white);
- tip->setPalette(pal);
- tip->setAutoFillBackground(true);
- tip->setMargin(3);
- tip->setText(windowTitle());
- }
- QPoint c = rect().center();
- QSize hint = tip->sizeHint();
- tip->setGeometry(c.x() - hint.width()/2, c.y() - hint.height()/2,
- hint.width(), hint.height());
-
- tip->show();
-*/
-}
-
-void ToolBar::leaveEvent(QEvent*)
-{
- if (tip != 0)
- tip->hide();
-}
diff --git a/examples/widgets/mainwindows/mainwindow/toolbar.h b/examples/widgets/mainwindows/mainwindow/toolbar.h
index b1674a2034..2629d9d7a7 100644
--- a/examples/widgets/mainwindows/mainwindow/toolbar.h
+++ b/examples/widgets/mainwindows/mainwindow/toolbar.h
@@ -40,49 +40,15 @@ QT_FORWARD_DECLARE_CLASS(QAction)
QT_FORWARD_DECLARE_CLASS(QActionGroup)
QT_FORWARD_DECLARE_CLASS(QMenu)
QT_FORWARD_DECLARE_CLASS(QSpinBox)
-QT_FORWARD_DECLARE_CLASS(QLabel)
class ToolBar : public QToolBar
{
Q_OBJECT
- QSpinBox *spinbox;
- QAction *spinboxAction;
-
- QAction *orderAction;
- QAction *randomizeAction;
- QAction *addSpinBoxAction;
- QAction *removeSpinBoxAction;
-
- QAction *movableAction;
-
- QActionGroup *allowedAreasActions;
- QAction *allowLeftAction;
- QAction *allowRightAction;
- QAction *allowTopAction;
- QAction *allowBottomAction;
-
- QActionGroup *areaActions;
- QAction *leftAction;
- QAction *rightAction;
- QAction *topAction;
- QAction *bottomAction;
-
- QAction *toolBarBreakAction;
-
public:
- ToolBar(const QString &title, QWidget *parent);
-
- QMenu *menu;
+ explicit ToolBar(const QString &title, QWidget *parent);
-protected:
- void enterEvent(QEvent*) Q_DECL_OVERRIDE;
- void leaveEvent(QEvent*) Q_DECL_OVERRIDE;
-
-private:
- void allow(Qt::ToolBarArea area, bool allow);
- void place(Qt::ToolBarArea area, bool place);
- QLabel *tip;
+ QMenu *toolbarMenu() const { return menu; }
private slots:
void order();
@@ -105,6 +71,32 @@ private slots:
void updateMenu();
void insertToolBarBreak();
+private:
+ void allow(Qt::ToolBarArea area, bool allow);
+ void place(Qt::ToolBarArea area, bool place);
+
+ QSpinBox *spinbox;
+ QAction *spinboxAction;
+
+ QMenu *menu;
+ QAction *orderAction;
+ QAction *randomizeAction;
+ QAction *addSpinBoxAction;
+ QAction *removeSpinBoxAction;
+
+ QAction *movableAction;
+
+ QActionGroup *allowedAreasActions;
+ QAction *allowLeftAction;
+ QAction *allowRightAction;
+ QAction *allowTopAction;
+ QAction *allowBottomAction;
+
+ QActionGroup *areaActions;
+ QAction *leftAction;
+ QAction *rightAction;
+ QAction *topAction;
+ QAction *bottomAction;
};
-#endif
+#endif // TOOLBAR_H
diff --git a/examples/widgets/mainwindows/mainwindows.pro b/examples/widgets/mainwindows/mainwindows.pro
index 52179ec9bd..dcda89abaf 100644
--- a/examples/widgets/mainwindows/mainwindows.pro
+++ b/examples/widgets/mainwindows/mainwindows.pro
@@ -4,5 +4,4 @@ SUBDIRS = application \
mainwindow \
mdi \
menus \
- recentfiles \
sdi
diff --git a/examples/widgets/mainwindows/mdi/main.cpp b/examples/widgets/mainwindows/mdi/main.cpp
index 5976c85c1c..f02285d1cf 100644
--- a/examples/widgets/mainwindows/mdi/main.cpp
+++ b/examples/widgets/mainwindows/mdi/main.cpp
@@ -49,6 +49,8 @@ int main(int argc, char *argv[])
Q_INIT_RESOURCE(mdi);
QApplication app(argc, argv);
+ QCoreApplication::setApplicationName("MDI Example");
+ QCoreApplication::setOrganizationName("QtProject");
QCoreApplication::setApplicationVersion(QT_VERSION_STR);
QCommandLineParser parser;
parser.setApplicationDescription("Qt MDI Example");
diff --git a/examples/widgets/mainwindows/mdi/mainwindow.cpp b/examples/widgets/mainwindows/mdi/mainwindow.cpp
index 83ffbf6557..35136c81c4 100644
--- a/examples/widgets/mainwindows/mdi/mainwindow.cpp
+++ b/examples/widgets/mainwindows/mdi/mainwindow.cpp
@@ -44,20 +44,15 @@
#include "mdichild.h"
MainWindow::MainWindow()
+ : mdiArea(new QMdiArea)
{
- mdiArea = new QMdiArea;
mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setCentralWidget(mdiArea);
- connect(mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),
- this, SLOT(updateMenus()));
- windowMapper = new QSignalMapper(this);
- connect(windowMapper, SIGNAL(mapped(QWidget*)),
- this, SLOT(setActiveSubWindow(QWidget*)));
+ connect(mdiArea, &QMdiArea::subWindowActivated,
+ this, &MainWindow::updateMenus);
createActions();
- createMenus();
- createToolBars();
createStatusBar();
updateMenus();
@@ -87,20 +82,24 @@ void MainWindow::newFile()
void MainWindow::open()
{
- QString fileName = QFileDialog::getOpenFileName(this);
- if (!fileName.isEmpty()) {
- QMdiSubWindow *existing = findMdiChild(fileName);
- if (existing) {
- mdiArea->setActiveSubWindow(existing);
- return;
- }
+ const QString fileName = QFileDialog::getOpenFileName(this);
+ if (!fileName.isEmpty())
+ openFile(fileName);
+}
- if (openFile(fileName))
- statusBar()->showMessage(tr("File loaded"), 2000);
+bool MainWindow::openFile(const QString &fileName)
+{
+ if (QMdiSubWindow *existing = findMdiChild(fileName)) {
+ mdiArea->setActiveSubWindow(existing);
+ return true;
}
+ const bool succeeded = loadFile(fileName);
+ if (succeeded)
+ statusBar()->showMessage(tr("File loaded"), 2000);
+ return succeeded;
}
-bool MainWindow::openFile(const QString &fileName)
+bool MainWindow::loadFile(const QString &fileName)
{
MdiChild *child = createMdiChild();
const bool succeeded = child->loadFile(fileName);
@@ -108,9 +107,87 @@ bool MainWindow::openFile(const QString &fileName)
child->show();
else
child->close();
+ MainWindow::prependToRecentFiles(fileName);
return succeeded;
}
+static inline QString recentFilesKey() { return QStringLiteral("recentFileList"); }
+static inline QString fileKey() { return QStringLiteral("file"); }
+
+static QStringList readRecentFiles(QSettings &settings)
+{
+ QStringList result;
+ const int count = settings.beginReadArray(recentFilesKey());
+ for (int i = 0; i < count; ++i) {
+ settings.setArrayIndex(i);
+ result.append(settings.value(fileKey()).toString());
+ }
+ settings.endArray();
+ return result;
+}
+
+static void writeRecentFiles(const QStringList &files, QSettings &settings)
+{
+ const int count = files.size();
+ settings.beginWriteArray(recentFilesKey());
+ for (int i = 0; i < count; ++i) {
+ settings.setArrayIndex(i);
+ settings.setValue(fileKey(), files.at(i));
+ }
+ settings.endArray();
+}
+
+bool MainWindow::hasRecentFiles()
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ const int count = settings.beginReadArray(recentFilesKey());
+ settings.endArray();
+ return count > 0;
+}
+
+void MainWindow::prependToRecentFiles(const QString &fileName)
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+
+ const QStringList oldRecentFiles = readRecentFiles(settings);
+ QStringList recentFiles = oldRecentFiles;
+ recentFiles.removeAll(fileName);
+ recentFiles.prepend(fileName);
+ if (oldRecentFiles != recentFiles)
+ writeRecentFiles(recentFiles, settings);
+
+ setRecentFilesVisible(!recentFiles.isEmpty());
+}
+
+void MainWindow::setRecentFilesVisible(bool visible)
+{
+ recentFileSubMenuAct->setVisible(visible);
+ recentFileSeparator->setVisible(visible);
+}
+
+void MainWindow::updateRecentFileActions()
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+
+ const QStringList recentFiles = readRecentFiles(settings);
+ const int count = qMin(int(MaxRecentFiles), recentFiles.size());
+ int i = 0;
+ for ( ; i < count; ++i) {
+ const QString fileName = QFileInfo(recentFiles.at(i)).fileName();
+ recentFileActs[i]->setText(tr("&%1 %2").arg(i + 1).arg(fileName));
+ recentFileActs[i]->setData(recentFiles.at(i));
+ recentFileActs[i]->setVisible(true);
+ }
+ for ( ; i < MaxRecentFiles; ++i)
+ recentFileActs[i]->setVisible(false);
+}
+
+void MainWindow::openRecentFile()
+{
+ if (const QAction *action = qobject_cast<const QAction *>(sender()))
+ openFile(action->data().toString());
+}
+
void MainWindow::save()
{
if (activeMdiChild() && activeMdiChild()->save())
@@ -119,8 +196,11 @@ void MainWindow::save()
void MainWindow::saveAs()
{
- if (activeMdiChild() && activeMdiChild()->saveAs())
+ MdiChild *child = activeMdiChild();
+ if (child && child->saveAs()) {
statusBar()->showMessage(tr("File saved"), 2000);
+ MainWindow::prependToRecentFiles(child->currentFile());
+ }
}
#ifndef QT_NO_CLIPBOARD
@@ -164,7 +244,7 @@ void MainWindow::updateMenus()
cascadeAct->setEnabled(hasMdiChild);
nextAct->setEnabled(hasMdiChild);
previousAct->setEnabled(hasMdiChild);
- separatorAct->setVisible(hasMdiChild);
+ windowMenuSeparatorAct->setVisible(hasMdiChild);
#ifndef QT_NO_CLIPBOARD
bool hasSelection = (activeMdiChild() &&
@@ -174,6 +254,16 @@ void MainWindow::updateMenus()
#endif
}
+class ActiveMdiSubWindowFunctor {
+public:
+ explicit ActiveMdiSubWindowFunctor(QMdiArea *mdiArea, QMdiSubWindow *activeWindow) : m_mdiArea(mdiArea), m_activeWindow(activeWindow) {}
+ void operator()() const { m_mdiArea->setActiveSubWindow(m_activeWindow); }
+
+private:
+ QMdiArea *m_mdiArea;
+ QMdiSubWindow *m_activeWindow;
+};
+
void MainWindow::updateWindowMenu()
{
windowMenu->clear();
@@ -185,13 +275,14 @@ void MainWindow::updateWindowMenu()
windowMenu->addSeparator();
windowMenu->addAction(nextAct);
windowMenu->addAction(previousAct);
- windowMenu->addAction(separatorAct);
+ windowMenu->addAction(windowMenuSeparatorAct);
QList<QMdiSubWindow *> windows = mdiArea->subWindowList();
- separatorAct->setVisible(!windows.isEmpty());
+ windowMenuSeparatorAct->setVisible(!windows.isEmpty());
for (int i = 0; i < windows.size(); ++i) {
- MdiChild *child = qobject_cast<MdiChild *>(windows.at(i)->widget());
+ QMdiSubWindow *mdiSubWindow = windows.at(i);
+ MdiChild *child = qobject_cast<MdiChild *>(mdiSubWindow->widget());
QString text;
if (i < 9) {
@@ -201,11 +292,9 @@ void MainWindow::updateWindowMenu()
text = tr("%1 %2").arg(i + 1)
.arg(child->userFriendlyCurrentFile());
}
- QAction *action = windowMenu->addAction(text);
+ QAction *action = windowMenu->addAction(text, mdiSubWindow, ActiveMdiSubWindowFunctor(mdiArea, mdiSubWindow));
action->setCheckable(true);
action ->setChecked(child == activeMdiChild());
- connect(action, SIGNAL(triggered()), windowMapper, SLOT(map()));
- windowMapper->setMapping(action, windows.at(i));
}
}
@@ -215,10 +304,8 @@ MdiChild *MainWindow::createMdiChild()
mdiArea->addSubWindow(child);
#ifndef QT_NO_CLIPBOARD
- connect(child, SIGNAL(copyAvailable(bool)),
- cutAct, SLOT(setEnabled(bool)));
- connect(child, SIGNAL(copyAvailable(bool)),
- copyAct, SLOT(setEnabled(bool)));
+ connect(child, &QTextEdit::copyAvailable, cutAct, &QAction::setEnabled);
+ connect(child, &QTextEdit::copyAvailable, copyAct, &QAction::setEnabled);
#endif
return child;
@@ -226,139 +313,143 @@ MdiChild *MainWindow::createMdiChild()
void MainWindow::createActions()
{
- newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
+ QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
+ QToolBar *fileToolBar = addToolBar(tr("File"));
+
+ const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(":/images/new.png"));
+ newAct = new QAction(newIcon, tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
- connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
+ connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
+ fileMenu->addAction(newAct);
+ fileToolBar->addAction(newAct);
- openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
+ const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png"));
+ QAction *openAct = new QAction(openIcon, tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
+ connect(openAct, &QAction::triggered, this, &MainWindow::open);
+ fileMenu->addAction(openAct);
+ fileToolBar->addAction(openAct);
- saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
+ const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png"));
+ saveAct = new QAction(saveIcon, tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::save);
+ fileToolBar->addAction(saveAct);
- saveAsAct = new QAction(tr("Save &As..."), this);
+ const QIcon saveAsIcon = QIcon::fromTheme("document-save-as");
+ saveAsAct = new QAction(saveAsIcon, tr("Save &As..."), this);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
- connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
+ connect(saveAsAct, &QAction::triggered, this, &MainWindow::saveAs);
+ fileMenu->addAction(saveAsAct);
+
+ fileMenu->addSeparator();
+
+ QMenu *recentMenu = fileMenu->addMenu(tr("Recent..."));
+ connect(recentMenu, &QMenu::aboutToShow, this, &MainWindow::updateRecentFileActions);
+ recentFileSubMenuAct = recentMenu->menuAction();
+
+ for (int i = 0; i < MaxRecentFiles; ++i) {
+ recentFileActs[i] = recentMenu->addAction(QString(), this, &MainWindow::openRecentFile);
+ recentFileActs[i]->setVisible(false);
+ }
+
+ recentFileSeparator = fileMenu->addSeparator();
+
+ setRecentFilesVisible(MainWindow::hasRecentFiles());
+
+ fileMenu->addAction(tr("Switch layout direction"), this, &MainWindow::switchLayoutDirection);
+
+ fileMenu->addSeparator();
//! [0]
- exitAct = new QAction(tr("E&xit"), this);
+ const QIcon exitIcon = QIcon::fromTheme("application-exit");
+ QAction *exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), qApp, &QApplication::closeAllWindows);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
+ fileMenu->addAction(exitAct);
//! [0]
#ifndef QT_NO_CLIPBOARD
- cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
+ QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
+ QToolBar *editToolBar = addToolBar(tr("Edit"));
+
+ const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(":/images/cut.png"));
+ cutAct = new QAction(cutIcon, tr("Cu&t"), this);
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
- connect(cutAct, SIGNAL(triggered()), this, SLOT(cut()));
+ connect(cutAct, &QAction::triggered, this, &MainWindow::cut);
+ editMenu->addAction(cutAct);
+ editToolBar->addAction(cutAct);
- copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
+ const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(":/images/copy.png"));
+ copyAct = new QAction(copyIcon, tr("&Copy"), this);
copyAct->setShortcuts(QKeySequence::Copy);
copyAct->setStatusTip(tr("Copy the current selection's contents to the "
"clipboard"));
- connect(copyAct, SIGNAL(triggered()), this, SLOT(copy()));
+ connect(copyAct, &QAction::triggered, this, &MainWindow::copy);
+ editMenu->addAction(copyAct);
+ editToolBar->addAction(copyAct);
- pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
+ const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(":/images/paste.png"));
+ pasteAct = new QAction(pasteIcon, tr("&Paste"), this);
pasteAct->setShortcuts(QKeySequence::Paste);
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
"selection"));
- connect(pasteAct, SIGNAL(triggered()), this, SLOT(paste()));
+ connect(pasteAct, &QAction::triggered, this, &MainWindow::paste);
+ editMenu->addAction(pasteAct);
+ editToolBar->addAction(pasteAct);
#endif
+ windowMenu = menuBar()->addMenu(tr("&Window"));
+ connect(windowMenu, &QMenu::aboutToShow, this, &MainWindow::updateWindowMenu);
+
closeAct = new QAction(tr("Cl&ose"), this);
closeAct->setStatusTip(tr("Close the active window"));
- connect(closeAct, SIGNAL(triggered()),
- mdiArea, SLOT(closeActiveSubWindow()));
+ connect(closeAct, &QAction::triggered,
+ mdiArea, &QMdiArea::closeActiveSubWindow);
closeAllAct = new QAction(tr("Close &All"), this);
closeAllAct->setStatusTip(tr("Close all the windows"));
- connect(closeAllAct, SIGNAL(triggered()),
- mdiArea, SLOT(closeAllSubWindows()));
+ connect(closeAllAct, &QAction::triggered, mdiArea, &QMdiArea::closeAllSubWindows);
tileAct = new QAction(tr("&Tile"), this);
tileAct->setStatusTip(tr("Tile the windows"));
- connect(tileAct, SIGNAL(triggered()), mdiArea, SLOT(tileSubWindows()));
+ connect(tileAct, &QAction::triggered, mdiArea, &QMdiArea::tileSubWindows);
cascadeAct = new QAction(tr("&Cascade"), this);
cascadeAct->setStatusTip(tr("Cascade the windows"));
- connect(cascadeAct, SIGNAL(triggered()), mdiArea, SLOT(cascadeSubWindows()));
+ connect(cascadeAct, &QAction::triggered, mdiArea, &QMdiArea::cascadeSubWindows);
nextAct = new QAction(tr("Ne&xt"), this);
nextAct->setShortcuts(QKeySequence::NextChild);
nextAct->setStatusTip(tr("Move the focus to the next window"));
- connect(nextAct, SIGNAL(triggered()),
- mdiArea, SLOT(activateNextSubWindow()));
+ connect(nextAct, &QAction::triggered, mdiArea, &QMdiArea::activateNextSubWindow);
previousAct = new QAction(tr("Pre&vious"), this);
previousAct->setShortcuts(QKeySequence::PreviousChild);
previousAct->setStatusTip(tr("Move the focus to the previous "
"window"));
- connect(previousAct, SIGNAL(triggered()),
- mdiArea, SLOT(activatePreviousSubWindow()));
-
- separatorAct = new QAction(this);
- separatorAct->setSeparator(true);
-
- aboutAct = new QAction(tr("&About"), this);
- aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
-
- aboutQtAct = new QAction(tr("About &Qt"), this);
- aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
-}
-
-void MainWindow::createMenus()
-{
- fileMenu = menuBar()->addMenu(tr("&File"));
- fileMenu->addAction(newAct);
- fileMenu->addAction(openAct);
- fileMenu->addAction(saveAct);
- fileMenu->addAction(saveAsAct);
- fileMenu->addSeparator();
- QAction *action = fileMenu->addAction(tr("Switch layout direction"));
- connect(action, SIGNAL(triggered()), this, SLOT(switchLayoutDirection()));
- fileMenu->addAction(exitAct);
+ connect(previousAct, &QAction::triggered, mdiArea, &QMdiArea::activatePreviousSubWindow);
- editMenu = menuBar()->addMenu(tr("&Edit"));
-#ifndef QT_NO_CLIPBOARD
- editMenu->addAction(cutAct);
- editMenu->addAction(copyAct);
- editMenu->addAction(pasteAct);
-#endif
+ windowMenuSeparatorAct = new QAction(this);
+ windowMenuSeparatorAct->setSeparator(true);
- windowMenu = menuBar()->addMenu(tr("&Window"));
updateWindowMenu();
- connect(windowMenu, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));
menuBar()->addSeparator();
- helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-}
+ QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
-void MainWindow::createToolBars()
-{
- fileToolBar = addToolBar(tr("File"));
- fileToolBar->addAction(newAct);
- fileToolBar->addAction(openAct);
- fileToolBar->addAction(saveAct);
+ QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about);
+ aboutAct->setStatusTip(tr("Show the application's About box"));
-#ifndef QT_NO_CLIPBOARD
- editToolBar = addToolBar(tr("Edit"));
- editToolBar->addAction(cutAct);
- editToolBar->addAction(copyAct);
- editToolBar->addAction(pasteAct);
-#endif
+ QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
+ aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
}
void MainWindow::createStatusBar()
@@ -368,28 +459,32 @@ void MainWindow::createStatusBar()
void MainWindow::readSettings()
{
- QSettings settings("QtProject", "MDI Example");
- QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
- QSize size = settings.value("size", QSize(400, 400)).toSize();
- move(pos);
- resize(size);
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
+ if (geometry.isEmpty()) {
+ const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
+ resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
+ move((availableGeometry.width() - width()) / 2,
+ (availableGeometry.height() - height()) / 2);
+ } else {
+ restoreGeometry(geometry);
+ }
}
void MainWindow::writeSettings()
{
- QSettings settings("QtProject", "MDI Example");
- settings.setValue("pos", pos());
- settings.setValue("size", size());
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ settings.setValue("geometry", saveGeometry());
}
-MdiChild *MainWindow::activeMdiChild()
+MdiChild *MainWindow::activeMdiChild() const
{
if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())
return qobject_cast<MdiChild *>(activeSubWindow->widget());
return 0;
}
-QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName)
+QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const
{
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
@@ -404,14 +499,7 @@ QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName)
void MainWindow::switchLayoutDirection()
{
if (layoutDirection() == Qt::LeftToRight)
- qApp->setLayoutDirection(Qt::RightToLeft);
+ QGuiApplication::setLayoutDirection(Qt::RightToLeft);
else
- qApp->setLayoutDirection(Qt::LeftToRight);
-}
-
-void MainWindow::setActiveSubWindow(QWidget *window)
-{
- if (!window)
- return;
- mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(window));
+ QGuiApplication::setLayoutDirection(Qt::LeftToRight);
}
diff --git a/examples/widgets/mainwindows/mdi/mainwindow.h b/examples/widgets/mainwindows/mdi/mainwindow.h
index fa8e0131e9..3ac60282fd 100644
--- a/examples/widgets/mainwindows/mdi/mainwindow.h
+++ b/examples/widgets/mainwindows/mdi/mainwindow.h
@@ -49,7 +49,6 @@ class QAction;
class QMenu;
class QMdiArea;
class QMdiSubWindow;
-class QSignalMapper;
QT_END_NAMESPACE
class MainWindow : public QMainWindow
@@ -69,6 +68,8 @@ private slots:
void open();
void save();
void saveAs();
+ void updateRecentFileActions();
+ void openRecentFile();
#ifndef QT_NO_CLIPBOARD
void cut();
void copy();
@@ -79,32 +80,30 @@ private slots:
void updateWindowMenu();
MdiChild *createMdiChild();
void switchLayoutDirection();
- void setActiveSubWindow(QWidget *window);
private:
+ enum { MaxRecentFiles = 5 };
+
void createActions();
- void createMenus();
- void createToolBars();
void createStatusBar();
void readSettings();
void writeSettings();
- MdiChild *activeMdiChild();
- QMdiSubWindow *findMdiChild(const QString &fileName);
+ bool loadFile(const QString &fileName);
+ static bool hasRecentFiles();
+ void prependToRecentFiles(const QString &fileName);
+ void setRecentFilesVisible(bool visible);
+ MdiChild *activeMdiChild() const;
+ QMdiSubWindow *findMdiChild(const QString &fileName) const;
QMdiArea *mdiArea;
- QSignalMapper *windowMapper;
- QMenu *fileMenu;
- QMenu *editMenu;
QMenu *windowMenu;
- QMenu *helpMenu;
- QToolBar *fileToolBar;
- QToolBar *editToolBar;
QAction *newAct;
- QAction *openAct;
QAction *saveAct;
QAction *saveAsAct;
- QAction *exitAct;
+ QAction *recentFileActs[MaxRecentFiles];
+ QAction *recentFileSeparator;
+ QAction *recentFileSubMenuAct;
#ifndef QT_NO_CLIPBOARD
QAction *cutAct;
QAction *copyAct;
@@ -116,9 +115,7 @@ private:
QAction *cascadeAct;
QAction *nextAct;
QAction *previousAct;
- QAction *separatorAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
+ QAction *windowMenuSeparatorAct;
};
#endif
diff --git a/examples/widgets/mainwindows/mdi/mdichild.cpp b/examples/widgets/mainwindows/mdi/mdichild.cpp
index 242e8248a2..73364eb3ee 100644
--- a/examples/widgets/mainwindows/mdi/mdichild.cpp
+++ b/examples/widgets/mainwindows/mdi/mdichild.cpp
@@ -56,8 +56,8 @@ void MdiChild::newFile()
curFile = tr("document%1.txt").arg(sequenceNumber++);
setWindowTitle(curFile + "[*]");
- connect(document(), SIGNAL(contentsChanged()),
- this, SLOT(documentWasModified()));
+ connect(document(), &QTextDocument::contentsChanged,
+ this, &MdiChild::documentWasModified);
}
bool MdiChild::loadFile(const QString &fileName)
@@ -78,8 +78,8 @@ bool MdiChild::loadFile(const QString &fileName)
setCurrentFile(fileName);
- connect(document(), SIGNAL(contentsChanged()),
- this, SLOT(documentWasModified()));
+ connect(document(), &QTextDocument::contentsChanged,
+ this, &MdiChild::documentWasModified);
return true;
}
@@ -109,8 +109,7 @@ bool MdiChild::saveFile(const QString &fileName)
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot write file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName), file.errorString()));
return false;
}
@@ -144,18 +143,22 @@ void MdiChild::documentWasModified()
bool MdiChild::maybeSave()
{
- if (document()->isModified()) {
- QMessageBox::StandardButton ret;
- ret = QMessageBox::warning(this, tr("MDI"),
- tr("'%1' has been modified.\n"
- "Do you want to save your changes?")
- .arg(userFriendlyCurrentFile()),
- QMessageBox::Save | QMessageBox::Discard
- | QMessageBox::Cancel);
- if (ret == QMessageBox::Save)
- return save();
- else if (ret == QMessageBox::Cancel)
- return false;
+ if (!document()->isModified())
+ return true;
+ const QMessageBox::StandardButton ret
+ = QMessageBox::warning(this, tr("MDI"),
+ tr("'%1' has been modified.\n"
+ "Do you want to save your changes?")
+ .arg(userFriendlyCurrentFile()),
+ QMessageBox::Save | QMessageBox::Discard
+ | QMessageBox::Cancel);
+ switch (ret) {
+ case QMessageBox::Save:
+ return save();
+ case QMessageBox::Cancel:
+ return false;
+ default:
+ break;
}
return true;
}
diff --git a/examples/widgets/mainwindows/menus/mainwindow.cpp b/examples/widgets/mainwindows/menus/mainwindow.cpp
index 31515394bd..d487e3a277 100644
--- a/examples/widgets/mainwindows/menus/mainwindow.cpp
+++ b/examples/widgets/mainwindows/menus/mainwindow.cpp
@@ -198,63 +198,63 @@ void MainWindow::createActions()
newAct = new QAction(tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
- connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
+ connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
//! [4]
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
+ connect(openAct, &QAction::triggered, this, &MainWindow::open);
//! [5]
saveAct = new QAction(tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::save);
printAct = new QAction(tr("&Print..."), this);
printAct->setShortcuts(QKeySequence::Print);
printAct->setStatusTip(tr("Print the document"));
- connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
+ connect(printAct, &QAction::triggered, this, &MainWindow::print);
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
+ connect(exitAct, &QAction::triggered, this, &QWidget::close);
undoAct = new QAction(tr("&Undo"), this);
undoAct->setShortcuts(QKeySequence::Undo);
undoAct->setStatusTip(tr("Undo the last operation"));
- connect(undoAct, SIGNAL(triggered()), this, SLOT(undo()));
+ connect(undoAct, &QAction::triggered, this, &MainWindow::undo);
redoAct = new QAction(tr("&Redo"), this);
redoAct->setShortcuts(QKeySequence::Redo);
redoAct->setStatusTip(tr("Redo the last operation"));
- connect(redoAct, SIGNAL(triggered()), this, SLOT(redo()));
+ connect(redoAct, &QAction::triggered, this, &MainWindow::redo);
cutAct = new QAction(tr("Cu&t"), this);
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
- connect(cutAct, SIGNAL(triggered()), this, SLOT(cut()));
+ connect(cutAct, &QAction::triggered, this, &MainWindow::cut);
copyAct = new QAction(tr("&Copy"), this);
copyAct->setShortcuts(QKeySequence::Copy);
copyAct->setStatusTip(tr("Copy the current selection's contents to the "
"clipboard"));
- connect(copyAct, SIGNAL(triggered()), this, SLOT(copy()));
+ connect(copyAct, &QAction::triggered, this, &MainWindow::copy);
pasteAct = new QAction(tr("&Paste"), this);
pasteAct->setShortcuts(QKeySequence::Paste);
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
"selection"));
- connect(pasteAct, SIGNAL(triggered()), this, SLOT(paste()));
+ connect(pasteAct, &QAction::triggered, this, &MainWindow::paste);
boldAct = new QAction(tr("&Bold"), this);
boldAct->setCheckable(true);
boldAct->setShortcut(QKeySequence::Bold);
boldAct->setStatusTip(tr("Make the text bold"));
- connect(boldAct, SIGNAL(triggered()), this, SLOT(bold()));
+ connect(boldAct, &QAction::triggered, this, &MainWindow::bold);
QFont boldFont = boldAct->font();
boldFont.setBold(true);
@@ -264,7 +264,7 @@ void MainWindow::createActions()
italicAct->setCheckable(true);
italicAct->setShortcut(QKeySequence::Italic);
italicAct->setStatusTip(tr("Make the text italic"));
- connect(italicAct, SIGNAL(triggered()), this, SLOT(italic()));
+ connect(italicAct, &QAction::triggered, this, &MainWindow::italic);
QFont italicFont = italicAct->font();
italicFont.setItalic(true);
@@ -273,45 +273,45 @@ void MainWindow::createActions()
setLineSpacingAct = new QAction(tr("Set &Line Spacing..."), this);
setLineSpacingAct->setStatusTip(tr("Change the gap between the lines of a "
"paragraph"));
- connect(setLineSpacingAct, SIGNAL(triggered()), this, SLOT(setLineSpacing()));
+ connect(setLineSpacingAct, &QAction::triggered, this, &MainWindow::setLineSpacing);
setParagraphSpacingAct = new QAction(tr("Set &Paragraph Spacing..."), this);
setParagraphSpacingAct->setStatusTip(tr("Change the gap between paragraphs"));
- connect(setParagraphSpacingAct, SIGNAL(triggered()),
- this, SLOT(setParagraphSpacing()));
+ connect(setParagraphSpacingAct, &QAction::triggered,
+ this, &MainWindow::setParagraphSpacing);
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
+ connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
- connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt()));
+ connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
+ connect(aboutQtAct, &QAction::triggered, this, &MainWindow::aboutQt);
leftAlignAct = new QAction(tr("&Left Align"), this);
leftAlignAct->setCheckable(true);
leftAlignAct->setShortcut(tr("Ctrl+L"));
leftAlignAct->setStatusTip(tr("Left align the selected text"));
- connect(leftAlignAct, SIGNAL(triggered()), this, SLOT(leftAlign()));
+ connect(leftAlignAct, &QAction::triggered, this, &MainWindow::leftAlign);
rightAlignAct = new QAction(tr("&Right Align"), this);
rightAlignAct->setCheckable(true);
rightAlignAct->setShortcut(tr("Ctrl+R"));
rightAlignAct->setStatusTip(tr("Right align the selected text"));
- connect(rightAlignAct, SIGNAL(triggered()), this, SLOT(rightAlign()));
+ connect(rightAlignAct, &QAction::triggered, this, &MainWindow::rightAlign);
justifyAct = new QAction(tr("&Justify"), this);
justifyAct->setCheckable(true);
justifyAct->setShortcut(tr("Ctrl+J"));
justifyAct->setStatusTip(tr("Justify the selected text"));
- connect(justifyAct, SIGNAL(triggered()), this, SLOT(justify()));
+ connect(justifyAct, &QAction::triggered, this, &MainWindow::justify);
centerAct = new QAction(tr("&Center"), this);
centerAct->setCheckable(true);
centerAct->setShortcut(tr("Ctrl+E"));
centerAct->setStatusTip(tr("Center the selected text"));
- connect(centerAct, SIGNAL(triggered()), this, SLOT(center()));
+ connect(centerAct, &QAction::triggered, this, &MainWindow::center);
//! [6] //! [7]
alignmentGroup = new QActionGroup(this);
diff --git a/examples/widgets/mainwindows/recentfiles/mainwindow.cpp b/examples/widgets/mainwindows/recentfiles/mainwindow.cpp
deleted file mode 100644
index b89797092a..0000000000
--- a/examples/widgets/mainwindows/recentfiles/mainwindow.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** You may use this file under the terms of the BSD license as follows:
-**
-** "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 The Qt Company Ltd 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."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtWidgets>
-
-#include "mainwindow.h"
-
-MainWindow::MainWindow()
-{
- setAttribute(Qt::WA_DeleteOnClose);
-
- textEdit = new QTextEdit;
- setCentralWidget(textEdit);
-
- createActions();
- createMenus();
- (void)statusBar();
-
- setWindowFilePath(QString());
- resize(400, 300);
-}
-
-void MainWindow::newFile()
-{
- MainWindow *other = new MainWindow;
- other->show();
-}
-
-void MainWindow::open()
-{
- QString fileName = QFileDialog::getOpenFileName(this);
- if (!fileName.isEmpty())
- loadFile(fileName);
-}
-
-void MainWindow::save()
-{
- if (curFile.isEmpty())
- saveAs();
- else
- saveFile(curFile);
-}
-
-void MainWindow::saveAs()
-{
- QString fileName = QFileDialog::getSaveFileName(this);
- if (fileName.isEmpty())
- return;
-
- saveFile(fileName);
-}
-
-void MainWindow::openRecentFile()
-{
- QAction *action = qobject_cast<QAction *>(sender());
- if (action)
- loadFile(action->data().toString());
-}
-
-void MainWindow::about()
-{
- QMessageBox::about(this, tr("About Recent Files"),
- tr("The <b>Recent Files</b> example demonstrates how to provide a "
- "recently used file menu in a Qt application."));
-}
-
-void MainWindow::createActions()
-{
- newAct = new QAction(tr("&New"), this);
- newAct->setShortcuts(QKeySequence::New);
- newAct->setStatusTip(tr("Create a new file"));
- connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
-
- openAct = new QAction(tr("&Open..."), this);
- openAct->setShortcuts(QKeySequence::Open);
- openAct->setStatusTip(tr("Open an existing file"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
-
- saveAct = new QAction(tr("&Save"), this);
- saveAct->setShortcuts(QKeySequence::Save);
- saveAct->setStatusTip(tr("Save the document to disk"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
-
- saveAsAct = new QAction(tr("Save &As..."), this);
- saveAsAct->setShortcuts(QKeySequence::SaveAs);
- saveAsAct->setStatusTip(tr("Save the document under a new name"));
- connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
-
- for (int i = 0; i < MaxRecentFiles; ++i) {
- recentFileActs[i] = new QAction(this);
- recentFileActs[i]->setVisible(false);
- connect(recentFileActs[i], SIGNAL(triggered()),
- this, SLOT(openRecentFile()));
- }
-
- exitAct = new QAction(tr("E&xit"), this);
- exitAct->setShortcuts(QKeySequence::Quit);
- exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
-
- aboutAct = new QAction(tr("&About"), this);
- aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
-
- aboutQtAct = new QAction(tr("About &Qt"), this);
- aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
-}
-
-void MainWindow::createMenus()
-{
- fileMenu = menuBar()->addMenu(tr("&File"));
- fileMenu->addAction(newAct);
- fileMenu->addAction(openAct);
- fileMenu->addAction(saveAct);
- fileMenu->addAction(saveAsAct);
- separatorAct = fileMenu->addSeparator();
- for (int i = 0; i < MaxRecentFiles; ++i)
- fileMenu->addAction(recentFileActs[i]);
- fileMenu->addSeparator();
- fileMenu->addAction(exitAct);
- updateRecentFileActions();
-
- menuBar()->addSeparator();
-
- helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-}
-
-void MainWindow::loadFile(const QString &fileName)
-{
- QFile file(fileName);
- if (!file.open(QFile::ReadOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("Recent Files"),
- tr("Cannot read file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
- return;
- }
-
- QTextStream in(&file);
- QApplication::setOverrideCursor(Qt::WaitCursor);
- textEdit->setPlainText(in.readAll());
- QApplication::restoreOverrideCursor();
-
- setCurrentFile(fileName);
- statusBar()->showMessage(tr("File loaded"), 2000);
-}
-
-void MainWindow::saveFile(const QString &fileName)
-{
- QFile file(fileName);
- if (!file.open(QFile::WriteOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("Recent Files"),
- tr("Cannot write file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
- return;
- }
-
- QTextStream out(&file);
- QApplication::setOverrideCursor(Qt::WaitCursor);
- out << textEdit->toPlainText();
- QApplication::restoreOverrideCursor();
-
- setCurrentFile(fileName);
- statusBar()->showMessage(tr("File saved"), 2000);
-}
-
-void MainWindow::setCurrentFile(const QString &fileName)
-{
- curFile = fileName;
- setWindowFilePath(curFile);
-
- QSettings settings;
- QStringList files = settings.value("recentFileList").toStringList();
- files.removeAll(fileName);
- files.prepend(fileName);
- while (files.size() > MaxRecentFiles)
- files.removeLast();
-
- settings.setValue("recentFileList", files);
-
- foreach (QWidget *widget, QApplication::topLevelWidgets()) {
- MainWindow *mainWin = qobject_cast<MainWindow *>(widget);
- if (mainWin)
- mainWin->updateRecentFileActions();
- }
-}
-
-void MainWindow::updateRecentFileActions()
-{
- QSettings settings;
- QStringList files = settings.value("recentFileList").toStringList();
-
- int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles);
-
- for (int i = 0; i < numRecentFiles; ++i) {
- QString text = tr("&%1 %2").arg(i + 1).arg(strippedName(files[i]));
- recentFileActs[i]->setText(text);
- recentFileActs[i]->setData(files[i]);
- recentFileActs[i]->setVisible(true);
- }
- for (int j = numRecentFiles; j < MaxRecentFiles; ++j)
- recentFileActs[j]->setVisible(false);
-
- separatorAct->setVisible(numRecentFiles > 0);
-}
-
-QString MainWindow::strippedName(const QString &fullFileName)
-{
- return QFileInfo(fullFileName).fileName();
-}
diff --git a/examples/widgets/mainwindows/recentfiles/recentfiles.pro b/examples/widgets/mainwindows/recentfiles/recentfiles.pro
deleted file mode 100644
index ccf948f560..0000000000
--- a/examples/widgets/mainwindows/recentfiles/recentfiles.pro
+++ /dev/null
@@ -1,9 +0,0 @@
-QT += widgets
-
-HEADERS = mainwindow.h
-SOURCES = main.cpp \
- mainwindow.cpp
-
-# install
-target.path = $$[QT_INSTALL_EXAMPLES]/widgets/mainwindows/recentfiles
-INSTALLS += target
diff --git a/examples/widgets/mainwindows/sdi/main.cpp b/examples/widgets/mainwindows/sdi/main.cpp
index d3350da946..4b125722d8 100644
--- a/examples/widgets/mainwindows/sdi/main.cpp
+++ b/examples/widgets/mainwindows/sdi/main.cpp
@@ -39,6 +39,7 @@
****************************************************************************/
#include <QApplication>
+#include <QCommandLineParser>
#include "mainwindow.h"
@@ -46,9 +47,27 @@ int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(sdi);
QApplication app(argc, argv);
- app.setApplicationName("SDI Example");
- app.setOrganizationName("QtProject");
- MainWindow *mainWin = new MainWindow;
+ QCoreApplication::setApplicationName("SDI Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ parser.addPositionalArgument("file", "The file(s) to open.");
+ parser.process(app);
+
+ MainWindow *mainWin = Q_NULLPTR;
+ foreach (const QString &file, parser.positionalArguments()) {
+ MainWindow *newWin = new MainWindow(file);
+ newWin->tile(mainWin);
+ newWin->show();
+ mainWin = newWin;
+ }
+
+ if (!mainWin)
+ mainWin = new MainWindow;
mainWin->show();
+
return app.exec();
}
diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp
index 1d6226e45c..f59172f172 100644
--- a/examples/widgets/mainwindows/sdi/mainwindow.cpp
+++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp
@@ -45,7 +45,7 @@
MainWindow::MainWindow()
{
init();
- setCurrentFile("");
+ setCurrentFile(QString());
}
MainWindow::MainWindow(const QString &fileName)
@@ -67,44 +67,44 @@ void MainWindow::closeEvent(QCloseEvent *event)
void MainWindow::newFile()
{
MainWindow *other = new MainWindow;
- other->move(x() + 40, y() + 40);
+ other->tile(this);
other->show();
}
void MainWindow::open()
{
- QString fileName = QFileDialog::getOpenFileName(this);
- if (!fileName.isEmpty()) {
- MainWindow *existing = findMainWindow(fileName);
- if (existing) {
- existing->show();
- existing->raise();
- existing->activateWindow();
- return;
- }
-
- if (isUntitled && textEdit->document()->isEmpty()
- && !isWindowModified()) {
- loadFile(fileName);
- } else {
- MainWindow *other = new MainWindow(fileName);
- if (other->isUntitled) {
- delete other;
- return;
- }
- other->move(x() + 40, y() + 40);
- other->show();
- }
+ const QString fileName = QFileDialog::getOpenFileName(this);
+ if (!fileName.isEmpty())
+ openFile(fileName);
+}
+
+void MainWindow::openFile(const QString &fileName)
+{
+ MainWindow *existing = findMainWindow(fileName);
+ if (existing) {
+ existing->show();
+ existing->raise();
+ existing->activateWindow();
+ return;
+ }
+
+ if (isUntitled && textEdit->document()->isEmpty() && !isWindowModified()) {
+ loadFile(fileName);
+ return;
}
+
+ MainWindow *other = new MainWindow(fileName);
+ if (other->isUntitled) {
+ delete other;
+ return;
+ }
+ other->tile(this);
+ other->show();
}
bool MainWindow::save()
{
- if (isUntitled) {
- return saveAs();
- } else {
- return saveFile(curFile);
- }
+ return isUntitled ? saveAs() : saveFile(curFile);
}
bool MainWindow::saveAs()
@@ -139,123 +139,135 @@ void MainWindow::init()
setCentralWidget(textEdit);
createActions();
- createMenus();
- createToolBars();
createStatusBar();
readSettings();
- connect(textEdit->document(), SIGNAL(contentsChanged()),
- this, SLOT(documentWasModified()));
+ connect(textEdit->document(), &QTextDocument::contentsChanged,
+ this, &MainWindow::documentWasModified);
setUnifiedTitleAndToolBarOnMac(true);
}
+void MainWindow::tile(const QMainWindow *previous)
+{
+ if (!previous)
+ return;
+ int topFrameWidth = previous->geometry().top() - previous->pos().y();
+ if (!topFrameWidth)
+ topFrameWidth = 40;
+ const QPoint pos = previous->pos() + 2 * QPoint(topFrameWidth, topFrameWidth);
+ if (QApplication::desktop()->availableGeometry(this).contains(rect().bottomRight() + pos))
+ move(pos);
+}
+
+//! [implicit tr context]
void MainWindow::createActions()
{
- newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
+ QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
+//! [implicit tr context]
+ QToolBar *fileToolBar = addToolBar(tr("File"));
+
+ const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(":/images/new.png"));
+ QAction *newAct = new QAction(newIcon, tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
- connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
+ connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
+ fileMenu->addAction(newAct);
+ fileToolBar->addAction(newAct);
- openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
+ const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png"));
+ QAction *openAct = new QAction(openIcon, tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
+ connect(openAct, &QAction::triggered, this, &MainWindow::open);
+ fileMenu->addAction(openAct);
+ fileToolBar->addAction(openAct);
- saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
+ const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png"));
+ QAction *saveAct = new QAction(saveIcon, tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
- connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
+ connect(saveAct, &QAction::triggered, this, &MainWindow::save);
+ fileMenu->addAction(saveAct);
+ fileToolBar->addAction(saveAct);
- saveAsAct = new QAction(tr("Save &As..."), this);
+ const QIcon saveAsIcon = QIcon::fromTheme("document-save-as");
+ QAction *saveAsAct = fileMenu->addAction(saveAsIcon, tr("Save &As..."), this, &MainWindow::saveAs);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
- connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
- closeAct = new QAction(tr("&Close"), this);
+ fileMenu->addSeparator();
+
+ QMenu *recentMenu = fileMenu->addMenu(tr("Recent..."));
+ connect(recentMenu, &QMenu::aboutToShow, this, &MainWindow::updateRecentFileActions);
+ recentFileSubMenuAct = recentMenu->menuAction();
+
+ for (int i = 0; i < MaxRecentFiles; ++i) {
+ recentFileActs[i] = recentMenu->addAction(QString(), this, &MainWindow::openRecentFile);
+ recentFileActs[i]->setVisible(false);
+ }
+
+ recentFileSeparator = fileMenu->addSeparator();
+
+ setRecentFilesVisible(MainWindow::hasRecentFiles());
+
+ QAction *closeAct = fileMenu->addAction(tr("&Close"), this, &QWidget::close);
closeAct->setShortcut(tr("Ctrl+W"));
closeAct->setStatusTip(tr("Close this window"));
- connect(closeAct, SIGNAL(triggered()), this, SLOT(close()));
- exitAct = new QAction(tr("E&xit"), this);
+ const QIcon exitIcon = QIcon::fromTheme("application-exit");
+ QAction *exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), qApp, &QApplication::closeAllWindows);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
- cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
+ QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
+ QToolBar *editToolBar = addToolBar(tr("Edit"));
+
+#ifndef QT_NO_CLIPBOARD
+ const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(":/images/cut.png"));
+ QAction *cutAct = new QAction(cutIcon, tr("Cu&t"), this);
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
- connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));
+ connect(cutAct, &QAction::triggered, textEdit, &QTextEdit::cut);
+ editMenu->addAction(cutAct);
+ editToolBar->addAction(cutAct);
- copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
+ const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(":/images/copy.png"));
+ QAction *copyAct = new QAction(copyIcon, tr("&Copy"), this);
copyAct->setShortcuts(QKeySequence::Copy);
copyAct->setStatusTip(tr("Copy the current selection's contents to the "
"clipboard"));
- connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));
+ connect(copyAct, &QAction::triggered, textEdit, &QTextEdit::copy);
+ editMenu->addAction(copyAct);
+ editToolBar->addAction(copyAct);
- pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
+ const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(":/images/paste.png"));
+ QAction *pasteAct = new QAction(pasteIcon, tr("&Paste"), this);
pasteAct->setShortcuts(QKeySequence::Paste);
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
"selection"));
- connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));
+ connect(pasteAct, &QAction::triggered, textEdit, &QTextEdit::paste);
+ editMenu->addAction(pasteAct);
+ editToolBar->addAction(pasteAct);
+
+ menuBar()->addSeparator();
+#endif // !QT_NO_CLIPBOARD
- aboutAct = new QAction(tr("&About"), this);
+ QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
+ QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about);
aboutAct->setStatusTip(tr("Show the application's About box"));
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
- aboutQtAct = new QAction(tr("About &Qt"), this);
+ QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
-
+#ifndef QT_NO_CLIPBOARD
cutAct->setEnabled(false);
copyAct->setEnabled(false);
- connect(textEdit, SIGNAL(copyAvailable(bool)),
- cutAct, SLOT(setEnabled(bool)));
- connect(textEdit, SIGNAL(copyAvailable(bool)),
- copyAct, SLOT(setEnabled(bool)));
-}
-
-//! [implicit tr context]
-void MainWindow::createMenus()
-{
- fileMenu = menuBar()->addMenu(tr("&File"));
-//! [implicit tr context]
- fileMenu->addAction(newAct);
- fileMenu->addAction(openAct);
- fileMenu->addAction(saveAct);
- fileMenu->addAction(saveAsAct);
- fileMenu->addSeparator();
- fileMenu->addAction(closeAct);
- fileMenu->addAction(exitAct);
-
- editMenu = menuBar()->addMenu(tr("&Edit"));
- editMenu->addAction(cutAct);
- editMenu->addAction(copyAct);
- editMenu->addAction(pasteAct);
-
- menuBar()->addSeparator();
-
- helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-}
-
-void MainWindow::createToolBars()
-{
-//! [0]
- fileToolBar = addToolBar(tr("File"));
- fileToolBar->addAction(newAct);
- fileToolBar->addAction(openAct);
-//! [0]
- fileToolBar->addAction(saveAct);
-
- editToolBar = addToolBar(tr("Edit"));
- editToolBar->addAction(cutAct);
- editToolBar->addAction(copyAct);
- editToolBar->addAction(pasteAct);
+ connect(textEdit, &QTextEdit::copyAvailable, cutAct, &QAction::setEnabled);
+ connect(textEdit, &QTextEdit::copyAvailable, copyAct, &QAction::setEnabled);
+#endif // !QT_NO_CLIPBOARD
}
void MainWindow::createStatusBar()
@@ -265,33 +277,41 @@ void MainWindow::createStatusBar()
void MainWindow::readSettings()
{
- QSettings settings;
- QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
- QSize size = settings.value("size", QSize(400, 400)).toSize();
- move(pos);
- resize(size);
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
+ if (geometry.isEmpty()) {
+ const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
+ resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
+ move((availableGeometry.width() - width()) / 2,
+ (availableGeometry.height() - height()) / 2);
+ } else {
+ restoreGeometry(geometry);
+ }
}
void MainWindow::writeSettings()
{
- QSettings settings;
- settings.setValue("pos", pos());
- settings.setValue("size", size());
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ settings.setValue("geometry", saveGeometry());
}
bool MainWindow::maybeSave()
{
- if (textEdit->document()->isModified()) {
- QMessageBox::StandardButton ret;
- ret = QMessageBox::warning(this, tr("SDI"),
- tr("The document has been modified.\n"
- "Do you want to save your changes?"),
- QMessageBox::Save | QMessageBox::Discard
- | QMessageBox::Cancel);
- if (ret == QMessageBox::Save)
- return save();
- else if (ret == QMessageBox::Cancel)
- return false;
+ if (!textEdit->document()->isModified())
+ return true;
+ const QMessageBox::StandardButton ret
+ = QMessageBox::warning(this, tr("SDI"),
+ tr("The document has been modified.\n"
+ "Do you want to save your changes?"),
+ QMessageBox::Save | QMessageBox::Discard
+ | QMessageBox::Cancel);
+ switch (ret) {
+ case QMessageBox::Save:
+ return save();
+ case QMessageBox::Cancel:
+ return false;
+ default:
+ break;
}
return true;
}
@@ -303,8 +323,7 @@ void MainWindow::loadFile(const QString &fileName)
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("SDI"),
tr("Cannot read file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName), file.errorString()));
return;
}
@@ -317,14 +336,90 @@ void MainWindow::loadFile(const QString &fileName)
statusBar()->showMessage(tr("File loaded"), 2000);
}
+void MainWindow::setRecentFilesVisible(bool visible)
+{
+ recentFileSubMenuAct->setVisible(visible);
+ recentFileSeparator->setVisible(visible);
+}
+
+static inline QString recentFilesKey() { return QStringLiteral("recentFileList"); }
+static inline QString fileKey() { return QStringLiteral("file"); }
+
+static QStringList readRecentFiles(QSettings &settings)
+{
+ QStringList result;
+ const int count = settings.beginReadArray(recentFilesKey());
+ for (int i = 0; i < count; ++i) {
+ settings.setArrayIndex(i);
+ result.append(settings.value(fileKey()).toString());
+ }
+ settings.endArray();
+ return result;
+}
+
+static void writeRecentFiles(const QStringList &files, QSettings &settings)
+{
+ const int count = files.size();
+ settings.beginWriteArray(recentFilesKey());
+ for (int i = 0; i < count; ++i) {
+ settings.setArrayIndex(i);
+ settings.setValue(fileKey(), files.at(i));
+ }
+ settings.endArray();
+}
+
+bool MainWindow::hasRecentFiles()
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+ const int count = settings.beginReadArray(recentFilesKey());
+ settings.endArray();
+ return count > 0;
+}
+
+void MainWindow::prependToRecentFiles(const QString &fileName)
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+
+ const QStringList oldRecentFiles = readRecentFiles(settings);
+ QStringList recentFiles = oldRecentFiles;
+ recentFiles.removeAll(fileName);
+ recentFiles.prepend(fileName);
+ if (oldRecentFiles != recentFiles)
+ writeRecentFiles(recentFiles, settings);
+
+ setRecentFilesVisible(!recentFiles.isEmpty());
+}
+
+void MainWindow::updateRecentFileActions()
+{
+ QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
+
+ const QStringList recentFiles = readRecentFiles(settings);
+ const int count = qMin(int(MaxRecentFiles), recentFiles.size());
+ int i = 0;
+ for ( ; i < count; ++i) {
+ const QString fileName = MainWindow::strippedName(recentFiles.at(i));
+ recentFileActs[i]->setText(tr("&%1 %2").arg(i + 1).arg(fileName));
+ recentFileActs[i]->setData(recentFiles.at(i));
+ recentFileActs[i]->setVisible(true);
+ }
+ for ( ; i < MaxRecentFiles; ++i)
+ recentFileActs[i]->setVisible(false);
+}
+
+void MainWindow::openRecentFile()
+{
+ if (const QAction *action = qobject_cast<const QAction *>(sender()))
+ openFile(action->data().toString());
+}
+
bool MainWindow::saveFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("SDI"),
tr("Cannot write file %1:\n%2.")
- .arg(fileName)
- .arg(file.errorString()));
+ .arg(QDir::toNativeSeparators(fileName), file.errorString()));
return false;
}
@@ -351,6 +446,10 @@ void MainWindow::setCurrentFile(const QString &fileName)
textEdit->document()->setModified(false);
setWindowModified(false);
+
+ if (!isUntitled && windowFilePath() != curFile)
+ MainWindow::prependToRecentFiles(curFile);
+
setWindowFilePath(curFile);
}
@@ -359,14 +458,15 @@ QString MainWindow::strippedName(const QString &fullFileName)
return QFileInfo(fullFileName).fileName();
}
-MainWindow *MainWindow::findMainWindow(const QString &fileName)
+MainWindow *MainWindow::findMainWindow(const QString &fileName) const
{
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
- foreach (QWidget *widget, qApp->topLevelWidgets()) {
+ foreach (QWidget *widget, QApplication::topLevelWidgets()) {
MainWindow *mainWin = qobject_cast<MainWindow *>(widget);
if (mainWin && mainWin->curFile == canonicalFilePath)
return mainWin;
}
+
return 0;
}
diff --git a/examples/widgets/mainwindows/sdi/mainwindow.h b/examples/widgets/mainwindows/sdi/mainwindow.h
index f1860a8511..66ac618c72 100644
--- a/examples/widgets/mainwindows/sdi/mainwindow.h
+++ b/examples/widgets/mainwindows/sdi/mainwindow.h
@@ -42,6 +42,7 @@
#define MAINWINDOW_H
#include <QMainWindow>
+#include <QList>
QT_BEGIN_NAMESPACE
class QAction;
@@ -57,7 +58,9 @@ class MainWindow : public QMainWindow
public:
MainWindow();
//! [class definition with macro]
- MainWindow(const QString &fileName);
+ explicit MainWindow(const QString &fileName);
+
+ void tile(const QMainWindow *previous);
protected:
void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;
@@ -67,44 +70,38 @@ private slots:
void open();
bool save();
bool saveAs();
+ void updateRecentFileActions();
+ void openRecentFile();
void about();
void documentWasModified();
private:
+ enum { MaxRecentFiles = 5 };
+
void init();
void createActions();
- void createMenus();
- void createToolBars();
void createStatusBar();
void readSettings();
void writeSettings();
bool maybeSave();
+ void openFile(const QString &fileName);
void loadFile(const QString &fileName);
+ static bool hasRecentFiles();
+ void prependToRecentFiles(const QString &fileName);
+ void setRecentFilesVisible(bool visible);
bool saveFile(const QString &fileName);
void setCurrentFile(const QString &fileName);
- QString strippedName(const QString &fullFileName);
- MainWindow *findMainWindow(const QString &fileName);
+ static QString strippedName(const QString &fullFileName);
+ MainWindow *findMainWindow(const QString &fileName) const;
QTextEdit *textEdit;
+
+ QAction *recentFileActs[MaxRecentFiles];
+ QAction *recentFileSeparator;
+ QAction *recentFileSubMenuAct;
+
QString curFile;
bool isUntitled;
-
- QMenu *fileMenu;
- QMenu *editMenu;
- QMenu *helpMenu;
- QToolBar *fileToolBar;
- QToolBar *editToolBar;
- QAction *newAct;
- QAction *openAct;
- QAction *saveAct;
- QAction *saveAsAct;
- QAction *closeAct;
- QAction *exitAct;
- QAction *cutAct;
- QAction *copyAct;
- QAction *pasteAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
};
#endif
diff --git a/examples/widgets/painting/fontsampler/mainwindow.cpp b/examples/widgets/painting/fontsampler/mainwindow.cpp
index bff8ae9c22..53a2aac82e 100644
--- a/examples/widgets/painting/fontsampler/mainwindow.cpp
+++ b/examples/widgets/painting/fontsampler/mainwindow.cpp
@@ -80,7 +80,7 @@ void MainWindow::setupFontTree()
QTreeWidgetItem *familyItem = new QTreeWidgetItem(fontTree);
familyItem->setText(0, family);
familyItem->setCheckState(0, Qt::Unchecked);
- familyItem->setFlags(familyItem->flags() | Qt::ItemIsTristate);
+ familyItem->setFlags(familyItem->flags() | Qt::ItemIsAutoTristate);
foreach (QString style, styles) {
QTreeWidgetItem *styleItem = new QTreeWidgetItem(familyItem);
diff --git a/examples/widgets/richtext/syntaxhighlighter/syntaxhighlighter.pro b/examples/widgets/richtext/syntaxhighlighter/syntaxhighlighter.pro
index 19f471b5cf..93cd950b0b 100644
--- a/examples/widgets/richtext/syntaxhighlighter/syntaxhighlighter.pro
+++ b/examples/widgets/richtext/syntaxhighlighter/syntaxhighlighter.pro
@@ -14,5 +14,5 @@ INSTALLS += target
wince {
addFiles.files = main.cpp mainwindow.cpp
addFiles.path = .
- DEPLOYMENT += addFiles
+ INSTALLS += addFiles
}
diff --git a/examples/widgets/tools/regularexpression/images/copy.png b/examples/widgets/tools/regularexpression/images/copy.png
new file mode 100644
index 0000000000..2aeb28288f
--- /dev/null
+++ b/examples/widgets/tools/regularexpression/images/copy.png
Binary files differ
diff --git a/examples/widgets/mainwindows/recentfiles/main.cpp b/examples/widgets/tools/regularexpression/main.cpp
index 23ff3eda16..a5ef410688 100644
--- a/examples/widgets/mainwindows/recentfiles/main.cpp
+++ b/examples/widgets/tools/regularexpression/main.cpp
@@ -38,16 +38,14 @@
**
****************************************************************************/
-#include <QApplication>
+#include "regularexpressiondialog.h"
-#include "mainwindow.h"
+#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
- app.setOrganizationName("QtProject");
- app.setApplicationName("Recent Files Example");
- MainWindow *mainWin = new MainWindow;
- mainWin->show();
+ RegularExpressionDialog dialog;
+ dialog.show();
return app.exec();
}
diff --git a/examples/widgets/tools/regularexpression/regularexpression.pro b/examples/widgets/tools/regularexpression/regularexpression.pro
new file mode 100644
index 0000000000..8e72e171b8
--- /dev/null
+++ b/examples/widgets/tools/regularexpression/regularexpression.pro
@@ -0,0 +1,11 @@
+QT += widgets
+
+HEADERS = regularexpressiondialog.h
+SOURCES = regularexpressiondialog.cpp \
+ main.cpp
+
+RESOURCES += regularexpression.qrc
+
+# install
+target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tools/regularexpression
+INSTALLS += target
diff --git a/examples/widgets/tools/regularexpression/regularexpression.qrc b/examples/widgets/tools/regularexpression/regularexpression.qrc
new file mode 100644
index 0000000000..ce7e104af3
--- /dev/null
+++ b/examples/widgets/tools/regularexpression/regularexpression.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>images/copy.png</file>
+</qresource>
+</RCC>
diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp
new file mode 100644
index 0000000000..d40b4b325d
--- /dev/null
+++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp
@@ -0,0 +1,349 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
+** Copyright (C) 2015 Samuel Gaist <samuel.gaist@edeltech.ch>
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "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 The Qt Company Ltd 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."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "regularexpressiondialog.h"
+
+#include <QApplication>
+
+#include <QCheckBox>
+#include <QComboBox>
+#include <QLabel>
+#include <QLineEdit>
+#include <QSpinBox>
+#include <QPlainTextEdit>
+#include <QTreeWidget>
+
+#include <QAction>
+#include <QClipboard>
+
+#include <QHBoxLayout>
+#include <QGridLayout>
+#include <QFormLayout>
+
+#include <QRegularExpression>
+#include <QRegularExpressionMatch>
+#include <QRegularExpressionMatchIterator>
+
+Q_DECLARE_METATYPE(QRegularExpression::MatchType)
+
+RegularExpressionDialog::RegularExpressionDialog(QWidget *parent)
+ : QDialog(parent)
+{
+ setupUi();
+ setWindowTitle(tr("QRegularExpression Example"));
+
+ connect(patternLineEdit, &QLineEdit::textChanged, this, &RegularExpressionDialog::refresh);
+ connect(subjectTextEdit, &QPlainTextEdit::textChanged, this, &RegularExpressionDialog::refresh);
+
+ connect(caseInsensitiveOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(dotMatchesEverythingOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(multilineOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(extendedPatternSyntaxOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(invertedGreedinessOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(dontCaptureOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(useUnicodePropertiesOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(optimizeOnFirstUsageOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(dontAutomaticallyOptimizeOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+
+ connect(offsetSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
+ this, &RegularExpressionDialog::refresh);
+
+ connect(matchTypeComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &RegularExpressionDialog::refresh);
+
+ connect(anchoredMatchOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+ connect(dontCheckSubjectStringMatchOptionCheckBox, &QCheckBox::toggled, this, &RegularExpressionDialog::refresh);
+
+ patternLineEdit->setText(tr("(\\+?\\d+)-(?<prefix>\\d+)-(?<number>\\w+)"));
+ subjectTextEdit->setPlainText(tr("My office number is +43-152-0123456, my mobile is 001-41-255512 instead."));
+
+ refresh();
+}
+
+void RegularExpressionDialog::refresh()
+{
+ setUpdatesEnabled(false);
+
+ const QString pattern = patternLineEdit->text();
+ const QString text = subjectTextEdit->toPlainText();
+
+ offsetSpinBox->setMaximum(qMax(0, text.length() - 1));
+
+ QString escaped = pattern;
+ escaped.replace(QLatin1String("\\"), QLatin1String("\\\\"));
+ escaped.replace(QLatin1String("\""), QLatin1String("\\\""));
+ escaped.prepend(QLatin1String("\""));
+ escaped.append(QLatin1String("\""));
+ escapedPatternLineEdit->setText(escaped);
+
+ QRegularExpression rx(pattern);
+ QRegularExpression::MatchType matchType = matchTypeComboBox->currentData().value<QRegularExpression::MatchType>();
+ QRegularExpression::PatternOptions patternOptions = QRegularExpression::NoPatternOption;
+ QRegularExpression::MatchOptions matchOptions = QRegularExpression::NoMatchOption;
+
+ if (anchoredMatchOptionCheckBox->isChecked())
+ matchOptions |= QRegularExpression::AnchoredMatchOption;
+ if (dontCheckSubjectStringMatchOptionCheckBox->isChecked())
+ matchOptions |= QRegularExpression::DontCheckSubjectStringMatchOption;
+
+ if (caseInsensitiveOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::CaseInsensitiveOption;
+ if (dotMatchesEverythingOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::DotMatchesEverythingOption;
+ if (multilineOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::MultilineOption;
+ if (extendedPatternSyntaxOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::ExtendedPatternSyntaxOption;
+ if (invertedGreedinessOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::InvertedGreedinessOption;
+ if (dontCaptureOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::DontCaptureOption;
+ if (useUnicodePropertiesOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::UseUnicodePropertiesOption;
+ if (optimizeOnFirstUsageOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::OptimizeOnFirstUsageOption;
+ if (dontAutomaticallyOptimizeOptionCheckBox->isChecked())
+ patternOptions |= QRegularExpression::DontAutomaticallyOptimizeOption;
+
+ rx.setPatternOptions(patternOptions);
+
+ QPalette palette = patternLineEdit->palette();
+ if (rx.isValid())
+ palette.setColor(QPalette::Text, subjectTextEdit->palette().color(QPalette::Text));
+ else
+ palette.setColor(QPalette::Text, Qt::red);
+ patternLineEdit->setPalette(palette);
+
+ matchDetailsTreeWidget->clear();
+ matchDetailsTreeWidget->setEnabled(rx.isValid());
+
+ if (rx.isValid()) {
+ const int capturingGroupsCount = rx.captureCount() + 1;
+
+ QRegularExpressionMatchIterator iterator = rx.globalMatch(text, offsetSpinBox->value(), matchType, matchOptions);
+ int i = 0;
+
+ while (iterator.hasNext()) {
+ QRegularExpressionMatch match = iterator.next();
+
+ QTreeWidgetItem *matchDetailTopItem = new QTreeWidgetItem(matchDetailsTreeWidget);
+ matchDetailTopItem->setText(0, QString::number(i));
+
+ for (int captureGroupIndex = 0; captureGroupIndex < capturingGroupsCount; ++captureGroupIndex) {
+ QTreeWidgetItem *matchDetailItem = new QTreeWidgetItem(matchDetailTopItem);
+ matchDetailItem->setText(1, QString::number(captureGroupIndex));
+ matchDetailItem->setText(2, match.captured(captureGroupIndex));
+ }
+
+ ++i;
+ }
+ }
+
+ matchDetailsTreeWidget->expandAll();
+
+ namedGroupsTreeWidget->clear();
+ namedGroupsTreeWidget->setEnabled(rx.isValid());
+
+ if (rx.isValid()) {
+ regexpStatusLabel->setText(tr("Valid"));
+
+ const QStringList namedCaptureGroups = rx.namedCaptureGroups();
+ for (int i = 0; i < namedCaptureGroups.size(); ++i) {
+ const QString currentNamedCaptureGroup = namedCaptureGroups.at(i);
+
+ QTreeWidgetItem *namedGroupItem = new QTreeWidgetItem(namedGroupsTreeWidget);
+ namedGroupItem->setText(0, QString::number(i));
+ namedGroupItem->setText(1, currentNamedCaptureGroup.isNull() ? tr("<no name>") : currentNamedCaptureGroup);
+ }
+ } else {
+ regexpStatusLabel->setText(tr("Invalid: syntax error at position %1 (%2)")
+ .arg(rx.patternErrorOffset())
+ .arg(rx.errorString()));
+ }
+
+ setUpdatesEnabled(true);
+}
+
+void RegularExpressionDialog::copyEscapedPatternToClipboard()
+{
+#ifndef QT_NO_CLIPBOARD
+ QClipboard *clipboard = QGuiApplication::clipboard();
+ if (clipboard)
+ clipboard->setText(escapedPatternLineEdit->text());
+#endif
+}
+
+void RegularExpressionDialog::setupUi()
+{
+ QWidget *leftHalfContainer = setupLeftUi();
+
+ QFrame *verticalSeparator = new QFrame;
+ verticalSeparator->setFrameStyle(QFrame::VLine | QFrame::Sunken);
+
+ QWidget *rightHalfContainer = setupRightUi();
+
+ QHBoxLayout *mainLayout = new QHBoxLayout;
+ mainLayout->addWidget(leftHalfContainer);
+ mainLayout->addWidget(verticalSeparator);
+ mainLayout->addWidget(rightHalfContainer);
+
+ setLayout(mainLayout);
+}
+
+QWidget *RegularExpressionDialog::setupLeftUi()
+{
+ QWidget *container = new QWidget;
+
+ QFormLayout *layout = new QFormLayout(container);
+ layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
+ layout->setMargin(0);
+
+ QLabel *regexpAndSubjectLabel = new QLabel(tr("<h3>Regular expression and text input</h3>"));
+ layout->addRow(regexpAndSubjectLabel);
+
+ patternLineEdit = new QLineEdit;
+ patternLineEdit->setClearButtonEnabled(true);
+ layout->addRow(tr("&Pattern:"), patternLineEdit);
+
+ escapedPatternLineEdit = new QLineEdit;
+ escapedPatternLineEdit->setReadOnly(true);
+ QPalette palette = escapedPatternLineEdit->palette();
+ palette.setBrush(QPalette::Base, palette.brush(QPalette::Disabled, QPalette::Base));
+ escapedPatternLineEdit->setPalette(palette);
+
+#ifndef QT_NO_CLIPBOARD
+ QAction *copyEscapedPatternAction = new QAction(this);
+ copyEscapedPatternAction->setText(tr("Copy to clipboard"));
+ copyEscapedPatternAction->setIcon(QIcon(QStringLiteral(":/images/copy.png")));
+ connect(copyEscapedPatternAction, &QAction::triggered, this, &RegularExpressionDialog::copyEscapedPatternToClipboard);
+ escapedPatternLineEdit->addAction(copyEscapedPatternAction, QLineEdit::TrailingPosition);
+#endif
+
+ layout->addRow(tr("&Escaped pattern:"), escapedPatternLineEdit);
+
+ subjectTextEdit = new QPlainTextEdit;
+ layout->addRow(tr("&Subject text:"), subjectTextEdit);
+
+ caseInsensitiveOptionCheckBox = new QCheckBox(tr("Case insensitive (/i)"));
+ dotMatchesEverythingOptionCheckBox = new QCheckBox(tr("Dot matches everything (/s)"));
+ multilineOptionCheckBox = new QCheckBox(tr("Multiline (/m)"));
+ extendedPatternSyntaxOptionCheckBox = new QCheckBox(tr("Extended pattern (/x)"));
+ invertedGreedinessOptionCheckBox = new QCheckBox(tr("Inverted greediness"));
+ dontCaptureOptionCheckBox = new QCheckBox(tr("Don't capture"));
+ useUnicodePropertiesOptionCheckBox = new QCheckBox(tr("Use unicode properties (/u)"));
+ optimizeOnFirstUsageOptionCheckBox = new QCheckBox(tr("Optimize on first usage"));
+ dontAutomaticallyOptimizeOptionCheckBox = new QCheckBox(tr("Don't automatically optimize"));
+
+ QGridLayout *patternOptionsCheckBoxLayout = new QGridLayout;
+ int gridRow = 0;
+ patternOptionsCheckBoxLayout->addWidget(caseInsensitiveOptionCheckBox, gridRow, 1);
+ patternOptionsCheckBoxLayout->addWidget(dotMatchesEverythingOptionCheckBox, gridRow, 2);
+ ++gridRow;
+ patternOptionsCheckBoxLayout->addWidget(multilineOptionCheckBox, gridRow, 1);
+ patternOptionsCheckBoxLayout->addWidget(extendedPatternSyntaxOptionCheckBox, gridRow, 2);
+ ++gridRow;
+ patternOptionsCheckBoxLayout->addWidget(invertedGreedinessOptionCheckBox, gridRow, 1);
+ patternOptionsCheckBoxLayout->addWidget(dontCaptureOptionCheckBox, gridRow, 2);
+ ++gridRow;
+ patternOptionsCheckBoxLayout->addWidget(useUnicodePropertiesOptionCheckBox, gridRow, 1);
+ patternOptionsCheckBoxLayout->addWidget(optimizeOnFirstUsageOptionCheckBox, gridRow, 2);
+ ++gridRow;
+ patternOptionsCheckBoxLayout->addWidget(dontAutomaticallyOptimizeOptionCheckBox, gridRow, 1);
+
+ layout->addRow(tr("Pattern options:"), patternOptionsCheckBoxLayout);
+
+ offsetSpinBox = new QSpinBox;
+ layout->addRow(tr("Match &offset:"), offsetSpinBox);
+
+ matchTypeComboBox = new QComboBox;
+ matchTypeComboBox->addItem(tr("Normal"), QVariant::fromValue(QRegularExpression::NormalMatch));
+ matchTypeComboBox->addItem(tr("Partial prefer complete"), QVariant::fromValue(QRegularExpression::PartialPreferCompleteMatch));
+ matchTypeComboBox->addItem(tr("Partial prefer first"), QVariant::fromValue(QRegularExpression::PartialPreferFirstMatch));
+ matchTypeComboBox->addItem(tr("No match"), QVariant::fromValue(QRegularExpression::NoMatch));
+ layout->addRow(tr("Match &type:"), matchTypeComboBox);
+
+ dontCheckSubjectStringMatchOptionCheckBox = new QCheckBox(tr("Don't check subject string"));
+ anchoredMatchOptionCheckBox = new QCheckBox(tr("Anchored match"));
+
+ QGridLayout *matchOptionsCheckBoxLayout = new QGridLayout;
+ matchOptionsCheckBoxLayout->addWidget(dontCheckSubjectStringMatchOptionCheckBox, 0, 0);
+ matchOptionsCheckBoxLayout->addWidget(anchoredMatchOptionCheckBox, 0, 1);
+ layout->addRow(tr("Match options:"), matchOptionsCheckBoxLayout);
+
+ return container;
+}
+
+QWidget *RegularExpressionDialog::setupRightUi()
+{
+ QWidget *container = new QWidget;
+
+ QFormLayout *layout = new QFormLayout(container);
+ layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
+ layout->setMargin(0);
+
+ QLabel *matchInfoLabel = new QLabel(tr("<h3>Match information</h3>"));
+ layout->addRow(matchInfoLabel);
+
+ matchDetailsTreeWidget = new QTreeWidget;
+ matchDetailsTreeWidget->setHeaderLabels(QStringList() << tr("Match index") << tr("Group index") << tr("Captured string"));
+ matchDetailsTreeWidget->setSizeAdjustPolicy(QTreeWidget::AdjustToContents);
+ layout->addRow(tr("Match details:"), matchDetailsTreeWidget);
+
+ QFrame *horizontalSeparator = new QFrame;
+ horizontalSeparator->setFrameStyle(QFrame::HLine | QFrame::Sunken);
+ layout->addRow(horizontalSeparator);
+
+ QLabel *regexpInfoLabel = new QLabel(tr("<h3>Regular expression information</h3>"));
+ layout->addRow(regexpInfoLabel);
+
+ regexpStatusLabel = new QLabel(tr("Valid"));
+ regexpStatusLabel->setWordWrap(true);
+ layout->addRow(tr("Pattern status:"), regexpStatusLabel);
+
+ namedGroupsTreeWidget = new QTreeWidget;
+ namedGroupsTreeWidget->setHeaderLabels(QStringList() << tr("Index") << tr("Named group"));
+ namedGroupsTreeWidget->setSizeAdjustPolicy(QTreeWidget::AdjustToContents);
+ namedGroupsTreeWidget->setRootIsDecorated(false);
+ layout->addRow(tr("Named groups:"), namedGroupsTreeWidget);
+
+ return container;
+}
diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.h b/examples/widgets/tools/regularexpression/regularexpressiondialog.h
new file mode 100644
index 0000000000..1b3b147c14
--- /dev/null
+++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
+** Copyright (C) 2015 Samuel Gaist <samuel.gaist@edeltech.ch>
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "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 The Qt Company Ltd 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."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef REGULAREXPRESSIONDIALOG_H
+#define REGULAREXPRESSIONDIALOG_H
+
+#include <QDialog>
+
+QT_BEGIN_NAMESPACE
+class QCheckBox;
+class QComboBox;
+class QLabel;
+class QLineEdit;
+class QSpinBox;
+class QPlainTextEdit;
+class QTreeWidget;
+QT_END_NAMESPACE
+
+class RegularExpressionDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ RegularExpressionDialog(QWidget *parent = 0);
+
+private:
+ void refresh();
+ void copyEscapedPatternToClipboard();
+ void setupUi();
+ QWidget *setupLeftUi();
+ QWidget *setupRightUi();
+
+ QLineEdit *patternLineEdit;
+ QLineEdit *escapedPatternLineEdit;
+
+ QPlainTextEdit *subjectTextEdit;
+
+ QCheckBox *caseInsensitiveOptionCheckBox;
+ QCheckBox *dotMatchesEverythingOptionCheckBox;
+ QCheckBox *multilineOptionCheckBox;
+ QCheckBox *extendedPatternSyntaxOptionCheckBox;
+ QCheckBox *invertedGreedinessOptionCheckBox;
+ QCheckBox *dontCaptureOptionCheckBox;
+ QCheckBox *useUnicodePropertiesOptionCheckBox;
+ QCheckBox *optimizeOnFirstUsageOptionCheckBox;
+ QCheckBox *dontAutomaticallyOptimizeOptionCheckBox;
+
+ QSpinBox *offsetSpinBox;
+
+ QComboBox *matchTypeComboBox;
+
+ QCheckBox *anchoredMatchOptionCheckBox;
+ QCheckBox *dontCheckSubjectStringMatchOptionCheckBox;
+
+ QTreeWidget *matchDetailsTreeWidget;
+
+ QLabel *regexpStatusLabel;
+ QTreeWidget *namedGroupsTreeWidget;
+};
+
+#endif
diff --git a/examples/widgets/tools/tools.pro b/examples/widgets/tools/tools.pro
index 7178411110..282f8dedea 100644
--- a/examples/widgets/tools/tools.pro
+++ b/examples/widgets/tools/tools.pro
@@ -8,6 +8,7 @@ SUBDIRS = \
plugandpaintplugins \
plugandpaint \
regexp \
+ regularexpression \
settingseditor \
styleplugin \
treemodelcompleter \
diff --git a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp
index 45ded876a7..6764423d71 100644
--- a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp
+++ b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp
@@ -370,7 +370,6 @@ void AddressBook::loadFromFile()
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_3);
- contacts.empty(); // empty existing contacts
in >> contacts;
QMap<QString, QString>::iterator i = contacts.begin();
diff --git a/examples/widgets/widgets/icons/icons.pro b/examples/widgets/widgets/icons/icons.pro
index 21165163aa..4312a40e95 100644
--- a/examples/widgets/widgets/icons/icons.pro
+++ b/examples/widgets/widgets/icons/icons.pro
@@ -24,5 +24,5 @@ wince {
} else {
imageFiles.path = images
}
- DEPLOYMENT += imageFiles
+ INSTALLS += imageFiles
}
diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp
index 93b88e9c18..a4b37060f6 100644
--- a/examples/widgets/widgets/imageviewer/imageviewer.cpp
+++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp
@@ -47,19 +47,20 @@
//! [0]
ImageViewer::ImageViewer()
+ : imageLabel(new QLabel)
+ , scrollArea(new QScrollArea)
+ , scaleFactor(1)
{
- imageLabel = new QLabel;
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);
- scrollArea = new QScrollArea;
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageLabel);
+ scrollArea->setVisible(false);
setCentralWidget(scrollArea);
createActions();
- createMenus();
resize(QGuiApplication::primaryScreen()->availableSize() * 3 / 5);
}
@@ -71,53 +72,99 @@ bool ImageViewer::loadFile(const QString &fileName)
{
QImageReader reader(fileName);
reader.setAutoTransform(true);
- const QImage image = reader.read();
- if (image.isNull()) {
+ const QImage newImage = reader.read();
+ if (newImage.isNull()) {
QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
- tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName)));
- setWindowFilePath(QString());
- imageLabel->setPixmap(QPixmap());
- imageLabel->adjustSize();
+ tr("Cannot load %1: %2")
+ .arg(QDir::toNativeSeparators(fileName)), reader.errorString());
return false;
}
-//! [2] //! [3]
+//! [2]
+
+ setImage(newImage);
+
+ setWindowFilePath(fileName);
+
+ const QString message = tr("Opened \"%1\", %2x%3, Depth: %4")
+ .arg(QDir::toNativeSeparators(fileName)).arg(image.width()).arg(image.height()).arg(image.depth());
+ statusBar()->showMessage(message);
+ return true;
+}
+
+void ImageViewer::setImage(const QImage &newImage)
+{
+ image = newImage;
imageLabel->setPixmap(QPixmap::fromImage(image));
-//! [3] //! [4]
+//! [4]
scaleFactor = 1.0;
+ scrollArea->setVisible(true);
printAct->setEnabled(true);
fitToWindowAct->setEnabled(true);
updateActions();
if (!fitToWindowAct->isChecked())
imageLabel->adjustSize();
-
- setWindowFilePath(fileName);
- return true;
}
//! [4]
-//! [2]
+bool ImageViewer::saveFile(const QString &fileName)
+{
+ QImageWriter writer(fileName);
+
+ if (!writer.write(image)) {
+ QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
+ tr("Cannot write %1: %2")
+ .arg(QDir::toNativeSeparators(fileName)), writer.errorString());
+ return false;
+ }
+ const QString message = tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(fileName));
+ statusBar()->showMessage(message);
+ return true;
+}
//! [1]
-void ImageViewer::open()
+
+static void initializeImageFileDialog(QFileDialog &dialog, QFileDialog::AcceptMode acceptMode)
{
+ static bool firstDialog = true;
+
+ if (firstDialog) {
+ firstDialog = false;
+ const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
+ dialog.setDirectory(picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
+ }
+
QStringList mimeTypeFilters;
- foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
+ const QByteArrayList supportedMimeTypes = acceptMode == QFileDialog::AcceptOpen
+ ? QImageReader::supportedMimeTypes() : QImageWriter::supportedMimeTypes();
+ foreach (const QByteArray &mimeTypeName, supportedMimeTypes)
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
- const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
- QFileDialog dialog(this, tr("Open File"),
- picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
- dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setMimeTypeFilters(mimeTypeFilters);
dialog.selectMimeTypeFilter("image/jpeg");
+ if (acceptMode == QFileDialog::AcceptSave)
+ dialog.setDefaultSuffix("jpg");
+}
+
+void ImageViewer::open()
+{
+ QFileDialog dialog(this, tr("Open File"));
+ initializeImageFileDialog(dialog, QFileDialog::AcceptOpen);
while (dialog.exec() == QDialog::Accepted && !loadFile(dialog.selectedFiles().first())) {}
}
//! [1]
+void ImageViewer::saveAs()
+{
+ QFileDialog dialog(this, tr("Save File As"));
+ initializeImageFileDialog(dialog, QFileDialog::AcceptSave);
+
+ while (dialog.exec() == QDialog::Accepted && !saveFile(dialog.selectedFiles().first())) {}
+}
+
//! [5]
void ImageViewer::print()
//! [5] //! [6]
@@ -140,6 +187,43 @@ void ImageViewer::print()
}
//! [8]
+void ImageViewer::copy()
+{
+#ifndef QT_NO_CLIPBOARD
+ QGuiApplication::clipboard()->setImage(image);
+#endif // !QT_NO_CLIPBOARD
+}
+
+#ifndef QT_NO_CLIPBOARD
+static QImage clipboardImage()
+{
+ if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData()) {
+ if (mimeData->hasImage()) {
+ const QImage image = qvariant_cast<QImage>(mimeData->imageData());
+ if (!image.isNull())
+ return image;
+ }
+ }
+ return QImage();
+}
+#endif // !QT_NO_CLIPBOARD
+
+void ImageViewer::paste()
+{
+#ifndef QT_NO_CLIPBOARD
+ const QImage newImage = clipboardImage();
+ if (newImage.isNull()) {
+ statusBar()->showMessage(tr("No image in clipboard"));
+ } else {
+ setImage(newImage);
+ setWindowFilePath(QString());
+ const QString message = tr("Obtained image from clipboard, %1x%2, Depth: %3")
+ .arg(newImage.width()).arg(newImage.height()).arg(newImage.depth());
+ statusBar()->showMessage(message);
+ }
+#endif // !QT_NO_CLIPBOARD
+}
+
//! [9]
void ImageViewer::zoomIn()
//! [9] //! [10]
@@ -167,9 +251,8 @@ void ImageViewer::fitToWindow()
{
bool fitToWindow = fitToWindowAct->isChecked();
scrollArea->setWidgetResizable(fitToWindow);
- if (!fitToWindow) {
+ if (!fitToWindow)
normalSize();
- }
updateActions();
}
//! [14]
@@ -199,79 +282,66 @@ void ImageViewer::about()
void ImageViewer::createActions()
//! [17] //! [18]
{
- openAct = new QAction(tr("&Open..."), this);
- openAct->setShortcut(tr("Ctrl+O"));
- connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
+ QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
+
+ QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &ImageViewer::open);
+ openAct->setShortcut(QKeySequence::Open);
+
+ saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &ImageViewer::saveAs);
+ saveAsAct->setEnabled(false);
- printAct = new QAction(tr("&Print..."), this);
- printAct->setShortcut(tr("Ctrl+P"));
+ printAct = fileMenu->addAction(tr("&Print..."), this, &ImageViewer::print);
+ printAct->setShortcut(QKeySequence::Print);
printAct->setEnabled(false);
- connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
- exitAct = new QAction(tr("E&xit"), this);
+ fileMenu->addSeparator();
+
+ QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close);
exitAct->setShortcut(tr("Ctrl+Q"));
- connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
- zoomInAct = new QAction(tr("Zoom &In (25%)"), this);
- zoomInAct->setShortcut(tr("Ctrl++"));
+ QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
+
+ copyAct = editMenu->addAction(tr("&Copy"), this, &ImageViewer::copy);
+ copyAct->setShortcut(QKeySequence::Copy);
+ copyAct->setEnabled(false);
+
+ QAction *pasteAct = editMenu->addAction(tr("&Paste"), this, &ImageViewer::paste);
+ pasteAct->setShortcut(QKeySequence::Paste);
+
+ QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
+
+ zoomInAct = viewMenu->addAction(tr("Zoom &In (25%)"), this, &ImageViewer::zoomIn);
+ zoomInAct->setShortcut(QKeySequence::ZoomIn);
zoomInAct->setEnabled(false);
- connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));
- zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this);
- zoomOutAct->setShortcut(tr("Ctrl+-"));
+ zoomOutAct = viewMenu->addAction(tr("Zoom &Out (25%)"), this, &ImageViewer::zoomOut);
+ zoomOutAct->setShortcut(QKeySequence::ZoomOut);
zoomOutAct->setEnabled(false);
- connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
- normalSizeAct = new QAction(tr("&Normal Size"), this);
+ normalSizeAct = viewMenu->addAction(tr("&Normal Size"), this, &ImageViewer::normalSize);
normalSizeAct->setShortcut(tr("Ctrl+S"));
normalSizeAct->setEnabled(false);
- connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));
- fitToWindowAct = new QAction(tr("&Fit to Window"), this);
+ viewMenu->addSeparator();
+
+ fitToWindowAct = viewMenu->addAction(tr("&Fit to Window"), this, &ImageViewer::fitToWindow);
fitToWindowAct->setEnabled(false);
fitToWindowAct->setCheckable(true);
fitToWindowAct->setShortcut(tr("Ctrl+F"));
- connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));
- aboutAct = new QAction(tr("&About"), this);
- connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
+ QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
- aboutQtAct = new QAction(tr("About &Qt"), this);
- connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
+ helpMenu->addAction(tr("&About"), this, &ImageViewer::about);
+ helpMenu->addAction(tr("About &Qt"), &QApplication::aboutQt);
}
//! [18]
-//! [19]
-void ImageViewer::createMenus()
-//! [19] //! [20]
-{
- fileMenu = new QMenu(tr("&File"), this);
- fileMenu->addAction(openAct);
- fileMenu->addAction(printAct);
- fileMenu->addSeparator();
- fileMenu->addAction(exitAct);
-
- viewMenu = new QMenu(tr("&View"), this);
- viewMenu->addAction(zoomInAct);
- viewMenu->addAction(zoomOutAct);
- viewMenu->addAction(normalSizeAct);
- viewMenu->addSeparator();
- viewMenu->addAction(fitToWindowAct);
-
- helpMenu = new QMenu(tr("&Help"), this);
- helpMenu->addAction(aboutAct);
- helpMenu->addAction(aboutQtAct);
-
- menuBar()->addMenu(fileMenu);
- menuBar()->addMenu(viewMenu);
- menuBar()->addMenu(helpMenu);
-}
-//! [20]
-
//! [21]
void ImageViewer::updateActions()
//! [21] //! [22]
{
+ saveAsAct->setEnabled(!image.isNull());
+ copyAct->setEnabled(!image.isNull());
zoomInAct->setEnabled(!fitToWindowAct->isChecked());
zoomOutAct->setEnabled(!fitToWindowAct->isChecked());
normalSizeAct->setEnabled(!fitToWindowAct->isChecked());
diff --git a/examples/widgets/widgets/imageviewer/imageviewer.h b/examples/widgets/widgets/imageviewer/imageviewer.h
index 7b35e3ee9e..7084bf98d1 100644
--- a/examples/widgets/widgets/imageviewer/imageviewer.h
+++ b/examples/widgets/widgets/imageviewer/imageviewer.h
@@ -42,6 +42,7 @@
#define IMAGEVIEWER_H
#include <QMainWindow>
+#include <QImage>
#ifndef QT_NO_PRINTER
#include <QPrinter>
#endif
@@ -65,7 +66,10 @@ public:
private slots:
void open();
+ void saveAs();
void print();
+ void copy();
+ void paste();
void zoomIn();
void zoomOut();
void normalSize();
@@ -76,9 +80,12 @@ private:
void createActions();
void createMenus();
void updateActions();
+ bool saveFile(const QString &fileName);
+ void setImage(const QImage &newImage);
void scaleImage(double factor);
void adjustScrollBar(QScrollBar *scrollBar, double factor);
+ QImage image;
QLabel *imageLabel;
QScrollArea *scrollArea;
double scaleFactor;
@@ -87,19 +94,13 @@ private:
QPrinter printer;
#endif
- QAction *openAct;
+ QAction *saveAsAct;
QAction *printAct;
- QAction *exitAct;
+ QAction *copyAct;
QAction *zoomInAct;
QAction *zoomOutAct;
QAction *normalSizeAct;
QAction *fitToWindowAct;
- QAction *aboutAct;
- QAction *aboutQtAct;
-
- QMenu *fileMenu;
- QMenu *viewMenu;
- QMenu *helpMenu;
};
//! [0]
diff --git a/examples/widgets/widgets/movie/movie.pro b/examples/widgets/widgets/movie/movie.pro
index 86d85552c2..94d86454d8 100644
--- a/examples/widgets/widgets/movie/movie.pro
+++ b/examples/widgets/widgets/movie/movie.pro
@@ -14,5 +14,5 @@ INSTALLS += target
wince {
addFiles.files += *.gif
addFiles.path = .
- DEPLOYMENT += addFiles
+ INSTALLS += addFiles
}
diff --git a/examples/widgets/widgets/tablet/images.qrc b/examples/widgets/widgets/tablet/images.qrc
new file mode 100644
index 0000000000..eb3eabbace
--- /dev/null
+++ b/examples/widgets/widgets/tablet/images.qrc
@@ -0,0 +1,8 @@
+<RCC>
+ <qresource>
+ <file>images/cursor-airbrush.png</file>
+ <file>images/cursor-eraser.png</file>
+ <file>images/cursor-felt-marker.png</file>
+ <file>images/cursor-pencil.png</file>
+ </qresource>
+</RCC>
diff --git a/examples/widgets/widgets/tablet/images/cursor-airbrush.png b/examples/widgets/widgets/tablet/images/cursor-airbrush.png
new file mode 100644
index 0000000000..bea756ed6f
--- /dev/null
+++ b/examples/widgets/widgets/tablet/images/cursor-airbrush.png
Binary files differ
diff --git a/examples/widgets/widgets/tablet/images/cursor-eraser.png b/examples/widgets/widgets/tablet/images/cursor-eraser.png
new file mode 100644
index 0000000000..e5488a89f2
--- /dev/null
+++ b/examples/widgets/widgets/tablet/images/cursor-eraser.png
Binary files differ
diff --git a/examples/widgets/widgets/tablet/images/cursor-felt-marker.png b/examples/widgets/widgets/tablet/images/cursor-felt-marker.png
new file mode 100644
index 0000000000..132f09aa39
--- /dev/null
+++ b/examples/widgets/widgets/tablet/images/cursor-felt-marker.png
Binary files differ
diff --git a/examples/widgets/widgets/tablet/images/cursor-pencil.png b/examples/widgets/widgets/tablet/images/cursor-pencil.png
new file mode 100644
index 0000000000..cc2f447d02
--- /dev/null
+++ b/examples/widgets/widgets/tablet/images/cursor-pencil.png
Binary files differ
diff --git a/examples/widgets/widgets/tablet/mainwindow.cpp b/examples/widgets/widgets/tablet/mainwindow.cpp
index aed84c50df..5e84f5b6a2 100644
--- a/examples/widgets/widgets/tablet/mainwindow.cpp
+++ b/examples/widgets/widgets/tablet/mainwindow.cpp
@@ -52,7 +52,7 @@ MainWindow::MainWindow(TabletCanvas *canvas)
myCanvas->setColor(Qt::red);
myCanvas->setLineWidthType(TabletCanvas::LineWidthPressure);
- myCanvas->setAlphaChannelType(TabletCanvas::NoAlpha);
+ myCanvas->setAlphaChannelType(TabletCanvas::AlphaTangentialPressure);
myCanvas->setColorSaturationType(TabletCanvas::NoSaturation);
setWindowTitle(tr("Tablet Example"));
@@ -75,6 +75,8 @@ void MainWindow::alphaActionTriggered(QAction *action)
{
if (action == alphaChannelPressureAction) {
myCanvas->setAlphaChannelType(TabletCanvas::AlphaPressure);
+ } else if (action == alphaChannelTangentialPressureAction) {
+ myCanvas->setAlphaChannelType(TabletCanvas::AlphaTangentialPressure);
} else if (action == alphaChannelTiltAction) {
myCanvas->setAlphaChannelType(TabletCanvas::AlphaTilt);
} else {
@@ -157,15 +159,19 @@ void MainWindow::createActions()
alphaChannelPressureAction = new QAction(tr("&Pressure"), this);
alphaChannelPressureAction->setCheckable(true);
+ alphaChannelTangentialPressureAction = new QAction(tr("T&angential Pressure"), this);
+ alphaChannelTangentialPressureAction->setCheckable(true);
+ alphaChannelTangentialPressureAction->setChecked(true);
+
alphaChannelTiltAction = new QAction(tr("&Tilt"), this);
alphaChannelTiltAction->setCheckable(true);
noAlphaChannelAction = new QAction(tr("No Alpha Channel"), this);
noAlphaChannelAction->setCheckable(true);
- noAlphaChannelAction->setChecked(true);
alphaChannelGroup = new QActionGroup(this);
alphaChannelGroup->addAction(alphaChannelPressureAction);
+ alphaChannelGroup->addAction(alphaChannelTangentialPressureAction);
alphaChannelGroup->addAction(alphaChannelTiltAction);
alphaChannelGroup->addAction(noAlphaChannelAction);
connect(alphaChannelGroup, SIGNAL(triggered(QAction*)),
@@ -259,6 +265,7 @@ void MainWindow::createMenus()
alphaChannelMenu = tabletMenu->addMenu(tr("&Alpha Channel"));
alphaChannelMenu->addAction(alphaChannelPressureAction);
+ alphaChannelMenu->addAction(alphaChannelTangentialPressureAction);
alphaChannelMenu->addAction(alphaChannelTiltAction);
alphaChannelMenu->addAction(noAlphaChannelAction);
diff --git a/examples/widgets/widgets/tablet/mainwindow.h b/examples/widgets/widgets/tablet/mainwindow.h
index 5e77ea1acf..c6ac2e6026 100644
--- a/examples/widgets/widgets/tablet/mainwindow.h
+++ b/examples/widgets/widgets/tablet/mainwindow.h
@@ -79,6 +79,7 @@ private:
QActionGroup *alphaChannelGroup;
QAction *alphaChannelPressureAction;
+ QAction *alphaChannelTangentialPressureAction;
QAction *alphaChannelTiltAction;
QAction *noAlphaChannelAction;
diff --git a/examples/widgets/widgets/tablet/tablet.pro b/examples/widgets/widgets/tablet/tablet.pro
index de81e7b198..9b8927f483 100644
--- a/examples/widgets/widgets/tablet/tablet.pro
+++ b/examples/widgets/widgets/tablet/tablet.pro
@@ -1,12 +1,13 @@
QT += widgets
HEADERS = mainwindow.h \
- tabletcanvas.h \
- tabletapplication.h
+ tabletcanvas.h \
+ tabletapplication.h
SOURCES = mainwindow.cpp \
- main.cpp \
- tabletcanvas.cpp \
- tabletapplication.cpp
+ main.cpp \
+ tabletcanvas.cpp \
+ tabletapplication.cpp
+RESOURCES += images.qrc
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/widgets/tablet
diff --git a/examples/widgets/widgets/tablet/tabletapplication.cpp b/examples/widgets/widgets/tablet/tabletapplication.cpp
index c3210f822c..3e1356ee9c 100644
--- a/examples/widgets/widgets/tablet/tabletapplication.cpp
+++ b/examples/widgets/widgets/tablet/tabletapplication.cpp
@@ -47,8 +47,7 @@ bool TabletApplication::event(QEvent *event)
{
if (event->type() == QEvent::TabletEnterProximity ||
event->type() == QEvent::TabletLeaveProximity) {
- myCanvas->setTabletDevice(
- static_cast<QTabletEvent *>(event)->device());
+ myCanvas->setTabletDevice(static_cast<QTabletEvent *>(event));
return true;
}
return QApplication::event(event);
diff --git a/examples/widgets/widgets/tablet/tabletcanvas.cpp b/examples/widgets/widgets/tablet/tabletcanvas.cpp
index 20d6291292..8ff3d41e0e 100644
--- a/examples/widgets/widgets/tablet/tabletcanvas.cpp
+++ b/examples/widgets/widgets/tablet/tabletcanvas.cpp
@@ -47,14 +47,13 @@
TabletCanvas::TabletCanvas()
{
resize(500, 500);
- myBrush = QBrush();
- myPen = QPen();
+ myColor = Qt::red;
+ myBrush = QBrush(myColor);
+ myPen = QPen(myBrush, 1.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
initPixmap();
setAutoFillBackground(true);
deviceDown = false;
- myColor = Qt::red;
- myTabletDevice = QTabletEvent::Stylus;
- alphaChannelType = NoAlpha;
+ alphaChannelType = AlphaTangentialPressure;
colorSaturationType = NoSaturation;
lineWidthType = LineWidthPressure;
}
@@ -99,24 +98,25 @@ void TabletCanvas::tabletEvent(QTabletEvent *event)
case QEvent::TabletPress:
if (!deviceDown) {
deviceDown = true;
- polyLine[0] = polyLine[1] = polyLine[2] = event->pos();
+ lastPoint.pos = event->posF();
+ lastPoint.rotation = event->rotation();
}
break;
- case QEvent::TabletRelease:
- if (deviceDown)
- deviceDown = false;
- break;
case QEvent::TabletMove:
- polyLine[2] = polyLine[1];
- polyLine[1] = polyLine[0];
- polyLine[0] = event->pos();
-
+ if (event->device() == QTabletEvent::RotationStylus)
+ updateCursor(event);
if (deviceDown) {
updateBrush(event);
QPainter painter(&pixmap);
paintPixmap(painter, event);
+ lastPoint.pos = event->posF();
+ lastPoint.rotation = event->rotation();
}
break;
+ case QEvent::TabletRelease:
+ if (deviceDown && event->buttons() == Qt::NoButton)
+ deviceDown = false;
+ break;
default:
break;
}
@@ -135,23 +135,44 @@ void TabletCanvas::paintEvent(QPaintEvent *)
//! [5]
void TabletCanvas::paintPixmap(QPainter &painter, QTabletEvent *event)
{
- QPoint brushAdjust(10, 10);
+ painter.setRenderHint(QPainter::Antialiasing);
- switch (myTabletDevice) {
+ switch (event->device()) {
+//! [6]
case QTabletEvent::Airbrush:
- myBrush.setColor(myColor);
- myBrush.setStyle(brushPattern(event->pressure()));
- painter.setPen(Qt::NoPen);
- painter.setBrush(myBrush);
-
- for (int i = 0; i < 3; ++i) {
- painter.drawEllipse(QRect(polyLine[i] - brushAdjust,
- polyLine[i] + brushAdjust));
+ {
+ painter.setPen(Qt::NoPen);
+ QRadialGradient grad(lastPoint.pos, myPen.widthF() * 10.0);
+ QColor color = myBrush.color();
+ color.setAlphaF(color.alphaF() * 0.25);
+ grad.setColorAt(0, myBrush.color());
+ grad.setColorAt(0.5, Qt::transparent);
+ painter.setBrush(grad);
+ qreal radius = grad.radius();
+ painter.drawEllipse(event->posF(), radius, radius);
+ }
+ break;
+ case QTabletEvent::RotationStylus:
+ {
+ myBrush.setStyle(Qt::SolidPattern);
+ painter.setPen(Qt::NoPen);
+ painter.setBrush(myBrush);
+ QPolygonF poly;
+ qreal halfWidth = myPen.widthF();
+ QPointF brushAdjust(qSin(qDegreesToRadians(lastPoint.rotation)) * halfWidth,
+ qCos(qDegreesToRadians(lastPoint.rotation)) * halfWidth);
+ poly << lastPoint.pos + brushAdjust;
+ poly << lastPoint.pos - brushAdjust;
+ brushAdjust = QPointF(qSin(qDegreesToRadians(event->rotation())) * halfWidth,
+ qCos(qDegreesToRadians(event->rotation())) * halfWidth);
+ poly << event->posF() - brushAdjust;
+ poly << event->posF() + brushAdjust;
+ painter.drawConvexPolygon(poly);
}
break;
+//! [6]
case QTabletEvent::Puck:
case QTabletEvent::FourDMouse:
- case QTabletEvent::RotationStylus:
{
const QString error(tr("This input device is not supported by the example."));
#ifndef QT_NO_STATUSTIP
@@ -174,42 +195,15 @@ void TabletCanvas::paintPixmap(QPainter &painter, QTabletEvent *event)
}
// FALL-THROUGH
case QTabletEvent::Stylus:
- painter.setBrush(myBrush);
painter.setPen(myPen);
- painter.drawLine(polyLine[1], event->pos());
+ painter.drawLine(lastPoint.pos, event->posF());
break;
}
}
//! [5]
-//! [6]
-Qt::BrushStyle TabletCanvas::brushPattern(qreal value)
-{
- int pattern = int((value) * 100.0) % 7;
-
- switch (pattern) {
- case 0:
- return Qt::SolidPattern;
- case 1:
- return Qt::Dense1Pattern;
- case 2:
- return Qt::Dense2Pattern;
- case 3:
- return Qt::Dense3Pattern;
- case 4:
- return Qt::Dense4Pattern;
- case 5:
- return Qt::Dense5Pattern;
- case 6:
- return Qt::Dense6Pattern;
- default:
- return Qt::Dense7Pattern;
- }
-}
-//! [6]
-
//! [7]
-void TabletCanvas::updateBrush(QTabletEvent *event)
+void TabletCanvas::updateBrush(const QTabletEvent *event)
{
int hue, saturation, value, alpha;
myColor.getHsv(&hue, &saturation, &value, &alpha);
@@ -220,7 +214,13 @@ void TabletCanvas::updateBrush(QTabletEvent *event)
switch (alphaChannelType) {
case AlphaPressure:
- myColor.setAlpha(int(event->pressure() * 255.0));
+ myColor.setAlphaF(event->pressure());
+ break;
+ case AlphaTangentialPressure:
+ if (event->device() == QTabletEvent::Airbrush)
+ myColor.setAlphaF(qMax(0.01, (event->tangentialPressure() + 1.0) / 2.0));
+ else
+ myColor.setAlpha(255);
break;
case AlphaTilt:
myColor.setAlpha(maximum(abs(vValue - 127), abs(hValue - 127)));
@@ -268,8 +268,47 @@ void TabletCanvas::updateBrush(QTabletEvent *event)
}
//! [11]
+void TabletCanvas::updateCursor(const QTabletEvent *event)
+{
+ QCursor cursor;
+ if (event->type() != QEvent::TabletLeaveProximity) {
+ if (event->pointerType() == QTabletEvent::Eraser) {
+ cursor = QCursor(QPixmap(":/images/cursor-eraser.png"), 3, 28);
+ } else {
+ switch (event->device()) {
+ case QTabletEvent::Stylus:
+ cursor = QCursor(QPixmap(":/images/cursor-pencil.png"), 0, 0);
+ break;
+ case QTabletEvent::Airbrush:
+ cursor = QCursor(QPixmap(":/images/cursor-airbrush.png"), 3, 4);
+ break;
+ case QTabletEvent::RotationStylus: {
+ QImage origImg(QLatin1String(":/images/cursor-felt-marker.png"));
+ QImage img(32, 32, QImage::Format_ARGB32);
+ QColor solid = myColor;
+ solid.setAlpha(255);
+ img.fill(solid);
+ QPainter painter(&img);
+ QTransform transform = painter.transform();
+ transform.translate(16, 16);
+ transform.rotate(-event->rotation());
+ painter.setTransform(transform);
+ painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
+ painter.drawImage(-24, -24, origImg);
+ painter.setCompositionMode(QPainter::CompositionMode_HardLight);
+ painter.drawImage(-24, -24, origImg);
+ painter.end();
+ cursor = QCursor(QPixmap::fromImage(img), 16, 16);
+ } break;
+ default:
+ break;
+ }
+ }
+ }
+ setCursor(cursor);
+}
+
void TabletCanvas::resizeEvent(QResizeEvent *)
{
initPixmap();
- polyLine[0] = polyLine[1] = polyLine[2] = QPoint();
}
diff --git a/examples/widgets/widgets/tablet/tabletcanvas.h b/examples/widgets/widgets/tablet/tabletcanvas.h
index 873f3a7ab0..a7335dbaf0 100644
--- a/examples/widgets/widgets/tablet/tabletcanvas.h
+++ b/examples/widgets/widgets/tablet/tabletcanvas.h
@@ -61,7 +61,7 @@ class TabletCanvas : public QWidget
Q_OBJECT
public:
- enum AlphaChannelType { AlphaPressure, AlphaTilt, NoAlpha };
+ enum AlphaChannelType { AlphaPressure, AlphaTangentialPressure, AlphaTilt, NoAlpha };
enum ColorSaturationType { SaturationVTilt, SaturationHTilt,
SaturationPressure, NoSaturation };
enum LineWidthType { LineWidthPressure, LineWidthTilt, NoLineWidth };
@@ -80,8 +80,8 @@ public:
{ myColor = color; }
QColor color() const
{ return myColor; }
- void setTabletDevice(QTabletEvent::TabletDevice device)
- { myTabletDevice = device; }
+ void setTabletDevice(QTabletEvent *event)
+ { myTabletDevice = event->device(); updateCursor(event); }
int maximum(int a, int b)
{ return a > b ? a : b; }
@@ -94,7 +94,8 @@ private:
void initPixmap();
void paintPixmap(QPainter &painter, QTabletEvent *event);
Qt::BrushStyle brushPattern(qreal value);
- void updateBrush(QTabletEvent *event);
+ void updateBrush(const QTabletEvent *event);
+ void updateCursor(const QTabletEvent *event);
AlphaChannelType alphaChannelType;
ColorSaturationType colorSaturationType;
@@ -107,7 +108,11 @@ private:
QBrush myBrush;
QPen myPen;
bool deviceDown;
- QPoint polyLine[3];
+
+ struct Point {
+ QPointF pos;
+ qreal rotation;
+ } lastPoint;
};
//! [0]
diff --git a/examples/xml/dombookmarks/dombookmarks.pro b/examples/xml/dombookmarks/dombookmarks.pro
index baf63fa191..0ab4f0266d 100644
--- a/examples/xml/dombookmarks/dombookmarks.pro
+++ b/examples/xml/dombookmarks/dombookmarks.pro
@@ -14,6 +14,6 @@ INSTALLS += target
wince {
addFiles.files = frank.xbel jennifer.xbel
addFiles.path = "\\My Documents"
- DEPLOYMENT += addFiles
+ INSTALLS += addFiles
}
diff --git a/examples/xml/htmlinfo/htmlinfo.pro b/examples/xml/htmlinfo/htmlinfo.pro
index c0b82965ee..8adaa780b8 100644
--- a/examples/xml/htmlinfo/htmlinfo.pro
+++ b/examples/xml/htmlinfo/htmlinfo.pro
@@ -9,7 +9,7 @@ win32: CONFIG += console
wince {
htmlfiles.files = *.html
htmlfiles.path = .
- DEPLOYMENT += htmlfiles
+ INSTALLS += htmlfiles
}
# install
diff --git a/examples/xml/saxbookmarks/saxbookmarks.pro b/examples/xml/saxbookmarks/saxbookmarks.pro
index 353e1559cc..96a48ef5d4 100644
--- a/examples/xml/saxbookmarks/saxbookmarks.pro
+++ b/examples/xml/saxbookmarks/saxbookmarks.pro
@@ -16,5 +16,5 @@ INSTALLS += target
wince {
addFiles.files = frank.xbel jennifer.xbel
addFiles.path = "\\My Documents"
- DEPLOYMENT += addFiles
+ INSTALLS += addFiles
}
diff --git a/mkspecs/common/clang-mac.conf b/mkspecs/common/clang-mac.conf
index 3280274f36..d95e982b14 100644
--- a/mkspecs/common/clang-mac.conf
+++ b/mkspecs/common/clang-mac.conf
@@ -6,5 +6,6 @@ QMAKE_OBJCXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
QMAKE_XCODE_GCC_VERSION = com.apple.compilers.llvm.clang.1_0
-QMAKE_CXXFLAGS_CXX11 += -stdlib=libc++
-QMAKE_LFLAGS_CXX11 += -stdlib=libc++
+QMAKE_CXXFLAGS += -stdlib=libc++
+QMAKE_OBJECTIVE_CFLAGS += -stdlib=libc++
+QMAKE_LFLAGS += -stdlib=libc++
diff --git a/mkspecs/common/clang.conf b/mkspecs/common/clang.conf
index a0a2b3f3d1..ee5fc14458 100644
--- a/mkspecs/common/clang.conf
+++ b/mkspecs/common/clang.conf
@@ -27,6 +27,7 @@ QMAKE_CXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_CXXFLAGS_DISABLE_LTCG = $$QMAKE_CFLAGS_DISABLE_LTCG
QMAKE_CXXFLAGS_CXX11 = -std=c++11
+QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++11
QMAKE_LFLAGS_CXX11 =
QMAKE_LFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
diff --git a/mkspecs/common/g++-base.conf b/mkspecs/common/g++-base.conf
index d687dbc3f3..114a441687 100644
--- a/mkspecs/common/g++-base.conf
+++ b/mkspecs/common/g++-base.conf
@@ -28,4 +28,5 @@ QMAKE_CXXFLAGS_PRECOMPILE = -x c++-header -c ${QMAKE_PCH_INPUT} -o ${QMAKE_P
QMAKE_CXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
QMAKE_CXXFLAGS_CXX11 = -std=c++0x
+QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++0x
QMAKE_LFLAGS_CXX11 =
diff --git a/mkspecs/common/mac/qplatformdefs.h b/mkspecs/common/mac/qplatformdefs.h
index 44664933df..18f62e23f8 100644
--- a/mkspecs/common/mac/qplatformdefs.h
+++ b/mkspecs/common/mac/qplatformdefs.h
@@ -62,6 +62,7 @@
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
+#define __APPLE_USE_RFC_3542
#include <netinet/in.h>
#ifndef QT_NO_IPV6IFNAME
#include <net/if.h>
diff --git a/mkspecs/common/msvc-desktop.conf b/mkspecs/common/msvc-desktop.conf
index 369f95bae9..849048dad0 100644
--- a/mkspecs/common/msvc-desktop.conf
+++ b/mkspecs/common/msvc-desktop.conf
@@ -23,7 +23,7 @@ contains(QMAKE_TARGET.arch, x86_64) {
QMAKE_CC = cl
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -nologo -Zc:wchar_t
QMAKE_CFLAGS_WARN_ON = -W3
diff --git a/mkspecs/common/wince/qmake.conf b/mkspecs/common/wince/qmake.conf
index 434e063de8..3eac38f6b7 100644
--- a/mkspecs/common/wince/qmake.conf
+++ b/mkspecs/common/wince/qmake.conf
@@ -15,7 +15,7 @@ QMAKE_COMPILER = msvc
QMAKE_CC = cl
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -nologo -Zm200 -Zc:wchar_t-
QMAKE_CFLAGS_WARN_ON = -W3
diff --git a/mkspecs/common/winrt_winphone/qmake.conf b/mkspecs/common/winrt_winphone/qmake.conf
index 97ef661230..ca5119bded 100644
--- a/mkspecs/common/winrt_winphone/qmake.conf
+++ b/mkspecs/common/winrt_winphone/qmake.conf
@@ -16,7 +16,7 @@ DEPLOYMENT_PLUGIN += qwinrt
QMAKE_CC = cl
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -nologo
QMAKE_CFLAGS_WARN_ON = -W3
diff --git a/mkspecs/common/winrt_winphone/qplatformdefs.h b/mkspecs/common/winrt_winphone/qplatformdefs.h
index 14f6c58253..6abac1e94d 100644
--- a/mkspecs/common/winrt_winphone/qplatformdefs.h
+++ b/mkspecs/common/winrt_winphone/qplatformdefs.h
@@ -130,4 +130,14 @@
typedef int mode_t;
+#ifndef INADDR_ANY
+# define INADDR_ANY (u_long)0x00000000
+#endif
+#ifndef INADDR_LOOPBACK
+# define INADDR_LOOPBACK 0x7f000001
+#endif
+#ifndef INADDR_BROADCAST
+# define INADDR_BROADCAST (u_long)0xffffffff
+#endif
+
#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/cygwin-g++/qmake.conf b/mkspecs/cygwin-g++/qmake.conf
index caed4133b1..53cd35611f 100644
--- a/mkspecs/cygwin-g++/qmake.conf
+++ b/mkspecs/cygwin-g++/qmake.conf
@@ -14,7 +14,7 @@ QMAKE_COMPILER = gcc
QMAKE_CC = gcc
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -pipe
QMAKE_CFLAGS_DEPS = -M
diff --git a/mkspecs/devices/common/linux_device_post.conf b/mkspecs/devices/common/linux_device_post.conf
index d90d25191f..88fa31d805 100644
--- a/mkspecs/devices/common/linux_device_post.conf
+++ b/mkspecs/devices/common/linux_device_post.conf
@@ -3,6 +3,10 @@ contains(DISTRO_OPTS, deb-multi-arch) {
-Wl,-rpath-link,$$[QT_SYSROOT]/lib/$${GCC_MACHINE_DUMP}
}
+contains(DISTRO_OPTS, boot2qt) {
+ QMAKE_PLATFORM += boot2qt
+}
+
QMAKE_CFLAGS += $$COMPILER_FLAGS
QMAKE_CXXFLAGS += $$COMPILER_FLAGS
QMAKE_LFLAGS += $$LINKER_FLAGS
diff --git a/mkspecs/devices/linux-beagleboard-g++/qmake.conf b/mkspecs/devices/linux-beagleboard-g++/qmake.conf
index 1d32d374c6..604da50f63 100644
--- a/mkspecs/devices/linux-beagleboard-g++/qmake.conf
+++ b/mkspecs/devices/linux-beagleboard-g++/qmake.conf
@@ -26,7 +26,7 @@ QMAKE_OBJCOPY = $${CROSS_COMPILE}objcopy
QMAKE_NM = $${CROSS_COMPILE}nm -P
QMAKE_STRIP = $${CROSS_COMPILE}strip
-COMPILER_FLAGS = -march=armv7-a -mtune=cortex-a8 -mfpu=neon -mfloat-abi=softfp
+COMPILER_FLAGS = -march=armv7-a -mtune=cortex-a8 -mfpu=neon -mthumb
#modifications to gcc-base.conf
QMAKE_CFLAGS += $${COMPILER_FLAGS}
@@ -47,11 +47,12 @@ QMAKE_LIBS_EGL = -lEGL -lIMGegl -lsrv_um
QMAKE_LIBS_OPENGL_ES2 = -lGLESv2 $${QMAKE_LIBS_EGL}
QMAKE_LIBS_OPENVG = -lOpenVG $${QMAKE_LIBS_EGL}
+DISTRO_OPTS += hard-float
+
# No need for any special EGL device integration.
# Prioritize the default, compiled-in integration over any plugins.
EGLFS_DEVICE_INTEGRATION = none
-# Sanity check
-deviceSanityCheckCompiler()
+include(../common/linux_arm_device_post.conf)
load(qt_config)
diff --git a/mkspecs/devices/linux-nuc-g++/qmake.conf b/mkspecs/devices/linux-nuc-g++/qmake.conf
new file mode 100644
index 0000000000..fef5991341
--- /dev/null
+++ b/mkspecs/devices/linux-nuc-g++/qmake.conf
@@ -0,0 +1,20 @@
+#
+# qmake configuration for the Intel NUC DE3815TYKE targeting EGL/GLES either via KMS (eglfs) or Wayland
+#
+# Verified with a core-image-weston image produced by Yocto.
+
+include(../common/linux_device_pre.conf)
+
+QMAKE_LIBS_EGL += -lEGL
+QMAKE_LIBS_OPENGL_ES2 += -lGLESv2 -lEGL
+
+NUC_CFLAGS = -m64
+QMAKE_CFLAGS += $$NUC_CFLAGS
+QMAKE_CXXFLAGS += $$NUC_CFLAGS
+
+# Preferred eglfs backend
+EGLFS_DEVICE_INTEGRATION = eglfs_kms
+
+include(../common/linux_device_post.conf)
+
+load(qt_config)
diff --git a/mkspecs/devices/linux-nuc-g++/qplatformdefs.h b/mkspecs/devices/linux-nuc-g++/qplatformdefs.h
new file mode 100644
index 0000000000..5ae49b35dd
--- /dev/null
+++ b/mkspecs/devices/linux-nuc-g++/qplatformdefs.h
@@ -0,0 +1,34 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the qmake spec of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "../../linux-g++/qplatformdefs.h"
diff --git a/mkspecs/features/c++11.prf b/mkspecs/features/c++11.prf
index 32eaca4a9b..c8a86548ee 100644
--- a/mkspecs/features/c++11.prf
+++ b/mkspecs/features/c++11.prf
@@ -1,10 +1,9 @@
-QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_CXX11
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_CXXFLAGS_CXX11
-QMAKE_LFLAGS += $$QMAKE_LFLAGS_CXX11
-
-contains(QMAKE_LFLAGS, -stdlib=libc++) {
- equals(QMAKE_MACOSX_DEPLOYMENT_TARGET, 10.6): \
- QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.7
- contains(QMAKE_IOS_DEPLOYMENT_TARGET, ^4.*): \
- QMAKE_IOS_DEPLOYMENT_TARGET = 5.0
+strict_c++|isEmpty(QMAKE_CXXFLAGS_GNUCXX11) {
+ QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_CXX11
+ QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_CXXFLAGS_CXX11
+ QMAKE_LFLAGS += $$QMAKE_LFLAGS_CXX11
+} else {
+ QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_GNUCXX11
+ QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_CXXFLAGS_GNUCXX11
+ QMAKE_LFLAGS += $$QMAKE_LFLAGS_GNUCXX11
}
diff --git a/mkspecs/features/c++14.prf b/mkspecs/features/c++14.prf
index a54d11840d..076458560d 100644
--- a/mkspecs/features/c++14.prf
+++ b/mkspecs/features/c++14.prf
@@ -2,15 +2,21 @@ intel_icc {
# ICC does not support C++14 yet
} else: clang {
# Clang has supported -std=c++1y since version 3.2
- greaterThan(QT_CLANG_MAJOR_VERSION, 3)|greaterThan(QT_CLANG_MINOR_VERSION, 1): \
+ greaterThan(QT_CLANG_MAJOR_VERSION, 3)|greaterThan(QT_CLANG_MINOR_VERSION, 1) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
+ QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
+ }
# Unknown how long Apple Clang has supported -std=c++1y, but at least since XCode 5.0
- greaterThan(QT_APPLE_CLANG_MAJOR_VERSION, 4): \
+ greaterThan(QT_APPLE_CLANG_MAJOR_VERSION, 4) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
+ QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
+ }
} else: gcc {
# GCC has supported -std=c++1y since 4.8
- greaterThan(QT_GCC_MAJOR_VERSION, 4)|greaterThan(QT_GCC_MINOR_VERSION, 7): \
+ greaterThan(QT_GCC_MAJOR_VERSION, 4)|greaterThan(QT_GCC_MINOR_VERSION, 7) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
+ QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
+ }
}
# Delegate to c++11.prf
diff --git a/mkspecs/features/lex.prf b/mkspecs/features/lex.prf
index 43d8fbd038..19ffe1932c 100644
--- a/mkspecs/features/lex.prf
+++ b/mkspecs/features/lex.prf
@@ -10,13 +10,22 @@
} else {
lex.variable_out = GENERATED_SOURCES
}
- isEmpty(QMAKE_LEXFLAGS_MANGLE):QMAKE_LEXFLAGS_MANGLE = -P${QMAKE_FILE_BASE}
- QMAKE_LEXEXTRAFLAGS = $$QMAKE_LEXFLAGS
- !yacc_no_name_mangle:QMAKE_LEXEXTRAFLAGS += $$QMAKE_LEXFLAGS_MANGLE
- lex.commands = $$QMAKE_LEX $$QMAKE_LEXEXTRAFLAGS ${QMAKE_FILE_IN}$$escape_expand(\\n\\t) \
- $$QMAKE_DEL_FILE $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_lex$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t) \
- $$QMAKE_MOVE lex.${QMAKE_FILE_BASE}.c $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_lex$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t)
+ contains(QMAKE_LEX, .*flex) {
+ # GNU flex, we can use -o outfile
+ lex.commands = $$QMAKE_LEX $$QMAKE_LEXFLAGS --nounistd -o ${QMAKE_FILE_OUT} ${QMAKE_FILE_IN}
+ } else {
+ # stupid POSIX lex, it only generates a file called lex.yy.c
+ # or lex.prefix.c if the -P<prefix> option is active
+ intermediate_file = lex.yy.c
+ QMAKE_LEXEXTRAFLAGS = $$QMAKE_LEXFLAGS $$QMAKE_LEXFLAGS_MANGLE
+
+ lex.commands = \
+ -$(DEL_FILE) ${QMAKE_FILE_OUT}$$escape_expand(\\n\\t) \
+ $$QMAKE_LEX $$QMAKE_LEXEXTRAFLAGS ${QMAKE_FILE_IN}$$escape_expand(\\n\\t) \
+ $(MOVE) $$intermediate_file ${QMAKE_FILE_OUT} $$escape_expand(\\n\\t)
+ unset(intermediate_file)
+ }
lex.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_lex$${first(QMAKE_EXT_CPP)}
silent:lex.commands = @echo Lex ${QMAKE_FILE_IN} && $$lex.commands
diff --git a/mkspecs/features/plugin_bundle.prf b/mkspecs/features/plugin_bundle.prf
new file mode 100644
index 0000000000..f3e7294c90
--- /dev/null
+++ b/mkspecs/features/plugin_bundle.prf
@@ -0,0 +1,2 @@
+# Override mkspec default which creates a shared library
+mac: QMAKE_LFLAGS_PLUGIN = -bundle
diff --git a/mkspecs/features/qt.prf b/mkspecs/features/qt.prf
index be54d030e7..ce93105f4b 100644
--- a/mkspecs/features/qt.prf
+++ b/mkspecs/features/qt.prf
@@ -252,15 +252,18 @@ for(QT_CURRENT_VERIFY, $$list($$QT_PLUGIN_VERIFY)) {
# if the plugin is linked statically there is no need to deploy it
DEPLOYMENT_PLUGIN -= $$QT_CURRENT_VERIFY
}
- isEqual(QT_CURRENT_VERIFY, DEPLOYMENT_PLUGIN):shared:if(wince*|winrt): {
+
+ # The following block is currently broken, because qt_plugin_XXX.prf files
+ # are not generated for dynamic builds.
+ false:isEqual(QT_CURRENT_VERIFY, DEPLOYMENT_PLUGIN):shared:if(wince*|winrt) {
QT_ITEM =
debug: QT_ITEM = $${QTPLUG}d4.dll
else: QT_ITEM = $${QTPLUG}4.dll
- eval(qt_additional_plugin_$${QTPLUG}.files = $$[QT_INSTALL_PLUGINS/get]/$${QT_PLUGINPATH}/$${QT_ITEM})
- eval(qt_additional_plugin_$${QTPLUG}.path = $${QT_PLUGINPATH})
+ qt_additional_plugin_$${QTPLUG}.files = $$[QT_INSTALL_PLUGINS/get]/$${QT_PLUGINPATH}/$${QT_ITEM}
+ qt_additional_plugin_$${QTPLUG}.path = $${QT_PLUGINPATH}
- DEPLOYMENT *= qt_additional_plugin_$${QTPLUG}
+ INSTALLS *= qt_additional_plugin_$${QTPLUG}
}
}
}
diff --git a/mkspecs/features/qt_common.prf b/mkspecs/features/qt_common.prf
index 55f65b5526..2ed43e5063 100644
--- a/mkspecs/features/qt_common.prf
+++ b/mkspecs/features/qt_common.prf
@@ -12,7 +12,7 @@
QMAKE_DIR_REPLACE_SANE += DESTDIR
CONFIG -= debug_and_release_target
-contains(QT_CONFIG, c++11): CONFIG += c++11
+contains(QT_CONFIG, c++11): CONFIG += c++11 strict_c++
contains(TEMPLATE, .*lib) {
# module and plugins
!host_build:contains(QT_CONFIG, reduce_exports): CONFIG += hide_symbols
diff --git a/mkspecs/features/resources.prf b/mkspecs/features/resources.prf
index 8564731a22..7a38ff8f38 100644
--- a/mkspecs/features/resources.prf
+++ b/mkspecs/features/resources.prf
@@ -6,6 +6,66 @@ isEmpty(QMAKE_MOD_RCC):QMAKE_MOD_RCC = qrc
!contains(QMAKE_RESOURCE_FLAGS, -root):!isEmpty(QMAKE_RESOURCE_ROOT):QMAKE_RESOURCE_FLAGS += -root $$QMAKE_RESOURCE_ROOT
!contains(QMAKE_RESOURCE_FLAGS, -name): QMAKE_RESOURCE_FLAGS += -name ${QMAKE_FILE_BASE}
+# http://www.w3.org/TR/xml/#syntax
+defineReplace(xml_escape) {
+ 1 ~= s,&,&amp;,
+ 1 ~= s,\',&apos;,
+ 1 ~= s,\",&quot;,
+ 1 ~= s,<,&lt;,
+ 1 ~= s,>,&gt;,
+ return($$1)
+}
+
+RESOURCES += qmake_immediate
+for(resource, RESOURCES) {
+ # Regular case of user qrc file
+ contains(resource, ".*\.qrc$"): \
+ next()
+
+ # Fallback for stand-alone files/directories
+ !defined($${resource}.files, var) {
+ !equals(resource, qmake_immediate) {
+ !exists($$absolute_path($$resource, $$_PRO_FILE_PWD_)): \
+ warning("Failure to find: $$resource")
+ qmake_immediate.files += $$resource
+ }
+ RESOURCES -= $$resource
+ next()
+ }
+
+ resource_file = $$RCC_DIR/qmake_$${resource}.qrc
+
+ !debug_and_release|build_pass {
+ # Collection of files, generate qrc file
+ prefix = $$eval($${resource}.prefix)
+ isEmpty(prefix): \
+ prefix = "/"
+
+ resource_file_content = \
+ "<!DOCTYPE RCC><RCC version=\"1.0\">" \
+ "<qresource prefix=\"$$xml_escape($$prefix)\">"
+
+ abs_base = $$absolute_path($$eval($${resource}.base), $$_PRO_FILE_PWD_)
+
+ for(file, $${resource}.files) {
+ abs_path = $$absolute_path($$file, $$_PRO_FILE_PWD_)
+ alias = $$relative_path($$abs_path, $$abs_base)
+ resource_file_content += \
+ "<file alias=\"$$xml_escape($$alias)\">$$xml_escape($$abs_path)</file>"
+ }
+
+ resource_file_content += \
+ "</qresource>" \
+ "</RCC>"
+
+ !write_file($$OUT_PWD/$$resource_file, resource_file_content): \
+ error("Aborting.")
+ }
+
+ RESOURCES -= $$resource
+ RESOURCES += $$resource_file
+}
+
rcc.input = RESOURCES
rcc.name = RCC ${QMAKE_FILE_IN}
rcc.depend_command = $$QMAKE_RCC_DEP -list $$QMAKE_RESOURCE_FLAGS ${QMAKE_FILE_IN}
diff --git a/mkspecs/features/yacc.prf b/mkspecs/features/yacc.prf
index 4d7e0a381b..22fe4cb0a2 100644
--- a/mkspecs/features/yacc.prf
+++ b/mkspecs/features/yacc.prf
@@ -9,9 +9,9 @@
isEmpty(QMAKE_YACCFLAGS_MANGLE) {
- QMAKE_YACCFLAGS_MANGLE = -p ${QMAKE_FILE_BASE}
- QMAKE_YACC_HEADER = y.tab.h
- QMAKE_YACC_SOURCE = y.tab.c
+ QMAKE_YACCFLAGS_MANGLE = -p ${QMAKE_FILE_BASE} -b ${QMAKE_FILE_BASE}
+ QMAKE_YACC_HEADER = ${QMAKE_FILE_BASE}.tab.h
+ QMAKE_YACC_SOURCE = ${QMAKE_FILE_BASE}.tab.c
} else {
QMAKE_YACCFLAGS_MANGLE ~= s/\\$base/${QMAKE_FILE_BASE}/g #backwards compat
QMAKE_YACC_HEADER ~= s/\\$base/${QMAKE_FILE_BASE}/g
@@ -21,10 +21,10 @@
!yacc_no_name_mangle:QMAKE_YACCDECLFLAGS += $$QMAKE_YACCFLAGS_MANGLE
yacc_decl.commands = \
+ -$(DEL_FILE) $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t) \
$$QMAKE_YACC $$QMAKE_YACCDECLFLAGS ${QMAKE_FILE_IN}$$escape_expand(\\n\\t) \
- $$QMAKE_DEL_FILE $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t) \
- $$QMAKE_MOVE $${QMAKE_YACC_HEADER} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)}$$escape_expand(\\n\\t) \
- $$QMAKE_MOVE $${QMAKE_YACC_SOURCE} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t)
+ $(MOVE) $${QMAKE_YACC_HEADER} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)}$$escape_expand(\\n\\t) \
+ $(MOVE) $${QMAKE_YACC_SOURCE} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t)
yacc_decl.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)}
silent:yacc_decl.commands = @echo Yacc ${QMAKE_FILE_IN} && $$yacc_decl.commands
diff --git a/mkspecs/linux-icc/qmake.conf b/mkspecs/linux-icc/qmake.conf
index 9190aa9f28..ca9e81512e 100644
--- a/mkspecs/linux-icc/qmake.conf
+++ b/mkspecs/linux-icc/qmake.conf
@@ -50,6 +50,7 @@ QMAKE_CXXFLAGS_SPLIT_SECTIONS = $$QMAKE_CFLAGS_SPLIT_SECTIONS
# Disabling exceptions disabled - workaround for QTBUG-36577
#QMAKE_CXXFLAGS_EXCEPTIONS_OFF = -fno-exceptions
QMAKE_CXXFLAGS_CXX11 = -std=c++0x
+QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++0x
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_INCDIR =
diff --git a/mkspecs/macx-icc/qmake.conf b/mkspecs/macx-icc/qmake.conf
index 5e45e67d0c..c145c2c8f3 100644
--- a/mkspecs/macx-icc/qmake.conf
+++ b/mkspecs/macx-icc/qmake.conf
@@ -53,6 +53,7 @@ QMAKE_CXXFLAGS_STATIC_LIB = $$QMAKE_CFLAGS_STATIC_LIB
QMAKE_CXXFLAGS_YACC = $$QMAKE_CFLAGS_YACC
QMAKE_CXXFLAGS_THREAD = $$QMAKE_CFLAGS_THREAD
QMAKE_CXXFLAGS_CXX11 = -std=c++11
+QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++11
QMAKE_CXXFLAGS_SPLIT_SECTIONS = $$QMAKE_CFLAGS_SPLIT_SECTIONS
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
diff --git a/mkspecs/macx-ios-clang/Info.plist.app b/mkspecs/macx-ios-clang/Info.plist.app
index 623ed496c5..623ed496c5 100755..100644
--- a/mkspecs/macx-ios-clang/Info.plist.app
+++ b/mkspecs/macx-ios-clang/Info.plist.app
diff --git a/mkspecs/macx-ios-clang/features/default_post.prf b/mkspecs/macx-ios-clang/features/default_post.prf
index 172e34bac5..5266c88f16 100644
--- a/mkspecs/macx-ios-clang/features/default_post.prf
+++ b/mkspecs/macx-ios-clang/features/default_post.prf
@@ -1,179 +1,24 @@
-load(sdk)
-
-# Resolve config so we don't need to use CONFIG() later on
-CONFIG(iphonesimulator, iphonesimulator|iphoneos) {
- CONFIG -= iphoneos
-} else {
- CONFIG -= iphonesimulator
- CONFIG += iphoneos
-}
-
-equals(TEMPLATE, app) {
+equals(TEMPLATE, app):contains(CONFIG, qt) {
# If the application uses Qt, it needs to be an application bundle
# to be able to deploy and run on iOS. The only exception to this
# is if you're working with a jailbroken device and can run the
# resulting binary from the console/over SSH, but that's not a
# use-case we care about, so no need to complicate the logic.
- qt: CONFIG *= app_bundle
-
- app_bundle {
- macx-xcode {
- # There is no way to genereate Xcode projects that are limited to either
- # simulator or device builds, so iphonesimulator_and_iphoneos is always
- # effectivly active, even if the user disabled it explicitly.
- # The Xcode generator doesn't support multiple BUILDS though (exclusive
- # builds), so we have to manually set up the simulator suffix.
- library_suffix_iphonesimulator.name = "$${QMAKE_XCODE_LIBRARY_SUFFIX_SETTING}[sdk=iphonesimulator*]"
- library_suffix_iphonesimulator.value = "_iphonesimulator$($${QMAKE_XCODE_LIBRARY_SUFFIX_SETTING})"
- QMAKE_MAC_XCODE_SETTINGS += library_suffix_iphonesimulator
- CONFIG *= xcode_dynamic_library_suffix
- } else {
- # For Qt applications we want Xcode project files as the generated output,
- # but since qmake doesn't handle the transition between makefiles and Xcode
- # project files (which happens when using subdirs), we create a wrapper
- # makefile that takes care of generating the Xcode project, and allows
- # building by calling out to xcodebuild.
- TEMPLATE = aux
-
- SOURCES =
- OBJECTIVE_SOURCES =
- RESOURCES =
- INSTALLS =
- QMAKE_EXTRA_COMPILERS =
-
- !build_pass {
- CONFIG += debug_and_release
- load(resolve_config)
-
- CONFIG += iphonesimulator_and_iphoneos
- iphonesimulator.name = Simulator
- iphoneos.name = Device
- addExclusiveBuilds(iphonesimulator, iphoneos)
-
- load(exclusive_builds_post)
-
- xcode_distclean.commands = "$(DEL_FILE) -R $${TARGET}.xcodeproj"
- xcode_distclean.depends = \
- debug-iphonesimulator-distclean debug-iphoneos-distclean \
- release-iphonesimulator-distclean release-iphoneos-distclean
- QMAKE_EXTRA_TARGETS += xcode_distclean
- DISTCLEAN_DEPS += xcode_distclean
-
- mkpath($$OUT_PWD)|error("Aborting.")
- args =
- for(arg, QMAKE_ARGS): \
- args += $$system_quote($$arg)
- system("cd $$system_quote($$OUT_PWD) && $$QMAKE_QMAKE $$args $$system_quote($$_PRO_FILE_) -spec macx-xcode")
-
- # We have a target, even though our template is aux
- CONFIG += have_target
-
- } else {
- load(resolve_config)
-
- iphonesimulator: \
- sdk = iphonesimulator
- else: \
- sdk = iphoneos
-
- debug: \
- cfg = debug
- else: \
- cfg = release
-
- for(action, $$list(build install clean test)) {
- equals(action, build) {
- action_target_suffix =
- action_target = all
- } else: equals(action, test) {
- action_target_suffix = -check
- action_target = check
- } else {
- action_target_suffix = -$$action
- action_target = $$action
- }
-
- target = $${sdk}-$${cfg}$${action_target_suffix}
-
- xcodebuild = "xcodebuild $$action -scheme $(TARGET) -sdk $$sdk -configuration $$title($$cfg)"
-
- equals(action, test):equals(sdk, iphoneos) {
- AVAILABLE_DEVICE_IDS = "$(shell system_profiler SPUSBDataType | sed -n -E -e '/(iPhone|iPad|iPod)/,/Serial/s/ *Serial Number: *(.+)/\1/p')"
- CUSTOM_DEVICE_IDS = "$(filter $(EXPORT_AVAILABLE_DEVICE_IDS), $(IOS_TEST_DEVICE_IDS))"
- TEST_DEVICE_IDS = "$(strip $(if $(EXPORT_CUSTOM_DEVICE_IDS), $(EXPORT_CUSTOM_DEVICE_IDS), $(EXPORT_AVAILABLE_DEVICE_IDS)))"
-
- QMAKE_EXTRA_VARIABLES += AVAILABLE_DEVICE_IDS CUSTOM_DEVICE_IDS TEST_DEVICE_IDS
-
- xcodebuild = "@$(if $(EXPORT_TEST_DEVICE_IDS),"\
- "echo Running tests on $(words $(EXPORT_TEST_DEVICE_IDS)) device\\(s\\): && ("\
- "$(foreach deviceid, $(EXPORT_TEST_DEVICE_IDS),"\
- "(echo Testing on device ID '$(deviceid)' ... && $${xcodebuild} -destination 'platform=iOS,id=$(deviceid)' && echo) &&"\
- ") echo Tests completed successfully on all devices"\
- "), $(error No iOS devices connected, please connect at least one device that can be used for testing.))"
- }
-
- $${target}.commands = $$xcodebuild
- QMAKE_EXTRA_TARGETS += $$target
-
- $${action_target}.depends += $$target
- QMAKE_EXTRA_TARGETS *= $${action_target}
- }
-
- xcode_build_dir_distclean.commands = "$(DEL_FILE) -R $$title($$cfg)-$${sdk}"
- xcode_build_dir_distclean.depends = clean
- QMAKE_EXTRA_TARGETS += xcode_build_dir_distclean
- distclean.depends = xcode_build_dir_distclean
- QMAKE_EXTRA_TARGETS += distclean
- }
- }
- }
-} else: equals(TEMPLATE, lib) {
- iphonesimulator.name = Simulator
- iphoneos.name = Device
- addExclusiveBuilds(iphonesimulator, iphoneos)
-} else: equals(TEMPLATE, subdirs) {
- # Prevent recursion into host_builds
- for(subdir, SUBDIRS) {
- contains($${subdir}.CONFIG, host_build) {
- $${subdir}.CONFIG += no_iphoneos_target no_iphonesimulator_target
-
- # Other targets which we do want to recurse into may depend on this target,
- # for example corelib depends on moc, rcc, bootstrap, etc, and other libs
- # may depend on host-tools that are needed to build the lib, so we resolve
- # the final target name and redirect it to the base target, so that the
- # dependency chain is not broken for the other targets.
-
- !isEmpty($${subdir}.target) {
- target = $$eval($${subdir}.target)
- } else {
- !isEmpty($${subdir}.file): \
- file = $$eval($${subdir}.file)
- else: !isEmpty($${subdir}.subdir): \
- file = $$eval($${subdir}.subdir)
- else: \
- file = $$subdir
-
- target = sub-$$file
- }
-
- target ~= s,[^a-zA-Z0-9_],-,
-
- $${target}-iphonesimulator.depends = $$target
- $${target}-iphoneos.depends = $$target
- QMAKE_EXTRA_TARGETS += $${target}-iphonesimulator $${target}-iphoneos
- }
- }
-
- prepareRecursiveTarget(iphonesimulator)
- prepareRecursiveTarget(iphoneos)
- QMAKE_EXTRA_TARGETS += iphonesimulator iphoneos
-
-} else: equals(TEMPLATE, aux) {
- # Dummy targets for the 'aux' TEMPLATE, so we can always recurse
- QMAKE_EXTRA_TARGETS *= iphonesimulator iphoneos
+ CONFIG *= app_bundle
+
+ # For Qt applications we want Xcode project files as the generated output,
+ # but since qmake doesn't handle the transition between makefiles and Xcode
+ # project files (which happens when using subdirs), we can't just override
+ # MAKEFILE_GENERATOR. Instead, we generate the Xcode project by spawning a
+ # child qmake process with -spec macx-xcode and let the top level qmake
+ # process generate a wrapper makefile that forwards everything to xcodebuild.
+ equals(MAKEFILE_GENERATOR, UNIX): \
+ CONFIG = xcodebuild $$CONFIG
}
+load(default_post)
+
macx-xcode {
ios_device_family.name = TARGETED_DEVICE_FAMILY
ios_device_family.value = $$QMAKE_IOS_TARGETED_DEVICE_FAMILY
@@ -251,5 +96,3 @@ macx-xcode {
QMAKE_OBJECTIVE_CFLAGS += $$arch_flags
QMAKE_LFLAGS += $$arch_flags
}
-
-load(default_post)
diff --git a/mkspecs/macx-ios-clang/features/exclusive_builds_post.prf b/mkspecs/macx-ios-clang/features/exclusive_builds_post.prf
new file mode 100644
index 0000000000..1fb0a55846
--- /dev/null
+++ b/mkspecs/macx-ios-clang/features/exclusive_builds_post.prf
@@ -0,0 +1,8 @@
+
+xcodebuild {
+ # Prevent qmake from generating empty output dirs for each exclusive build,
+ # as Xcode will do this by itself, and with a different name.
+ QMAKE_DIR_REPLACE =
+}
+
+load(exclusive_builds_post)
diff --git a/mkspecs/macx-ios-clang/features/qt.prf b/mkspecs/macx-ios-clang/features/qt.prf
index 9e6b486c6e..474a195e4b 100644
--- a/mkspecs/macx-ios-clang/features/qt.prf
+++ b/mkspecs/macx-ios-clang/features/qt.prf
@@ -19,34 +19,12 @@ equals(TEMPLATE, app):contains(qt_depends, gui(-private)?) {
QTPLUGIN.platforms = -
!no_main_wrapper {
- # We use ld to rename the _main symbol to _qt_main, so that we don't get a symbol clash
- # with the _main we provide that calls UIApplicationMain. We need to make a copy of the
- # original object file, as ld will not copy over DWARF debug information to the output
- # file. Instead, it will inject a reference back to the original object file, so when
- # Xcode runs dsymutil to make the final dSYM file it will still find the debug info
- # for the object file that provided the original _main. This back-reference has the
- # interesting side-effect of the debug information still referring to the original
- # symbol name, so stack-traces will show both our wrapper main and the original
- # user main as 'main', and adding a symbolic breakpoint for 'main' will break on
- # both functions. Although a bit weird, it's a good thing, as the user will still be
- # able to add symbolic breakpoints for 'main', not caring that the symbol is actually
- # called 'qt_main' now.
-
- macx-xcode {
- objects_dir = "\"${OBJECT_FILE_DIR}-${CURRENT_VARIANT}\""
- archs = "\"${ARCHS}\""
- } else {
- isEmpty(OBJECTS_DIR): \
- objects_dir = .
- else: \
- objects_dir = $$shell_quote($$OBJECTS_DIR)
- archs = $$shell_quote($$QMAKE_IOS_DEVICE_ARCHS $$QMAKE_IOS_SIMULATOR_ARCHS)
- }
-
- !isEmpty(QMAKE_PRE_LINK): \
- QMAKE_PRE_LINK += ";"
-
- QMAKE_PRE_LINK += $$shell_quote($$QMAKESPEC/rename_main.sh) $$objects_dir $$archs
+ # The LC_MAIN load command available in iOS 6.0 and above allows dyld to
+ # directly call the entrypoint instead of going through _start in crt.o.
+ # Passing -e to the linker changes the entrypoint from _main to our custom
+ # wrapper that calls UIApplicationMain and dispatches back to main() once
+ # the application has started up and is ready to initialize QApplication.
+ QMAKE_LFLAGS += -Wl,-e,_qt_main_wrapper
}
}
diff --git a/mkspecs/macx-ios-clang/features/resolve_config.prf b/mkspecs/macx-ios-clang/features/resolve_config.prf
new file mode 100644
index 0000000000..d1d3e8ca39
--- /dev/null
+++ b/mkspecs/macx-ios-clang/features/resolve_config.prf
@@ -0,0 +1,64 @@
+
+xcodebuild {
+ # Xcode project files always support both Debug and Release configurations
+ # and iOS device and simulator targets, so we make sure the wrapper-makefile
+ # also does.
+ CONFIG += debug_and_release iphonesimulator_and_iphoneos
+}
+
+load(resolve_config)
+
+CONFIG(iphonesimulator, iphonesimulator|iphoneos): \
+ CONFIG -= iphoneos
+else: \
+ CONFIG -= iphonesimulator
+
+macx-xcode {
+ # There is no way to genereate Xcode projects that are limited to either
+ # simulator or device builds, so iphonesimulator_and_iphoneos is always
+ # effectivly active, even if the user disabled it explicitly.
+ # The Xcode generator doesn't support multiple BUILDS though (exclusive
+ # builds), so we have to manually set up the simulator suffix.
+ library_suffix_iphonesimulator.name = "$${QMAKE_XCODE_LIBRARY_SUFFIX_SETTING}[sdk=iphonesimulator*]"
+ library_suffix_iphonesimulator.value = "_iphonesimulator$($${QMAKE_XCODE_LIBRARY_SUFFIX_SETTING})"
+ QMAKE_MAC_XCODE_SETTINGS += library_suffix_iphonesimulator
+ CONFIG *= xcode_dynamic_library_suffix
+} else {
+ iphonesimulator.name = Simulator
+ iphoneos.name = Device
+ addExclusiveBuilds(iphonesimulator, iphoneos)
+}
+
+equals(TEMPLATE, subdirs) {
+ # Prevent recursion into host_builds
+ for(subdir, SUBDIRS) {
+ contains($${subdir}.CONFIG, host_build) {
+ $${subdir}.CONFIG += no_iphoneos_target no_iphonesimulator_target
+
+ # Other targets which we do want to recurse into may depend on this target,
+ # for example corelib depends on moc, rcc, bootstrap, etc, and other libs
+ # may depend on host-tools that are needed to build the lib, so we resolve
+ # the final target name and redirect it to the base target, so that the
+ # dependency chain is not broken for the other targets.
+
+ !isEmpty($${subdir}.target) {
+ target = $$eval($${subdir}.target)
+ } else {
+ !isEmpty($${subdir}.file): \
+ file = $$eval($${subdir}.file)
+ else: !isEmpty($${subdir}.subdir): \
+ file = $$eval($${subdir}.subdir)
+ else: \
+ file = $$subdir
+
+ target = sub-$$file
+ }
+
+ target ~= s,[^a-zA-Z0-9_],-,
+
+ $${target}-iphonesimulator.depends = $$target
+ $${target}-iphoneos.depends = $$target
+ QMAKE_EXTRA_TARGETS += $${target}-iphonesimulator $${target}-iphoneos
+ }
+ }
+}
diff --git a/mkspecs/macx-ios-clang/features/testcase.prf b/mkspecs/macx-ios-clang/features/testcase.prf
new file mode 100644
index 0000000000..e16c163ffa
--- /dev/null
+++ b/mkspecs/macx-ios-clang/features/testcase.prf
@@ -0,0 +1,12 @@
+# Pretend we have a target, even though our template is aux
+xcodebuild: \
+ CONFIG += have_target
+
+load(testcase)
+
+# We provide our own check logic
+xcodebuild {
+ check.depends =
+ check.commands =
+ QMAKE_EXTRA_TARGETS *= check
+}
diff --git a/mkspecs/macx-ios-clang/features/testcase_targets.prf b/mkspecs/macx-ios-clang/features/testcase_targets.prf
new file mode 100644
index 0000000000..e0a2922c3f
--- /dev/null
+++ b/mkspecs/macx-ios-clang/features/testcase_targets.prf
@@ -0,0 +1,3 @@
+# For the xcodebuild wrapper makefile we deal with test targets manually
+!xcodebuild: \
+ load(testcase_targets)
diff --git a/mkspecs/macx-ios-clang/features/xcodebuild.prf b/mkspecs/macx-ios-clang/features/xcodebuild.prf
new file mode 100644
index 0000000000..b897432a43
--- /dev/null
+++ b/mkspecs/macx-ios-clang/features/xcodebuild.prf
@@ -0,0 +1,49 @@
+
+# For Qt applications we want Xcode project files as the generated output,
+# but since qmake doesn't handle the transition between makefiles and Xcode
+# project files (which happens when using subdirs), we can't just override
+# MAKEFILE_GENERATOR. Instead, we generate the Xcode project by spawing a
+# child qmake process with -spec macx-xcode and let the top level qmake
+# process generate a wrapper makefile that forwards everything to xcodebuild.
+
+TEMPLATE = aux
+
+SOURCES =
+OBJECTIVE_SOURCES =
+RESOURCES =
+INSTALLS =
+QMAKE_EXTRA_COMPILERS =
+
+!mkpath($$OUT_PWD): \
+ error("Failed to create $$OUT_PWD")
+
+args =
+for(arg, QMAKE_ARGS): \
+ args += $$system_quote($$arg)
+
+cmd = "$$QMAKE_QMAKE $$args $$system_quote($$_PRO_FILE_) -spec macx-xcode"
+debug(1, "Generating Xcode project in $$OUT_PWD using '$$cmd'")
+system("cd $$system_quote($$OUT_PWD) && $$cmd")
+
+# Subtargets
+
+for(build, BUILDS): \
+ SUBTARGETS += $$eval($${build}.target)
+QMAKE_EXTRA_VARIABLES += SUBTARGETS
+
+CONFIG += no_default_goal_deps
+
+QMAKE_EXTRA_INCLUDES += $$shell_quote($$QMAKESPEC/xcodebuild.mk)
+
+# Distclean
+
+distfiles = $${TARGET}.xcodeproj
+for(build, BUILDS): \
+ distfiles += $$title($$eval($${build}.target))
+distclean_xcodebuild.commands = -$(DEL_FILE) -R $$distfiles
+
+distclean.depends += clean_all distclean_xcodebuild
+QMAKE_EXTRA_TARGETS += distclean distclean_xcodebuild
+
+# Empty exclusive builds, we've set them up manually
+BUILDS =
diff --git a/mkspecs/macx-ios-clang/rename_main.sh b/mkspecs/macx-ios-clang/ios_destinations.sh
index 1547f5f75c..aebf8f6403 100755
--- a/mkspecs/macx-ios-clang/rename_main.sh
+++ b/mkspecs/macx-ios-clang/ios_destinations.sh
@@ -33,46 +33,23 @@
##
#############################################################################
-if [ $# -ne 2 ]; then
- echo "$0: wrong number of arguments for internal tool used by iOS mkspec"
-else
- arch_paths=""
- for a in $2; do
- arch_paths="$arch_paths
-$1/$a"
+booted_simulator=$(xcrun simctl list devices | grep -v unavailable | grep Booted | perl -lne 'print $1 if /\((.*?)\)/')
+echo "IPHONESIMULATOR_DEVICES = $booted_simulator"
+
+xcodebuild test -scheme $1 -destination 'id=0' -destination-timeout 1 2>&1| sed -n 's/{ \(platform:.*\) }/\1/p' | while read destination; do
+ id=$(echo $destination | sed -n -E 's/.*id:([^ ,]+).*/\1/p')
+ echo $destination | tr ',' '\n' | while read keyval; do
+ key=$(echo $keyval | cut -d ':' -f 1 | tr '[:lower:]' '[:upper:]')
+ val=$(echo $keyval | cut -d ':' -f 2)
+ echo "%_$id: DESTINATION_${key} = $val"
+
+ if [ $key = 'PLATFORM' ]; then
+ if [ "$val" = "iOS" ]; then
+ echo "IPHONEOS_DEVICES += $id"
+ elif [ "$val" = "iOS Simulator" -a "$id" != "$booted_simulator" ]; then
+ echo "IPHONESIMULATOR_DEVICES += $id"
+ fi
+ fi
done
- for f in $(IFS="
-"; find $arch_paths -name '*.o'); do
- # Skip object files without the _main symbol
- nm $f 2>/dev/null | grep -q 'T _main$' || continue
-
- fname=${f#$1/}
-
- file -b $f | grep -qi 'llvm bit-code' && \
- (cat \
-<<EOF >&2
-$f:: error: The file '$fname' contains LLVM bitcode, not object code. Automatic main() redirection could not be applied.
-note: This is most likely due to the use of link-time optimization (-flto). Please disable LTO, or work around the \
-issue by manually renaming your main() function to qtmn():
-
-#ifdef Q_OS_IOS
-extern "C" int qtmn(int argc, char *argv[])
-#else
-int main(int argc, char *argv[])
-#endif
-EOF
- ) && exit 1
-
- echo "Found main() in $fname"
-
- strings -t d - $f | grep '_main\(\.eh\)\?$' | while read match; do
- offset=$(echo $match | cut -d ' ' -f 1)
- symbol=$(echo $match | cut -d ' ' -f 2)
-
- echo " Renaming '$symbol' at offset $offset to '${symbol/main/qtmn}'"
-
- # In-place rename the string (keeping the same length)
- printf '_qtmn' | dd of=$f bs=1 seek=$offset conv=notrunc >/dev/null 2>&1
- done
- done
-fi \ No newline at end of file
+ echo
+done
diff --git a/mkspecs/macx-ios-clang/qmake.conf b/mkspecs/macx-ios-clang/qmake.conf
index 0dd761760c..d5e5840902 100644
--- a/mkspecs/macx-ios-clang/qmake.conf
+++ b/mkspecs/macx-ios-clang/qmake.conf
@@ -7,7 +7,7 @@ CONFIG += app_bundle reduce_exports incremental global_init_link
QMAKE_INCREMENTAL_STYLE = sublib
QMAKE_MACOSX_DEPLOYMENT_TARGET =
-QMAKE_IOS_DEPLOYMENT_TARGET = 5.1.1
+QMAKE_IOS_DEPLOYMENT_TARGET = 6.0
INCLUDEPATH += $$PWD/ios
DEFINES += DARWIN_NO_CARBON QT_NO_PRINTER QT_NO_PRINTDIALOG
diff --git a/mkspecs/macx-ios-clang/xcodebuild.mk b/mkspecs/macx-ios-clang/xcodebuild.mk
new file mode 100644
index 0000000000..f50010abc1
--- /dev/null
+++ b/mkspecs/macx-ios-clang/xcodebuild.mk
@@ -0,0 +1,96 @@
+
+# We don't want xcodebuild to run in parallel
+.NOTPARALLEL:
+
+# Functions
+targets = $(foreach target, $(EXPORT_SUBTARGETS), $(target)-$(strip $(1)))
+toupper = $(shell echo $1 | tr '[:lower:]' '[:upper:]')
+tolower = $(shell echo $1 | tr '[:upper:]' '[:lower:]')
+basesdk = $(shell echo $1 | sed 's/[0-9.]*$$//')
+
+# Explicit comma variable
+, := ,
+
+# Default targets
+first: build
+all: build_all
+
+.DEFAULT_GOAL = first
+
+# Top level targets
+build: build_first
+clean: clean_first
+install: install_first
+check: check_first
+distclean: clean_all
+
+$(EXPORT_SUBTARGETS): % : %-build
+
+# Generic targets
+%_first: $(firstword $(call targets, %)) ;
+%_all: $(call targets, %) ;
+
+# Actions
+%-build: ACTION = build
+%-build: xcodebuild-% ;
+
+%-clean: ACTION = clean
+%-clean: xcodebuild-% ;
+
+%-install: ACTION = install
+%-install: xcodebuild-% ;
+
+# Limit check to a single configuration
+%-iphoneos-check: check-iphoneos ;
+%-iphonesimulator-check: check-iphonesimulator ;
+
+# SDK
+%-iphoneos: SDK = iphoneos
+%-iphonesimulator: SDK = iphonesimulator
+
+# Configuration
+release-%: CONFIGURATION = Release
+debug-%: CONFIGURATION = Debug
+
+# Test and build (device) destinations
+ifneq ($(filter check%,$(MAKECMDGOALS)),)
+ ifeq ($(DEVICES),)
+ $(info Enumerating test destinations (you may override this by setting DEVICES explicitly), please wait...)
+ SPECDIR := $(dir $(lastword $(MAKEFILE_LIST)))
+ DESTINATIONS_INCLUDE = /tmp/ios_destinations.mk
+ $(shell $(SPECDIR)/ios_destinations.sh $(TARGET) > $(DESTINATIONS_INCLUDE))
+ include $(DESTINATIONS_INCLUDE)
+ endif
+endif
+
+%-iphonesimulator: DEVICES = $(firstword $(IPHONESIMULATOR_DEVICES))
+%-iphoneos: DEVICES = $(IPHONEOS_DEVICES)
+
+IPHONEOS_GENERIC_DESTINATION := "generic/platform=iOS"
+IPHONESIMULATOR_GENERIC_DESTINATION := "id=$(shell xcrun simctl list devices | grep -v unavailable | perl -lne 'print $$1 if /\((.*?)\)/' | tail -n 1)"
+
+DESTINATION = $(if $(DESTINATION_ID),"id=$(DESTINATION_ID)",$(value $(call toupper,$(call basesdk,$(SDK)))_GENERIC_DESTINATION))
+
+# Xcodebuild
+
+DESTINATION_MESSAGE = "Running $(call tolower,$(CONFIGURATION)) $(ACTION) \
+ on '$(DESTINATION_NAME)' ($(DESTINATION_ID))$(if $(DESTINATION_OS),$(,) $(DESTINATION_PLATFORM) $(DESTINATION_OS),)"
+
+xcodebuild-%:
+ @$(if $(DESTINATION_NAME), echo $(DESTINATION_MESSAGE),)
+ xcodebuild $(ACTION) -scheme $(TARGET) $(if $(SDK), -sdk $(SDK),) $(if $(CONFIGURATION), -configuration $(CONFIGURATION),) $(if $(DESTINATION), -destination $(DESTINATION) -destination-timeout 1,)
+
+xcodebuild-check-device_%: DESTINATION_ID=$(lastword $(subst _, ,$@))
+
+# Special check target (requires SECONDEXPANSION due to devices)
+.SECONDEXPANSION:
+check-%: ACTION = test
+check-%: $$(foreach device, $$(DEVICES), xcodebuild-check-device_$$(device)) ;
+ @echo $(if $^, Ran $(call tolower,$(CONFIGURATION)) tests on $(words $^) $(SDK) destination\(s\): $(DEVICES), No compatible test devices found for \'$(SDK)\' SDK && false)
+
+# Determined by device
+check-%: SDK =
+
+# Default to debug for testing
+check-%: CONFIGURATION = Debug
+
diff --git a/mkspecs/win32-g++/qmake.conf b/mkspecs/win32-g++/qmake.conf
index c6ff808a99..019c220de5 100644
--- a/mkspecs/win32-g++/qmake.conf
+++ b/mkspecs/win32-g++/qmake.conf
@@ -23,7 +23,7 @@ QMAKE_COMPILER = gcc
QMAKE_CC = $${CROSS_COMPILE}gcc
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -pipe -fno-keep-inline-dllexport
QMAKE_CFLAGS_DEPS = -M
@@ -56,6 +56,7 @@ QMAKE_CXXFLAGS_RTTI_OFF = -fno-rtti
QMAKE_CXXFLAGS_EXCEPTIONS_ON = -fexceptions -mthreads
QMAKE_CXXFLAGS_EXCEPTIONS_OFF = -fno-exceptions
QMAKE_CXXFLAGS_CXX11 = -std=c++0x
+QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++0x
QMAKE_CXXFLAGS_SPLIT_SECTIONS = $$QMAKE_CFLAGS_SPLIT_SECTIONS
QMAKE_INCDIR =
diff --git a/mkspecs/win32-icc/qmake.conf b/mkspecs/win32-icc/qmake.conf
index 2ec0d84918..31c87fff26 100644
--- a/mkspecs/win32-icc/qmake.conf
+++ b/mkspecs/win32-icc/qmake.conf
@@ -15,7 +15,7 @@ QMAKE_COMPILER = msvc intel_icl # icl pretends to be msvc
QMAKE_CC = icl
QMAKE_LEX = flex
QMAKE_LEXFLAGS =
-QMAKE_YACC = byacc
+QMAKE_YACC = bison -y
QMAKE_YACCFLAGS = -d
QMAKE_CFLAGS = -nologo -Zm200 /Qprec /Qwd1744,1738
QMAKE_CFLAGS_WARN_ON = -W3 /Qwd673
diff --git a/qmake/Makefile.unix b/qmake/Makefile.unix
index 86f884fe20..520ae667e9 100644
--- a/qmake/Makefile.unix
+++ b/qmake/Makefile.unix
@@ -13,7 +13,7 @@ OBJS=project.o option.o property.o main.o ioutils.o proitems.o \
#qt code
QOBJS=qtextcodec.o qutfcodec.o qstring.o qstring_compat.o qstringbuilder.o qtextstream.o qiodevice.o \
- qdebug.o qmalloc.o qglobal.o \
+ qringbuffer.o qdebug.o qmalloc.o qglobal.o \
qarraydata.o qbytearray.o qbytearraymatcher.o qdatastream.o qbuffer.o qlist.o qfiledevice.o qfile.o \
qfilesystementry.o qfilesystemengine.o qfsfileengine.o qfsfileengine_iterator.o qregexp.o qvector.o \
qbitarray.o qdir.o qdiriterator.o quuid.o qhash.o qfileinfo.o qdatetime.o qstringlist.o \
@@ -44,6 +44,7 @@ DEPEND_SRC = \
$(SOURCE_PATH)/src/corelib/tools/qstring_compat.cpp \
$(SOURCE_PATH)/src/corelib/io/qfiledevice.cpp \
$(SOURCE_PATH)/src/corelib/io/qtextstream.cpp $(SOURCE_PATH)/src/corelib/io/qiodevice.cpp \
+ $(SOURCE_PATH)/src/corelib/tools/qringbuffer.cpp \
$(SOURCE_PATH)/src/corelib/io/qdebug.cpp \
$(SOURCE_PATH)/src/corelib/global/qmalloc.cpp \
$(SOURCE_PATH)/src/corelib/global/qglobal.cpp $(SOURCE_PATH)/src/corelib/tools/qregexp.cpp \
@@ -242,6 +243,9 @@ qsettings_win.o: $(SOURCE_PATH)/src/corelib/io/qsettings_win.cpp
qiodevice.o: $(SOURCE_PATH)/src/corelib/io/qiodevice.cpp
$(CXX) -c -o $@ $(CXXFLAGS) $(SOURCE_PATH)/src/corelib/io/qiodevice.cpp
+qringbuffer.o: $(SOURCE_PATH)/src/corelib/tools/qringbuffer.cpp
+ $(CXX) -c -o $@ $(CXXFLAGS) $(SOURCE_PATH)/src/corelib/tools/qringbuffer.cpp
+
qdebug.o: $(SOURCE_PATH)/src/corelib/io/qdebug.cpp
$(CXX) -c -o $@ $(CXXFLAGS) $(SOURCE_PATH)/src/corelib/io/qdebug.cpp
diff --git a/qmake/Makefile.win32 b/qmake/Makefile.win32
index 9dda6ca1e7..272a0c09b1 100644
--- a/qmake/Makefile.win32
+++ b/qmake/Makefile.win32
@@ -88,6 +88,7 @@ QTOBJS= \
qglobal.obj \
qhash.obj \
qiodevice.obj \
+ qringbuffer.obj \
qdebug.obj \
qlist.obj \
qlinkedlist.obj \
diff --git a/qmake/doc/snippets/code/doc_src_qmake-manual.pro b/qmake/doc/snippets/code/doc_src_qmake-manual.pro
index 43de125446..6fa3ca085d 100644
--- a/qmake/doc/snippets/code/doc_src_qmake-manual.pro
+++ b/qmake/doc/snippets/code/doc_src_qmake-manual.pro
@@ -186,21 +186,6 @@ DEFINES += USE_MY_STUFF
#! [27]
-#! [28]
-myFiles.files = path\*.png
-DEPLOYMENT += myFiles
-#! [28]
-
-
-#! [29]
-myFiles.files = path\file1.ext1 path2\file2.ext1 path3\*
-myFiles.path = \some\path\on\device
-someother.files = C:\additional\files\*
-someother.path = \myFiles\path2
-DEPLOYMENT += myFiles someother
-#! [29]
-
-
#! [30]
DESTDIR = ../../lib
#! [30]
@@ -989,8 +974,12 @@ VERSION_PE_HEADER = 1.2
#! [185]
#! [186]
+RC_DEFINES += USE_MY_STUFF
+#! [186]
+
+#! [187]
win32-g++:contains(QMAKE_HOST.arch, x86_64):{
message("Host is 64bit")
...
}
-#! [186]
+#! [187]
diff --git a/qmake/doc/src/qmake-manual.qdoc b/qmake/doc/src/qmake-manual.qdoc
index a2afeaf765..d54dc9569a 100644
--- a/qmake/doc/src/qmake-manual.qdoc
+++ b/qmake/doc/src/qmake-manual.qdoc
@@ -1120,38 +1120,6 @@
Specifies a list of all directories to look in to resolve dependencies. This
variable is used when crawling through \c included files.
- \target DEPLOYMENT
- \section1 DEPLOYMENT
-
- \note This variable is used only on the Windows CE platform.
-
- Specifies which additional files will be deployed. Deployment means the
- transfer of files from the development system to the target device or
- emulator.
-
- Files can be deployed by either creating a Visual Studio project or using
- the \l {Using Qt Test remotely on Windows CE}{cetest} executable.
-
- For example, the following definition uploads all PNG images in \c path to
- the directory where the build target is deployed:
-
- \snippet code/doc_src_qmake-manual.pro 28
-
- The default deployment target path for Windows CE is
- \c{%CSIDL_PROGRAM_FILES%\target}, which usually gets expanded to
- \c{\Program Files\target}.
-
- It is also possible to specify multiple \c sources to be deployed on
- target \c paths. In addition, different variables can be used for
- deployment to different directories.
-
- For example:
-
- \snippet code/doc_src_qmake-manual.pro 29
-
- \note In Windows CE all linked Qt libraries will be deployed to the path
- specified by \c{myFiles.path}.
-
\target DEPLOYMENT_PLUGIN
\section1 DEPLOYMENT_PLUGIN
@@ -1276,6 +1244,13 @@
For more information, see \l{Installing Files}.
+ This variable is also used to specify which additional files will be
+ deployed to embedded devices.
+
+ For Windows CE, the default deployment target path is
+ \c{%CSIDL_PROGRAM_FILES%\target}, which usually gets expanded to
+ \c{\Program Files\target}.
+
\target LEXIMPLS
\section1 LEXIMPLS
@@ -1756,7 +1731,7 @@
\row \li .version_string \li Host OS version string
\endtable
- \snippet code/doc_src_qmake-manual.pro 186
+ \snippet code/doc_src_qmake-manual.pro 187
\target QMAKE_INCDIR
\section1 QMAKE_INCDIR
@@ -2229,52 +2204,10 @@
\section1 QT
- Specifies the Qt modules that are used by your project.
-
- The table below shows the options that can be used with the \c QT variable
- and the Qt modules that are associated with each of them:
+ Specifies the \l{All Modules}{Qt modules} that are used by your project. For
+ the value to add for each module, see the module documentation.
- \table
- \header \li Option \li Module Enabled
- \row \li axcontainer \li \l{Using ActiveX controls and COM in Qt}
- {QAxContainer}, which is
- part of the \l{Active Qt} framework
- \row \li axserver \li \l{Building ActiveX servers in Qt}
- {QAxServer}, which is
- part of the \l{Active Qt} framework
- \row \li concurrent \li \l{Qt Concurrent}
- \row \li core (included by default) \li \l{Qt Core}
- \row \li dbus \li \l{Qt D-Bus}
- \row \li declarative \li \l{Qt Quick 1} (deprecated)
- \row \li designer \li \l{Qt Designer}
- \row \li gui (included by default) \li \l{Qt GUI}
- \row \li help \li \l{Qt Help}
- \row \li multimedia \li \l{Qt Multimedia}
- \row \li multimediawidgets \li \l{Qt Multimedia Widgets}
- \row \li network \li \l{Qt Network}
- \row \li opengl \li \l{Qt OpenGL} (deprecated)
- \row \li printsupport \li \l{Qt Print Support}
- \row \li qml \li \l{Qt QML}
- \row \li qmltest \li \l{Qt QML Test}
- \row \li x11extras \li \l{Qt X11 Extras}
- \row \li quick \li \l{Qt Quick}
- \row \li script \li \l{Qt Script} (deprecated)
- \row \li scripttools \li \l{Qt Script Tools} (deprecated)
- \row \li sensors \li \l{Qt Sensors}
- \row \li serialport \li \l{Qt Serial Port}
- \row \li sql \li \l{Qt SQL}
- \row \li svg \li \l{Qt SVG}
- \row \li testlib \li \l{Qt Test}
- \row \li uitools \li \l{Qt UI Tools}
- \row \li webkit \li \l{Qt WebKit}
- \row \li webkitwidgets \li \l{Qt WebKit Widgets}
- \row \li widgets \li \l{Qt Widgets}
- \row \li winextras \li \l{Qt Windows Extras}
- \row \li xml \li \l{Qt XML} (deprecated)
- \row \li xmlpatterns \li \l{Qt XML Patterns}
- \endtable
-
- By default, \c QT contains both \c core and \c gui, ensuring that standard
+ By default, \c QT contains \c core and \c gui, ensuring that standard
GUI applications can be built without further configuration.
If you want to build a project \e without the \l{Qt GUI} module, you need to
@@ -2337,6 +2270,14 @@
.rc file. This is only utilized if the \l{VERSION} or \l{RC_ICONS} variable
is set and the \l{RC_FILE} and \l{RES_FILE} variables are not set.
+ \target RC_DEFINES
+ \section1 RC_DEFINES
+
+ Windows only. qmake adds the values of this variable as RC preprocessor macros
+ (/d option). If this variable is not set, the \l{DEFINES} variable is used instead.
+
+ \snippet code/doc_src_qmake-manual.pro 186
+
\target RC_ICONS
\section1 RC_ICONS
diff --git a/qmake/generators/unix/unixmake2.cpp b/qmake/generators/unix/unixmake2.cpp
index e4973157cd..05a090b23a 100644
--- a/qmake/generators/unix/unixmake2.cpp
+++ b/qmake/generators/unix/unixmake2.cpp
@@ -306,7 +306,7 @@ UnixMakefileGenerator::writeMakeParts(QTextStream &t)
t << "include " << escapeDependencyPath(*it) << endl;
/* rules */
- t << "first: all\n";
+ t << "first:" << (!project->isActiveConfig("no_default_goal_deps") ? " all" : "") << "\n";
t << "####### Implicit rules\n\n";
t << ".SUFFIXES: " << Option::obj_ext;
for(QStringList::Iterator cit = Option::c_ext.begin(); cit != Option::c_ext.end(); ++cit)
@@ -807,11 +807,10 @@ UnixMakefileGenerator::writeMakeParts(QTextStream &t)
} else {
info_plist = escapeFilePath(fileFixify(info_plist));
}
- bool isApp = (project->first("TEMPLATE") == "app");
- QString info_plist_out =
- bundle_dir + (isApp ? "Contents/Info.plist"
- : "Versions/" + project->first("QMAKE_FRAMEWORK_VERSION")
- + "/Resources/Info.plist");
+ bool isFramework = project->first("TEMPLATE") == "lib" && project->isActiveConfig("lib_bundle");
+ QString info_plist_out = bundle_dir +
+ (isFramework ? ("Versions/" + project->first("QMAKE_FRAMEWORK_VERSION") + "/Resources/Info.plist")
+ : "Contents/Info.plist");
bundledFiles << info_plist_out;
alldeps << info_plist_out;
QString destdir = info_plist_out.section(Option::dir_sep, 0, -2);
@@ -844,7 +843,7 @@ UnixMakefileGenerator::writeMakeParts(QTextStream &t)
bundleIdentifier.replace('_', '-');
commonSedArgs << "-e \"s,@BUNDLEIDENTIFIER@," << bundleIdentifier << ",g\" ";
- if (isApp) {
+ if (!isFramework) {
QString icon = fileFixify(var("ICON"));
t << "@$(DEL_FILE) " << info_plist_out << "\n\t"
<< "@sed ";
@@ -852,6 +851,7 @@ UnixMakefileGenerator::writeMakeParts(QTextStream &t)
t << arg;
t << "-e \"s,@ICON@," << icon.section(Option::dir_sep, -1) << ",g\" "
<< "-e \"s,@EXECUTABLE@," << var("QMAKE_ORIG_TARGET") << ",g\" "
+ << "-e \"s,@LIBRARY@," << var("QMAKE_ORIG_TARGET") << ",g\" "
<< "-e \"s,@TYPEINFO@,"<< (project->isEmpty("QMAKE_PKGINFO_TYPEINFO") ?
QString::fromLatin1("????") : project->first("QMAKE_PKGINFO_TYPEINFO").left(4)) << ",g\" "
<< "" << info_plist << " >" << info_plist_out << endl;
diff --git a/qmake/generators/win32/cesdkhandler.cpp b/qmake/generators/win32/cesdkhandler.cpp
index cbee1d0dbd..f8235bae27 100644
--- a/qmake/generators/win32/cesdkhandler.cpp
+++ b/qmake/generators/win32/cesdkhandler.cpp
@@ -49,6 +49,7 @@ struct PropertyContainer
QString value;
QMap<QString, PropertyContainer> properties;
};
+Q_DECLARE_TYPEINFO(PropertyContainer, Q_MOVABLE_TYPE);
CeSdkInfo::CeSdkInfo() : m_major(0) , m_minor(0)
{
@@ -60,7 +61,7 @@ CeSdkHandler::CeSdkHandler()
struct ContainsPathKey
{
- bool operator()(const QString &val)
+ bool operator()(const QString &val) const
{
return !(val.endsWith(QStringLiteral("MSBuildToolsPath"))
|| val.endsWith(QStringLiteral("MSBuildToolsRoot")));
@@ -69,8 +70,8 @@ struct ContainsPathKey
struct ValueFromKey
{
- ValueFromKey(const QSettings *settings) : settings(settings){}
- QString operator()(const QString &key)
+ explicit ValueFromKey(const QSettings *settings) : settings(settings) {}
+ QString operator()(const QString &key) const
{
return settings->value(key).toString();
}
@@ -178,13 +179,14 @@ QStringList CeSdkHandler::filterMsBuildToolPaths(const QStringList &paths) const
{
QStringList result;
foreach (const QString &path, paths) {
- QDir dir(path);
+ QDir dirVC110(path);
if (path.endsWith(QStringLiteral("bin")))
- dir.cdUp();
- if (dir.cd(QStringLiteral("Microsoft.Cpp\\v4.0\\V110\\Platforms"))
- || dir.cd(QStringLiteral("Microsoft.Cpp\\v4.0\\V120\\Platforms"))) {
- result << dir.absolutePath();
- }
+ dirVC110.cdUp();
+ QDir dirVC120 = dirVC110;
+ if (dirVC110.cd(QStringLiteral("Microsoft.Cpp\\v4.0\\V110\\Platforms")))
+ result << dirVC110.absolutePath();
+ if (dirVC120.cd(QStringLiteral("Microsoft.Cpp\\v4.0\\V120\\Platforms")))
+ result << dirVC120.absolutePath();
}
return result;
}
@@ -286,6 +288,8 @@ void CeSdkHandler::retrieveWEC2013SDKs()
currentSdk.m_minor = currentProperty.properties.value(QLatin1String("OSMinor")).value.toInt();
retrieveEnvironment(currentProperty.properties.value(QLatin1String("MSBuild Files110")).value.split(';'),
filteredToolPaths, &currentSdk);
+ retrieveEnvironment(currentProperty.properties.value(QLatin1String("MSBuild Files120")).value.split(';'),
+ filteredToolPaths, &currentSdk);
if (!currentSdk.m_include.isEmpty())
m_list.append(currentSdk);
}
diff --git a/qmake/generators/win32/mingw_make.cpp b/qmake/generators/win32/mingw_make.cpp
index c19e17bc0e..57955dc456 100644
--- a/qmake/generators/win32/mingw_make.cpp
+++ b/qmake/generators/win32/mingw_make.cpp
@@ -405,9 +405,14 @@ void MingwMakefileGenerator::writeRcFilePart(QTextStream &t)
}
if (!rc_file.isEmpty()) {
+
+ ProString defines = varGlue("RC_DEFINES", " -D", " -D", "");
+ if (defines.isEmpty())
+ defines = ProString(" $(DEFINES)");
+
t << escapeDependencyPath(var("RES_FILE")) << ": " << escapeDependencyPath(rc_file) << "\n\t"
<< var("QMAKE_RC") << " -i " << escapeFilePath(rc_file) << " -o " << fileVar("RES_FILE")
- << incPathStr << " $(DEFINES)\n\n";
+ << incPathStr << defines << "\n\n";
}
}
diff --git a/qmake/generators/win32/msvc_vcproj.cpp b/qmake/generators/win32/msvc_vcproj.cpp
index 8e08ab248e..ae4fcfd482 100644
--- a/qmake/generators/win32/msvc_vcproj.cpp
+++ b/qmake/generators/win32/msvc_vcproj.cpp
@@ -1224,7 +1224,12 @@ void VcprojGenerator::initLinkerTool()
void VcprojGenerator::initResourceTool()
{
VCConfiguration &conf = vcProject.Configuration;
- conf.resource.PreprocessorDefinitions = conf.compiler.PreprocessorDefinitions;
+
+ ProStringList rcDefines = project->values("RC_DEFINES");
+ if (rcDefines.size() > 0)
+ conf.resource.PreprocessorDefinitions = rcDefines.toQStringList();
+ else
+ conf.resource.PreprocessorDefinitions = conf.compiler.PreprocessorDefinitions;
foreach (const ProString &path, project->values("RC_INCLUDEPATH")) {
QString fixedPath = fileFixify(path.toQString());
@@ -1381,8 +1386,7 @@ void VcprojGenerator::initDeploymentTool()
}
}
- // foreach item in DEPLOYMENT
- foreach (const ProString &item, project->values("DEPLOYMENT")) {
+ foreach (const ProString &item, project->values("INSTALLS")) {
// get item.path
QString devicePath = project->first(ProKey(item + ".path")).toQString();
if (!conf.WinRT) {
diff --git a/qmake/generators/win32/winmakefile.cpp b/qmake/generators/win32/winmakefile.cpp
index 386e2865fa..0d761b08a2 100644
--- a/qmake/generators/win32/winmakefile.cpp
+++ b/qmake/generators/win32/winmakefile.cpp
@@ -755,10 +755,6 @@ void Win32MakefileGenerator::writeRcFilePart(QTextStream &t)
if(!project->values("RC_FILE").isEmpty()) {
const ProString res_file = project->first("RES_FILE");
const QString rc_file = fileFixify(project->first("RC_FILE").toQString());
- // The resource tool needs to have the same defines passed in as the compiler, since you may
- // use these defines in the .rc file itself. Also, we need to add the _DEBUG define manually
- // since the compiler defines this symbol by itself, and we use it in the automatically
- // created rc file when VERSION is define the .pro file.
const ProStringList rcIncPaths = project->values("RC_INCLUDEPATH");
QString incPathStr;
@@ -770,9 +766,20 @@ void Win32MakefileGenerator::writeRcFilePart(QTextStream &t)
incPathStr += escapeFilePath(path);
}
+ // The resource tool may use defines. This might be the same defines passed in as the
+ // compiler, since you may use these defines in the .rc file itself.
+ // As the escape syntax for the command line defines for RC is different from that for CL,
+ // we might have to set specific defines for RC.
+ ProString defines = varGlue("RC_DEFINES", " -D", " -D", "");
+ if (defines.isEmpty())
+ defines = ProString(" $(DEFINES)");
+
+ // Also, we need to add the _DEBUG define manually since the compiler defines this symbol
+ // by itself, and we use it in the automatically created rc file when VERSION is defined
+ // in the .pro file.
t << escapeDependencyPath(res_file) << ": " << escapeDependencyPath(rc_file) << "\n\t"
<< var("QMAKE_RC") << (project->isActiveConfig("debug") ? " -D_DEBUG" : "")
- << " $(DEFINES)" << incPathStr << " -fo " << escapeFilePath(res_file)
+ << defines << incPathStr << " -fo " << escapeFilePath(res_file)
<< ' ' << escapeFilePath(rc_file);
t << endl << endl;
}
diff --git a/qmake/library/qmakeevaluator.cpp b/qmake/library/qmakeevaluator.cpp
index 4cfd265591..cfb95b946c 100644
--- a/qmake/library/qmakeevaluator.cpp
+++ b/qmake/library/qmakeevaluator.cpp
@@ -188,7 +188,8 @@ void QMakeEvaluator::initStatics()
{ "QMAKE_RPATH", "QMAKE_LFLAGS_RPATH" },
{ "QMAKE_FRAMEWORKDIR", "QMAKE_FRAMEWORKPATH" },
{ "QMAKE_FRAMEWORKDIR_FLAGS", "QMAKE_FRAMEWORKPATH_FLAGS" },
- { "IN_PWD", "PWD" }
+ { "IN_PWD", "PWD" },
+ { "DEPLOYMENT", "INSTALLS" }
};
for (unsigned i = 0; i < sizeof(mapInits)/sizeof(mapInits[0]); ++i)
statics.varMap.insert(ProKey(mapInits[i].oldname), ProKey(mapInits[i].newname));
diff --git a/qmake/library/qmakeevaluator.h b/qmake/library/qmakeevaluator.h
index a60adde84e..8995d49582 100644
--- a/qmake/library/qmakeevaluator.h
+++ b/qmake/library/qmakeevaluator.h
@@ -310,6 +310,7 @@ public:
QMakeHandler *m_handler;
QMakeVfs *m_vfs;
};
+Q_DECLARE_TYPEINFO(QMakeEvaluator::Location, Q_PRIMITIVE_TYPE);
Q_DECLARE_OPERATORS_FOR_FLAGS(QMakeEvaluator::LoadFlags)
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/SurfaceD3D.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/SurfaceD3D.cpp
index 4a87488014..84515f4c6c 100644..100755
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/SurfaceD3D.cpp
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/SurfaceD3D.cpp
@@ -203,6 +203,7 @@ egl::Error SurfaceD3D::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
if (width == 0 || height == 0)
{
+ checkForOutOfDateSwapChain();
return egl::Error(EGL_SUCCESS);
}
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
index dc539cf66e..0af2cf12c6 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
@@ -154,14 +154,8 @@ EGLint SwapChain11::resetOffscreenTexture(int backbufferWidth, int backbufferHei
const bool useSharedResource = !mNativeWindow.getNativeWindow() && mRenderer->getShareHandleSupport();
D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- const int textureLength = std::max(backbufferWidth, backbufferHeight);
- offscreenTextureDesc.Width = textureLength;
- offscreenTextureDesc.Height = textureLength;
-#else
offscreenTextureDesc.Width = backbufferWidth;
offscreenTextureDesc.Height = backbufferHeight;
-#endif
offscreenTextureDesc.Format = backbufferFormatInfo.texFormat;
offscreenTextureDesc.MipLevels = 1;
offscreenTextureDesc.ArraySize = 1;
@@ -241,14 +235,8 @@ EGLint SwapChain11::resetOffscreenTexture(int backbufferWidth, int backbufferHei
if (mDepthBufferFormat != GL_NONE)
{
D3D11_TEXTURE2D_DESC depthStencilTextureDesc;
-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- const int textureLength = std::max(backbufferWidth, backbufferHeight);
- depthStencilTextureDesc.Width = textureLength;
- depthStencilTextureDesc.Height = textureLength;
-#else
depthStencilTextureDesc.Width = backbufferWidth;
depthStencilTextureDesc.Height = backbufferHeight;
-#endif
depthStencilTextureDesc.Format = depthBufferFormatInfo.texFormat;
depthStencilTextureDesc.MipLevels = 1;
depthStencilTextureDesc.ArraySize = 1;
@@ -349,7 +337,6 @@ EGLint SwapChain11::resize(EGLint backbufferWidth, EGLint backbufferHeight)
return EGL_SUCCESS;
}
-#if !defined(ANGLE_ENABLE_WINDOWS_STORE) || (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP)
// Can only call resize if we have already created our swap buffer and resources
ASSERT(mSwapChain && mBackBufferTexture && mBackBufferRTView);
@@ -392,12 +379,6 @@ EGLint SwapChain11::resize(EGLint backbufferWidth, EGLint backbufferHeight)
}
return resetOffscreenTexture(backbufferWidth, backbufferHeight);
-#else
- // Do nothing on Windows Phone apart from updating the internal buffer/width height
- mWidth = backbufferWidth;
- mHeight = backbufferHeight;
- return EGL_SUCCESS;
-#endif
}
EGLint SwapChain11::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
@@ -552,27 +533,6 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- // Create a quad in homogeneous coordinates
- float x1 = -1.0f;
- float y1 = -1.0f;
- float x2 = 1.0f;
- float y2 = 1.0f;
-
- const float dim = std::max(mWidth, mHeight);
- float u1 = 0;
- float v1 = 0;
- float u2 = float(width) / dim;
- float v2 = float(height) / dim;
-
- const NativeWindow::RotationFlags flags = mNativeWindow.rotationFlags();
- const bool rotateL = flags == NativeWindow::RotateLeft;
- const bool rotateR = flags == NativeWindow::RotateRight;
- d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, rotateL ? u2 : u1, rotateR ? v2 : v1);
- d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, rotateR ? u2 : u1, rotateL ? v1 : v2);
- d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, rotateR ? u1 : u2, rotateL ? v2 : v1);
- d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, rotateL ? u1 : u2, rotateR ? v1 : v2);
-#else
// Create a quad in homogeneous coordinates
float x1 = (x / float(mWidth)) * 2.0f - 1.0f;
float y1 = (y / float(mHeight)) * 2.0f - 1.0f;
@@ -588,7 +548,6 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v2);
d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v1);
d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v2);
-#endif
deviceContext->Unmap(mQuadVB, 0);
@@ -618,13 +577,8 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- viewport.Width = (rotateL || rotateR) ? height : width;
- viewport.Height = (rotateL || rotateR) ? width : height;
-#else
viewport.Width = mWidth;
viewport.Height = mHeight;
-#endif
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
deviceContext->RSSetViewports(1, &viewport);
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
index fa9a69c5a1..f45a077d97 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
@@ -191,25 +191,4 @@ HRESULT GetCoreWindowSizeInPixels(const ComPtr<ABI::Windows::UI::Core::ICoreWind
return result;
}
-
-static float GetLogicalDpi()
-{
- ComPtr<ABI::Windows::Graphics::Display::IDisplayPropertiesStatics> displayProperties;
- float dpi = 96.0f;
-
- if (SUCCEEDED(GetActivationFactory(HStringReference(RuntimeClass_Windows_Graphics_Display_DisplayProperties).Get(), displayProperties.GetAddressOf())))
- {
- if (SUCCEEDED(displayProperties->get_LogicalDpi(&dpi)))
- {
- return dpi;
- }
- }
- return dpi;
-}
-
-long ConvertDipsToPixels(float dips)
-{
- static const float dipsPerInch = 96.0f;
- return lround((dips * GetLogicalDpi() / dipsPerInch));
-}
}
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
index 59df9d5a6c..87cdfe6f22 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
@@ -19,7 +19,6 @@ typedef ABI::Windows::Foundation::__FITypedEventHandler_2_Windows__CGraphics__CD
namespace rx
{
-long ConvertDipsToPixels(float dips);
class CoreWindowNativeWindow : public InspectableNativeWindow, public std::enable_shared_from_this<CoreWindowNativeWindow>
{
@@ -64,8 +63,7 @@ class CoreWindowSizeChangedHandler :
ABI::Windows::Foundation::Size windowSize;
if (SUCCEEDED(sizeChangedEventArgs->get_Size(&windowSize)))
{
- SIZE windowSizeInPixels = { ConvertDipsToPixels(windowSize.Width), ConvertDipsToPixels(windowSize.Height) };
- host->setNewClientSize(windowSizeInPixels);
+ host->setNewClientSize(windowSize);
}
}
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
index 2bf48c5d94..e83f47929f 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
@@ -288,4 +288,25 @@ HRESULT GetOptionalSizePropertyValue(const ComPtr<ABI::Windows::Foundation::Coll
return result;
}
+
+static float GetLogicalDpi()
+{
+ ComPtr<ABI::Windows::Graphics::Display::IDisplayPropertiesStatics> displayProperties;
+ float dpi = 96.0f;
+
+ if (SUCCEEDED(GetActivationFactory(HStringReference(RuntimeClass_Windows_Graphics_Display_DisplayProperties).Get(), displayProperties.GetAddressOf())))
+ {
+ if (SUCCEEDED(displayProperties->get_LogicalDpi(&dpi)))
+ {
+ return dpi;
+ }
+ }
+ return dpi;
+}
+
+long ConvertDipsToPixels(float dips)
+{
+ static const float dipsPerInch = 96.0f;
+ return lround((dips * GetLogicalDpi() / dipsPerInch));
+}
}
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
index 575bdf8a58..f0534077ae 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
@@ -26,6 +26,8 @@ using namespace ABI::Windows::Foundation::Collections;
namespace rx
{
+long ConvertDipsToPixels(float dips);
+
class InspectableNativeWindow
{
public:
@@ -45,7 +47,7 @@ class InspectableNativeWindow
virtual HRESULT createSwapChain(ID3D11Device *device, DXGIFactory *factory, DXGI_FORMAT format, unsigned int width, unsigned int height, DXGISwapChain **swapChain) = 0;
virtual bool registerForSizeChangeEvents() = 0;
virtual void unregisterForSizeChangeEvents() = 0;
- virtual HRESULT scaleSwapChain(const SIZE& newSize) { return S_OK; }
+ virtual HRESULT scaleSwapChain(const Size& newSize) { return S_OK; }
bool getClientRect(RECT *rect)
{
@@ -59,11 +61,11 @@ class InspectableNativeWindow
return true;
}
- void setNewClientSize(const SIZE &newSize)
+ void setNewClientSize(const Size &newSize)
{
- if (mSupportsSwapChainResize && !mRequiresSwapChainScaling)
+ if (mSupportsSwapChainResize)
{
- mNewClientRect = { 0, 0, newSize.cx, newSize.cy };
+ mNewClientRect = { 0, 0, ConvertDipsToPixels(newSize.Width), ConvertDipsToPixels(newSize.Height) };
mClientRectChanged = true;
}
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
index 53899dbb30..0b48b54334 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
@@ -66,7 +66,7 @@ bool SwapChainPanelNativeWindow::initialize(EGLNativeWindowType window, IPropert
}
else
{
- result = GetSwapChainPanelSize(mSwapChainPanel, &mClientRect);
+ result = GetSwapChainPanelSize(mSwapChainPanel, &mClientRect, &mRequiresSwapChainScaling);
}
}
@@ -139,7 +139,6 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
ComPtr<IDXGISwapChain1> newSwapChain;
ComPtr<ISwapChainPanelNative> swapChainPanelNative;
- RECT currentPanelSize = {};
HRESULT result = factory->CreateSwapChainForComposition(device, &swapChainDesc, nullptr, newSwapChain.ReleaseAndGetAddressOf());
@@ -167,13 +166,13 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
// first reading the current size of the swapchain panel, then scaling
if (SUCCEEDED(result) && mRequiresSwapChainScaling)
{
- result = GetSwapChainPanelSize(mSwapChainPanel, &currentPanelSize);
- }
+ ComPtr<ABI::Windows::UI::Xaml::IUIElement> uiElement;
+ result = mSwapChainPanel.As(&uiElement);
+ ASSERT(SUCCEEDED(result));
- // Scale the swapchain to fit inside the contents of the panel.
- if (SUCCEEDED(result) && mRequiresSwapChainScaling)
- {
- SIZE currentSize = { currentPanelSize.right, currentPanelSize.bottom };
+ Size currentSize;
+ result = uiElement->get_RenderSize(&currentSize);
+ ASSERT(SUCCEEDED(result));
result = scaleSwapChain(currentSize);
}
@@ -190,9 +189,9 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
return result;
}
-HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const SIZE &newSize)
+HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const Size &newSize)
{
- ABI::Windows::Foundation::Size renderScale = { (float)newSize.cx/(float)mClientRect.right, (float)newSize.cy/(float)mClientRect.bottom };
+ ABI::Windows::Foundation::Size renderScale = { newSize.Width / mNewClientRect.right, newSize.Height / mNewClientRect.bottom };
// Setup a scale matrix for the swap chain
DXGI_MATRIX_3X2_F scaleMatrix = {};
scaleMatrix._11 = renderScale.Width;
@@ -208,7 +207,7 @@ HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const SIZE &newSize)
return result;
}
-HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize)
+HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize, bool *scalingActive)
{
ComPtr<ABI::Windows::UI::Xaml::IUIElement> uiElement;
ABI::Windows::Foundation::Size renderSize = { 0, 0 };
@@ -220,7 +219,14 @@ HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISw
if (SUCCEEDED(result))
{
- *windowSize = { 0, 0, lround(renderSize.Width), lround(renderSize.Height) };
+ long width = ConvertDipsToPixels(renderSize.Width);
+ long height = ConvertDipsToPixels(renderSize.Height);
+ *windowSize = { 0, 0, width, height };
+
+ if (scalingActive)
+ {
+ *scalingActive = width != renderSize.Width || height != renderSize.Height;
+ }
}
return result;
diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
index caf327d913..5debd2fd0b 100644
--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
+++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
@@ -22,7 +22,7 @@ class SwapChainPanelNativeWindow : public InspectableNativeWindow, public std::e
bool registerForSizeChangeEvents();
void unregisterForSizeChangeEvents();
HRESULT createSwapChain(ID3D11Device *device, DXGIFactory *factory, DXGI_FORMAT format, unsigned int width, unsigned int height, DXGISwapChain **swapChain);
- HRESULT scaleSwapChain(const SIZE &newSize);
+ HRESULT scaleSwapChain(const Size &newSize) override;
private:
ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> mSwapChainPanel;
@@ -62,8 +62,7 @@ class SwapChainPanelSizeChangedHandler :
HRESULT result = sizeChangedEventArgs->get_NewSize(&newSize);
if (SUCCEEDED(result))
{
- SIZE windowSize = { lround(newSize.Width), lround(newSize.Height) };
- host->setNewClientSize(windowSize);
+ host->setNewClientSize(newSize);
}
}
@@ -74,6 +73,6 @@ class SwapChainPanelSizeChangedHandler :
std::weak_ptr<InspectableNativeWindow> mHost;
};
-HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize);
+HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize, bool *scalingActive = nullptr);
}
#endif // LIBANGLE_RENDERER_D3D_D3D11_WINRT_SWAPCHAINPANELNATIVEWINDOW_H_
diff --git a/src/3rdparty/forkfd/forkfd.c b/src/3rdparty/forkfd/forkfd.c
index a61198a954..51223aef1f 100644
--- a/src/3rdparty/forkfd/forkfd.c
+++ b/src/3rdparty/forkfd/forkfd.c
@@ -25,9 +25,8 @@
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
-# define _POSIX_C_SOURCE 200809L
-# define _XOPEN_SOURCE 700
#endif
+
#include "forkfd.h"
#include <sys/types.h>
@@ -44,6 +43,7 @@
#include <unistd.h>
#ifdef __linux__
+# define HAVE_WAIT4 1
# if defined(__BIONIC__) || (defined(__GLIBC__) && (__GLIBC__ << 8) + __GLIBC_MINOR__ >= 0x207 && \
(!defined(__UCLIBC__) || ((__UCLIBC_MAJOR__ << 16) + (__UCLIBC_MINOR__ << 8) + __UCLIBC_SUBLEVEL__ > 0x921)))
# include <sys/eventfd.h>
@@ -54,6 +54,9 @@
# define HAVE_PIPE2 1
# endif
#endif
+#if defined(__FreeBSD__) && __FreeBSD__ >= 9
+# include <sys/procdesc.h>
+#endif
#if _POSIX_VERSION-0 >= 200809L || _XOPEN_VERSION-0 >= 500
# define HAVE_WAITID 1
@@ -62,6 +65,10 @@
#if defined(__FreeBSD__)
# define HAVE_PIPE2 1
#endif
+#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
+ defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
+# define HAVE_WAIT4 1
+#endif
#if defined(__APPLE__)
/* Up until OS X 10.7, waitid(P_ALL, ...) will return success, but will not
@@ -194,12 +201,33 @@ static int isChildReady(pid_t pid, siginfo_t *info)
}
#endif
+static void convertStatusToForkfdInfo(int status, struct forkfd_info *info)
+{
+ if (WIFEXITED(status)) {
+ info->code = CLD_EXITED;
+ info->status = WEXITSTATUS(status);
+ } else if (WIFSIGNALED(status)) {
+ info->code = CLD_KILLED;
+# ifdef WCOREDUMP
+ if (WCOREDUMP(status))
+ info->code = CLD_DUMPED;
+# endif
+ info->status = WTERMSIG(status);
+ }
+}
+
static int tryReaping(pid_t pid, struct pipe_payload *payload)
{
/* reap the child */
-#ifdef HAVE_WAITID
+#if defined(HAVE_WAIT4)
+ int status;
+ if (wait4(pid, &status, WNOHANG, &payload->rusage) <= 0)
+ return 0;
+ convertStatusToForkfdInfo(status, &payload->info);
+#else
+# if defined(HAVE_WAITID)
if (waitid_works) {
- // we have waitid(2), which fills in siginfo_t for us
+ /* we have waitid(2), which gets us some payload values on some systems */
siginfo_t info;
info.si_pid = 0;
int ret = waitid(P_PID, pid, &info, WEXITED | WNOHANG) == 0 && info.si_pid == pid;
@@ -208,30 +236,20 @@ static int tryReaping(pid_t pid, struct pipe_payload *payload)
payload->info.code = info.si_code;
payload->info.status = info.si_status;
-# ifdef __linux__
+# ifdef __linux__
payload->rusage.ru_utime.tv_sec = info.si_utime / CLOCKS_PER_SEC;
payload->rusage.ru_utime.tv_usec = info.si_utime % CLOCKS_PER_SEC;
payload->rusage.ru_stime.tv_sec = info.si_stime / CLOCKS_PER_SEC;
payload->rusage.ru_stime.tv_usec = info.si_stime % CLOCKS_PER_SEC;
-# endif
+# endif
return 1;
}
-#endif
+# endif // HAVE_WAITID
int status;
if (waitpid(pid, &status, WNOHANG) <= 0)
return 0; // child did not change state
-
- if (WIFEXITED(status)) {
- payload->info.code = CLD_EXITED;
- payload->info.status = WEXITSTATUS(status);
- } else if (WIFSIGNALED(status)) {
- payload->info.code = CLD_KILLED;
-# ifdef WCOREDUMP
- if (WCOREDUMP(status))
- payload->info.code = CLD_DUMPED;
-# endif
- payload->info.status = WTERMSIG(status);
- }
+ convertStatusToForkfdInfo(status, &payload->info);
+#endif // !HAVE_WAIT4
return 1;
}
@@ -491,6 +509,55 @@ static int create_pipe(int filedes[], int flags)
return ret;
}
+#if defined(FORKFD_NO_SPAWNFD) && defined(__FreeBSD__) && __FreeBSD__ >= 9
+# if __FreeBSD__ == 9
+/* PROCDESC is an optional feature in the kernel and wasn't enabled
+ * by default on FreeBSD 9. So we need to check for it at runtime. */
+static ffd_atomic_int system_has_forkfd = FFD_ATOMIC_INIT(1);
+# else
+/* On FreeBSD 10, PROCDESC was enabled by default. On v11, it's not an option
+ * anymore and can't be disabled. */
+static const int system_has_forkfd = 1;
+# endif
+
+static int system_forkfd(int flags, pid_t *ppid)
+{
+ int ret;
+ pid_t pid;
+ pid = pdfork(&ret, PD_DAEMON);
+ if (__builtin_expect(pid == -1, 0)) {
+# if __FreeBSD__ == 9
+ if (errno == ENOSYS) {
+ /* PROCDESC wasn't compiled into the kernel: don't try it again. */
+ ffd_atomic_store(&system_has_forkfd, 0, FFD_ATOMIC_RELAXED);
+ }
+# endif
+ return -1;
+ }
+ if (pid == 0) {
+ /* child process */
+ return FFD_CHILD_PROCESS;
+ }
+
+ /* parent process */
+ if (flags & FFD_CLOEXEC)
+ fcntl(ret, F_SETFD, FD_CLOEXEC);
+ if (flags & FFD_NONBLOCK)
+ fcntl(ret, F_SETFL, fcntl(ret, F_GETFL) | O_NONBLOCK);
+ if (ppid)
+ *ppid = pid;
+ return ret;
+}
+#else
+static const int system_has_forkfd = 0;
+static int system_forkfd(int flags, pid_t *ppid)
+{
+ (void)flags;
+ (void)ppid;
+ return -1;
+}
+#endif
+
#ifndef FORKFD_NO_FORKFD
/**
* @brief forkfd returns a file descriptor representing a child process
@@ -538,6 +605,12 @@ int forkfd(int flags, pid_t *ppid)
int efd;
#endif
+ if (system_has_forkfd) {
+ ret = system_forkfd(flags, ppid);
+ if (system_has_forkfd)
+ return ret;
+ }
+
(void) pthread_once(&forkfd_initialization, forkfd_initialize);
info = allocateInfo(&header);
@@ -661,6 +734,8 @@ int spawnfd(int flags, pid_t *ppid, const char *path, const posix_spawn_file_act
/* we can only do work if we have a way to start the child in stopped mode;
* otherwise, we have a major race condition. */
+ assert(!system_has_forkfd);
+
(void) pthread_once(&forkfd_initialization, forkfd_initialize);
info = allocateInfo(&header);
@@ -717,6 +792,26 @@ int forkfd_wait(int ffd, forkfd_info *info, struct rusage *rusage)
struct pipe_payload payload;
int ret;
+ if (system_has_forkfd) {
+#if defined(__FreeBSD__) && __FreeBSD__ >= 9
+ pid_t pid;
+ int status;
+ int options = WEXITED;
+
+ ret = pdgetpid(ffd, &pid);
+ if (ret == -1)
+ return ret;
+ ret = fcntl(ffd, F_GETFL);
+ if (ret == -1)
+ return ret;
+ options |= (ret & O_NONBLOCK) ? WNOHANG : 0;
+ ret = wait4(pid, &status, options, rusage);
+ if (ret != -1 && info)
+ convertStatusToForkfdInfo(status, info);
+ return ret == -1 ? -1 : 0;
+#endif
+ }
+
ret = read(ffd, &payload, sizeof(payload));
if (ret == -1)
return ret; /* pass errno, probably EINTR, EBADF or EWOULDBLOCK */
diff --git a/src/3rdparty/harfbuzz-ng/src/hb-private.hh b/src/3rdparty/harfbuzz-ng/src/hb-private.hh
index 06b24a80f8..06d7f228a7 100644
--- a/src/3rdparty/harfbuzz-ng/src/hb-private.hh
+++ b/src/3rdparty/harfbuzz-ng/src/hb-private.hh
@@ -121,16 +121,17 @@
# if defined(_WIN32_WCE)
/* Some things not defined on Windows CE. */
+# define strdup _strdup
# define getenv(Name) NULL
-# define setlocale(Category, Locale) "C"
+# if _WIN32_WCE < 0x800
+# define setlocale(Category, Locale) "C"
static int errno = 0; /* Use something better? */
+# endif
# elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
# define getenv(Name) NULL
# endif
-# if (defined(__WIN32__) && !defined(__WINE__)) || defined(_MSC_VER)
+# if defined(_MSC_VER) && _MSC_VER < 1900
# define snprintf _snprintf
- /* Windows CE only has _strdup, while rest of Windows has both. */
-# define strdup _strdup
# endif
#endif
diff --git a/src/3rdparty/sha3/KeccakF-1600-32-rvk.macros b/src/3rdparty/sha3/KeccakF-1600-32-rvk.macros
index c0c9029873..c0c9029873 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-32-rvk.macros
+++ b/src/3rdparty/sha3/KeccakF-1600-32-rvk.macros
diff --git a/src/3rdparty/sha3/KeccakF-1600-32.macros b/src/3rdparty/sha3/KeccakF-1600-32.macros
index 9ade600067..9ade600067 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-32.macros
+++ b/src/3rdparty/sha3/KeccakF-1600-32.macros
diff --git a/src/3rdparty/sha3/KeccakF-1600-64.macros b/src/3rdparty/sha3/KeccakF-1600-64.macros
index 0c20bca40f..0c20bca40f 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-64.macros
+++ b/src/3rdparty/sha3/KeccakF-1600-64.macros
diff --git a/src/3rdparty/sha3/KeccakF-1600-int-set.h b/src/3rdparty/sha3/KeccakF-1600-int-set.h
index 0ed1d802e3..0ed1d802e3 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-int-set.h
+++ b/src/3rdparty/sha3/KeccakF-1600-int-set.h
diff --git a/src/3rdparty/sha3/KeccakF-1600-interface.h b/src/3rdparty/sha3/KeccakF-1600-interface.h
index ce2710eeb2..ce2710eeb2 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-interface.h
+++ b/src/3rdparty/sha3/KeccakF-1600-interface.h
diff --git a/src/3rdparty/sha3/KeccakF-1600-opt32-settings.h b/src/3rdparty/sha3/KeccakF-1600-opt32-settings.h
index b135918ca9..b135918ca9 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-opt32-settings.h
+++ b/src/3rdparty/sha3/KeccakF-1600-opt32-settings.h
diff --git a/src/3rdparty/sha3/KeccakF-1600-opt32.c b/src/3rdparty/sha3/KeccakF-1600-opt32.c
index 4e32dca9cb..4e32dca9cb 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-opt32.c
+++ b/src/3rdparty/sha3/KeccakF-1600-opt32.c
diff --git a/src/3rdparty/sha3/KeccakF-1600-opt64-settings.h b/src/3rdparty/sha3/KeccakF-1600-opt64-settings.h
index 8f16ada636..8f16ada636 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-opt64-settings.h
+++ b/src/3rdparty/sha3/KeccakF-1600-opt64-settings.h
diff --git a/src/3rdparty/sha3/KeccakF-1600-unrolling.macros b/src/3rdparty/sha3/KeccakF-1600-unrolling.macros
index 83c694ca48..83c694ca48 100755..100644
--- a/src/3rdparty/sha3/KeccakF-1600-unrolling.macros
+++ b/src/3rdparty/sha3/KeccakF-1600-unrolling.macros
diff --git a/src/3rdparty/sha3/KeccakNISTInterface.c b/src/3rdparty/sha3/KeccakNISTInterface.c
index e530a11db5..e530a11db5 100755..100644
--- a/src/3rdparty/sha3/KeccakNISTInterface.c
+++ b/src/3rdparty/sha3/KeccakNISTInterface.c
diff --git a/src/3rdparty/sha3/KeccakNISTInterface.h b/src/3rdparty/sha3/KeccakNISTInterface.h
index cd85f24aa7..cd85f24aa7 100755..100644
--- a/src/3rdparty/sha3/KeccakNISTInterface.h
+++ b/src/3rdparty/sha3/KeccakNISTInterface.h
diff --git a/src/3rdparty/sha3/KeccakSponge.c b/src/3rdparty/sha3/KeccakSponge.c
index 6f3da95dbb..6f3da95dbb 100755..100644
--- a/src/3rdparty/sha3/KeccakSponge.c
+++ b/src/3rdparty/sha3/KeccakSponge.c
diff --git a/src/3rdparty/sha3/KeccakSponge.h b/src/3rdparty/sha3/KeccakSponge.h
index 8bb11a8a1d..8bb11a8a1d 100755..100644
--- a/src/3rdparty/sha3/KeccakSponge.h
+++ b/src/3rdparty/sha3/KeccakSponge.h
diff --git a/src/3rdparty/sha3/brg_endian.h b/src/3rdparty/sha3/brg_endian.h
index 7226eb3bec..7226eb3bec 100755..100644
--- a/src/3rdparty/sha3/brg_endian.h
+++ b/src/3rdparty/sha3/brg_endian.h
diff --git a/src/3rdparty/sqlite/sqlite3.c b/src/3rdparty/sqlite/sqlite3.c
index ff78701615..06f6d154f1 100644
--- a/src/3rdparty/sqlite/sqlite3.c
+++ b/src/3rdparty/sqlite/sqlite3.c
@@ -35209,6 +35209,7 @@ static void winLogIoerr(int nRetry, int lineno){
** create a substitute.
*/
/* #include <time.h> */
+# if _WIN32_WCE < 0x800
struct tm *__cdecl localtime(const time_t *t)
{
static struct tm y;
@@ -35230,6 +35231,7 @@ struct tm *__cdecl localtime(const time_t *t)
y.tm_sec = pTm.wSecond;
return &y;
}
+# endif
#endif
#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
diff --git a/src/3rdparty/zlib/0001-Fix-WEC2013-build-of-zlib.patch b/src/3rdparty/zlib/0001-Fix-WEC2013-build-of-zlib.patch
new file mode 100644
index 0000000000..ef6fb33eed
--- /dev/null
+++ b/src/3rdparty/zlib/0001-Fix-WEC2013-build-of-zlib.patch
@@ -0,0 +1,26 @@
+From f2652cfd83f34ec3e70a936e5ea9f8623b66bd95 Mon Sep 17 00:00:00 2001
+From: Bjoern Breitmeyer <bjoern.breitmeyer@kdab.com>
+Date: Fri, 27 Mar 2015 15:46:59 +0100
+Subject: [PATCH] Fix WEC2013 build of zlib.
+
+Change-Id: I4d1908f1175ed39e2df8717fb0b5a17befe88744
+---
+ src/3rdparty/zlib/zutil.h | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/3rdparty/zlib/zutil.h b/src/3rdparty/zlib/zutil.h
+index 8e535ac..4d367a9 100644
+--- a/src/3rdparty/zlib/zutil.h
++++ b/src/3rdparty/zlib/zutil.h
+@@ -143,7 +143,7 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
+ #endif
+
+ #if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
+-# if defined(_WIN32_WCE)
++# if defined(_WIN32_WCE) && _WIN32_WCE < 0x800
+ # define fdopen(fd,mode) NULL /* No fdopen() */
+ # ifndef _PTRDIFF_T_DEFINED
+ typedef int ptrdiff_t;
+--
+1.8.1.msysgit.1
+
diff --git a/src/3rdparty/zlib/zutil.h b/src/3rdparty/zlib/zutil.h
index 8e535acf40..4d367a92db 100644
--- a/src/3rdparty/zlib/zutil.h
+++ b/src/3rdparty/zlib/zutil.h
@@ -143,7 +143,7 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
#endif
#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
-# if defined(_WIN32_WCE)
+# if defined(_WIN32_WCE) && _WIN32_WCE < 0x800
# define fdopen(fd,mode) NULL /* No fdopen() */
# ifndef _PTRDIFF_T_DEFINED
typedef int ptrdiff_t;
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
index ba3ecfecd6..ee196f1aef 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
@@ -203,6 +203,16 @@ public class QtActivityDelegate
private final int ImhUrlCharactersOnly = 0x400000;
private final int ImhLatinOnly = 0x800000;
+ // enter key type - must be kept in sync with QTDIR/src/corelib/global/qnamespace.h
+ private final int EnterKeyDefault = 0;
+ private final int EnterKeyReturn = 1;
+ private final int EnterKeyDone = 2;
+ private final int EnterKeyGo = 3;
+ private final int EnterKeySend = 4;
+ private final int EnterKeySearch = 5;
+ private final int EnterKeyNext = 6;
+ private final int EnterKeyPrevious = 7;
+
// application state
private final int ApplicationSuspended = 0x0;
private final int ApplicationHidden = 0x1;
@@ -239,7 +249,7 @@ public class QtActivityDelegate
}, 5);
}
- public void showSoftwareKeyboard(int x, int y, int width, int height, int inputHints)
+ public void showSoftwareKeyboard(int x, int y, int width, int height, int inputHints, int enterKeyType)
{
if (m_imm == null)
return;
@@ -252,7 +262,31 @@ public class QtActivityDelegate
m_activity.getWindow().setSoftInputMode(m_softInputMode);
int initialCapsMode = 0;
+
int imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_DONE;
+
+ switch (enterKeyType) {
+ case EnterKeyReturn:
+ imeOptions = android.view.inputmethod.EditorInfo.IME_FLAG_NO_ENTER_ACTION;
+ break;
+ case EnterKeyGo:
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_GO;
+ break;
+ case EnterKeySend:
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_SEND;
+ break;
+ case EnterKeySearch:
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH;
+ break;
+ case EnterKeyNext:
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_NEXT;
+ break;
+ case EnterKeyPrevious:
+ if (Build.VERSION.SDK_INT > 10)
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_PREVIOUS;
+ break;
+ }
+
int inputType = android.text.InputType.TYPE_CLASS_TEXT;
if ((inputHints & (ImhPreferNumbers | ImhDigitsOnly | ImhFormattedNumbersOnly)) != 0) {
@@ -278,7 +312,9 @@ public class QtActivityDelegate
if ((inputHints & (ImhEmailCharactersOnly | ImhUrlCharactersOnly)) != 0) {
if ((inputHints & ImhUrlCharactersOnly) != 0) {
inputType |= android.text.InputType.TYPE_TEXT_VARIATION_URI;
- imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_GO;
+
+ if (enterKeyType == 0) // not explicitly overridden
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_GO;
} else if ((inputHints & ImhEmailCharactersOnly) != 0) {
inputType |= android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
}
@@ -305,7 +341,7 @@ public class QtActivityDelegate
}
}
- if ((inputHints & ImhMultiLine) != 0)
+ if (enterKeyType == 0 && (inputHints & ImhMultiLine) != 0)
imeOptions = android.view.inputmethod.EditorInfo.IME_FLAG_NO_ENTER_ACTION;
m_editText.setInitialCapsMode(initialCapsMode);
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
index 040eba5e42..a1e7dac4d4 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
@@ -43,6 +43,7 @@ import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.ClipboardManager;
+import android.os.Build;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
@@ -301,32 +302,49 @@ public class QtNative
static public void sendTouchEvent(MotionEvent event, int id)
{
- //@ANDROID-5
- touchBegin(id);
- for (int i=0;i<event.getPointerCount();i++) {
- touchAdd(id,
- event.getPointerId(i),
- getAction(i, event),
- i == 0,
- (int)event.getX(i),
- (int)event.getY(i),
- event.getSize(i),
- event.getPressure(i));
- }
+ int pointerType = 0;
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- touchEnd(id,0);
+ if (Build.VERSION.SDK_INT >= 14) {
+ switch (event.getToolType(0)) {
+ case MotionEvent.TOOL_TYPE_STYLUS:
+ pointerType = 1; // QTabletEvent::Pen
break;
-
- case MotionEvent.ACTION_UP:
- touchEnd(id,2);
+ case MotionEvent.TOOL_TYPE_ERASER:
+ pointerType = 3; // QTabletEvent::Eraser
break;
+ // TODO TOOL_TYPE_MOUSE
+ }
+ }
- default:
- touchEnd(id,1);
+ if (pointerType != 0) {
+ tabletEvent(id, event.getDeviceId(), event.getEventTime(), event.getAction(), pointerType,
+ event.getButtonState(), event.getX(), event.getY(), event.getPressure());
+ } else {
+ touchBegin(id);
+ for (int i = 0; i < event.getPointerCount(); ++i) {
+ touchAdd(id,
+ event.getPointerId(i),
+ getAction(i, event),
+ i == 0,
+ (int)event.getX(i),
+ (int)event.getY(i),
+ event.getSize(i),
+ event.getPressure(i));
+ }
+
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ touchEnd(id, 0);
+ break;
+
+ case MotionEvent.ACTION_UP:
+ touchEnd(id, 2);
+ break;
+
+ default:
+ touchEnd(id, 1);
+ }
}
- //@ANDROID-5
}
static public void sendTrackballEvent(MotionEvent event, int id)
@@ -371,12 +389,13 @@ public class QtNative
final int y,
final int width,
final int height,
- final int inputHints )
+ final int inputHints,
+ final int enterKeyType)
{
runAction(new Runnable() {
@Override
public void run() {
- m_activityDelegate.showSoftwareKeyboard(x, y, width, height, inputHints);
+ m_activityDelegate.showSoftwareKeyboard(x, y, width, height, inputHints, enterKeyType);
}
});
}
@@ -602,6 +621,10 @@ public class QtNative
public static native void longPress(int winId, int x, int y);
// pointer methods
+ // tablet methods
+ public static native void tabletEvent(int winId, int deviceId, long time, int action, int pointerType, int buttonState, float x, float y, float pressure);
+ // tablet methods
+
// keyboard methods
public static native void keyDown(int key, int unicode, int modifier, boolean autoRepeat);
public static native void keyUp(int key, int unicode, int modifier, boolean autoRepeat);
diff --git a/src/angle/patches/0008-ANGLE-Use-pixel-sizes-in-the-XAML-swap-chain.patch b/src/angle/patches/0008-ANGLE-Use-pixel-sizes-in-the-XAML-swap-chain.patch
new file mode 100644
index 0000000000..cf383d7106
--- /dev/null
+++ b/src/angle/patches/0008-ANGLE-Use-pixel-sizes-in-the-XAML-swap-chain.patch
@@ -0,0 +1,361 @@
+From 333bb863e5c3e04fcc513e4750208fa3742be7a1 Mon Sep 17 00:00:00 2001
+From: Andrew Knight <andrew.knight@intopalo.com>
+Date: Sat, 8 Aug 2015 21:42:03 +0300
+Subject: [PATCH 2/4] ANGLE: Use pixel sizes in the XAML swap chain
+
+This is necessary for Qt applications, as they render to GL in physical
+pixels. This is consistent with the CoreWindow swap chain behavior.
+
+This includes a partial revert of "ANGLE: Improve Windows Phone Support"
+as the modifications to SwapChain11 are incompatible with the XAML swap
+chain.
+
+This change only affects Windows Runtime targets.
+
+Change-Id: I401ae81028a9dfdb9da37f51c60844467c476f76
+---
+ .../libANGLE/renderer/d3d/d3d11/SwapChain11.cpp | 46 ----------------------
+ .../d3d/d3d11/winrt/CoreWindowNativeWindow.cpp | 21 ----------
+ .../d3d/d3d11/winrt/CoreWindowNativeWindow.h | 4 +-
+ .../d3d/d3d11/winrt/InspectableNativeWindow.cpp | 21 ++++++++++
+ .../d3d/d3d11/winrt/InspectableNativeWindow.h | 10 +++--
+ .../d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp | 30 ++++++++------
+ .../d3d/d3d11/winrt/SwapChainPanelNativeWindow.h | 7 ++--
+ 7 files changed, 49 insertions(+), 90 deletions(-)
+
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
+index dc539cf..0af2cf1 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/SwapChain11.cpp
+@@ -154,14 +154,8 @@ EGLint SwapChain11::resetOffscreenTexture(int backbufferWidth, int backbufferHei
+ const bool useSharedResource = !mNativeWindow.getNativeWindow() && mRenderer->getShareHandleSupport();
+
+ D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
+-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
+- const int textureLength = std::max(backbufferWidth, backbufferHeight);
+- offscreenTextureDesc.Width = textureLength;
+- offscreenTextureDesc.Height = textureLength;
+-#else
+ offscreenTextureDesc.Width = backbufferWidth;
+ offscreenTextureDesc.Height = backbufferHeight;
+-#endif
+ offscreenTextureDesc.Format = backbufferFormatInfo.texFormat;
+ offscreenTextureDesc.MipLevels = 1;
+ offscreenTextureDesc.ArraySize = 1;
+@@ -241,14 +235,8 @@ EGLint SwapChain11::resetOffscreenTexture(int backbufferWidth, int backbufferHei
+ if (mDepthBufferFormat != GL_NONE)
+ {
+ D3D11_TEXTURE2D_DESC depthStencilTextureDesc;
+-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
+- const int textureLength = std::max(backbufferWidth, backbufferHeight);
+- depthStencilTextureDesc.Width = textureLength;
+- depthStencilTextureDesc.Height = textureLength;
+-#else
+ depthStencilTextureDesc.Width = backbufferWidth;
+ depthStencilTextureDesc.Height = backbufferHeight;
+-#endif
+ depthStencilTextureDesc.Format = depthBufferFormatInfo.texFormat;
+ depthStencilTextureDesc.MipLevels = 1;
+ depthStencilTextureDesc.ArraySize = 1;
+@@ -349,7 +337,6 @@ EGLint SwapChain11::resize(EGLint backbufferWidth, EGLint backbufferHeight)
+ return EGL_SUCCESS;
+ }
+
+-#if !defined(ANGLE_ENABLE_WINDOWS_STORE) || (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP)
+ // Can only call resize if we have already created our swap buffer and resources
+ ASSERT(mSwapChain && mBackBufferTexture && mBackBufferRTView);
+
+@@ -392,12 +379,6 @@ EGLint SwapChain11::resize(EGLint backbufferWidth, EGLint backbufferHeight)
+ }
+
+ return resetOffscreenTexture(backbufferWidth, backbufferHeight);
+-#else
+- // Do nothing on Windows Phone apart from updating the internal buffer/width height
+- mWidth = backbufferWidth;
+- mHeight = backbufferHeight;
+- return EGL_SUCCESS;
+-#endif
+ }
+
+ EGLint SwapChain11::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
+@@ -552,27 +533,6 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
+
+ d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
+
+-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
+- // Create a quad in homogeneous coordinates
+- float x1 = -1.0f;
+- float y1 = -1.0f;
+- float x2 = 1.0f;
+- float y2 = 1.0f;
+-
+- const float dim = std::max(mWidth, mHeight);
+- float u1 = 0;
+- float v1 = 0;
+- float u2 = float(width) / dim;
+- float v2 = float(height) / dim;
+-
+- const NativeWindow::RotationFlags flags = mNativeWindow.rotationFlags();
+- const bool rotateL = flags == NativeWindow::RotateLeft;
+- const bool rotateR = flags == NativeWindow::RotateRight;
+- d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, rotateL ? u2 : u1, rotateR ? v2 : v1);
+- d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, rotateR ? u2 : u1, rotateL ? v1 : v2);
+- d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, rotateR ? u1 : u2, rotateL ? v2 : v1);
+- d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, rotateL ? u1 : u2, rotateR ? v1 : v2);
+-#else
+ // Create a quad in homogeneous coordinates
+ float x1 = (x / float(mWidth)) * 2.0f - 1.0f;
+ float y1 = (y / float(mHeight)) * 2.0f - 1.0f;
+@@ -588,7 +548,6 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
+ d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v2);
+ d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v1);
+ d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v2);
+-#endif
+
+ deviceContext->Unmap(mQuadVB, 0);
+
+@@ -618,13 +577,8 @@ EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = 0;
+ viewport.TopLeftY = 0;
+-#if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
+- viewport.Width = (rotateL || rotateR) ? height : width;
+- viewport.Height = (rotateL || rotateR) ? width : height;
+-#else
+ viewport.Width = mWidth;
+ viewport.Height = mHeight;
+-#endif
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+ deviceContext->RSSetViewports(1, &viewport);
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
+index fa9a69c..f45a077 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.cpp
+@@ -191,25 +191,4 @@ HRESULT GetCoreWindowSizeInPixels(const ComPtr<ABI::Windows::UI::Core::ICoreWind
+
+ return result;
+ }
+-
+-static float GetLogicalDpi()
+-{
+- ComPtr<ABI::Windows::Graphics::Display::IDisplayPropertiesStatics> displayProperties;
+- float dpi = 96.0f;
+-
+- if (SUCCEEDED(GetActivationFactory(HStringReference(RuntimeClass_Windows_Graphics_Display_DisplayProperties).Get(), displayProperties.GetAddressOf())))
+- {
+- if (SUCCEEDED(displayProperties->get_LogicalDpi(&dpi)))
+- {
+- return dpi;
+- }
+- }
+- return dpi;
+-}
+-
+-long ConvertDipsToPixels(float dips)
+-{
+- static const float dipsPerInch = 96.0f;
+- return lround((dips * GetLogicalDpi() / dipsPerInch));
+-}
+ }
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
+index 59df9d5..87cdfe6 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/CoreWindowNativeWindow.h
+@@ -19,7 +19,6 @@ typedef ABI::Windows::Foundation::__FITypedEventHandler_2_Windows__CGraphics__CD
+
+ namespace rx
+ {
+-long ConvertDipsToPixels(float dips);
+
+ class CoreWindowNativeWindow : public InspectableNativeWindow, public std::enable_shared_from_this<CoreWindowNativeWindow>
+ {
+@@ -64,8 +63,7 @@ class CoreWindowSizeChangedHandler :
+ ABI::Windows::Foundation::Size windowSize;
+ if (SUCCEEDED(sizeChangedEventArgs->get_Size(&windowSize)))
+ {
+- SIZE windowSizeInPixels = { ConvertDipsToPixels(windowSize.Width), ConvertDipsToPixels(windowSize.Height) };
+- host->setNewClientSize(windowSizeInPixels);
++ host->setNewClientSize(windowSize);
+ }
+ }
+
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
+index 2bf48c5..e83f479 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.cpp
+@@ -288,4 +288,25 @@ HRESULT GetOptionalSizePropertyValue(const ComPtr<ABI::Windows::Foundation::Coll
+
+ return result;
+ }
++
++static float GetLogicalDpi()
++{
++ ComPtr<ABI::Windows::Graphics::Display::IDisplayPropertiesStatics> displayProperties;
++ float dpi = 96.0f;
++
++ if (SUCCEEDED(GetActivationFactory(HStringReference(RuntimeClass_Windows_Graphics_Display_DisplayProperties).Get(), displayProperties.GetAddressOf())))
++ {
++ if (SUCCEEDED(displayProperties->get_LogicalDpi(&dpi)))
++ {
++ return dpi;
++ }
++ }
++ return dpi;
++}
++
++long ConvertDipsToPixels(float dips)
++{
++ static const float dipsPerInch = 96.0f;
++ return lround((dips * GetLogicalDpi() / dipsPerInch));
++}
+ }
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
+index 575bdf8..f053407 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/InspectableNativeWindow.h
+@@ -26,6 +26,8 @@ using namespace ABI::Windows::Foundation::Collections;
+
+ namespace rx
+ {
++long ConvertDipsToPixels(float dips);
++
+ class InspectableNativeWindow
+ {
+ public:
+@@ -45,7 +47,7 @@ class InspectableNativeWindow
+ virtual HRESULT createSwapChain(ID3D11Device *device, DXGIFactory *factory, DXGI_FORMAT format, unsigned int width, unsigned int height, DXGISwapChain **swapChain) = 0;
+ virtual bool registerForSizeChangeEvents() = 0;
+ virtual void unregisterForSizeChangeEvents() = 0;
+- virtual HRESULT scaleSwapChain(const SIZE& newSize) { return S_OK; }
++ virtual HRESULT scaleSwapChain(const Size& newSize) { return S_OK; }
+
+ bool getClientRect(RECT *rect)
+ {
+@@ -59,11 +61,11 @@ class InspectableNativeWindow
+ return true;
+ }
+
+- void setNewClientSize(const SIZE &newSize)
++ void setNewClientSize(const Size &newSize)
+ {
+- if (mSupportsSwapChainResize && !mRequiresSwapChainScaling)
++ if (mSupportsSwapChainResize)
+ {
+- mNewClientRect = { 0, 0, newSize.cx, newSize.cy };
++ mNewClientRect = { 0, 0, ConvertDipsToPixels(newSize.Width), ConvertDipsToPixels(newSize.Height) };
+ mClientRectChanged = true;
+ }
+
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
+index 53899db..0b48b54 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.cpp
+@@ -66,7 +66,7 @@ bool SwapChainPanelNativeWindow::initialize(EGLNativeWindowType window, IPropert
+ }
+ else
+ {
+- result = GetSwapChainPanelSize(mSwapChainPanel, &mClientRect);
++ result = GetSwapChainPanelSize(mSwapChainPanel, &mClientRect, &mRequiresSwapChainScaling);
+ }
+ }
+
+@@ -139,7 +139,6 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
+
+ ComPtr<IDXGISwapChain1> newSwapChain;
+ ComPtr<ISwapChainPanelNative> swapChainPanelNative;
+- RECT currentPanelSize = {};
+
+ HRESULT result = factory->CreateSwapChainForComposition(device, &swapChainDesc, nullptr, newSwapChain.ReleaseAndGetAddressOf());
+
+@@ -167,13 +166,13 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
+ // first reading the current size of the swapchain panel, then scaling
+ if (SUCCEEDED(result) && mRequiresSwapChainScaling)
+ {
+- result = GetSwapChainPanelSize(mSwapChainPanel, &currentPanelSize);
+- }
++ ComPtr<ABI::Windows::UI::Xaml::IUIElement> uiElement;
++ result = mSwapChainPanel.As(&uiElement);
++ ASSERT(SUCCEEDED(result));
+
+- // Scale the swapchain to fit inside the contents of the panel.
+- if (SUCCEEDED(result) && mRequiresSwapChainScaling)
+- {
+- SIZE currentSize = { currentPanelSize.right, currentPanelSize.bottom };
++ Size currentSize;
++ result = uiElement->get_RenderSize(&currentSize);
++ ASSERT(SUCCEEDED(result));
+ result = scaleSwapChain(currentSize);
+ }
+
+@@ -190,9 +189,9 @@ HRESULT SwapChainPanelNativeWindow::createSwapChain(ID3D11Device *device, DXGIFa
+ return result;
+ }
+
+-HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const SIZE &newSize)
++HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const Size &newSize)
+ {
+- ABI::Windows::Foundation::Size renderScale = { (float)newSize.cx/(float)mClientRect.right, (float)newSize.cy/(float)mClientRect.bottom };
++ ABI::Windows::Foundation::Size renderScale = { newSize.Width / mNewClientRect.right, newSize.Height / mNewClientRect.bottom };
+ // Setup a scale matrix for the swap chain
+ DXGI_MATRIX_3X2_F scaleMatrix = {};
+ scaleMatrix._11 = renderScale.Width;
+@@ -208,7 +207,7 @@ HRESULT SwapChainPanelNativeWindow::scaleSwapChain(const SIZE &newSize)
+ return result;
+ }
+
+-HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize)
++HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize, bool *scalingActive)
+ {
+ ComPtr<ABI::Windows::UI::Xaml::IUIElement> uiElement;
+ ABI::Windows::Foundation::Size renderSize = { 0, 0 };
+@@ -220,7 +219,14 @@ HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISw
+
+ if (SUCCEEDED(result))
+ {
+- *windowSize = { 0, 0, lround(renderSize.Width), lround(renderSize.Height) };
++ long width = ConvertDipsToPixels(renderSize.Width);
++ long height = ConvertDipsToPixels(renderSize.Height);
++ *windowSize = { 0, 0, width, height };
++
++ if (scalingActive)
++ {
++ *scalingActive = width != renderSize.Width || height != renderSize.Height;
++ }
+ }
+
+ return result;
+diff --git a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
+index caf327d..5debd2f 100644
+--- a/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
++++ b/src/3rdparty/angle/src/libANGLE/renderer/d3d/d3d11/winrt/SwapChainPanelNativeWindow.h
+@@ -22,7 +22,7 @@ class SwapChainPanelNativeWindow : public InspectableNativeWindow, public std::e
+ bool registerForSizeChangeEvents();
+ void unregisterForSizeChangeEvents();
+ HRESULT createSwapChain(ID3D11Device *device, DXGIFactory *factory, DXGI_FORMAT format, unsigned int width, unsigned int height, DXGISwapChain **swapChain);
+- HRESULT scaleSwapChain(const SIZE &newSize);
++ HRESULT scaleSwapChain(const Size &newSize) override;
+
+ private:
+ ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> mSwapChainPanel;
+@@ -62,8 +62,7 @@ class SwapChainPanelSizeChangedHandler :
+ HRESULT result = sizeChangedEventArgs->get_NewSize(&newSize);
+ if (SUCCEEDED(result))
+ {
+- SIZE windowSize = { lround(newSize.Width), lround(newSize.Height) };
+- host->setNewClientSize(windowSize);
++ host->setNewClientSize(newSize);
+ }
+ }
+
+@@ -74,6 +73,6 @@ class SwapChainPanelSizeChangedHandler :
+ std::weak_ptr<InspectableNativeWindow> mHost;
+ };
+
+-HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize);
++HRESULT GetSwapChainPanelSize(const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, RECT *windowSize, bool *scalingActive = nullptr);
+ }
+ #endif // LIBANGLE_RENDERER_D3D_D3D11_WINRT_SWAPCHAINPANELNATIVEWINDOW_H_
+--
+1.9.5.msysgit.1
+
diff --git a/src/angle/src/common/common.pri b/src/angle/src/common/common.pri
index 735c841ad8..57f92f1089 100644
--- a/src/angle/src/common/common.pri
+++ b/src/angle/src/common/common.pri
@@ -7,6 +7,8 @@ INCLUDEPATH += \
LIBS_PRIVATE = $$QMAKE_LIBS_CORE $$QMAKE_LIBS_GUI
+TR_EXCLUDE += $$ANGLE_DIR/src/*
+
lib_replace.match = $$[QT_INSTALL_LIBS/get]
lib_replace.replace = \$\$\$\$[QT_INSTALL_LIBS]
lib_replace.CONFIG = path
diff --git a/src/corelib/animation/qabstractanimation.h b/src/corelib/animation/qabstractanimation.h
index da78341d90..7085a9fc5e 100644
--- a/src/corelib/animation/qabstractanimation.h
+++ b/src/corelib/animation/qabstractanimation.h
@@ -76,7 +76,7 @@ public:
DeleteWhenStopped
};
- QAbstractAnimation(QObject *parent = 0);
+ QAbstractAnimation(QObject *parent = Q_NULLPTR);
virtual ~QAbstractAnimation();
State state() const;
@@ -111,7 +111,7 @@ public Q_SLOTS:
void setCurrentTime(int msecs);
protected:
- QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent = 0);
+ QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent = Q_NULLPTR);
bool event(QEvent *event) Q_DECL_OVERRIDE;
virtual void updateCurrentTime(int currentTime) = 0;
@@ -130,7 +130,7 @@ class Q_CORE_EXPORT QAnimationDriver : public QObject
Q_DECLARE_PRIVATE(QAnimationDriver)
public:
- QAnimationDriver(QObject *parent = 0);
+ QAnimationDriver(QObject *parent = Q_NULLPTR);
~QAnimationDriver();
virtual void advance();
@@ -156,7 +156,7 @@ protected:
virtual void start();
virtual void stop();
- QAnimationDriver(QAnimationDriverPrivate &dd, QObject *parent = 0);
+ QAnimationDriver(QAnimationDriverPrivate &dd, QObject *parent = Q_NULLPTR);
private:
friend class QUnifiedTimer;
diff --git a/src/corelib/animation/qanimationgroup.h b/src/corelib/animation/qanimationgroup.h
index 9b180b1704..b668b503b4 100644
--- a/src/corelib/animation/qanimationgroup.h
+++ b/src/corelib/animation/qanimationgroup.h
@@ -47,7 +47,7 @@ class Q_CORE_EXPORT QAnimationGroup : public QAbstractAnimation
Q_OBJECT
public:
- QAnimationGroup(QObject *parent = 0);
+ QAnimationGroup(QObject *parent = Q_NULLPTR);
~QAnimationGroup();
QAbstractAnimation *animationAt(int index) const;
diff --git a/src/corelib/animation/qparallelanimationgroup.h b/src/corelib/animation/qparallelanimationgroup.h
index 52a61dafcd..7ce05d6344 100644
--- a/src/corelib/animation/qparallelanimationgroup.h
+++ b/src/corelib/animation/qparallelanimationgroup.h
@@ -47,7 +47,7 @@ class Q_CORE_EXPORT QParallelAnimationGroup : public QAnimationGroup
Q_OBJECT
public:
- QParallelAnimationGroup(QObject *parent = 0);
+ QParallelAnimationGroup(QObject *parent = Q_NULLPTR);
~QParallelAnimationGroup();
int duration() const Q_DECL_OVERRIDE;
diff --git a/src/corelib/animation/qpauseanimation.h b/src/corelib/animation/qpauseanimation.h
index 159d82f969..5207472623 100644
--- a/src/corelib/animation/qpauseanimation.h
+++ b/src/corelib/animation/qpauseanimation.h
@@ -48,8 +48,8 @@ class Q_CORE_EXPORT QPauseAnimation : public QAbstractAnimation
Q_OBJECT
Q_PROPERTY(int duration READ duration WRITE setDuration)
public:
- QPauseAnimation(QObject *parent = 0);
- QPauseAnimation(int msecs, QObject *parent = 0);
+ QPauseAnimation(QObject *parent = Q_NULLPTR);
+ QPauseAnimation(int msecs, QObject *parent = Q_NULLPTR);
~QPauseAnimation();
int duration() const Q_DECL_OVERRIDE;
diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h
index 8d06a9f354..c0d30ba0fd 100644
--- a/src/corelib/animation/qpropertyanimation.h
+++ b/src/corelib/animation/qpropertyanimation.h
@@ -49,8 +49,8 @@ class Q_CORE_EXPORT QPropertyAnimation : public QVariantAnimation
Q_PROPERTY(QObject* targetObject READ targetObject WRITE setTargetObject)
public:
- QPropertyAnimation(QObject *parent = 0);
- QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0);
+ QPropertyAnimation(QObject *parent = Q_NULLPTR);
+ QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = Q_NULLPTR);
~QPropertyAnimation();
QObject *targetObject() const;
diff --git a/src/corelib/animation/qsequentialanimationgroup.h b/src/corelib/animation/qsequentialanimationgroup.h
index 1a4ead90d4..c8a84a1220 100644
--- a/src/corelib/animation/qsequentialanimationgroup.h
+++ b/src/corelib/animation/qsequentialanimationgroup.h
@@ -50,7 +50,7 @@ class Q_CORE_EXPORT QSequentialAnimationGroup : public QAnimationGroup
Q_PROPERTY(QAbstractAnimation* currentAnimation READ currentAnimation NOTIFY currentAnimationChanged)
public:
- QSequentialAnimationGroup(QObject *parent = 0);
+ QSequentialAnimationGroup(QObject *parent = Q_NULLPTR);
~QSequentialAnimationGroup();
QPauseAnimation *addPause(int msecs);
diff --git a/src/corelib/animation/qsequentialanimationgroup_p.h b/src/corelib/animation/qsequentialanimationgroup_p.h
index 035a553799..fdb97ca83c 100644
--- a/src/corelib/animation/qsequentialanimationgroup_p.h
+++ b/src/corelib/animation/qsequentialanimationgroup_p.h
@@ -86,7 +86,7 @@ public:
// this is the actual duration of uncontrolled animations
// it helps seeking and even going forward
- QList<int> actualDuration;
+ QVector<int> actualDuration;
void restart();
int lastLoop;
diff --git a/src/corelib/animation/qvariantanimation.h b/src/corelib/animation/qvariantanimation.h
index 8a6524a594..4340a187a2 100644
--- a/src/corelib/animation/qvariantanimation.h
+++ b/src/corelib/animation/qvariantanimation.h
@@ -59,7 +59,7 @@ public:
typedef QPair<qreal, QVariant> KeyValue;
typedef QVector<KeyValue> KeyValues;
- QVariantAnimation(QObject *parent = 0);
+ QVariantAnimation(QObject *parent = Q_NULLPTR);
~QVariantAnimation();
QVariant startValue() const;
@@ -88,7 +88,7 @@ Q_SIGNALS:
void valueChanged(const QVariant &value);
protected:
- QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent = 0);
+ QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent = Q_NULLPTR);
bool event(QEvent *event) Q_DECL_OVERRIDE;
void updateCurrentTime(int) Q_DECL_OVERRIDE;
diff --git a/src/corelib/codecs/qtextcodec.cpp b/src/corelib/codecs/qtextcodec.cpp
index c6d5c7388d..88987865c4 100644
--- a/src/corelib/codecs/qtextcodec.cpp
+++ b/src/corelib/codecs/qtextcodec.cpp
@@ -1155,7 +1155,6 @@ QTextCodec *QTextCodec::codecForUtfText(const QByteArray &ba)
function returns 0 (the default), tr() assumes Latin-1.
*/
-
/*!
\internal
\since 4.3
diff --git a/src/corelib/codecs/qtextcodec.h b/src/corelib/codecs/qtextcodec.h
index 1d5e25efcc..3e73872d64 100644
--- a/src/corelib/codecs/qtextcodec.h
+++ b/src/corelib/codecs/qtextcodec.h
@@ -88,7 +88,7 @@ public:
struct Q_CORE_EXPORT ConverterState {
ConverterState(ConversionFlags f = DefaultConversion)
- : flags(f), remainingChars(0), invalidChars(0), d(0) { state_data[0] = state_data[1] = state_data[2] = 0; }
+ : flags(f), remainingChars(0), invalidChars(0), d(Q_NULLPTR) { state_data[0] = state_data[1] = state_data[2] = 0; }
~ConverterState();
ConversionFlags flags;
int remainingChars;
@@ -99,9 +99,9 @@ public:
Q_DISABLE_COPY(ConverterState)
};
- QString toUnicode(const char *in, int length, ConverterState *state = 0) const
+ QString toUnicode(const char *in, int length, ConverterState *state = Q_NULLPTR) const
{ return convertToUnicode(in, length, state); }
- QByteArray fromUnicode(const QChar *in, int length, ConverterState *state = 0) const
+ QByteArray fromUnicode(const QChar *in, int length, ConverterState *state = Q_NULLPTR) const
{ return convertFromUnicode(in, length, state); }
QTextDecoder* makeDecoder(ConversionFlags flags = DefaultConversion) const;
diff --git a/src/corelib/corelib.pro b/src/corelib/corelib.pro
index 2d78041752..5cd0bde87b 100644
--- a/src/corelib/corelib.pro
+++ b/src/corelib/corelib.pro
@@ -13,9 +13,6 @@ irix-cc*:QMAKE_CXXFLAGS += -no_prelink -ptused
CONFIG += optimize_full
-# otherwise mingw headers do not declare common functions like putenv
-mingw:QMAKE_CXXFLAGS_CXX11 = -std=gnu++0x
-
QMAKE_DOCS = $$PWD/doc/qtcore.qdocconf
ANDROID_JAR_DEPENDENCIES = \
@@ -48,6 +45,9 @@ include(statemachine/statemachine.pri)
include(mimetypes/mimetypes.pri)
include(xml/xml.pri)
+# otherwise mingw headers do not declare common functions like putenv
+mingw: CONFIG -= strict_c++
+
mac|darwin {
!ios {
LIBS_PRIVATE += -framework ApplicationServices
diff --git a/src/corelib/doc/snippets/code/src_corelib_codecs_qtextcodec.cpp b/src/corelib/doc/snippets/code/src_corelib_codecs_qtextcodec.cpp
index e2cf761ff8..eacc94b19f 100644
--- a/src/corelib/doc/snippets/code/src_corelib_codecs_qtextcodec.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_codecs_qtextcodec.cpp
@@ -63,13 +63,3 @@ while (new_data_available()) {
}
delete decoder;
//! [2]
-
-
-//! [3]
-int main(int argc, char *argv[])
-{
- QApplication app(argc, argv);
- QTextCodec::setCodecForTr(QTextCodec::codecForName("eucKR"));
- ...
-}
-//! [3]
diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp
index b0048014a4..8ff44c9dca 100644
--- a/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp
@@ -418,17 +418,17 @@ QString example = tr("Example");
//! [40]
//! [41]
-QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildOnly);
+QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly);
//! [41]
//! [42]
-QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildOnly);
+QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildrenOnly);
//! [42]
//! [43]
-QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildOnly);
+QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildrenOnly);
//! [43]
//! [44]
diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp
index 43d64fc08e..0ac7cb5769 100644
--- a/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp
@@ -298,6 +298,25 @@ while (i != hash.end() && i.key() == "plenty") {
}
//! [26]
+//! [27]
+for (QHash<int, QString>::const_iterator it = hash.cbegin(), end = hash.cend(); it != end; ++it) {
+ cout << "The key: " << it.key() << endl
+ cout << "The value: " << it.value() << endl;
+ cout << "Also the value: " << (*it) << endl;
+}
+//! [27]
+
+//! [28]
+// Inefficient, keys() is expensive
+QList<int> keys = hash.keys();
+int numPrimes = std::count_if(keys.cbegin(), keys.cend(), isPrimeNumber);
+qDeleteAll(hash2.keys());
+
+// Efficient, no memory allocation needed
+int numPrimes = std::count_if(hash.keyBegin(), hash.keyEnd(), isPrimeNumber);
+qDeleteAll(hash2.keyBegin(), hash2.keyEnd());
+//! [28]
+
//! [qhashbits]
inline uint qHash(const std::vector<int> &key, uint seed = 0)
{
diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp
index 7580b6bbaf..29e53fc700 100644
--- a/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp
@@ -311,3 +311,22 @@ while (i != map.end() && i.key() == "plenty") {
++i;
}
//! [27]
+
+//! [keyiterator1]
+for (QMap<int, QString>::const_iterator it = map.cbegin(), end = map.cend(); it != end; ++it) {
+ cout << "The key: " << it.key() << endl
+ cout << "The value: " << it.value() << endl;
+ cout << "Also the value: " << (*it) << endl;
+}
+//! [keyiterator1]
+
+//! [keyiterator2]
+// Inefficient, keys() is expensive
+QList<int> keys = map.keys();
+int numPrimes = std::count_if(map.cbegin(), map.cend(), isPrimeNumber);
+qDeleteAll(map2.keys());
+
+// Efficient, no memory allocation needed
+int numPrimes = std::count_if(map.keyBegin(), map.keyEnd(), isPrimeNumber);
+qDeleteAll(map2.keyBegin(), map2.keyEnd());
+//! [keyiterator2]
diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qvector.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qvector.cpp
index 77b34c95fc..5def361b83 100644
--- a/src/corelib/doc/snippets/code/src_corelib_tools_qvector.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_tools_qvector.cpp
@@ -84,14 +84,27 @@ for (int i = 0; i < 10; ++i)
//! [7]
-QVector<QString> vector(0);
+QVector<QString> vector;
vector.append("one");
vector.append("two");
-vector.append("three");
+QString three = "three";
+vector.append(three);
// vector: ["one", "two", "three"]
+// three: "three"
//! [7]
+//! [move-append]
+QVector<QString> vector;
+vector.append("one");
+vector.append("two");
+QString three = "three";
+vector.append(std::move(three));
+// vector: ["one", "two", "three"]
+// three: ""
+//! [move-append]
+
+
//! [8]
QVector<QString> vector;
vector.prepend("one");
diff --git a/src/corelib/doc/src/external-resources.qdoc b/src/corelib/doc/src/external-resources.qdoc
index ec4715c933..d612ce8280 100644
--- a/src/corelib/doc/src/external-resources.qdoc
+++ b/src/corelib/doc/src/external-resources.qdoc
@@ -65,4 +65,13 @@
\externalpage http://doc-snapshot.qt-project.org/qt5-5.4/designer-widget-mode.html#the-property-editor
\title Qt Designer's Widget Editing Mode#The Property Editor
*/
+
+/*!
+ \externalpage http://marcmutz.wordpress.com/effective-qt/containers/#containers-qlist
+ \title Pros and Cons of Using QList
+*/
+
+/*!
+ \externalpage http://marcmutz.wordpress.com/effective-qt/containers/
+ \title Understand the Qt Containers
*/
diff --git a/src/corelib/doc/src/objectmodel/properties.qdoc b/src/corelib/doc/src/objectmodel/properties.qdoc
index abb0720fe9..55622dd56b 100644
--- a/src/corelib/doc/src/objectmodel/properties.qdoc
+++ b/src/corelib/doc/src/objectmodel/properties.qdoc
@@ -160,13 +160,8 @@
Because QDate is user-defined, you must include the \c{<QDate>}
header file with the property declaration.
- For QMap, QList, and QValueList properties, the property value is
- a QVariant whose value is the entire list or map. Note that the
- Q_PROPERTY string cannot contain commas, because commas separate
- macro arguments. Therefore, you must use \c QMap as the property
- type instead of \c QMap<QString,QVariant>. For consistency, also
- use \c QList and \c QValueList instead of \c QList<QVariant> and
- \c QValueList<QVariant>.
+ For historical reasons, \a QMap and \a QList as property types
+ are synonym of \a QVariantMap and \a QVariantList.
\section1 Reading and Writing Properties with the Meta-Object System
diff --git a/src/corelib/global/global.pri b/src/corelib/global/global.pri
index 6a8104bee2..43f3a86544 100644
--- a/src/corelib/global/global.pri
+++ b/src/corelib/global/global.pri
@@ -54,3 +54,7 @@ journald {
PKGCONFIG_PRIVATE += libsystemd-journal
DEFINES += QT_USE_JOURNALD
}
+
+syslog {
+ DEFINES += QT_USE_SYSLOG
+}
diff --git a/src/corelib/global/qflags.h b/src/corelib/global/qflags.h
index d3b9c3f5a7..f434e87c85 100644
--- a/src/corelib/global/qflags.h
+++ b/src/corelib/global/qflags.h
@@ -109,7 +109,7 @@ public:
inline QFlags &operator=(const QFlags &other);
#endif
Q_DECL_CONSTEXPR inline QFlags(Enum f) Q_DECL_NOTHROW : i(Int(f)) {}
- Q_DECL_CONSTEXPR inline QFlags(Zero = 0) Q_DECL_NOTHROW : i(0) {}
+ Q_DECL_CONSTEXPR inline QFlags(Zero = Q_NULLPTR) Q_DECL_NOTHROW : i(0) {}
Q_DECL_CONSTEXPR inline QFlags(QFlag f) Q_DECL_NOTHROW : i(f) {}
#ifdef Q_COMPILER_INITIALIZER_LISTS
diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp
index b5bdcedaa1..77ac53f7e9 100644
--- a/src/corelib/global/qglobal.cpp
+++ b/src/corelib/global/qglobal.cpp
@@ -42,6 +42,7 @@
#include <private/qlocale_tools_p.h>
#include <private/qsystemlibrary_p.h>
+#include <qmutex.h>
#ifndef QT_NO_QOBJECT
#include <private/qthread_p.h>
@@ -64,6 +65,20 @@
# endif
#endif
+#ifdef Q_OS_WINRT
+#include <wrl.h>
+#include <windows.networking.h>
+#include <windows.networking.sockets.h>
+#include <windows.networking.connectivity.h>
+using namespace Microsoft::WRL;
+using namespace Microsoft::WRL::Wrappers;
+using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::Foundation::Collections;
+using namespace ABI::Windows::Networking;
+using namespace ABI::Windows::Networking::Connectivity;
+using namespace ABI::Windows::Networking::Sockets;
+#endif
+
#if defined(Q_OS_VXWORKS) && defined(_WRS_KERNEL)
# include <envLib.h>
#endif
@@ -89,6 +104,10 @@
#include <private/qcore_unix_p.h>
#endif
+#ifdef Q_OS_BSD4
+#include <sys/sysctl.h>
+#endif
+
#include "archdetect.cpp"
QT_BEGIN_NAMESPACE
@@ -1886,6 +1905,36 @@ QT_END_INCLUDE_NAMESPACE
#ifndef Q_OS_WINRT
+# ifndef QT_BOOTSTRAPPED
+class QWindowsSockInit
+{
+public:
+ QWindowsSockInit();
+ ~QWindowsSockInit();
+ int version;
+};
+
+QWindowsSockInit::QWindowsSockInit()
+: version(0)
+{
+ //### should we try for 2.2 on all platforms ??
+ WSAData wsadata;
+
+ // IPv6 requires Winsock v2.0 or better.
+ if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
+ qWarning("QTcpSocketAPI: WinSock v2.0 initialization failed.");
+ } else {
+ version = 0x20;
+ }
+}
+
+QWindowsSockInit::~QWindowsSockInit()
+{
+ WSACleanup();
+}
+Q_GLOBAL_STATIC(QWindowsSockInit, winsockInit)
+# endif // QT_BOOTSTRAPPED
+
# ifndef Q_OS_WINCE
// Determine Windows versions >= 8 by querying the version of kernel32.dll.
@@ -2774,6 +2823,82 @@ QString QSysInfo::prettyProductName()
return unknownText();
}
+#ifndef QT_BOOTSTRAPPED
+/*!
+ \since 5.6
+
+ Returns this machine's host name, if one is configured. Note that hostnames
+ are not guaranteed to be globally unique, especially if they were
+ configured automatically.
+
+ This function does not guarantee the returned host name is a Fully
+ Qualified Domain Name (FQDN). For that, use QHostInfo to resolve the
+ returned name to an FQDN.
+
+ This function returns the same as QHostInfo::localHostName().
+
+ \sa QHostInfo::localDomainName
+ */
+QString QSysInfo::machineHostName()
+{
+#if defined(Q_OS_LINUX)
+ // gethostname(3) on Linux just calls uname(2), so do it ourselves
+ // and avoid a memcpy
+ struct utsname u;
+ if (uname(&u) == 0)
+ return QString::fromLocal8Bit(u.nodename);
+#elif defined(Q_OS_WINRT)
+ ComPtr<INetworkInformationStatics> statics;
+ GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);
+
+ ComPtr<IVectorView<HostName *>> hostNames;
+ statics->GetHostNames(&hostNames);
+ if (!hostNames)
+ return QString();
+
+ unsigned int size;
+ hostNames->get_Size(&size);
+ if (size == 0)
+ return QString();
+
+ for (unsigned int i = 0; i < size; ++i) {
+ ComPtr<IHostName> hostName;
+ hostNames->GetAt(i, &hostName);
+ HostNameType type;
+ hostName->get_Type(&type);
+ if (type != HostNameType_DomainName)
+ continue;
+
+ HString name;
+ hostName->get_CanonicalName(name.GetAddressOf());
+ UINT32 length;
+ PCWSTR rawString = name.GetRawBuffer(&length);
+ return QString::fromWCharArray(rawString, length);
+ }
+ ComPtr<IHostName> firstHost;
+ hostNames->GetAt(0, &firstHost);
+
+ HString name;
+ firstHost->get_CanonicalName(name.GetAddressOf());
+ UINT32 length;
+ PCWSTR rawString = name.GetRawBuffer(&length);
+ return QString::fromWCharArray(rawString, length);
+#else
+# ifdef Q_OS_WIN
+ // Important: QtNetwork depends on machineHostName() initializing ws2_32.dll
+ winsockInit();
+# endif
+
+ char hostName[512];
+ if (gethostname(hostName, sizeof(hostName)) == -1)
+ return QString();
+ hostName[sizeof(hostName) - 1] = '\0';
+ return QString::fromLocal8Bit(hostName);
+#endif
+ return QString();
+}
+#endif // QT_BOOTSTRAPPED
+
/*!
\macro void Q_ASSERT(bool test)
\relates <QtGlobal>
@@ -2885,12 +3010,15 @@ QString QSysInfo::prettyProductName()
\macro void Q_CHECK_PTR(void *pointer)
\relates <QtGlobal>
- If \a pointer is 0, prints a warning message containing the source
+ If \a pointer is 0, prints a message containing the source
code's file name and line number, saying that the program ran out
- of memory.
+ of memory and aborts program execution. It throws \c std::bad_alloc instead
+ if exceptions are enabled.
- Q_CHECK_PTR does nothing if \c QT_NO_DEBUG was defined during
- compilation.
+ Q_CHECK_PTR does nothing if \c QT_NO_DEBUG and \c QT_NO_EXCEPTIONS were
+ defined during compilation. Therefore you must not use Q_CHECK_PTR to check
+ for successful memory allocations because the check will be disabled in
+ some cases.
Example:
@@ -3020,7 +3148,7 @@ namespace {
// depending on the return type
static inline Q_DECL_UNUSED QString fromstrerror_helper(int, const QByteArray &buf)
{
- return QString::fromLocal8Bit(buf);
+ return QString::fromLocal8Bit(buf.constData());
}
static inline Q_DECL_UNUSED QString fromstrerror_helper(const char *str, const QByteArray &)
{
@@ -3098,6 +3226,10 @@ QString qt_error_string(int errorCode)
return ret.trimmed();
}
+// In the C runtime on all platforms access to the environment is not thread-safe. We
+// add thread-safety for the Qt wrappers.
+static QBasicMutex environmentMutex;
+
// getenv is declared as deprecated in VS2005. This function
// makes use of the new secure getenv function.
/*!
@@ -3115,6 +3247,7 @@ QString qt_error_string(int errorCode)
*/
QByteArray qgetenv(const char *varName)
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
size_t requiredSize = 0;
QByteArray buffer;
@@ -3148,6 +3281,7 @@ QByteArray qgetenv(const char *varName)
*/
bool qEnvironmentVariableIsEmpty(const char *varName) Q_DECL_NOEXCEPT
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
// we provide a buffer that can only hold the empty string, so
// when the env.var isn't empty, we'll get an ERANGE error (buffer
@@ -3179,6 +3313,7 @@ bool qEnvironmentVariableIsEmpty(const char *varName) Q_DECL_NOEXCEPT
*/
int qEnvironmentVariableIntValue(const char *varName, bool *ok) Q_DECL_NOEXCEPT
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
// we provide a buffer that can hold any int value:
static const int NumBinaryDigitsPerOctalDigit = 3;
@@ -3227,6 +3362,7 @@ int qEnvironmentVariableIntValue(const char *varName, bool *ok) Q_DECL_NOEXCEPT
*/
bool qEnvironmentVariableIsSet(const char *varName) Q_DECL_NOEXCEPT
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
size_t requiredSize = 0;
(void)getenv_s(&requiredSize, 0, 0, varName);
@@ -3256,6 +3392,7 @@ bool qEnvironmentVariableIsSet(const char *varName) Q_DECL_NOEXCEPT
*/
bool qputenv(const char *varName, const QByteArray& value)
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
return _putenv_s(varName, value.constData()) == 0;
#elif (defined(_POSIX_VERSION) && (_POSIX_VERSION-0) >= 200112L) || defined(Q_OS_HAIKU)
@@ -3286,6 +3423,7 @@ bool qputenv(const char *varName, const QByteArray& value)
*/
bool qunsetenv(const char *varName)
{
+ QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
return _putenv_s(varName, "") == 0;
#elif (defined(_POSIX_VERSION) && (_POSIX_VERSION-0) >= 200112L) || defined(Q_OS_BSD4) || defined(Q_OS_HAIKU)
diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h
index 97c5f37cab..f8f306f614 100644
--- a/src/corelib/global/qglobal.h
+++ b/src/corelib/global/qglobal.h
@@ -41,11 +41,11 @@
#include <stddef.h>
-#define QT_VERSION_STR "5.5.1"
+#define QT_VERSION_STR "5.6.0"
/*
QT_VERSION is (major << 16) + (minor << 8) + patch.
*/
-#define QT_VERSION 0x050501
+#define QT_VERSION 0x050600
/*
can be used like #if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
*/
@@ -322,6 +322,15 @@ typedef double qreal;
#endif
/*
+ Some classes do not permit copies to be made of an object. These
+ classes contains a private copy constructor and assignment
+ operator to disable copying (the compiler gives an error message).
+*/
+#define Q_DISABLE_COPY(Class) \
+ Class(const Class &) Q_DECL_EQ_DELETE;\
+ Class &operator=(const Class &) Q_DECL_EQ_DELETE;
+
+/*
No, this is not an evil backdoor. QT_BUILD_INTERNAL just exports more symbols
for Qt's internal unit tests. If you want slower loading times and more
symbols that can vanish from version to version, feel free to define QT_BUILD_INTERNAL.
@@ -487,10 +496,13 @@ typedef qptrdiff qintptr;
#ifdef Q_CC_MSVC
# define Q_NEVER_INLINE __declspec(noinline)
+# define Q_ALWAYS_INLINE __forceinline
#elif defined(Q_CC_GNU)
# define Q_NEVER_INLINE __attribute__((noinline))
+# define Q_ALWAYS_INLINE inline __attribute__((always_inline))
#else
# define Q_NEVER_INLINE
+# define Q_ALWAYS_INLINE inline
#endif
//defines the type for the WNDPROC on windows
@@ -543,7 +555,21 @@ template <typename T>
Q_DECL_CONSTEXPR inline const T &qBound(const T &min, const T &val, const T &max)
{ return qMax(min, qMin(max, val)); }
-#ifdef Q_OS_DARWIN
+#ifndef Q_FORWARD_DECLARE_OBJC_CLASS
+# ifdef __OBJC__
+# define Q_FORWARD_DECLARE_OBJC_CLASS(classname) @class classname
+# else
+# define Q_FORWARD_DECLARE_OBJC_CLASS(classname) typedef struct objc_object classname
+# endif
+#endif
+#ifndef Q_FORWARD_DECLARE_CF_TYPE
+# define Q_FORWARD_DECLARE_CF_TYPE(type) typedef const struct __ ## type * type ## Ref
+#endif
+#ifndef Q_FORWARD_DECLARE_MUTABLE_CF_TYPE
+# define Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(type) typedef struct __ ## type * type ## Ref
+#endif
+
+#ifdef Q_OS_MAC
# define QT_MAC_PLATFORM_SDK_EQUAL_OR_ABOVE(osx, ios) \
((defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && osx != __MAC_NA && __MAC_OS_X_VERSION_MAX_ALLOWED >= osx) || \
(defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && ios != __IPHONE_NA && __IPHONE_OS_VERSION_MAX_ALLOWED >= ios))
@@ -561,7 +587,23 @@ Q_DECL_CONSTEXPR inline const T &qBound(const T &min, const T &val, const T &max
QT_MAC_DEPLOYMENT_TARGET_BELOW(__MAC_NA, ios)
# define QT_OSX_DEPLOYMENT_TARGET_BELOW(osx) \
QT_MAC_DEPLOYMENT_TARGET_BELOW(osx, __IPHONE_NA)
-#endif
+
+QT_END_NAMESPACE
+Q_FORWARD_DECLARE_OBJC_CLASS(NSAutoreleasePool);
+QT_BEGIN_NAMESPACE
+
+// Implemented in qcore_mac_objc.mm
+class Q_CORE_EXPORT QMacAutoReleasePool
+{
+public:
+ QMacAutoReleasePool();
+ ~QMacAutoReleasePool();
+private:
+ Q_DISABLE_COPY(QMacAutoReleasePool);
+ NSAutoreleasePool *pool;
+};
+
+#endif // Q_OS_MAC
/*
Data stream functions are provided by many classes (defined in qdatastream.h)
@@ -1033,15 +1075,6 @@ Q_CORE_EXPORT QString qtTrId(const char *id, int n = -1);
{ return T::dynamic_cast_will_always_fail_because_rtti_is_disabled; }
#endif
-/*
- Some classes do not permit copies to be made of an object. These
- classes contains a private copy constructor and assignment
- operator to disable copying (the compiler gives an error message).
-*/
-#define Q_DISABLE_COPY(Class) \
- Class(const Class &) Q_DECL_EQ_DELETE;\
- Class &operator=(const Class &) Q_DECL_EQ_DELETE;
-
class QByteArray;
Q_CORE_EXPORT QByteArray qgetenv(const char *varName);
Q_CORE_EXPORT bool qputenv(const char *varName, const QByteArray& value);
@@ -1049,7 +1082,7 @@ Q_CORE_EXPORT bool qunsetenv(const char *varName);
Q_CORE_EXPORT bool qEnvironmentVariableIsEmpty(const char *varName) Q_DECL_NOEXCEPT;
Q_CORE_EXPORT bool qEnvironmentVariableIsSet(const char *varName) Q_DECL_NOEXCEPT;
-Q_CORE_EXPORT int qEnvironmentVariableIntValue(const char *varName, bool *ok=0) Q_DECL_NOEXCEPT;
+Q_CORE_EXPORT int qEnvironmentVariableIntValue(const char *varName, bool *ok=Q_NULLPTR) Q_DECL_NOEXCEPT;
inline int qIntCast(double f) { return int(f); }
inline int qIntCast(float f) { return int(f); }
@@ -1077,20 +1110,6 @@ template <bool B, typename T, typename F> struct QConditional { typedef T Type;
template <typename T, typename F> struct QConditional<false, T, F> { typedef F Type; };
}
-#ifndef Q_FORWARD_DECLARE_OBJC_CLASS
-# ifdef __OBJC__
-# define Q_FORWARD_DECLARE_OBJC_CLASS(classname) @class classname
-# else
-# define Q_FORWARD_DECLARE_OBJC_CLASS(classname) typedef struct objc_object classname
-# endif
-#endif
-#ifndef Q_FORWARD_DECLARE_CF_TYPE
-# define Q_FORWARD_DECLARE_CF_TYPE(type) typedef const struct __ ## type * type ## Ref
-#endif
-#ifndef Q_FORWARD_DECLARE_MUTABLE_CF_TYPE
-# define Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(type) typedef struct __ ## type * type ## Ref
-#endif
-
QT_END_NAMESPACE
// We need to keep QTypeInfo, QSysInfo, QFlags, qDebug & family in qglobal.h for compatibility with Qt 4.
diff --git a/src/corelib/global/qlogging.cpp b/src/corelib/global/qlogging.cpp
index fca8656f9b..20c31f7ef8 100644
--- a/src/corelib/global/qlogging.cpp
+++ b/src/corelib/global/qlogging.cpp
@@ -65,6 +65,9 @@
# include <systemd/sd-journal.h>
# include <syslog.h>
#endif
+#if defined(QT_USE_SYSLOG) && !defined(QT_BOOTSTRAPPED)
+# include <syslog.h>
+#endif
#ifdef Q_OS_UNIX
# include <sys/types.h>
# include <sys/stat.h>
@@ -1436,6 +1439,32 @@ static void systemd_default_message_handler(QtMsgType type,
}
#endif
+#ifdef QT_USE_SYSLOG
+static void syslog_default_message_handler(QtMsgType type, const char *message)
+{
+ int priority = LOG_INFO; // Informational
+ switch (type) {
+ case QtDebugMsg:
+ priority = LOG_DEBUG; // Debug-level messages
+ break;
+ case QtInfoMsg:
+ priority = LOG_INFO; // Informational conditions
+ break;
+ case QtWarningMsg:
+ priority = LOG_WARNING; // Warning conditions
+ break;
+ case QtCriticalMsg:
+ priority = LOG_CRIT; // Critical conditions
+ break;
+ case QtFatalMsg:
+ priority = LOG_ALERT; // Action must be taken immediately
+ break;
+ }
+
+ syslog(priority, "%s", message);
+}
+#endif
+
#ifdef Q_OS_ANDROID
static void android_default_message_handler(QtMsgType type,
const QMessageLogContext &context,
@@ -1481,6 +1510,9 @@ static void qDefaultMessageHandler(QtMsgType type, const QMessageLogContext &con
#elif defined(QT_USE_JOURNALD) && !defined(QT_BOOTSTRAPPED)
systemd_default_message_handler(type, context, logMessage);
return;
+#elif defined(QT_USE_SYSLOG) && !defined(QT_BOOTSTRAPPED)
+ syslog_default_message_handler(type, logMessage.toUtf8().constData());
+ return;
#elif defined(Q_OS_ANDROID)
android_default_message_handler(type, context, logMessage);
return;
diff --git a/src/corelib/global/qlogging.h b/src/corelib/global/qlogging.h
index 679afddb20..c63346086a 100644
--- a/src/corelib/global/qlogging.h
+++ b/src/corelib/global/qlogging.h
@@ -57,7 +57,8 @@ class QMessageLogContext
{
Q_DISABLE_COPY(QMessageLogContext)
public:
- Q_DECL_CONSTEXPR QMessageLogContext() : version(2), line(0), file(0), function(0), category(0) {}
+ Q_DECL_CONSTEXPR QMessageLogContext()
+ : version(2), line(0), file(Q_NULLPTR), function(Q_NULLPTR), category(Q_NULLPTR) {}
Q_DECL_CONSTEXPR QMessageLogContext(const char *fileName, int lineNumber, const char *functionName, const char *categoryName)
: version(2), line(lineNumber), file(fileName), function(functionName), category(categoryName) {}
diff --git a/src/corelib/global/qnamespace.h b/src/corelib/global/qnamespace.h
index 82b383e69c..de8a17fa51 100644
--- a/src/corelib/global/qnamespace.h
+++ b/src/corelib/global/qnamespace.h
@@ -496,6 +496,7 @@ public:
AA_UseSoftwareOpenGL = 17,
AA_ShareOpenGLContexts = 18,
AA_SetPalette = 19,
+ AA_NoHighDpiScaling = 20,
// Add new attributes before this line
AA_AttributeCount
@@ -1326,6 +1327,7 @@ public:
ImAbsolutePosition = 0x400,
ImTextBeforeCursor = 0x800,
ImTextAfterCursor = 0x1000,
+ ImEnterKeyType = 0x2000,
ImPlatformData = 0x80000000,
ImQueryInput = ImCursorRectangle | ImCursorPosition | ImSurroundingText |
@@ -1365,6 +1367,17 @@ public:
};
Q_DECLARE_FLAGS(InputMethodHints, InputMethodHint)
+ enum EnterKeyType {
+ EnterKeyDefault,
+ EnterKeyReturn,
+ EnterKeyDone,
+ EnterKeyGo,
+ EnterKeySend,
+ EnterKeySearch,
+ EnterKeyNext,
+ EnterKeyPrevious
+ };
+
enum ToolButtonStyle {
ToolButtonIconOnly,
ToolButtonTextOnly,
@@ -1449,7 +1462,10 @@ public:
ItemIsDropEnabled = 8,
ItemIsUserCheckable = 16,
ItemIsEnabled = 32,
- ItemIsTristate = 64,
+ ItemIsAutoTristate = 64,
+#if QT_DEPRECATED_SINCE(5, 6)
+ ItemIsTristate = ItemIsAutoTristate,
+#endif
ItemNeverHasChildren = 128,
ItemIsUserTristate = 256
};
@@ -1520,9 +1536,16 @@ public:
TitleBarArea // For move
};
+#if defined(Q_COMPILER_CLASS_ENUM) && defined(Q_COMPILER_CONSTEXPR)
+ enum class Initialization {
+ Uninitialized
+ };
+ static constexpr Q_DECL_UNUSED Initialization Uninitialized = Initialization::Uninitialized;
+#else
enum Initialization {
Uninitialized
};
+#endif
enum CoordinateSystem {
DeviceCoordinates,
@@ -1610,7 +1633,8 @@ public:
enum MouseEventSource {
MouseEventNotSynthesized,
MouseEventSynthesizedBySystem,
- MouseEventSynthesizedByQt
+ MouseEventSynthesizedByQt,
+ MouseEventSynthesizedByApplication
};
enum MouseEventFlag {
@@ -1685,6 +1709,7 @@ public:
QT_Q_ENUM(InputMethodHint)
QT_Q_ENUM(InputMethodQuery)
QT_Q_FLAG(InputMethodHints)
+ QT_Q_ENUM(EnterKeyType)
QT_Q_FLAG(InputMethodQueries)
QT_Q_FLAG(TouchPointStates)
QT_Q_ENUM(ScreenOrientation)
diff --git a/src/corelib/global/qnamespace.qdoc b/src/corelib/global/qnamespace.qdoc
index c6098007d1..a7da751da4 100644
--- a/src/corelib/global/qnamespace.qdoc
+++ b/src/corelib/global/qnamespace.qdoc
@@ -170,12 +170,13 @@
\value AA_UseDesktopOpenGL Forces the usage of desktop OpenGL (for example,
\e opengl32.dll or \e libGL.so) on platforms that use dynamic loading
- of the OpenGL implementation.
- This value has been added in Qt 5.3.
+ of the OpenGL implementation. This value has been added in Qt 5.3.
+ This attribute must be set before Q(Gui)Application is constructed.
\value AA_UseOpenGLES Forces the usage of OpenGL ES 2.0 or higher on
platforms that use dynamic loading of the OpenGL implementation.
- This value has been added in Qt 5.3.
+ This value has been added in Qt 5.3. This attribute must be set
+ before Q(Gui)Application is constructed.
\value AA_UseSoftwareOpenGL Forces the usage of a software based OpenGL
implementation on platforms that use dynamic loading of the OpenGL
@@ -186,17 +187,24 @@
\c opengl32sw.dll and can be overridden by setting the environment
variable \e QT_OPENGL_DLL. See the platform-specific pages, for
instance \l{Qt for Windows}, for more information. This value has
- been added in Qt 5.4.
+ been added in Qt 5.4. This attribute must be set before
+ Q(Gui)Application is constructed.
\value AA_ShareOpenGLContexts Enables resource sharing between the OpenGL
contexts used by classes like QOpenGLWidget and QQuickWidget. This
allows sharing OpenGL resources, like textures, between QOpenGLWidget
instances that belong to different top-level windows. This value has
- been added in Qt 5.4.
+ been added in Qt 5.4. This attribute must be set before
+ Q(Gui)Application is constructed.
\value AA_SetPalette Indicates whether a palette was explicitly set on the
QApplication/QGuiApplication. This value has been added in Qt 5.5.
+ \value AA_NoHighDpiScaling Disables all high-DPI scaling in Qt, exposing window
+ system coordinates. Note that the window system may do its own scaling,
+ so this does not guarantee that QPaintDevice::devicePixelRatio() will
+ be equal to 1. This value has been added in Qt 5.6.
+
The following values are obsolete:
\value AA_ImmediateWidgetCreation This attribute is no longer fully
@@ -1670,6 +1678,16 @@
\value Key_Blue
\value Key_ChannelUp
\value Key_ChannelDown
+ \value Key_Guide
+ \value Key_Info
+ \value Key_Settings
+ \value Key_MicVolumeUp
+ \value Key_MicVolumeDown
+ \value Key_New
+ \value Key_Open
+ \value Key_Find
+ \value Key_Undo
+ \value Key_Redo
\value Key_MediaLast
\value Key_unknown
@@ -1694,6 +1712,7 @@
\value Key_Play
\value Key_Sleep
\value Key_Zoom
+ \value Key_Exit
\value Key_Cancel
\sa QKeyEvent::key()
@@ -2516,6 +2535,7 @@
but \b{must} not return an empty string unless the cursor is at the start of the document.
\value ImTextAfterCursor The plain text after the cursor. The widget can decide how much text to return,
but \b{must} not return an empty string unless the cursor is at the end of the document.
+ \value ImEnterKeyType The Enter key type.
Masks:
@@ -2526,6 +2546,37 @@
*/
/*!
+ \enum Qt::EnterKeyType
+
+ This can be used to alter the appearance of the Return key on an on-screen keyboard.
+
+ \note Not all of these values are supported on all platforms.
+ For unsupported values the default key will be used instead.
+
+ \value EnterKeyDefault The default Enter key.
+ This can either be a button closing the keyboard, or a Return button
+ causing a new line in case of a multi-line input field.
+ \value EnterKeyReturn Show a Return button that inserts a new line.
+ The keyboard will not close when this button is pressed.
+ \value EnterKeyDone Show a "Done" button.
+ The keyboard will close when this button is pressed.
+ \value EnterKeyGo Show a "Go" button.
+ Typically used in an address bar when entering a URL; the keyboard
+ will close when this button is pressed.
+ \value EnterKeySend Show a "Send" button.
+ The keyboard will close when this button is pressed.
+ \value EnterKeySearch Show a "Search" button.
+ The keyboard will close when this button is pressed.
+ \value EnterKeyNext Show a "Next" button.
+ Typically used in a form to allow navigating to the next input field;
+ the keyboard will not close when this button is pressed.
+ \value EnterKeyPrevious Show a "Previous" button.
+ The keyboard will not close when this button is pressed.
+
+ \since 5.6
+*/
+
+/*!
\enum Qt::ItemDataRole
Each item in the model has a set of data elements associated with
@@ -2600,10 +2651,12 @@
\value ItemIsDropEnabled It can be used as a drop target.
\value ItemIsUserCheckable It can be checked or unchecked by the user.
\value ItemIsEnabled The user can interact with the item.
- \value ItemIsTristate The item can show three separate states.
+ \value ItemIsAutoTristate The item's state depends on the state of its children.
This enables automatic management of the state of parent items in QTreeWidget
(checked if all children are checked, unchecked if all children are unchecked,
or partially checked if only some children are checked).
+ \value ItemIsTristate \e{This enum value is deprecated.} Use Qt::ItemIsAutoTristate
+ instead.
\value ItemNeverHasChildren The item never has child items.
This is used for optimization purposes only.
\value ItemIsUserTristate The user can cycle through three separate states.
@@ -3024,6 +3077,12 @@
\value MouseEventSynthesizedByQt Indicates that the mouse event was
synthesized from an unhandled touch event by Qt.
+ \value MouseEventSynthesizedByApplication Indicates that the mouse
+ event was synthesized by the application. This allows
+ distinguishing application-generated mouse events from the ones
+ that are coming from the system or are synthesized by Qt. This
+ value was introduced in Qt 5.6
+
\sa Qt::AA_SynthesizeMouseForUnhandledTouchEvents
*/
diff --git a/src/corelib/global/qsysinfo.h b/src/corelib/global/qsysinfo.h
index 625b366cc6..27a285fd36 100644
--- a/src/corelib/global/qsysinfo.h
+++ b/src/corelib/global/qsysinfo.h
@@ -125,19 +125,19 @@ public:
MV_Unknown = 0x0000,
/* version */
- MV_9 = 0x0001,
- MV_10_0 = 0x0002,
- MV_10_1 = 0x0003,
- MV_10_2 = 0x0004,
- MV_10_3 = 0x0005,
- MV_10_4 = 0x0006,
- MV_10_5 = 0x0007,
- MV_10_6 = 0x0008,
- MV_10_7 = 0x0009,
- MV_10_8 = 0x000A,
- MV_10_9 = 0x000B,
- MV_10_10 = 0x000C,
- MV_10_11 = 0x000D,
+ MV_9 = Q_MV_OSX(9, 0),
+ MV_10_0 = Q_MV_OSX(10, 0),
+ MV_10_1 = Q_MV_OSX(10, 1),
+ MV_10_2 = Q_MV_OSX(10, 2),
+ MV_10_3 = Q_MV_OSX(10, 3),
+ MV_10_4 = Q_MV_OSX(10, 4),
+ MV_10_5 = Q_MV_OSX(10, 5),
+ MV_10_6 = Q_MV_OSX(10, 6),
+ MV_10_7 = Q_MV_OSX(10, 7),
+ MV_10_8 = Q_MV_OSX(10, 8),
+ MV_10_9 = Q_MV_OSX(10, 9),
+ MV_10_10 = Q_MV_OSX(10, 10),
+ MV_10_11 = Q_MV_OSX(10, 11),
/* codenames */
MV_CHEETAH = MV_10_0,
@@ -186,6 +186,8 @@ public:
static QString productType();
static QString productVersion();
static QString prettyProductName();
+
+ static QString machineHostName();
};
QT_END_NAMESPACE
diff --git a/src/corelib/global/qtypeinfo.h b/src/corelib/global/qtypeinfo.h
index 90ac8c6a0c..b42e5998fc 100644
--- a/src/corelib/global/qtypeinfo.h
+++ b/src/corelib/global/qtypeinfo.h
@@ -32,6 +32,7 @@
****************************************************************************/
#include <QtCore/qtypetraits.h>
+#include <QtCore/qisenum.h>
#ifndef QTYPEINFO_H
#define QTYPEINFO_H
@@ -55,6 +56,7 @@ public:
isIntegral = QtPrivate::is_integral<T>::value,
isComplex = true,
isStatic = true,
+ isRelocatable = Q_IS_ENUM(T),
isLarge = (sizeof(T)>sizeof(void*)),
isDummy = false, //### Qt6: remove
sizeOf = sizeof(T)
@@ -70,6 +72,7 @@ public:
isIntegral = false,
isComplex = false,
isStatic = false,
+ isRelocatable = false,
isLarge = false,
isDummy = false,
sizeOf = 0
@@ -85,6 +88,7 @@ public:
isIntegral = false,
isComplex = false,
isStatic = false,
+ isRelocatable = true,
isLarge = false,
isDummy = false,
sizeOf = sizeof(T*)
@@ -92,6 +96,32 @@ public:
};
/*!
+ \class QTypeInfoQuery
+ \inmodule QtCore
+ \internal
+ \brief QTypeInfoQuery is used to query the values of a given QTypeInfo<T>
+
+ We use it because there may be some QTypeInfo<T> specializations in user
+ code that don't provide certain flags that we added after Qt 5.0. They are:
+ \list
+ \li isRelocatable: defaults to !isStatic
+ \endlist
+
+ DO NOT specialize this class elsewhere.
+*/
+// apply defaults for a generic QTypeInfo<T> that didn't provide the new values
+template <typename T, typename = void>
+struct QTypeInfoQuery : QTypeInfo<T>
+{
+ enum { isRelocatable = !QTypeInfo<T>::isStatic };
+};
+
+// if QTypeInfo<T>::isRelocatable exists, use it
+template <typename T>
+struct QTypeInfoQuery<T, typename QtPrivate::QEnableIf<QTypeInfo<T>::isRelocatable || true>::Type> : QTypeInfo<T>
+{};
+
+/*!
\class QTypeInfoMerger
\inmodule QtCore
\internal
@@ -116,8 +146,12 @@ class QTypeInfoMerger
{
public:
enum {
- isComplex = QTypeInfo<T1>::isComplex || QTypeInfo<T2>::isComplex || QTypeInfo<T3>::isComplex || QTypeInfo<T4>::isComplex,
- isStatic = QTypeInfo<T1>::isStatic || QTypeInfo<T2>::isStatic || QTypeInfo<T3>::isStatic || QTypeInfo<T4>::isStatic,
+ isComplex = QTypeInfoQuery<T1>::isComplex || QTypeInfoQuery<T2>::isComplex
+ || QTypeInfoQuery<T3>::isComplex || QTypeInfoQuery<T4>::isComplex,
+ isStatic = QTypeInfoQuery<T1>::isStatic || QTypeInfoQuery<T2>::isStatic
+ || QTypeInfoQuery<T3>::isStatic || QTypeInfoQuery<T4>::isStatic,
+ isRelocatable = QTypeInfoQuery<T1>::isRelocatable && QTypeInfoQuery<T2>::isRelocatable
+ && QTypeInfoQuery<T3>::isRelocatable && QTypeInfoQuery<T4>::isRelocatable,
isLarge = sizeof(T) > sizeof(void*),
isPointer = false,
isIntegral = false,
@@ -136,19 +170,20 @@ public: \
isPointer = false, \
isIntegral = false, \
isComplex = true, \
+ isRelocatable = true, \
isStatic = false, \
isLarge = (sizeof(CONTAINER<T>) > sizeof(void*)), \
isDummy = false, \
sizeOf = sizeof(CONTAINER<T>) \
}; \
-};
+}
-Q_DECLARE_MOVABLE_CONTAINER(QList)
-Q_DECLARE_MOVABLE_CONTAINER(QVector)
-Q_DECLARE_MOVABLE_CONTAINER(QQueue)
-Q_DECLARE_MOVABLE_CONTAINER(QStack)
-Q_DECLARE_MOVABLE_CONTAINER(QLinkedList)
-Q_DECLARE_MOVABLE_CONTAINER(QSet)
+Q_DECLARE_MOVABLE_CONTAINER(QList);
+Q_DECLARE_MOVABLE_CONTAINER(QVector);
+Q_DECLARE_MOVABLE_CONTAINER(QQueue);
+Q_DECLARE_MOVABLE_CONTAINER(QStack);
+Q_DECLARE_MOVABLE_CONTAINER(QLinkedList);
+Q_DECLARE_MOVABLE_CONTAINER(QSet);
#undef Q_DECLARE_MOVABLE_CONTAINER
@@ -164,8 +199,9 @@ enum { /* TYPEINFO flags */
Q_COMPLEX_TYPE = 0,
Q_PRIMITIVE_TYPE = 0x1,
Q_STATIC_TYPE = 0,
- Q_MOVABLE_TYPE = 0x2,
- Q_DUMMY_TYPE = 0x4
+ Q_MOVABLE_TYPE = 0x2, // ### Qt6: merge movable and relocatable once QList no longer depends on it
+ Q_DUMMY_TYPE = 0x4,
+ Q_RELOCATABLE_TYPE = 0x8
};
#define Q_DECLARE_TYPEINFO_BODY(TYPE, FLAGS) \
@@ -175,6 +211,7 @@ public: \
enum { \
isComplex = (((FLAGS) & Q_PRIMITIVE_TYPE) == 0), \
isStatic = (((FLAGS) & (Q_MOVABLE_TYPE | Q_PRIMITIVE_TYPE)) == 0), \
+ isRelocatable = !isStatic || ((FLAGS) & Q_RELOCATABLE_TYPE), \
isLarge = (sizeof(TYPE)>sizeof(void*)), \
isPointer = false, \
isIntegral = QtPrivate::is_integral< TYPE >::value, \
@@ -201,13 +238,22 @@ Q_DECLARE_TYPEINFO_BODY(QFlags<T>, Q_PRIMITIVE_TYPE);
where 'type' is the name of the type to specialize. NOTE: shared
types must define a member-swap, and be defined in the same
namespace as Qt for this to work.
+
+ If the type was already released without Q_DECLARE_SHARED applied,
+ _and_ without an explicit Q_DECLARE_TYPEINFO(type, Q_MOVABLE_TYPE),
+ then use Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(type) to mark the
+ type shared (incl. swap()), without marking it movable (which
+ would change the memory layout of QList, a BiC change.
*/
-#define Q_DECLARE_SHARED(TYPE) \
-Q_DECLARE_TYPEINFO(TYPE, Q_MOVABLE_TYPE); \
+#define Q_DECLARE_SHARED_IMPL(TYPE, FLAGS) \
+Q_DECLARE_TYPEINFO(TYPE, FLAGS); \
inline void swap(TYPE &value1, TYPE &value2) \
Q_DECL_NOEXCEPT_EXPR(noexcept(value1.swap(value2))) \
{ value1.swap(value2); }
+#define Q_DECLARE_SHARED(TYPE) Q_DECLARE_SHARED_IMPL(TYPE, Q_MOVABLE_TYPE)
+#define Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(TYPE) \
+ Q_DECLARE_SHARED_IMPL(TYPE, QT_VERSION >= QT_VERSION_CHECK(6,0,0) ? Q_MOVABLE_TYPE : Q_RELOCATABLE_TYPE)
/*
QTypeInfo primitive specializations
diff --git a/src/corelib/io/forkfd_qt.cpp b/src/corelib/io/forkfd_qt.cpp
index 6704ec6f2a..b226332cc1 100644
--- a/src/corelib/io/forkfd_qt.cpp
+++ b/src/corelib/io/forkfd_qt.cpp
@@ -32,13 +32,6 @@
****************************************************************************/
// these might be defined via precompiled headers
-#ifndef _POSIX_C_SOURCE
-# define _POSIX_C_SOURCE 200809L
-#endif
-#if !defined(_XOPEN_SOURCE) && !defined(__QNXNTO__) && !defined(ANDROID)
-# define _XOPEN_SOURCE 700
-#endif
-
#include <QtCore/qatomic.h>
#include "qprocess_p.h"
diff --git a/src/corelib/io/qabstractfileengine.cpp b/src/corelib/io/qabstractfileengine.cpp
index 07270eb790..2ab789e0af 100644
--- a/src/corelib/io/qabstractfileengine.cpp
+++ b/src/corelib/io/qabstractfileengine.cpp
@@ -891,7 +891,6 @@ bool QAbstractFileEngine::unmap(uchar *address)
/*!
\typedef QAbstractFileEngine::Iterator
\since 4.3
- \relates QAbstractFileEngine
Synonym for QAbstractFileEngineIterator.
*/
diff --git a/src/corelib/io/qbuffer.h b/src/corelib/io/qbuffer.h
index 1b2758d040..233c702213 100644
--- a/src/corelib/io/qbuffer.h
+++ b/src/corelib/io/qbuffer.h
@@ -51,8 +51,8 @@ class Q_CORE_EXPORT QBuffer : public QIODevice
public:
#ifndef QT_NO_QOBJECT
- explicit QBuffer(QObject *parent = 0);
- QBuffer(QByteArray *buf, QObject *parent = 0);
+ explicit QBuffer(QObject *parent = Q_NULLPTR);
+ QBuffer(QByteArray *buf, QObject *parent = Q_NULLPTR);
#else
QBuffer();
explicit QBuffer(QByteArray *buf);
diff --git a/src/corelib/io/qdatastream.cpp b/src/corelib/io/qdatastream.cpp
index 48672db2e9..713b5a2f55 100644
--- a/src/corelib/io/qdatastream.cpp
+++ b/src/corelib/io/qdatastream.cpp
@@ -526,6 +526,7 @@ void QDataStream::setByteOrder(ByteOrder bo)
\value Qt_5_3 Same as Qt_5_2
\value Qt_5_4 Version 16 (Qt 5.4)
\value Qt_5_5 Same as Qt_5_4
+ \value Qt_5_6 Same as Qt_5_4
\omitvalue Qt_DefaultCompiledVersion
\sa setVersion(), version()
diff --git a/src/corelib/io/qdatastream.h b/src/corelib/io/qdatastream.h
index 436bf8dd57..b87dbe4784 100644
--- a/src/corelib/io/qdatastream.h
+++ b/src/corelib/io/qdatastream.h
@@ -83,10 +83,11 @@ public:
Qt_5_3 = Qt_5_2,
Qt_5_4 = 16,
Qt_5_5 = Qt_5_4,
-#if QT_VERSION >= 0x050600
+ Qt_5_6 = Qt_5_5,
+#if QT_VERSION >= 0x050700
#error Add the datastream version for this Qt version and update Qt_DefaultCompiledVersion
#endif
- Qt_DefaultCompiledVersion = Qt_5_5
+ Qt_DefaultCompiledVersion = Qt_5_6
};
enum ByteOrder {
diff --git a/src/corelib/io/qdebug.cpp b/src/corelib/io/qdebug.cpp
index 30086b2dac..54a705b72b 100644
--- a/src/corelib/io/qdebug.cpp
+++ b/src/corelib/io/qdebug.cpp
@@ -351,6 +351,7 @@ QDebug &QDebug::resetFormat()
stream->space = true;
if (stream->context.version > 1)
stream->flags = 0;
+ stream->setVerbosity(Stream::defaultVerbosity);
return *this;
}
@@ -444,6 +445,32 @@ QDebug &QDebug::resetFormat()
*/
/*!
+ \fn int QDebug::verbosity() const
+ \since 5.6
+
+ Returns the verbosity of the debug stream.
+
+ Streaming operators can check the value to decide whether
+ verbose output is desired and print more information depending on the
+ level. Higher values indicate that more information is desired.
+
+ The allowed range is from 0 to 7. The default value is 2.
+
+ \sa setVerbosity()
+*/
+
+/*!
+ \fn void QDebug::setVerbosity(int verbosityLevel)
+ \since 5.6
+
+ Sets the verbosity of the stream to \a verbosityLevel.
+
+ The allowed range is from 0 to 7. The default value is 2.
+
+ \sa verbosity()
+*/
+
+/*!
\fn QDebug &QDebug::operator<<(QChar t)
Writes the character, \a t, to the stream and returns a reference to the
diff --git a/src/corelib/io/qdebug.h b/src/corelib/io/qdebug.h
index 3c3ceba249..2f626dfc1f 100644
--- a/src/corelib/io/qdebug.h
+++ b/src/corelib/io/qdebug.h
@@ -53,9 +53,14 @@ class Q_CORE_EXPORT QDebug
friend class QMessageLogger;
friend class QDebugStateSaverPrivate;
struct Stream {
- Stream(QIODevice *device) : ts(device), ref(1), type(QtDebugMsg), space(true), message_output(false), flags(0) {}
- Stream(QString *string) : ts(string, QIODevice::WriteOnly), ref(1), type(QtDebugMsg), space(true), message_output(false), flags(0) {}
- Stream(QtMsgType t) : ts(&buffer, QIODevice::WriteOnly), ref(1), type(t), space(true), message_output(true), flags(0) {}
+ enum { defaultVerbosity = 2, verbosityShift = 29, verbosityMask = 0x7 };
+
+ Stream(QIODevice *device) : ts(device), ref(1), type(QtDebugMsg),
+ space(true), message_output(false), flags(defaultVerbosity << verbosityShift) {}
+ Stream(QString *string) : ts(string, QIODevice::WriteOnly), ref(1), type(QtDebugMsg),
+ space(true), message_output(false), flags(defaultVerbosity << verbosityShift) {}
+ Stream(QtMsgType t) : ts(&buffer, QIODevice::WriteOnly), ref(1), type(t),
+ space(true), message_output(true), flags(defaultVerbosity << verbosityShift) {}
QTextStream ts;
QString buffer;
int ref;
@@ -64,7 +69,7 @@ class Q_CORE_EXPORT QDebug
bool message_output;
QMessageLogContext context;
- enum FormatFlag {
+ enum FormatFlag { // Note: Bits 29..31 are reserved for the verbose level introduced in 5.6.
NoQuotes = 0x1
};
@@ -72,7 +77,15 @@ class Q_CORE_EXPORT QDebug
bool testFlag(FormatFlag flag) const { return (context.version > 1) ? (flags & flag) : false; }
void setFlag(FormatFlag flag) { if (context.version > 1) { flags |= flag; } }
void unsetFlag(FormatFlag flag) { if (context.version > 1) { flags &= ~flag; } }
-
+ int verbosity() const
+ { return context.version > 1 ? (flags >> verbosityShift) & verbosityMask : int(Stream::defaultVerbosity); }
+ void setVerbosity(int v)
+ {
+ if (context.version > 1) {
+ flags &= ~(verbosityMask << verbosityShift);
+ flags |= (v & verbosityMask) << verbosityShift;
+ }
+ }
// added in 5.4
int flags;
} *stream;
@@ -96,6 +109,8 @@ public:
inline QDebug &space() { stream->space = true; stream->ts << ' '; return *this; }
inline QDebug &nospace() { stream->space = false; return *this; }
inline QDebug &maybeSpace() { if (stream->space) stream->ts << ' '; return *this; }
+ int verbosity() const { return stream->verbosity(); }
+ void setVerbosity(int verbosityLevel) { stream->setVerbosity(verbosityLevel); }
bool autoInsertSpaces() const { return stream->space; }
void setAutoInsertSpaces(bool b) { stream->space = b; }
diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp
index f6e132708e..e1d9858a66 100644
--- a/src/corelib/io/qdir.cpp
+++ b/src/corelib/io/qdir.cpp
@@ -1836,6 +1836,8 @@ QFileInfoList QDir::drives()
underlying operating system. If you want to display paths to the
user using their operating system's separator use
toNativeSeparators().
+
+ \sa listSeparator()
*/
QChar QDir::separator()
{
@@ -1847,6 +1849,16 @@ QChar QDir::separator()
}
/*!
+ \fn QDir::listSeparator()
+ \since 5.6
+
+ Returns the native path list separator: ':' under Unix
+ and ';' under Windows.
+
+ \sa separator()
+*/
+
+/*!
Sets the application's current working directory to \a path.
Returns \c true if the directory was successfully changed; otherwise
returns \c false.
diff --git a/src/corelib/io/qdir.h b/src/corelib/io/qdir.h
index e622011f98..ab3a331229 100644
--- a/src/corelib/io/qdir.h
+++ b/src/corelib/io/qdir.h
@@ -101,11 +101,10 @@ public:
QDir &operator=(const QDir &);
QDir &operator=(const QString &path);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QDir &operator=(QDir &&other)
- { qSwap(d_ptr, other.d_ptr); return *this; }
+ QDir &operator=(QDir &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QDir &other)
+ void swap(QDir &other) Q_DECL_NOTHROW
{ qSwap(d_ptr, other.d_ptr); }
void setPath(const QString &path);
@@ -177,7 +176,16 @@ public:
static QFileInfoList drives();
- static QChar separator();
+ Q_DECL_CONSTEXPR static inline QChar listSeparator() Q_DECL_NOTHROW
+ {
+#if defined(Q_OS_WIN)
+ return QLatin1Char(';');
+#else
+ return QLatin1Char(':');
+#endif
+ }
+
+ static QChar separator(); // ### Qt6: Make it inline
static bool setCurrent(const QString &path);
static inline QDir current() { return QDir(currentPath()); }
diff --git a/src/corelib/io/qfile.h b/src/corelib/io/qfile.h
index 35a73680af..4eac710d4c 100644
--- a/src/corelib/io/qfile.h
+++ b/src/corelib/io/qfile.h
@@ -134,7 +134,7 @@ protected:
#ifdef QT_NO_QOBJECT
QFile(QFilePrivate &dd);
#else
- QFile(QFilePrivate &dd, QObject *parent = 0);
+ QFile(QFilePrivate &dd, QObject *parent = Q_NULLPTR);
#endif
private:
diff --git a/src/corelib/io/qfiledevice.cpp b/src/corelib/io/qfiledevice.cpp
index 3ee0e33573..4c5ed0aef6 100644
--- a/src/corelib/io/qfiledevice.cpp
+++ b/src/corelib/io/qfiledevice.cpp
@@ -481,7 +481,7 @@ bool QFileDevicePrivate::putCharHelper(char c)
#else
// Cutoff for code that doesn't only touch the buffer.
- int writeBufferSize = writeBuffer.size();
+ qint64 writeBufferSize = writeBuffer.size();
if ((openMode & QIODevice::Unbuffered) || writeBufferSize + 1 >= QFILE_WRITEBUFFER_SIZE
#ifdef Q_OS_WIN
|| ((openMode & QIODevice::Text) && c == '\n' && writeBufferSize + 2 >= QFILE_WRITEBUFFER_SIZE)
diff --git a/src/corelib/io/qfiledevice.h b/src/corelib/io/qfiledevice.h
index e9320d8d31..afa42bd86b 100644
--- a/src/corelib/io/qfiledevice.h
+++ b/src/corelib/io/qfiledevice.h
@@ -119,7 +119,7 @@ protected:
QFileDevice(QFileDevicePrivate &dd);
#else
explicit QFileDevice(QObject *parent);
- QFileDevice(QFileDevicePrivate &dd, QObject *parent = 0);
+ QFileDevice(QFileDevicePrivate &dd, QObject *parent = Q_NULLPTR);
#endif
qint64 readData(char *data, qint64 maxlen) Q_DECL_OVERRIDE;
diff --git a/src/corelib/io/qfileinfo.h b/src/corelib/io/qfileinfo.h
index 58cf9a5c0f..59d12c3883 100644
--- a/src/corelib/io/qfileinfo.h
+++ b/src/corelib/io/qfileinfo.h
@@ -62,11 +62,10 @@ public:
QFileInfo &operator=(const QFileInfo &fileinfo);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QFileInfo&operator=(QFileInfo &&other)
- { qSwap(d_ptr, other.d_ptr); return *this; }
+ QFileInfo &operator=(QFileInfo &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QFileInfo &other)
+ void swap(QFileInfo &other) Q_DECL_NOTHROW
{ qSwap(d_ptr, other.d_ptr); }
bool operator==(const QFileInfo &fileinfo) const;
diff --git a/src/corelib/io/qfileselector.h b/src/corelib/io/qfileselector.h
index 967d5eee75..9ee3588780 100644
--- a/src/corelib/io/qfileselector.h
+++ b/src/corelib/io/qfileselector.h
@@ -44,7 +44,7 @@ class Q_CORE_EXPORT QFileSelector : public QObject
{
Q_OBJECT
public:
- explicit QFileSelector(QObject *parent = 0);
+ explicit QFileSelector(QObject *parent = Q_NULLPTR);
~QFileSelector();
QString select(const QString &filePath) const;
diff --git a/src/corelib/io/qfilesystemengine_win.cpp b/src/corelib/io/qfilesystemengine_win.cpp
index d62c120d7e..379095a83d 100644
--- a/src/corelib/io/qfilesystemengine_win.cpp
+++ b/src/corelib/io/qfilesystemengine_win.cpp
@@ -407,7 +407,7 @@ static QString readLink(const QFileSystemEntry &link)
Q_UNUSED(link);
return QString();
#endif // QT_NO_LIBRARY
-#else
+#elif !defined(QT_NO_WINCE_SHELLSDK)
wchar_t target[MAX_PATH];
QString result;
if (SHGetShortcutTarget((wchar_t*)QFileInfo(link.filePath()).absoluteFilePath().replace(QLatin1Char('/'),QLatin1Char('\\')).utf16(), target, MAX_PATH)) {
@@ -418,6 +418,9 @@ static QString readLink(const QFileSystemEntry &link)
result.remove(result.size()-1,1);
}
return result;
+#else // QT_NO_WINCE_SHELLSDK
+ Q_UNUSED(link);
+ return QString();
#endif // Q_OS_WINCE
}
diff --git a/src/corelib/io/qfilesystemwatcher.h b/src/corelib/io/qfilesystemwatcher.h
index 13d1782913..095b50d1e5 100644
--- a/src/corelib/io/qfilesystemwatcher.h
+++ b/src/corelib/io/qfilesystemwatcher.h
@@ -49,8 +49,8 @@ class Q_CORE_EXPORT QFileSystemWatcher : public QObject
Q_DECLARE_PRIVATE(QFileSystemWatcher)
public:
- QFileSystemWatcher(QObject *parent = 0);
- QFileSystemWatcher(const QStringList &paths, QObject *parent = 0);
+ QFileSystemWatcher(QObject *parent = Q_NULLPTR);
+ QFileSystemWatcher(const QStringList &paths, QObject *parent = Q_NULLPTR);
~QFileSystemWatcher();
bool addPath(const QString &file);
diff --git a/src/corelib/io/qfilesystemwatcher_fsevents.mm b/src/corelib/io/qfilesystemwatcher_fsevents.mm
index 8a028c91e1..7656530a46 100644
--- a/src/corelib/io/qfilesystemwatcher_fsevents.mm
+++ b/src/corelib/io/qfilesystemwatcher_fsevents.mm
@@ -56,25 +56,6 @@
QT_BEGIN_NAMESPACE
-namespace {
-class RaiiAutoreleasePool
-{
- Q_DISABLE_COPY(RaiiAutoreleasePool)
-
-public:
- RaiiAutoreleasePool()
- : pool([[NSAutoreleasePool alloc] init])
- {}
-
- ~RaiiAutoreleasePool()
- { [pool release]; }
-
-private:
- NSAutoreleasePool *pool;
-};
-#define Q_AUTORELEASE_POOL(pool) RaiiAutoreleasePool pool; Q_UNUSED(pool);
-}
-
static void callBackFunction(ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
@@ -82,7 +63,7 @@ static void callBackFunction(ConstFSEventStreamRef streamRef,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
char **paths = static_cast<char **>(eventPaths);
QFseventsFileSystemWatcherEngine *engine = static_cast<QFseventsFileSystemWatcherEngine *>(clientCallBackInfo);
@@ -297,7 +278,7 @@ void QFseventsFileSystemWatcherEngine::doEmitDirectoryChanged(const QString &pat
void QFseventsFileSystemWatcherEngine::restartStream()
{
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
QMutexLocker locker(&lock);
stopStream();
startStream();
@@ -328,7 +309,7 @@ QFseventsFileSystemWatcherEngine::QFseventsFileSystemWatcherEngine(QObject *pare
QFseventsFileSystemWatcherEngine::~QFseventsFileSystemWatcherEngine()
{
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
if (stream)
FSEventStreamStop(stream);
@@ -344,7 +325,7 @@ QStringList QFseventsFileSystemWatcherEngine::addPaths(const QStringList &paths,
QStringList *files,
QStringList *directories)
{
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
if (stream) {
DEBUG("Flushing, last id is %llu", FSEventStreamGetLatestEventId(stream));
@@ -432,7 +413,7 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat
QStringList *files,
QStringList *directories)
{
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
QMutexLocker locker(&lock);
@@ -489,7 +470,7 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat
bool QFseventsFileSystemWatcherEngine::startStream()
{
Q_ASSERT(stream == 0);
- Q_AUTORELEASE_POOL(pool)
+ QMacAutoReleasePool pool;
if (stream) // This shouldn't happen, but let's be nice and handle it.
stopStream();
diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp
index 19343f22ff..cfd50955a6 100644
--- a/src/corelib/io/qfsfileengine_win.cpp
+++ b/src/corelib/io/qfsfileengine_win.cpp
@@ -711,7 +711,7 @@ bool QFSFileEngine::link(const QString &newName)
Q_UNUSED(newName);
return false;
#endif // QT_NO_LIBRARY
-#elif defined(Q_OS_WINCE)
+#elif defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_SHELLSDK)
QString linkName = newName;
linkName.replace(QLatin1Char('/'), QLatin1Char('\\'));
if (!linkName.endsWith(QLatin1String(".lnk")))
@@ -724,7 +724,7 @@ bool QFSFileEngine::link(const QString &newName)
if (!ret)
setError(QFile::RenameError, qt_error_string());
return ret;
-#else // Q_OS_WINCE
+#else // Q_OS_WINCE && !QT_NO_WINCE_SHELLSDK
Q_UNUSED(newName);
Q_UNIMPLEMENTED();
return false;
diff --git a/src/corelib/io/qiodevice.cpp b/src/corelib/io/qiodevice.cpp
index b908ae3145..84a6a1d9cb 100644
--- a/src/corelib/io/qiodevice.cpp
+++ b/src/corelib/io/qiodevice.cpp
@@ -39,6 +39,7 @@
#include "qfile.h"
#include "qstringlist.h"
#include "qdir.h"
+#include "private/qbytearray_p.h"
#include <algorithm>
@@ -138,7 +139,6 @@ QIODevicePrivate::QIODevicePrivate()
: openMode(QIODevice::NotOpen), buffer(QIODEVICE_BUFFERSIZE),
pos(0), devicePos(0)
, baseReadLineDataCalled(false)
- , firstRead(true)
, accessMode(Unset)
#ifdef QT_NO_QOBJECT
, q_ptr(0)
@@ -463,7 +463,6 @@ void QIODevice::setOpenMode(OpenMode openMode)
#endif
d->openMode = openMode;
d->accessMode = QIODevicePrivate::Unset;
- d->firstRead = true;
if (!isReadable())
d->buffer.clear();
}
@@ -555,7 +554,6 @@ bool QIODevice::open(OpenMode mode)
d->pos = (mode & Append) ? size() : qint64(0);
d->buffer.clear();
d->accessMode = QIODevicePrivate::Unset;
- d->firstRead = true;
#if defined QIODEVICE_DEBUG
printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
#endif
@@ -585,7 +583,6 @@ void QIODevice::close()
d->errorString.clear();
d->pos = 0;
d->buffer.clear();
- d->firstRead = true;
}
/*!
@@ -692,12 +689,13 @@ bool QIODevice::seek(qint64 pos)
bool QIODevice::atEnd() const
{
Q_D(const QIODevice);
+ const bool result = (d->openMode == NotOpen || (d->buffer.isEmpty()
+ && bytesAvailable() == 0));
#if defined QIODEVICE_DEBUG
printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %lld\n", this,
- (d->openMode == NotOpen || d->pos == size()) ? "true" : "false", int(d->openMode),
- d->pos);
+ result ? "true" : "false", int(d->openMode), d->pos);
#endif
- return d->openMode == NotOpen || (d->buffer.isEmpty() && bytesAvailable() == 0);
+ return result;
}
/*!
@@ -814,12 +812,7 @@ qint64 QIODevice::read(char *data, qint64 maxSize)
bufferReadChunkSize, readSoFar - bufferReadChunkSize);
#endif
} else {
- if (d->firstRead) {
- // this is the first time the file has been read, check it's valid and set up pos pointers
- // for fast pos updates.
- CHECK_READABLE(read, qint64(-1));
- d->firstRead = false;
- }
+ CHECK_READABLE(read, qint64(-1));
}
if (maxSize > 0 && !deviceAtEof) {
@@ -941,9 +934,9 @@ QByteArray QIODevice::read(qint64 maxSize)
Q_UNUSED(d);
#endif
- if (quint64(maxSize) >= QByteArray::MaxSize) {
+ if (maxSize >= MaxByteArraySize) {
checkWarnMessage(this, "read", "maxSize argument exceeds QByteArray size limit");
- maxSize = QByteArray::MaxSize - 1;
+ maxSize = MaxByteArraySize - 1;
}
qint64 readBytes = 0;
@@ -990,40 +983,31 @@ QByteArray QIODevice::readAll()
#endif
QByteArray result;
- qint64 readBytes = 0;
- const bool sequential = d->isSequential();
-
- // flush internal read buffer
- if (!(d->openMode & Text) && !d->buffer.isEmpty()) {
- if (quint64(d->buffer.size()) >= QByteArray::MaxSize)
- return QByteArray();
- result = d->buffer.readAll();
- readBytes = result.size();
- if (!sequential)
- d->pos += readBytes;
- }
-
- qint64 theSize;
- if (sequential || (theSize = size()) == 0) {
+ qint64 readBytes = (d->isSequential() ? Q_INT64_C(0) : size());
+ if (readBytes == 0) {
// Size is unknown, read incrementally.
+ qint64 readChunkSize = qMax(d->buffer.size(), QIODEVICE_BUFFERSIZE);
qint64 readResult;
do {
- if (quint64(readBytes) + QIODEVICE_BUFFERSIZE > QByteArray::MaxSize) {
+ if (readBytes + readChunkSize >= MaxByteArraySize) {
// If resize would fail, don't read more, return what we have.
break;
}
- result.resize(readBytes + QIODEVICE_BUFFERSIZE);
- readResult = read(result.data() + readBytes, QIODEVICE_BUFFERSIZE);
- if (readResult > 0 || readBytes == 0)
+ result.resize(readBytes + readChunkSize);
+ readResult = read(result.data() + readBytes, readChunkSize);
+ if (readResult > 0 || readBytes == 0) {
readBytes += readResult;
+ readChunkSize = QIODEVICE_BUFFERSIZE;
+ }
} while (readResult > 0);
} else {
// Read it all in one go.
// If resize fails, don't read anything.
- if (quint64(readBytes + theSize - d->pos) > QByteArray::MaxSize)
+ readBytes -= d->pos;
+ if (readBytes >= MaxByteArraySize)
return QByteArray();
- result.resize(int(readBytes + theSize - d->pos));
- readBytes += read(result.data() + readBytes, result.size() - readBytes);
+ result.resize(readBytes);
+ readBytes = read(result.data(), readBytes);
}
if (readBytes <= 0)
@@ -1178,9 +1162,9 @@ QByteArray QIODevice::readLine(qint64 maxSize)
Q_UNUSED(d);
#endif
- if (quint64(maxSize) >= QByteArray::MaxSize) {
+ if (maxSize >= MaxByteArraySize) {
qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
- maxSize = QByteArray::MaxSize - 1;
+ maxSize = MaxByteArraySize - 1;
}
result.resize(int(maxSize));
@@ -1188,7 +1172,7 @@ QByteArray QIODevice::readLine(qint64 maxSize)
if (!result.size()) {
// If resize fails or maxSize == 0, read incrementally
if (maxSize == 0)
- maxSize = QByteArray::MaxSize - 1;
+ maxSize = MaxByteArraySize - 1;
// The first iteration needs to leave an extra byte for the terminating null
result.resize(1);
diff --git a/src/corelib/io/qiodevice.h b/src/corelib/io/qiodevice.h
index 4f45805fca..b62c8d266c 100644
--- a/src/corelib/io/qiodevice.h
+++ b/src/corelib/io/qiodevice.h
@@ -140,7 +140,7 @@ protected:
#ifdef QT_NO_QOBJECT
QIODevice(QIODevicePrivate &dd);
#else
- QIODevice(QIODevicePrivate &dd, QObject *parent = 0);
+ QIODevice(QIODevicePrivate &dd, QObject *parent = Q_NULLPTR);
#endif
virtual qint64 readData(char *data, qint64 maxlen) = 0;
virtual qint64 readLineData(char *data, qint64 maxlen);
diff --git a/src/corelib/io/qiodevice_p.h b/src/corelib/io/qiodevice_p.h
index f4cf387eb5..56a89ab680 100644
--- a/src/corelib/io/qiodevice_p.h
+++ b/src/corelib/io/qiodevice_p.h
@@ -212,7 +212,6 @@ public:
qint64 pos;
qint64 devicePos;
bool baseReadLineDataCalled;
- bool firstRead;
virtual bool putCharHelper(char c);
diff --git a/src/corelib/io/qlockfile_unix.cpp b/src/corelib/io/qlockfile_unix.cpp
index 815c0f025b..27f8a97fd4 100644
--- a/src/corelib/io/qlockfile_unix.cpp
+++ b/src/corelib/io/qlockfile_unix.cpp
@@ -241,6 +241,7 @@ QString QLockFilePrivate::processNameByPid(qint64 pid)
free(proc);
return name;
#else
+ Q_UNUSED(pid);
return QString();
#endif
}
diff --git a/src/corelib/io/qloggingcategory.cpp b/src/corelib/io/qloggingcategory.cpp
index e6bc7caaeb..b51085ef42 100644
--- a/src/corelib/io/qloggingcategory.cpp
+++ b/src/corelib/io/qloggingcategory.cpp
@@ -147,8 +147,17 @@ static void setBoolLane(QBasicAtomicInt *atomic, bool enable, int shift)
\c QT_LOGGING_CONF, and rules set by \c QT_LOGGING_RULES.
+ Since Qt 5.6, \c QT_LOGGING_RULES may contain multiple rules separated
+ by semicolons:
+
+ \code
+ QT_LOGGING_RULES="*.debug=false;driver.usb.debug=true"
+ \endcode
+
+
Order of evaluation:
\list
+ \li [QLibraryInfo::DataPath]/qtlogging.ini
\li QtProject/qtlogging.ini
\li \l setFilterRules()
\li \c QT_LOGGING_CONF
diff --git a/src/corelib/io/qloggingregistry.cpp b/src/corelib/io/qloggingregistry.cpp
index 880e567562..b53e251102 100644
--- a/src/corelib/io/qloggingregistry.cpp
+++ b/src/corelib/io/qloggingregistry.cpp
@@ -34,6 +34,7 @@
#include "qloggingregistry_p.h"
#include <QtCore/qfile.h>
+#include <QtCore/qlibraryinfo.h>
#include <QtCore/qstandardpaths.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qdir.h>
@@ -208,7 +209,7 @@ void QLoggingSettingsParser::setContent(QTextStream &stream)
continue;
}
- if (_section == QLatin1String("Rules")) {
+ if (_section.toLower() == QLatin1String("rules")) {
int equalPos = line.indexOf(QLatin1Char('='));
if (equalPos != -1) {
if (line.lastIndexOf(QLatin1Char('=')) == equalPos) {
@@ -247,6 +248,21 @@ static bool qtLoggingDebug()
return debugEnv;
}
+static QVector<QLoggingRule> loadRulesFromFile(const QString &filePath)
+{
+ QFile file(filePath);
+ if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ if (qtLoggingDebug())
+ debugMsg("Loading \"%s\" ...",
+ QDir::toNativeSeparators(file.fileName()).toUtf8().constData());
+ QTextStream stream(&file);
+ QLoggingSettingsParser parser;
+ parser.setContent(stream);
+ return parser.rules();
+ }
+ return QVector<QLoggingRule>();
+}
+
/*!
\internal
Initializes the rules database by loading
@@ -256,19 +272,10 @@ void QLoggingRegistry::init()
{
// get rules from environment
const QByteArray rulesFilePath = qgetenv("QT_LOGGING_CONF");
- if (!rulesFilePath.isEmpty()) {
- QFile file(QFile::decodeName(rulesFilePath));
- if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- if (qtLoggingDebug())
- debugMsg("Loading \"%s\" ...",
- QDir::toNativeSeparators(file.fileName()).toUtf8().constData());
- QTextStream stream(&file);
- QLoggingSettingsParser parser;
- parser.setContent(stream);
- envRules = parser.rules();
- }
- }
- const QByteArray rulesSrc = qgetenv("QT_LOGGING_RULES");
+ if (!rulesFilePath.isEmpty())
+ envRules = loadRulesFromFile(QFile::decodeName(rulesFilePath));
+
+ const QByteArray rulesSrc = qgetenv("QT_LOGGING_RULES").replace(';', '\n');
if (!rulesSrc.isEmpty()) {
QTextStream stream(rulesSrc);
QLoggingSettingsParser parser;
@@ -277,23 +284,22 @@ void QLoggingRegistry::init()
envRules += parser.rules();
}
- // get rules from qt configuration
- QString envPath = QStandardPaths::locate(QStandardPaths::GenericConfigLocation,
- QStringLiteral("QtProject/qtlogging.ini"));
- if (!envPath.isEmpty()) {
- QFile file(envPath);
- if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- if (qtLoggingDebug())
- debugMsg("Loading \"%s\" ...",
- QDir::toNativeSeparators(envPath).toUtf8().constData());
- QTextStream stream(&file);
- QLoggingSettingsParser parser;
- parser.setContent(stream);
- configRules = parser.rules();
- }
- }
+ const QString configFileName = QStringLiteral("qtlogging.ini");
+
+#if !defined(QT_BOOTSTRAPPED)
+ // get rules from Qt data configuration path
+ const QString qtConfigPath
+ = QDir(QLibraryInfo::location(QLibraryInfo::DataPath)).absoluteFilePath(configFileName);
+ qtConfigRules = loadRulesFromFile(qtConfigPath);
+#endif
+
+ // get rules from user's/system configuration
+ const QString envPath = QStandardPaths::locate(QStandardPaths::GenericConfigLocation,
+ QString::fromLatin1("QtProject/") + configFileName);
+ if (!envPath.isEmpty())
+ configRules = loadRulesFromFile(envPath);
- if (!envRules.isEmpty() || !configRules.isEmpty()) {
+ if (!envRules.isEmpty() || !qtConfigRules.isEmpty() || !configRules.isEmpty()) {
QMutexLocker locker(&registryMutex);
updateRules();
}
@@ -356,7 +362,7 @@ void QLoggingRegistry::updateRules()
if (categoryFilter != defaultCategoryFilter)
return;
- rules = configRules + apiRules + envRules;
+ rules = qtConfigRules + configRules + apiRules + envRules;
foreach (QLoggingCategory *cat, categories.keys())
(*categoryFilter)(cat);
diff --git a/src/corelib/io/qloggingregistry_p.h b/src/corelib/io/qloggingregistry_p.h
index 718e09d9bb..bb32a4996d 100644
--- a/src/corelib/io/qloggingregistry_p.h
+++ b/src/corelib/io/qloggingregistry_p.h
@@ -122,6 +122,7 @@ private:
QMutex registryMutex;
+ QVector<QLoggingRule> qtConfigRules;
QVector<QLoggingRule> configRules;
QVector<QLoggingRule> envRules;
QVector<QLoggingRule> apiRules;
diff --git a/src/corelib/io/qprocess.cpp b/src/corelib/io/qprocess.cpp
index c29b97b535..8ee8d0b703 100644
--- a/src/corelib/io/qprocess.cpp
+++ b/src/corelib/io/qprocess.cpp
@@ -101,6 +101,19 @@ QT_END_NAMESPACE
QT_BEGIN_NAMESPACE
/*!
+ \since 5.6
+
+ \macro QT_NO_PROCESS_COMBINED_ARGUMENT_START
+ \relates QProcess
+
+ Disables the QProcess::start() overload taking a single string.
+ In most cases where it is used, the user intends for the first argument
+ to be treated atomically as per the other overload.
+
+ \sa QProcess::start()
+*/
+
+/*!
\class QProcessEnvironment
\inmodule QtCore
@@ -110,7 +123,6 @@ QT_BEGIN_NAMESPACE
\ingroup io
\ingroup misc
\ingroup shared
- \mainclass
\reentrant
\since 4.6
@@ -265,11 +277,16 @@ bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const
{
if (d == other.d)
return true;
- if (d && other.d) {
- QProcessEnvironmentPrivate::OrderedMutexLocker locker(d, other.d);
- return d->hash == other.d->hash;
+ if (d) {
+ if (other.d) {
+ QProcessEnvironmentPrivate::OrderedMutexLocker locker(d, other.d);
+ return d->hash == other.d->hash;
+ } else {
+ return isEmpty();
+ }
+ } else {
+ return other.isEmpty();
}
- return false;
}
/*!
@@ -498,8 +515,8 @@ void QProcessPrivate::Channel::clear()
the process as arguments, and you can also call exitCode() to
obtain the exit code of the last process that finished, and
exitStatus() to obtain its exit status. If an error occurs at
- any point in time, QProcess will emit the error() signal. You
- can also call error() to find the type of error that occurred
+ any point in time, QProcess will emit the errorOccurred() signal.
+ You can also call error() to find the type of error that occurred
last, and state() to find the current process state.
\section1 Communicating via Channels
@@ -736,6 +753,14 @@ void QProcessPrivate::Channel::clear()
/*!
\fn void QProcess::error(QProcess::ProcessError error)
+ \obsolete
+
+ Use errorOccurred() instead.
+*/
+
+/*!
+ \fn void QProcess::errorOccurred(QProcess::ProcessError error)
+ \since 5.6
This signal is emitted when an error occurs with the process. The
specified \a error describes the type of error that occurred.
@@ -898,6 +923,50 @@ void QProcessPrivate::cleanup()
/*!
\internal
+*/
+void QProcessPrivate::setError(QProcess::ProcessError error, const QString &description)
+{
+ processError = error;
+ if (description.isEmpty()) {
+ switch (error) {
+ case QProcess::FailedToStart:
+ errorString = QProcess::tr("Process failed to start");
+ break;
+ case QProcess::Crashed:
+ errorString = QProcess::tr("Process crashed");
+ break;
+ case QProcess::Timedout:
+ errorString = QProcess::tr("Process operation timed out");
+ break;
+ case QProcess::ReadError:
+ errorString = QProcess::tr("Error reading from process");
+ break;
+ case QProcess::WriteError:
+ errorString = QProcess::tr("Error writing to process");
+ break;
+ case QProcess::UnknownError:
+ errorString.clear();
+ break;
+ }
+ } else {
+ errorString = description;
+ }
+}
+
+/*!
+ \internal
+*/
+void QProcessPrivate::setErrorAndEmit(QProcess::ProcessError error, const QString &description)
+{
+ Q_Q(QProcess);
+ Q_ASSERT(error != QProcess::UnknownError);
+ setError(error, description);
+ emit q->errorOccurred(processError);
+ emit q->error(processError);
+}
+
+/*!
+ \internal
Returns true if we emitted readyRead().
*/
bool QProcessPrivate::tryReadFromChannel(Channel *channel)
@@ -919,9 +988,7 @@ bool QProcessPrivate::tryReadFromChannel(Channel *channel)
return false;
}
if (readBytes == -1) {
- processError = QProcess::ReadError;
- q->setErrorString(QProcess::tr("Error reading from process"));
- emit q->error(processError);
+ setErrorAndEmit(QProcess::ReadError);
#if defined QPROCESS_DEBUG
qDebug("QProcessPrivate::tryReadFromChannel(%d), failed to read from the process", channel - &stdinChannel);
#endif
@@ -1005,9 +1072,7 @@ bool QProcessPrivate::_q_canWrite()
stdinChannel.buffer.nextDataBlockSize());
if (written < 0) {
closeChannel(&stdinChannel);
- processError = QProcess::WriteError;
- q->setErrorString(QProcess::tr("Error writing to process"));
- emit q->error(processError);
+ setErrorAndEmit(QProcess::WriteError);
return false;
}
@@ -1051,7 +1116,7 @@ bool QProcessPrivate::_q_processDied()
// the process may have died before it got a chance to report that it was
// either running or stopped, so we will call _q_startupNotification() and
- // give it a chance to emit started() or error(FailedToStart).
+ // give it a chance to emit started() or errorOccurred(FailedToStart).
if (processState == QProcess::Starting) {
if (!_q_startupNotification())
return true;
@@ -1076,9 +1141,7 @@ bool QProcessPrivate::_q_processDied()
if (crashed) {
exitStatus = QProcess::CrashExit;
- processError = QProcess::Crashed;
- q->setErrorString(QProcess::tr("Process crashed"));
- emit q->error(processError);
+ setErrorAndEmit(QProcess::Crashed);
} else {
#ifdef QPROCESS_USE_SPAWN
// if we're using posix_spawn, waitForStarted always succeeds.
@@ -1086,8 +1149,8 @@ bool QProcessPrivate::_q_processDied()
// 127 if anything prevents the target program from starting.
// http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_spawn.html
if (exitStatus == QProcess::NormalExit && exitCode == 127) {
- processError = QProcess::FailedToStart;
- q->setErrorString(QProcess::tr("Process failed to start (spawned process exited with code 127)"));
+ setError(QProcess::FailedToStart,
+ QProcess::tr("Process failed to start (spawned process exited with code 127)"));
}
#endif
}
@@ -1131,8 +1194,7 @@ bool QProcessPrivate::_q_startupNotification()
}
q->setProcessState(QProcess::NotRunning);
- processError = QProcess::FailedToStart;
- emit q->error(processError);
+ setErrorAndEmit(QProcess::FailedToStart);
#ifdef Q_OS_UNIX
// make sure the process manager removes this entry
waitForDeadChild();
@@ -1911,12 +1973,12 @@ qint64 QProcess::readData(char *data, qint64 maxlen)
return 1;
}
- qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
+ qint64 bytesToRead = qMin(readBuffer->size(), maxlen);
qint64 readSoFar = 0;
while (readSoFar < bytesToRead) {
const char *ptr = readBuffer->readPointer();
- int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
- readBuffer->nextDataBlockSize());
+ qint64 bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
+ readBuffer->nextDataBlockSize());
memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
readSoFar += bytesToReadFromThisBlock;
readBuffer->free(bytesToReadFromThisBlock);
@@ -1940,9 +2002,7 @@ qint64 QProcess::writeData(const char *data, qint64 len)
#if defined(Q_OS_WINCE)
Q_UNUSED(data);
Q_UNUSED(len);
- d->processError = QProcess::WriteError;
- setErrorString(tr("Error writing to process"));
- emit error(d->processError);
+ d->setErrorAndEmit(QProcess::WriteError);
return -1;
#endif
@@ -2033,10 +2093,10 @@ QByteArray QProcess::readAllStandardError()
The QProcess object will immediately enter the Starting state. If the
process starts successfully, QProcess will emit started(); otherwise,
- error() will be emitted.
+ errorOccurred() will be emitted.
\note Processes are started asynchronously, which means the started()
- and error() signals may be delayed. Call waitForStarted() to make
+ and errorOccurred() signals may be delayed. Call waitForStarted() to make
sure the process has started (or has failed to start) and those signals
have been emitted.
@@ -2147,6 +2207,16 @@ void QProcessPrivate::start(QIODevice::OpenMode mode)
mode &= ~QIODevice::ReadOnly; // not open for reading
if (mode == 0)
mode = QIODevice::Unbuffered;
+#ifndef Q_OS_WINCE
+ if ((mode & QIODevice::ReadOnly) == 0) {
+ if (stdoutChannel.type == QProcessPrivate::Channel::Normal)
+ q->setStandardOutputFile(q->nullDevice());
+ if (stderrChannel.type == QProcessPrivate::Channel::Normal
+ && processChannelMode != QProcess::MergedChannels)
+ q->setStandardErrorFile(q->nullDevice());
+ }
+#endif
+
q->QIODevice::open(mode);
stdinChannel.closed = false;
@@ -2226,15 +2296,26 @@ static QStringList parseCombinedArgString(const QString &program)
After the \a command string has been split and unquoted, this function
behaves like the overload which takes the arguments as a string list.
+ You can disable this overload by defining \c
+ QT_NO_PROCESS_COMBINED_ARGUMENT_START when you compile your applications.
+ This can be useful if you want to ensure that you are not splitting arguments
+ unintentionally, for example. In virtually all cases, using the other overload
+ is the preferred method.
+
+ On operating systems where the system API for passing command line
+ arguments to a subprocess natively uses a single string (Windows), one can
+ conceive command lines which cannot be passed via QProcess's portable
+ list-based API. In these rare cases you need to use setProgram() and
+ setNativeArguments() instead of this function.
+
*/
+#if !defined(QT_NO_PROCESS_COMBINED_ARGUMENT_START)
void QProcess::start(const QString &command, OpenMode mode)
{
QStringList args = parseCombinedArgString(command);
if (args.isEmpty()) {
Q_D(QProcess);
- d->processError = QProcess::FailedToStart;
- setErrorString(tr("No program defined"));
- emit error(d->processError);
+ d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
return;
}
@@ -2243,6 +2324,7 @@ void QProcess::start(const QString &command, OpenMode mode)
start(prog, args, mode);
}
+#endif
/*!
\since 5.0
diff --git a/src/corelib/io/qprocess.h b/src/corelib/io/qprocess.h
index 078217ea0b..f95358250e 100644
--- a/src/corelib/io/qprocess.h
+++ b/src/corelib/io/qprocess.h
@@ -60,9 +60,12 @@ public:
QProcessEnvironment();
QProcessEnvironment(const QProcessEnvironment &other);
~QProcessEnvironment();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QProcessEnvironment &operator=(QProcessEnvironment && other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QProcessEnvironment &operator=(const QProcessEnvironment &other);
- inline void swap(QProcessEnvironment &other) { qSwap(d, other.d); }
+ void swap(QProcessEnvironment &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QProcessEnvironment &other) const;
inline bool operator!=(const QProcessEnvironment &other) const
@@ -104,15 +107,21 @@ public:
WriteError,
UnknownError
};
+ Q_ENUM(ProcessError)
+
enum ProcessState {
NotRunning,
Starting,
Running
};
+ Q_ENUM(ProcessState)
+
enum ProcessChannel {
StandardOutput,
StandardError
};
+ Q_ENUM(ProcessChannel)
+
enum ProcessChannelMode {
SeparateChannels,
MergedChannels,
@@ -120,20 +129,27 @@ public:
ForwardedOutputChannel,
ForwardedErrorChannel
};
+ Q_ENUM(ProcessChannelMode)
+
enum InputChannelMode {
ManagedInputChannel,
ForwardedInputChannel
};
+ Q_ENUM(InputChannelMode)
+
enum ExitStatus {
NormalExit,
CrashExit
};
+ Q_ENUM(ExitStatus)
- explicit QProcess(QObject *parent = 0);
+ explicit QProcess(QObject *parent = Q_NULLPTR);
virtual ~QProcess();
void start(const QString &program, const QStringList &arguments, OpenMode mode = ReadWrite);
+#if !defined(QT_NO_PROCESS_COMBINED_ARGUMENT_START)
void start(const QString &command, OpenMode mode = ReadWrite);
+#endif
void start(OpenMode mode = ReadWrite);
bool open(OpenMode mode = ReadWrite) Q_DECL_OVERRIDE;
@@ -208,7 +224,7 @@ public:
#if defined(Q_QDOC)
= QString()
#endif
- , qint64 *pid = 0);
+ , qint64 *pid = Q_NULLPTR);
#if !defined(Q_QDOC)
static bool startDetached(const QString &program, const QStringList &arguments); // ### Qt6: merge overloads
#endif
@@ -226,7 +242,10 @@ Q_SIGNALS:
void started(QPrivateSignal);
void finished(int exitCode); // ### Qt 6: merge the two signals with a default value
void finished(int exitCode, QProcess::ExitStatus exitStatus);
- void error(QProcess::ProcessError error);
+#if QT_DEPRECATED_SINCE(5,6)
+ QT_MOC_COMPAT void error(QProcess::ProcessError error);
+#endif
+ void errorOccurred(QProcess::ProcessError error);
void stateChanged(QProcess::ProcessState state, QPrivateSignal);
void readyReadStandardOutput(QPrivateSignal);
diff --git a/src/corelib/io/qprocess_p.h b/src/corelib/io/qprocess_p.h
index f6bd64fb87..fc6b5345d1 100644
--- a/src/corelib/io/qprocess_p.h
+++ b/src/corelib/io/qprocess_p.h
@@ -383,6 +383,8 @@ public:
qint64 writeToStdin(const char *data, qint64 maxlen);
void cleanup();
+ void setError(QProcess::ProcessError error, const QString &description = QString());
+ void setErrorAndEmit(QProcess::ProcessError error, const QString &description = QString());
#ifdef Q_OS_BLACKBERRY
QList<QSocketNotifier *> defaultNotifiers() const;
diff --git a/src/corelib/io/qprocess_unix.cpp b/src/corelib/io/qprocess_unix.cpp
index 7b6da90b04..63480dfc6b 100644
--- a/src/corelib/io/qprocess_unix.cpp
+++ b/src/corelib/io/qprocess_unix.cpp
@@ -93,7 +93,6 @@ QT_END_NAMESPACE
#include <qfile.h>
#include <qfileinfo.h>
#include <qlist.h>
-#include <qhash.h>
#include <qmutex.h>
#include <qsemaphore.h>
#include <qsocketnotifier.h>
@@ -204,8 +203,8 @@ bool QProcessPrivate::openChannel(Channel &channel)
channel.pipe[1] = -1;
if ( (channel.pipe[0] = qt_safe_open(fname, O_RDONLY)) != -1)
return true; // success
-
- q->setErrorString(QProcess::tr("Could not open input redirection for reading"));
+ setErrorAndEmit(QProcess::FailedToStart,
+ QProcess::tr("Could not open input redirection for reading"));
} else {
int mode = O_WRONLY | O_CREAT;
if (channel.append)
@@ -217,12 +216,9 @@ bool QProcessPrivate::openChannel(Channel &channel)
if ( (channel.pipe[1] = qt_safe_open(fname, mode, 0666)) != -1)
return true; // success
- q->setErrorString(QProcess::tr("Could not open output redirection for writing"));
+ setErrorAndEmit(QProcess::FailedToStart,
+ QProcess::tr("Could not open input redirection for reading"));
}
-
- // could not open file
- processError = QProcess::FailedToStart;
- emit q->error(processError);
cleanup();
return false;
} else {
@@ -331,9 +327,7 @@ void QProcessPrivate::startProcess()
!openChannel(stdoutChannel) ||
!openChannel(stderrChannel) ||
qt_create_pipe(childStartedPipe) != 0) {
- processError = QProcess::FailedToStart;
- q->setErrorString(qt_error_string(errno));
- emit q->error(processError);
+ setErrorAndEmit(QProcess::FailedToStart, qt_error_string(errno));
cleanup();
return;
}
@@ -406,7 +400,7 @@ void QProcessPrivate::startProcess()
char **path = 0;
int pathc = 0;
if (!program.contains(QLatin1Char('/'))) {
- const QString pathEnv = QString::fromLocal8Bit(::getenv("PATH"));
+ const QString pathEnv = QString::fromLocal8Bit(qgetenv("PATH"));
if (!pathEnv.isEmpty()) {
QStringList pathEntries = pathEnv.split(QLatin1Char(':'), QString::SkipEmptyParts);
if (!pathEntries.isEmpty()) {
@@ -459,9 +453,8 @@ void QProcessPrivate::startProcess()
qDebug("fork failed: %s", qPrintable(qt_error_string(lastForkErrno)));
#endif
q->setProcessState(QProcess::NotRunning);
- processError = QProcess::FailedToStart;
- q->setErrorString(QProcess::tr("Resource error (fork failure): %1").arg(qt_error_string(lastForkErrno)));
- emit q->error(processError);
+ setErrorAndEmit(QProcess::FailedToStart,
+ QProcess::tr("Resource error (fork failure): %1").arg(qt_error_string(lastForkErrno)));
cleanup();
return;
}
@@ -679,9 +672,9 @@ void QProcessPrivate::execChild(const char *workingDir, char **path, char **argv
qt_safe_close(childStartedPipe[0]);
// enter the working directory
- if (workingDir) {
- if (QT_CHDIR(workingDir) == -1)
- qWarning("QProcessPrivate::execChild() failed to chdir to %s", workingDir);
+ if (workingDir && QT_CHDIR(workingDir) == -1) {
+ // failed, stop the process
+ goto report_errno;
}
// this is a virtual call, and it base behavior is to do nothing.
@@ -710,6 +703,7 @@ void QProcessPrivate::execChild(const char *workingDir, char **path, char **argv
}
// notify failure
+report_errno:
QString error = qt_error_string(errno);
#if defined (QPROCESS_DEBUG)
fprintf(stderr, "QProcessPrivate::execChild() failed (%s), notifying parent process\n", qPrintable(error));
@@ -809,8 +803,6 @@ void QProcessPrivate::killProcess()
bool QProcessPrivate::waitForStarted(int msecs)
{
- Q_Q(QProcess);
-
#if defined (QPROCESS_DEBUG)
qDebug("QProcessPrivate::waitForStarted(%d) waiting for child to start (fd = %d)", msecs,
childStartedPipe[0]);
@@ -820,8 +812,7 @@ bool QProcessPrivate::waitForStarted(int msecs)
FD_ZERO(&fds);
FD_SET(childStartedPipe[0], &fds);
if (qt_select_msecs(childStartedPipe[0] + 1, &fds, 0, msecs) == 0) {
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
#if defined (QPROCESS_DEBUG)
qDebug("QProcessPrivate::waitForStarted(%d) == false (timed out)", msecs);
#endif
@@ -848,7 +839,6 @@ QList<QSocketNotifier *> QProcessPrivate::defaultNotifiers() const
bool QProcessPrivate::waitForReadyRead(int msecs)
{
- Q_Q(QProcess);
#if defined (QPROCESS_DEBUG)
qDebug("QProcessPrivate::waitForReadyRead(%d)", msecs);
#endif
@@ -891,8 +881,7 @@ bool QProcessPrivate::waitForReadyRead(int msecs)
break;
}
if (ret == 0) {
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -928,7 +917,6 @@ bool QProcessPrivate::waitForReadyRead(int msecs)
bool QProcessPrivate::waitForBytesWritten(int msecs)
{
- Q_Q(QProcess);
#if defined (QPROCESS_DEBUG)
qDebug("QProcessPrivate::waitForBytesWritten(%d)", msecs);
#endif
@@ -973,8 +961,7 @@ bool QProcessPrivate::waitForBytesWritten(int msecs)
}
if (ret == 0) {
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -1003,7 +990,6 @@ bool QProcessPrivate::waitForBytesWritten(int msecs)
bool QProcessPrivate::waitForFinished(int msecs)
{
- Q_Q(QProcess);
#if defined (QPROCESS_DEBUG)
qDebug("QProcessPrivate::waitForFinished(%d)", msecs);
#endif
@@ -1047,8 +1033,7 @@ bool QProcessPrivate::waitForFinished(int msecs)
break;
}
if (ret == 0) {
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -1188,7 +1173,7 @@ bool QProcessPrivate::startDetached(const QString &program, const QStringList &a
argv[arguments.size() + 1] = 0;
if (!program.contains(QLatin1Char('/'))) {
- const QString path = QString::fromLocal8Bit(::getenv("PATH"));
+ const QString path = QString::fromLocal8Bit(qgetenv("PATH"));
if (!path.isEmpty()) {
QStringList pathEntries = path.split(QLatin1Char(':'));
for (int k = 0; k < pathEntries.size(); ++k) {
diff --git a/src/corelib/io/qprocess_win.cpp b/src/corelib/io/qprocess_win.cpp
index eb88ded2c9..e77249975c 100644
--- a/src/corelib/io/qprocess_win.cpp
+++ b/src/corelib/io/qprocess_win.cpp
@@ -217,7 +217,8 @@ bool QProcessPrivate::openChannel(Channel &channel)
if (channel.pipe[0] != INVALID_Q_PIPE)
return true;
- q->setErrorString(QProcess::tr("Could not open input redirection for reading"));
+ setErrorAndEmit(QProcess::FailedToStart,
+ QProcess::tr("Could not open input redirection for reading"));
} else {
// open in write mode
channel.pipe[0] = INVALID_Q_PIPE;
@@ -237,12 +238,9 @@ bool QProcessPrivate::openChannel(Channel &channel)
return true;
}
- q->setErrorString(QProcess::tr("Could not open output redirection for writing"));
+ setErrorAndEmit(QProcess::FailedToStart,
+ QProcess::tr("Could not open output redirection for writing"));
}
-
- // could not open file
- processError = QProcess::FailedToStart;
- emit q->error(processError);
cleanup();
return false;
} else {
@@ -504,9 +502,10 @@ void QProcessPrivate::startProcess()
environment.isEmpty() ? 0 : envlist.data(),
workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(),
&startupInfo, pid);
+ QString errorString;
if (!success) {
// Capture the error string before we do CloseHandle below
- q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string()));
+ errorString = QProcess::tr("Process failed to start: %1").arg(qt_error_string());
}
if (stdinChannel.pipe[0] != INVALID_Q_PIPE) {
@@ -524,8 +523,7 @@ void QProcessPrivate::startProcess()
if (!success) {
cleanup();
- processError = QProcess::FailedToStart;
- emit q->error(processError);
+ setErrorAndEmit(QProcess::FailedToStart, errorString);
q->setProcessState(QProcess::NotRunning);
return;
}
@@ -595,16 +593,13 @@ void QProcessPrivate::killProcess()
bool QProcessPrivate::waitForStarted(int)
{
- Q_Q(QProcess);
-
if (processStarted())
return true;
if (processError == QProcess::FailedToStart)
return false;
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -636,8 +631,6 @@ bool QProcessPrivate::drainOutputPipes()
bool QProcessPrivate::waitForReadyRead(int msecs)
{
- Q_Q(QProcess);
-
QIncrementalSleepTimer timer(msecs);
forever {
@@ -652,7 +645,7 @@ bool QProcessPrivate::waitForReadyRead(int msecs)
if (!pid)
return false;
- if (WaitForSingleObject(pid->hProcess, 0) == WAIT_OBJECT_0) {
+ if (WaitForSingleObjectEx(pid->hProcess, 0, false) == WAIT_OBJECT_0) {
bool readyReadEmitted = drainOutputPipes();
_q_processDied();
return readyReadEmitted;
@@ -663,15 +656,12 @@ bool QProcessPrivate::waitForReadyRead(int msecs)
break;
}
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
bool QProcessPrivate::waitForBytesWritten(int msecs)
{
- Q_Q(QProcess);
-
QIncrementalSleepTimer timer(msecs);
forever {
@@ -723,7 +713,7 @@ bool QProcessPrivate::waitForBytesWritten(int msecs)
// Wait for the process to signal any change in its state,
// such as incoming data, or if the process died.
- if (WaitForSingleObject(pid->hProcess, 0) == WAIT_OBJECT_0) {
+ if (WaitForSingleObjectEx(pid->hProcess, 0, false) == WAIT_OBJECT_0) {
_q_processDied();
return false;
}
@@ -733,14 +723,12 @@ bool QProcessPrivate::waitForBytesWritten(int msecs)
break;
}
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
bool QProcessPrivate::waitForFinished(int msecs)
{
- Q_Q(QProcess);
#if defined QPROCESS_DEBUG
qDebug("QProcessPrivate::waitForFinished(%d)", msecs);
#endif
@@ -772,8 +760,7 @@ bool QProcessPrivate::waitForFinished(int msecs)
break;
}
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -816,13 +803,10 @@ qint64 QProcessPrivate::writeToStdin(const char *data, qint64 maxlen)
bool QProcessPrivate::waitForWrite(int msecs)
{
- Q_Q(QProcess);
-
if (!stdinChannel.writer || stdinChannel.writer->waitForWrite(msecs))
return true;
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
diff --git a/src/corelib/io/qprocess_wince.cpp b/src/corelib/io/qprocess_wince.cpp
index 53767758c2..807472b7b2 100644
--- a/src/corelib/io/qprocess_wince.cpp
+++ b/src/corelib/io/qprocess_wince.cpp
@@ -138,8 +138,7 @@ void QProcessPrivate::startProcess()
if (!success) {
cleanup();
- processError = QProcess::FailedToStart;
- emit q->error(processError);
+ setErrorAndEmit(QProcess::FailedToStart);
q->setProcessState(QProcess::NotRunning);
return;
}
@@ -210,8 +209,7 @@ bool QProcessPrivate::waitForStarted(int)
if (processError == QProcess::FailedToStart)
return false;
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
@@ -251,8 +249,7 @@ bool QProcessPrivate::waitForFinished(int msecs)
if (timer.hasTimedOut())
break;
}
- processError = QProcess::Timedout;
- q->setErrorString(QProcess::tr("Process operation timed out"));
+ setError(QProcess::Timedout);
return false;
}
diff --git a/src/corelib/io/qresource.cpp b/src/corelib/io/qresource.cpp
index 6671333ffb..4e6079306b 100644
--- a/src/corelib/io/qresource.cpp
+++ b/src/corelib/io/qresource.cpp
@@ -35,7 +35,6 @@
#include "qresource_p.h"
#include "qresource_iterator_p.h"
#include "qset.h"
-#include "qhash.h"
#include "qmutex.h"
#include "qdebug.h"
#include "qlocale.h"
@@ -791,6 +790,7 @@ QStringList QResourceRoot::children(int node) const
offset += 4;
const int child_off = (tree[offset+0] << 24) + (tree[offset+1] << 16) +
(tree[offset+2] << 8) + (tree[offset+3] << 0);
+ ret.reserve(child_count);
for(int i = child_off; i < child_off+child_count; ++i)
ret << name(i);
}
diff --git a/src/corelib/io/qsavefile.h b/src/corelib/io/qsavefile.h
index 3f5f09bf5c..085378ed4e 100644
--- a/src/corelib/io/qsavefile.h
+++ b/src/corelib/io/qsavefile.h
@@ -58,7 +58,7 @@ class Q_CORE_EXPORT QSaveFile : public QFileDevice
public:
explicit QSaveFile(const QString &name);
- explicit QSaveFile(QObject *parent = 0);
+ explicit QSaveFile(QObject *parent = Q_NULLPTR);
explicit QSaveFile(const QString &name, QObject *parent);
~QSaveFile();
diff --git a/src/corelib/io/qsettings.cpp b/src/corelib/io/qsettings.cpp
index 413f5693f0..da4a02e4e4 100644
--- a/src/corelib/io/qsettings.cpp
+++ b/src/corelib/io/qsettings.cpp
@@ -127,6 +127,7 @@ struct QConfFileCustomFormat
QSettings::WriteFunc writeFunc;
Qt::CaseSensitivity caseSensitivity;
};
+Q_DECLARE_TYPEINFO(QConfFileCustomFormat, Q_MOVABLE_TYPE);
typedef QHash<QString, QConfFile *> ConfFileHash;
typedef QCache<QString, QConfFile> ConfFileCache;
@@ -299,7 +300,7 @@ QSettingsPrivate *QSettingsPrivate::create(const QString &fileName, QSettings::F
}
#endif
-void QSettingsPrivate::processChild(QString key, ChildSpec spec, QMap<QString, QString> &result)
+void QSettingsPrivate::processChild(QStringRef key, ChildSpec spec, QStringList &result)
{
if (spec != AllKeys) {
int slashPos = key.indexOf(QLatin1Char('/'));
@@ -312,7 +313,7 @@ void QSettingsPrivate::processChild(QString key, ChildSpec spec, QMap<QString, Q
key.truncate(slashPos);
}
}
- result.insert(key, QString());
+ result.append(key.toString());
}
void QSettingsPrivate::beginGroupOrArray(const QSettingsGroup &group)
@@ -357,6 +358,7 @@ void QSettingsPrivate::requestUpdate()
QStringList QSettingsPrivate::variantListToStringList(const QVariantList &l)
{
QStringList result;
+ result.reserve(l.count());
QVariantList::const_iterator it = l.constBegin();
for (; it != l.constEnd(); ++it)
result.append(variantToString(*it));
@@ -374,7 +376,9 @@ QVariant QSettingsPrivate::stringListToVariantList(const QStringList &l)
outStringList[i].remove(0, 1);
} else {
QVariantList variantList;
- for (int j = 0; j < l.count(); ++j)
+ const int stringCount = l.count();
+ variantList.reserve(stringCount);
+ for (int j = 0; j < stringCount; ++j)
variantList.append(stringToVariant(l.at(j)));
return variantList;
}
@@ -1052,12 +1056,12 @@ static void initDefaultPaths(QMutexLocker *locker)
// Non XDG platforms (OS X, iOS, Blackberry, Android...) have used this code path erroneously
// for some time now. Moving away from that would require migrating existing settings.
QString userPath;
- char *env = getenv("XDG_CONFIG_HOME");
- if (env == 0) {
+ QByteArray env = qgetenv("XDG_CONFIG_HOME");
+ if (env.isEmpty()) {
userPath = QDir::homePath();
userPath += QLatin1Char('/');
userPath += QLatin1String(".config");
- } else if (*env == '/') {
+ } else if (env.startsWith('/')) {
userPath = QFile::decodeName(env);
} else {
userPath = QDir::homePath();
@@ -1269,7 +1273,7 @@ bool QConfFileSettingsPrivate::get(const QString &key, QVariant *value) const
QStringList QConfFileSettingsPrivate::children(const QString &prefix, ChildSpec spec) const
{
- QMap<QString, QString> result;
+ QStringList result;
ParsedSettingsMap::const_iterator j;
QSettingsKey thePrefix(prefix, caseSensitivity);
@@ -1289,14 +1293,14 @@ QStringList QConfFileSettingsPrivate::children(const QString &prefix, ChildSpec
&confFile->originalKeys)->lowerBound( thePrefix);
while (j != confFile->originalKeys.constEnd() && j.key().startsWith(thePrefix)) {
if (!confFile->removedKeys.contains(j.key()))
- processChild(j.key().originalCaseKey().mid(startPos), spec, result);
+ processChild(j.key().originalCaseKey().midRef(startPos), spec, result);
++j;
}
j = const_cast<const ParsedSettingsMap *>(
&confFile->addedKeys)->lowerBound(thePrefix);
while (j != confFile->addedKeys.constEnd() && j.key().startsWith(thePrefix)) {
- processChild(j.key().originalCaseKey().mid(startPos), spec, result);
+ processChild(j.key().originalCaseKey().midRef(startPos), spec, result);
++j;
}
@@ -1304,7 +1308,10 @@ QStringList QConfFileSettingsPrivate::children(const QString &prefix, ChildSpec
break;
}
}
- return result.keys();
+ std::sort(result.begin(), result.end());
+ result.erase(std::unique(result.begin(), result.end()),
+ result.end());
+ return result;
}
void QConfFileSettingsPrivate::clear()
@@ -1755,6 +1762,7 @@ public:
int position;
};
+Q_DECLARE_TYPEINFO(QSettingsIniKey, Q_MOVABLE_TYPE);
static bool operator<(const QSettingsIniKey &k1, const QSettingsIniKey &k2)
{
diff --git a/src/corelib/io/qsettings.h b/src/corelib/io/qsettings.h
index f7a7bdbb19..8f41273ffa 100644
--- a/src/corelib/io/qsettings.h
+++ b/src/corelib/io/qsettings.h
@@ -105,13 +105,13 @@ public:
#ifndef QT_NO_QOBJECT
explicit QSettings(const QString &organization,
- const QString &application = QString(), QObject *parent = 0);
+ const QString &application = QString(), QObject *parent = Q_NULLPTR);
QSettings(Scope scope, const QString &organization,
- const QString &application = QString(), QObject *parent = 0);
+ const QString &application = QString(), QObject *parent = Q_NULLPTR);
QSettings(Format format, Scope scope, const QString &organization,
- const QString &application = QString(), QObject *parent = 0);
- QSettings(const QString &fileName, Format format, QObject *parent = 0);
- explicit QSettings(QObject *parent = 0);
+ const QString &application = QString(), QObject *parent = Q_NULLPTR);
+ QSettings(const QString &fileName, Format format, QObject *parent = Q_NULLPTR);
+ explicit QSettings(QObject *parent = Q_NULLPTR);
#else
explicit QSettings(const QString &organization,
const QString &application = QString());
diff --git a/src/corelib/io/qsettings_mac.cpp b/src/corelib/io/qsettings_mac.cpp
index 51321c49e7..1ad198b990 100644
--- a/src/corelib/io/qsettings_mac.cpp
+++ b/src/corelib/io/qsettings_mac.cpp
@@ -491,7 +491,7 @@ bool QMacSettingsPrivate::get(const QString &key, QVariant *value) const
QStringList QMacSettingsPrivate::children(const QString &prefix, ChildSpec spec) const
{
- QMap<QString, QString> result;
+ QStringList result;
int startPos = prefix.size();
for (int i = 0; i < numDomains; ++i) {
@@ -505,7 +505,7 @@ QStringList QMacSettingsPrivate::children(const QString &prefix, ChildSpec spec)
QString currentKey =
qtKey(static_cast<CFStringRef>(CFArrayGetValueAtIndex(cfarray, k)));
if (currentKey.startsWith(prefix))
- processChild(currentKey.mid(startPos), spec, result);
+ processChild(currentKey.midRef(startPos), spec, result);
}
}
}
@@ -513,7 +513,10 @@ QStringList QMacSettingsPrivate::children(const QString &prefix, ChildSpec spec)
if (!fallbacks)
break;
}
- return result.keys();
+ std::sort(result.begin(), result.end());
+ result.erase(std::unique(result.begin(), result.end()),
+ result.end());
+ return result;
}
void QMacSettingsPrivate::clear()
diff --git a/src/corelib/io/qsettings_p.h b/src/corelib/io/qsettings_p.h
index 93d63fd411..5a3eb58a58 100644
--- a/src/corelib/io/qsettings_p.h
+++ b/src/corelib/io/qsettings_p.h
@@ -127,6 +127,7 @@ public:
int num;
int maxNum;
};
+Q_DECLARE_TYPEINFO(QSettingsGroup, Q_MOVABLE_TYPE);
inline QString QSettingsGroup::toString() const
{
@@ -211,7 +212,7 @@ public:
const QString &organization, const QString &application);
static QSettingsPrivate *create(const QString &fileName, QSettings::Format format);
- static void processChild(QString key, ChildSpec spec, QMap<QString, QString> &result);
+ static void processChild(QStringRef key, ChildSpec spec, QStringList &result);
// Variant streaming functions
static QStringList variantListToStringList(const QVariantList &l);
diff --git a/src/corelib/io/qsettings_win.cpp b/src/corelib/io/qsettings_win.cpp
index 60b15f41a0..1546219c3b 100644
--- a/src/corelib/io/qsettings_win.cpp
+++ b/src/corelib/io/qsettings_win.cpp
@@ -319,11 +319,11 @@ private:
};
RegistryKey::RegistryKey(HKEY parent_handle, const QString &key, bool read_only)
+ : m_parent_handle(parent_handle),
+ m_handle(0),
+ m_key(key),
+ m_read_only(read_only)
{
- m_parent_handle = parent_handle;
- m_handle = 0;
- m_read_only = read_only;
- m_key = key;
}
QString RegistryKey::key() const
diff --git a/src/corelib/io/qstandardpaths.cpp b/src/corelib/io/qstandardpaths.cpp
index 74252d1f0a..8828e09e8f 100644
--- a/src/corelib/io/qstandardpaths.cpp
+++ b/src/corelib/io/qstandardpaths.cpp
@@ -35,7 +35,6 @@
#include <qdir.h>
#include <qfileinfo.h>
-#include <qhash.h>
#ifndef QT_BOOTSTRAPPED
#include <qobject.h>
@@ -183,7 +182,7 @@ QT_BEGIN_NAMESPACE
\li "C:/Users/<USER>/AppData/Local/<APPNAME>/cache"
\row \li GenericDataLocation
\li "~/Library/Application Support", "/Library/Application Support"
- \li "C:/Users/<USER>/AppData/Local", "C:/ProgramData"
+ \li "C:/Users/<USER>/AppData/Local", "C:/ProgramData", "<APPDIR>", "<APPDIR>/data"
\row \li RuntimeLocation
\li "~/Library/Application Support"
\li "C:/Users/<USER>"
@@ -523,13 +522,8 @@ QString QStandardPaths::findExecutable(const QString &executableName, const QStr
QStringList searchPaths = paths;
if (paths.isEmpty()) {
QByteArray pEnv = qgetenv("PATH");
-#if defined(Q_OS_WIN)
- const QLatin1Char pathSep(';');
-#else
- const QLatin1Char pathSep(':');
-#endif
// Remove trailing slashes, which occur on Windows.
- const QStringList rawPaths = QString::fromLocal8Bit(pEnv.constData()).split(pathSep, QString::SkipEmptyParts);
+ const QStringList rawPaths = QString::fromLocal8Bit(pEnv.constData()).split(QDir::listSeparator(), QString::SkipEmptyParts);
searchPaths.reserve(rawPaths.size());
foreach (const QString &rawPath, rawPaths) {
QString cleanPath = QDir::cleanPath(rawPath);
diff --git a/src/corelib/io/qstandardpaths_win.cpp b/src/corelib/io/qstandardpaths_win.cpp
index b1d5821a97..0a13f94f05 100644
--- a/src/corelib/io/qstandardpaths_win.cpp
+++ b/src/corelib/io/qstandardpaths_win.cpp
@@ -212,10 +212,8 @@ QStringList QStandardPaths::standardLocations(StandardLocation type)
}
dirs.append(result);
#ifndef QT_BOOTSTRAPPED
- if (type != GenericDataLocation) {
- dirs.append(QCoreApplication::applicationDirPath());
- dirs.append(QCoreApplication::applicationDirPath() + QLatin1String("/data"));
- }
+ dirs.append(QCoreApplication::applicationDirPath());
+ dirs.append(QCoreApplication::applicationDirPath() + QLatin1String("/data"));
#endif
}
break;
diff --git a/src/corelib/io/qstorageinfo.cpp b/src/corelib/io/qstorageinfo.cpp
index 337a9c7cef..99a2a1a42a 100644
--- a/src/corelib/io/qstorageinfo.cpp
+++ b/src/corelib/io/qstorageinfo.cpp
@@ -222,6 +222,18 @@ qint64 QStorageInfo::bytesTotal() const
}
/*!
+ \since 5.6
+ Returns the optimal transfer block size for this filesystem.
+
+ Returns -1 if QStorageInfo could not determine the size or if the QStorageInfo
+ object is not valid.
+ */
+int QStorageInfo::blockSize() const
+{
+ return d->blockSize;
+}
+
+/*!
Returns the type name of the filesystem.
This is a platform-dependent function, and filesystem names can vary
diff --git a/src/corelib/io/qstorageinfo.h b/src/corelib/io/qstorageinfo.h
index 848278e69f..c7a558bb4e 100644
--- a/src/corelib/io/qstorageinfo.h
+++ b/src/corelib/io/qstorageinfo.h
@@ -55,11 +55,10 @@ public:
QStorageInfo &operator=(const QStorageInfo &other);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QStorageInfo &operator=(QStorageInfo &&other)
- { qSwap(d, other.d); return *this; }
+ QStorageInfo &operator=(QStorageInfo &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QStorageInfo &other)
+ inline void swap(QStorageInfo &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
void setPath(const QString &path);
@@ -73,6 +72,7 @@ public:
qint64 bytesTotal() const;
qint64 bytesFree() const;
qint64 bytesAvailable() const;
+ int blockSize() const;
inline bool isRoot() const;
bool isReadOnly() const;
diff --git a/src/corelib/io/qstorageinfo_mac.cpp b/src/corelib/io/qstorageinfo_mac.cpp
index 539af33c5d..1ef9983918 100644
--- a/src/corelib/io/qstorageinfo_mac.cpp
+++ b/src/corelib/io/qstorageinfo_mac.cpp
@@ -76,6 +76,7 @@ void QStorageInfoPrivate::retrievePosixInfo()
device = QByteArray(statfs_buf.f_mntfromname);
readOnly = (statfs_buf.f_flags & MNT_RDONLY) != 0;
fileSystemType = QByteArray(statfs_buf.f_fstypename);
+ blockSize = statfs_buf.f_bsize;
}
}
diff --git a/src/corelib/io/qstorageinfo_p.h b/src/corelib/io/qstorageinfo_p.h
index 564321bedd..fb3bd8bd5b 100644
--- a/src/corelib/io/qstorageinfo_p.h
+++ b/src/corelib/io/qstorageinfo_p.h
@@ -53,7 +53,7 @@ class QStorageInfoPrivate : public QSharedData
{
public:
inline QStorageInfoPrivate() : QSharedData(),
- bytesTotal(-1), bytesFree(-1), bytesAvailable(-1),
+ bytesTotal(-1), bytesFree(-1), bytesAvailable(-1), blockSize(-1),
readOnly(false), ready(false), valid(false)
{}
@@ -84,6 +84,7 @@ public:
qint64 bytesTotal;
qint64 bytesFree;
qint64 bytesAvailable;
+ int blockSize;
bool readOnly;
bool ready;
diff --git a/src/corelib/io/qstorageinfo_unix.cpp b/src/corelib/io/qstorageinfo_unix.cpp
index bf1e6ce245..54a2855239 100644
--- a/src/corelib/io/qstorageinfo_unix.cpp
+++ b/src/corelib/io/qstorageinfo_unix.cpp
@@ -49,7 +49,7 @@
# include <sys/mount.h>
# include <sys/vfs.h>
# include <mntent.h>
-#elif defined(Q_OS_LINUX)
+#elif defined(Q_OS_LINUX) || defined(Q_OS_HURD)
# include <mntent.h>
# include <sys/statvfs.h>
#elif defined(Q_OS_SOLARIS)
@@ -145,7 +145,7 @@ private:
QByteArray m_rootPath;
QByteArray m_fileSystemType;
QByteArray m_device;
-#elif defined(Q_OS_LINUX)
+#elif defined(Q_OS_LINUX) || defined(Q_OS_HURD)
FILE *fp;
mntent mnt;
QByteArray buffer;
@@ -287,10 +287,11 @@ inline QByteArray QStorageIterator::device() const
return m_device;
}
-#elif defined(Q_OS_LINUX)
+#elif defined(Q_OS_LINUX) || defined(Q_OS_HURD)
static const char pathMounted[] = "/etc/mtab";
-static const int bufferSize = 3*PATH_MAX; // 2 paths (mount point+device) and metainfo
+static const int bufferSize = 1024; // 2 paths (mount point+device) and metainfo;
+ // should be enough
inline QStorageIterator::QStorageIterator() :
buffer(QByteArray(bufferSize, 0))
@@ -509,6 +510,7 @@ void QStorageInfoPrivate::retrieveVolumeInfo()
bytesTotal = statfs_buf.f_blocks * statfs_buf.f_frsize;
bytesFree = statfs_buf.f_bfree * statfs_buf.f_frsize;
bytesAvailable = statfs_buf.f_bavail * statfs_buf.f_frsize;
+ blockSize = statfs_buf.f_bsize;
#if defined(Q_OS_ANDROID) || defined (Q_OS_BSD4)
#if defined(_STATFS_F_FLAGS)
readOnly = (statfs_buf.f_flags & ST_RDONLY) != 0;
diff --git a/src/corelib/io/qtemporarydir.cpp b/src/corelib/io/qtemporarydir.cpp
index 0beda22f24..c7150d7b33 100644
--- a/src/corelib/io/qtemporarydir.cpp
+++ b/src/corelib/io/qtemporarydir.cpp
@@ -38,6 +38,7 @@
#include "qdiriterator.h"
#include "qplatformdefs.h"
#include <QDebug>
+#include <QPair>
#if defined(QT_BUILD_CORE_LIB)
#include "qcoreapplication.h"
@@ -59,7 +60,7 @@ public:
void create(const QString &templateName);
- QString path;
+ QString pathOrError;
bool autoRemove;
bool success;
};
@@ -97,7 +98,7 @@ static int nextRand(int &v)
return r;
}
-static char *q_mkdtemp(char *templateName)
+QPair<QString, bool> q_mkdtemp(char *templateName)
{
static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -105,8 +106,7 @@ static char *q_mkdtemp(char *templateName)
char *XXXXXX = templateName + length - 6;
- if ((length < 6u) || strncmp(XXXXXX, "XXXXXX", 6))
- return 0;
+ Q_ASSERT((length >= 6u) && strncmp(XXXXXX, "XXXXXX", 6) == 0);
for (int i = 0; i < 256; ++i) {
int v = qrand();
@@ -133,17 +133,27 @@ static char *q_mkdtemp(char *templateName)
qWarning() << "Unable to remove unused directory" << templateNameStr;
continue;
}
- return templateName;
+ return qMakePair(QFile::decodeName(templateName), true);
}
+# ifdef Q_OS_WIN
+ const int exists = ERROR_ALREADY_EXISTS;
+ int code = GetLastError();
+# else
+ const int exists = EEXIST;
+ int code = errno;
+# endif
+ if (code != exists)
+ return qMakePair(qt_error_string(code), false);
}
- return 0;
+ return qMakePair(qt_error_string(), false);
}
#else // defined(Q_OS_QNX ) || defined(Q_OS_WIN) || defined(Q_OS_ANDROID)
-static char *q_mkdtemp(char *templateName)
+QPair<QString, bool> q_mkdtemp(char *templateName)
{
- return mkdtemp(templateName);
+ bool ok = (mkdtemp(templateName) != 0);
+ return qMakePair(ok ? QFile::decodeName(templateName) : qt_error_string(), ok);
}
#endif
@@ -153,10 +163,9 @@ void QTemporaryDirPrivate::create(const QString &templateName)
QByteArray buffer = QFile::encodeName(templateName);
if (!buffer.endsWith("XXXXXX"))
buffer += "XXXXXX";
- if (q_mkdtemp(buffer.data())) { // modifies buffer
- success = true;
- path = QFile::decodeName(buffer.constData());
- }
+ QPair<QString, bool> result = q_mkdtemp(buffer.data()); // modifies buffer
+ pathOrError = result.first;
+ success = result.second;
}
//************* QTemporaryDir
@@ -256,12 +265,24 @@ bool QTemporaryDir::isValid() const
}
/*!
+ \since 5.6
+
+ If isValid() returns \c false, this function returns the error string that
+ explains why the creation of the temporary directory failed. Otherwise, this
+ function return an empty string.
+*/
+QString QTemporaryDir::errorString() const
+{
+ return d_ptr->success ? QString() : d_ptr->pathOrError;
+}
+
+/*!
Returns the path to the temporary directory.
Empty if the QTemporaryDir could not be created.
*/
QString QTemporaryDir::path() const
{
- return d_ptr->path;
+ return d_ptr->success ? d_ptr->pathOrError : QString();
}
/*!
diff --git a/src/corelib/io/qtemporarydir.h b/src/corelib/io/qtemporarydir.h
index 8b98226529..ab6d841cdf 100644
--- a/src/corelib/io/qtemporarydir.h
+++ b/src/corelib/io/qtemporarydir.h
@@ -52,6 +52,7 @@ public:
~QTemporaryDir();
bool isValid() const;
+ QString errorString() const;
bool autoRemove() const;
void setAutoRemove(bool b);
diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp
index 68ac85fffd..e8e8d8c878 100644
--- a/src/corelib/io/qtemporaryfile.cpp
+++ b/src/corelib/io/qtemporaryfile.cpp
@@ -236,9 +236,9 @@ QTemporaryFileEngine::~QTemporaryFileEngine()
QFSFileEngine::close();
}
-bool QTemporaryFileEngine::isReallyOpen()
+bool QTemporaryFileEngine::isReallyOpen() const
{
- Q_D(QFSFileEngine);
+ Q_D(const QFSFileEngine);
if (!((0 == d->fh) && (-1 == d->fd)
#if defined Q_OS_WIN
diff --git a/src/corelib/io/qtemporaryfile_p.h b/src/corelib/io/qtemporaryfile_p.h
index 2d4468fcf8..8002990270 100644
--- a/src/corelib/io/qtemporaryfile_p.h
+++ b/src/corelib/io/qtemporaryfile_p.h
@@ -91,7 +91,7 @@ public:
}
~QTemporaryFileEngine();
- bool isReallyOpen();
+ bool isReallyOpen() const;
void setFileName(const QString &file);
void setFileTemplate(const QString &fileTemplate);
diff --git a/src/corelib/io/qtextstream.h b/src/corelib/io/qtextstream.h
index e5f429ae4d..eb33db63d7 100644
--- a/src/corelib/io/qtextstream.h
+++ b/src/corelib/io/qtextstream.h
@@ -205,8 +205,8 @@ typedef void (QTextStream::*QTSMFC)(QChar); // manipulator w/QChar argument
class Q_CORE_EXPORT QTextStreamManipulator
{
public:
- QTextStreamManipulator(QTSMFI m, int a) { mf = m; mc = 0; arg = a; }
- QTextStreamManipulator(QTSMFC m, QChar c) { mf = 0; mc = m; ch = c; arg = -1; }
+ Q_DECL_CONSTEXPR QTextStreamManipulator(QTSMFI m, int a) Q_DECL_NOTHROW : mf(m), mc(Q_NULLPTR), arg(a), ch() {}
+ Q_DECL_CONSTEXPR QTextStreamManipulator(QTSMFC m, QChar c) Q_DECL_NOTHROW : mf(Q_NULLPTR), mc(m), arg(-1), ch(c) {}
void exec(QTextStream &s) { if (mf) { (s.*mf)(arg); } else { (s.*mc)(ch); } }
private:
diff --git a/src/corelib/io/qtldurl.cpp b/src/corelib/io/qtldurl.cpp
index 2e787a1bc5..d68d0ddf46 100644
--- a/src/corelib/io/qtldurl.cpp
+++ b/src/corelib/io/qtldurl.cpp
@@ -37,7 +37,6 @@
#include "private/qtldurl_p.h"
#include "QtCore/qstring.h"
#include "QtCore/qvector.h"
-#include "QtCore/qhash.h"
QT_BEGIN_NAMESPACE
diff --git a/src/corelib/io/qurlquery.cpp b/src/corelib/io/qurlquery.cpp
index 77d1ab3e24..2b695a4f7b 100644
--- a/src/corelib/io/qurlquery.cpp
+++ b/src/corelib/io/qurlquery.cpp
@@ -34,6 +34,7 @@
#include "qurlquery.h"
#include "qurl_p.h"
+#include <QtCore/qhashfunctions.h>
#include <QtCore/qstringlist.h>
QT_BEGIN_NAMESPACE
@@ -407,6 +408,7 @@ bool QUrlQuery::operator ==(const QUrlQuery &other) const
if (d == other.d)
return true;
if (d && other.d)
+ // keep in sync with qHash(QUrlQuery):
return d->valueDelimiter == other.d->valueDelimiter &&
d->pairDelimiter == other.d->pairDelimiter &&
d->itemList == other.d->itemList;
@@ -414,6 +416,25 @@ bool QUrlQuery::operator ==(const QUrlQuery &other) const
}
/*!
+ \since 5.6
+ \relates QUrlQuery
+
+ Returns the hash value for \a key,
+ using \a seed to seed the calculation.
+*/
+uint qHash(const QUrlQuery &key, uint seed) Q_DECL_NOTHROW
+{
+ if (const QUrlQueryPrivate *d = key.d) {
+ QtPrivate::QHashCombine hash;
+ // keep in sync with operator==:
+ seed = hash(seed, d->valueDelimiter);
+ seed = hash(seed, d->pairDelimiter);
+ seed = hash(seed, d->itemList);
+ }
+ return seed;
+}
+
+/*!
Returns \c true if this QUrlQuery object contains no key-value pairs, such as
after being default-constructed or after parsing an empty query string.
@@ -621,6 +642,7 @@ QList<QPair<QString, QString> > QUrlQuery::queryItems(QUrl::ComponentFormattingO
QList<QPair<QString, QString> > result;
Map::const_iterator it = d->itemList.constBegin();
Map::const_iterator end = d->itemList.constEnd();
+ result.reserve(d->itemList.count());
for ( ; it != end; ++it)
result << qMakePair(d->recodeToUser(it->first, encoding),
d->recodeToUser(it->second, encoding));
diff --git a/src/corelib/io/qurlquery.h b/src/corelib/io/qurlquery.h
index 77a0b4a82d..ae3a79c119 100644
--- a/src/corelib/io/qurlquery.h
+++ b/src/corelib/io/qurlquery.h
@@ -44,6 +44,8 @@
QT_BEGIN_NAMESPACE
+Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed = 0) Q_DECL_NOTHROW;
+
class QUrlQueryPrivate;
class Q_CORE_EXPORT QUrlQuery
{
@@ -54,8 +56,7 @@ public:
QUrlQuery(const QUrlQuery &other);
QUrlQuery &operator=(const QUrlQuery &other);
#ifdef Q_COMPILER_RVALUE_REFS
- QUrlQuery &operator=(QUrlQuery &&other)
- { qSwap(d, other.d); return *this; }
+ QUrlQuery &operator=(QUrlQuery &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
~QUrlQuery();
@@ -63,7 +64,7 @@ public:
bool operator!=(const QUrlQuery &other) const
{ return !(*this == other); }
- void swap(QUrlQuery &other) { qSwap(d, other.d); }
+ void swap(QUrlQuery &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isEmpty() const;
bool isDetached() const;
@@ -95,6 +96,7 @@ public:
private:
friend class QUrl;
+ friend Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed) Q_DECL_NOTHROW;
QSharedDataPointer<QUrlQueryPrivate> d;
public:
typedef QSharedDataPointer<QUrlQueryPrivate> DataPtr;
diff --git a/src/corelib/io/qwindowspipereader.cpp b/src/corelib/io/qwindowspipereader.cpp
index 14aad0e193..2cc5741250 100644
--- a/src/corelib/io/qwindowspipereader.cpp
+++ b/src/corelib/io/qwindowspipereader.cpp
@@ -136,12 +136,12 @@ qint64 QWindowsPipeReader::read(char *data, qint64 maxlen)
actualReadBufferSize--;
readSoFar = 1;
} else {
- qint64 bytesToRead = qMin(qint64(actualReadBufferSize), maxlen);
+ qint64 bytesToRead = qMin(actualReadBufferSize, maxlen);
readSoFar = 0;
while (readSoFar < bytesToRead) {
const char *ptr = readBuffer.readPointer();
- int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
- qint64(readBuffer.nextDataBlockSize()));
+ qint64 bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
+ readBuffer.nextDataBlockSize());
memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
readSoFar += bytesToReadFromThisBlock;
readBuffer.free(bytesToReadFromThisBlock);
diff --git a/src/corelib/io/qwindowspipereader_p.h b/src/corelib/io/qwindowspipereader_p.h
index 2c32eeb9ce..c8a66d9511 100644
--- a/src/corelib/io/qwindowspipereader_p.h
+++ b/src/corelib/io/qwindowspipereader_p.h
@@ -96,7 +96,7 @@ private:
QWinOverlappedIoNotifier *dataReadNotifier;
qint64 readBufferMaxSize;
QRingBuffer readBuffer;
- int actualReadBufferSize;
+ qint64 actualReadBufferSize;
bool stopped;
bool readSequenceStarted;
bool pipeBroken;
diff --git a/src/corelib/itemmodels/qabstractitemmodel.cpp b/src/corelib/itemmodels/qabstractitemmodel.cpp
index 60ac75133c..90297b9115 100644
--- a/src/corelib/itemmodels/qabstractitemmodel.cpp
+++ b/src/corelib/itemmodels/qabstractitemmodel.cpp
@@ -479,6 +479,11 @@ public:
Q_GLOBAL_STATIC(QEmptyItemModel, qEmptyModel)
+
+QAbstractItemModelPrivate::~QAbstractItemModelPrivate()
+{
+}
+
QAbstractItemModel *QAbstractItemModelPrivate::staticEmptyModel()
{
return qEmptyModel();
@@ -3217,6 +3222,7 @@ QModelIndexList QAbstractItemModel::persistentIndexList() const
{
Q_D(const QAbstractItemModel);
QModelIndexList result;
+ result.reserve(d->persistent.indexes.count());
for (QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it = d->persistent.indexes.constBegin();
it != d->persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
diff --git a/src/corelib/itemmodels/qabstractitemmodel.h b/src/corelib/itemmodels/qabstractitemmodel.h
index 5ca7bd0123..096e67c513 100644
--- a/src/corelib/itemmodels/qabstractitemmodel.h
+++ b/src/corelib/itemmodels/qabstractitemmodel.h
@@ -49,7 +49,7 @@ class Q_CORE_EXPORT QModelIndex
{
friend class QAbstractItemModel;
public:
- Q_DECL_CONSTEXPR inline QModelIndex() Q_DECL_NOTHROW : r(-1), c(-1), i(0), m(0) {}
+ Q_DECL_CONSTEXPR inline QModelIndex() Q_DECL_NOTHROW : r(-1), c(-1), i(0), m(Q_NULLPTR) {}
// compiler-generated copy/move ctors/assignment operators are fine!
Q_DECL_CONSTEXPR inline int row() const Q_DECL_NOTHROW { return r; }
Q_DECL_CONSTEXPR inline int column() const Q_DECL_NOTHROW { return c; }
@@ -61,7 +61,7 @@ public:
inline QVariant data(int role = Qt::DisplayRole) const;
inline Qt::ItemFlags flags() const;
Q_DECL_CONSTEXPR inline const QAbstractItemModel *model() const Q_DECL_NOTHROW { return m; }
- Q_DECL_CONSTEXPR inline bool isValid() const Q_DECL_NOTHROW { return (r >= 0) && (c >= 0) && (m != 0); }
+ Q_DECL_CONSTEXPR inline bool isValid() const Q_DECL_NOTHROW { return (r >= 0) && (c >= 0) && (m != Q_NULLPTR); }
Q_DECL_CONSTEXPR inline bool operator==(const QModelIndex &other) const Q_DECL_NOTHROW
{ return (other.r == r) && (other.i == i) && (other.c == c) && (other.m == m); }
Q_DECL_CONSTEXPR inline bool operator!=(const QModelIndex &other) const Q_DECL_NOTHROW
@@ -161,7 +161,7 @@ class Q_CORE_EXPORT QAbstractItemModel : public QObject
friend class QIdentityProxyModel;
public:
- explicit QAbstractItemModel(QObject *parent = 0);
+ explicit QAbstractItemModel(QObject *parent = Q_NULLPTR);
virtual ~QAbstractItemModel();
Q_INVOKABLE bool hasIndex(int row, int column, const QModelIndex &parent = QModelIndex()) const;
@@ -276,9 +276,9 @@ protected Q_SLOTS:
void resetInternalData();
protected:
- QAbstractItemModel(QAbstractItemModelPrivate &dd, QObject *parent = 0);
+ QAbstractItemModel(QAbstractItemModelPrivate &dd, QObject *parent = Q_NULLPTR);
- inline QModelIndex createIndex(int row, int column, void *data = 0) const;
+ inline QModelIndex createIndex(int row, int column, void *data = Q_NULLPTR) const;
inline QModelIndex createIndex(int row, int column, quintptr id) const;
void encodeData(const QModelIndexList &indexes, QDataStream &stream) const;
@@ -357,7 +357,7 @@ class Q_CORE_EXPORT QAbstractTableModel : public QAbstractItemModel
Q_OBJECT
public:
- explicit QAbstractTableModel(QObject *parent = 0);
+ explicit QAbstractTableModel(QObject *parent = Q_NULLPTR);
~QAbstractTableModel();
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
@@ -383,7 +383,7 @@ class Q_CORE_EXPORT QAbstractListModel : public QAbstractItemModel
Q_OBJECT
public:
- explicit QAbstractListModel(QObject *parent = 0);
+ explicit QAbstractListModel(QObject *parent = Q_NULLPTR);
~QAbstractListModel();
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
@@ -420,7 +420,7 @@ inline QVariant QModelIndex::data(int arole) const
{ return m ? m->data(*this, arole) : QVariant(); }
inline Qt::ItemFlags QModelIndex::flags() const
-{ return m ? m->flags(*this) : Qt::ItemFlags(0); }
+{ return m ? m->flags(*this) : Qt::ItemFlags(); }
inline uint qHash(const QModelIndex &index) Q_DECL_NOTHROW
{ return uint((index.row() << 4) + index.column() + index.internalId()); }
diff --git a/src/corelib/itemmodels/qabstractitemmodel_p.h b/src/corelib/itemmodels/qabstractitemmodel_p.h
index 075e6a9018..c2cbaf5298 100644
--- a/src/corelib/itemmodels/qabstractitemmodel_p.h
+++ b/src/corelib/itemmodels/qabstractitemmodel_p.h
@@ -71,6 +71,8 @@ class Q_CORE_EXPORT QAbstractItemModelPrivate : public QObjectPrivate
public:
QAbstractItemModelPrivate() : QObjectPrivate(), supportedDragActions(-1), roleNames(defaultRoleNames()) {}
+ ~QAbstractItemModelPrivate();
+
void removePersistentIndexData(QPersistentModelIndexData *data);
void movePersistentIndexes(const QVector<QPersistentModelIndexData *> &indexes, int change, const QModelIndex &parent, Qt::Orientation orientation);
void rowsAboutToBeInserted(const QModelIndex &parent, int first, int last);
@@ -162,6 +164,7 @@ public:
QHash<int,QByteArray> roleNames;
static const QHash<int,QByteArray> &defaultRoleNames();
};
+Q_DECLARE_TYPEINFO(QAbstractItemModelPrivate::Change, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/corelib/itemmodels/qabstractproxymodel.cpp b/src/corelib/itemmodels/qabstractproxymodel.cpp
index 4d08306d28..dbbbbb8ff4 100644
--- a/src/corelib/itemmodels/qabstractproxymodel.cpp
+++ b/src/corelib/itemmodels/qabstractproxymodel.cpp
@@ -379,6 +379,7 @@ QMimeData* QAbstractProxyModel::mimeData(const QModelIndexList &indexes) const
{
Q_D(const QAbstractProxyModel);
QModelIndexList list;
+ list.reserve(indexes.count());
foreach(const QModelIndex &index, indexes)
list << mapToSource(index);
return d->model->mimeData(list);
diff --git a/src/corelib/itemmodels/qabstractproxymodel.h b/src/corelib/itemmodels/qabstractproxymodel.h
index dc8d2d4dc8..a4cb74830b 100644
--- a/src/corelib/itemmodels/qabstractproxymodel.h
+++ b/src/corelib/itemmodels/qabstractproxymodel.h
@@ -50,7 +50,7 @@ class Q_CORE_EXPORT QAbstractProxyModel : public QAbstractItemModel
Q_PROPERTY(QAbstractItemModel* sourceModel READ sourceModel WRITE setSourceModel NOTIFY sourceModelChanged)
public:
- explicit QAbstractProxyModel(QObject *parent = 0);
+ explicit QAbstractProxyModel(QObject *parent = Q_NULLPTR);
~QAbstractProxyModel();
virtual void setSourceModel(QAbstractItemModel *sourceModel);
diff --git a/src/corelib/itemmodels/qidentityproxymodel.cpp b/src/corelib/itemmodels/qidentityproxymodel.cpp
index f773219aeb..f46fd135ca 100644
--- a/src/corelib/itemmodels/qidentityproxymodel.cpp
+++ b/src/corelib/itemmodels/qidentityproxymodel.cpp
@@ -212,6 +212,7 @@ QItemSelection QIdentityProxyModel::mapSelectionFromSource(const QItemSelection&
QItemSelection::const_iterator it = selection.constBegin();
const QItemSelection::const_iterator end = selection.constEnd();
+ proxySelection.reserve(selection.count());
for ( ; it != end; ++it) {
Q_ASSERT(it->model() == d->model);
const QItemSelectionRange range(mapFromSource(it->topLeft()), mapFromSource(it->bottomRight()));
@@ -234,6 +235,7 @@ QItemSelection QIdentityProxyModel::mapSelectionToSource(const QItemSelection& s
QItemSelection::const_iterator it = selection.constBegin();
const QItemSelection::const_iterator end = selection.constEnd();
+ sourceSelection.reserve(selection.count());
for ( ; it != end; ++it) {
Q_ASSERT(it->model() == this);
const QItemSelectionRange range(mapToSource(it->topLeft()), mapToSource(it->bottomRight()));
@@ -269,6 +271,7 @@ QModelIndexList QIdentityProxyModel::match(const QModelIndex& start, int role, c
QModelIndexList::const_iterator it = sourceList.constBegin();
const QModelIndexList::const_iterator end = sourceList.constEnd();
QModelIndexList proxyList;
+ proxyList.reserve(sourceList.count());
for ( ; it != end; ++it)
proxyList.append(mapFromSource(*it));
return proxyList;
diff --git a/src/corelib/itemmodels/qidentityproxymodel.h b/src/corelib/itemmodels/qidentityproxymodel.h
index e4587cb386..7578f8d380 100644
--- a/src/corelib/itemmodels/qidentityproxymodel.h
+++ b/src/corelib/itemmodels/qidentityproxymodel.h
@@ -48,7 +48,7 @@ class Q_CORE_EXPORT QIdentityProxyModel : public QAbstractProxyModel
{
Q_OBJECT
public:
- explicit QIdentityProxyModel(QObject* parent = 0);
+ explicit QIdentityProxyModel(QObject* parent = Q_NULLPTR);
~QIdentityProxyModel();
int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
diff --git a/src/corelib/itemmodels/qitemselectionmodel.cpp b/src/corelib/itemmodels/qitemselectionmodel.cpp
index de28953fb5..ba97543c44 100644
--- a/src/corelib/itemmodels/qitemselectionmodel.cpp
+++ b/src/corelib/itemmodels/qitemselectionmodel.cpp
@@ -104,6 +104,14 @@ QT_BEGIN_NAMESPACE
*/
/*!
+ \fn QItemSelectionRange::swap(QItemSelectionRange &other)
+ \since 5.6
+
+ Swaps this selection range's contents with \a other.
+ This function is very fast and never fails.
+*/
+
+/*!
\fn int QItemSelectionRange::top() const
Returns the row index corresponding to the uppermost selected row in the
@@ -1770,7 +1778,7 @@ const QAbstractItemModel *QItemSelectionModel::model() const
/*!
\since 5.5
- Sets the model. The modelChanged() signal will be emitted.
+ Sets the model to \a model. The modelChanged() signal will be emitted.
\sa model(), modelChanged()
*/
diff --git a/src/corelib/itemmodels/qitemselectionmodel.h b/src/corelib/itemmodels/qitemselectionmodel.h
index 4fe836c098..09b710175e 100644
--- a/src/corelib/itemmodels/qitemselectionmodel.h
+++ b/src/corelib/itemmodels/qitemselectionmodel.h
@@ -48,12 +48,28 @@ class Q_CORE_EXPORT QItemSelectionRange
{
public:
- inline QItemSelectionRange() {}
+ inline QItemSelectionRange() : tl(), br() {}
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+ // ### Qt 6: remove them all, the compiler-generated ones are fine
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; }
+# ifdef Q_COMPILER_RVALUE_REFS
+ QItemSelectionRange(QItemSelectionRange &&other) Q_DECL_NOTHROW
+ : tl(std::move(other.tl)), br(std::move(other.br)) {}
+ QItemSelectionRange &operator=(QItemSelectionRange &&other) Q_DECL_NOTHROW
+ { tl = std::move(other.tl); br = std::move(other.br); return *this; }
+# endif
+ QItemSelectionRange &operator=(const QItemSelectionRange &other)
+ { tl = other.tl; br = other.br; return *this; }
+#endif // Qt < 6
+ QItemSelectionRange(const QModelIndex &topL, const QModelIndex &bottomR) : tl(topL), br(bottomR) {}
+ explicit QItemSelectionRange(const QModelIndex &index) : tl(index), br(tl) {}
+
+ void swap(QItemSelectionRange &other) Q_DECL_NOTHROW
+ {
+ qSwap(tl, other.tl);
+ qSwap(br, other.br);
+ }
inline int top() const { return tl.row(); }
inline int left() const { return tl.column(); }
@@ -133,10 +149,6 @@ private:
};
Q_DECLARE_TYPEINFO(QItemSelectionRange, Q_MOVABLE_TYPE);
-inline QItemSelectionRange::QItemSelectionRange(const QModelIndex &atopLeft,
- const QModelIndex &abottomRight)
-{ tl = atopLeft; br = abottomRight; }
-
class QItemSelection;
class QItemSelectionModelPrivate;
@@ -170,7 +182,7 @@ public:
Q_DECLARE_FLAGS(SelectionFlags, SelectionFlag)
Q_FLAG(SelectionFlags)
- explicit QItemSelectionModel(QAbstractItemModel *model = 0);
+ explicit QItemSelectionModel(QAbstractItemModel *model = Q_NULLPTR);
explicit QItemSelectionModel(QAbstractItemModel *model, QObject *parent);
virtual ~QItemSelectionModel();
@@ -235,8 +247,11 @@ inline uint qHash(const QItemSelectionRange &) { return 0; }
class Q_CORE_EXPORT QItemSelection : public QList<QItemSelectionRange>
{
public:
- QItemSelection() {}
+ QItemSelection() Q_DECL_NOTHROW : QList<QItemSelectionRange>() {}
QItemSelection(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+
+ // reusing QList::swap() here is OK!
+
void select(const QModelIndex &topLeft, const QModelIndex &bottomRight);
bool contains(const QModelIndex &index) const;
QModelIndexList indexes() const;
@@ -245,6 +260,7 @@ public:
const QItemSelectionRange &other,
QItemSelection *result);
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QItemSelection)
#ifndef QT_NO_DEBUG_STREAM
Q_CORE_EXPORT QDebug operator<<(QDebug, const QItemSelectionRange &);
diff --git a/src/corelib/itemmodels/qsortfilterproxymodel.cpp b/src/corelib/itemmodels/qsortfilterproxymodel.cpp
index 6853cbd38f..0771fd0e30 100644
--- a/src/corelib/itemmodels/qsortfilterproxymodel.cpp
+++ b/src/corelib/itemmodels/qsortfilterproxymodel.cpp
@@ -272,6 +272,7 @@ public:
QModelIndexPairList store_persistent_indexes();
void update_persistent_indexes(const QModelIndexPairList &source_indexes);
+ void filter_about_to_be_changed(const QModelIndex &source_parent = QModelIndex());
void filter_changed(const QModelIndex &source_parent = QModelIndex());
QSet<int> handle_filter_changed(
QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
@@ -1011,6 +1012,7 @@ QModelIndexPairList QSortFilterProxyModelPrivate::store_persistent_indexes()
{
Q_Q(QSortFilterProxyModel);
QModelIndexPairList source_indexes;
+ source_indexes.reserve(persistent.indexes.count());
foreach (QPersistentModelIndexData *data, persistent.indexes) {
QModelIndex proxy_index = data->index;
QModelIndex source_index = q->mapToSource(proxy_index);
@@ -1030,7 +1032,10 @@ void QSortFilterProxyModelPrivate::update_persistent_indexes(
{
Q_Q(QSortFilterProxyModel);
QModelIndexList from, to;
- for (int i = 0; i < source_indexes.count(); ++i) {
+ const int numSourceIndexes = source_indexes.count();
+ from.reserve(numSourceIndexes);
+ to.reserve(numSourceIndexes);
+ for (int i = 0; i < numSourceIndexes; ++i) {
QModelIndex source_index = source_indexes.at(i).second;
QModelIndex old_proxy_index = source_indexes.at(i).first;
create_mapping(source_index.parent());
@@ -1041,6 +1046,19 @@ void QSortFilterProxyModelPrivate::update_persistent_indexes(
q->changePersistentIndexList(from, to);
}
+/*!
+ \internal
+
+ Updates the source_index mapping in case it's invalid and we
+ need it because we have a valid filter
+*/
+void QSortFilterProxyModelPrivate::filter_about_to_be_changed(const QModelIndex &source_parent)
+{
+ if (!filter_regexp.pattern().isEmpty() &&
+ source_index_mapping.constFind(source_parent) == source_index_mapping.constEnd())
+ create_mapping(source_parent);
+}
+
/*!
\internal
@@ -2013,7 +2031,9 @@ QMimeData *QSortFilterProxyModel::mimeData(const QModelIndexList &indexes) const
{
Q_D(const QSortFilterProxyModel);
QModelIndexList source_indexes;
- for (int i = 0; i < indexes.count(); ++i)
+ const int numIndexes = indexes.count();
+ source_indexes.reserve(numIndexes);
+ for (int i = 0; i < numIndexes; ++i)
source_indexes << mapToSource(indexes.at(i));
return d->model->mimeData(source_indexes);
}
@@ -2108,6 +2128,7 @@ bool QSortFilterProxyModel::removeRows(int row, int count, const QModelIndex &pa
// remove corresponding source intervals
// ### if this proves to be slow, we can switch to single-row removal
QVector<int> rows;
+ rows.reserve(count);
for (int i = row; i < row + count; ++i)
rows.append(m->source_rows.at(i));
std::sort(rows.begin(), rows.end());
@@ -2147,6 +2168,7 @@ bool QSortFilterProxyModel::removeColumns(int column, int count, const QModelInd
}
// remove corresponding source intervals
QVector<int> columns;
+ columns.reserve(count);
for (int i = column; i < column + count; ++i)
columns.append(m->source_columns.at(i));
@@ -2298,6 +2320,7 @@ QRegExp QSortFilterProxyModel::filterRegExp() const
void QSortFilterProxyModel::setFilterRegExp(const QRegExp &regExp)
{
Q_D(QSortFilterProxyModel);
+ d->filter_about_to_be_changed();
d->filter_regexp = regExp;
d->filter_changed();
}
@@ -2319,6 +2342,7 @@ int QSortFilterProxyModel::filterKeyColumn() const
void QSortFilterProxyModel::setFilterKeyColumn(int column)
{
Q_D(QSortFilterProxyModel);
+ d->filter_about_to_be_changed();
d->filter_column = column;
d->filter_changed();
}
@@ -2344,6 +2368,7 @@ void QSortFilterProxyModel::setFilterCaseSensitivity(Qt::CaseSensitivity cs)
Q_D(QSortFilterProxyModel);
if (cs == d->filter_regexp.caseSensitivity())
return;
+ d->filter_about_to_be_changed();
d->filter_regexp.setCaseSensitivity(cs);
d->filter_changed();
}
@@ -2409,6 +2434,7 @@ void QSortFilterProxyModel::setSortLocaleAware(bool on)
void QSortFilterProxyModel::setFilterRegExp(const QString &pattern)
{
Q_D(QSortFilterProxyModel);
+ d->filter_about_to_be_changed();
d->filter_regexp.setPatternSyntax(QRegExp::RegExp);
d->filter_regexp.setPattern(pattern);
d->filter_changed();
@@ -2423,6 +2449,7 @@ void QSortFilterProxyModel::setFilterRegExp(const QString &pattern)
void QSortFilterProxyModel::setFilterWildcard(const QString &pattern)
{
Q_D(QSortFilterProxyModel);
+ d->filter_about_to_be_changed();
d->filter_regexp.setPatternSyntax(QRegExp::Wildcard);
d->filter_regexp.setPattern(pattern);
d->filter_changed();
@@ -2437,6 +2464,7 @@ void QSortFilterProxyModel::setFilterWildcard(const QString &pattern)
void QSortFilterProxyModel::setFilterFixedString(const QString &pattern)
{
Q_D(QSortFilterProxyModel);
+ d->filter_about_to_be_changed();
d->filter_regexp.setPatternSyntax(QRegExp::FixedString);
d->filter_regexp.setPattern(pattern);
d->filter_changed();
@@ -2516,6 +2544,7 @@ void QSortFilterProxyModel::setFilterRole(int role)
Q_D(QSortFilterProxyModel);
if (d->filter_role == role)
return;
+ d->filter_about_to_be_changed();
d->filter_role = role;
d->filter_changed();
}
diff --git a/src/corelib/itemmodels/qsortfilterproxymodel.h b/src/corelib/itemmodels/qsortfilterproxymodel.h
index a08d7c6416..4be5aedd48 100644
--- a/src/corelib/itemmodels/qsortfilterproxymodel.h
+++ b/src/corelib/itemmodels/qsortfilterproxymodel.h
@@ -63,7 +63,7 @@ class Q_CORE_EXPORT QSortFilterProxyModel : public QAbstractProxyModel
Q_PROPERTY(int filterRole READ filterRole WRITE setFilterRole)
public:
- explicit QSortFilterProxyModel(QObject *parent = 0);
+ explicit QSortFilterProxyModel(QObject *parent = Q_NULLPTR);
~QSortFilterProxyModel();
void setSourceModel(QAbstractItemModel *sourceModel) Q_DECL_OVERRIDE;
diff --git a/src/corelib/itemmodels/qstringlistmodel.cpp b/src/corelib/itemmodels/qstringlistmodel.cpp
index 2853be3fda..dad736b445 100644
--- a/src/corelib/itemmodels/qstringlistmodel.cpp
+++ b/src/corelib/itemmodels/qstringlistmodel.cpp
@@ -257,7 +257,9 @@ void QStringListModel::sort(int, Qt::SortOrder order)
emit layoutAboutToBeChanged(QList<QPersistentModelIndex>(), VerticalSortHint);
QList<QPair<QString, int> > list;
- for (int i = 0; i < lst.count(); ++i)
+ const int lstCount = lst.count();
+ list.reserve(lstCount);
+ for (int i = 0; i < lstCount; ++i)
list.append(QPair<QString, int>(lst.at(i), i));
if (order == Qt::AscendingOrder)
diff --git a/src/corelib/itemmodels/qstringlistmodel.h b/src/corelib/itemmodels/qstringlistmodel.h
index 973007995b..a1cb923dbb 100644
--- a/src/corelib/itemmodels/qstringlistmodel.h
+++ b/src/corelib/itemmodels/qstringlistmodel.h
@@ -46,8 +46,8 @@ class Q_CORE_EXPORT QStringListModel : public QAbstractListModel
{
Q_OBJECT
public:
- explicit QStringListModel(QObject *parent = 0);
- explicit QStringListModel(const QStringList &strings, QObject *parent = 0);
+ explicit QStringListModel(QObject *parent = Q_NULLPTR);
+ explicit QStringListModel(const QStringList &strings, QObject *parent = Q_NULLPTR);
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
QModelIndex sibling(int row, int column, const QModelIndex &idx) const Q_DECL_OVERRIDE;
diff --git a/src/corelib/json/qjsonarray.cpp b/src/corelib/json/qjsonarray.cpp
index 77a3d0a2b8..dd27603d6d 100644
--- a/src/corelib/json/qjsonarray.cpp
+++ b/src/corelib/json/qjsonarray.cpp
@@ -271,6 +271,7 @@ QVariantList QJsonArray::toVariantList() const
QVariantList list;
if (a) {
+ list.reserve(a->length);
for (int i = 0; i < (int)a->length; ++i)
list.append(QJsonValue(d, a, a->at(i)).toVariant());
}
diff --git a/src/corelib/json/qjsonarray.h b/src/corelib/json/qjsonarray.h
index 6148642106..611e1f4193 100644
--- a/src/corelib/json/qjsonarray.h
+++ b/src/corelib/json/qjsonarray.h
@@ -107,7 +107,7 @@ public:
typedef QJsonValueRef reference;
typedef QJsonValueRefPtr pointer;
- inline iterator() : a(0), i(0) { }
+ inline iterator() : a(Q_NULLPTR), i(0) { }
explicit inline iterator(QJsonArray *array, int index) : a(array), i(index) { }
inline QJsonValueRef operator*() const { return QJsonValueRef(a, i); }
@@ -152,9 +152,11 @@ public:
typedef QJsonValue reference;
typedef QJsonValuePtr pointer;
- inline const_iterator() : a(0), i(0) { }
+ inline const_iterator() : a(Q_NULLPTR), i(0) { }
explicit inline const_iterator(const QJsonArray *array, int index) : a(array), i(index) { }
- inline const_iterator(const const_iterator &o) : a(o.a), i(o.i) {}
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+ inline const_iterator(const const_iterator &o) : a(o.a), i(o.i) {} // ### Qt 6: Removed so class can be trivially-copyable
+#endif
inline const_iterator(const iterator &o) : a(o.a), i(o.i) {}
inline QJsonValue operator*() const { return a->at(i); }
diff --git a/src/corelib/json/qjsondocument.h b/src/corelib/json/qjsondocument.h
index 285b42c6c8..d7a88b2f15 100644
--- a/src/corelib/json/qjsondocument.h
+++ b/src/corelib/json/qjsondocument.h
@@ -106,7 +106,7 @@ public:
Compact
};
- static QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error = 0);
+ static QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error = Q_NULLPTR);
#ifdef Q_QDOC
QByteArray toJson(JsonFormat format = Indented) const;
diff --git a/src/corelib/json/qjsonobject.cpp b/src/corelib/json/qjsonobject.cpp
index ae44cd9ff9..b7dfe88434 100644
--- a/src/corelib/json/qjsonobject.cpp
+++ b/src/corelib/json/qjsonobject.cpp
@@ -274,7 +274,7 @@ QStringList QJsonObject::keys() const
return QStringList();
QStringList keys;
-
+ keys.reserve(o->length);
for (uint i = 0; i < o->length; ++i) {
QJsonPrivate::Entry *e = o->entryAt(i);
keys.append(e->key());
diff --git a/src/corelib/json/qjsonobject.h b/src/corelib/json/qjsonobject.h
index 5f24ac3ac8..19c938fd83 100644
--- a/src/corelib/json/qjsonobject.h
+++ b/src/corelib/json/qjsonobject.h
@@ -105,7 +105,7 @@ public:
typedef QJsonValue value_type;
typedef QJsonValueRef reference;
- Q_DECL_CONSTEXPR inline iterator() : o(0), i(0) {}
+ Q_DECL_CONSTEXPR inline iterator() : o(Q_NULLPTR), i(0) {}
Q_DECL_CONSTEXPR inline iterator(QJsonObject *obj, int index) : o(obj), i(index) {}
inline QString key() const { return o->keyAt(i); }
@@ -147,7 +147,7 @@ public:
typedef QJsonValue value_type;
typedef QJsonValue reference;
- Q_DECL_CONSTEXPR inline const_iterator() : o(0), i(0) {}
+ Q_DECL_CONSTEXPR inline const_iterator() : o(Q_NULLPTR), i(0) {}
Q_DECL_CONSTEXPR inline const_iterator(const QJsonObject *obj, int index)
: o(obj), i(index) {}
inline const_iterator(const iterator &other)
diff --git a/src/corelib/kernel/qabstracteventdispatcher.h b/src/corelib/kernel/qabstracteventdispatcher.h
index c80f7d3d08..eb357cefe5 100644
--- a/src/corelib/kernel/qabstracteventdispatcher.h
+++ b/src/corelib/kernel/qabstracteventdispatcher.h
@@ -64,10 +64,10 @@ public:
{ }
};
- explicit QAbstractEventDispatcher(QObject *parent = 0);
+ explicit QAbstractEventDispatcher(QObject *parent = Q_NULLPTR);
~QAbstractEventDispatcher();
- static QAbstractEventDispatcher *instance(QThread *thread = 0);
+ static QAbstractEventDispatcher *instance(QThread *thread = Q_NULLPTR);
virtual bool processEvents(QEventLoop::ProcessEventsFlags flags) = 0;
virtual bool hasPendingEvents() = 0; // ### Qt6: remove, mark final or make protected
diff --git a/src/corelib/kernel/qcore_mac_objc.mm b/src/corelib/kernel/qcore_mac_objc.mm
index a215557aed..14c0f803b9 100644
--- a/src/corelib/kernel/qcore_mac_objc.mm
+++ b/src/corelib/kernel/qcore_mac_objc.mm
@@ -131,5 +131,22 @@ QAppleOperatingSystemVersion qt_apple_os_version()
return v;
}
+// -------------------------------------------------------------------------
+
+QMacAutoReleasePool::QMacAutoReleasePool()
+ : pool([[NSAutoreleasePool alloc] init])
+{
+}
+
+QMacAutoReleasePool::~QMacAutoReleasePool()
+{
+ // Drain behaves the same as release, with the advantage that
+ // if we're ever used in a garbage-collected environment, the
+ // drain acts as a hint to the garbage collector to collect.
+ [pool drain];
+}
+
+// -------------------------------------------------------------------------
+
QT_END_NAMESPACE
diff --git a/src/corelib/kernel/qcore_unix_p.h b/src/corelib/kernel/qcore_unix_p.h
index fa083a3f44..c744873fce 100644
--- a/src/corelib/kernel/qcore_unix_p.h
+++ b/src/corelib/kernel/qcore_unix_p.h
@@ -67,24 +67,6 @@
struct sockaddr;
-#if defined(Q_OS_LINUX) && defined(O_CLOEXEC)
-# define QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC 1
-QT_BEGIN_NAMESPACE
-namespace QtLibcSupplement {
- inline int accept4(int, sockaddr *, QT_SOCKLEN_T *, int)
- { errno = ENOSYS; return -1; }
- inline int dup3(int, int, int)
- { errno = ENOSYS; return -1; }
- inline int pipe2(int [], int )
- { errno = ENOSYS; return -1; }
-}
-QT_END_NAMESPACE
-using namespace QT_PREPEND_NAMESPACE(QtLibcSupplement);
-
-#else
-# define QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC 0
-#endif
-
#define EINTR_LOOP(var, cmd) \
do { \
var = cmd; \
@@ -179,22 +161,14 @@ static inline int qt_safe_open(const char *pathname, int flags, mode_t mode = 07
// call qt_safe_pipe
static inline int qt_safe_pipe(int pipefd[2], int flags = 0)
{
-#ifdef O_CLOEXEC
- Q_ASSERT((flags & ~(O_CLOEXEC | O_NONBLOCK)) == 0);
-#else
Q_ASSERT((flags & ~O_NONBLOCK) == 0);
-#endif
- int ret;
-#if QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC && defined(O_CLOEXEC)
+#ifdef QT_THREADSAFE_CLOEXEC
// use pipe2
flags |= O_CLOEXEC;
- ret = ::pipe2(pipefd, flags); // pipe2 is Linux-specific and is documented not to return EINTR
- if (ret == 0 || errno != ENOSYS)
- return ret;
-#endif
-
- ret = ::pipe(pipefd);
+ return ::pipe2(pipefd, flags); // pipe2 is documented not to return EINTR
+#else
+ int ret = ::pipe(pipefd);
if (ret == -1)
return -1;
@@ -208,6 +182,7 @@ static inline int qt_safe_pipe(int pipefd[2], int flags = 0)
}
return 0;
+#endif
}
#endif // Q_OS_VXWORKS
@@ -217,22 +192,19 @@ static inline int qt_safe_dup(int oldfd, int atleast = 0, int flags = FD_CLOEXEC
{
Q_ASSERT(flags == FD_CLOEXEC || flags == 0);
- int ret;
#ifdef F_DUPFD_CLOEXEC
- // use this fcntl
- if (flags & FD_CLOEXEC) {
- ret = ::fcntl(oldfd, F_DUPFD_CLOEXEC, atleast);
- if (ret != -1 || errno != EINVAL)
- return ret;
- }
-#endif
-
+ int cmd = F_DUPFD;
+ if (flags & FD_CLOEXEC)
+ cmd = F_DUPFD_CLOEXEC;
+ return ::fcntl(oldfd, cmd, atleast);
+#else
// use F_DUPFD
- ret = ::fcntl(oldfd, F_DUPFD, atleast);
+ int ret = ::fcntl(oldfd, F_DUPFD, atleast);
if (flags && ret != -1)
::fcntl(ret, F_SETFD, flags);
return ret;
+#endif
}
// don't call dup2
@@ -242,14 +214,11 @@ static inline int qt_safe_dup2(int oldfd, int newfd, int flags = FD_CLOEXEC)
Q_ASSERT(flags == FD_CLOEXEC || flags == 0);
int ret;
-#if QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC && defined(O_CLOEXEC)
+#ifdef QT_THREADSAFE_CLOEXEC
// use dup3
- if (flags & FD_CLOEXEC) {
- EINTR_LOOP(ret, ::dup3(oldfd, newfd, O_CLOEXEC));
- if (ret == 0 || errno != ENOSYS)
- return ret;
- }
-#endif
+ EINTR_LOOP(ret, ::dup3(oldfd, newfd, flags ? O_CLOEXEC : 0));
+ return ret;
+#else
EINTR_LOOP(ret, ::dup2(oldfd, newfd));
if (ret == -1)
return -1;
@@ -257,6 +226,7 @@ static inline int qt_safe_dup2(int oldfd, int newfd, int flags = FD_CLOEXEC)
if (flags)
::fcntl(newfd, F_SETFD, flags);
return 0;
+#endif
}
static inline qint64 qt_safe_read(int fd, void *data, qint64 maxlen)
diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp
index 37a26cf556..8f4774a1e0 100644
--- a/src/corelib/kernel/qcoreapplication.cpp
+++ b/src/corelib/kernel/qcoreapplication.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
@@ -45,7 +46,6 @@
#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
-#include <qhash.h>
#include <qmutex.h>
#include <private/qloggingregistry_p.h>
#include <qstandardpaths.h>
@@ -323,15 +323,9 @@ uint QCoreApplicationPrivate::attribs = (1 << Qt::AA_SynthesizeMouseForUnhandled
struct QCoreApplicationData {
QCoreApplicationData() Q_DECL_NOTHROW {
-#ifndef QT_NO_LIBRARY
- app_libpaths = 0;
-#endif
applicationNameSet = false;
}
~QCoreApplicationData() {
-#ifndef QT_NO_LIBRARY
- delete app_libpaths;
-#endif
#ifndef QT_NO_QOBJECT
// cleanup the QAdoptedThread created for the main() thread
if (QCoreApplicationPrivate::theMainThread) {
@@ -375,7 +369,8 @@ struct QCoreApplicationData {
bool applicationNameSet; // true if setApplicationName was called
#ifndef QT_NO_LIBRARY
- QStringList *app_libpaths;
+ QScopedPointer<QStringList> app_libpaths;
+ QScopedPointer<QStringList> manual_libpaths;
#endif
};
@@ -538,6 +533,14 @@ QThread *QCoreApplicationPrivate::mainThread()
return theMainThread;
}
+bool QCoreApplicationPrivate::threadRequiresCoreApplication()
+{
+ QThreadData *data = QThreadData::current(false);
+ if (!data)
+ return true; // default setting
+ return data->requiresCoreApplication;
+}
+
void QCoreApplicationPrivate::checkReceiverThread(QObject *receiver)
{
QThread *currentThread = QThread::currentThread();
@@ -560,9 +563,9 @@ void QCoreApplicationPrivate::checkReceiverThread(QObject *receiver)
void QCoreApplicationPrivate::appendApplicationPathToLibraryPaths()
{
#ifndef QT_NO_LIBRARY
- QStringList *app_libpaths = coreappdata()->app_libpaths;
+ QStringList *app_libpaths = coreappdata()->app_libpaths.data();
if (!app_libpaths)
- coreappdata()->app_libpaths = app_libpaths = new QStringList;
+ coreappdata()->app_libpaths.reset(app_libpaths = new QStringList);
QString app_location = QCoreApplication::applicationFilePath();
app_location.truncate(app_location.lastIndexOf(QLatin1Char('/')));
#ifdef Q_OS_WINRT
@@ -759,6 +762,36 @@ void QCoreApplication::init()
QLoggingRegistry::instance()->init();
+#ifndef QT_NO_LIBRARY
+ // Reset the lib paths, so that they will be recomputed, taking the availability of argv[0]
+ // into account. If necessary, recompute right away and replay the manual changes on top of the
+ // new lib paths.
+ QStringList *appPaths = coreappdata()->app_libpaths.take();
+ QStringList *manualPaths = coreappdata()->manual_libpaths.take();
+ if (appPaths) {
+ if (manualPaths) {
+ // Replay the delta. As paths can only be prepended to the front or removed from
+ // anywhere in the list, we can just linearly scan the lists and find the items that
+ // have been removed. Once the original list is exhausted we know all the remaining
+ // items have been added.
+ QStringList newPaths(libraryPaths());
+ for (int i = manualPaths->length(), j = appPaths->length(); i > 0 || j > 0; qt_noop()) {
+ if (--j < 0) {
+ newPaths.prepend((*manualPaths)[--i]);
+ } else if (--i < 0) {
+ newPaths.removeAll((*appPaths)[j]);
+ } else if ((*manualPaths)[i] != (*appPaths)[j]) {
+ newPaths.removeAll((*appPaths)[j]);
+ ++i; // try again with next item.
+ }
+ }
+ delete manualPaths;
+ coreappdata()->manual_libpaths.reset(new QStringList(newPaths));
+ }
+ delete appPaths;
+ }
+#endif
+
#ifndef QT_NO_QOBJECT
// use the event dispatcher created by the app programmer (if any)
if (!QCoreApplicationPrivate::eventDispatcher)
@@ -777,11 +810,6 @@ void QCoreApplication::init()
d->eventDispatcherReady();
#endif
-#ifndef QT_NO_LIBRARY
- if (coreappdata()->app_libpaths)
- d->appendApplicationPathToLibraryPaths();
-#endif
-
#ifdef QT_EVAL
extern void qt_core_eval_init(QCoreApplicationPrivate::Type);
qt_core_eval_init(d->application_type);
@@ -834,8 +862,8 @@ QCoreApplication::~QCoreApplication()
#endif
#ifndef QT_NO_LIBRARY
- delete coreappdata()->app_libpaths;
- coreappdata()->app_libpaths = 0;
+ coreappdata()->app_libpaths.reset();
+ coreappdata()->manual_libpaths.reset();
#endif
}
@@ -909,31 +937,21 @@ bool QCoreApplication::testAttribute(Qt::ApplicationAttribute attribute)
/*!
\property QCoreApplication::quitLockEnabled
- Returns \c true if the use of the QEventLoopLocker feature can cause the
- application to quit, otherwise returns \c false.
+ \brief Whether the use of the QEventLoopLocker feature can cause the
+ application to quit.
+
+ The default is \c true.
\sa QEventLoopLocker
*/
-/*!
- Returns \c true if the use of the QEventLoopLocker feature can cause the
- application to quit, otherwise returns \c false.
-
- \sa QEventLoopLocker
- */
bool QCoreApplication::isQuitLockEnabled()
{
return quitLockRefEnabled;
}
-/*!
- Enables the ability of the QEventLoopLocker feature to quit
- the application.
-
- If disabled, the use of QEventLoopLocker will not quit the application.
+static bool doNotify(QObject *, QEvent *);
- \sa QEventLoopLocker
- */
void QCoreApplication::setQuitLockEnabled(bool enabled)
{
quitLockRefEnabled = enabled;
@@ -941,12 +959,29 @@ void QCoreApplication::setQuitLockEnabled(bool enabled)
/*!
\internal
+ \deprecated
This function is here to make it possible for Qt extensions to
hook into event notification without subclassing QApplication
*/
bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
{
+ return notifyInternal2(receiver, event);
+}
+
+/*!
+ \internal
+ \since 5.6
+
+ This function is here to make it possible for Qt extensions to
+ hook into event notification without subclassing QApplication.
+*/
+bool QCoreApplication::notifyInternal2(QObject *receiver, QEvent *event)
+{
+ bool selfRequired = QCoreApplicationPrivate::threadRequiresCoreApplication();
+ if (!self && selfRequired)
+ return false;
+
// Make it possible for Qt Script to hook into events even
// though QApplication is subclassed...
bool result = false;
@@ -962,10 +997,11 @@ bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
QObjectPrivate *d = receiver->d_func();
QThreadData *threadData = d->threadData;
QScopedLoopLevelCounter loopLevelCounter(threadData);
- return notify(receiver, event);
+ if (!selfRequired)
+ return doNotify(receiver, event);
+ return self->notify(receiver, event);
}
-
/*!
Sends \a event to \a receiver: \a {receiver}->event(\a event).
Returns the value that is returned from the receiver's event
@@ -1021,26 +1057,32 @@ bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
bool QCoreApplication::notify(QObject *receiver, QEvent *event)
{
- Q_D(QCoreApplication);
// no events are delivered after ~QCoreApplication() has started
if (QCoreApplicationPrivate::is_app_closing)
return true;
+ return doNotify(receiver, event);
+}
+static bool doNotify(QObject *receiver, QEvent *event)
+{
if (receiver == 0) { // serious error
qWarning("QCoreApplication::notify: Unexpected null receiver");
return true;
}
#ifndef QT_NO_DEBUG
- d->checkReceiverThread(receiver);
+ QCoreApplicationPrivate::checkReceiverThread(receiver);
#endif
- return receiver->isWidgetType() ? false : d->notify_helper(receiver, event);
+ return receiver->isWidgetType() ? false : QCoreApplicationPrivate::notify_helper(receiver, event);
}
bool QCoreApplicationPrivate::sendThroughApplicationEventFilters(QObject *receiver, QEvent *event)
{
- if (receiver->d_func()->threadData == this->threadData && extraData) {
+ // We can't access the application event filters outside of the main thread (race conditions)
+ Q_ASSERT(receiver->d_func()->threadData->thread == mainThread());
+
+ if (extraData) {
// application event filters are only called for objects in the GUI thread
for (int i = 0; i < extraData->eventFilters.size(); ++i) {
QObject *obj = extraData->eventFilters.at(i);
@@ -1059,8 +1101,7 @@ bool QCoreApplicationPrivate::sendThroughApplicationEventFilters(QObject *receiv
bool QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject *receiver, QEvent *event)
{
- Q_Q(QCoreApplication);
- if (receiver != q && receiver->d_func()->extraData) {
+ if (receiver != QCoreApplication::instance() && receiver->d_func()->extraData) {
for (int i = 0; i < receiver->d_func()->extraData->eventFilters.size(); ++i) {
QObject *obj = receiver->d_func()->extraData->eventFilters.at(i);
if (!obj)
@@ -1079,12 +1120,14 @@ bool QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject *receiver, Q
/*!
\internal
- Helper function called by notify()
+ Helper function called by QCoreApplicationPrivate::notify() and qapplication.cpp
*/
bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
{
- // send to all application event filters
- if (sendThroughApplicationEventFilters(receiver, event))
+ // send to all application event filters (only does anything in the main thread)
+ if (QCoreApplication::self
+ && receiver->d_func()->threadData->thread == mainThread()
+ && QCoreApplication::self->d_func()->sendThroughApplicationEventFilters(receiver, event))
return true;
// send to all receiver event filters
if (sendThroughObjectEventFilters(receiver, event))
@@ -1764,7 +1807,7 @@ void QCoreApplicationPrivate::maybeQuit()
Tells the application to exit with return code 0 (success).
Equivalent to calling QCoreApplication::exit(0).
- It's common to connect the QApplication::lastWindowClosed() signal
+ It's common to connect the QGuiApplication::lastWindowClosed() signal
to quit(), and you also often connect e.g. QAbstractButton::clicked() or
signals in QAction, QMenu, or QMenuBar to it.
@@ -1772,7 +1815,7 @@ void QCoreApplicationPrivate::maybeQuit()
\snippet code/src_corelib_kernel_qcoreapplication.cpp 1
- \sa exit(), aboutToQuit(), QApplication::lastWindowClosed()
+ \sa exit(), aboutToQuit(), QGuiApplication::lastWindowClosed()
*/
void QCoreApplication::quit()
@@ -2468,28 +2511,17 @@ Q_GLOBAL_STATIC_WITH_ARGS(QMutex, libraryPathMutex, (QMutex::Recursive))
QStringList QCoreApplication::libraryPaths()
{
QMutexLocker locker(libraryPathMutex());
- if (!coreappdata()->app_libpaths) {
- QStringList *app_libpaths = coreappdata()->app_libpaths = new QStringList;
- QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath);
- if (QFile::exists(installPathPlugins)) {
- // Make sure we convert from backslashes to slashes.
- installPathPlugins = QDir(installPathPlugins).canonicalPath();
- if (!app_libpaths->contains(installPathPlugins))
- app_libpaths->append(installPathPlugins);
- }
- // If QCoreApplication is not yet instantiated,
- // make sure we add the application path when we construct the QCoreApplication
- if (self) self->d_func()->appendApplicationPathToLibraryPaths();
+ if (coreappdata()->manual_libpaths)
+ return *(coreappdata()->manual_libpaths);
+
+ if (!coreappdata()->app_libpaths) {
+ QStringList *app_libpaths = new QStringList;
+ coreappdata()->app_libpaths.reset(app_libpaths);
const QByteArray libPathEnv = qgetenv("QT_PLUGIN_PATH");
if (!libPathEnv.isEmpty()) {
-#if defined(Q_OS_WIN)
- QLatin1Char pathSep(';');
-#else
- QLatin1Char pathSep(':');
-#endif
- QStringList paths = QFile::decodeName(libPathEnv).split(pathSep, QString::SkipEmptyParts);
+ QStringList paths = QFile::decodeName(libPathEnv).split(QDir::listSeparator(), QString::SkipEmptyParts);
for (QStringList::const_iterator it = paths.constBegin(); it != paths.constEnd(); ++it) {
QString canonicalPath = QDir(*it).canonicalPath();
if (!canonicalPath.isEmpty()
@@ -2498,6 +2530,18 @@ QStringList QCoreApplication::libraryPaths()
}
}
}
+
+ QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath);
+ if (QFile::exists(installPathPlugins)) {
+ // Make sure we convert from backslashes to slashes.
+ installPathPlugins = QDir(installPathPlugins).canonicalPath();
+ if (!app_libpaths->contains(installPathPlugins))
+ app_libpaths->append(installPathPlugins);
+ }
+
+ // If QCoreApplication is not yet instantiated,
+ // make sure we add the application path when we construct the QCoreApplication
+ if (self) self->d_func()->appendApplicationPathToLibraryPaths();
}
return *(coreappdata()->app_libpaths);
}
@@ -2510,14 +2554,26 @@ QStringList QCoreApplication::libraryPaths()
\a paths. All existing paths will be deleted and the path list
will consist of the paths given in \a paths.
+ The library paths are reset to the default when an instance of
+ QCoreApplication is destructed.
+
\sa libraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary
*/
void QCoreApplication::setLibraryPaths(const QStringList &paths)
{
QMutexLocker locker(libraryPathMutex());
+
+ // setLibraryPaths() is considered a "remove everything and then add some new ones" operation.
+ // When the application is constructed it should still amend the paths. So we keep the originals
+ // around, and even create them if they don't exist, yet.
if (!coreappdata()->app_libpaths)
- coreappdata()->app_libpaths = new QStringList;
- *(coreappdata()->app_libpaths) = paths;
+ libraryPaths();
+
+ if (coreappdata()->manual_libpaths)
+ *(coreappdata()->manual_libpaths) = paths;
+ else
+ coreappdata()->manual_libpaths.reset(new QStringList(paths));
+
locker.unlock();
QFactoryLoader::refreshAll();
}
@@ -2532,6 +2588,9 @@ void QCoreApplication::setLibraryPaths(const QStringList &paths)
is \c INSTALL/plugins, where \c INSTALL is the directory where Qt was
installed.
+ The library paths are reset to the default when an instance of
+ QCoreApplication is destructed.
+
\sa removeLibraryPath(), libraryPaths(), setLibraryPaths()
*/
void QCoreApplication::addLibraryPath(const QString &path)
@@ -2539,24 +2598,38 @@ void QCoreApplication::addLibraryPath(const QString &path)
if (path.isEmpty())
return;
+ QString canonicalPath = QDir(path).canonicalPath();
+ if (canonicalPath.isEmpty())
+ return;
+
QMutexLocker locker(libraryPathMutex());
- // make sure that library paths is initialized
- libraryPaths();
+ QStringList *libpaths = coreappdata()->manual_libpaths.data();
+ if (libpaths) {
+ if (libpaths->contains(canonicalPath))
+ return;
+ } else {
+ // make sure that library paths are initialized
+ libraryPaths();
+ QStringList *app_libpaths = coreappdata()->app_libpaths.data();
+ if (app_libpaths->contains(canonicalPath))
+ return;
- QString canonicalPath = QDir(path).canonicalPath();
- if (!canonicalPath.isEmpty()
- && !coreappdata()->app_libpaths->contains(canonicalPath)) {
- coreappdata()->app_libpaths->prepend(canonicalPath);
- locker.unlock();
- QFactoryLoader::refreshAll();
+ coreappdata()->manual_libpaths.reset(libpaths = new QStringList(*app_libpaths));
}
+
+ libpaths->prepend(canonicalPath);
+ locker.unlock();
+ QFactoryLoader::refreshAll();
}
/*!
Removes \a path from the library path list. If \a path is empty or not
in the path list, the list is not changed.
+ The library paths are reset to the default when an instance of
+ QCoreApplication is destructed.
+
\sa addLibraryPath(), libraryPaths(), setLibraryPaths()
*/
void QCoreApplication::removeLibraryPath(const QString &path)
@@ -2564,13 +2637,28 @@ void QCoreApplication::removeLibraryPath(const QString &path)
if (path.isEmpty())
return;
+ QString canonicalPath = QDir(path).canonicalPath();
+ if (canonicalPath.isEmpty())
+ return;
+
QMutexLocker locker(libraryPathMutex());
- // make sure that library paths is initialized
- libraryPaths();
+ QStringList *libpaths = coreappdata()->manual_libpaths.data();
+ if (libpaths) {
+ if (libpaths->removeAll(canonicalPath) == 0)
+ return;
+ } else {
+ // make sure that library paths is initialized
+ libraryPaths();
+ QStringList *app_libpaths = coreappdata()->app_libpaths.data();
+ if (!app_libpaths->contains(canonicalPath))
+ return;
+
+ coreappdata()->manual_libpaths.reset(libpaths = new QStringList(*app_libpaths));
+ libpaths->removeAll(canonicalPath);
+ }
- QString canonicalPath = QDir(path).canonicalPath();
- coreappdata()->app_libpaths->removeAll(canonicalPath);
+ locker.unlock();
QFactoryLoader::refreshAll();
}
diff --git a/src/corelib/kernel/qcoreapplication.h b/src/corelib/kernel/qcoreapplication.h
index 1cd835daae..d865c4e7a8 100644
--- a/src/corelib/kernel/qcoreapplication.h
+++ b/src/corelib/kernel/qcoreapplication.h
@@ -117,7 +117,7 @@ public:
static bool sendEvent(QObject *receiver, QEvent *event);
static void postEvent(QObject *receiver, QEvent *event, int priority = Qt::NormalEventPriority);
- static void sendPostedEvents(QObject *receiver = 0, int event_type = 0);
+ static void sendPostedEvents(QObject *receiver = Q_NULLPTR, int event_type = 0);
static void removePostedEvents(QObject *receiver, int eventType = 0);
#if QT_DEPRECATED_SINCE(5, 3)
QT_DEPRECATED static bool hasPendingEvents();
@@ -149,7 +149,7 @@ public:
static QString translate(const char * context,
const char * key,
- const char * disambiguation = 0,
+ const char * disambiguation = Q_NULLPTR,
int n = -1);
#if QT_DEPRECATED_SINCE(5, 0)
enum Encoding { UnicodeUTF8, Latin1, DefaultCodec = UnicodeUTF8, CodecForTr = UnicodeUTF8 };
@@ -194,7 +194,10 @@ protected:
private:
#ifndef QT_NO_QOBJECT
static bool sendSpontaneousEvent(QObject *receiver, QEvent *event);
- bool notifyInternal(QObject *receiver, QEvent *event);
+# if QT_DEPRECATED_SINCE(5,6)
+ QT_DEPRECATED bool notifyInternal(QObject *receiver, QEvent *event); // ### Qt6 BIC: remove me
+# endif
+ static bool notifyInternal2(QObject *receiver, QEvent *);
#endif
void init();
@@ -221,23 +224,23 @@ private:
#ifndef QT_NO_QOBJECT
inline bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
-{ if (event) event->spont = false; return self ? self->notifyInternal(receiver, event) : false; }
+{ if (event) event->spont = false; return notifyInternal2(receiver, event); }
inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
-{ if (event) event->spont = true; return self ? self->notifyInternal(receiver, event) : false; }
+{ if (event) event->spont = true; return notifyInternal2(receiver, event); }
#endif
#ifdef QT_NO_DEPRECATED
# define QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context)
#else
# define QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context) \
- QT_DEPRECATED static inline QString trUtf8(const char *sourceText, const char *disambiguation = 0, int n = -1) \
+ QT_DEPRECATED static inline QString trUtf8(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
{ return QCoreApplication::translate(#context, sourceText, disambiguation, n); }
#endif
#define Q_DECLARE_TR_FUNCTIONS(context) \
public: \
- static inline QString tr(const char *sourceText, const char *disambiguation = 0, int n = -1) \
+ static inline QString tr(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
{ return QCoreApplication::translate(#context, sourceText, disambiguation, n); } \
QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context) \
private:
diff --git a/src/corelib/kernel/qcoreapplication_p.h b/src/corelib/kernel/qcoreapplication_p.h
index 2646a28d71..21f59d8197 100644
--- a/src/corelib/kernel/qcoreapplication_p.h
+++ b/src/corelib/kernel/qcoreapplication_p.h
@@ -86,8 +86,8 @@ public:
#ifndef QT_NO_QOBJECT
bool sendThroughApplicationEventFilters(QObject *, QEvent *);
- bool sendThroughObjectEventFilters(QObject *, QEvent *);
- bool notify_helper(QObject *, QEvent *);
+ static bool sendThroughObjectEventFilters(QObject *, QEvent *);
+ static bool notify_helper(QObject *, QEvent *);
static inline void setEventSpontaneous(QEvent *e, bool spontaneous) { e->spont = spontaneous; }
virtual void createEventDispatcher();
@@ -107,9 +107,11 @@ public:
static QThread *theMainThread;
static QThread *mainThread();
+ static bool threadRequiresCoreApplication();
+
static void sendPostedEvents(QObject *receiver, int event_type, QThreadData *data);
- void checkReceiverThread(QObject *receiver);
+ static void checkReceiverThread(QObject *receiver);
void cleanupThreadData();
#endif // QT_NO_QOBJECT
diff --git a/src/corelib/kernel/qcoreevent.cpp b/src/corelib/kernel/qcoreevent.cpp
index e9ae355d70..98514c56af 100644
--- a/src/corelib/kernel/qcoreevent.cpp
+++ b/src/corelib/kernel/qcoreevent.cpp
@@ -150,7 +150,7 @@ QT_BEGIN_NAMESPACE
\value HoverLeave The mouse cursor leaves a hover widget (QHoverEvent).
\value HoverMove The mouse cursor moves inside a hover widget (QHoverEvent).
\value IconDrag The main icon of a window has been dragged away (QIconDragEvent).
- \value IconTextChange Widget's icon text has been changed.
+ \value IconTextChange Widget's icon text has been changed. (Deprecated)
\value InputMethod An input method is being used (QInputMethodEvent).
\value InputMethodQuery A input method query event (QInputMethodQueryEvent)
\value KeyboardLayoutChange The keyboard layout has changed.
diff --git a/src/corelib/kernel/qcoreevent.h b/src/corelib/kernel/qcoreevent.h
index c208eb1180..53da4a849b 100644
--- a/src/corelib/kernel/qcoreevent.h
+++ b/src/corelib/kernel/qcoreevent.h
@@ -133,7 +133,7 @@ public:
EnabledChange = 98, // enabled state has changed
ActivationChange = 99, // window activation has changed
StyleChange = 100, // style has changed
- IconTextChange = 101, // icon text has changed
+ IconTextChange = 101, // icon text has changed. Deprecated.
ModifiedChange = 102, // modified state has changed
MouseTrackingChange = 109, // mouse tracking state has changed
diff --git a/src/corelib/kernel/qeventdispatcher_glib.cpp b/src/corelib/kernel/qeventdispatcher_glib.cpp
index 876825b5f0..d9bbd4d5f2 100644
--- a/src/corelib/kernel/qeventdispatcher_glib.cpp
+++ b/src/corelib/kernel/qeventdispatcher_glib.cpp
@@ -39,7 +39,6 @@
#include "qcoreapplication.h"
#include "qsocketnotifier.h"
-#include <QtCore/qhash.h>
#include <QtCore/qlist.h>
#include <QtCore/qpair.h>
diff --git a/src/corelib/kernel/qeventdispatcher_glib_p.h b/src/corelib/kernel/qeventdispatcher_glib_p.h
index afdb6b9317..2cb919df07 100644
--- a/src/corelib/kernel/qeventdispatcher_glib_p.h
+++ b/src/corelib/kernel/qeventdispatcher_glib_p.h
@@ -48,8 +48,6 @@
#include "qabstracteventdispatcher.h"
#include "qabstracteventdispatcher_p.h"
-#include <QtCore/qhash.h>
-
typedef struct _GMainContext GMainContext;
QT_BEGIN_NAMESPACE
diff --git a/src/corelib/kernel/qeventdispatcher_win.cpp b/src/corelib/kernel/qeventdispatcher_win.cpp
index 6da70cf0bd..e8ff8a7936 100644
--- a/src/corelib/kernel/qeventdispatcher_win.cpp
+++ b/src/corelib/kernel/qeventdispatcher_win.cpp
@@ -34,7 +34,6 @@
#include "qeventdispatcher_win_p.h"
#include "qcoreapplication.h"
-#include "qhash.h"
#include <private/qsystemlibrary_p.h>
#include "qpair.h"
#include "qset.h"
@@ -1087,11 +1086,10 @@ void QEventDispatcherWin32::activateEventNotifiers()
for (int i=0; i<d->winEventNotifierList.count(); i++) {
#if !defined(Q_OS_WINCE)
if (WaitForSingleObjectEx(d->winEventNotifierList.at(i)->handle(), 0, TRUE) == WAIT_OBJECT_0)
- d->activateEventNotifier(d->winEventNotifierList.at(i));
#else
if (WaitForSingleObject(d->winEventNotifierList.at(i)->handle(), 0) == WAIT_OBJECT_0)
- d->activateEventNotifier(d->winEventNotifierList.at(i));
#endif
+ d->activateEventNotifier(d->winEventNotifierList.at(i));
}
}
diff --git a/src/corelib/kernel/qeventdispatcher_winrt.cpp b/src/corelib/kernel/qeventdispatcher_winrt.cpp
index eceba8d002..f771974a24 100644
--- a/src/corelib/kernel/qeventdispatcher_winrt.cpp
+++ b/src/corelib/kernel/qeventdispatcher_winrt.cpp
@@ -40,6 +40,7 @@
#include <private/qabstracteventdispatcher_p.h>
#include <private/qcoreapplication_p.h>
+#include <functional>
#include <wrl.h>
#include <windows.foundation.h>
#include <windows.system.threading.h>
@@ -70,6 +71,23 @@ struct WinRTTimerInfo : public QAbstractEventDispatcher::TimerInfo {
quint64 targetTime;
};
+class AgileDispatchedHandler : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IDispatchedHandler, IAgileObject>
+{
+public:
+ AgileDispatchedHandler(const std::function<HRESULT()> &delegate)
+ : delegate(delegate)
+ {
+ }
+
+ HRESULT __stdcall Invoke()
+ {
+ return delegate();
+ }
+
+private:
+ std::function<HRESULT()> delegate;
+};
+
class QEventDispatcherWinRTPrivate : public QAbstractEventDispatcherPrivate
{
Q_DECLARE_PUBLIC(QEventDispatcherWinRT)
@@ -80,8 +98,6 @@ public:
private:
ComPtr<IThreadPoolTimerStatics> timerFactory;
- ComPtr<ICoreDispatcher> coreDispatcher;
- QPointer<QThread> thread;
QHash<int, QObject *> timerIdToObject;
QVector<WinRTTimerInfo> timerInfos;
@@ -136,40 +152,11 @@ private:
}
return true;
}
-
- void fetchCoreDispatcher()
- {
- ComPtr<ICoreImmersiveApplication> application;
- HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(),
- IID_PPV_ARGS(&application));
- RETURN_VOID_IF_FAILED("Failed to get the application factory");
-
- static ComPtr<ICoreApplicationView> view;
- if (view)
- return;
-
- hr = application->get_MainView(&view);
- RETURN_VOID_IF_FAILED("Failed to get the main view");
-
- ComPtr<ICoreApplicationView2> view2;
- hr = view.As(&view2);
- RETURN_VOID_IF_FAILED("Failed to cast the main view");
-
- hr = view2->get_Dispatcher(&coreDispatcher);
- if (hr == HRESULT_FROM_WIN32(ERROR_NOT_FOUND)) // expected in thread pool cases
- return;
- RETURN_VOID_IF_FAILED("Failed to get core dispatcher");
-
- thread = QThread::currentThread();
- }
};
QEventDispatcherWinRT::QEventDispatcherWinRT(QObject *parent)
: QAbstractEventDispatcher(*new QEventDispatcherWinRTPrivate, parent)
{
- Q_D(QEventDispatcherWinRT);
-
- d->fetchCoreDispatcher();
}
QEventDispatcherWinRT::QEventDispatcherWinRT(QEventDispatcherWinRTPrivate &dd, QObject *parent)
@@ -180,25 +167,43 @@ QEventDispatcherWinRT::~QEventDispatcherWinRT()
{
}
+HRESULT QEventDispatcherWinRT::runOnXamlThread(const std::function<HRESULT ()> &delegate)
+{
+ static __declspec(thread) ICoreDispatcher *dispatcher = nullptr;
+ if (!dispatcher) {
+ HRESULT hr;
+ ComPtr<ICoreImmersiveApplication> application;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(),
+ IID_PPV_ARGS(&application));
+ ComPtr<ICoreApplicationView> view;
+ hr = application->get_MainView(&view);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<ICoreWindow> window;
+ hr = view->get_CoreWindow(&window);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = window->get_Dispatcher(&dispatcher);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+
+ HRESULT hr;
+ boolean onXamlThread;
+ hr = dispatcher->get_HasThreadAccess(&onXamlThread);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (onXamlThread) // Already there
+ return delegate();
+
+ ComPtr<IAsyncAction> op;
+ hr = dispatcher->RunAsync(CoreDispatcherPriority_Normal, Make<AgileDispatchedHandler>(delegate).Get(), &op);
+ if (FAILED(hr))
+ return hr;
+ return QWinRTFunctions::await(op);
+}
+
bool QEventDispatcherWinRT::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QEventDispatcherWinRT);
- if (d->thread && d->thread != QThread::currentThread())
- d->fetchCoreDispatcher();
-
do {
- // Process native events
- if (d->coreDispatcher) {
- boolean hasThreadAccess;
- HRESULT hr = d->coreDispatcher->get_HasThreadAccess(&hasThreadAccess);
- if (SUCCEEDED(hr) && hasThreadAccess) {
- hr = d->coreDispatcher->ProcessEvents(CoreProcessEventsOption_ProcessAllIfPresent);
- if (FAILED(hr))
- qErrnoWarning(hr, "Failed to process events");
- }
- }
-
// Additional user events have to be handled before timer events, but the function may not
// return yet.
const bool userEventsSent = sendPostedEvents(flags);
@@ -284,10 +289,11 @@ void QEventDispatcherWinRT::registerTimer(int timerId, int interval, Qt::TimerTy
TimeSpan period;
period.Duration = interval ? (interval * 10000) : 1; // TimeSpan is based on 100-nanosecond units
- IThreadPoolTimer *timer;
const HANDLE handle = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE | EVENT_MODIFY_STATE);
const HANDLE cancelHandle = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE|EVENT_MODIFY_STATE);
- HRESULT hr = d->timerFactory->CreatePeriodicTimerWithCompletion(
+ HRESULT hr = runOnXamlThread([&]() {
+ IThreadPoolTimer *timer;
+ HRESULT hr = d->timerFactory->CreatePeriodicTimerWithCompletion(
Callback<ITimerElapsedHandler>([handle, cancelHandle](IThreadPoolTimer *timer) {
DWORD cancelResult = WaitForSingleObjectEx(cancelHandle, 0, TRUE);
if (cancelResult == WAIT_OBJECT_0) {
@@ -306,13 +312,15 @@ void QEventDispatcherWinRT::registerTimer(int timerId, int interval, Qt::TimerTy
CloseHandle(cancelHandle);
return S_OK;
}).Get(), &timer);
+ RETURN_HR_IF_FAILED("Failed to create periodic timer");
+
+ d->addTimer(timerId, interval, timerType, object, handle, cancelHandle);
+ return hr;
+ });
if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to create periodic timer");
CloseHandle(handle);
CloseHandle(cancelHandle);
- return;
}
- d->addTimer(timerId, interval, timerType, object, handle, cancelHandle);
}
bool QEventDispatcherWinRT::unregisterTimer(int timerId)
diff --git a/src/corelib/kernel/qeventdispatcher_winrt_p.h b/src/corelib/kernel/qeventdispatcher_winrt_p.h
index fd3d259c96..073aa1c121 100644
--- a/src/corelib/kernel/qeventdispatcher_winrt_p.h
+++ b/src/corelib/kernel/qeventdispatcher_winrt_p.h
@@ -50,6 +50,8 @@
#include <qt_windows.h>
+namespace std { template <typename T> class function; }
+
QT_BEGIN_NAMESPACE
quint64 qt_msectime();
@@ -65,6 +67,8 @@ public:
explicit QEventDispatcherWinRT(QObject *parent = 0);
~QEventDispatcherWinRT();
+ static HRESULT runOnXamlThread(const std::function<HRESULT()> &delegate);
+
bool processEvents(QEventLoop::ProcessEventsFlags flags);
bool hasPendingEvents();
diff --git a/src/corelib/kernel/qeventloop.cpp b/src/corelib/kernel/qeventloop.cpp
index 1723db0ab9..dca25ce968 100644
--- a/src/corelib/kernel/qeventloop.cpp
+++ b/src/corelib/kernel/qeventloop.cpp
@@ -93,7 +93,7 @@ QEventLoop::QEventLoop(QObject *parent)
: QObject(*new QEventLoopPrivate, parent)
{
Q_D(QEventLoop);
- if (!QCoreApplication::instance()) {
+ if (!QCoreApplication::instance() && QCoreApplicationPrivate::threadRequiresCoreApplication()) {
qWarning("QEventLoop: Cannot be used without QApplication");
} else if (!d->threadData->eventDispatcher.load()) {
QThreadPrivate::createEventDispatcher(d->threadData);
diff --git a/src/corelib/kernel/qeventloop.h b/src/corelib/kernel/qeventloop.h
index 99c0cd50ff..375a63abdd 100644
--- a/src/corelib/kernel/qeventloop.h
+++ b/src/corelib/kernel/qeventloop.h
@@ -47,7 +47,7 @@ class Q_CORE_EXPORT QEventLoop : public QObject
Q_DECLARE_PRIVATE(QEventLoop)
public:
- explicit QEventLoop(QObject *parent = 0);
+ explicit QEventLoop(QObject *parent = Q_NULLPTR);
~QEventLoop();
enum ProcessEventsFlag {
diff --git a/src/corelib/kernel/qfunctions_wince.cpp b/src/corelib/kernel/qfunctions_wince.cpp
index 8f8fc21313..2503a262cd 100644
--- a/src/corelib/kernel/qfunctions_wince.cpp
+++ b/src/corelib/kernel/qfunctions_wince.cpp
@@ -36,7 +36,11 @@
#include <winbase.h>
#include <kfuncs.h>
#include <stdio.h>
-#include <altcecrt.h>
+#if _WIN32_WCE < 0x800
+# include <altcecrt.h>
+#else
+# include <fcntl.h>
+#endif
#include "qplatformdefs.h"
#include "qfunctions_wince.h"
@@ -93,7 +97,9 @@ FILETIME qt_wince_time_tToFt( time_t tt )
}
// File I/O ---------------------------------------------------------
+#if _WIN32_WCE < 0x800
int errno = 0;
+#endif
int qt_wince__getdrive( void )
{
diff --git a/src/corelib/kernel/qfunctions_wince.h b/src/corelib/kernel/qfunctions_wince.h
index 987342d29a..d172acceec 100644
--- a/src/corelib/kernel/qfunctions_wince.h
+++ b/src/corelib/kernel/qfunctions_wince.h
@@ -37,6 +37,9 @@
#include <QtCore/qglobal.h>
#ifdef Q_OS_WINCE
+# ifndef NOMINMAX
+# define NOMINMAX
+# endif
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
@@ -47,7 +50,12 @@
#include <ctype.h>
#include <time.h>
#include <crtdefs.h>
-#include <altcecrt.h>
+#if _WIN32_WCE < 0x800
+# include <altcecrt.h>
+#else
+# include <fcntl.h>
+# include <stat.h>
+#endif
#include <winsock.h>
#include <ceconfig.h>
@@ -102,6 +110,8 @@ struct tm {
FILETIME qt_wince_time_tToFt( time_t tt );
time_t qt_wince_ftToTime_t( const FILETIME ft );
+#if _WIN32_WCE < 0x800
+
// File I/O ---------------------------------------------------------
#define _O_RDONLY 0x0001
#define _O_RDWR 0x0002
@@ -161,6 +171,7 @@ struct stat
typedef int mode_t;
extern int errno;
+#endif // _WIN32_WCE < 0x800
int qt_wince__getdrive( void );
int qt_wince__waccess( const wchar_t *path, int pmode );
@@ -437,8 +448,10 @@ generate_inline_return_func0(tmpfile, FILE *)
generate_inline_return_func2(_rename, int, const char *, const char *)
generate_inline_return_func1(_remove, int, const char *)
generate_inline_return_func1(SetErrorMode, int, int)
+#if _WIN32_WCE < 0x800
generate_inline_return_func2(_chmod, bool, const char *, int)
generate_inline_return_func2(_wchmod, bool, const wchar_t *, int)
+#endif
generate_inline_return_func7(CreateFileA, HANDLE, LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE)
generate_inline_return_func4(SetWindowOrgEx, BOOL, HDC, int, int, LPPOINT)
generate_inline_return_func2(calloc, void *, size_t, size_t)
diff --git a/src/corelib/kernel/qjni.cpp b/src/corelib/kernel/qjni.cpp
index 2640ecaaaf..108a01aab7 100644
--- a/src/corelib/kernel/qjni.cpp
+++ b/src/corelib/kernel/qjni.cpp
@@ -225,6 +225,15 @@ static jfieldID getCachedFieldID(JNIEnv *env,
}
}
+void QJNILocalRefDeleter::cleanup(jobject obj)
+{
+ if (obj == 0)
+ return;
+
+ QJNIEnvironmentPrivate env;
+ env->DeleteLocalRef(obj);
+}
+
class QJNIEnvironmentPrivateTLS
{
public:
@@ -2371,4 +2380,3 @@ bool QJNIObjectPrivate::isSameObject(const QJNIObjectPrivate &other) const
}
QT_END_NAMESPACE
-
diff --git a/src/corelib/kernel/qjni_p.h b/src/corelib/kernel/qjni_p.h
index a32d656ebf..1c23f2ab76 100644
--- a/src/corelib/kernel/qjni_p.h
+++ b/src/corelib/kernel/qjni_p.h
@@ -51,6 +51,14 @@
QT_BEGIN_NAMESPACE
+struct Q_CORE_EXPORT QJNILocalRefDeleter
+{
+ static void cleanup(jobject obj);
+};
+
+// To simplify this we only define it for jobjects.
+typedef QScopedPointer<_jobject, QJNILocalRefDeleter> QJNIScopedLocalRef;
+
class Q_CORE_EXPORT QJNIEnvironmentPrivate
{
public:
diff --git a/src/corelib/kernel/qjnihelpers.cpp b/src/corelib/kernel/qjnihelpers.cpp
index dad2d5dc1e..f77fc4220c 100644
--- a/src/corelib/kernel/qjnihelpers.cpp
+++ b/src/corelib/kernel/qjnihelpers.cpp
@@ -122,6 +122,45 @@ void QtAndroidPrivate::handleNewIntent(JNIEnv *env, jobject intent)
}
}
+namespace {
+ class ResumePauseListeners
+ {
+ public:
+ QMutex mutex;
+ QList<QtAndroidPrivate::ResumePauseListener *> listeners;
+ };
+}
+
+Q_GLOBAL_STATIC(ResumePauseListeners, g_resumePauseListeners)
+
+void QtAndroidPrivate::registerResumePauseListener(ResumePauseListener *listener)
+{
+ QMutexLocker locker(&g_resumePauseListeners()->mutex);
+ g_resumePauseListeners()->listeners.append(listener);
+}
+
+void QtAndroidPrivate::unregisterResumePauseListener(ResumePauseListener *listener)
+{
+ QMutexLocker locker(&g_resumePauseListeners()->mutex);
+ g_resumePauseListeners()->listeners.removeAll(listener);
+}
+
+void QtAndroidPrivate::handlePause()
+{
+ QMutexLocker locker(&g_resumePauseListeners()->mutex);
+ const QList<QtAndroidPrivate::ResumePauseListener *> &listeners = g_resumePauseListeners()->listeners;
+ for (int i=0; i<listeners.size(); ++i)
+ listeners.at(i)->handlePause();
+}
+
+void QtAndroidPrivate::handleResume()
+{
+ QMutexLocker locker(&g_resumePauseListeners()->mutex);
+ const QList<QtAndroidPrivate::ResumePauseListener *> &listeners = g_resumePauseListeners()->listeners;
+ for (int i=0; i<listeners.size(); ++i)
+ listeners.at(i)->handleResume();
+}
+
static inline bool exceptionCheck(JNIEnv *env)
{
if (env->ExceptionCheck()) {
diff --git a/src/corelib/kernel/qjnihelpers_p.h b/src/corelib/kernel/qjnihelpers_p.h
index 3ed8338b18..883b08ef60 100644
--- a/src/corelib/kernel/qjnihelpers_p.h
+++ b/src/corelib/kernel/qjnihelpers_p.h
@@ -68,6 +68,14 @@ namespace QtAndroidPrivate
virtual bool handleNewIntent(JNIEnv *env, jobject intent) = 0;
};
+ class Q_CORE_EXPORT ResumePauseListener
+ {
+ public:
+ virtual ~ResumePauseListener() {}
+ virtual void handlePause() {};
+ virtual void handleResume() {};
+ };
+
Q_CORE_EXPORT jobject activity();
Q_CORE_EXPORT JavaVM *javaVM();
Q_CORE_EXPORT jint initJNI(JavaVM *vm, JNIEnv *env);
@@ -82,6 +90,11 @@ namespace QtAndroidPrivate
Q_CORE_EXPORT void handleNewIntent(JNIEnv *env, jobject intent);
Q_CORE_EXPORT void registerNewIntentListener(NewIntentListener *listener);
Q_CORE_EXPORT void unregisterNewIntentListener(NewIntentListener *listener);
+
+ Q_CORE_EXPORT void handlePause();
+ Q_CORE_EXPORT void handleResume();
+ Q_CORE_EXPORT void registerResumePauseListener(ResumePauseListener *listener);
+ Q_CORE_EXPORT void unregisterResumePauseListener(ResumePauseListener *listener);
}
QT_END_NAMESPACE
diff --git a/src/corelib/kernel/qmath.h b/src/corelib/kernel/qmath.h
index 5cc3ec586e..e60561c05f 100644
--- a/src/corelib/kernel/qmath.h
+++ b/src/corelib/kernel/qmath.h
@@ -40,8 +40,18 @@
#include <QtCore/qglobal.h>
+#ifndef _USE_MATH_DEFINES
+# define _USE_MATH_DEFINES
+# define undef_USE_MATH_DEFINES
+#endif
+
#include <cmath>
+#ifdef undef_USE_MATH_DEFINES
+# undef _USE_MATH_DEFINES
+# undef undef_USE_MATH_DEFINES
+#endif
+
QT_BEGIN_NAMESPACE
#define QT_SINE_TABLE_SIZE 256
diff --git a/src/corelib/kernel/qmetaobject.cpp b/src/corelib/kernel/qmetaobject.cpp
index 6858209b12..7ae9fef622 100644
--- a/src/corelib/kernel/qmetaobject.cpp
+++ b/src/corelib/kernel/qmetaobject.cpp
@@ -43,7 +43,6 @@
#include <qstringlist.h>
#include <qthread.h>
#include <qvariant.h>
-#include <qhash.h>
#include <qdebug.h>
#include <qsemaphore.h>
diff --git a/src/corelib/kernel/qmetaobject.h b/src/corelib/kernel/qmetaobject.h
index b522a211bb..1a282d3261 100644
--- a/src/corelib/kernel/qmetaobject.h
+++ b/src/corelib/kernel/qmetaobject.h
@@ -48,7 +48,7 @@ template <typename T> class QList;
class Q_CORE_EXPORT QMetaMethod
{
public:
- Q_DECL_CONSTEXPR inline QMetaMethod() : mobj(0),handle(0) {}
+ Q_DECL_CONSTEXPR inline QMetaMethod() : mobj(Q_NULLPTR), handle(0) {}
QByteArray methodSignature() const;
QByteArray name() const;
@@ -74,7 +74,7 @@ public:
bool invoke(QObject *object,
Qt::ConnectionType connectionType,
QGenericReturnArgument returnValue,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -86,7 +86,7 @@ public:
QGenericArgument val9 = QGenericArgument()) const;
inline bool invoke(QObject *object,
QGenericReturnArgument returnValue,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -102,7 +102,7 @@ public:
}
inline bool invoke(QObject *object,
Qt::ConnectionType connectionType,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -117,7 +117,7 @@ public:
val0, val1, val2, val3, val4, val5, val6, val7, val8, val9);
}
inline bool invoke(QObject *object,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -134,7 +134,7 @@ public:
bool invokeOnGadget(void *gadget,
QGenericReturnArgument returnValue,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -145,7 +145,7 @@ public:
QGenericArgument val8 = QGenericArgument(),
QGenericArgument val9 = QGenericArgument()) const;
inline bool invokeOnGadget(void *gadget,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -160,7 +160,7 @@ public:
val0, val1, val2, val3, val4, val5, val6, val7, val8, val9);
}
- inline bool isValid() const { return mobj != 0; }
+ inline bool isValid() const { return mobj != Q_NULLPTR; }
#ifdef Q_QDOC
static QMetaMethod fromSignal(PointerToMemberFunction signal);
@@ -204,7 +204,7 @@ inline bool operator!=(const QMetaMethod &m1, const QMetaMethod &m2)
class Q_CORE_EXPORT QMetaEnum
{
public:
- Q_DECL_CONSTEXPR inline QMetaEnum() : mobj(0),handle(0) {}
+ Q_DECL_CONSTEXPR inline QMetaEnum() : mobj(Q_NULLPTR), handle(0) {}
const char *name() const;
bool isFlag() const;
@@ -215,14 +215,14 @@ public:
const char *scope() const;
- int keyToValue(const char *key, bool *ok = 0) const;
+ int keyToValue(const char *key, bool *ok = Q_NULLPTR) const;
const char* valueToKey(int value) const;
- int keysToValue(const char * keys, bool *ok = 0) const;
+ int keysToValue(const char * keys, bool *ok = Q_NULLPTR) const;
QByteArray valueToKeys(int value) const;
inline const QMetaObject *enclosingMetaObject() const { return mobj; }
- inline bool isValid() const { return name() != 0; }
+ inline bool isValid() const { return name() != Q_NULLPTR; }
template<typename T> static QMetaEnum fromType() {
Q_STATIC_ASSERT_X(QtPrivate::IsQEnumHelper<T>::Value,
@@ -253,11 +253,11 @@ public:
bool isReadable() const;
bool isWritable() const;
bool isResettable() const;
- bool isDesignable(const QObject *obj = 0) const;
- bool isScriptable(const QObject *obj = 0) const;
- bool isStored(const QObject *obj = 0) const;
- bool isEditable(const QObject *obj = 0) const;
- bool isUser(const QObject *obj = 0) const;
+ bool isDesignable(const QObject *obj = Q_NULLPTR) const;
+ bool isScriptable(const QObject *obj = Q_NULLPTR) const;
+ bool isStored(const QObject *obj = Q_NULLPTR) const;
+ bool isEditable(const QObject *obj = Q_NULLPTR) const;
+ bool isUser(const QObject *obj = Q_NULLPTR) const;
bool isConstant() const;
bool isFinal() const;
@@ -297,7 +297,7 @@ private:
class Q_CORE_EXPORT QMetaClassInfo
{
public:
- Q_DECL_CONSTEXPR inline QMetaClassInfo() : mobj(0),handle(0) {}
+ Q_DECL_CONSTEXPR inline QMetaClassInfo() : mobj(Q_NULLPTR), handle(0) {}
const char *name() const;
const char *value() const;
inline const QMetaObject *enclosingMetaObject() const { return mobj; }
diff --git a/src/corelib/kernel/qmetaobjectbuilder.cpp b/src/corelib/kernel/qmetaobjectbuilder.cpp
index a1b8125121..021e137273 100644
--- a/src/corelib/kernel/qmetaobjectbuilder.cpp
+++ b/src/corelib/kernel/qmetaobjectbuilder.cpp
@@ -88,6 +88,7 @@ static inline Q_DECL_UNUSED const QMetaObjectPrivate *priv(const uint* data)
class QMetaMethodBuilderPrivate
{
public:
+ QMetaMethodBuilderPrivate() {} // for QVector, don't use
QMetaMethodBuilderPrivate
(QMetaMethod::MethodType _methodType,
const QByteArray& _signature,
@@ -139,10 +140,12 @@ public:
return signature.left(qMax(signature.indexOf('('), 0));
}
};
+Q_DECLARE_TYPEINFO(QMetaMethodBuilderPrivate, Q_MOVABLE_TYPE);
class QMetaPropertyBuilderPrivate
{
public:
+ QMetaPropertyBuilderPrivate() {} // for QVector, don't use
QMetaPropertyBuilderPrivate
(const QByteArray& _name, const QByteArray& _type, int notifierIdx=-1,
int _revision = 0)
@@ -176,10 +179,12 @@ public:
flags &= ~f;
}
};
+Q_DECLARE_TYPEINFO(QMetaPropertyBuilderPrivate, Q_MOVABLE_TYPE);
class QMetaEnumBuilderPrivate
{
public:
+ QMetaEnumBuilderPrivate() {} // for QVector, don't use
QMetaEnumBuilderPrivate(const QByteArray& _name)
: name(_name), isFlag(false)
{
@@ -188,8 +193,9 @@ public:
QByteArray name;
bool isFlag;
QList<QByteArray> keys;
- QList<int> values;
+ QVector<int> values;
};
+Q_DECLARE_TYPEINFO(QMetaEnumBuilderPrivate, Q_MOVABLE_TYPE);
class QMetaObjectBuilderPrivate
{
@@ -207,12 +213,12 @@ public:
QByteArray className;
const QMetaObject *superClass;
QMetaObjectBuilder::StaticMetacallFunction staticMetacallFunction;
- QList<QMetaMethodBuilderPrivate> methods;
- QList<QMetaMethodBuilderPrivate> constructors;
- QList<QMetaPropertyBuilderPrivate> properties;
+ QVector<QMetaMethodBuilderPrivate> methods;
+ QVector<QMetaMethodBuilderPrivate> constructors;
+ QVector<QMetaPropertyBuilderPrivate> properties;
QList<QByteArray> classInfoNames;
QList<QByteArray> classInfoValues;
- QList<QMetaEnumBuilderPrivate> enumerators;
+ QVector<QMetaEnumBuilderPrivate> enumerators;
QList<const QMetaObject *> relatedMetaObjects;
int flags;
};
@@ -1149,7 +1155,7 @@ void QMetaStringTable::writeBlob(char *out) const
// Returns the sum of all parameters (including return type) for the given
// \a methods. This is needed for calculating the size of the methods'
// parameter type/name meta-data.
-static int aggregateParameterCount(const QList<QMetaMethodBuilderPrivate> &methods)
+static int aggregateParameterCount(const QVector<QMetaMethodBuilderPrivate> &methods)
{
int sum = 0;
for (int i = 0; i < methods.size(); ++i)
@@ -1330,7 +1336,7 @@ static int buildMetaObject(QMetaObjectBuilderPrivate *d, char *buf,
Q_ASSERT(!buf || dataIndex == pmeta->methodData + d->methods.size() * 5
+ (hasRevisionedMethods ? d->methods.size() : 0));
for (int x = 0; x < 2; ++x) {
- QList<QMetaMethodBuilderPrivate> &methods = (x == 0) ? d->methods : d->constructors;
+ QVector<QMetaMethodBuilderPrivate> &methods = (x == 0) ? d->methods : d->constructors;
for (index = 0; index < methods.size(); ++index) {
QMetaMethodBuilderPrivate *method = &(methods[index]);
QList<QByteArray> paramTypeNames = method->parameterTypes();
diff --git a/src/corelib/kernel/qmetatype.cpp b/src/corelib/kernel/qmetatype.cpp
index 7fadb66319..01e2542dfa 100644
--- a/src/corelib/kernel/qmetatype.cpp
+++ b/src/corelib/kernel/qmetatype.cpp
@@ -1081,25 +1081,16 @@ int QMetaType::registerNormalizedType(const NS(QByteArray) &normalizedTypeName,
normalizedTypeName.constData(), idx, previousSize, size);
}
- // Do not compare types higher than 0x100:
- // Ignore WasDeclaredAsMetaType inconsitency, to many users were hitting the problem
- // Ignore IsGadget as it was added in Qt 5.5
- // Ignore all the future flags as well
- if ((previousFlags ^ flags) & 0xff) {
- const int maskForTypeInfo = NeedsConstruction | NeedsDestruction | MovableType;
+ // these flags cannot change in a binary compatible way:
+ const int binaryCompatibilityFlag = PointerToQObject | IsEnumeration | SharedPointerToQObject
+ | WeakPointerToQObject | TrackingPointerToQObject;
+ if ((previousFlags ^ flags) & binaryCompatibilityFlag) {
+
const char *msg = "QMetaType::registerType: Binary compatibility break. "
"\nType flags for type '%s' [%i] don't match. Previously "
- "registered TypeFlags(0x%x), now registering TypeFlags(0x%x). "
- "This is an ODR break, which means that your application depends on a C++ undefined behavior."
- "\nHint: %s";
- QT_PREPEND_NAMESPACE(QByteArray) hint;
- if ((previousFlags & maskForTypeInfo) != (flags & maskForTypeInfo)) {
- hint += "\nIt seems that the type was registered at least twice in a different translation units, "
- "but Q_DECLARE_TYPEINFO is not visible from all the translations unit or different flags were used."
- "Remember that Q_DECLARE_TYPEINFO should be declared before QMetaType registration, "
- "preferably it should be placed just after the type declaration and before Q_DECLARE_METATYPE";
- }
- qFatal(msg, normalizedTypeName.constData(), idx, previousFlags, int(flags), hint.constData());
+ "registered TypeFlags(0x%x), now registering TypeFlags(0x%x). ";
+
+ qFatal(msg, normalizedTypeName.constData(), idx, previousFlags, int(flags));
}
return idx;
@@ -1188,9 +1179,6 @@ bool QMetaType::isRegistered(int type)
return ((type >= User) && (ct && ct->count() > type - User) && !ct->at(type - User).typeName.isEmpty());
}
-/*!
- \internal
-*/
template <bool tryNormalizedType>
static inline int qMetaTypeTypeImpl(const char *typeName, int length)
{
diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h
index 1b214e9f74..b7f01ca5ca 100644
--- a/src/corelib/kernel/qmetatype.h
+++ b/src/corelib/kernel/qmetatype.h
@@ -229,7 +229,7 @@ struct AbstractDebugStreamFunction
{
typedef void (*Stream)(const AbstractDebugStreamFunction *, QDebug&, const void *);
typedef void (*Destroy)(AbstractDebugStreamFunction *);
- explicit AbstractDebugStreamFunction(Stream s = 0, Destroy d = 0)
+ explicit AbstractDebugStreamFunction(Stream s = Q_NULLPTR, Destroy d = Q_NULLPTR)
: stream(s), destroy(d) {}
Q_DISABLE_COPY(AbstractDebugStreamFunction)
Stream stream;
@@ -259,7 +259,7 @@ struct AbstractComparatorFunction
typedef bool (*LessThan)(const AbstractComparatorFunction *, const void *, const void *);
typedef bool (*Equals)(const AbstractComparatorFunction *, const void *, const void *);
typedef void (*Destroy)(AbstractComparatorFunction *);
- explicit AbstractComparatorFunction(LessThan lt = 0, Equals e = 0, Destroy d = 0)
+ explicit AbstractComparatorFunction(LessThan lt = Q_NULLPTR, Equals e = Q_NULLPTR, Destroy d = Q_NULLPTR)
: lessThan(lt), equals(e), destroy(d) {}
Q_DISABLE_COPY(AbstractComparatorFunction)
LessThan lessThan;
@@ -296,7 +296,7 @@ template<typename T>
struct BuiltInEqualsComparatorFunction : public AbstractComparatorFunction
{
BuiltInEqualsComparatorFunction()
- : AbstractComparatorFunction(0, equals, destroy) {}
+ : AbstractComparatorFunction(Q_NULLPTR, equals, destroy) {}
static bool equals(const AbstractComparatorFunction *, const void *l, const void *r)
{
const T *lhs = static_cast<const T *>(l);
@@ -313,7 +313,7 @@ struct BuiltInEqualsComparatorFunction : public AbstractComparatorFunction
struct AbstractConverterFunction
{
typedef bool (*Converter)(const AbstractConverterFunction *, const void *, void*);
- explicit AbstractConverterFunction(Converter c = 0)
+ explicit AbstractConverterFunction(Converter c = Q_NULLPTR)
: convert(c) {}
Q_DISABLE_COPY(AbstractConverterFunction)
Converter convert;
@@ -510,9 +510,9 @@ public:
static TypeFlags typeFlags(int type);
static const QMetaObject *metaObjectForType(int type);
static bool isRegistered(int type);
- static void *create(int type, const void *copy = 0);
+ static void *create(int type, const void *copy = Q_NULLPTR);
#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static void *construct(int type, const void *copy = 0)
+ QT_DEPRECATED static void *construct(int type, const void *copy = Q_NULLPTR)
{ return create(type, copy); }
#endif
static void destroy(int type, void *data);
@@ -533,9 +533,9 @@ public:
inline TypeFlags flags() const;
inline const QMetaObject *metaObject() const;
- inline void *create(const void *copy = 0) const;
+ inline void *create(const void *copy = Q_NULLPTR) const;
inline void destroy(void *data) const;
- inline void *construct(void *where, const void *copy = 0) const;
+ inline void *construct(void *where, const void *copy = Q_NULLPTR) const;
inline void destruct(void *data) const;
public:
@@ -611,7 +611,7 @@ public:
return registerConverterFunction(&f, fromTypeId, toTypeId);
}
- // member function as in "double QString::toDouble(bool *ok = 0) const"
+ // member function as in "double QString::toDouble(bool *ok = Q_NULLPTR) const"
template<typename From, typename To>
static bool registerConverter(To(From::*function)(bool*) const)
{
@@ -674,9 +674,9 @@ private:
uint sizeExtended() const;
QMetaType::TypeFlags flagsExtended() const;
const QMetaObject *metaObjectExtended() const;
- void *createExtended(const void *copy = 0) const;
+ void *createExtended(const void *copy = Q_NULLPTR) const;
void destroyExtended(void *data) const;
- void *constructExtended(void *where, const void *copy = 0) const;
+ void *constructExtended(void *where, const void *copy = Q_NULLPTR) const;
void destructExtended(void *data) const;
static bool registerComparatorFunction(const QtPrivate::AbstractComparatorFunction *f, int type);
@@ -740,6 +740,11 @@ ConverterFunctor<From, To, UnaryFunction>::~ConverterFunctor()
}
+#define QT_METATYPE_PRIVATE_DECLARE_TYPEINFO(C, F) \
+ } \
+ Q_DECLARE_TYPEINFO(QtMetaTypePrivate:: C, (F)); \
+ namespace QtMetaTypePrivate {
+
namespace QtMetaTypePrivate {
template <typename T, bool Accepted = true>
struct QMetaTypeFunctionHelper {
@@ -771,7 +776,7 @@ struct QMetaTypeFunctionHelper {
template <typename T>
struct QMetaTypeFunctionHelper<T, /* Accepted */ false> {
static void Destruct(void *) {}
- static void *Construct(void *, const void *) { return 0; }
+ static void *Construct(void *, const void *) { return Q_NULLPTR; }
#ifndef QT_NO_DATASTREAM
static void Save(QDataStream &, const void *) {}
static void Load(QDataStream &, void *) {}
@@ -1009,7 +1014,7 @@ public:
public:
template<class T> QSequentialIterableImpl(const T*p)
: _iterable(p)
- , _iterator(0)
+ , _iterator(Q_NULLPTR)
, _metaType_id(qMetaTypeId<typename T::value_type>())
, _metaType_flags(QTypeInfo<typename T::value_type>::isPointer)
, _iteratorCapabilities(ContainerAPI<T>::IteratorCapabilities)
@@ -1026,20 +1031,20 @@ public:
}
QSequentialIterableImpl()
- : _iterable(0)
- , _iterator(0)
+ : _iterable(Q_NULLPTR)
+ , _iterator(Q_NULLPTR)
, _metaType_id(QMetaType::UnknownType)
, _metaType_flags(0)
, _iteratorCapabilities(0)
- , _size(0)
- , _at(0)
- , _moveToBegin(0)
- , _moveToEnd(0)
- , _advance(0)
- , _get(0)
- , _destroyIter(0)
- , _equalIter(0)
- , _copyIter(0)
+ , _size(Q_NULLPTR)
+ , _at(Q_NULLPTR)
+ , _moveToBegin(Q_NULLPTR)
+ , _moveToEnd(Q_NULLPTR)
+ , _advance(Q_NULLPTR)
+ , _get(Q_NULLPTR)
+ , _destroyIter(Q_NULLPTR)
+ , _equalIter(Q_NULLPTR)
+ , _copyIter(Q_NULLPTR)
{
}
@@ -1067,6 +1072,7 @@ public:
_copyIter(&_iterator, &other._iterator);
}
};
+QT_METATYPE_PRIVATE_DECLARE_TYPEINFO(QSequentialIterableImpl, Q_MOVABLE_TYPE)
template<typename From>
struct QSequentialIterableConvertFunctor
@@ -1195,21 +1201,21 @@ public:
}
QAssociativeIterableImpl()
- : _iterable(0)
+ : _iterable(Q_NULLPTR)
, _metaType_id_key(QMetaType::UnknownType)
, _metaType_flags_key(0)
, _metaType_id_value(QMetaType::UnknownType)
, _metaType_flags_value(0)
- , _size(0)
- , _find(0)
- , _begin(0)
- , _end(0)
- , _advance(0)
- , _getKey(0)
- , _getValue(0)
- , _destroyIter(0)
- , _equalIter(0)
- , _copyIter(0)
+ , _size(Q_NULLPTR)
+ , _find(Q_NULLPTR)
+ , _begin(Q_NULLPTR)
+ , _end(Q_NULLPTR)
+ , _advance(Q_NULLPTR)
+ , _getKey(Q_NULLPTR)
+ , _getValue(Q_NULLPTR)
+ , _destroyIter(Q_NULLPTR)
+ , _equalIter(Q_NULLPTR)
+ , _copyIter(Q_NULLPTR)
{
}
@@ -1234,6 +1240,7 @@ public:
_copyIter(&_iterator, &other._iterator);
}
};
+QT_METATYPE_PRIVATE_DECLARE_TYPEINFO(QAssociativeIterableImpl, Q_MOVABLE_TYPE)
template<typename From>
struct QAssociativeIterableConvertFunctor
@@ -1277,15 +1284,20 @@ public:
}
QPairVariantInterfaceImpl()
- : _pair(0)
- , _getFirst(0)
- , _getSecond(0)
+ : _pair(Q_NULLPTR)
+ , _metaType_id_first(QMetaType::UnknownType)
+ , _metaType_flags_first(0)
+ , _metaType_id_second(QMetaType::UnknownType)
+ , _metaType_flags_second(0)
+ , _getFirst(Q_NULLPTR)
+ , _getSecond(Q_NULLPTR)
{
}
inline VariantData first() const { return _getFirst(&_pair, _metaType_id_first, _metaType_flags_first); }
inline VariantData second() const { return _getSecond(&_pair, _metaType_id_second, _metaType_flags_second); }
};
+QT_METATYPE_PRIVATE_DECLARE_TYPEINFO(QPairVariantInterfaceImpl, Q_MOVABLE_TYPE)
template<typename From>
struct QPairVariantInterfaceConvertFunctor;
@@ -1354,7 +1366,7 @@ namespace QtPrivate
#endif
static no_type checkType(...);
Q_STATIC_ASSERT_X(sizeof(T), "Type argument of Q_DECLARE_METATYPE(T*) must be fully defined");
- enum { Value = sizeof(checkType(static_cast<T*>(0))) == sizeof(yes_type) };
+ enum { Value = sizeof(checkType(static_cast<T*>(Q_NULLPTR))) == sizeof(yes_type) };
};
template<typename T, typename Enable = void>
@@ -1391,7 +1403,7 @@ QT_WARNING_POP
template<typename T, typename Enable = void>
struct MetaObjectForType
{
- static inline const QMetaObject *value() { return 0; }
+ static inline const QMetaObject *value() { return Q_NULLPTR; }
};
template<>
struct MetaObjectForType<void>
@@ -1692,7 +1704,7 @@ int qRegisterNormalizedMetaType(const QT_PREPEND_NAMESPACE(QByteArray) &normaliz
template <typename T>
int qRegisterMetaType(const char *typeName
#ifndef Q_QDOC
- , T * dummy = 0
+ , T * dummy = Q_NULLPTR
, typename QtPrivate::MetaTypeDefinedHelper<T, QMetaTypeId2<T>::Defined && !QMetaTypeId2<T>::IsBuiltIn>::DefinedType defined = QtPrivate::MetaTypeDefinedHelper<T, QMetaTypeId2<T>::Defined && !QMetaTypeId2<T>::IsBuiltIn>::Defined
#endif
)
@@ -1709,7 +1721,7 @@ int qRegisterMetaType(const char *typeName
template <typename T>
void qRegisterMetaTypeStreamOperators(const char *typeName
#ifndef Q_QDOC
- , T * /* dummy */ = 0
+ , T * /* dummy */ = Q_NULLPTR
#endif
)
{
@@ -2095,7 +2107,7 @@ inline QMetaType::QMetaType(const ExtensionFlag extensionFlags, const QMetaTypeI
, m_loadOp(loadOp)
, m_constructor(constructor)
, m_destructor(destructor)
- , m_extension(0)
+ , m_extension(Q_NULLPTR)
, m_size(size)
, m_typeFlags(theTypeFlags)
, m_extensionFlags(extensionFlags)
@@ -2232,21 +2244,6 @@ namespace QtPrivate {
};
}
-namespace QtMetaTypePrivate {
-inline Q_DECL_CONSTEXPR bool isBuiltinSequentialType(int typeId)
-{
- return typeId == qMetaTypeId<QStringList>()
- || typeId == qMetaTypeId<QByteArrayList>()
- || typeId == qMetaTypeId<QVariantList>();
-}
-
-inline Q_DECL_CONSTEXPR bool isBuiltinAssociativeType(int typeId)
-{
- return typeId == qMetaTypeId<QVariantHash>()
- || typeId == qMetaTypeId<QVariantMap>();
-}
-} // QtMetaTypePrivate
-
QT_END_NAMESPACE
#endif // QMETATYPE_H
diff --git a/src/corelib/kernel/qmimedata.cpp b/src/corelib/kernel/qmimedata.cpp
index 3e9cdac966..93788afeae 100644
--- a/src/corelib/kernel/qmimedata.cpp
+++ b/src/corelib/kernel/qmimedata.cpp
@@ -354,7 +354,9 @@ void QMimeData::setUrls(const QList<QUrl> &urls)
{
Q_D(QMimeData);
QList<QVariant> list;
- for (int i = 0; i < urls.size(); ++i)
+ const int numUrls = urls.size();
+ list.reserve(numUrls);
+ for (int i = 0; i < numUrls; ++i)
list.append(urls.at(i));
d->setData(QLatin1String("text/uri-list"), list);
diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp
index bcc4e7f8e6..b624c3880e 100644
--- a/src/corelib/kernel/qobject.cpp
+++ b/src/corelib/kernel/qobject.cpp
@@ -47,7 +47,6 @@
#include <qthread.h>
#include <private/qthread_p.h>
#include <qdebug.h>
-#include <qhash.h>
#include <qpair.h>
#include <qvarlengtharray.h>
#include <qset.h>
@@ -66,6 +65,16 @@ QT_BEGIN_NAMESPACE
static int DIRECT_CONNECTION_ONLY = 0;
+
+QDynamicMetaObjectData::~QDynamicMetaObjectData()
+{
+}
+
+QAbstractDynamicMetaObject::~QAbstractDynamicMetaObject()
+{
+}
+
+
struct QSlotObjectBaseDeleter { // for use with QScopedPointer<QSlotObjectBase,...>
static void cleanup(QtPrivate::QSlotObjectBase *slot) {
if (slot) slot->destroyIfLastRef();
@@ -494,6 +503,7 @@ void QMetaCallEvent::placeMetaCall(QObject *object)
\brief Exception-safe wrapper around QObject::blockSignals()
\since 5.3
\ingroup objectmodel
+ \inmodule QtCore
\reentrant
diff --git a/src/corelib/kernel/qobject.h b/src/corelib/kernel/qobject.h
index 5f61dd984f..64c5b58fd4 100644
--- a/src/corelib/kernel/qobject.h
+++ b/src/corelib/kernel/qobject.h
@@ -110,23 +110,23 @@ class Q_CORE_EXPORT QObject
Q_DECLARE_PRIVATE(QObject)
public:
- Q_INVOKABLE explicit QObject(QObject *parent=0);
+ Q_INVOKABLE explicit QObject(QObject *parent=Q_NULLPTR);
virtual ~QObject();
virtual bool event(QEvent *);
virtual bool eventFilter(QObject *, QEvent *);
#ifdef Q_QDOC
- static QString tr(const char *sourceText, const char *comment = 0, int n = -1);
- static QString trUtf8(const char *sourceText, const char *comment = 0, int n = -1);
+ static QString tr(const char *sourceText, const char *comment = Q_NULLPTR, int n = -1);
+ static QString trUtf8(const char *sourceText, const char *comment = Q_NULLPTR, int n = -1);
virtual const QMetaObject *metaObject() const;
static const QMetaObject staticMetaObject;
#endif
#ifdef QT_NO_TRANSLATION
- static QString tr(const char *sourceText, const char * = 0, int = -1)
+ static QString tr(const char *sourceText, const char * = Q_NULLPTR, int = -1)
{ return QString::fromUtf8(sourceText); }
#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static QString trUtf8(const char *sourceText, const char * = 0, int = -1)
+ QT_DEPRECATED static QString trUtf8(const char *sourceText, const char * = Q_NULLPTR, int = -1)
{ return QString::fromUtf8(sourceText); }
#endif
#endif //QT_NO_TRANSLATION
@@ -228,7 +228,7 @@ public:
Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<typename SlotType::ReturnType, typename SignalType::ReturnType>::value),
"Return type of the slot is not compatible with the return type of the signal.");
- const int *types = 0;
+ const int *types = Q_NULLPTR;
if (type == Qt::QueuedConnection || type == Qt::BlockingQueuedConnection)
types = QtPrivate::ConnectionTypes<typename SignalType::Arguments>::types();
@@ -268,11 +268,11 @@ public:
Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<typename SlotType::ReturnType, typename SignalType::ReturnType>::value),
"Return type of the slot is not compatible with the return type of the signal.");
- const int *types = 0;
+ const int *types = Q_NULLPTR;
if (type == Qt::QueuedConnection || type == Qt::BlockingQueuedConnection)
types = QtPrivate::ConnectionTypes<typename SignalType::Arguments>::types();
- return connectImpl(sender, reinterpret_cast<void **>(&signal), context, 0,
+ return connectImpl(sender, reinterpret_cast<void **>(&signal), context, Q_NULLPTR,
new QtPrivate::QStaticSlotObject<Func2,
typename QtPrivate::List_Left<typename SignalType::Arguments, SlotType::ArgumentCount>::Value,
typename SignalType::ReturnType>(slot),
@@ -338,11 +338,11 @@ public:
Q_STATIC_ASSERT_X(QtPrivate::HasQ_OBJECT_Macro<typename SignalType::Object>::Value,
"No Q_OBJECT in the class with the signal");
- const int *types = 0;
+ const int *types = Q_NULLPTR;
if (type == Qt::QueuedConnection || type == Qt::BlockingQueuedConnection)
types = QtPrivate::ConnectionTypes<typename SignalType::Arguments>::types();
- return connectImpl(sender, reinterpret_cast<void **>(&signal), context, 0,
+ return connectImpl(sender, reinterpret_cast<void **>(&signal), context, Q_NULLPTR,
new QtPrivate::QFunctorSlotObject<Func2, SlotArgumentCount,
typename QtPrivate::List_Left<typename SignalType::Arguments, SlotArgumentCount>::Value,
typename SignalType::ReturnType>(slot),
@@ -354,11 +354,11 @@ public:
const QObject *receiver, const char *member);
static bool disconnect(const QObject *sender, const QMetaMethod &signal,
const QObject *receiver, const QMetaMethod &member);
- inline bool disconnect(const char *signal = 0,
- const QObject *receiver = 0, const char *member = 0) const
+ inline bool disconnect(const char *signal = Q_NULLPTR,
+ const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR) const
{ return disconnect(this, signal, receiver, member); }
- inline bool disconnect(const QObject *receiver, const char *member = 0) const
- { return disconnect(this, 0, receiver, member); }
+ inline bool disconnect(const QObject *receiver, const char *member = Q_NULLPTR) const
+ { return disconnect(this, Q_NULLPTR, receiver, member); }
static bool disconnect(const QMetaObject::Connection &);
#ifdef Q_QDOC
@@ -385,7 +385,7 @@ public:
static inline bool disconnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal,
const QObject *receiver, void **zero)
{
- // This is the overload for when one wish to disconnect a signal from any slot. (slot=0)
+ // This is the overload for when one wish to disconnect a signal from any slot. (slot=Q_NULLPTR)
// Since the function template parameter cannot be deduced from '0', we use a
// dummy void ** parameter that must be equal to 0
Q_ASSERT(!zero);
@@ -412,14 +412,14 @@ public:
#endif // QT_NO_USERDATA
Q_SIGNALS:
- void destroyed(QObject * = 0);
+ void destroyed(QObject * = Q_NULLPTR);
void objectNameChanged(const QString &objectName, QPrivateSignal);
public:
inline QObject *parent() const { return d_ptr->parent; }
inline bool inherits(const char *classname) const
- { return const_cast<QObject *>(this)->qt_metacast(classname) != 0; }
+ { return const_cast<QObject *>(this)->qt_metacast(classname) != Q_NULLPTR; }
public Q_SLOTS:
void deleteLater();
@@ -438,7 +438,7 @@ protected:
virtual void disconnectNotify(const QMetaMethod &signal);
protected:
- QObject(QObjectPrivate &dd, QObject *parent = 0);
+ QObject(QObjectPrivate &dd, QObject *parent = Q_NULLPTR);
protected:
QScopedPointer<QObjectData> d_ptr;
@@ -529,16 +529,16 @@ inline T qobject_cast(const QObject *object)
template <class T> inline const char * qobject_interface_iid()
-{ return 0; }
+{ return Q_NULLPTR; }
#ifndef Q_MOC_RUN
# define Q_DECLARE_INTERFACE(IFace, IId) \
template <> inline const char *qobject_interface_iid<IFace *>() \
{ return IId; } \
template <> inline IFace *qobject_cast<IFace *>(QObject *object) \
- { return reinterpret_cast<IFace *>((object ? object->qt_metacast(IId) : 0)); } \
+ { return reinterpret_cast<IFace *>((object ? object->qt_metacast(IId) : Q_NULLPTR)); } \
template <> inline IFace *qobject_cast<IFace *>(const QObject *object) \
- { return reinterpret_cast<IFace *>((object ? const_cast<QObject *>(object)->qt_metacast(IId) : 0)); }
+ { return reinterpret_cast<IFace *>((object ? const_cast<QObject *>(object)->qt_metacast(IId) : Q_NULLPTR)); }
#endif // Q_MOC_RUN
#ifndef QT_NO_DEBUG_STREAM
@@ -584,7 +584,7 @@ QSignalBlocker::QSignalBlocker(QSignalBlocker &&other) Q_DECL_NOTHROW
m_blocked(other.m_blocked),
m_inhibited(other.m_inhibited)
{
- other.m_o = 0;
+ other.m_o = Q_NULLPTR;
}
QSignalBlocker &QSignalBlocker::operator=(QSignalBlocker &&other) Q_DECL_NOTHROW
@@ -598,7 +598,7 @@ QSignalBlocker &QSignalBlocker::operator=(QSignalBlocker &&other) Q_DECL_NOTHROW
m_blocked = other.m_blocked;
m_inhibited = other.m_inhibited;
// disable other:
- other.m_o = 0;
+ other.m_o = Q_NULLPTR;
}
return *this;
}
diff --git a/src/corelib/kernel/qobject_impl.h b/src/corelib/kernel/qobject_impl.h
index 4d9e42ba76..09d52584c4 100644
--- a/src/corelib/kernel/qobject_impl.h
+++ b/src/corelib/kernel/qobject_impl.h
@@ -90,9 +90,9 @@ namespace QtPrivate {
{ enum { Value = QMetaTypeId2<Arg>::Defined && TypesAreDeclaredMetaType<List<Tail...>>::Value }; };
template <typename ArgList, bool Declared = TypesAreDeclaredMetaType<ArgList>::Value > struct ConnectionTypes
- { static const int *types() { return 0; } };
+ { static const int *types() { return Q_NULLPTR; } };
template <> struct ConnectionTypes<List<>, true>
- { static const int *types() { return 0; } };
+ { static const int *types() { return Q_NULLPTR; } };
template <typename... Args> struct ConnectionTypes<List<Args...>, true>
{ static const int *types() { static const int t[sizeof...(Args) + 1] = { (QtPrivate::QMetaTypeIdHelper<Args>::qt_metatype_id())..., 0 }; return t; } };
#endif
@@ -118,10 +118,10 @@ namespace QtPrivate {
inline int ref() Q_DECL_NOTHROW { return m_ref.ref(); }
inline void destroyIfLastRef() Q_DECL_NOTHROW
- { if (!m_ref.deref()) m_impl(Destroy, this, 0, 0, 0); }
+ { if (!m_ref.deref()) m_impl(Destroy, this, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR); }
- inline bool compare(void **a) { bool ret; m_impl(Compare, this, 0, a, &ret); return ret; }
- inline void call(QObject *r, void **a) { m_impl(Call, this, r, a, 0); }
+ inline bool compare(void **a) { bool ret; m_impl(Compare, this, Q_NULLPTR, a, &ret); return ret; }
+ inline void call(QObject *r, void **a) { m_impl(Call, this, r, a, Q_NULLPTR); }
protected:
~QSlotObjectBase() {}
private:
diff --git a/src/corelib/kernel/qobject_p.h b/src/corelib/kernel/qobject_p.h
index 1b64103e40..b0690563d7 100644
--- a/src/corelib/kernel/qobject_p.h
+++ b/src/corelib/kernel/qobject_p.h
@@ -110,7 +110,7 @@ public:
QVector<QObjectUserData *> userData;
#endif
QList<QByteArray> propertyNames;
- QList<QVariant> propertyValues;
+ QVector<QVariant> propertyValues;
QVector<int> runningTimers;
QList<QPointer<QObject> > eventFilters;
QString objectName;
@@ -406,7 +406,7 @@ void Q_CORE_EXPORT qDeleteInEventHandler(QObject *o);
struct QAbstractDynamicMetaObject;
struct Q_CORE_EXPORT QDynamicMetaObjectData
{
- virtual ~QDynamicMetaObjectData() {}
+ virtual ~QDynamicMetaObjectData();
virtual void objectDestroyed(QObject *) { delete this; }
virtual QAbstractDynamicMetaObject *toDynamicMetaObject(QObject *) = 0;
@@ -415,6 +415,8 @@ struct Q_CORE_EXPORT QDynamicMetaObjectData
struct Q_CORE_EXPORT QAbstractDynamicMetaObject : public QDynamicMetaObjectData, public QMetaObject
{
+ ~QAbstractDynamicMetaObject();
+
virtual QAbstractDynamicMetaObject *toDynamicMetaObject(QObject *) Q_DECL_OVERRIDE { return this; }
virtual int createProperty(const char *, const char *) { return -1; }
virtual int metaCall(QObject *, QMetaObject::Call c, int _id, void **a) Q_DECL_OVERRIDE
diff --git a/src/corelib/kernel/qobjectdefs.h b/src/corelib/kernel/qobjectdefs.h
index 6484507a12..b1ed971eba 100644
--- a/src/corelib/kernel/qobjectdefs.h
+++ b/src/corelib/kernel/qobjectdefs.h
@@ -78,7 +78,11 @@ class QString;
#define Q_CLASSINFO(name, value)
#define Q_PLUGIN_METADATA(x)
#define Q_INTERFACES(x)
+#ifdef Q_COMPILER_VARIADIC_MACROS
+#define Q_PROPERTY(...)
+#else
#define Q_PROPERTY(text)
+#endif
#define Q_PRIVATE_PROPERTY(d, text)
#define Q_REVISION(v)
#define Q_OVERRIDE(text)
@@ -254,7 +258,7 @@ class QMetaClassInfo;
class Q_CORE_EXPORT QGenericArgument
{
public:
- inline QGenericArgument(const char *aName = 0, const void *aData = 0)
+ inline QGenericArgument(const char *aName = Q_NULLPTR, const void *aData = Q_NULLPTR)
: _data(aData), _name(aName) {}
inline void *data() const { return const_cast<void *>(_data); }
inline const char *name() const { return _name; }
@@ -267,7 +271,7 @@ private:
class Q_CORE_EXPORT QGenericReturnArgument: public QGenericArgument
{
public:
- inline QGenericReturnArgument(const char *aName = 0, void *aData = 0)
+ inline QGenericReturnArgument(const char *aName = Q_NULLPTR, void *aData = Q_NULLPTR)
: QGenericArgument(aName, aData)
{}
};
@@ -347,7 +351,7 @@ struct Q_CORE_EXPORT QMetaObject
// internal index-based connect
static Connection connect(const QObject *sender, int signal_index,
const QObject *receiver, int method_index,
- int type = 0, int *types = 0);
+ int type = 0, int *types = Q_NULLPTR);
// internal index-based disconnect
static bool disconnect(const QObject *sender, int signal_index,
const QObject *receiver, int method_index);
@@ -364,7 +368,7 @@ struct Q_CORE_EXPORT QMetaObject
static bool invokeMethod(QObject *obj, const char *member,
Qt::ConnectionType,
QGenericReturnArgument ret,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -377,7 +381,7 @@ struct Q_CORE_EXPORT QMetaObject
static inline bool invokeMethod(QObject *obj, const char *member,
QGenericReturnArgument ret,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -394,7 +398,7 @@ struct Q_CORE_EXPORT QMetaObject
static inline bool invokeMethod(QObject *obj, const char *member,
Qt::ConnectionType type,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -410,7 +414,7 @@ struct Q_CORE_EXPORT QMetaObject
}
static inline bool invokeMethod(QObject *obj, const char *member,
- QGenericArgument val0 = QGenericArgument(0),
+ QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -425,7 +429,7 @@ struct Q_CORE_EXPORT QMetaObject
val1, val2, val3, val4, val5, val6, val7, val8, val9);
}
- QObject *newInstance(QGenericArgument val0 = QGenericArgument(0),
+ QObject *newInstance(QGenericArgument val0 = QGenericArgument(Q_NULLPTR),
QGenericArgument val1 = QGenericArgument(),
QGenericArgument val2 = QGenericArgument(),
QGenericArgument val3 = QGenericArgument(),
@@ -482,11 +486,11 @@ public:
operator bool() const;
#else
typedef void *Connection::*RestrictedBool;
- operator RestrictedBool() const { return d_ptr && isConnected_helper() ? &Connection::d_ptr : 0; }
+ operator RestrictedBool() const { return d_ptr && isConnected_helper() ? &Connection::d_ptr : Q_NULLPTR; }
#endif
#ifdef Q_COMPILER_RVALUE_REFS
- inline Connection(Connection &&o) : d_ptr(o.d_ptr) { o.d_ptr = 0; }
+ inline Connection(Connection &&o) : d_ptr(o.d_ptr) { o.d_ptr = Q_NULLPTR; }
inline Connection &operator=(Connection &&other)
{ qSwap(d_ptr, other.d_ptr); return *this; }
#endif
diff --git a/src/corelib/kernel/qpointer.cpp b/src/corelib/kernel/qpointer.cpp
index 2c872716d1..f237498f4e 100644
--- a/src/corelib/kernel/qpointer.cpp
+++ b/src/corelib/kernel/qpointer.cpp
@@ -128,6 +128,14 @@
*/
/*!
+ \fn void QPointer::swap(QPointer &other)
+ \since 5.6
+
+ Swaps the contents of this QPointer with the contents of \a other.
+ This operation is very fast and never fails.
+*/
+
+/*!
\fn QPointer<T> & QPointer::operator=(T* p)
Assignment operator. This guarded pointer will now point to the
diff --git a/src/corelib/kernel/qpointer.h b/src/corelib/kernel/qpointer.h
index af7c11e4d7..52bd368301 100644
--- a/src/corelib/kernel/qpointer.h
+++ b/src/corelib/kernel/qpointer.h
@@ -35,6 +35,7 @@
#define QPOINTER_H
#include <QtCore/qsharedpointer.h>
+#include <QtCore/qtypeinfo.h>
#ifndef QT_NO_QOBJECT
@@ -45,6 +46,8 @@ class QVariant;
template <class T>
class QPointer
{
+ Q_STATIC_ASSERT_X(!QtPrivate::is_pointer<T>::value, "QPointer's template type must not be a pointer type");
+
template<typename U>
struct TypeSelector
{
@@ -61,7 +64,14 @@ public:
inline QPointer() { }
inline QPointer(T *p) : wp(p, true) { }
// compiler-generated copy/move ctor/assignment operators are fine!
- inline ~QPointer() { }
+ // compiler-generated dtor is fine!
+
+#ifdef Q_QDOC
+ // Stop qdoc from complaining about missing function
+ ~QPointer();
+#endif
+
+ inline void swap(QPointer &other) { wp.swap(other.wp); }
inline QPointer<T> &operator=(T* p)
{ wp.assign(static_cast<QObjectType*>(p)); return *this; }
diff --git a/src/corelib/kernel/qsharedmemory.h b/src/corelib/kernel/qsharedmemory.h
index c192910dc7..67558e3348 100644
--- a/src/corelib/kernel/qsharedmemory.h
+++ b/src/corelib/kernel/qsharedmemory.h
@@ -68,8 +68,8 @@ public:
UnknownError
};
- QSharedMemory(QObject *parent = 0);
- QSharedMemory(const QString &key, QObject *parent = 0);
+ QSharedMemory(QObject *parent = Q_NULLPTR);
+ QSharedMemory(const QString &key, QObject *parent = Q_NULLPTR);
~QSharedMemory();
void setKey(const QString &key);
diff --git a/src/corelib/kernel/qsignalmapper.h b/src/corelib/kernel/qsignalmapper.h
index df2a0a52ea..7aaef6affc 100644
--- a/src/corelib/kernel/qsignalmapper.h
+++ b/src/corelib/kernel/qsignalmapper.h
@@ -45,7 +45,7 @@ class Q_CORE_EXPORT QSignalMapper : public QObject
Q_OBJECT
Q_DECLARE_PRIVATE(QSignalMapper)
public:
- explicit QSignalMapper(QObject *parent = 0);
+ explicit QSignalMapper(QObject *parent = Q_NULLPTR);
~QSignalMapper();
void setMapping(QObject *sender, int id);
diff --git a/src/corelib/kernel/qsocketnotifier.h b/src/corelib/kernel/qsocketnotifier.h
index 4bafbfa69f..8a7af6ebbc 100644
--- a/src/corelib/kernel/qsocketnotifier.h
+++ b/src/corelib/kernel/qsocketnotifier.h
@@ -47,7 +47,7 @@ class Q_CORE_EXPORT QSocketNotifier : public QObject
public:
enum Type { Read, Write, Exception };
- QSocketNotifier(qintptr socket, Type, QObject *parent = 0);
+ QSocketNotifier(qintptr socket, Type, QObject *parent = Q_NULLPTR);
~QSocketNotifier();
qintptr socket() const;
diff --git a/src/corelib/kernel/qsystemerror.cpp b/src/corelib/kernel/qsystemerror.cpp
index 19d84c2b3e..e333104add 100644
--- a/src/corelib/kernel/qsystemerror.cpp
+++ b/src/corelib/kernel/qsystemerror.cpp
@@ -145,7 +145,7 @@ static QString standardLibraryErrorString(int errorCode)
return ret.trimmed();
}
-QString QSystemError::toString()
+QString QSystemError::toString() const
{
switch(errorScope) {
case NativeError:
diff --git a/src/corelib/kernel/qsystemerror_p.h b/src/corelib/kernel/qsystemerror_p.h
index e7efb9bbf3..29e9e440e4 100644
--- a/src/corelib/kernel/qsystemerror_p.h
+++ b/src/corelib/kernel/qsystemerror_p.h
@@ -62,9 +62,9 @@ public:
inline QSystemError(int error, ErrorScope scope);
inline QSystemError();
- QString toString();
- inline ErrorScope scope();
- inline int error();
+ QString toString() const;
+ inline ErrorScope scope() const;
+ inline int error() const;
//data members
int errorCode;
@@ -83,12 +83,12 @@ QSystemError::QSystemError()
}
-QSystemError::ErrorScope QSystemError::scope()
+QSystemError::ErrorScope QSystemError::scope() const
{
return errorScope;
}
-int QSystemError::error()
+int QSystemError::error() const
{
return errorCode;
}
diff --git a/src/corelib/kernel/qsystemsemaphore_win.cpp b/src/corelib/kernel/qsystemsemaphore_win.cpp
index ca55025c2a..89b8a87f2a 100644
--- a/src/corelib/kernel/qsystemsemaphore_win.cpp
+++ b/src/corelib/kernel/qsystemsemaphore_win.cpp
@@ -115,7 +115,7 @@ bool QSystemSemaphorePrivate::modifySemaphore(int count)
return false;
}
} else {
-#if defined(Q_OS_WINRT)
+#if !defined(Q_OS_WINCE)
if (WAIT_OBJECT_0 != WaitForSingleObjectEx(semaphore, INFINITE, FALSE)) {
#else
if (WAIT_OBJECT_0 != WaitForSingleObject(semaphore, INFINITE)) {
diff --git a/src/corelib/kernel/qtimer.h b/src/corelib/kernel/qtimer.h
index 163ef75291..889f5d7f70 100644
--- a/src/corelib/kernel/qtimer.h
+++ b/src/corelib/kernel/qtimer.h
@@ -53,7 +53,7 @@ class Q_CORE_EXPORT QTimer : public QObject
Q_PROPERTY(Qt::TimerType timerType READ timerType WRITE setTimerType)
Q_PROPERTY(bool active READ isActive)
public:
- explicit QTimer(QObject *parent = 0);
+ explicit QTimer(QObject *parent = Q_NULLPTR);
~QTimer();
inline bool isActive() const { return id >= 0; }
@@ -102,12 +102,16 @@ public:
}
// singleShot to a functor or function pointer (without context)
template <typename Func1>
- static inline void singleShot(int msec, Func1 slot)
+ static inline typename QtPrivate::QEnableIf<!QtPrivate::FunctionPointer<Func1>::IsPointerToMemberFunction &&
+ !QtPrivate::is_same<const char*, Func1>::value, void>::Type
+ singleShot(int msec, Func1 slot)
{
singleShot(msec, msec >= 2000 ? Qt::CoarseTimer : Qt::PreciseTimer, Q_NULLPTR, slot);
}
template <typename Func1>
- static inline void singleShot(int msec, Qt::TimerType timerType, Func1 slot)
+ static inline typename QtPrivate::QEnableIf<!QtPrivate::FunctionPointer<Func1>::IsPointerToMemberFunction &&
+ !QtPrivate::is_same<const char*, Func1>::value, void>::Type
+ singleShot(int msec, Qt::TimerType timerType, Func1 slot)
{
singleShot(msec, timerType, Q_NULLPTR, slot);
}
diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp
index 360c5873d4..794a4aaa0c 100644
--- a/src/corelib/kernel/qtranslator.cpp
+++ b/src/corelib/kernel/qtranslator.cpp
@@ -46,7 +46,6 @@
#include "qfile.h"
#include "qmap.h"
#include "qalgorithms.h"
-#include "qhash.h"
#include "qtranslator_p.h"
#include "qlocale.h"
#include "qendian.h"
diff --git a/src/corelib/kernel/qtranslator.h b/src/corelib/kernel/qtranslator.h
index 1552bbde35..78f714c5c6 100644
--- a/src/corelib/kernel/qtranslator.h
+++ b/src/corelib/kernel/qtranslator.h
@@ -49,11 +49,11 @@ class Q_CORE_EXPORT QTranslator : public QObject
{
Q_OBJECT
public:
- explicit QTranslator(QObject *parent = 0);
+ explicit QTranslator(QObject *parent = Q_NULLPTR);
~QTranslator();
virtual QString translate(const char *context, const char *sourceText,
- const char *disambiguation = 0, int n = -1) const;
+ const char *disambiguation = Q_NULLPTR, int n = -1) const;
virtual bool isEmpty() const;
diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp
index f7a4abbf68..35f178e6a9 100644
--- a/src/corelib/kernel/qvariant.cpp
+++ b/src/corelib/kernel/qvariant.cpp
@@ -3832,7 +3832,11 @@ QDebug operator<<(QDebug dbg, const QVariant::Type p)
/*!
\internal
*/
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QSequentialIterable::QSequentialIterable(QtMetaTypePrivate::QSequentialIterableImpl impl)
+#else
+QSequentialIterable::QSequentialIterable(const QtMetaTypePrivate::QSequentialIterableImpl &impl)
+#endif
: m_impl(impl)
{
}
@@ -4140,7 +4144,11 @@ QSequentialIterable::const_iterator QSequentialIterable::const_iterator::operato
/*!
\internal
*/
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QAssociativeIterable::QAssociativeIterable(QtMetaTypePrivate::QAssociativeIterableImpl impl)
+#else
+QAssociativeIterable::QAssociativeIterable(const QtMetaTypePrivate::QAssociativeIterableImpl &impl)
+#endif
: m_impl(impl)
{
}
diff --git a/src/corelib/kernel/qvariant.h b/src/corelib/kernel/qvariant.h
index 58dfc3aab0..4c7e498280 100644
--- a/src/corelib/kernel/qvariant.h
+++ b/src/corelib/kernel/qvariant.h
@@ -278,14 +278,14 @@ class Q_CORE_EXPORT QVariant
void detach();
inline bool isDetached() const;
- int toInt(bool *ok = 0) const;
- uint toUInt(bool *ok = 0) const;
- qlonglong toLongLong(bool *ok = 0) const;
- qulonglong toULongLong(bool *ok = 0) const;
+ int toInt(bool *ok = Q_NULLPTR) const;
+ uint toUInt(bool *ok = Q_NULLPTR) const;
+ qlonglong toLongLong(bool *ok = Q_NULLPTR) const;
+ qulonglong toULongLong(bool *ok = Q_NULLPTR) const;
bool toBool() const;
- double toDouble(bool *ok = 0) const;
- float toFloat(bool *ok = 0) const;
- qreal toReal(bool *ok = 0) const;
+ double toDouble(bool *ok = Q_NULLPTR) const;
+ float toFloat(bool *ok = Q_NULLPTR) const;
+ qreal toReal(bool *ok = Q_NULLPTR) const;
QByteArray toByteArray() const;
QBitArray toBitArray() const;
QString toString() const;
@@ -364,7 +364,7 @@ class Q_CORE_EXPORT QVariant
struct Private
{
inline Private() Q_DECL_NOTHROW : type(Invalid), is_shared(false), is_null(true)
- { data.ptr = 0; }
+ { data.ptr = Q_NULLPTR; }
// Internal constructor for initialized variants.
explicit inline Private(uint variantType) Q_DECL_NOTHROW
@@ -607,7 +607,11 @@ public:
friend struct const_iterator;
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
explicit QSequentialIterable(QtMetaTypePrivate::QSequentialIterableImpl impl);
+#else
+ explicit QSequentialIterable(const QtMetaTypePrivate::QSequentialIterableImpl &impl);
+#endif
const_iterator begin() const;
const_iterator end() const;
@@ -660,7 +664,11 @@ public:
friend struct const_iterator;
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
explicit QAssociativeIterable(QtMetaTypePrivate::QAssociativeIterableImpl impl);
+#else
+ explicit QAssociativeIterable(const QtMetaTypePrivate::QAssociativeIterableImpl &impl);
+#endif
const_iterator begin() const;
const_iterator end() const;
@@ -742,7 +750,7 @@ namespace QtPrivate {
static QVariantList invoke(const QVariant &v)
{
const int typeId = v.userType();
- if (QtMetaTypePrivate::isBuiltinSequentialType(typeId) || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QSequentialIterableImpl>())) {
+ if (typeId == qMetaTypeId<QStringList>() || typeId == qMetaTypeId<QByteArrayList>() || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QSequentialIterableImpl>())) {
QSequentialIterable iter = QVariantValueHelperInterface<QSequentialIterable>::invoke(v);
QVariantList l;
l.reserve(iter.size());
@@ -759,7 +767,7 @@ namespace QtPrivate {
static QVariantHash invoke(const QVariant &v)
{
const int typeId = v.userType();
- if (QtMetaTypePrivate::isBuiltinAssociativeType(typeId) || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QAssociativeIterableImpl>())) {
+ if (typeId == qMetaTypeId<QVariantMap>() || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QAssociativeIterableImpl>())) {
QAssociativeIterable iter = QVariantValueHelperInterface<QAssociativeIterable>::invoke(v);
QVariantHash l;
l.reserve(iter.size());
@@ -776,7 +784,7 @@ namespace QtPrivate {
static QVariantMap invoke(const QVariant &v)
{
const int typeId = v.userType();
- if (QtMetaTypePrivate::isBuiltinAssociativeType(typeId) || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QAssociativeIterableImpl>())) {
+ if (typeId == qMetaTypeId<QVariantHash>() || QMetaType::hasRegisteredConverterFunction(typeId, qMetaTypeId<QtMetaTypePrivate::QAssociativeIterableImpl>())) {
QAssociativeIterable iter = QVariantValueHelperInterface<QAssociativeIterable>::invoke(v);
QVariantMap l;
for (QAssociativeIterable::const_iterator it = iter.begin(), end = iter.end(); it != end; ++it)
diff --git a/src/corelib/mimetypes/qmimedatabase.cpp b/src/corelib/mimetypes/qmimedatabase.cpp
index bec7a79e8f..133933f9af 100644
--- a/src/corelib/mimetypes/qmimedatabase.cpp
+++ b/src/corelib/mimetypes/qmimedatabase.cpp
@@ -434,6 +434,7 @@ QList<QMimeType> QMimeDatabase::mimeTypesForFileName(const QString &fileName) co
QStringList matches = d->mimeTypeForFileName(fileName);
QList<QMimeType> mimes;
matches.sort(); // Make it deterministic
+ mimes.reserve(matches.count());
foreach (const QString &mime, matches)
mimes.append(d->mimeTypeForName(mime));
return mimes;
diff --git a/src/corelib/mimetypes/qmimedatabase_p.h b/src/corelib/mimetypes/qmimedatabase_p.h
index e3cfe3443f..1308907b9b 100644
--- a/src/corelib/mimetypes/qmimedatabase_p.h
+++ b/src/corelib/mimetypes/qmimedatabase_p.h
@@ -52,7 +52,6 @@
#include "qmimetype_p.h"
#include "qmimeglobpattern_p.h"
-#include <QtCore/qhash.h>
#include <QtCore/qmutex.h>
QT_BEGIN_NAMESPACE
diff --git a/src/corelib/mimetypes/qmimeprovider.cpp b/src/corelib/mimetypes/qmimeprovider.cpp
index 887db51e5c..fa40b743d3 100644
--- a/src/corelib/mimetypes/qmimeprovider.cpp
+++ b/src/corelib/mimetypes/qmimeprovider.cpp
@@ -540,6 +540,7 @@ QList<QMimeType> QMimeBinaryProvider::allMimeTypes()
{
QList<QMimeType> result;
loadMimeTypeList();
+ result.reserve(m_mimetypeNames.count());
for (QSet<QString>::const_iterator it = m_mimetypeNames.constBegin();
it != m_mimetypeNames.constEnd(); ++it)
diff --git a/src/corelib/mimetypes/qmimetype.cpp b/src/corelib/mimetypes/qmimetype.cpp
index a5f9cb70d5..3206ff66e3 100644
--- a/src/corelib/mimetypes/qmimetype.cpp
+++ b/src/corelib/mimetypes/qmimetype.cpp
@@ -43,6 +43,7 @@
#include <QtCore/QDebug>
#include <QtCore/QLocale>
+#include <QtCore/QHashFunctions>
#include <memory>
@@ -181,6 +182,18 @@ bool QMimeType::operator==(const QMimeType &other) const
}
/*!
+ \since 5.6
+ \relates QMimeType
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+ */
+uint qHash(const QMimeType &key, uint seed) Q_DECL_NOTHROW
+{
+ return qHash(key.d->name, seed);
+}
+
+/*!
\fn bool QMimeType::operator!=(const QMimeType &other) const;
Returns \c true if \a other does not equal this QMimeType object, otherwise returns \c false.
*/
diff --git a/src/corelib/mimetypes/qmimetype.h b/src/corelib/mimetypes/qmimetype.h
index 4ba3c53470..3c153da21d 100644
--- a/src/corelib/mimetypes/qmimetype.h
+++ b/src/corelib/mimetypes/qmimetype.h
@@ -46,6 +46,9 @@ QT_BEGIN_NAMESPACE
class QMimeTypePrivate;
class QFileinfo;
class QStringList;
+class QMimeType;
+
+Q_CORE_EXPORT uint qHash(const QMimeType &key, uint seed = 0) Q_DECL_NOTHROW;
class Q_CORE_EXPORT QMimeType
{
@@ -54,13 +57,9 @@ public:
QMimeType(const QMimeType &other);
QMimeType &operator=(const QMimeType &other);
#ifdef Q_COMPILER_RVALUE_REFS
- QMimeType &operator=(QMimeType &&other)
- {
- qSwap(d, other.d);
- return *this;
- }
+ QMimeType &operator=(QMimeType &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- void swap(QMimeType &other)
+ void swap(QMimeType &other) Q_DECL_NOTHROW
{
qSwap(d, other.d);
}
@@ -100,6 +99,7 @@ protected:
friend class QMimeXMLProvider;
friend class QMimeBinaryProvider;
friend class QMimeTypePrivate;
+ friend Q_CORE_EXPORT uint qHash(const QMimeType &key, uint seed) Q_DECL_NOTHROW;
QExplicitlySharedDataPointer<QMimeTypePrivate> d;
};
diff --git a/src/corelib/plugin/plugin.pri b/src/corelib/plugin/plugin.pri
index 338b3d0972..8b64f93467 100644
--- a/src/corelib/plugin/plugin.pri
+++ b/src/corelib/plugin/plugin.pri
@@ -13,6 +13,7 @@ HEADERS += \
plugin/qmachparser_p.h
SOURCES += \
+ plugin/qfactoryinterface.cpp \
plugin/qpluginloader.cpp \
plugin/qfactoryloader.cpp \
plugin/quuid.cpp \
diff --git a/src/plugins/platforms/cocoa/qcocoaautoreleasepool.mm b/src/corelib/plugin/qfactoryinterface.cpp
index 8f30365186..0307d58315 100644
--- a/src/plugins/platforms/cocoa/qcocoaautoreleasepool.mm
+++ b/src/corelib/plugin/qfactoryinterface.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@@ -31,18 +31,13 @@
**
****************************************************************************/
-#include "qcocoaautoreleasepool.h"
+#include "qfactoryinterface.h"
QT_BEGIN_NAMESPACE
-QCocoaAutoReleasePool::QCocoaAutoReleasePool()
+QFactoryInterface::~QFactoryInterface()
{
- pool = [[NSAutoreleasePool alloc] init];
-}
-
-QCocoaAutoReleasePool::~QCocoaAutoReleasePool()
-{
- [pool release];
+ // must be empty until ### Qt 6
}
QT_END_NAMESPACE
diff --git a/src/corelib/plugin/qfactoryinterface.h b/src/corelib/plugin/qfactoryinterface.h
index e20864cd31..86a46fabfa 100644
--- a/src/corelib/plugin/qfactoryinterface.h
+++ b/src/corelib/plugin/qfactoryinterface.h
@@ -42,7 +42,7 @@ QT_BEGIN_NAMESPACE
struct Q_CORE_EXPORT QFactoryInterface
{
- virtual ~QFactoryInterface() {}
+ virtual ~QFactoryInterface();
virtual QStringList keys() const = 0;
};
diff --git a/src/corelib/plugin/qlibrary.h b/src/corelib/plugin/qlibrary.h
index 16bdf79206..77ad107c6f 100644
--- a/src/corelib/plugin/qlibrary.h
+++ b/src/corelib/plugin/qlibrary.h
@@ -59,10 +59,10 @@ public:
Q_FLAG(LoadHint)
Q_FLAG(LoadHints)
- explicit QLibrary(QObject *parent = 0);
- explicit QLibrary(const QString& fileName, QObject *parent = 0);
- explicit QLibrary(const QString& fileName, int verNum, QObject *parent = 0);
- explicit QLibrary(const QString& fileName, const QString &version, QObject *parent = 0);
+ explicit QLibrary(QObject *parent = Q_NULLPTR);
+ explicit QLibrary(const QString& fileName, QObject *parent = Q_NULLPTR);
+ explicit QLibrary(const QString& fileName, int verNum, QObject *parent = Q_NULLPTR);
+ explicit QLibrary(const QString& fileName, const QString &version, QObject *parent = Q_NULLPTR);
~QLibrary();
QFunctionPointer resolve(const char *symbol);
diff --git a/src/corelib/plugin/qpluginloader.cpp b/src/corelib/plugin/qpluginloader.cpp
index 988dad1d94..292ad30525 100644
--- a/src/corelib/plugin/qpluginloader.cpp
+++ b/src/corelib/plugin/qpluginloader.cpp
@@ -273,6 +273,13 @@ bool QPluginLoader::isLoaded() const
#if defined(QT_SHARED)
static QString locatePlugin(const QString& fileName)
{
+ const bool isAbsolute = QDir::isAbsolutePath(fileName);
+ if (isAbsolute) {
+ QFileInfo fi(fileName);
+ if (fi.isFile()) {
+ return fi.canonicalFilePath();
+ }
+ }
QStringList prefixes = QLibraryPrivate::prefixes_sys();
prefixes.prepend(QString());
QStringList suffixes = QLibraryPrivate::suffixes_sys(QString());
@@ -281,12 +288,18 @@ static QString locatePlugin(const QString& fileName)
// Split up "subdir/filename"
const int slash = fileName.lastIndexOf('/');
const QString baseName = fileName.mid(slash + 1);
- const QString basePath = fileName.left(slash + 1); // keep the '/'
+ const QString basePath = isAbsolute ? QString() : fileName.left(slash + 1); // keep the '/'
const bool debug = qt_debug_component();
- QStringList paths = QCoreApplication::libraryPaths();
- paths.prepend(QStringLiteral("./")); // search in current dir first
+ QStringList paths;
+ if (isAbsolute) {
+ paths.append(fileName.left(slash)); // don't include the '/'
+ } else {
+ paths = QCoreApplication::libraryPaths();
+ paths.prepend(QStringLiteral(".")); // search in current dir first
+ }
+
foreach (const QString &path, paths) {
foreach (const QString &prefix, prefixes) {
foreach (const QString &suffix, suffixes) {
@@ -337,12 +350,7 @@ void QPluginLoader::setFileName(const QString &fileName)
did_load = false;
}
- QFileInfo fi(fileName);
- QString fn;
- if (fi.isAbsolute())
- fn = fi.canonicalFilePath();
- else
- fn = locatePlugin(fileName);
+ const QString fn = locatePlugin(fileName);
d = QLibraryPrivate::findOrCreate(fn, QString(), lh);
if (!fn.isEmpty())
@@ -427,7 +435,9 @@ QObjectList QPluginLoader::staticInstances()
QObjectList instances;
const StaticPluginList *plugins = staticPluginList();
if (plugins) {
- for (int i = 0; i < plugins->size(); ++i)
+ const int numPlugins = plugins->size();
+ instances.reserve(numPlugins);
+ for (int i = 0; i < numPlugins; ++i)
instances += plugins->at(i).instance();
}
return instances;
diff --git a/src/corelib/plugin/qpluginloader.h b/src/corelib/plugin/qpluginloader.h
index b947e6ed9e..0ab25bbb07 100644
--- a/src/corelib/plugin/qpluginloader.h
+++ b/src/corelib/plugin/qpluginloader.h
@@ -50,8 +50,8 @@ class Q_CORE_EXPORT QPluginLoader : public QObject
Q_PROPERTY(QString fileName READ fileName WRITE setFileName)
Q_PROPERTY(QLibrary::LoadHints loadHints READ loadHints WRITE setLoadHints)
public:
- explicit QPluginLoader(QObject *parent = 0);
- explicit QPluginLoader(const QString &fileName, QObject *parent = 0);
+ explicit QPluginLoader(QObject *parent = Q_NULLPTR);
+ explicit QPluginLoader(const QString &fileName, QObject *parent = Q_NULLPTR);
~QPluginLoader();
QObject *instance();
diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp
index 543edb2f98..2c412849e8 100644
--- a/src/corelib/statemachine/qabstractstate.cpp
+++ b/src/corelib/statemachine/qabstractstate.cpp
@@ -85,16 +85,6 @@ QAbstractStatePrivate::QAbstractStatePrivate(StateType type)
{
}
-QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q)
-{
- return q->d_func();
-}
-
-const QAbstractStatePrivate *QAbstractStatePrivate::get(const QAbstractState *q)
-{
- return q->d_func();
-}
-
QStateMachine *QAbstractStatePrivate::machine() const
{
QObject *par = parent;
@@ -227,7 +217,7 @@ bool QAbstractState::active() const
\fn QAbstractState::activeChanged(bool active)
\since 5.4
- This signal is emitted when the active property is changed.
+ This signal is emitted when the active property is changed with \a active as argument.
\sa QAbstractState::active, entered(), exited()
*/
diff --git a/src/corelib/statemachine/qabstractstate.h b/src/corelib/statemachine/qabstractstate.h
index 592c841c18..3aa4b2fabb 100644
--- a/src/corelib/statemachine/qabstractstate.h
+++ b/src/corelib/statemachine/qabstractstate.h
@@ -63,7 +63,7 @@ Q_SIGNALS:
void activeChanged(bool active);
protected:
- QAbstractState(QState *parent = 0);
+ QAbstractState(QState *parent = Q_NULLPTR);
virtual void onEntry(QEvent *event) = 0;
virtual void onExit(QEvent *event) = 0;
diff --git a/src/corelib/statemachine/qabstractstate_p.h b/src/corelib/statemachine/qabstractstate_p.h
index 087e355b71..1eb3cbd420 100644
--- a/src/corelib/statemachine/qabstractstate_p.h
+++ b/src/corelib/statemachine/qabstractstate_p.h
@@ -46,12 +46,13 @@
//
#include <private/qobject_p.h>
+#include <QtCore/qabstractstate.h>
QT_BEGIN_NAMESPACE
class QStateMachine;
-class QAbstractState;
+class QState;
class QAbstractStatePrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QAbstractState)
@@ -66,8 +67,10 @@ public:
QAbstractStatePrivate(StateType type);
- static QAbstractStatePrivate *get(QAbstractState *q);
- static const QAbstractStatePrivate *get(const QAbstractState *q);
+ static QAbstractStatePrivate *get(QAbstractState *q)
+ { return q->d_func(); }
+ static const QAbstractStatePrivate *get(const QAbstractState *q)
+ { return q->d_func(); }
QStateMachine *machine() const;
diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp
index 81b38ea4c4..5a7a95883b 100644
--- a/src/corelib/statemachine/qabstracttransition.cpp
+++ b/src/corelib/statemachine/qabstracttransition.cpp
@@ -37,6 +37,7 @@
#include "qabstracttransition_p.h"
#include "qabstractstate.h"
+#include "qhistorystate.h"
#include "qstate.h"
#include "qstatemachine.h"
@@ -133,17 +134,14 @@ QAbstractTransitionPrivate::QAbstractTransitionPrivate()
{
}
-QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(QAbstractTransition *q)
-{
- return q->d_func();
-}
-
QStateMachine *QAbstractTransitionPrivate::machine() const
{
- QState *source = sourceState();
- if (!source)
- return 0;
- return source->machine();
+ if (QState *source = sourceState())
+ return source->machine();
+ Q_Q(const QAbstractTransition);
+ if (QHistoryState *parent = qobject_cast<QHistoryState *>(q->parent()))
+ return parent->machine();
+ return 0;
}
bool QAbstractTransitionPrivate::callEventTest(QEvent *e)
@@ -254,7 +252,7 @@ QList<QAbstractState*> QAbstractTransition::targetStates() const
void QAbstractTransition::setTargetStates(const QList<QAbstractState*> &targets)
{
Q_D(QAbstractTransition);
- QList<QPointer<QAbstractState> > copy(d->targetStates);
+ QVector<QPointer<QAbstractState> > copy(d->targetStates);
bool sameList = true;
for (int i = 0; i < targets.size(); ++i) {
QAbstractState *target = targets.at(i);
diff --git a/src/corelib/statemachine/qabstracttransition.h b/src/corelib/statemachine/qabstracttransition.h
index 475a4dedfc..4398c41ca2 100644
--- a/src/corelib/statemachine/qabstracttransition.h
+++ b/src/corelib/statemachine/qabstracttransition.h
@@ -67,7 +67,7 @@ public:
};
Q_ENUM(TransitionType)
- QAbstractTransition(QState *sourceState = 0);
+ QAbstractTransition(QState *sourceState = Q_NULLPTR);
virtual ~QAbstractTransition();
QState *sourceState() const;
diff --git a/src/corelib/statemachine/qabstracttransition_p.h b/src/corelib/statemachine/qabstracttransition_p.h
index 4b0644acd9..ed726fa6ef 100644
--- a/src/corelib/statemachine/qabstracttransition_p.h
+++ b/src/corelib/statemachine/qabstracttransition_p.h
@@ -48,6 +48,7 @@
#include <private/qobject_p.h>
#include <QtCore/qlist.h>
+#include <QtCore/qvector.h>
#include <QtCore/qsharedpointer.h>
QT_BEGIN_NAMESPACE
@@ -64,7 +65,8 @@ class Q_CORE_EXPORT QAbstractTransitionPrivate
public:
QAbstractTransitionPrivate();
- static QAbstractTransitionPrivate *get(QAbstractTransition *q);
+ static QAbstractTransitionPrivate *get(QAbstractTransition *q)
+ { return q->d_func(); }
bool callEventTest(QEvent *e);
virtual void callOnTransition(QEvent *e);
@@ -72,7 +74,7 @@ public:
QStateMachine *machine() const;
void emitTriggered();
- QList<QPointer<QAbstractState> > targetStates;
+ QVector<QPointer<QAbstractState> > targetStates;
QAbstractTransition::TransitionType transitionType;
#ifndef QT_NO_ANIMATION
diff --git a/src/corelib/statemachine/qeventtransition.cpp b/src/corelib/statemachine/qeventtransition.cpp
index 096d667bc3..de6858ae42 100644
--- a/src/corelib/statemachine/qeventtransition.cpp
+++ b/src/corelib/statemachine/qeventtransition.cpp
@@ -102,9 +102,8 @@ QEventTransitionPrivate::QEventTransitionPrivate()
registered = false;
}
-QEventTransitionPrivate *QEventTransitionPrivate::get(QEventTransition *q)
+QEventTransitionPrivate::~QEventTransitionPrivate()
{
- return q->d_func();
}
void QEventTransitionPrivate::unregister()
diff --git a/src/corelib/statemachine/qeventtransition.h b/src/corelib/statemachine/qeventtransition.h
index 6909e855b1..5ec3b7bb26 100644
--- a/src/corelib/statemachine/qeventtransition.h
+++ b/src/corelib/statemachine/qeventtransition.h
@@ -49,8 +49,8 @@ class Q_CORE_EXPORT QEventTransition : public QAbstractTransition
Q_PROPERTY(QObject* eventSource READ eventSource WRITE setEventSource)
Q_PROPERTY(QEvent::Type eventType READ eventType WRITE setEventType)
public:
- QEventTransition(QState *sourceState = 0);
- QEventTransition(QObject *object, QEvent::Type type, QState *sourceState = 0);
+ QEventTransition(QState *sourceState = Q_NULLPTR);
+ QEventTransition(QObject *object, QEvent::Type type, QState *sourceState = Q_NULLPTR);
~QEventTransition();
QObject *eventSource() const;
diff --git a/src/corelib/statemachine/qeventtransition_p.h b/src/corelib/statemachine/qeventtransition_p.h
index 59b0fcb30f..3f6c9475ea 100644
--- a/src/corelib/statemachine/qeventtransition_p.h
+++ b/src/corelib/statemachine/qeventtransition_p.h
@@ -55,8 +55,10 @@ class Q_CORE_EXPORT QEventTransitionPrivate : public QAbstractTransitionPrivate
Q_DECLARE_PUBLIC(QEventTransition)
public:
QEventTransitionPrivate();
+ ~QEventTransitionPrivate();
- static QEventTransitionPrivate *get(QEventTransition *q);
+ static QEventTransitionPrivate *get(QEventTransition *q)
+ { return q->d_func(); }
void unregister();
void maybeRegister();
diff --git a/src/corelib/statemachine/qfinalstate.h b/src/corelib/statemachine/qfinalstate.h
index 51c97b1545..2c76e7b6e6 100644
--- a/src/corelib/statemachine/qfinalstate.h
+++ b/src/corelib/statemachine/qfinalstate.h
@@ -46,7 +46,7 @@ class Q_CORE_EXPORT QFinalState : public QAbstractState
{
Q_OBJECT
public:
- QFinalState(QState *parent = 0);
+ QFinalState(QState *parent = Q_NULLPTR);
~QFinalState();
protected:
diff --git a/src/corelib/statemachine/qhistorystate.cpp b/src/corelib/statemachine/qhistorystate.cpp
index e58b0c16fc..a0ebb9d239 100644
--- a/src/corelib/statemachine/qhistorystate.cpp
+++ b/src/corelib/statemachine/qhistorystate.cpp
@@ -50,7 +50,7 @@ QT_BEGIN_NAMESPACE
A history state is a pseudo-state that represents the child state that the
parent state was in the last time the parent state was exited. A transition
- with a history state as its target is in fact a transition to one of the
+ with a history state as its target is in fact a transition to one or more
other child states of the parent state. QHistoryState is part of \l{The
State Machine Framework}.
@@ -79,11 +79,22 @@ QT_BEGIN_NAMESPACE
s1->addTransition(button, SIGNAL(clicked()), s1h);
\endcode
+ If more than one default state has to be entered, or if the transition to the default state(s)
+ has to be acted upon, the defaultTransition should be set instead. Note that the eventTest()
+ method of that transition will never be called: the selection and execution of the transition is
+ done automatically when entering the history state.
+
By default a history state is shallow, meaning that it won't remember nested
states. This can be configured through the historyType property.
*/
/*!
+ \property QHistoryState::defaultTransition
+
+ \brief the default transition of this history state
+*/
+
+/*!
\property QHistoryState::defaultState
\brief the default state of this history state
@@ -113,14 +124,17 @@ QT_BEGIN_NAMESPACE
*/
QHistoryStatePrivate::QHistoryStatePrivate()
- : QAbstractStatePrivate(HistoryState),
- defaultState(0), historyType(QHistoryState::ShallowHistory)
+ : QAbstractStatePrivate(HistoryState)
+ , defaultTransition(0)
+ , historyType(QHistoryState::ShallowHistory)
{
}
-QHistoryStatePrivate *QHistoryStatePrivate::get(QHistoryState *q)
+DefaultStateTransition::DefaultStateTransition(QHistoryState *source, QAbstractState *target)
+ : QAbstractTransition()
{
- return q->d_func();
+ setParent(source);
+ setTargetState(target);
}
/*!
@@ -149,13 +163,40 @@ QHistoryState::~QHistoryState()
}
/*!
+ Returns this history state's default transition. The default transition is
+ taken when the history state has never been entered before. The target states
+ of the default transition therefore make up the default state.
+*/
+QAbstractTransition *QHistoryState::defaultTransition() const
+{
+ Q_D(const QHistoryState);
+ return d->defaultTransition;
+}
+
+/*!
+ Sets this history state's default transition to be the given \a transition.
+ This will set the source state of the \a transition to the history state.
+
+ Note that the eventTest method of the \a transition will never be called.
+*/
+void QHistoryState::setDefaultTransition(QAbstractTransition *transition)
+{
+ Q_D(QHistoryState);
+ if (d->defaultTransition != transition) {
+ d->defaultTransition = transition;
+ transition->setParent(this);
+ emit defaultTransitionChanged(QHistoryState::QPrivateSignal());
+ }
+}
+
+/*!
Returns this history state's default state. The default state indicates the
state to transition to if the parent state has never been entered before.
*/
QAbstractState *QHistoryState::defaultState() const
{
Q_D(const QHistoryState);
- return d->defaultState;
+ return d->defaultTransition ? d->defaultTransition->targetState() : Q_NULLPTR;
}
/*!
@@ -173,8 +214,15 @@ void QHistoryState::setDefaultState(QAbstractState *state)
"to this history state's group (%p)", state, parentState());
return;
}
- if (d->defaultState != state) {
- d->defaultState = state;
+ if (!d->defaultTransition
+ || d->defaultTransition->targetStates().size() != 1
+ || d->defaultTransition->targetStates().first() != state) {
+ if (!d->defaultTransition || !qobject_cast<DefaultStateTransition*>(d->defaultTransition)) {
+ d->defaultTransition = new DefaultStateTransition(this, state);
+ emit defaultTransitionChanged(QHistoryState::QPrivateSignal());
+ } else {
+ d->defaultTransition->setTargetState(state);
+ }
emit defaultStateChanged(QHistoryState::QPrivateSignal());
}
}
diff --git a/src/corelib/statemachine/qhistorystate.h b/src/corelib/statemachine/qhistorystate.h
index 549be15ab0..2f2081bf9c 100644
--- a/src/corelib/statemachine/qhistorystate.h
+++ b/src/corelib/statemachine/qhistorystate.h
@@ -41,11 +41,13 @@ QT_BEGIN_NAMESPACE
#ifndef QT_NO_STATEMACHINE
+class QAbstractTransition;
class QHistoryStatePrivate;
class Q_CORE_EXPORT QHistoryState : public QAbstractState
{
Q_OBJECT
Q_PROPERTY(QAbstractState* defaultState READ defaultState WRITE setDefaultState NOTIFY defaultStateChanged)
+ Q_PROPERTY(QAbstractTransition* defaultTransition READ defaultTransition WRITE setDefaultTransition NOTIFY defaultTransitionChanged)
Q_PROPERTY(HistoryType historyType READ historyType WRITE setHistoryType NOTIFY historyTypeChanged)
public:
enum HistoryType {
@@ -54,10 +56,13 @@ public:
};
Q_ENUM(HistoryType)
- QHistoryState(QState *parent = 0);
- QHistoryState(HistoryType type, QState *parent = 0);
+ QHistoryState(QState *parent = Q_NULLPTR);
+ QHistoryState(HistoryType type, QState *parent = Q_NULLPTR);
~QHistoryState();
+ QAbstractTransition *defaultTransition() const;
+ void setDefaultTransition(QAbstractTransition *transition);
+
QAbstractState *defaultState() const;
void setDefaultState(QAbstractState *state);
@@ -65,6 +70,7 @@ public:
void setHistoryType(HistoryType type);
Q_SIGNALS:
+ void defaultTransitionChanged(QPrivateSignal);
void defaultStateChanged(QPrivateSignal);
void historyTypeChanged(QPrivateSignal);
diff --git a/src/corelib/statemachine/qhistorystate_p.h b/src/corelib/statemachine/qhistorystate_p.h
index b5c353fdff..b0865f7f46 100644
--- a/src/corelib/statemachine/qhistorystate_p.h
+++ b/src/corelib/statemachine/qhistorystate_p.h
@@ -47,11 +47,12 @@
#include "private/qabstractstate_p.h"
+#include <QtCore/qabstracttransition.h>
+#include <QtCore/qhistorystate.h>
#include <QtCore/qlist.h>
QT_BEGIN_NAMESPACE
-class QHistoryState;
class QHistoryStatePrivate : public QAbstractStatePrivate
{
Q_DECLARE_PUBLIC(QHistoryState)
@@ -59,13 +60,31 @@ class QHistoryStatePrivate : public QAbstractStatePrivate
public:
QHistoryStatePrivate();
- static QHistoryStatePrivate *get(QHistoryState *q);
+ static QHistoryStatePrivate *get(QHistoryState *q)
+ { return q->d_func(); }
- QAbstractState *defaultState;
+ QAbstractTransition *defaultTransition;
QHistoryState::HistoryType historyType;
QList<QAbstractState*> configuration;
};
+class DefaultStateTransition: public QAbstractTransition
+{
+ Q_OBJECT
+
+public:
+ DefaultStateTransition(QHistoryState *source, QAbstractState *target);
+
+protected:
+ // It doesn't matter whether this transition matches any event or not. It is always associated
+ // with a QHistoryState, and as soon as the state-machine detects that it enters a history
+ // state, it will handle this transition as a special case. The history state itself is never
+ // entered either: either the stored configuration will be used, or the target(s) of this
+ // transition are used.
+ virtual bool eventTest(QEvent *event) { Q_UNUSED(event); return false; }
+ virtual void onTransition(QEvent *event) { Q_UNUSED(event); }
+};
+
QT_END_NAMESPACE
#endif
diff --git a/src/corelib/statemachine/qsignaltransition.cpp b/src/corelib/statemachine/qsignaltransition.cpp
index 41005fca41..7ec72df77c 100644
--- a/src/corelib/statemachine/qsignaltransition.cpp
+++ b/src/corelib/statemachine/qsignaltransition.cpp
@@ -108,11 +108,6 @@ QSignalTransitionPrivate::QSignalTransitionPrivate()
signalIndex = -1;
}
-QSignalTransitionPrivate *QSignalTransitionPrivate::get(QSignalTransition *q)
-{
- return q->d_func();
-}
-
void QSignalTransitionPrivate::unregister()
{
Q_Q(QSignalTransition);
diff --git a/src/corelib/statemachine/qsignaltransition.h b/src/corelib/statemachine/qsignaltransition.h
index bc56f4e9b7..c388323ec4 100644
--- a/src/corelib/statemachine/qsignaltransition.h
+++ b/src/corelib/statemachine/qsignaltransition.h
@@ -49,9 +49,9 @@ class Q_CORE_EXPORT QSignalTransition : public QAbstractTransition
Q_PROPERTY(QByteArray signal READ signal WRITE setSignal NOTIFY signalChanged)
public:
- QSignalTransition(QState *sourceState = 0);
+ QSignalTransition(QState *sourceState = Q_NULLPTR);
QSignalTransition(const QObject *sender, const char *signal,
- QState *sourceState = 0);
+ QState *sourceState = Q_NULLPTR);
~QSignalTransition();
QObject *senderObject() const;
diff --git a/src/corelib/statemachine/qsignaltransition_p.h b/src/corelib/statemachine/qsignaltransition_p.h
index bed0abd9ff..0bf4b1540b 100644
--- a/src/corelib/statemachine/qsignaltransition_p.h
+++ b/src/corelib/statemachine/qsignaltransition_p.h
@@ -56,7 +56,8 @@ class QSignalTransitionPrivate : public QAbstractTransitionPrivate
public:
QSignalTransitionPrivate();
- static QSignalTransitionPrivate *get(QSignalTransition *q);
+ static QSignalTransitionPrivate *get(QSignalTransition *q)
+ { return q->d_func(); }
void unregister();
void maybeRegister();
diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp
index 6e9fb63554..3b84230cb2 100644
--- a/src/corelib/statemachine/qstate.cpp
+++ b/src/corelib/statemachine/qstate.cpp
@@ -320,7 +320,7 @@ void QState::addTransition(QAbstractTransition *transition)
}
transition->setParent(this);
- const QList<QPointer<QAbstractState> > &targets = QAbstractTransitionPrivate::get(transition)->targetStates;
+ const QVector<QPointer<QAbstractState> > &targets = QAbstractTransitionPrivate::get(transition)->targetStates;
for (int i = 0; i < targets.size(); ++i) {
QAbstractState *t = targets.at(i).data();
if (!t) {
@@ -518,6 +518,14 @@ QState::ChildMode QState::childMode() const
void QState::setChildMode(ChildMode mode)
{
Q_D(QState);
+
+ if (mode == QState::ParallelStates && d->initialState) {
+ qWarning("QState::setChildMode: setting the child-mode of state %p to "
+ "parallel removes the initial state", this);
+ d->initialState = Q_NULLPTR;
+ emit initialStateChanged(QState::QPrivateSignal());
+ }
+
if (d->childMode != mode) {
d->childMode = mode;
emit childModeChanged(QState::QPrivateSignal());
diff --git a/src/corelib/statemachine/qstate.h b/src/corelib/statemachine/qstate.h
index a74c782027..0300a9ef2d 100644
--- a/src/corelib/statemachine/qstate.h
+++ b/src/corelib/statemachine/qstate.h
@@ -66,8 +66,8 @@ public:
};
Q_ENUM(RestorePolicy)
- QState(QState *parent = 0);
- QState(ChildMode childMode, QState *parent = 0);
+ QState(QState *parent = Q_NULLPTR);
+ QState(ChildMode childMode, QState *parent = Q_NULLPTR);
~QState();
QAbstractState *errorState() const;
diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h
index 2ce0c13522..3b8dae9499 100644
--- a/src/corelib/statemachine/qstate_p.h
+++ b/src/corelib/statemachine/qstate_p.h
@@ -75,6 +75,7 @@ struct QPropertyAssignment
QVariant value;
bool explicitlySet; // false means the property is being restored to its old value
};
+Q_DECLARE_TYPEINFO(QPropertyAssignment, Q_MOVABLE_TYPE);
#endif // QT_NO_PROPERTIES
@@ -108,7 +109,7 @@ public:
mutable QList<QAbstractTransition*> transitionsList;
#ifndef QT_NO_PROPERTIES
- QList<QPropertyAssignment> propertyAssignments;
+ QVector<QPropertyAssignment> propertyAssignments;
#endif
};
diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp
index e5d019dc8b..687f676819 100644
--- a/src/corelib/statemachine/qstatemachine.cpp
+++ b/src/corelib/statemachine/qstatemachine.cpp
@@ -160,6 +160,8 @@ QT_BEGIN_NAMESPACE
\since 5.4
\brief the running state of this state machine
+
+ \sa start(), stop(), started(), stopped(), runningChanged()
*/
#ifndef QT_NO_ANIMATION
@@ -365,9 +367,9 @@ static QList<QAbstractState *> getEffectiveTargetStates(QAbstractTransition *tra
if (!historyConfiguration.isEmpty()) {
// There is a saved history, so apply that.
targets.unite(historyConfiguration.toSet());
- } else if (QAbstractState *defaultState = historyState->defaultState()) {
- // Qt does not support initial transitions, but uses the default state of the history state for this.
- targets.insert(defaultState);
+ } else if (QAbstractTransition *defaultTransition = historyState->defaultTransition()) {
+ // No saved history, take all default transition targets.
+ targets.unite(defaultTransition->targetStates().toSet());
} else {
// Woops, we found a history state without a default state. That's not valid!
QStateMachinePrivate *m = QStateMachinePrivate::get(historyState->machine());
@@ -383,10 +385,6 @@ static QList<QAbstractState *> getEffectiveTargetStates(QAbstractTransition *tra
return targetsList;
}
-template <class T>
-static uint qHash(const QPointer<T> &p)
-{ return qHash(p.data()); }
-
QStateMachinePrivate::QStateMachinePrivate()
{
isMachine = true;
@@ -410,13 +408,6 @@ QStateMachinePrivate::~QStateMachinePrivate()
qDeleteAll(externalEventQueue);
}
-QStateMachinePrivate *QStateMachinePrivate::get(QStateMachine *q)
-{
- if (q)
- return q->d_func();
- return 0;
-}
-
QState *QStateMachinePrivate::rootState() const
{
return const_cast<QStateMachine*>(q_func());
@@ -684,7 +675,7 @@ void QStateMachinePrivate::microstep(QEvent *event, const QList<QAbstractTransit
qDebug() << q_func() << ": computed entry set:" << enteredStates;
#endif
- QHash<QAbstractState*, QList<QPropertyAssignment> > assignmentsForEnteredStates =
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > assignmentsForEnteredStates =
computePropertyAssignments(enteredStates, pendingRestorables);
if (!pendingRestorables.isEmpty()) {
// Add "implicit" assignments for restored properties to the first
@@ -795,7 +786,7 @@ QSet<QAbstractState*> QStateMachinePrivate::computeExitSet_Unordered(QAbstractTr
}
void QStateMachinePrivate::exitStates(QEvent *event, const QList<QAbstractState*> &statesToExit_sorted,
- const QHash<QAbstractState*, QList<QPropertyAssignment> > &assignmentsForEnteredStates)
+ const QHash<QAbstractState*, QVector<QPropertyAssignment> > &assignmentsForEnteredStates)
{
for (int i = 0; i < statesToExit_sorted.size(); ++i) {
QAbstractState *s = statesToExit_sorted.at(i);
@@ -943,7 +934,7 @@ QAbstractState *QStateMachinePrivate::getTransitionDomain(QAbstractTransition *t
void QStateMachinePrivate::enterStates(QEvent *event, const QList<QAbstractState*> &exitedStates_sorted,
const QList<QAbstractState*> &statesToEnter_sorted,
const QSet<QAbstractState*> &statesForDefaultEntry,
- QHash<QAbstractState*, QList<QPropertyAssignment> > &propertyAssignmentsForState
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > &propertyAssignmentsForState
#ifndef QT_NO_ANIMATION
, const QList<QAbstractAnimation *> &selectedAnimations
#endif
@@ -966,7 +957,7 @@ void QStateMachinePrivate::enterStates(QEvent *event, const QList<QAbstractState
// Immediately set the properties that are not animated.
{
- QList<QPropertyAssignment> assignments = propertyAssignmentsForState.value(s);
+ QVector<QPropertyAssignment> assignments = propertyAssignmentsForState.value(s);
for (int i = 0; i < assignments.size(); ++i) {
const QPropertyAssignment &assn = assignments.at(i);
if (globalRestorePolicy == QState::RestoreProperties) {
@@ -989,9 +980,16 @@ void QStateMachinePrivate::enterStates(QEvent *event, const QList<QAbstractState
QAbstractStatePrivate::get(s)->callOnEntry(event);
QAbstractStatePrivate::get(s)->emitEntered();
- if (statesForDefaultEntry.contains(s)) {
- // ### executeContent(s.initial.transition.children())
- }
+
+ // FIXME:
+ // See the "initial transitions" comment in addDescendantStatesToEnter first, then implement:
+// if (statesForDefaultEntry.contains(s)) {
+// // ### executeContent(s.initial.transition.children())
+// }
+ Q_UNUSED(statesForDefaultEntry);
+
+ if (QHistoryState *h = toHistoryState(s))
+ QAbstractTransitionPrivate::get(h->defaultTransition())->callOnTransition(event);
// Emit propertiesAssigned signal if the state has no animated properties.
{
@@ -1052,69 +1050,6 @@ void QStateMachinePrivate::enterStates(QEvent *event, const QList<QAbstractState
// qDebug() << "configuration:" << configuration.toList();
}
-void QStateMachinePrivate::addStatesToEnter(QAbstractState *s, QState *root,
- QSet<QAbstractState*> &statesToEnter,
- QSet<QAbstractState*> &statesForDefaultEntry)
-{
- if (QHistoryState *h = toHistoryState(s)) {
- QList<QAbstractState*> hconf = QHistoryStatePrivate::get(h)->configuration;
- if (!hconf.isEmpty()) {
- for (int k = 0; k < hconf.size(); ++k) {
- QAbstractState *s0 = hconf.at(k);
- addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry);
- }
-#ifdef QSTATEMACHINE_DEBUG
- qDebug() << q_func() << ": restoring"
- << ((QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) ? "deep" : "shallow")
- << "history from" << s << ':' << hconf;
-#endif
- } else {
- QList<QAbstractState*> hlst;
- if (QHistoryStatePrivate::get(h)->defaultState)
- hlst.append(QHistoryStatePrivate::get(h)->defaultState);
-
- if (hlst.isEmpty()) {
- setError(QStateMachine::NoDefaultStateInHistoryStateError, h);
- } else {
- for (int k = 0; k < hlst.size(); ++k) {
- QAbstractState *s0 = hlst.at(k);
- addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry);
- }
-#ifdef QSTATEMACHINE_DEBUG
- qDebug() << q_func() << ": initial history targets for" << s << ':' << hlst;
-#endif
- }
- }
- } else {
- if (s == rootState()) {
- // Error has already been set by exitStates().
- Q_ASSERT(error != QStateMachine::NoError);
- return;
- }
- statesToEnter.insert(s);
- if (isParallel(s)) {
- QState *grp = toStandardState(s);
- QList<QAbstractState*> lst = QStatePrivate::get(grp)->childStates();
- for (int i = 0; i < lst.size(); ++i) {
- QAbstractState *child = lst.at(i);
- addStatesToEnter(child, grp, statesToEnter, statesForDefaultEntry);
- }
- } else if (isCompound(s)) {
- statesForDefaultEntry.insert(s);
- QState *grp = toStandardState(s);
- QAbstractState *initial = grp->initialState();
- if (initial != 0) {
- Q_ASSERT(initial->machine() == q_func());
- addStatesToEnter(initial, grp, statesToEnter, statesForDefaultEntry);
- } else {
- setError(QStateMachine::NoInitialStateError, grp);
- return;
- }
- }
- addAncestorStatesToEnter(s, root, statesToEnter, statesForDefaultEntry);
- }
-}
-
/* The algorithm as described in http://www.w3.org/TR/2014/WD-scxml-20140529/ has a bug. See
* QTBUG-44963 for details. The algorithm here is as described in
* http://www.w3.org/Voice/2013/scxml-irp/SCXML.htm as of Friday March 13, 2015.
@@ -1165,8 +1100,8 @@ void QStateMachinePrivate::addDescendantStatesToEnter(QAbstractState *state,
#endif
} else {
QList<QAbstractState*> defaultHistoryContent;
- if (QHistoryStatePrivate::get(h)->defaultState)
- defaultHistoryContent.append(QHistoryStatePrivate::get(h)->defaultState);
+ if (QAbstractTransition *t = QHistoryStatePrivate::get(h)->defaultTransition)
+ defaultHistoryContent = t->targetStates();
if (defaultHistoryContent.isEmpty()) {
setError(QStateMachine::NoDefaultStateInHistoryStateError, h);
@@ -1192,8 +1127,10 @@ void QStateMachinePrivate::addDescendantStatesToEnter(QAbstractState *state,
if (QAbstractState *initial = toStandardState(state)->initialState()) {
Q_ASSERT(initial->machine() == q_func());
+ // FIXME:
// Qt does not support initial transitions (which is a problem for parallel states).
// The way it simulates this for other states, is by having a single initial state.
+ // See also the FIXME in enterStates.
statesForDefaultEntry.insert(initial);
addDescendantStatesToEnter(initial, statesToEnter, statesForDefaultEntry);
@@ -1413,9 +1350,9 @@ void QStateMachinePrivate::unregisterRestorables(const QList<QAbstractState *> &
}
}
-QList<QPropertyAssignment> QStateMachinePrivate::restorablesToPropertyList(const QHash<RestorableId, QVariant> &restorables) const
+QVector<QPropertyAssignment> QStateMachinePrivate::restorablesToPropertyList(const QHash<RestorableId, QVariant> &restorables) const
{
- QList<QPropertyAssignment> result;
+ QVector<QPropertyAssignment> result;
QHash<RestorableId, QVariant>::const_iterator it;
for (it = restorables.constBegin(); it != restorables.constEnd(); ++it) {
const RestorableId &id = it.key();
@@ -1470,16 +1407,16 @@ QHash<QStateMachinePrivate::RestorableId, QVariant> QStateMachinePrivate::comput
properties that should not be restored because they are assigned by an
entered state).
*/
-QHash<QAbstractState*, QList<QPropertyAssignment> > QStateMachinePrivate::computePropertyAssignments(
+QHash<QAbstractState*, QVector<QPropertyAssignment> > QStateMachinePrivate::computePropertyAssignments(
const QList<QAbstractState*> &statesToEnter_sorted, QHash<RestorableId, QVariant> &pendingRestorables) const
{
- QHash<QAbstractState*, QList<QPropertyAssignment> > assignmentsForState;
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > assignmentsForState;
for (int i = 0; i < statesToEnter_sorted.size(); ++i) {
QState *s = toStandardState(statesToEnter_sorted.at(i));
if (!s)
continue;
- QList<QPropertyAssignment> &assignments = QStatePrivate::get(s)->propertyAssignments;
+ QVector<QPropertyAssignment> &assignments = QStatePrivate::get(s)->propertyAssignments;
for (int j = 0; j < assignments.size(); ++j) {
const QPropertyAssignment &assn = assignments.at(j);
if (assn.objectDeleted()) {
@@ -1556,8 +1493,11 @@ void QStateMachinePrivate::setError(QStateMachine::Error errorCode, QAbstractSta
#ifdef QSTATEMACHINE_DEBUG
qDebug() << q << ": entering error state" << currentErrorState << "from" << currentContext;
#endif
- QState *lca = findLCA(QList<QAbstractState*>() << currentErrorState << currentContext);
- addStatesToEnter(currentErrorState, lca, pendingErrorStates, pendingErrorStatesForDefaultEntry);
+ pendingErrorStates.insert(currentErrorState);
+ addDescendantStatesToEnter(currentErrorState, pendingErrorStates, pendingErrorStatesForDefaultEntry);
+ addAncestorStatesToEnter(currentErrorState, rootState(), pendingErrorStates, pendingErrorStatesForDefaultEntry);
+ foreach (QAbstractState *s, configuration)
+ pendingErrorStates.remove(s);
} else {
qWarning("Unrecoverable error detected in running state machine: %s",
qPrintable(errorString));
@@ -1652,7 +1592,7 @@ QList<QAbstractAnimation *> QStateMachinePrivate::selectAnimations(const QList<Q
}
void QStateMachinePrivate::terminateActiveAnimations(QAbstractState *state,
- const QHash<QAbstractState*, QList<QPropertyAssignment> > &assignmentsForEnteredStates)
+ const QHash<QAbstractState*, QVector<QPropertyAssignment> > &assignmentsForEnteredStates)
{
Q_Q(QStateMachine);
QList<QAbstractAnimation*> animations = animationsForState.take(state);
@@ -1677,9 +1617,9 @@ void QStateMachinePrivate::terminateActiveAnimations(QAbstractState *state,
// If there is no property assignment that sets this property,
// set the property to its target value.
bool found = false;
- QHash<QAbstractState*, QList<QPropertyAssignment> >::const_iterator it;
+ QHash<QAbstractState*, QVector<QPropertyAssignment> >::const_iterator it;
for (it = assignmentsForEnteredStates.constBegin(); it != assignmentsForEnteredStates.constEnd(); ++it) {
- const QList<QPropertyAssignment> &assignments = it.value();
+ const QVector<QPropertyAssignment> &assignments = it.value();
for (int j = 0; j < assignments.size(); ++j) {
if (assignments.at(j).hasTarget(assn.object, assn.propertyName)) {
found = true;
@@ -1697,15 +1637,15 @@ void QStateMachinePrivate::terminateActiveAnimations(QAbstractState *state,
void QStateMachinePrivate::initializeAnimations(QAbstractState *state, const QList<QAbstractAnimation *> &selectedAnimations,
const QList<QAbstractState*> &exitedStates_sorted,
- QHash<QAbstractState*, QList<QPropertyAssignment> > &assignmentsForEnteredStates)
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > &assignmentsForEnteredStates)
{
Q_Q(QStateMachine);
if (!assignmentsForEnteredStates.contains(state))
return;
- QList<QPropertyAssignment> &assignments = assignmentsForEnteredStates[state];
+ QVector<QPropertyAssignment> &assignments = assignmentsForEnteredStates[state];
for (int i = 0; i < selectedAnimations.size(); ++i) {
QAbstractAnimation *anim = selectedAnimations.at(i);
- QList<QPropertyAssignment>::iterator it;
+ QVector<QPropertyAssignment>::iterator it;
for (it = assignments.begin(); it != assignments.end(); ) {
QPair<QList<QAbstractAnimation*>, QList<QAbstractAnimation*> > ret;
const QPropertyAssignment &assn = *it;
@@ -1864,7 +1804,7 @@ void QStateMachinePrivate::_q_start()
QSet<QAbstractState*> statesForDefaultEntry;
QList<QAbstractState*> enteredStates = computeEntrySet(transitions, statesForDefaultEntry, &calculationCache);
QHash<RestorableId, QVariant> pendingRestorables;
- QHash<QAbstractState*, QList<QPropertyAssignment> > assignmentsForEnteredStates =
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > assignmentsForEnteredStates =
computePropertyAssignments(enteredStates, pendingRestorables);
#ifndef QT_NO_ANIMATION
QList<QAbstractAnimation*> selectedAnimations = selectAnimations(transitions);
@@ -2097,23 +2037,6 @@ void QStateMachinePrivate::cancelAllDelayedEvents()
delayedEvents.clear();
}
-void QStateMachinePrivate::emitStateFinished(QState *forState, QFinalState *guiltyState)
-{
- Q_UNUSED(guiltyState);
- Q_ASSERT(guiltyState);
-
-#ifdef QSTATEMACHINE_DEBUG
- Q_Q(QStateMachine);
- qDebug() << q << ": emitting finished signal for" << forState;
-#endif
-
- QStatePrivate::get(forState)->emitFinished();
-}
-
-void QStateMachinePrivate::startupHook()
-{
-}
-
/*
This function is called when the state machine is performing no
microstep because no transition is enabled (i.e. an event is ignored).
@@ -2154,6 +2077,24 @@ void QStateMachinePrivate::endMacrostep(bool didChange)
Q_UNUSED(didChange);
}
+
+void QStateMachinePrivate::emitStateFinished(QState *forState, QFinalState *guiltyState)
+{
+ Q_UNUSED(guiltyState);
+ Q_ASSERT(guiltyState);
+
+#ifdef QSTATEMACHINE_DEBUG
+ Q_Q(QStateMachine);
+ qDebug() << q << ": emitting finished signal for" << forState;
+#endif
+
+ QStatePrivate::get(forState)->emitFinished();
+}
+
+void QStateMachinePrivate::startupHook()
+{
+}
+
namespace _QStateMachine_Internal{
class GoToStateTransition : public QAbstractTransition
@@ -2453,6 +2394,7 @@ void QStateMachinePrivate::handleTransitionSignal(QObject *sender, int signalInd
QMetaMethod method = meta->method(signalIndex);
int argc = method.parameterCount();
QList<QVariant> vargs;
+ vargs.reserve(argc);
for (int i = 0; i < argc; ++i) {
int type = method.parameterType(i);
vargs.append(QVariant(type, argv[i+1]));
@@ -2636,11 +2578,6 @@ void QStateMachine::removeState(QAbstractState *state)
state->setParent(0);
}
-/*!
- Returns whether this state machine is running.
-
- \sa start(), stop()
-*/
bool QStateMachine::isRunning() const
{
Q_D(const QStateMachine);
@@ -2703,11 +2640,6 @@ void QStateMachine::stop()
}
}
-/*!
- Convenience functions to start/stop this state machine.
-
- \sa start(), stop(), started(), finished(), stopped()
-*/
void QStateMachine::setRunning(bool running)
{
if (running)
@@ -3272,7 +3204,7 @@ QStateMachine::WrappedEvent::~WrappedEvent()
\fn QStateMachine::runningChanged(bool running)
\since 5.4
- This signal is emitted when the running property is changed.
+ This signal is emitted when the running property is changed with \a running as argument.
\sa QStateMachine::running
*/
diff --git a/src/corelib/statemachine/qstatemachine.h b/src/corelib/statemachine/qstatemachine.h
index d6c3b7bfa7..5fca034386 100644
--- a/src/corelib/statemachine/qstatemachine.h
+++ b/src/corelib/statemachine/qstatemachine.h
@@ -104,8 +104,8 @@ public:
NoCommonAncestorForTransitionError
};
- explicit QStateMachine(QObject *parent = 0);
- explicit QStateMachine(QState::ChildMode childMode, QObject *parent = 0);
+ explicit QStateMachine(QObject *parent = Q_NULLPTR);
+ explicit QStateMachine(QState::ChildMode childMode, QObject *parent = Q_NULLPTR);
~QStateMachine();
void addState(QAbstractState *state);
diff --git a/src/corelib/statemachine/qstatemachine_p.h b/src/corelib/statemachine/qstatemachine_p.h
index 426f2732df..4419ebc7f3 100644
--- a/src/corelib/statemachine/qstatemachine_p.h
+++ b/src/corelib/statemachine/qstatemachine_p.h
@@ -99,7 +99,8 @@ public:
QStateMachinePrivate();
~QStateMachinePrivate();
- static QStateMachinePrivate *get(QStateMachine *q);
+ static QStateMachinePrivate *get(QStateMachine *q)
+ { return q ? q->d_func() : 0; }
QState *findLCA(const QList<QAbstractState*> &states, bool onlyCompound = false) const;
QState *findLCCA(const QList<QAbstractState*> &states) const;
@@ -133,7 +134,7 @@ public:
virtual void beginMacrostep();
virtual void endMacrostep(bool didChange);
void exitStates(QEvent *event, const QList<QAbstractState *> &statesToExit_sorted,
- const QHash<QAbstractState*, QList<QPropertyAssignment> > &assignmentsForEnteredStates);
+ const QHash<QAbstractState*, QVector<QPropertyAssignment> > &assignmentsForEnteredStates);
QList<QAbstractState*> computeExitSet(const QList<QAbstractTransition*> &enabledTransitions, CalculationCache *cache);
QSet<QAbstractState*> computeExitSet_Unordered(const QList<QAbstractTransition*> &enabledTransitions, CalculationCache *cache);
QSet<QAbstractState*> computeExitSet_Unordered(QAbstractTransition *t, CalculationCache *cache);
@@ -141,7 +142,7 @@ public:
void enterStates(QEvent *event, const QList<QAbstractState*> &exitedStates_sorted,
const QList<QAbstractState*> &statesToEnter_sorted,
const QSet<QAbstractState*> &statesForDefaultEntry,
- QHash<QAbstractState *, QList<QPropertyAssignment> > &propertyAssignmentsForState
+ QHash<QAbstractState *, QVector<QPropertyAssignment> > &propertyAssignmentsForState
#ifndef QT_NO_ANIMATION
, const QList<QAbstractAnimation*> &selectedAnimations
#endif
@@ -154,9 +155,6 @@ public:
void addDescendantStatesToEnter(QAbstractState *state,
QSet<QAbstractState*> &statesToEnter,
QSet<QAbstractState*> &statesForDefaultEntry);
- void addStatesToEnter(QAbstractState *s, QState *root,
- QSet<QAbstractState*> &statesToEnter,
- QSet<QAbstractState*> &statesForDefaultEntry);
void addAncestorStatesToEnter(QAbstractState *s, QAbstractState *ancestor,
QSet<QAbstractState*> &statesToEnter,
QSet<QAbstractState*> &statesForDefaultEntry);
@@ -232,9 +230,9 @@ public:
const QVariant &value);
void unregisterRestorables(const QList<QAbstractState*> &states, QObject *object,
const QByteArray &propertyName);
- QList<QPropertyAssignment> restorablesToPropertyList(const QHash<RestorableId, QVariant> &restorables) const;
+ QVector<QPropertyAssignment> restorablesToPropertyList(const QHash<RestorableId, QVariant> &restorables) const;
QHash<RestorableId, QVariant> computePendingRestorables(const QList<QAbstractState*> &statesToExit_sorted) const;
- QHash<QAbstractState*, QList<QPropertyAssignment> > computePropertyAssignments(
+ QHash<QAbstractState*, QVector<QPropertyAssignment> > computePropertyAssignments(
const QList<QAbstractState*> &statesToEnter_sorted,
QHash<RestorableId, QVariant> &pendingRestorables) const;
#endif
@@ -275,10 +273,10 @@ public:
QList<QAbstractAnimation *> selectAnimations(const QList<QAbstractTransition *> &transitionList) const;
void terminateActiveAnimations(QAbstractState *state,
- const QHash<QAbstractState*, QList<QPropertyAssignment> > &assignmentsForEnteredStates);
+ const QHash<QAbstractState*, QVector<QPropertyAssignment> > &assignmentsForEnteredStates);
void initializeAnimations(QAbstractState *state, const QList<QAbstractAnimation*> &selectedAnimations,
const QList<QAbstractState *> &exitedStates_sorted,
- QHash<QAbstractState *, QList<QPropertyAssignment> > &assignmentsForEnteredStates);
+ QHash<QAbstractState *, QVector<QPropertyAssignment> > &assignmentsForEnteredStates);
#endif // QT_NO_ANIMATION
QSignalEventGenerator *signalEventGenerator;
diff --git a/src/corelib/thread/qexception.cpp b/src/corelib/thread/qexception.cpp
index acc3663936..04a03b8623 100644
--- a/src/corelib/thread/qexception.cpp
+++ b/src/corelib/thread/qexception.cpp
@@ -107,6 +107,16 @@ QT_BEGIN_NAMESPACE
\internal
*/
+QException::~QException()
+#ifdef Q_COMPILER_NOEXCEPT
+ noexcept
+#else
+ throw()
+#endif
+{
+ // must stay empty until ### Qt 6
+}
+
void QException::raise() const
{
QException e = *this;
@@ -118,6 +128,16 @@ QException *QException::clone() const
return new QException(*this);
}
+QUnhandledException::~QUnhandledException()
+#ifdef Q_COMPILER_NOEXCEPT
+ noexcept
+#else
+ throw()
+#endif
+{
+ // must stay empty until ### Qt 6
+}
+
void QUnhandledException::raise() const
{
QUnhandledException e = *this;
diff --git a/src/corelib/thread/qexception.h b/src/corelib/thread/qexception.h
index 55fc441020..b15ae5095a 100644
--- a/src/corelib/thread/qexception.h
+++ b/src/corelib/thread/qexception.h
@@ -53,6 +53,13 @@ QT_BEGIN_NAMESPACE
class Q_CORE_EXPORT QException : public std::exception
{
public:
+ ~QException()
+#ifdef Q_COMPILER_NOEXCEPT
+ noexcept
+#else
+ throw()
+#endif
+ ;
virtual void raise() const;
virtual QException *clone() const;
};
@@ -60,6 +67,13 @@ public:
class Q_CORE_EXPORT QUnhandledException : public QException
{
public:
+ ~QUnhandledException()
+#ifdef Q_COMPILER_NOEXCEPT
+ noexcept
+#else
+ throw()
+#endif
+ ;
void raise() const Q_DECL_OVERRIDE;
QUnhandledException *clone() const Q_DECL_OVERRIDE;
};
@@ -70,7 +84,7 @@ class Base;
class Q_CORE_EXPORT ExceptionHolder
{
public:
- ExceptionHolder(QException *exception = 0);
+ ExceptionHolder(QException *exception = Q_NULLPTR);
ExceptionHolder(const ExceptionHolder &other);
void operator=(const ExceptionHolder &other);
~ExceptionHolder();
diff --git a/src/corelib/thread/qfuture.qdoc b/src/corelib/thread/qfuture.qdoc
index be4cee2bd6..ed0b26e121 100644
--- a/src/corelib/thread/qfuture.qdoc
+++ b/src/corelib/thread/qfuture.qdoc
@@ -352,6 +352,7 @@
/*! \class QFuture::const_iterator
\reentrant
\since 4.4
+ \inmodule QtCore
\brief The QFuture::const_iterator class provides an STL-style const
iterator for QFuture.
diff --git a/src/corelib/thread/qfutureinterface.h b/src/corelib/thread/qfutureinterface.h
index 01eb043a5e..8c1f7e7d82 100644
--- a/src/corelib/thread/qfutureinterface.h
+++ b/src/corelib/thread/qfutureinterface.h
@@ -299,7 +299,7 @@ public:
void reportResult(const void *, int) { }
void reportResults(const QVector<void> &, int) { }
- void reportFinished(const void * = 0) { QFutureInterfaceBase::reportFinished(); }
+ void reportFinished(const void * = Q_NULLPTR) { QFutureInterfaceBase::reportFinished(); }
};
QT_END_NAMESPACE
diff --git a/src/corelib/thread/qfuturewatcher.h b/src/corelib/thread/qfuturewatcher.h
index 63558d4a0f..42a22d9063 100644
--- a/src/corelib/thread/qfuturewatcher.h
+++ b/src/corelib/thread/qfuturewatcher.h
@@ -52,7 +52,7 @@ class Q_CORE_EXPORT QFutureWatcherBase : public QObject
Q_DECLARE_PRIVATE(QFutureWatcherBase)
public:
- explicit QFutureWatcherBase(QObject *parent = 0);
+ explicit QFutureWatcherBase(QObject *parent = Q_NULLPTR);
// de-inline dtor
int progressValue() const;
@@ -179,7 +179,7 @@ template <>
class QFutureWatcher<void> : public QFutureWatcherBase
{
public:
- explicit QFutureWatcher(QObject *_parent = 0)
+ explicit QFutureWatcher(QObject *_parent = Q_NULLPTR)
: QFutureWatcherBase(_parent)
{ }
~QFutureWatcher()
diff --git a/src/corelib/thread/qgenericatomic.h b/src/corelib/thread/qgenericatomic.h
index a9a790c14c..d3e7d51efd 100644
--- a/src/corelib/thread/qgenericatomic.h
+++ b/src/corelib/thread/qgenericatomic.h
@@ -46,13 +46,6 @@ QT_END_NAMESPACE
#pragma qt_sync_stop_processing
#endif
-#ifdef Q_CC_GNU
-// lowercase is fine, we'll undef it below
-#define always_inline __attribute__((always_inline, gnu_inline))
-#else
-#define always_inline
-#endif
-
template<int> struct QAtomicOpsSupport { enum { IsSupported = 0 }; };
template<> struct QAtomicOpsSupport<4> { enum { IsSupported = 1 }; };
@@ -84,19 +77,19 @@ template <typename BaseClass> struct QGenericAtomicOps
{
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T load(const T &_q_value) Q_DECL_NOTHROW
{
return _q_value;
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
void store(T &_q_value, X newValue) Q_DECL_NOTHROW
{
_q_value = newValue;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T loadAcquire(const T &_q_value) Q_DECL_NOTHROW
{
T tmp = *static_cast<const volatile T *>(&_q_value);
@@ -104,7 +97,7 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
void storeRelease(T &_q_value, X newValue) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
@@ -115,13 +108,13 @@ template <typename BaseClass> struct QGenericAtomicOps
{ return BaseClass::isFetchAndAddNative(); }
static inline Q_DECL_CONSTEXPR bool isReferenceCountingWaitFree() Q_DECL_NOTHROW
{ return BaseClass::isFetchAndAddWaitFree(); }
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
bool ref(T &_q_value) Q_DECL_NOTHROW
{
return BaseClass::fetchAndAddRelaxed(_q_value, 1) != T(-1);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
bool deref(T &_q_value) Q_DECL_NOTHROW
{
return BaseClass::fetchAndAddRelaxed(_q_value, -1) != 1;
@@ -138,7 +131,7 @@ template <typename BaseClass> struct QGenericAtomicOps
bool testAndSetRelaxed(T &_q_value, X expectedValue, X newValue, X *currentValue) Q_DECL_NOTHROW;
#endif
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetAcquire(T &_q_value, X expectedValue, X newValue) Q_DECL_NOTHROW
{
bool tmp = BaseClass::testAndSetRelaxed(_q_value, expectedValue, newValue);
@@ -146,21 +139,21 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetRelease(T &_q_value, X expectedValue, X newValue) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::testAndSetRelaxed(_q_value, expectedValue, newValue);
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetOrdered(T &_q_value, X expectedValue, X newValue) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
return BaseClass::testAndSetRelaxed(_q_value, expectedValue, newValue);
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetAcquire(T &_q_value, X expectedValue, X newValue, X *currentValue) Q_DECL_NOTHROW
{
bool tmp = BaseClass::testAndSetRelaxed(_q_value, expectedValue, newValue, currentValue);
@@ -168,14 +161,14 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetRelease(T &_q_value, X expectedValue, X newValue, X *currentValue) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::testAndSetRelaxed(_q_value, expectedValue, newValue, currentValue);
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
bool testAndSetOrdered(T &_q_value, X expectedValue, X newValue, X *currentValue) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
@@ -185,7 +178,7 @@ template <typename BaseClass> struct QGenericAtomicOps
static inline Q_DECL_CONSTEXPR bool isFetchAndStoreNative() Q_DECL_NOTHROW { return false; }
static inline Q_DECL_CONSTEXPR bool isFetchAndStoreWaitFree() Q_DECL_NOTHROW { return false; }
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
T fetchAndStoreRelaxed(T &_q_value, X newValue) Q_DECL_NOTHROW
{
// implement fetchAndStore on top of testAndSet
@@ -196,7 +189,7 @@ template <typename BaseClass> struct QGenericAtomicOps
}
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
T fetchAndStoreAcquire(T &_q_value, X newValue) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndStoreRelaxed(_q_value, newValue);
@@ -204,14 +197,14 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
T fetchAndStoreRelease(T &_q_value, X newValue) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndStoreRelaxed(_q_value, newValue);
}
- template <typename T, typename X> static inline always_inline
+ template <typename T, typename X> static Q_ALWAYS_INLINE
T fetchAndStoreOrdered(T &_q_value, X newValue) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
@@ -220,7 +213,7 @@ template <typename BaseClass> struct QGenericAtomicOps
static inline Q_DECL_CONSTEXPR bool isFetchAndAddNative() Q_DECL_NOTHROW { return false; }
static inline Q_DECL_CONSTEXPR bool isFetchAndAddWaitFree() Q_DECL_NOTHROW { return false; }
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAddRelaxed(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT valueToAdd) Q_DECL_NOTHROW
{
// implement fetchAndAdd on top of testAndSet
@@ -231,7 +224,7 @@ template <typename BaseClass> struct QGenericAtomicOps
}
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAddAcquire(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT valueToAdd) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndAddRelaxed(_q_value, valueToAdd);
@@ -239,28 +232,28 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAddRelease(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT valueToAdd) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndAddRelaxed(_q_value, valueToAdd);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAddOrdered(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT valueToAdd) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
return BaseClass::fetchAndAddRelaxed(_q_value, valueToAdd);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndSubRelaxed(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT operand) Q_DECL_NOTHROW
{
// implement fetchAndSub on top of fetchAndAdd
return fetchAndAddRelaxed(_q_value, -operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndSubAcquire(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT operand) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndSubRelaxed(_q_value, operand);
@@ -268,21 +261,21 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndSubRelease(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT operand) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndSubRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndSubOrdered(T &_q_value, typename QAtomicAdditiveType<T>::AdditiveT operand) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
return BaseClass::fetchAndSubRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAndRelaxed(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
// implement fetchAndAnd on top of testAndSet
@@ -293,7 +286,7 @@ template <typename BaseClass> struct QGenericAtomicOps
}
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAndAcquire(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndAndRelaxed(_q_value, operand);
@@ -301,21 +294,21 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAndRelease(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndAndRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndAndOrdered(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
return BaseClass::fetchAndAndRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndOrRelaxed(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
// implement fetchAndOr on top of testAndSet
@@ -326,7 +319,7 @@ template <typename BaseClass> struct QGenericAtomicOps
}
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndOrAcquire(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndOrRelaxed(_q_value, operand);
@@ -334,21 +327,21 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndOrRelease(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndOrRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndOrOrdered(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
return BaseClass::fetchAndOrRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndXorRelaxed(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
// implement fetchAndXor on top of testAndSet
@@ -359,7 +352,7 @@ template <typename BaseClass> struct QGenericAtomicOps
}
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndXorAcquire(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
T tmp = BaseClass::fetchAndXorRelaxed(_q_value, operand);
@@ -367,14 +360,14 @@ template <typename BaseClass> struct QGenericAtomicOps
return tmp;
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndXorRelease(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::releaseMemoryFence(_q_value);
return BaseClass::fetchAndXorRelaxed(_q_value, operand);
}
- template <typename T> static inline always_inline
+ template <typename T> static Q_ALWAYS_INLINE
T fetchAndXorOrdered(T &_q_value, typename QtPrivate::QEnableIf<QTypeInfo<T>::isIntegral, T>::Type operand) Q_DECL_NOTHROW
{
BaseClass::orderedMemoryFence(_q_value);
@@ -382,7 +375,5 @@ template <typename BaseClass> struct QGenericAtomicOps
}
};
-#undef always_inline
-
QT_END_NAMESPACE
#endif // QGENERICATOMIC_H
diff --git a/src/corelib/thread/qmutex.h b/src/corelib/thread/qmutex.h
index 63c488747f..0c5a73b4df 100644
--- a/src/corelib/thread/qmutex.h
+++ b/src/corelib/thread/qmutex.h
@@ -73,16 +73,16 @@ public:
private:
inline bool fastTryLock() Q_DECL_NOTHROW {
- return d_ptr.testAndSetAcquire(0, dummyLocked());
+ return d_ptr.testAndSetAcquire(Q_NULLPTR, dummyLocked());
}
inline bool fastTryUnlock() Q_DECL_NOTHROW {
- return d_ptr.testAndSetRelease(dummyLocked(), 0);
+ return d_ptr.testAndSetRelease(dummyLocked(), Q_NULLPTR);
}
inline bool fastTryLock(QMutexData *&current) Q_DECL_NOTHROW {
- return d_ptr.testAndSetAcquire(0, dummyLocked(), current);
+ return d_ptr.testAndSetAcquire(Q_NULLPTR, dummyLocked(), current);
}
inline bool fastTryUnlock(QMutexData *&current) Q_DECL_NOTHROW {
- return d_ptr.testAndSetRelease(dummyLocked(), 0, current);
+ return d_ptr.testAndSetRelease(dummyLocked(), Q_NULLPTR, current);
}
void lockInternal() QT_MUTEX_LOCK_NOEXCEPT;
diff --git a/src/corelib/thread/qmutex_win.cpp b/src/corelib/thread/qmutex_win.cpp
index c4130fdba5..c24ea58868 100644
--- a/src/corelib/thread/qmutex_win.cpp
+++ b/src/corelib/thread/qmutex_win.cpp
@@ -55,10 +55,10 @@ QMutexPrivate::~QMutexPrivate()
bool QMutexPrivate::wait(int timeout)
{
-#ifndef Q_OS_WINRT
- return (WaitForSingleObject(event, timeout < 0 ? INFINITE : timeout) == WAIT_OBJECT_0);
-#else
+#ifndef Q_OS_WINCE
return (WaitForSingleObjectEx(event, timeout < 0 ? INFINITE : timeout, FALSE) == WAIT_OBJECT_0);
+#else
+ return (WaitForSingleObject(event, timeout < 0 ? INFINITE : timeout) == WAIT_OBJECT_0);
#endif
}
diff --git a/src/corelib/thread/qresultstore.h b/src/corelib/thread/qresultstore.h
index fbcb8ad3cd..7ecaa231b2 100644
--- a/src/corelib/thread/qresultstore.h
+++ b/src/corelib/thread/qresultstore.h
@@ -61,8 +61,8 @@ class ResultItem
public:
ResultItem(const void *_result, int _count) : m_count(_count), result(_result) { } // contruct with vector of results
ResultItem(const void *_result) : m_count(0), result(_result) { } // construct with result
- ResultItem() : m_count(0), result(0) { }
- bool isValid() const { return result != 0; }
+ ResultItem() : m_count(0), result(Q_NULLPTR) { }
+ bool isValid() const { return result != Q_NULLPTR; }
bool isVector() const { return m_count != 0; }
int count() const { return (m_count == 0) ? 1 : m_count; }
int m_count; // result is either a pointer to a result or to a vector of results,
diff --git a/src/corelib/thread/qrunnable.cpp b/src/corelib/thread/qrunnable.cpp
index 64a2613d27..04aa39a81e 100644
--- a/src/corelib/thread/qrunnable.cpp
+++ b/src/corelib/thread/qrunnable.cpp
@@ -31,6 +31,15 @@
**
****************************************************************************/
+#include "qrunnable.h"
+
+QT_BEGIN_NAMESPACE
+
+QRunnable::~QRunnable()
+{
+ // Must be empty until ### Qt 6
+}
+
/*!
\class QRunnable
\inmodule QtCore
@@ -98,3 +107,5 @@
\sa autoDelete(), QThreadPool
*/
+
+QT_END_NAMESPACE
diff --git a/src/corelib/thread/qrunnable.h b/src/corelib/thread/qrunnable.h
index f00c58d51d..28d14a46c0 100644
--- a/src/corelib/thread/qrunnable.h
+++ b/src/corelib/thread/qrunnable.h
@@ -38,20 +38,21 @@
QT_BEGIN_NAMESPACE
-
-class QRunnable
+class Q_CORE_EXPORT QRunnable
{
int ref;
friend class QThreadPool;
friend class QThreadPoolPrivate;
friend class QThreadPoolThread;
-
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ Q_DISABLE_COPY(QRunnable)
+#endif
public:
virtual void run() = 0;
QRunnable() : ref(0) { }
- virtual ~QRunnable() { }
+ virtual ~QRunnable();
bool autoDelete() const { return ref != -1; }
void setAutoDelete(bool _autoDelete) { ref = _autoDelete ? 0 : -1; }
diff --git a/src/corelib/thread/qthread.cpp b/src/corelib/thread/qthread.cpp
index dc231a00f8..590479d68c 100644
--- a/src/corelib/thread/qthread.cpp
+++ b/src/corelib/thread/qthread.cpp
@@ -38,7 +38,6 @@
#include "qabstracteventdispatcher.h"
#include <qeventloop.h>
-#include <qhash.h>
#include "qthread_p.h"
#include "private/qcoreapplication_p.h"
@@ -51,7 +50,8 @@ QT_BEGIN_NAMESPACE
QThreadData::QThreadData(int initialRefCount)
: _ref(initialRefCount), loopLevel(0), thread(0), threadId(0),
- eventDispatcher(0), quitNow(false), canWait(true), isAdopted(false)
+ eventDispatcher(0),
+ quitNow(false), canWait(true), isAdopted(false), requiresCoreApplication(true)
{
// fprintf(stderr, "QThreadData %p created\n", this);
}
@@ -868,4 +868,28 @@ bool QThread::isInterruptionRequested() const
return d->interruptionRequested;
}
+/*!
+ \class QDaemonThread
+ \since 5.5
+ \brief The QDaemonThread provides a class to manage threads that outlive QCoreApplication
+ \internal
+
+ Note: don't try to deliver events from the started() signal.
+*/
+static void setThreadDoesNotRequireCoreApplication()
+{
+ QThreadData::current()->requiresCoreApplication = false;
+}
+
+QDaemonThread::QDaemonThread(QObject *parent)
+ : QThread(parent)
+{
+ // QThread::started() is emitted from the thread we start
+ connect(this, &QThread::started, setThreadDoesNotRequireCoreApplication);
+}
+
+QDaemonThread::~QDaemonThread()
+{
+}
+
QT_END_NAMESPACE
diff --git a/src/corelib/thread/qthread.h b/src/corelib/thread/qthread.h
index bfc469583d..d333980bf4 100644
--- a/src/corelib/thread/qthread.h
+++ b/src/corelib/thread/qthread.h
@@ -55,7 +55,7 @@ public:
static int idealThreadCount() Q_DECL_NOTHROW;
static void yieldCurrentThread();
- explicit QThread(QObject *parent = 0);
+ explicit QThread(QObject *parent = Q_NULLPTR);
~QThread();
enum Priority {
@@ -116,7 +116,7 @@ protected:
static void setTerminationEnabled(bool enabled = true);
protected:
- QThread(QThreadPrivate &dd, QObject *parent = 0);
+ QThread(QThreadPrivate &dd, QObject *parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QThread)
diff --git a/src/corelib/thread/qthread_p.h b/src/corelib/thread/qthread_p.h
index 1ecd682ad1..ffefe0b1d1 100644
--- a/src/corelib/thread/qthread_p.h
+++ b/src/corelib/thread/qthread_p.h
@@ -135,6 +135,13 @@ private:
#ifndef QT_NO_THREAD
+class Q_CORE_EXPORT QDaemonThread : public QThread
+{
+public:
+ QDaemonThread(QObject *parent = 0);
+ ~QDaemonThread();
+};
+
class QThreadPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QThread)
@@ -224,7 +231,7 @@ public:
QThreadData(int initialRefCount = 1);
~QThreadData();
- static QThreadData *current(bool createIfNecessary = true);
+ static Q_AUTOTEST_EXPORT QThreadData *current(bool createIfNecessary = true);
static void clearCurrentThreadData();
static QThreadData *get2(QThread *thread)
{ Q_ASSERT_X(thread != 0, "QThread", "internal error"); return thread->d_func()->data; }
@@ -278,6 +285,7 @@ public:
bool quitNow;
bool canWait;
bool isAdopted;
+ bool requiresCoreApplication;
};
class QScopedLoopLevelCounter
diff --git a/src/corelib/thread/qthread_unix.cpp b/src/corelib/thread/qthread_unix.cpp
index 77093c9cf1..f054a727cf 100644
--- a/src/corelib/thread/qthread_unix.cpp
+++ b/src/corelib/thread/qthread_unix.cpp
@@ -313,14 +313,15 @@ void *QThreadPrivate::start(void *arg)
createEventDispatcher(data);
#if (defined(Q_OS_LINUX) || defined(Q_OS_MAC) || defined(Q_OS_QNX))
- // sets the name of the current thread.
- QString objectName = thr->objectName();
-
- if (Q_LIKELY(objectName.isEmpty()))
- setCurrentThreadName(thr->d_func()->thread_id, thr->metaObject()->className());
- else
- setCurrentThreadName(thr->d_func()->thread_id, objectName.toLocal8Bit());
+ {
+ // sets the name of the current thread.
+ QString objectName = thr->objectName();
+ if (Q_LIKELY(objectName.isEmpty()))
+ setCurrentThreadName(thr->d_func()->thread_id, thr->metaObject()->className());
+ else
+ setCurrentThreadName(thr->d_func()->thread_id, objectName.toLocal8Bit());
+ }
#endif
emit thr->started(QThread::QPrivateSignal());
diff --git a/src/corelib/thread/qthread_win.cpp b/src/corelib/thread/qthread_win.cpp
index c16a2e958c..57eeb10b7d 100644
--- a/src/corelib/thread/qthread_win.cpp
+++ b/src/corelib/thread/qthread_win.cpp
@@ -118,7 +118,7 @@ QThreadData *QThreadData::current(bool createIfNecessary)
}
threadData->deref();
threadData->isAdopted = true;
- threadData->threadId = reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
+ threadData->threadId = reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
if (!QCoreApplicationPrivate::theMainThread) {
QCoreApplicationPrivate::theMainThread = threadData->thread;
@@ -340,7 +340,7 @@ unsigned int __stdcall QT_ENSURE_STACK_ALIGNED_FOR_SSE QThreadPrivate::start(voi
qt_create_tls();
TlsSetValue(qt_current_thread_data_tls_index, data);
- data->threadId = reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
+ data->threadId = reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
QThread::setTerminationEnabled(false);
@@ -413,7 +413,7 @@ void QThreadPrivate::finish(void *arg, bool lockAnyway)
Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
- return reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
+ return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
}
int QThread::idealThreadCount() Q_DECL_NOTHROW
diff --git a/src/corelib/thread/qthreadpool.h b/src/corelib/thread/qthreadpool.h
index b1ca808a99..95b41a0417 100644
--- a/src/corelib/thread/qthreadpool.h
+++ b/src/corelib/thread/qthreadpool.h
@@ -55,7 +55,7 @@ class Q_CORE_EXPORT QThreadPool : public QObject
friend class QFutureInterfaceBase;
public:
- QThreadPool(QObject *parent = 0);
+ QThreadPool(QObject *parent = Q_NULLPTR);
~QThreadPool();
static QThreadPool *globalInstance();
diff --git a/src/corelib/thread/qwaitcondition_unix.cpp b/src/corelib/thread/qwaitcondition_unix.cpp
index fd6af7db39..89bf523263 100644
--- a/src/corelib/thread/qwaitcondition_unix.cpp
+++ b/src/corelib/thread/qwaitcondition_unix.cpp
@@ -77,7 +77,7 @@ void qt_initialize_pthread_cond(pthread_cond_t *cond, const char *where)
#if defined(Q_OS_ANDROID)
if (local_condattr_setclock && QElapsedTimer::clockType() == QElapsedTimer::MonotonicClock)
local_condattr_setclock(&condattr, CLOCK_MONOTONIC);
-#elif !defined(Q_OS_MAC) && !defined(Q_OS_HAIKU)
+#elif !defined(Q_OS_MAC)
if (QElapsedTimer::clockType() == QElapsedTimer::MonotonicClock)
pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC);
#endif
diff --git a/src/corelib/thread/qwaitcondition_win.cpp b/src/corelib/thread/qwaitcondition_win.cpp
index ef8330570e..3ea34461d3 100644
--- a/src/corelib/thread/qwaitcondition_win.cpp
+++ b/src/corelib/thread/qwaitcondition_win.cpp
@@ -109,10 +109,10 @@ bool QWaitConditionPrivate::wait(QWaitConditionEvent *wce, unsigned long time)
{
// wait for the event
bool ret = false;
-#ifndef Q_OS_WINRT
- switch (WaitForSingleObject(wce->event, time)) {
-#else
+#ifndef Q_OS_WINCE
switch (WaitForSingleObjectEx(wce->event, time, FALSE)) {
+#else
+ switch (WaitForSingleObject(wce->event, time)) {
#endif
default: break;
diff --git a/src/corelib/tools/qalgorithms.h b/src/corelib/tools/qalgorithms.h
index ff4d5a3ebd..ffa3082d5e 100644
--- a/src/corelib/tools/qalgorithms.h
+++ b/src/corelib/tools/qalgorithms.h
@@ -584,6 +584,131 @@ Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(long unsigne
#undef QALGORITHMS_USE_BUILTIN_POPCOUNT
#endif
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint32 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_ctz(v) : 32U;
+#else
+ // see http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightParallel
+ unsigned int c = 32; // c will be the number of zero bits on the right
+ v &= -signed(v);
+ if (v) c--;
+ if (v & 0x0000FFFF) c -= 16;
+ if (v & 0x00FF00FF) c -= 8;
+ if (v & 0x0F0F0F0F) c -= 4;
+ if (v & 0x33333333) c -= 2;
+ if (v & 0x55555555) c -= 1;
+ return c;
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint8 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_ctz(v) : 8U;
+#else
+ unsigned int c = 8; // c will be the number of zero bits on the right
+ v &= -signed(v);
+ if (v) c--;
+ if (v & 0x0000000F) c -= 4;
+ if (v & 0x00000033) c -= 2;
+ if (v & 0x00000055) c -= 1;
+ return c;
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint16 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_ctz(v) : 16U;
+#else
+ unsigned int c = 16; // c will be the number of zero bits on the right
+ v &= -signed(v);
+ if (v) c--;
+ if (v & 0x000000FF) c -= 8;
+ if (v & 0x00000F0F) c -= 4;
+ if (v & 0x00003333) c -= 2;
+ if (v & 0x00005555) c -= 1;
+ return c;
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint64 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_ctzll(v) : 64;
+#else
+ quint32 x = static_cast<quint32>(v);
+ return x ? qCountTrailingZeroBits(x)
+ : 32 + qCountTrailingZeroBits(static_cast<quint32>(v >> 32));
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(unsigned long v) Q_DECL_NOTHROW
+{
+ return qCountTrailingZeroBits(QIntegerForSizeof<long>::Unsigned(v));
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint32 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_clz(v) : 32U;
+#else
+ // Hacker's Delight, 2nd ed. Fig 5-16, p. 102
+ v = v | (v >> 1);
+ v = v | (v >> 2);
+ v = v | (v >> 4);
+ v = v | (v >> 8);
+ v = v | (v >> 16);
+ return qPopulationCount(~v);
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint8 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_clz(v)-24U : 8U;
+#else
+ v = v | (v >> 1);
+ v = v | (v >> 2);
+ v = v | (v >> 4);
+ return qPopulationCount(static_cast<quint8>(~v));
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint16 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_clz(v)-16U : 16U;
+#else
+ v = v | (v >> 1);
+ v = v | (v >> 2);
+ v = v | (v >> 4);
+ v = v | (v >> 8);
+ return qPopulationCount(static_cast<quint16>(~v));
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint64 v) Q_DECL_NOTHROW
+{
+#if defined(Q_CC_GNU)
+ return v ? __builtin_clzll(v) : 64U;
+#else
+ v = v | (v >> 1);
+ v = v | (v >> 2);
+ v = v | (v >> 4);
+ v = v | (v >> 8);
+ v = v | (v >> 16);
+ v = v | (v >> 32);
+ return qPopulationCount(~v);
+#endif
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(unsigned long v) Q_DECL_NOTHROW
+{
+ return qCountLeadingZeroBits(QIntegerForSizeof<long>::Unsigned(v));
+}
+
QT_WARNING_POP
QT_END_NAMESPACE
diff --git a/src/corelib/tools/qalgorithms.qdoc b/src/corelib/tools/qalgorithms.qdoc
index 193042e017..dac353fa70 100644..100755
--- a/src/corelib/tools/qalgorithms.qdoc
+++ b/src/corelib/tools/qalgorithms.qdoc
@@ -785,3 +785,73 @@
\since 5.2
\overload
*/
+
+/*!
+ \fn uint qCountTrailingZeroBits(quint8 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+
+ Returns the number of consecutive zero bits in \a v, when searching from the LSB.
+ For example, qCountTrailingZeroBits(1) returns 0 and qCountTrailingZeroBits(8) returns 3.
+ */
+
+/*!
+ \fn uint qCountTrailingZeroBits(quint16 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+ \overload
+ */
+
+/*!
+ \fn uint qCountTrailingZeroBits(quint32 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+ \overload
+ */
+
+/*!
+ \fn uint qCountTrailingZeroBits(quint64 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+ \overload
+ */
+
+/*!
+ \fn uint qCountLeadingZeroBits(quint8 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+
+ Returns the number of consecutive zero bits in \a v, when searching from the MSB.
+ For example, qCountLeadingZeroBits(quint8(1)) returns 7 and
+ qCountLeadingZeroBits(quint8(8)) returns 4.
+ */
+
+/*!
+ \fn uint qCountLeadingZeroBits(quint16 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+
+ Returns the number of consecutive zero bits in \a v, when searching from the MSB.
+ For example, qCountLeadingZeroBits(quint16(1)) returns 15 and
+ qCountLeadingZeroBits(quint16(8)) returns 12.
+ */
+
+/*!
+ \fn uint qCountLeadingZeroBits(quint32 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+
+ Returns the number of consecutive zero bits in \a v, when searching from the MSB.
+ For example, qCountLeadingZeroBits(quint32(1)) returns 31 and
+ qCountLeadingZeroBits(quint32(8)) returns 28.
+ */
+
+/*!
+ \fn uint qCountLeadingZeroBits(quint64 v)
+ \relates <QtAlgorithms>
+ \since 5.6
+
+ Returns the number of consecutive zero bits in \a v, when searching from the MSB.
+ For example, qCountLeadingZeroBits(quint64(1)) returns 63 and
+ qCountLeadingZeroBits(quint64(8)) returns 60.
+ */
diff --git a/src/corelib/tools/qarraydata.cpp b/src/corelib/tools/qarraydata.cpp
index ef15fae83a..d9519745b0 100644
--- a/src/corelib/tools/qarraydata.cpp
+++ b/src/corelib/tools/qarraydata.cpp
@@ -103,7 +103,11 @@ QArrayData *QArrayData::allocate(size_t objectSize, size_t alignment,
quintptr data = (quintptr(header) + sizeof(QArrayData) + alignment - 1)
& ~(alignment - 1);
+#if QT_SUPPORTS(UNSHARABLE_CONTAINERS)
header->ref.atomic.store(bool(!(options & Unsharable)));
+#else
+ header->ref.atomic.store(1);
+#endif
header->size = 0;
header->alloc = capacity;
header->capacityReserved = bool(options & CapacityReserved);
diff --git a/src/corelib/tools/qarraydata.h b/src/corelib/tools/qarraydata.h
index df35a1cb62..865bd4325d 100644
--- a/src/corelib/tools/qarraydata.h
+++ b/src/corelib/tools/qarraydata.h
@@ -132,7 +132,7 @@ struct QTypedArrayData
typedef T *pointer;
typedef T &reference;
- inline iterator() : i(0) {}
+ inline iterator() : i(Q_NULLPTR) {}
inline iterator(T *n) : i(n) {}
inline iterator(const iterator &o): i(o.i){} // #### Qt 6: remove, the implicit version is fine
inline T &operator*() const { return *i; }
@@ -166,7 +166,7 @@ struct QTypedArrayData
typedef const T *pointer;
typedef const T &reference;
- inline const_iterator() : i(0) {}
+ inline const_iterator() : i(Q_NULLPTR) {}
inline const_iterator(const T *n) : i(n) {}
inline const_iterator(const const_iterator &o): i(o.i) {} // #### Qt 6: remove, the default version is fine
inline explicit const_iterator(const iterator &o): i(o.i) {}
@@ -249,11 +249,13 @@ struct QTypedArrayData
return allocate(/* capacity */ 0);
}
+#if QT_SUPPORTS(UNSHARABLE_CONTAINERS)
static QTypedArrayData *unsharableEmpty()
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
return allocate(/* capacity */ 0, Unsharable);
}
+#endif
};
template <class T, size_t N>
diff --git a/src/corelib/tools/qarraydatapointer.h b/src/corelib/tools/qarraydatapointer.h
index 103eb073a9..9804d2c2d5 100644
--- a/src/corelib/tools/qarraydatapointer.h
+++ b/src/corelib/tools/qarraydatapointer.h
@@ -46,7 +46,7 @@ private:
typedef QArrayDataOps<T> DataOps;
public:
- QArrayDataPointer()
+ QArrayDataPointer() Q_DECL_NOTHROW
: d(Data::sharedNull())
{
}
@@ -77,15 +77,16 @@ public:
}
#ifdef Q_COMPILER_RVALUE_REFS
- QArrayDataPointer(QArrayDataPointer &&other)
+ QArrayDataPointer(QArrayDataPointer &&other) Q_DECL_NOTHROW
: d(other.d)
{
other.d = Data::sharedNull();
}
- QArrayDataPointer &operator=(QArrayDataPointer &&other)
+ QArrayDataPointer &operator=(QArrayDataPointer &&other) Q_DECL_NOTHROW
{
- this->swap(other);
+ QArrayDataPointer moved(std::move(other));
+ this->swap(moved);
return *this;
}
#endif
@@ -143,7 +144,7 @@ public:
bool isSharable() const { return d->isSharable(); }
#endif
- void swap(QArrayDataPointer &other)
+ void swap(QArrayDataPointer &other) Q_DECL_NOTHROW
{
qSwap(d, other.d);
}
diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp
index 9d6c9d4ed1..5ed72fc341 100644
--- a/src/corelib/tools/qbytearray.cpp
+++ b/src/corelib/tools/qbytearray.cpp
@@ -41,6 +41,7 @@
#include "qlocale_p.h"
#include "qstringalgorithms_p.h"
#include "qscopedpointer.h"
+#include "qbytearray_p.h"
#include <qdatastream.h>
#include <qmath.h>
@@ -123,7 +124,7 @@ int qFindByteArray(
int qAllocMore(int alloc, int extra) Q_DECL_NOTHROW
{
- Q_ASSERT(alloc >= 0 && extra >= 0);
+ Q_ASSERT(alloc >= 0 && extra >= 0 && extra <= MaxAllocSize);
Q_ASSERT_X(alloc <= MaxAllocSize - extra, "qAllocMore", "Requested size is too large!");
unsigned nalloc = qNextPowerOfTwo(alloc + extra);
@@ -488,8 +489,8 @@ quint16 qChecksum(const char *data, uint len)
\overload
- Compresses the first \a nbytes of \a data and returns the
- compressed data in a new byte array.
+ Compresses the first \a nbytes of \a data at compression level
+ \a compressionLevel and returns the compressed data in a new byte array.
*/
#ifndef QT_NO_COMPRESS
@@ -838,15 +839,6 @@ static inline char qToLower(char c)
*/
/*!
- \variable QByteArray::MaxSize
- \internal
- \since 5.4
-
- The maximum size of a QByteArray, in bytes. Also applies to a the maximum
- storage size of QString and QVector, though not the number of elements.
-*/
-
-/*!
\enum QByteArray::Base64Option
\since 5.2
@@ -927,6 +919,52 @@ static inline char qToLower(char c)
\sa constBegin(), end()
*/
+/*! \fn QByteArray::reverse_iterator QByteArray::rbegin()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ character in the byte-array, in reverse order.
+
+ \sa begin(), crbegin(), rend()
+*/
+
+/*! \fn QByteArray::const_reverse_iterator QByteArray::rbegin() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QByteArray::const_reverse_iterator QByteArray::crbegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ character in the byte-array, in reverse order.
+
+ \sa begin(), rbegin(), rend()
+*/
+
+/*! \fn QByteArray::reverse_iterator QByteArray::rend()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
+ the last character in the byte-array, in reverse order.
+
+ \sa end(), crend(), rbegin()
+*/
+
+/*! \fn QByteArray::const_reverse_iterator QByteArray::rend() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QByteArray::const_reverse_iterator QByteArray::crend() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
+ past the last character in the byte-array, in reverse order.
+
+ \sa end(), rend(), rbegin()
+*/
+
/*! \fn void QByteArray::push_back(const QByteArray &other)
This function is provided for STL compatibility. It is equivalent
@@ -1574,7 +1612,7 @@ void QByteArray::reallocData(uint alloc, Data::AllocationOptions options)
d = x;
} else {
if (options & Data::Grow) {
- if (alloc > uint(MaxAllocSize) - uint(sizeof(Data)))
+ if (alloc > MaxByteArraySize)
qBadAlloc();
alloc = qAllocMore(alloc, sizeof(Data));
}
@@ -4489,11 +4527,33 @@ QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteA
*/
/*! \typedef QByteArray::const_iterator
- \internal
+
+ This typedef provides an STL-style const iterator for QByteArray.
+
+ \sa QByteArray::const_reverse_iterator, QByteArray::iterator
*/
/*! \typedef QByteArray::iterator
- \internal
+
+ This typedef provides an STL-style non-const iterator for QByteArray.
+
+ \sa QByteArray::reverse_iterator, QByteArray::const_iterator
+*/
+
+/*! \typedef QByteArray::const_reverse_iterator
+ \since 5.6
+
+ This typedef provides an STL-style const reverse iterator for QByteArray.
+
+ \sa QByteArray::reverse_iterator, QByteArray::const_iterator
+*/
+
+/*! \typedef QByteArray::reverse_iterator
+ \since 5.6
+
+ This typedef provides an STL-style non-const reverse iterator for QByteArray.
+
+ \sa QByteArray::const_reverse_iterator, QByteArray::iterator
*/
/*! \typedef QByteArray::size_type
diff --git a/src/corelib/tools/qbytearray.h b/src/corelib/tools/qbytearray.h
index 6d14cd5131..f0032227e8 100644
--- a/src/corelib/tools/qbytearray.h
+++ b/src/corelib/tools/qbytearray.h
@@ -43,6 +43,7 @@
#include <stdarg.h>
#include <string>
+#include <iterator>
#ifdef truncate
#error qbytearray.h must be included before any header file that defines truncate
@@ -162,9 +163,6 @@ private:
typedef QTypedArrayData<char> Data;
public:
- // undocumented:
- static const quint64 MaxSize = (1 << 30) - sizeof(Data);
-
enum Base64Option {
Base64Encoding = 0,
Base64UrlEncoding = 1,
@@ -338,16 +336,16 @@ public:
inline QT_ASCII_CAST_WARN bool operator>=(const QString &s2) const;
#endif
- short toShort(bool *ok = 0, int base = 10) const;
- ushort toUShort(bool *ok = 0, int base = 10) const;
- int toInt(bool *ok = 0, int base = 10) const;
- uint toUInt(bool *ok = 0, int base = 10) const;
- long toLong(bool *ok = 0, int base = 10) const;
- ulong toULong(bool *ok = 0, int base = 10) const;
- qlonglong toLongLong(bool *ok = 0, int base = 10) const;
- qulonglong toULongLong(bool *ok = 0, int base = 10) const;
- float toFloat(bool *ok = 0) const;
- double toDouble(bool *ok = 0) const;
+ short toShort(bool *ok = Q_NULLPTR, int base = 10) const;
+ ushort toUShort(bool *ok = Q_NULLPTR, int base = 10) const;
+ int toInt(bool *ok = Q_NULLPTR, int base = 10) const;
+ uint toUInt(bool *ok = Q_NULLPTR, int base = 10) const;
+ long toLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ ulong toULong(bool *ok = Q_NULLPTR, int base = 10) const;
+ qlonglong toLongLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ qulonglong toULongLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ float toFloat(bool *ok = Q_NULLPTR) const;
+ double toDouble(bool *ok = Q_NULLPTR) const;
QByteArray toBase64(Base64Options options) const;
QByteArray toBase64() const; // ### Qt6 merge with previous
QByteArray toHex() const;
@@ -393,14 +391,22 @@ public:
typedef const char *const_iterator;
typedef iterator Iterator;
typedef const_iterator ConstIterator;
- iterator begin();
- const_iterator begin() const;
- const_iterator cbegin() const;
- const_iterator constBegin() const;
- iterator end();
- const_iterator end() const;
- const_iterator cend() const;
- const_iterator constEnd() const;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ inline iterator begin();
+ inline const_iterator begin() const;
+ inline const_iterator cbegin() const;
+ inline const_iterator constBegin() const;
+ inline iterator end();
+ inline const_iterator end() const;
+ inline const_iterator cend() const;
+ inline const_iterator constEnd() const;
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
+ const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
// stl compatibility
typedef int size_type;
diff --git a/src/plugins/platforms/kms/main.cpp b/src/corelib/tools/qbytearray_p.h
index 565ac7a7d4..78c667aa90 100644
--- a/src/plugins/platforms/kms/main.cpp
+++ b/src/corelib/tools/qbytearray_p.h
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@@ -31,28 +31,31 @@
**
****************************************************************************/
-#include <qpa/qplatformintegrationplugin.h>
-#include "qkmsintegration.h"
+#ifndef QBYTEARRAY_P_H
+#define QBYTEARRAY_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 other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
-class QKmsIntegrationPlugin : public QPlatformIntegrationPlugin
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "kms.json")
-public:
- QPlatformIntegration *create(const QString&, const QStringList&) Q_DECL_OVERRIDE;
-};
+#include <QtCore/qbytearray.h>
+#include <QtCore/qtypetraits.h>
+#include "qtools_p.h"
-QPlatformIntegration *QKmsIntegrationPlugin::create(const QString& system, const QStringList& paramList)
-{
- Q_UNUSED(paramList);
- if (!system.compare(QLatin1String("kms"), Qt::CaseInsensitive))
- return new QKmsIntegration;
+QT_BEGIN_NAMESPACE
- return 0;
-}
+enum {
+ // Define as enum to force inlining. Don't expose MaxAllocSize in a public header.
+ MaxByteArraySize = MaxAllocSize - sizeof(QtPrivate::remove_pointer<QByteArray::DataPtr>::type)
+};
QT_END_NAMESPACE
-#include "main.moc"
+#endif // QBYTEARRAY_P_H
diff --git a/src/corelib/tools/qbytearraylist.h b/src/corelib/tools/qbytearraylist.h
index f8539ca07a..8b832b7760 100644
--- a/src/corelib/tools/qbytearraylist.h
+++ b/src/corelib/tools/qbytearraylist.h
@@ -61,7 +61,7 @@ protected:
#endif
public:
inline QByteArray join() const
- { return QtPrivate::QByteArrayList_join(self(), 0, 0); }
+ { return QtPrivate::QByteArrayList_join(self(), Q_NULLPTR, 0); }
inline QByteArray join(const QByteArray &sep) const
{ return QtPrivate::QByteArrayList_join(self(), sep.constData(), sep.size()); }
inline QByteArray join(char sep) const
diff --git a/src/corelib/tools/qchar.cpp b/src/corelib/tools/qchar.cpp
index 014d91162a..5469eee14d 100644
--- a/src/corelib/tools/qchar.cpp
+++ b/src/corelib/tools/qchar.cpp
@@ -178,6 +178,7 @@ QT_BEGIN_NAMESPACE
\value Unicode_6_1 Version 6.1
\value Unicode_6_2 Version 6.2
\value Unicode_6_3 Version 6.3 Since Qt 5.3
+ \value Unicode_7_0 Version 7.0 Since Qt 5.5
\value Unicode_Unassigned The value is not assigned to any character
in version 6.3 of Unicode.
@@ -691,7 +692,7 @@ QT_BEGIN_NAMESPACE
Note that this gives no indication of whether the character is
available in a particular font.
*/
-bool QChar::isPrint(uint ucs4)
+bool QChar::isPrint(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -724,7 +725,7 @@ bool QChar::isPrint(uint ucs4)
/*!
\internal
*/
-bool QT_FASTCALL QChar::isSpace_helper(uint ucs4)
+bool QT_FASTCALL QChar::isSpace_helper(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -750,7 +751,7 @@ bool QT_FASTCALL QChar::isSpace_helper(uint ucs4)
Returns \c true if the UCS-4-encoded character specified by \a ucs4 is
a mark (Mark_* categories); otherwise returns \c false.
*/
-bool QChar::isMark(uint ucs4)
+bool QChar::isMark(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -774,7 +775,7 @@ bool QChar::isMark(uint ucs4)
Returns \c true if the UCS-4-encoded character specified by \a ucs4 is
a punctuation mark (Punctuation_* categories); otherwise returns \c false.
*/
-bool QChar::isPunct(uint ucs4)
+bool QChar::isPunct(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -802,7 +803,7 @@ bool QChar::isPunct(uint ucs4)
Returns \c true if the UCS-4-encoded character specified by \a ucs4 is
a symbol (Symbol_* categories); otherwise returns \c false.
*/
-bool QChar::isSymbol(uint ucs4)
+bool QChar::isSymbol(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -832,7 +833,7 @@ bool QChar::isSymbol(uint ucs4)
/*!
\internal
*/
-bool QT_FASTCALL QChar::isLetter_helper(uint ucs4)
+bool QT_FASTCALL QChar::isLetter_helper(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -867,7 +868,7 @@ bool QT_FASTCALL QChar::isLetter_helper(uint ucs4)
/*!
\internal
*/
-bool QT_FASTCALL QChar::isNumber_helper(uint ucs4)
+bool QT_FASTCALL QChar::isNumber_helper(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -896,7 +897,7 @@ bool QT_FASTCALL QChar::isNumber_helper(uint ucs4)
/*!
\internal
*/
-bool QT_FASTCALL QChar::isLetterOrNumber_helper(uint ucs4)
+bool QT_FASTCALL QChar::isLetterOrNumber_helper(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -1059,7 +1060,7 @@ bool QT_FASTCALL QChar::isLetterOrNumber_helper(uint ucs4)
Returns the numeric value of the digit specified by the UCS-4-encoded
character, \a ucs4, or -1 if the character is not a digit.
*/
-int QChar::digitValue(uint ucs4)
+int QChar::digitValue(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return -1;
@@ -1076,7 +1077,7 @@ int QChar::digitValue(uint ucs4)
\overload
Returns the category of the UCS-4-encoded character specified by \a ucs4.
*/
-QChar::Category QChar::category(uint ucs4)
+QChar::Category QChar::category(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::Other_NotAssigned;
@@ -1093,7 +1094,7 @@ QChar::Category QChar::category(uint ucs4)
\overload
Returns the direction of the UCS-4-encoded character specified by \a ucs4.
*/
-QChar::Direction QChar::direction(uint ucs4)
+QChar::Direction QChar::direction(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::DirL;
@@ -1116,7 +1117,7 @@ QChar::Direction QChar::direction(uint ucs4)
character specified by \a ucs4
(needed for certain languages such as Arabic or Syriac).
*/
-QChar::JoiningType QChar::joiningType(uint ucs4)
+QChar::JoiningType QChar::joiningType(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::Joining_None;
@@ -1139,7 +1140,7 @@ QChar::JoiningType QChar::joiningType(uint ucs4)
Returns information about the joining properties of the UCS-4-encoded
character specified by \a ucs4 (needed for certain languages such as Arabic).
*/
-QChar::Joining QChar::joining(uint ucs4)
+QChar::Joining QChar::joining(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::OtherJoining;
@@ -1175,7 +1176,7 @@ QChar::Joining QChar::joining(uint ucs4)
\sa mirroredChar()
*/
-bool QChar::hasMirrored(uint ucs4)
+bool QChar::hasMirrored(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return false;
@@ -1257,7 +1258,7 @@ bool QChar::hasMirrored(uint ucs4)
\sa hasMirrored()
*/
-uint QChar::mirroredChar(uint ucs4)
+uint QChar::mirroredChar(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return ucs4;
@@ -1341,7 +1342,7 @@ QString QChar::decomposition(uint ucs4)
Returns the tag defining the composition of the UCS-4-encoded character
specified by \a ucs4. Returns QChar::NoDecomposition if no decomposition exists.
*/
-QChar::Decomposition QChar::decompositionTag(uint ucs4)
+QChar::Decomposition QChar::decompositionTag(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 >= Hangul_SBase && ucs4 < Hangul_SBase + Hangul_SCount)
return QChar::Canonical;
@@ -1367,7 +1368,7 @@ QChar::Decomposition QChar::decompositionTag(uint ucs4)
Returns the combining class for the UCS-4-encoded character specified by
\a ucs4, as defined in the Unicode standard.
*/
-unsigned char QChar::combiningClass(uint ucs4)
+unsigned char QChar::combiningClass(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return 0;
@@ -1388,7 +1389,7 @@ unsigned char QChar::combiningClass(uint ucs4)
Returns the Unicode script property value for the character specified in
its UCS-4-encoded form as \a ucs4.
*/
-QChar::Script QChar::script(uint ucs4)
+QChar::Script QChar::script(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::Script_Unknown;
@@ -1406,7 +1407,7 @@ QChar::Script QChar::script(uint ucs4)
Returns the Unicode version that introduced the character specified in
its UCS-4-encoded form as \a ucs4.
*/
-QChar::UnicodeVersion QChar::unicodeVersion(uint ucs4)
+QChar::UnicodeVersion QChar::unicodeVersion(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return QChar::Unicode_Unassigned;
@@ -1416,14 +1417,14 @@ QChar::UnicodeVersion QChar::unicodeVersion(uint ucs4)
/*!
Returns the most recent supported Unicode version.
*/
-QChar::UnicodeVersion QChar::currentUnicodeVersion()
+QChar::UnicodeVersion QChar::currentUnicodeVersion() Q_DECL_NOTHROW
{
return UNICODE_DATA_VERSION;
}
template <typename T>
-Q_DECL_CONST_FUNCTION static inline T toLowerCase_helper(T uc)
+Q_DECL_CONST_FUNCTION static inline T toLowerCase_helper(T uc) Q_DECL_NOTHROW
{
const QUnicodeTables::Properties *p = qGetProp(uc);
if (p->lowerCaseSpecial) {
@@ -1434,7 +1435,7 @@ Q_DECL_CONST_FUNCTION static inline T toLowerCase_helper(T uc)
}
template <typename T>
-Q_DECL_CONST_FUNCTION static inline T toUpperCase_helper(T uc)
+Q_DECL_CONST_FUNCTION static inline T toUpperCase_helper(T uc) Q_DECL_NOTHROW
{
const QUnicodeTables::Properties *p = qGetProp(uc);
if (p->upperCaseSpecial) {
@@ -1445,7 +1446,7 @@ Q_DECL_CONST_FUNCTION static inline T toUpperCase_helper(T uc)
}
template <typename T>
-Q_DECL_CONST_FUNCTION static inline T toTitleCase_helper(T uc)
+Q_DECL_CONST_FUNCTION static inline T toTitleCase_helper(T uc) Q_DECL_NOTHROW
{
const QUnicodeTables::Properties *p = qGetProp(uc);
if (p->titleCaseSpecial) {
@@ -1456,7 +1457,7 @@ Q_DECL_CONST_FUNCTION static inline T toTitleCase_helper(T uc)
}
template <typename T>
-Q_DECL_CONST_FUNCTION static inline T toCaseFolded_helper(T uc)
+Q_DECL_CONST_FUNCTION static inline T toCaseFolded_helper(T uc) Q_DECL_NOTHROW
{
const QUnicodeTables::Properties *p = qGetProp(uc);
if (p->caseFoldSpecial) {
@@ -1479,7 +1480,7 @@ Q_DECL_CONST_FUNCTION static inline T toCaseFolded_helper(T uc)
by \a ucs4 if the character is uppercase or titlecase; otherwise returns
the character itself.
*/
-uint QChar::toLower(uint ucs4)
+uint QChar::toLower(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return ucs4;
@@ -1499,7 +1500,7 @@ uint QChar::toLower(uint ucs4)
by \a ucs4 if the character is lowercase or titlecase; otherwise returns
the character itself.
*/
-uint QChar::toUpper(uint ucs4)
+uint QChar::toUpper(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return ucs4;
@@ -1519,7 +1520,7 @@ uint QChar::toUpper(uint ucs4)
by \a ucs4 if the character is lowercase or uppercase; otherwise returns
the character itself.
*/
-uint QChar::toTitleCase(uint ucs4)
+uint QChar::toTitleCase(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return ucs4;
@@ -1534,7 +1535,7 @@ static inline uint foldCase(const ushort *ch, const ushort *start)
return toCaseFolded_helper<uint>(c);
}
-static inline uint foldCase(uint ch, uint &last)
+static inline uint foldCase(uint ch, uint &last) Q_DECL_NOTHROW
{
uint c = ch;
if (QChar(c).isLowSurrogate() && QChar(last).isHighSurrogate())
@@ -1543,7 +1544,7 @@ static inline uint foldCase(uint ch, uint &last)
return toCaseFolded_helper<uint>(c);
}
-static inline ushort foldCase(ushort ch)
+static inline ushort foldCase(ushort ch) Q_DECL_NOTHROW
{
return toCaseFolded_helper<ushort>(ch);
}
@@ -1560,7 +1561,7 @@ static inline ushort foldCase(ushort ch)
Returns the case folded equivalent of the UCS-4-encoded character specified
by \a ucs4. For most Unicode characters this is the same as toLower().
*/
-uint QChar::toCaseFolded(uint ucs4)
+uint QChar::toCaseFolded(uint ucs4) Q_DECL_NOTHROW
{
if (ucs4 > LastValidCodePoint)
return ucs4;
diff --git a/src/corelib/tools/qchar.h b/src/corelib/tools/qchar.h
index 97e2aa7088..fc1fc7bc16 100644
--- a/src/corelib/tools/qchar.h
+++ b/src/corelib/tools/qchar.h
@@ -44,9 +44,9 @@ class QString;
struct QLatin1Char
{
public:
- Q_DECL_CONSTEXPR inline explicit QLatin1Char(char c) : ch(c) {}
- Q_DECL_CONSTEXPR inline char toLatin1() const { return ch; }
- Q_DECL_CONSTEXPR inline ushort unicode() const { return ushort(uchar(ch)); }
+ Q_DECL_CONSTEXPR inline explicit QLatin1Char(char c) Q_DECL_NOTHROW : ch(c) {}
+ Q_DECL_CONSTEXPR inline char toLatin1() const Q_DECL_NOTHROW { return ch; }
+ Q_DECL_CONSTEXPR inline ushort unicode() const Q_DECL_NOTHROW { return ushort(uchar(ch)); }
private:
char ch;
@@ -72,19 +72,19 @@ public:
LastValidCodePoint = 0x10ffff
};
- Q_DECL_CONSTEXPR QChar() : ucs(0) {}
- Q_DECL_CONSTEXPR QChar(ushort rc) : ucs(rc){} // implicit
- Q_DECL_CONSTEXPR QChar(uchar c, uchar r) : ucs(ushort((r << 8) | c)){}
- Q_DECL_CONSTEXPR QChar(short rc) : ucs(ushort(rc)){} // implicit
- Q_DECL_CONSTEXPR QChar(uint rc) : ucs(ushort(rc & 0xffff)){}
- Q_DECL_CONSTEXPR QChar(int rc) : ucs(ushort(rc & 0xffff)){}
- Q_DECL_CONSTEXPR QChar(SpecialCharacter s) : ucs(ushort(s)) {} // implicit
- Q_DECL_CONSTEXPR QChar(QLatin1Char ch) : ucs(ch.unicode()) {} // implicit
+ Q_DECL_CONSTEXPR QChar() Q_DECL_NOTHROW : ucs(0) {}
+ Q_DECL_CONSTEXPR QChar(ushort rc) Q_DECL_NOTHROW : ucs(rc) {} // implicit
+ Q_DECL_CONSTEXPR QChar(uchar c, uchar r) Q_DECL_NOTHROW : ucs(ushort((r << 8) | c)) {}
+ Q_DECL_CONSTEXPR QChar(short rc) Q_DECL_NOTHROW : ucs(ushort(rc)) {} // implicit
+ Q_DECL_CONSTEXPR QChar(uint rc) Q_DECL_NOTHROW : ucs(ushort(rc & 0xffff)) {}
+ Q_DECL_CONSTEXPR QChar(int rc) Q_DECL_NOTHROW : ucs(ushort(rc & 0xffff)) {}
+ Q_DECL_CONSTEXPR QChar(SpecialCharacter s) Q_DECL_NOTHROW : ucs(ushort(s)) {} // implicit
+ Q_DECL_CONSTEXPR QChar(QLatin1Char ch) Q_DECL_NOTHROW : ucs(ch.unicode()) {} // implicit
#ifndef QT_NO_CAST_FROM_ASCII
- QT_ASCII_CAST_WARN Q_DECL_CONSTEXPR explicit QChar(char c) : ucs(uchar(c)) { }
+ QT_ASCII_CAST_WARN Q_DECL_CONSTEXPR explicit QChar(char c) Q_DECL_NOTHROW : ucs(uchar(c)) { }
#ifndef QT_RESTRICTED_CAST_FROM_ASCII
- QT_ASCII_CAST_WARN Q_DECL_CONSTEXPR explicit QChar(uchar c) : ucs(c) { }
+ QT_ASCII_CAST_WARN Q_DECL_CONSTEXPR explicit QChar(uchar c) Q_DECL_NOTHROW : ucs(c) { }
#endif
#endif
// Unicode information
@@ -369,11 +369,11 @@ public:
};
// ****** WHEN ADDING FUNCTIONS, CONSIDER ADDING TO QCharRef TOO
- inline Category category() const { return QChar::category(ucs); }
- inline Direction direction() const { return QChar::direction(ucs); }
- inline JoiningType joiningType() const { return QChar::joiningType(ucs); }
+ inline Category category() const Q_DECL_NOTHROW { return QChar::category(ucs); }
+ inline Direction direction() const Q_DECL_NOTHROW { return QChar::direction(ucs); }
+ inline JoiningType joiningType() const Q_DECL_NOTHROW { return QChar::joiningType(ucs); }
#if QT_DEPRECATED_SINCE(5, 3)
- QT_DEPRECATED inline Joining joining() const
+ QT_DEPRECATED inline Joining joining() const Q_DECL_NOTHROW
{
switch (QChar::joiningType(ucs)) {
case QChar::Joining_Causing: return QChar::Center;
@@ -386,194 +386,177 @@ public:
}
}
#endif
- inline unsigned char combiningClass() const { return QChar::combiningClass(ucs); }
+ inline unsigned char combiningClass() const Q_DECL_NOTHROW { return QChar::combiningClass(ucs); }
- inline QChar mirroredChar() const { return QChar::mirroredChar(ucs); }
- inline bool hasMirrored() const { return QChar::hasMirrored(ucs); }
+ inline QChar mirroredChar() const Q_DECL_NOTHROW { return QChar::mirroredChar(ucs); }
+ inline bool hasMirrored() const Q_DECL_NOTHROW { return QChar::hasMirrored(ucs); }
QString decomposition() const;
- inline Decomposition decompositionTag() const { return QChar::decompositionTag(ucs); }
+ inline Decomposition decompositionTag() const Q_DECL_NOTHROW { return QChar::decompositionTag(ucs); }
- inline int digitValue() const { return QChar::digitValue(ucs); }
- inline QChar toLower() const { return QChar::toLower(ucs); }
- inline QChar toUpper() const { return QChar::toUpper(ucs); }
- inline QChar toTitleCase() const { return QChar::toTitleCase(ucs); }
- inline QChar toCaseFolded() const { return QChar::toCaseFolded(ucs); }
+ inline int digitValue() const Q_DECL_NOTHROW { return QChar::digitValue(ucs); }
+ inline QChar toLower() const Q_DECL_NOTHROW { return QChar::toLower(ucs); }
+ inline QChar toUpper() const Q_DECL_NOTHROW { return QChar::toUpper(ucs); }
+ inline QChar toTitleCase() const Q_DECL_NOTHROW { return QChar::toTitleCase(ucs); }
+ inline QChar toCaseFolded() const Q_DECL_NOTHROW { return QChar::toCaseFolded(ucs); }
- inline Script script() const { return QChar::script(ucs); }
+ inline Script script() const Q_DECL_NOTHROW { return QChar::script(ucs); }
- inline UnicodeVersion unicodeVersion() const { return QChar::unicodeVersion(ucs); }
+ inline UnicodeVersion unicodeVersion() const Q_DECL_NOTHROW { return QChar::unicodeVersion(ucs); }
#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED Q_DECL_CONSTEXPR inline char toAscii() const { return toLatin1(); }
+ QT_DEPRECATED Q_DECL_CONSTEXPR inline char toAscii() const Q_DECL_NOTHROW { return toLatin1(); }
#endif
- Q_DECL_CONSTEXPR inline char toLatin1() const;
- Q_DECL_CONSTEXPR inline ushort unicode() const { return ucs; }
- inline ushort &unicode() { return ucs; }
+ Q_DECL_CONSTEXPR inline char toLatin1() const Q_DECL_NOTHROW { return ucs > 0xff ? '\0' : char(ucs); }
+ Q_DECL_CONSTEXPR inline ushort unicode() const Q_DECL_NOTHROW { return ucs; }
+ Q_DECL_RELAXED_CONSTEXPR inline ushort &unicode() Q_DECL_NOTHROW { return ucs; }
#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static Q_DECL_CONSTEXPR inline QChar fromAscii(char c)
+ QT_DEPRECATED static Q_DECL_CONSTEXPR inline QChar fromAscii(char c) Q_DECL_NOTHROW
{ return fromLatin1(c); }
#endif
- Q_DECL_CONSTEXPR static inline QChar fromLatin1(char c);
-
- Q_DECL_CONSTEXPR inline bool isNull() const { return ucs == 0; }
-
- inline bool isPrint() const { return QChar::isPrint(ucs); }
- Q_DECL_CONSTEXPR inline bool isSpace() const { return QChar::isSpace(ucs); }
- inline bool isMark() const { return QChar::isMark(ucs); }
- inline bool isPunct() const { return QChar::isPunct(ucs); }
- inline bool isSymbol() const { return QChar::isSymbol(ucs); }
- Q_DECL_CONSTEXPR inline bool isLetter() const { return QChar::isLetter(ucs); }
- Q_DECL_CONSTEXPR inline bool isNumber() const { return QChar::isNumber(ucs); }
- Q_DECL_CONSTEXPR inline bool isLetterOrNumber() const { return QChar::isLetterOrNumber(ucs); }
- Q_DECL_CONSTEXPR inline bool isDigit() const { return QChar::isDigit(ucs); }
- Q_DECL_CONSTEXPR inline bool isLower() const { return QChar::isLower(ucs); }
- Q_DECL_CONSTEXPR inline bool isUpper() const { return QChar::isUpper(ucs); }
- Q_DECL_CONSTEXPR inline bool isTitleCase() const { return QChar::isTitleCase(ucs); }
-
- Q_DECL_CONSTEXPR inline bool isNonCharacter() const { return QChar::isNonCharacter(ucs); }
- Q_DECL_CONSTEXPR inline bool isHighSurrogate() const { return QChar::isHighSurrogate(ucs); }
- Q_DECL_CONSTEXPR inline bool isLowSurrogate() const { return QChar::isLowSurrogate(ucs); }
- Q_DECL_CONSTEXPR inline bool isSurrogate() const { return QChar::isSurrogate(ucs); }
-
- Q_DECL_CONSTEXPR inline uchar cell() const { return uchar(ucs & 0xff); }
- Q_DECL_CONSTEXPR inline uchar row() const { return uchar((ucs>>8)&0xff); }
- inline void setCell(uchar cell);
- inline void setRow(uchar row);
-
- static Q_DECL_CONSTEXPR inline bool isNonCharacter(uint ucs4)
+ static Q_DECL_CONSTEXPR inline QChar fromLatin1(char c) Q_DECL_NOTHROW { return QChar(ushort(uchar(c))); }
+
+ Q_DECL_CONSTEXPR inline bool isNull() const Q_DECL_NOTHROW { return ucs == 0; }
+
+ inline bool isPrint() const Q_DECL_NOTHROW { return QChar::isPrint(ucs); }
+ Q_DECL_CONSTEXPR inline bool isSpace() const Q_DECL_NOTHROW { return QChar::isSpace(ucs); }
+ inline bool isMark() const Q_DECL_NOTHROW { return QChar::isMark(ucs); }
+ inline bool isPunct() const Q_DECL_NOTHROW { return QChar::isPunct(ucs); }
+ inline bool isSymbol() const Q_DECL_NOTHROW { return QChar::isSymbol(ucs); }
+ Q_DECL_CONSTEXPR inline bool isLetter() const Q_DECL_NOTHROW { return QChar::isLetter(ucs); }
+ Q_DECL_CONSTEXPR inline bool isNumber() const Q_DECL_NOTHROW { return QChar::isNumber(ucs); }
+ Q_DECL_CONSTEXPR inline bool isLetterOrNumber() const Q_DECL_NOTHROW { return QChar::isLetterOrNumber(ucs); }
+ Q_DECL_CONSTEXPR inline bool isDigit() const Q_DECL_NOTHROW { return QChar::isDigit(ucs); }
+ Q_DECL_CONSTEXPR inline bool isLower() const Q_DECL_NOTHROW { return QChar::isLower(ucs); }
+ Q_DECL_CONSTEXPR inline bool isUpper() const Q_DECL_NOTHROW { return QChar::isUpper(ucs); }
+ Q_DECL_CONSTEXPR inline bool isTitleCase() const Q_DECL_NOTHROW { return QChar::isTitleCase(ucs); }
+
+ Q_DECL_CONSTEXPR inline bool isNonCharacter() const Q_DECL_NOTHROW { return QChar::isNonCharacter(ucs); }
+ Q_DECL_CONSTEXPR inline bool isHighSurrogate() const Q_DECL_NOTHROW { return QChar::isHighSurrogate(ucs); }
+ Q_DECL_CONSTEXPR inline bool isLowSurrogate() const Q_DECL_NOTHROW { return QChar::isLowSurrogate(ucs); }
+ Q_DECL_CONSTEXPR inline bool isSurrogate() const Q_DECL_NOTHROW { return QChar::isSurrogate(ucs); }
+
+ Q_DECL_CONSTEXPR inline uchar cell() const Q_DECL_NOTHROW { return uchar(ucs & 0xff); }
+ Q_DECL_CONSTEXPR inline uchar row() const Q_DECL_NOTHROW { return uchar((ucs>>8)&0xff); }
+ Q_DECL_RELAXED_CONSTEXPR inline void setCell(uchar acell) Q_DECL_NOTHROW { ucs = ushort((ucs & 0xff00) + acell); }
+ Q_DECL_RELAXED_CONSTEXPR inline void setRow(uchar arow) Q_DECL_NOTHROW { ucs = ushort((ushort(arow)<<8) + (ucs&0xff)); }
+
+ static Q_DECL_CONSTEXPR inline bool isNonCharacter(uint ucs4) Q_DECL_NOTHROW
{
return ucs4 >= 0xfdd0 && (ucs4 <= 0xfdef || (ucs4 & 0xfffe) == 0xfffe);
}
- static Q_DECL_CONSTEXPR inline bool isHighSurrogate(uint ucs4)
+ static Q_DECL_CONSTEXPR inline bool isHighSurrogate(uint ucs4) Q_DECL_NOTHROW
{
return ((ucs4 & 0xfffffc00) == 0xd800);
}
- static Q_DECL_CONSTEXPR inline bool isLowSurrogate(uint ucs4)
+ static Q_DECL_CONSTEXPR inline bool isLowSurrogate(uint ucs4) Q_DECL_NOTHROW
{
return ((ucs4 & 0xfffffc00) == 0xdc00);
}
- static Q_DECL_CONSTEXPR inline bool isSurrogate(uint ucs4)
+ static Q_DECL_CONSTEXPR inline bool isSurrogate(uint ucs4) Q_DECL_NOTHROW
{
return (ucs4 - 0xd800u < 2048u);
}
- static Q_DECL_CONSTEXPR inline bool requiresSurrogates(uint ucs4)
+ static Q_DECL_CONSTEXPR inline bool requiresSurrogates(uint ucs4) Q_DECL_NOTHROW
{
return (ucs4 >= 0x10000);
}
- static Q_DECL_CONSTEXPR inline uint surrogateToUcs4(ushort high, ushort low)
+ static Q_DECL_CONSTEXPR inline uint surrogateToUcs4(ushort high, ushort low) Q_DECL_NOTHROW
{
return (uint(high)<<10) + low - 0x35fdc00;
}
- static Q_DECL_CONSTEXPR inline uint surrogateToUcs4(QChar high, QChar low)
+ static Q_DECL_CONSTEXPR inline uint surrogateToUcs4(QChar high, QChar low) Q_DECL_NOTHROW
{
return surrogateToUcs4(high.ucs, low.ucs);
}
- static Q_DECL_CONSTEXPR inline ushort highSurrogate(uint ucs4)
+ static Q_DECL_CONSTEXPR inline ushort highSurrogate(uint ucs4) Q_DECL_NOTHROW
{
return ushort((ucs4>>10) + 0xd7c0);
}
- static Q_DECL_CONSTEXPR inline ushort lowSurrogate(uint ucs4)
+ static Q_DECL_CONSTEXPR inline ushort lowSurrogate(uint ucs4) Q_DECL_NOTHROW
{
return ushort(ucs4%0x400 + 0xdc00);
}
- static Category QT_FASTCALL category(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Direction QT_FASTCALL direction(uint ucs4) Q_DECL_CONST_FUNCTION;
- static JoiningType QT_FASTCALL joiningType(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static Category QT_FASTCALL category(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static Direction QT_FASTCALL direction(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static JoiningType QT_FASTCALL joiningType(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
#if QT_DEPRECATED_SINCE(5, 3)
- QT_DEPRECATED static Joining QT_FASTCALL joining(uint ucs4) Q_DECL_CONST_FUNCTION;
+ QT_DEPRECATED static Joining QT_FASTCALL joining(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
#endif
- static unsigned char QT_FASTCALL combiningClass(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static unsigned char QT_FASTCALL combiningClass(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static uint QT_FASTCALL mirroredChar(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL hasMirrored(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static uint QT_FASTCALL mirroredChar(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL hasMirrored(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
static QString QT_FASTCALL decomposition(uint ucs4);
- static Decomposition QT_FASTCALL decompositionTag(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static Decomposition QT_FASTCALL decompositionTag(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static int QT_FASTCALL digitValue(uint ucs4) Q_DECL_CONST_FUNCTION;
- static uint QT_FASTCALL toLower(uint ucs4) Q_DECL_CONST_FUNCTION;
- static uint QT_FASTCALL toUpper(uint ucs4) Q_DECL_CONST_FUNCTION;
- static uint QT_FASTCALL toTitleCase(uint ucs4) Q_DECL_CONST_FUNCTION;
- static uint QT_FASTCALL toCaseFolded(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static int QT_FASTCALL digitValue(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static uint QT_FASTCALL toLower(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static uint QT_FASTCALL toUpper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static uint QT_FASTCALL toTitleCase(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static uint QT_FASTCALL toCaseFolded(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static Script QT_FASTCALL script(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static Script QT_FASTCALL script(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static UnicodeVersion QT_FASTCALL unicodeVersion(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static UnicodeVersion QT_FASTCALL unicodeVersion(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static UnicodeVersion QT_FASTCALL currentUnicodeVersion() Q_DECL_CONST_FUNCTION;
+ static UnicodeVersion QT_FASTCALL currentUnicodeVersion() Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isPrint(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isSpace(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isMark(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isPunct(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isSymbol(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isLetter(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isNumber(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isLetterOrNumber(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isDigit(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isLower(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isUpper(uint ucs4) Q_DECL_CONST_FUNCTION;
- static Q_DECL_CONSTEXPR inline bool isTitleCase(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isPrint(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static Q_DECL_CONSTEXPR inline bool isSpace(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ {
+ // note that [0x09..0x0d] + 0x85 are exceptional Cc-s and must be handled explicitly
+ return ucs4 == 0x20 || (ucs4 <= 0x0d && ucs4 >= 0x09)
+ || (ucs4 > 127 && (ucs4 == 0x85 || ucs4 == 0xa0 || QChar::isSpace_helper(ucs4)));
+ }
+ static bool QT_FASTCALL isMark(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isPunct(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isSymbol(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static Q_DECL_CONSTEXPR inline bool isLetter(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ {
+ return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
+ || (ucs4 > 127 && QChar::isLetter_helper(ucs4));
+ }
+ static Q_DECL_CONSTEXPR inline bool isNumber(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ { return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::isNumber_helper(ucs4)); }
+ static Q_DECL_CONSTEXPR inline bool isLetterOrNumber(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ {
+ return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
+ || (ucs4 >= '0' && ucs4 <= '9')
+ || (ucs4 > 127 && QChar::isLetterOrNumber_helper(ucs4));
+ }
+ static Q_DECL_CONSTEXPR inline bool isDigit(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ { return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::category(ucs4) == Number_DecimalDigit); }
+ static Q_DECL_CONSTEXPR inline bool isLower(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ { return (ucs4 <= 'z' && ucs4 >= 'a') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Lowercase); }
+ static Q_DECL_CONSTEXPR inline bool isUpper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ { return (ucs4 <= 'Z' && ucs4 >= 'A') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Uppercase); }
+ static Q_DECL_CONSTEXPR inline bool isTitleCase(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION
+ { return ucs4 > 127 && QChar::category(ucs4) == Letter_Titlecase; }
private:
- static bool QT_FASTCALL isSpace_helper(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isLetter_helper(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isNumber_helper(uint ucs4) Q_DECL_CONST_FUNCTION;
- static bool QT_FASTCALL isLetterOrNumber_helper(uint ucs4) Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isSpace_helper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isLetter_helper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isNumber_helper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
+ static bool QT_FASTCALL isLetterOrNumber_helper(uint ucs4) Q_DECL_NOTHROW Q_DECL_CONST_FUNCTION;
#ifdef QT_NO_CAST_FROM_ASCII
- QChar(char c);
- QChar(uchar c);
+ QChar(char c) Q_DECL_NOTHROW;
+ QChar(uchar c) Q_DECL_NOTHROW;
#endif
- friend Q_DECL_CONSTEXPR bool operator==(QChar, QChar);
- friend Q_DECL_CONSTEXPR bool operator< (QChar, QChar);
+ friend Q_DECL_CONSTEXPR bool operator==(QChar, QChar) Q_DECL_NOTHROW;
+ friend Q_DECL_CONSTEXPR bool operator< (QChar, QChar) Q_DECL_NOTHROW;
ushort ucs;
};
Q_DECLARE_TYPEINFO(QChar, Q_MOVABLE_TYPE);
-Q_DECL_CONSTEXPR inline char QChar::toLatin1() const { return ucs > 0xff ? '\0' : char(ucs); }
-Q_DECL_CONSTEXPR inline QChar QChar::fromLatin1(char c) { return QChar(ushort(uchar(c))); }
-
-inline void QChar::setCell(uchar acell)
-{ ucs = ushort((ucs & 0xff00) + acell); }
-inline void QChar::setRow(uchar arow)
-{ ucs = ushort((ushort(arow)<<8) + (ucs&0xff)); }
-
-Q_DECL_CONSTEXPR inline bool QChar::isSpace(uint ucs4)
-{
- // note that [0x09..0x0d] + 0x85 are exceptional Cc-s and must be handled explicitly
- return ucs4 == 0x20 || (ucs4 <= 0x0d && ucs4 >= 0x09)
- || (ucs4 > 127 && (ucs4 == 0x85 || ucs4 == 0xa0 || QChar::isSpace_helper(ucs4)));
-}
-Q_DECL_CONSTEXPR inline bool QChar::isLetter(uint ucs4)
-{
- return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
- || (ucs4 > 127 && QChar::isLetter_helper(ucs4));
-}
-Q_DECL_CONSTEXPR inline bool QChar::isNumber(uint ucs4)
-{ return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::isNumber_helper(ucs4)); }
-Q_DECL_CONSTEXPR inline bool QChar::isLetterOrNumber(uint ucs4)
-{
- return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
- || (ucs4 >= '0' && ucs4 <= '9')
- || (ucs4 > 127 && QChar::isLetterOrNumber_helper(ucs4));
-}
-Q_DECL_CONSTEXPR inline bool QChar::isDigit(uint ucs4)
-{ return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::category(ucs4) == Number_DecimalDigit); }
-Q_DECL_CONSTEXPR inline bool QChar::isLower(uint ucs4)
-{ return (ucs4 <= 'z' && ucs4 >= 'a') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Lowercase); }
-Q_DECL_CONSTEXPR inline bool QChar::isUpper(uint ucs4)
-{ return (ucs4 <= 'Z' && ucs4 >= 'A') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Uppercase); }
-Q_DECL_CONSTEXPR inline bool QChar::isTitleCase(uint ucs4)
-{ return ucs4 > 127 && QChar::category(ucs4) == Letter_Titlecase; }
-
-Q_DECL_CONSTEXPR inline bool operator==(QChar c1, QChar c2) { return c1.ucs == c2.ucs; }
-Q_DECL_CONSTEXPR inline bool operator< (QChar c1, QChar c2) { return c1.ucs < c2.ucs; }
+Q_DECL_CONSTEXPR inline bool operator==(QChar c1, QChar c2) Q_DECL_NOTHROW { return c1.ucs == c2.ucs; }
+Q_DECL_CONSTEXPR inline bool operator< (QChar c1, QChar c2) Q_DECL_NOTHROW { return c1.ucs < c2.ucs; }
Q_DECL_CONSTEXPR inline bool operator!=(QChar c1, QChar c2) { return !operator==(c1, c2); }
Q_DECL_CONSTEXPR inline bool operator>=(QChar c1, QChar c2) { return !operator< (c1, c2); }
diff --git a/src/corelib/tools/qcollator.h b/src/corelib/tools/qcollator.h
index e1fa161257..57133165c4 100644
--- a/src/corelib/tools/qcollator.h
+++ b/src/corelib/tools/qcollator.h
@@ -83,7 +83,7 @@ public:
QCollator &operator=(const QCollator &);
#ifdef Q_COMPILER_RVALUE_REFS
QCollator(QCollator &&other) Q_DECL_NOTHROW
- : d(other.d) { other.d = 0; }
+ : d(other.d) { other.d = Q_NULLPTR; }
QCollator &operator=(QCollator &&other) Q_DECL_NOTHROW
{ swap(other); return *this; }
#endif
diff --git a/src/corelib/tools/qcommandlineoption.cpp b/src/corelib/tools/qcommandlineoption.cpp
index 7f898f68a8..8c0ba8cb2b 100644
--- a/src/corelib/tools/qcommandlineoption.cpp
+++ b/src/corelib/tools/qcommandlineoption.cpp
@@ -41,10 +41,19 @@ QT_BEGIN_NAMESPACE
class QCommandLineOptionPrivate : public QSharedData
{
public:
- inline QCommandLineOptionPrivate()
+ Q_NEVER_INLINE
+ explicit QCommandLineOptionPrivate(const QString &name)
+ : names(removeInvalidNames(QStringList(name))),
+ hidden(false)
{ }
- void setNames(const QStringList &nameList);
+ Q_NEVER_INLINE
+ explicit QCommandLineOptionPrivate(const QStringList &names)
+ : names(removeInvalidNames(names)),
+ hidden(false)
+ { }
+
+ static QStringList removeInvalidNames(QStringList nameList);
//! The list of names used for this option.
QStringList names;
@@ -58,6 +67,9 @@ public:
//! The list of default values used for this option.
QStringList defaultValues;
+
+ //! Show or hide in --help
+ bool hidden;
};
/*!
@@ -98,9 +110,8 @@ public:
\sa setDescription(), setValueName(), setDefaultValues()
*/
QCommandLineOption::QCommandLineOption(const QString &name)
- : d(new QCommandLineOptionPrivate)
+ : d(new QCommandLineOptionPrivate(name))
{
- d->setNames(QStringList(name));
}
/*!
@@ -117,9 +128,8 @@ QCommandLineOption::QCommandLineOption(const QString &name)
\sa setDescription(), setValueName(), setDefaultValues()
*/
QCommandLineOption::QCommandLineOption(const QStringList &names)
- : d(new QCommandLineOptionPrivate)
+ : d(new QCommandLineOptionPrivate(names))
{
- d->setNames(names);
}
/*!
@@ -148,9 +158,8 @@ QCommandLineOption::QCommandLineOption(const QStringList &names)
QCommandLineOption::QCommandLineOption(const QString &name, const QString &description,
const QString &valueName,
const QString &defaultValue)
- : d(new QCommandLineOptionPrivate)
+ : d(new QCommandLineOptionPrivate(name))
{
- d->setNames(QStringList(name));
setValueName(valueName);
setDescription(description);
setDefaultValue(defaultValue);
@@ -185,9 +194,8 @@ QCommandLineOption::QCommandLineOption(const QString &name, const QString &descr
QCommandLineOption::QCommandLineOption(const QStringList &names, const QString &description,
const QString &valueName,
const QString &defaultValue)
- : d(new QCommandLineOptionPrivate)
+ : d(new QCommandLineOptionPrivate(names))
{
- d->setNames(names);
setValueName(valueName);
setDescription(description);
setDefaultValue(defaultValue);
@@ -236,29 +244,47 @@ QStringList QCommandLineOption::names() const
return d->names;
}
-void QCommandLineOptionPrivate::setNames(const QStringList &nameList)
-{
- QStringList newNames;
- newNames.reserve(nameList.size());
- if (nameList.isEmpty())
- qWarning("QCommandLineOption: Options must have at least one name");
- foreach (const QString &name, nameList) {
- if (name.isEmpty()) {
- qWarning("QCommandLineOption: Option names cannot be empty");
- } else {
+namespace {
+ struct IsInvalidName
+ {
+ typedef bool result_type;
+ typedef QString argument_type;
+
+ Q_NEVER_INLINE
+ result_type operator()(const QString &name) const Q_DECL_NOEXCEPT
+ {
+ if (Q_UNLIKELY(name.isEmpty()))
+ return warn("be empty");
+
const QChar c = name.at(0);
- if (c == QLatin1Char('-'))
- qWarning("QCommandLineOption: Option names cannot start with a '-'");
- else if (c == QLatin1Char('/'))
- qWarning("QCommandLineOption: Option names cannot start with a '/'");
- else if (name.contains(QLatin1Char('=')))
- qWarning("QCommandLineOption: Option names cannot contain a '='");
- else
- newNames.append(name);
+ if (Q_UNLIKELY(c == QLatin1Char('-')))
+ return warn("start with a '-'");
+ if (Q_UNLIKELY(c == QLatin1Char('/')))
+ return warn("start with a '/'");
+ if (Q_UNLIKELY(name.contains(QLatin1Char('='))))
+ return warn("contain a '='");
+
+ return false;
}
- }
- // commit
- names.swap(newNames);
+
+ Q_NEVER_INLINE
+ static bool warn(const char *what) Q_DECL_NOEXCEPT
+ {
+ qWarning("QCommandLineOption: Option names cannot %s", what);
+ return true;
+ }
+ };
+} // unnamed namespace
+
+// static
+QStringList QCommandLineOptionPrivate::removeInvalidNames(QStringList nameList)
+{
+ if (Q_UNLIKELY(nameList.isEmpty()))
+ qWarning("QCommandLineOption: Options must have at least one name");
+ else
+ nameList.erase(std::remove_if(nameList.begin(), nameList.end(), IsInvalidName()),
+ nameList.end());
+ return nameList;
}
/*!
@@ -362,4 +388,30 @@ QStringList QCommandLineOption::defaultValues() const
return d->defaultValues;
}
+/*!
+ Sets whether to hide this option in the user-visible help output.
+
+ All options are visible by default. Setting \a hide to true for
+ a particular option makes it internal, i.e. not listed in the help output.
+
+ \since 5.6
+ \sa isHidden
+ */
+void QCommandLineOption::setHidden(bool hide)
+{
+ d->hidden = hide;
+}
+
+/*!
+ Returns true if this option is omitted from the help output,
+ false if the option is listed.
+
+ \since 5.6
+ \sa setHidden()
+ */
+bool QCommandLineOption::isHidden() const
+{
+ return d->hidden;
+}
+
QT_END_NAMESPACE
diff --git a/src/corelib/tools/qcommandlineoption.h b/src/corelib/tools/qcommandlineoption.h
index cf4160ecd2..828522cbc5 100644
--- a/src/corelib/tools/qcommandlineoption.h
+++ b/src/corelib/tools/qcommandlineoption.h
@@ -58,11 +58,10 @@ public:
QCommandLineOption &operator=(const QCommandLineOption &other);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QCommandLineOption &operator=(QCommandLineOption &&other)
- { qSwap(d, other.d); return *this; }
+ QCommandLineOption &operator=(QCommandLineOption &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QCommandLineOption &other)
+ void swap(QCommandLineOption &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
QStringList names() const;
@@ -77,6 +76,9 @@ public:
void setDefaultValues(const QStringList &defaultValues);
QStringList defaultValues() const;
+ void setHidden(bool hidden);
+ bool isHidden() const;
+
private:
QSharedDataPointer<QCommandLineOptionPrivate> d;
};
diff --git a/src/corelib/tools/qcommandlineparser.cpp b/src/corelib/tools/qcommandlineparser.cpp
index 0814921a58..20e0688f45 100644
--- a/src/corelib/tools/qcommandlineparser.cpp
+++ b/src/corelib/tools/qcommandlineparser.cpp
@@ -53,6 +53,7 @@ class QCommandLineParserPrivate
public:
inline QCommandLineParserPrivate()
: singleDashWordOptionMode(QCommandLineParser::ParseAsCompactedShortOptions),
+ optionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsOptions),
builtinVersionOption(false),
builtinHelpOption(false),
needsParsing(true)
@@ -103,6 +104,9 @@ public:
//! The parsing mode for "-abc"
QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode;
+ //! How to parse "arg -option"
+ QCommandLineParser::OptionsAfterPositionalArgumentsMode optionsAfterPositionalArgumentsMode;
+
//! Whether addVersionOption was called
bool builtinVersionOption;
@@ -112,6 +116,7 @@ public:
//! True if parse() needs to be called
bool needsParsing;
};
+Q_DECLARE_TYPEINFO(QCommandLineParserPrivate::PositionalArgumentDefinition, Q_MOVABLE_TYPE);
QStringList QCommandLineParserPrivate::aliases(const QString &optionName) const
{
@@ -299,6 +304,41 @@ void QCommandLineParser::setSingleDashWordOptionMode(QCommandLineParser::SingleD
}
/*!
+ \enum QCommandLineParser::OptionsAfterPositionalArgumentsMode
+
+ This enum describes the way the parser interprets options that
+ occur after positional arguments.
+
+ \value ParseAsOptions \c{application argument --opt -t} is interpreted as setting
+ the options \c{opt} and \c{t}, just like \c{application --opt -t argument} would do.
+ This is the default parsing mode. In order to specify that \c{--opt} and \c{-t}
+ are positional arguments instead, the user can use \c{--}, as in
+ \c{application argument -- --opt -t}.
+
+ \value ParseAsPositionalArguments \c{application argument --opt} is interpreted as
+ having two positional arguments, \c{argument} and \c{--opt}.
+ This mode is useful for executables that aim to launch other executables
+ (e.g. wrappers, debugging tools, etc.) or that support internal commands
+ followed by options for the command. \c{argument} is the name of the command,
+ and all options occurring after it can be collected and parsed by another
+ command line parser, possibly in another executable.
+
+ \sa setOptionsAfterPositionalArgumentsMode()
+
+ \since 5.5
+*/
+
+/*!
+ Sets the parsing mode to \a parsingMode.
+ This must be called before process() or parse().
+ \since 5.5
+*/
+void QCommandLineParser::setOptionsAfterPositionalArgumentsMode(QCommandLineParser::OptionsAfterPositionalArgumentsMode parsingMode)
+{
+ d->optionsAfterPositionalArgumentsMode = parsingMode;
+}
+
+/*!
Adds the option \a option to look for while parsing.
Returns \c true if adding the option was successful; otherwise returns \c false.
@@ -640,7 +680,7 @@ bool QCommandLineParserPrivate::parse(const QStringList &args)
const QLatin1Char dashChar('-');
const QLatin1Char assignChar('=');
- bool doubleDashFound = false;
+ bool forcePositional = false;
errorText.clear();
positionalArgumentList.clear();
optionNames.clear();
@@ -658,7 +698,7 @@ bool QCommandLineParserPrivate::parse(const QStringList &args)
for (; argumentIterator != args.end() ; ++argumentIterator) {
QString argument = *argumentIterator;
- if (doubleDashFound) {
+ if (forcePositional) {
positionalArgumentList.append(argument);
} else if (argument.startsWith(doubleDashString)) {
if (argument.length() > 2) {
@@ -670,7 +710,7 @@ bool QCommandLineParserPrivate::parse(const QStringList &args)
error = true;
}
} else {
- doubleDashFound = true;
+ forcePositional = true;
}
} else if (argument.startsWith(dashChar)) {
if (argument.size() == 1) { // single dash ("stdin")
@@ -722,6 +762,8 @@ bool QCommandLineParserPrivate::parse(const QStringList &args)
}
} else {
positionalArgumentList.append(argument);
+ if (optionsAfterPositionalArgumentsMode == QCommandLineParser::ParseAsPositionalArguments)
+ forcePositional = true;
}
if (argumentIterator == args.end())
break;
@@ -1062,6 +1104,8 @@ QString QCommandLineParserPrivate::helpText() const
++longestOptionNameString;
for (int i = 0; i < commandLineOptionList.count(); ++i) {
const QCommandLineOption &option = commandLineOptionList.at(i);
+ if (option.isHidden())
+ continue;
text += wrapText(optionNameList.at(i), longestOptionNameString, option.description());
}
if (!positionalArgumentDefinitions.isEmpty()) {
diff --git a/src/corelib/tools/qcommandlineparser.h b/src/corelib/tools/qcommandlineparser.h
index 91a799b4d5..8c528ba69e 100644
--- a/src/corelib/tools/qcommandlineparser.h
+++ b/src/corelib/tools/qcommandlineparser.h
@@ -57,6 +57,12 @@ public:
};
void setSingleDashWordOptionMode(SingleDashWordOptionMode parsingMode);
+ enum OptionsAfterPositionalArgumentsMode {
+ ParseAsOptions,
+ ParseAsPositionalArguments
+ };
+ void setOptionsAfterPositionalArgumentsMode(OptionsAfterPositionalArgumentsMode mode);
+
bool addOption(const QCommandLineOption &commandLineOption);
bool addOptions(const QList<QCommandLineOption> &options);
diff --git a/src/corelib/tools/qdatetime.h b/src/corelib/tools/qdatetime.h
index 6651efdc13..c44f7f8fee 100644
--- a/src/corelib/tools/qdatetime.h
+++ b/src/corelib/tools/qdatetime.h
@@ -74,7 +74,7 @@ public:
int dayOfYear() const;
int daysInMonth() const;
int daysInYear() const;
- int weekNumber(int *yearNum = 0) const;
+ int weekNumber(int *yearNum = Q_NULLPTR) const;
#ifndef QT_NO_TEXTDATE
static QString shortMonthName(int month, MonthNameType type = DateFormat);
@@ -222,9 +222,12 @@ public:
QDateTime(const QDateTime &other);
~QDateTime();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDateTime &operator=(QDateTime &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDateTime &operator=(const QDateTime &other);
- inline void swap(QDateTime &other) { qSwap(d, other.d); }
+ void swap(QDateTime &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isNull() const;
bool isValid() const;
diff --git a/src/corelib/tools/qdatetimeparser_p.h b/src/corelib/tools/qdatetimeparser_p.h
index 9457e35ad5..a1cf8f283f 100644
--- a/src/corelib/tools/qdatetimeparser_p.h
+++ b/src/corelib/tools/qdatetimeparser_p.h
@@ -252,6 +252,7 @@ public:
Qt::TimeSpec spec; // spec if used by QDateTimeEdit
Context context;
};
+Q_DECLARE_TYPEINFO(QDateTimeParser::SectionNode, Q_PRIMITIVE_TYPE);
Q_CORE_EXPORT bool operator==(const QDateTimeParser::SectionNode &s1, const QDateTimeParser::SectionNode &s2);
diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp
index 1bd9c5ebb9..22f5c65a40 100644
--- a/src/corelib/tools/qeasingcurve.cpp
+++ b/src/corelib/tools/qeasingcurve.cpp
@@ -340,6 +340,7 @@ struct TCBPoint {
qFuzzyCompare(_b, other._b);
}
};
+Q_DECLARE_TYPEINFO(TCBPoint, Q_PRIMITIVE_TYPE);
typedef QVector<TCBPoint> TCBPoints;
@@ -1219,6 +1220,7 @@ QVector<QPointF> static inline tcbToBezier(const TCBPoints &tcbPoints)
{
const int count = tcbPoints.count();
QVector<QPointF> bezierPoints;
+ bezierPoints.reserve(3 * (count - 1));
for (int i = 1; i < count; i++) {
const qreal t_0 = tcbPoints.at(i - 1)._t;
diff --git a/src/corelib/tools/qeasingcurve.h b/src/corelib/tools/qeasingcurve.h
index 4065de1366..d04d5ef30a 100644
--- a/src/corelib/tools/qeasingcurve.h
+++ b/src/corelib/tools/qeasingcurve.h
@@ -75,7 +75,7 @@ public:
QEasingCurve &operator=(const QEasingCurve &other)
{ if ( this != &other ) { QEasingCurve copy(other); swap(copy); } return *this; }
#ifdef Q_COMPILER_RVALUE_REFS
- QEasingCurve(QEasingCurve &&other) : d_ptr(other.d_ptr) { other.d_ptr = 0; }
+ QEasingCurve(QEasingCurve &&other) : d_ptr(other.d_ptr) { other.d_ptr = Q_NULLPTR; }
QEasingCurve &operator=(QEasingCurve &&other)
{ qSwap(d_ptr, other.d_ptr); return *this; }
#endif
diff --git a/src/corelib/tools/qharfbuzz.cpp b/src/corelib/tools/qharfbuzz.cpp
index afc8b23473..fa279949ea 100644
--- a/src/corelib/tools/qharfbuzz.cpp
+++ b/src/corelib/tools/qharfbuzz.cpp
@@ -65,6 +65,9 @@ HB_UChar16 HB_GetMirroredChar(HB_UChar16 ch)
void (*HB_Library_Resolve(const char *library, int version, const char *symbol))()
{
#ifdef QT_NO_LIBRARY
+ Q_UNUSED(library);
+ Q_UNUSED(version);
+ Q_UNUSED(symbol);
return 0;
#else
return QLibrary::resolve(QLatin1String(library), version, symbol);
diff --git a/src/corelib/tools/qhash.cpp b/src/corelib/tools/qhash.cpp
index a8a461e868..1f3ea36121 100644
--- a/src/corelib/tools/qhash.cpp
+++ b/src/corelib/tools/qhash.cpp
@@ -1536,6 +1536,15 @@ uint qHash(long double key, uint seed) Q_DECL_NOTHROW
\sa begin(), constEnd()
*/
+/*! \fn QHash::key_iterator QHash::keyBegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first key
+ in the hash.
+
+ \sa keyEnd()
+*/
+
/*! \fn QHash::iterator QHash::end()
Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary item
@@ -1566,6 +1575,15 @@ uint qHash(long double key, uint seed) Q_DECL_NOTHROW
\sa cbegin(), end()
*/
+/*! \fn QHash::key_iterator QHash::keyEnd() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
+ item after the last key in the hash.
+
+ \sa keyBegin()
+*/
+
/*! \fn QHash::iterator QHash::erase(iterator pos)
Removes the (key, value) pair associated with the iterator \a pos
@@ -1729,6 +1747,26 @@ uint qHash(long double key, uint seed) Q_DECL_NOTHROW
\internal
*/
+/*! \typedef QHash::key_iterator::difference_type
+ \internal
+*/
+
+/*! \typedef QHash::key_iterator::iterator_category
+ \internal
+*/
+
+/*! \typedef QHash::key_iterator::pointer
+ \internal
+*/
+
+/*! \typedef QHash::key_iterator::reference
+ \internal
+*/
+
+/*! \typedef QHash::key_iterator::value_type
+ \internal
+*/
+
/*! \class QHash::iterator
\inmodule QtCore
\brief The QHash::iterator class provides an STL-style non-const iterator for QHash and QMultiHash.
@@ -1802,7 +1840,7 @@ uint qHash(long double key, uint seed) Q_DECL_NOTHROW
while iterators are active on that container. For more information,
read \l{Implicit sharing iterator problem}.
- \sa QHash::const_iterator, QMutableHashIterator
+ \sa QHash::const_iterator, QHash::key_iterator, QMutableHashIterator
*/
/*! \fn QHash::iterator::iterator()
@@ -2155,6 +2193,114 @@ uint qHash(long double key, uint seed) Q_DECL_NOTHROW
\sa operator+=(), operator-()
*/
+/*! \class QHash::key_iterator
+ \inmodule QtCore
+ \since 5.6
+ \brief The QHash::key_iterator class provides an STL-style const iterator for QHash and QMultiHash keys.
+
+ QHash::key_iterator is essentially the same as QHash::const_iterator
+ with the difference that operator*() and operator->() return a key
+ instead of a value.
+
+ For most uses QHash::iterator and QHash::const_iterator should be used,
+ you can easily access the key by calling QHash::iterator::key():
+
+ \snippet code/src_corelib_tools_qhash.cpp 27
+
+ However, to have interoperability between QHash's keys and STL-style
+ algorithms we need an iterator that dereferences to a key instead
+ of a value. With QHash::key_iterator we can apply an algorithm to a
+ range of keys without having to call QHash::keys(), which is inefficient
+ as it costs one QHash iteration and memory allocation to create a temporary
+ QList.
+
+ \snippet code/src_corelib_tools_qhash.cpp 28
+
+ QHash::key_iterator is const, it's not possible to modify the key.
+
+ The default QHash::key_iterator constructor creates an uninitialized
+ iterator. You must initialize it using a QHash function like
+ QHash::keyBegin() or QHash::keyEnd().
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QHash::const_iterator, QHash::iterator
+*/
+
+/*! \fn const T &QHash::key_iterator::operator*() const
+
+ Returns the current item's key.
+*/
+
+/*! \fn const T *QHash::key_iterator::operator->() const
+
+ Returns a pointer to the current item's key.
+*/
+
+/*! \fn bool QHash::key_iterator::operator==(key_iterator other) const
+
+ Returns \c true if \a other points to the same item as this
+ iterator; otherwise returns \c false.
+
+ \sa operator!=()
+*/
+
+/*! \fn bool QHash::key_iterator::operator!=(key_iterator other) const
+
+ Returns \c true if \a other points to a different item than this
+ iterator; otherwise returns \c false.
+
+ \sa operator==()
+*/
+
+/*!
+ \fn QHash::key_iterator &QHash::key_iterator::operator++()
+
+ The prefix ++ operator (\c{++i}) advances the iterator to the
+ next item in the hash and returns an iterator to the new current
+ item.
+
+ Calling this function on QHash::keyEnd() leads to undefined results.
+
+ \sa operator--()
+*/
+
+/*! \fn QHash::key_iterator QHash::key_iterator::operator++(int)
+
+ \overload
+
+ The postfix ++ operator (\c{i++}) advances the iterator to the
+ next item in the hash and returns an iterator to the previous
+ item.
+*/
+
+/*! \fn QHash::key_iterator &QHash::key_iterator::operator--()
+
+ The prefix -- operator (\c{--i}) makes the preceding item
+ current and returns an iterator pointing to the new current item.
+
+ Calling this function on QHash::keyBegin() leads to undefined
+ results.
+
+ \sa operator++()
+*/
+
+/*! \fn QHash::key_iterator QHash::key_iterator::operator--(int)
+
+ \overload
+
+ The postfix -- operator (\c{i--}) makes the preceding item
+ current and returns an iterator pointing to the previous
+ item.
+*/
+
+/*! \fn const_iterator QHash::key_iterator::base() const
+ Returns the underlying const_iterator this key_iterator is based on.
+*/
+
/*! \fn QDataStream &operator<<(QDataStream &out, const QHash<Key, T>& hash)
\relates QHash
diff --git a/src/corelib/tools/qhash.h b/src/corelib/tools/qhash.h
index a9ece12670..e367cc0068 100644
--- a/src/corelib/tools/qhash.h
+++ b/src/corelib/tools/qhash.h
@@ -38,10 +38,9 @@
#include <QtCore/qchar.h>
#include <QtCore/qiterator.h>
#include <QtCore/qlist.h>
-#include <QtCore/qpair.h>
#include <QtCore/qrefcount.h>
+#include <QtCore/qhashfunctions.h>
-#include <numeric> // for std::accumulate
#ifdef Q_COMPILER_INITIALIZER_LISTS
#include <initializer_list>
#endif
@@ -54,101 +53,6 @@
QT_BEGIN_NAMESPACE
-class QBitArray;
-class QByteArray;
-class QString;
-class QStringRef;
-class QLatin1String;
-
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHashBits(const void *p, size_t size, uint seed = 0) Q_DECL_NOTHROW;
-
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(uchar key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(signed char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(ushort key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(short key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(uint key, uint seed = 0) Q_DECL_NOTHROW { return key ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(int key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(ulong key, uint seed = 0) Q_DECL_NOTHROW
-{
- return (sizeof(ulong) > sizeof(uint))
- ? (uint(((key >> (8 * sizeof(uint) - 1)) ^ key) & (~0U)) ^ seed)
- : (uint(key & (~0U)) ^ seed);
-}
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(long key, uint seed = 0) Q_DECL_NOTHROW { return qHash(ulong(key), seed); }
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(quint64 key, uint seed = 0) Q_DECL_NOTHROW
-{
- return uint(((key >> (8 * sizeof(uint) - 1)) ^ key) & (~0U)) ^ seed;
-}
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(qint64 key, uint seed = 0) Q_DECL_NOTHROW { return qHash(quint64(key), seed); }
-Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(float key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(double key, uint seed = 0) Q_DECL_NOTHROW;
-#ifndef Q_OS_DARWIN
-Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(long double key, uint seed = 0) Q_DECL_NOTHROW;
-#endif
-Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(const QChar key, uint seed = 0) Q_DECL_NOTHROW { return qHash(key.unicode(), seed); }
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QByteArray &key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QString &key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QStringRef &key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QBitArray &key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(QLatin1String key, uint seed = 0) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qt_hash(const QString &key) Q_DECL_NOTHROW;
-Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qt_hash(const QStringRef &key) Q_DECL_NOTHROW;
-
-template <class T> inline uint qHash(const T *key, uint seed = 0) Q_DECL_NOTHROW
-{
- return qHash(reinterpret_cast<quintptr>(key), seed);
-}
-template<typename T> inline uint qHash(const T &t, uint seed)
- Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
-{ return (qHash(t) ^ seed); }
-
-namespace QtPrivate {
-
-struct QHashCombine {
- typedef uint result_type;
- template <typename T>
- Q_DECL_CONSTEXPR result_type operator()(uint seed, const T &t) const Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
- // combiner taken from N3876 / boost::hash_combine
- { return seed ^ (qHash(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2)) ; }
-};
-
-struct QHashCombineCommutative {
- // QHashCombine is a good hash combiner, but is not commutative,
- // ie. it depends on the order of the input elements. That is
- // usually what we want: {0,1,3} should hash differently than
- // {1,3,0}. Except when it isn't (e.g. for QSet and
- // QHash). Therefore, provide a commutative combiner, too.
- typedef uint result_type;
- template <typename T>
- Q_DECL_CONSTEXPR result_type operator()(uint seed, const T &t) const Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
- { return seed + qHash(t); } // don't use xor!
-};
-
-} // namespace QtPrivate
-
-template <typename InputIterator>
-inline uint qHashRange(InputIterator first, InputIterator last, uint seed = 0)
- Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(*first))) // assume iterator operations don't throw
-{
- return std::accumulate(first, last, seed, QtPrivate::QHashCombine());
-}
-
-template <typename InputIterator>
-inline uint qHashRangeCommutative(InputIterator first, InputIterator last, uint seed = 0)
- Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(*first))) // assume iterator operations don't throw
-{
- return std::accumulate(first, last, seed, QtPrivate::QHashCombineCommutative());
-}
-
-template <typename T1, typename T2> inline uint qHash(const QPair<T1, T2> &key, uint seed = 0)
- Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(key.first, seed)) && noexcept(qHash(key.second, seed)))
-{
- uint h1 = qHash(key.first, seed);
- uint h2 = qHash(key.second, seed);
- return ((h1 << 16) | (h1 >> 16)) ^ h2 ^ seed;
-}
-
struct Q_CORE_EXPORT QHashData
{
struct Node {
@@ -345,7 +249,7 @@ public:
#ifdef Q_COMPILER_RVALUE_REFS
QHash(QHash &&other) Q_DECL_NOTHROW : d(other.d) { other.d = const_cast<QHashData *>(&QHashData::shared_null); }
QHash &operator=(QHash &&other) Q_DECL_NOTHROW
- { qSwap(d, other.d); return *this; }
+ { QHash moved(std::move(other)); swap(moved); return *this; }
#endif
void swap(QHash &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
@@ -402,7 +306,7 @@ public:
typedef T *pointer;
typedef T &reference;
- inline iterator() : i(0) { }
+ inline iterator() : i(Q_NULLPTR) { }
explicit inline iterator(void *node) : i(reinterpret_cast<QHashData::Node *>(node)) { }
inline const Key &key() const { return concrete(i)->key; }
@@ -449,6 +353,7 @@ public:
class const_iterator
{
friend class iterator;
+ friend class QSet<Key>;
QHashData::Node *i;
public:
@@ -458,7 +363,7 @@ public:
typedef const T *pointer;
typedef const T &reference;
- inline const_iterator() : i(0) { }
+ inline const_iterator() : i(Q_NULLPTR) { }
explicit inline const_iterator(void *node)
: i(reinterpret_cast<QHashData::Node *>(node)) { }
#ifdef QT_STRICT_ITERATORS
@@ -508,6 +413,31 @@ public:
};
friend class const_iterator;
+ class key_iterator
+ {
+ const_iterator i;
+
+ public:
+ typedef typename const_iterator::iterator_category iterator_category;
+ typedef typename const_iterator::difference_type difference_type;
+ typedef Key value_type;
+ typedef const Key *pointer;
+ typedef const Key &reference;
+
+ explicit key_iterator(const_iterator o) : i(o) { }
+
+ const Key &operator*() const { return i.key(); }
+ const Key *operator->() const { return &i.key(); }
+ bool operator==(key_iterator o) const { return i == o.i; }
+ bool operator!=(key_iterator o) const { return i != o.i; }
+
+ inline key_iterator &operator++() { ++i; return *this; }
+ inline key_iterator operator++(int) { return key_iterator(i++);}
+ inline key_iterator &operator--() { --i; return *this; }
+ inline key_iterator operator--(int) { return key_iterator(i--); }
+ const_iterator base() const { return i; }
+ };
+
// STL style
inline iterator begin() { detach(); return iterator(d->firstNode()); }
inline const_iterator begin() const { return const_iterator(d->firstNode()); }
@@ -517,6 +447,9 @@ public:
inline const_iterator end() const { return const_iterator(e); }
inline const_iterator cend() const { return const_iterator(e); }
inline const_iterator constEnd() const { return const_iterator(e); }
+ inline key_iterator keyBegin() const { return key_iterator(begin()); }
+ inline key_iterator keyEnd() const { return key_iterator(end()); }
+
iterator erase(iterator it);
// more Qt
@@ -546,7 +479,8 @@ public:
private:
void detach_helper();
void freeData(QHashData *d);
- Node **findNode(const Key &key, uint *hp = 0) const;
+ Node **findNode(const Key &key, uint *hp = Q_NULLPTR) const;
+ Node **findNode(const Key &key, uint h) const;
Node *createNode(uint h, const Key &key, const T &value, Node **nextNode);
void deleteNode(Node *node);
static void deleteNode2(QHashData::Node *node);
@@ -590,7 +524,7 @@ template <class Key, class T>
Q_INLINE_TEMPLATE void QHash<Key, T>::duplicateNode(QHashData::Node *node, void *newNode)
{
Node *concreteNode = concrete(node);
- new (newNode) Node(concreteNode->key, concreteNode->value, concreteNode->h, 0);
+ new (newNode) Node(concreteNode->key, concreteNode->value, concreteNode->h, Q_NULLPTR);
}
template <class Key, class T>
@@ -942,17 +876,10 @@ Q_INLINE_TEMPLATE bool QHash<Key, T>::contains(const Key &akey) const
}
template <class Key, class T>
-Q_OUTOFLINE_TEMPLATE typename QHash<Key, T>::Node **QHash<Key, T>::findNode(const Key &akey,
- uint *ahp) const
+Q_OUTOFLINE_TEMPLATE typename QHash<Key, T>::Node **QHash<Key, T>::findNode(const Key &akey, uint h) const
{
Node **node;
- uint h = 0;
- if (d->numBuckets || ahp) {
- h = qHash(akey, d->seed);
- if (ahp)
- *ahp = h;
- }
if (d->numBuckets) {
node = reinterpret_cast<Node **>(&d->buckets[h % d->numBuckets]);
Q_ASSERT(*node == e || (*node)->next);
@@ -965,6 +892,20 @@ Q_OUTOFLINE_TEMPLATE typename QHash<Key, T>::Node **QHash<Key, T>::findNode(cons
}
template <class Key, class T>
+Q_OUTOFLINE_TEMPLATE typename QHash<Key, T>::Node **QHash<Key, T>::findNode(const Key &akey,
+ uint *ahp) const
+{
+ uint h = 0;
+
+ if (d->numBuckets || ahp) {
+ h = qHash(akey, d->seed);
+ if (ahp)
+ *ahp = h;
+ }
+ return findNode(akey, h);
+}
+
+template <class Key, class T>
Q_OUTOFLINE_TEMPLATE bool QHash<Key, T>::operator==(const QHash &other) const
{
if (size() != other.size())
@@ -1003,6 +944,9 @@ public:
insert(it->first, it->second);
}
#endif
+ // compiler-generated copy/move ctors/assignment operators are fine!
+ // compiler-generated destructor is fine!
+
QMultiHash(const QHash<Key, T> &other) : QHash<Key, T>(other) {}
void swap(QMultiHash &other) { QHash<Key, T>::swap(other); } // prevent QMultiHash<->QHash swaps
diff --git a/src/corelib/tools/qhashfunctions.h b/src/corelib/tools/qhashfunctions.h
new file mode 100644
index 0000000000..e15fbb07ac
--- /dev/null
+++ b/src/corelib/tools/qhashfunctions.h
@@ -0,0 +1,156 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QHASHFUNCTIONS_H
+#define QHASHFUNCTIONS_H
+
+#include <QtCore/qchar.h>
+#include <QtCore/qpair.h>
+
+#include <numeric> // for std::accumulate
+
+#if 0
+#pragma qt_class(QHashFunctions)
+#endif
+
+#if defined(Q_CC_MSVC)
+#pragma warning( push )
+#pragma warning( disable : 4311 ) // disable pointer truncation warning
+#pragma warning( disable : 4127 ) // conditional expression is constant
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QBitArray;
+class QByteArray;
+class QString;
+class QStringRef;
+class QLatin1String;
+
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHashBits(const void *p, size_t size, uint seed = 0) Q_DECL_NOTHROW;
+
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(uchar key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(signed char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(ushort key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(short key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(uint key, uint seed = 0) Q_DECL_NOTHROW { return key ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(int key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(ulong key, uint seed = 0) Q_DECL_NOTHROW
+{
+ return (sizeof(ulong) > sizeof(uint))
+ ? (uint(((key >> (8 * sizeof(uint) - 1)) ^ key) & (~0U)) ^ seed)
+ : (uint(key & (~0U)) ^ seed);
+}
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(long key, uint seed = 0) Q_DECL_NOTHROW { return qHash(ulong(key), seed); }
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(quint64 key, uint seed = 0) Q_DECL_NOTHROW
+{
+ return uint(((key >> (8 * sizeof(uint) - 1)) ^ key) & (~0U)) ^ seed;
+}
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(qint64 key, uint seed = 0) Q_DECL_NOTHROW { return qHash(quint64(key), seed); }
+Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(float key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(double key, uint seed = 0) Q_DECL_NOTHROW;
+#ifndef Q_OS_DARWIN
+Q_CORE_EXPORT Q_DECL_CONST_FUNCTION uint qHash(long double key, uint seed = 0) Q_DECL_NOTHROW;
+#endif
+Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qHash(const QChar key, uint seed = 0) Q_DECL_NOTHROW { return qHash(key.unicode(), seed); }
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QByteArray &key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QString &key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QStringRef &key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QBitArray &key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qHash(QLatin1String key, uint seed = 0) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qt_hash(const QString &key) Q_DECL_NOTHROW;
+Q_CORE_EXPORT Q_DECL_PURE_FUNCTION uint qt_hash(const QStringRef &key) Q_DECL_NOTHROW;
+
+template <class T> inline uint qHash(const T *key, uint seed = 0) Q_DECL_NOTHROW
+{
+ return qHash(reinterpret_cast<quintptr>(key), seed);
+}
+template<typename T> inline uint qHash(const T &t, uint seed)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
+{ return qHash(t) ^ seed; }
+
+namespace QtPrivate {
+
+struct QHashCombine {
+ typedef uint result_type;
+ template <typename T>
+ Q_DECL_CONSTEXPR result_type operator()(uint seed, const T &t) const Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
+ // combiner taken from N3876 / boost::hash_combine
+ { return seed ^ (qHash(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2)) ; }
+};
+
+struct QHashCombineCommutative {
+ // QHashCombine is a good hash combiner, but is not commutative,
+ // ie. it depends on the order of the input elements. That is
+ // usually what we want: {0,1,3} should hash differently than
+ // {1,3,0}. Except when it isn't (e.g. for QSet and
+ // QHash). Therefore, provide a commutative combiner, too.
+ typedef uint result_type;
+ template <typename T>
+ Q_DECL_CONSTEXPR result_type operator()(uint seed, const T &t) const Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(t)))
+ { return seed + qHash(t); } // don't use xor!
+};
+
+} // namespace QtPrivate
+
+template <typename InputIterator>
+inline uint qHashRange(InputIterator first, InputIterator last, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(*first))) // assume iterator operations don't throw
+{
+ return std::accumulate(first, last, seed, QtPrivate::QHashCombine());
+}
+
+template <typename InputIterator>
+inline uint qHashRangeCommutative(InputIterator first, InputIterator last, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(*first))) // assume iterator operations don't throw
+{
+ return std::accumulate(first, last, seed, QtPrivate::QHashCombineCommutative());
+}
+
+template <typename T1, typename T2> inline uint qHash(const QPair<T1, T2> &key, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(key.first, seed)) && noexcept(qHash(key.second, seed)))
+{
+ uint h1 = qHash(key.first, seed);
+ uint h2 = qHash(key.second, seed);
+ return ((h1 << 16) | (h1 >> 16)) ^ h2 ^ seed;
+}
+
+QT_END_NAMESPACE
+
+#if defined(Q_CC_MSVC)
+#pragma warning( pop )
+#endif
+
+#endif // QHASHFUNCTIONS_H
diff --git a/src/corelib/tools/qlinkedlist.h b/src/corelib/tools/qlinkedlist.h
index 7908bf5137..f216aa121c 100644
--- a/src/corelib/tools/qlinkedlist.h
+++ b/src/corelib/tools/qlinkedlist.h
@@ -88,7 +88,7 @@ public:
#ifdef Q_COMPILER_RVALUE_REFS
inline QLinkedList(QLinkedList<T> &&other) : d(other.d) { other.d = const_cast<QLinkedListData *>(&QLinkedListData::shared_null); }
inline QLinkedList<T> &operator=(QLinkedList<T> &&other)
- { qSwap(d, other.d); return *this; }
+ { QLinkedList moved(std::move(other)); swap(moved); return *this; }
#endif
inline void swap(QLinkedList<T> &other) { qSwap(d, other.d); }
bool operator==(const QLinkedList<T> &l) const;
diff --git a/src/corelib/tools/qlist.cpp b/src/corelib/tools/qlist.cpp
index db00dcb458..8ed0da7ca0 100644
--- a/src/corelib/tools/qlist.cpp
+++ b/src/corelib/tools/qlist.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
@@ -148,6 +149,17 @@ void QListData::realloc(int alloc)
d->begin = d->end = 0;
}
+void QListData::realloc_grow(int growth)
+{
+ Q_ASSERT(!d->ref.isShared());
+ int alloc = grow(d->alloc + growth);
+ Data *x = static_cast<Data *>(::realloc(d, DataHeaderSize + alloc * sizeof(void *)));
+ Q_CHECK_PTR(x);
+
+ d = x;
+ d->alloc = alloc;
+}
+
void QListData::dispose(Data *d)
{
Q_ASSERT(!d->ref.isShared());
@@ -167,7 +179,7 @@ void **QListData::append(int n)
::memcpy(d->array, d->array + b, e * sizeof(void *));
d->begin = 0;
} else {
- realloc(grow(d->alloc + n));
+ realloc_grow(n);
}
}
d->end = e + n;
@@ -191,7 +203,7 @@ void **QListData::prepend()
Q_ASSERT(!d->ref.isShared());
if (d->begin == 0) {
if (d->end >= d->alloc / 3)
- realloc(grow(d->alloc + 1));
+ realloc_grow(1);
if (d->end < d->alloc / 3)
d->begin = d->alloc - 2 * d->end;
@@ -218,7 +230,7 @@ void **QListData::insert(int i)
if (d->begin == 0) {
if (d->end == d->alloc) {
// If the array is full, we expand it and move some items rightward
- realloc(grow(d->alloc + 1));
+ realloc_grow(1);
} else {
// If there is free space at the end of the array, we move some items rightward
}
@@ -332,41 +344,56 @@ void **QListData::erase(void **xi)
\reentrant
QList\<T\> is one of Qt's generic \l{container classes}. It
- stores a list of values and provides fast index-based access as
- well as fast insertions and removals.
+ stores items in a list that provides fast index-based access
+ and index-based insertions and removals.
QList\<T\>, QLinkedList\<T\>, and QVector\<T\> provide similar
- functionality. Here's an overview:
+ APIs and functionality. They are often interchangeable, but there
+ are performance consequences. Here is an overview of use cases:
\list
- \li For most purposes, QList is the right class to use. Its
- index-based API is more convenient than QLinkedList's
- iterator-based API, and it is usually faster than
- QVector because of the way it stores its items in
- memory. It also expands to less code in your executable.
- \li If you need a real linked list, with guarantees of \l{constant
- time} insertions in the middle of the list and iterators to
- items rather than indexes, use QLinkedList.
- \li If you want the items to occupy adjacent memory positions,
- use QVector.
+ \li QVector should be your default first choice.
+ QVector\<T\> will usually give better performance than QList\<T\>,
+ because QVector\<T\> always stores its items sequentially in memory,
+ where QList\<T\> will allocate its items on the heap unless
+ \c {sizeof(T) <= sizeof(void*)} and T has been declared to be
+ either a \c{Q_MOVABLE_TYPE} or a \c{Q_PRIMITIVE_TYPE} using
+ \l {Q_DECLARE_TYPEINFO}. See the \l {Pros and Cons of Using QList}
+ for an explanation.
+ \li However, QList is used throughout the Qt APIs for passing
+ parameters and for returning values. Use QList to interface with
+ those APIs.
+ \li If you need a real linked list, which guarantees
+ \l {Algorithmic Complexity}{constant time} insertions mid-list and
+ uses iterators to items rather than indexes, use QLinkedList.
\endlist
+ \note QVector and QVarLengthArray both guarantee C-compatible
+ array layout. QList does not. This might be important if your
+ application must interface with a C API.
- Internally, QList\<T\> is represented as an array of pointers to
- items of type T. If T is itself a pointer type or a basic type
- that is no larger than a pointer, or if T is one of Qt's \l{shared
- classes}, then QList\<T\> stores the items directly in the pointer
- array. For lists under a thousand items, this array representation
- allows for very fast insertions in the middle, and it allows
- index-based access. Furthermore, operations like prepend() and
- append() are very fast, because QList preallocates memory at both
+ \note Iterators into a QLinkedList and references into
+ heap-allocating QLists remain valid long as the referenced items
+ remain in the container. This is not true for iterators and
+ references into a QVector and non-heap-allocating QLists.
+
+ Internally, QList\<T\> is represented as an array of T if
+ \c{sizeof(T) <= sizeof(void*)} and T has been declared to be
+ either a \c{Q_MOVABLE_TYPE} or a \c{Q_PRIMITIVE_TYPE} using
+ \l {Q_DECLARE_TYPEINFO}. Otherwise, QList\<T\> is represented
+ as an array of T* and the items are allocated on the heap.
+
+ The array representation allows very fast insertions and
+ index-based access. The prepend() and append() operations are
+ also very fast because QList preallocates memory at both
ends of its internal array. (See \l{Algorithmic Complexity} for
- details.) Note, however, that for unshared list items that are
- larger than a pointer, each append or insert of a new item
- requires allocating the new item on the heap, and this per item
- allocation might make QVector a better choice in cases that do
- lots of appending or inserting, since QVector allocates memory for
- its items in a single heap allocation.
+ details.
+
+ Note, however, that when the conditions specified above are not met,
+ each append or insert of a new item requires allocating the new item
+ on the heap, and this per item allocation will make QVector a better
+ choice for use cases that do a lot of appending or inserting, because
+ QVector can allocate memory for many items in a single heap allocation.
Note that the internal array only ever gets bigger over the life
of the list. It never shrinks. The internal array is deallocated
@@ -401,9 +428,10 @@ void **QListData::erase(void **xi)
\snippet code/src_corelib_tools_qlistdata.cpp 2
- Because QList is implemented as an array of pointers, this
- operation is very fast (\l{constant time}). For read-only access,
- an alternative syntax is to use at():
+ Because QList is implemented as an array of pointers for types
+ that are larger than a pointer or are not movable, this operation
+ requires (\l{Algorithmic Complexity}{constant time}). For read-only
+ access, an alternative syntax is to use at():
\snippet code/src_corelib_tools_qlistdata.cpp 3
@@ -417,10 +445,10 @@ void **QListData::erase(void **xi)
\snippet code/src_corelib_tools_qlistdata.cpp 4
- Inserting and removing items at either ends of the list is very
- fast (\l{constant time} in most cases), because QList
- preallocates extra space on both sides of its internal buffer to
- allow for fast growth at both ends of the list.
+ Inserting and removing items at either end of the list is very
+ fast (\l{Algorithmic Complexity}{constant time} in most cases),
+ because QList preallocates extra space on both sides of its
+ internal buffer to allow for fast growth at both ends of the list.
If you want to find all occurrences of a particular value in a
list, use indexOf() or lastIndexOf(). The former searches forward
@@ -481,6 +509,11 @@ void **QListData::erase(void **xi)
\l{QStringList::removeDuplicates()}{removeDuplicates},
\l{QStringList::sort()}{sort}.
+ \section1 More Information on Using Qt Containers
+
+ For a detailed discussion comparing Qt containers with each other and
+ with STL containers, see \l {Understand the Qt Containers}.
+
\sa QListIterator, QMutableListIterator, QLinkedList, QVector
*/
@@ -512,10 +545,11 @@ void **QListData::erase(void **xi)
Constructs a copy of \a other.
- This operation takes \l{constant time}, because QList is
- \l{implicitly shared}. This makes returning a QList from a
- function very fast. If a shared instance is modified, it will be
- copied (copy-on-write), and that takes \l{linear time}.
+ This operation takes \l{Algorithmic Complexity}{constant time},
+ because QList is \l{implicitly shared}. This makes returning a
+ QList from a function very fast. If a shared instance is modified,
+ it will be copied (copy-on-write), and that takes
+ \l{Algorithmic Complexity}{linear time}.
\sa operator=()
*/
@@ -584,6 +618,65 @@ void **QListData::erase(void **xi)
\sa operator==()
*/
+/*! \fn bool operator<(const QList<T> &lhs, const QList<T> &rhs)
+ \since 5.6
+ \relates QList
+
+ Returns \c true if list \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator<=(const QList<T> &lhs, const QList<T> &rhs)
+ \since 5.6
+ \relates QList
+
+ Returns \c true if list \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>(const QList<T> &lhs, const QList<T> &rhs)
+ \since 5.6
+ \relates QList
+
+ Returns \c true if list \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>=(const QList<T> &lhs, const QList<T> &rhs)
+ \since 5.6
+ \relates QList
+
+ Returns \c true if list \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*!
+ \fn uint qHash(const QList<T> &key, uint seed = 0)
+ \since 5.6
+ \relates QList
+
+ Returns the hash value for \a key,
+ using \a seed to seed the calculation.
+
+ This function requires qHash() to be overloaded for the value type \c T.
+*/
+
/*!
\fn int QList::size() const
@@ -641,7 +734,7 @@ void **QListData::erase(void **xi)
Returns the item at index position \a i in the list. \a i must be
a valid index position in the list (i.e., 0 <= \a i < size()).
- This function is very fast (\l{constant time}).
+ This function is very fast (\l{Algorithmic Complexity}{constant time}).
\sa value(), operator[]()
*/
@@ -654,8 +747,8 @@ void **QListData::erase(void **xi)
If this function is called on a list that is currently being shared, it
will trigger a copy of all elements. Otherwise, this function runs in
- \l{constant time}. If you do not want to modify the list you should use
- QList::at().
+ \l{Algorithmic Complexity}{constant time}. If you do not want to modify
+ the list you should use QList::at().
\sa at(), value()
*/
@@ -664,7 +757,7 @@ void **QListData::erase(void **xi)
\overload
- Same as at(). This function runs in \l{constant time}.
+ Same as at(). This function runs in \l{Algorithmic Complexity}{constant time}.
*/
/*! \fn QList::reserve(int alloc)
@@ -690,9 +783,9 @@ void **QListData::erase(void **xi)
This is the same as list.insert(size(), \a value).
If this list is not shared, this operation is typically
- very fast (amortized \l{constant time}), because QList
- preallocates extra space on both sides of its internal
- buffer to allow for fast growth at both ends of the list.
+ very fast (amortized \l{Algorithmic Complexity}{constant time}),
+ because QList preallocates extra space on both sides of its
+ internal buffer to allow for fast growth at both ends of the list.
\sa operator<<(), prepend(), insert()
*/
@@ -718,9 +811,9 @@ void **QListData::erase(void **xi)
This is the same as list.insert(0, \a value).
If this list is not shared, this operation is typically
- very fast (amortized \l{constant time}), because QList
- preallocates extra space on both sides of its internal
- buffer to allow for fast growth at both ends of the list.
+ very fast (amortized \l{Algorithmic Complexity}{constant time}),
+ because QList preallocates extra space on both sides of its
+ internal buffer to allow for fast growth at both ends of the list.
\sa append(), insert()
*/
@@ -811,7 +904,8 @@ void **QListData::erase(void **xi)
same as takeAt(0). This function assumes the list is not empty. To
avoid failure, call isEmpty() before calling this function.
- If this list is not shared, this operation takes \l{constant time}.
+ If this list is not shared, this operation takes
+ \l {Algorithmic Complexity}{constant time}.
If you don't use the return value, removeFirst() is more
efficient.
@@ -826,7 +920,8 @@ void **QListData::erase(void **xi)
not empty. To avoid failure, call isEmpty() before calling this
function.
- If this list is not shared, this operation takes \l{constant time}.
+ If this list is not shared, this operation takes
+ \l {Algorithmic Complexity}{constant time}.
If you don't use the return value, removeLast() is more
efficient.
@@ -1000,6 +1095,52 @@ void **QListData::erase(void **xi)
\sa constBegin(), end()
*/
+/*! \fn QList::reverse_iterator QList::rbegin()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the list, in reverse order.
+
+ \sa begin(), crbegin(), rend()
+*/
+
+/*! \fn QList::const_reverse_iterator QList::rbegin() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QList::const_reverse_iterator QList::crbegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the list, in reverse order.
+
+ \sa begin(), rbegin(), rend()
+*/
+
+/*! \fn QList::reverse_iterator QList::rend()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
+ the last item in the list, in reverse order.
+
+ \sa end(), crend(), rbegin()
+*/
+
+/*! \fn QList::const_reverse_iterator QList::rend() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QList::const_reverse_iterator QList::crend() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
+ past the last item in the list, in reverse order.
+
+ \sa end(), rend(), rbegin()
+*/
+
/*! \fn QList::iterator QList::erase(iterator pos)
Removes the item associated with the iterator \a pos from the
@@ -1070,6 +1211,38 @@ void **QListData::erase(void **xi)
Typedef for const T &. Provided for STL compatibility.
*/
+/*! \typedef QList::reverse_iterator
+ \since 5.6
+
+ The QList::reverse_iterator typedef provides an STL-style non-const
+ reverse iterator for QList.
+
+ It is simply a typedef for \c{std::reverse_iterator<iterator>}.
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QList::rbegin(), QList::rend(), QList::const_reverse_iterator, QList::iterator
+*/
+
+/*! \typedef QList::const_reverse_iterator
+ \since 5.6
+
+ The QList::const_reverse_iterator typedef provides an STL-style const
+ reverse iterator for QList.
+
+ It is simply a typedef for \c{std::reverse_iterator<const_iterator>}.
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QList::rbegin(), QList::rend(), QList::reverse_iterator, QList::const_iterator
+*/
+
/*! \fn int QList::count() const
Returns the number of items in the list. This is effectively the
@@ -1090,7 +1263,7 @@ void **QListData::erase(void **xi)
not be empty. If the list can be empty, call isEmpty() before
calling this function.
- \sa last(), isEmpty()
+ \sa constFirst(), last(), isEmpty()
*/
/*! \fn const T& QList::first() const
@@ -1098,13 +1271,23 @@ void **QListData::erase(void **xi)
\overload
*/
+/*! \fn const T& QList::constFirst() const
+ \since 5.6
+
+ Returns a const reference to the first item in the list. The list must
+ not be empty. If the list can be empty, call isEmpty() before
+ calling this function.
+
+ \sa constLast(), isEmpty(), first()
+*/
+
/*! \fn T& QList::last()
Returns a reference to the last item in the list. The list must
not be empty. If the list can be empty, call isEmpty() before
calling this function.
- \sa first(), isEmpty()
+ \sa constLast(), first(), isEmpty()
*/
/*! \fn const T& QList::last() const
@@ -1112,6 +1295,16 @@ void **QListData::erase(void **xi)
\overload
*/
+/*! \fn const T& QList::constLast() const
+ \since 5.6
+
+ Returns a reference to the last item in the list. The list must
+ not be empty. If the list can be empty, call isEmpty() before
+ calling this function.
+
+ \sa constFirst(), isEmpty(), last()
+*/
+
/*! \fn void QList::removeFirst()
Removes the first item in the list. Calling this function is
diff --git a/src/corelib/tools/qlist.h b/src/corelib/tools/qlist.h
index f5ff952f97..32e0141d55 100644
--- a/src/corelib/tools/qlist.h
+++ b/src/corelib/tools/qlist.h
@@ -38,6 +38,7 @@
#include <QtCore/qiterator.h>
#include <QtCore/qrefcount.h>
#include <QtCore/qarraydata.h>
+#include <QtCore/qhashfunctions.h>
#include <iterator>
#include <list>
@@ -89,6 +90,7 @@ struct Q_CORE_EXPORT QListData {
Data *detach(int alloc);
Data *detach_grow(int *i, int n);
void realloc(int alloc);
+ void realloc_grow(int growth);
inline void dispose() { dispose(d); }
static void dispose(Data *d);
static const Data shared_null;
@@ -102,11 +104,11 @@ struct Q_CORE_EXPORT QListData {
void remove(int i);
void remove(int i, int n);
void move(int from, int to);
- inline int size() const { return d->end - d->begin; }
- inline bool isEmpty() const { return d->end == d->begin; }
- inline void **at(int i) const { return d->array + d->begin + i; }
- inline void **begin() const { return d->array + d->begin; }
- inline void **end() const { return d->array + d->end; }
+ inline int size() const Q_DECL_NOTHROW { return d->end - d->begin; }
+ inline bool isEmpty() const Q_DECL_NOTHROW { return d->end == d->begin; }
+ inline void **at(int i) const Q_DECL_NOTHROW { return d->array + d->begin + i; }
+ inline void **begin() const Q_DECL_NOTHROW { return d->array + d->begin; }
+ inline void **end() const Q_DECL_NOTHROW { return d->array + d->end; }
};
template <typename T>
@@ -143,7 +145,7 @@ public:
#ifdef Q_COMPILER_RVALUE_REFS
inline QList(QList<T> &&other) : d(other.d) { other.d = const_cast<QListData::Data *>(&QListData::shared_null); }
inline QList &operator=(QList<T> &&other)
- { qSwap(d, other.d); return *this; }
+ { QList moved(std::move(other)); swap(moved); return *this; }
#endif
inline void swap(QList<T> &other) { qSwap(d, other.d); }
#ifdef Q_COMPILER_INITIALIZER_LISTS
@@ -154,7 +156,7 @@ public:
bool operator==(const QList<T> &l) const;
inline bool operator!=(const QList<T> &l) const { return !(*this == l); }
- inline int size() const { return p.size(); }
+ inline int size() const Q_DECL_NOTHROW { return p.size(); }
inline void detach() { if (d->ref.isShared()) detach_helper(); }
@@ -177,9 +179,9 @@ public:
d->ref.setSharable(sharable);
}
#endif
- inline bool isSharedWith(const QList<T> &other) const { return d == other.d; }
+ inline bool isSharedWith(const QList<T> &other) const Q_DECL_NOTHROW { return d == other.d; }
- inline bool isEmpty() const { return p.isEmpty(); }
+ inline bool isEmpty() const Q_DECL_NOTHROW { return p.isEmpty(); }
void clear();
@@ -218,30 +220,34 @@ public:
typedef T *pointer;
typedef T &reference;
- inline iterator() : i(0) {}
- inline iterator(Node *n) : i(n) {}
- inline iterator(const iterator &o): i(o.i){}
+ inline iterator() Q_DECL_NOTHROW : i(Q_NULLPTR) {}
+ inline iterator(Node *n) Q_DECL_NOTHROW : i(n) {}
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+ // can't remove it in Qt 5, since doing so would make the type trivial,
+ // which changes the way it's passed to functions by value.
+ inline iterator(const iterator &o) Q_DECL_NOTHROW : i(o.i){}
+#endif
inline T &operator*() const { return i->t(); }
inline T *operator->() const { return &i->t(); }
inline T &operator[](difference_type j) const { return i[j].t(); }
- inline bool operator==(const iterator &o) const { return i == o.i; }
- inline bool operator!=(const iterator &o) const { return i != o.i; }
- inline bool operator<(const iterator& other) const { return i < other.i; }
- inline bool operator<=(const iterator& other) const { return i <= other.i; }
- inline bool operator>(const iterator& other) const { return i > other.i; }
- inline bool operator>=(const iterator& other) const { return i >= other.i; }
+ inline bool operator==(const iterator &o) const Q_DECL_NOTHROW { return i == o.i; }
+ inline bool operator!=(const iterator &o) const Q_DECL_NOTHROW { return i != o.i; }
+ inline bool operator<(const iterator& other) const Q_DECL_NOTHROW { return i < other.i; }
+ inline bool operator<=(const iterator& other) const Q_DECL_NOTHROW { return i <= other.i; }
+ inline bool operator>(const iterator& other) const Q_DECL_NOTHROW { return i > other.i; }
+ inline bool operator>=(const iterator& other) const Q_DECL_NOTHROW { return i >= other.i; }
#ifndef QT_STRICT_ITERATORS
- inline bool operator==(const const_iterator &o) const
+ inline bool operator==(const const_iterator &o) const Q_DECL_NOTHROW
{ return i == o.i; }
- inline bool operator!=(const const_iterator &o) const
+ inline bool operator!=(const const_iterator &o) const Q_DECL_NOTHROW
{ return i != o.i; }
- inline bool operator<(const const_iterator& other) const
+ inline bool operator<(const const_iterator& other) const Q_DECL_NOTHROW
{ return i < other.i; }
- inline bool operator<=(const const_iterator& other) const
+ inline bool operator<=(const const_iterator& other) const Q_DECL_NOTHROW
{ return i <= other.i; }
- inline bool operator>(const const_iterator& other) const
+ inline bool operator>(const const_iterator& other) const Q_DECL_NOTHROW
{ return i > other.i; }
- inline bool operator>=(const const_iterator& other) const
+ inline bool operator>=(const const_iterator& other) const Q_DECL_NOTHROW
{ return i >= other.i; }
#endif
inline iterator &operator++() { ++i; return *this; }
@@ -266,23 +272,27 @@ public:
typedef const T *pointer;
typedef const T &reference;
- inline const_iterator() : i(0) {}
- inline const_iterator(Node *n) : i(n) {}
- inline const_iterator(const const_iterator &o): i(o.i) {}
+ inline const_iterator() Q_DECL_NOTHROW : i(Q_NULLPTR) {}
+ inline const_iterator(Node *n) Q_DECL_NOTHROW : i(n) {}
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+ // can't remove it in Qt 5, since doing so would make the type trivial,
+ // which changes the way it's passed to functions by value.
+ inline const_iterator(const const_iterator &o) Q_DECL_NOTHROW : i(o.i) {}
+#endif
#ifdef QT_STRICT_ITERATORS
- inline explicit const_iterator(const iterator &o): i(o.i) {}
+ inline explicit const_iterator(const iterator &o) Q_DECL_NOTHROW : i(o.i) {}
#else
- inline const_iterator(const iterator &o): i(o.i) {}
+ inline const_iterator(const iterator &o) Q_DECL_NOTHROW : i(o.i) {}
#endif
inline const T &operator*() const { return i->t(); }
inline const T *operator->() const { return &i->t(); }
inline const T &operator[](difference_type j) const { return i[j].t(); }
- inline bool operator==(const const_iterator &o) const { return i == o.i; }
- inline bool operator!=(const const_iterator &o) const { return i != o.i; }
- inline bool operator<(const const_iterator& other) const { return i < other.i; }
- inline bool operator<=(const const_iterator& other) const { return i <= other.i; }
- inline bool operator>(const const_iterator& other) const { return i > other.i; }
- inline bool operator>=(const const_iterator& other) const { return i >= other.i; }
+ inline bool operator==(const const_iterator &o) const Q_DECL_NOTHROW { return i == o.i; }
+ inline bool operator!=(const const_iterator &o) const Q_DECL_NOTHROW { return i != o.i; }
+ inline bool operator<(const const_iterator& other) const Q_DECL_NOTHROW { return i < other.i; }
+ inline bool operator<=(const const_iterator& other) const Q_DECL_NOTHROW { return i <= other.i; }
+ inline bool operator>(const const_iterator& other) const Q_DECL_NOTHROW { return i > other.i; }
+ inline bool operator>=(const const_iterator& other) const Q_DECL_NOTHROW { return i >= other.i; }
inline const_iterator &operator++() { ++i; return *this; }
inline const_iterator operator++(int) { Node *n = i; ++i; return n; }
inline const_iterator &operator--() { i--; return *this; }
@@ -296,14 +306,22 @@ public:
friend class const_iterator;
// stl style
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
inline iterator begin() { detach(); return reinterpret_cast<Node *>(p.begin()); }
- inline const_iterator begin() const { return reinterpret_cast<Node *>(p.begin()); }
- inline const_iterator cbegin() const { return reinterpret_cast<Node *>(p.begin()); }
- inline const_iterator constBegin() const { return reinterpret_cast<Node *>(p.begin()); }
+ inline const_iterator begin() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.begin()); }
+ inline const_iterator cbegin() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.begin()); }
+ inline const_iterator constBegin() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.begin()); }
inline iterator end() { detach(); return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator end() const { return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator cend() const { return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator constEnd() const { return reinterpret_cast<Node *>(p.end()); }
+ inline const_iterator end() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.end()); }
+ inline const_iterator cend() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.end()); }
+ inline const_iterator constEnd() const Q_DECL_NOTHROW { return reinterpret_cast<Node *>(p.end()); }
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
+ const_reverse_iterator rend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
+ const_reverse_iterator crbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
+ const_reverse_iterator crend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
iterator insert(iterator before, const T &t);
iterator erase(iterator pos);
iterator erase(iterator first, iterator last);
@@ -314,9 +332,11 @@ public:
inline int count() const { return p.size(); }
inline int length() const { return p.size(); } // Same as count()
inline T& first() { Q_ASSERT(!isEmpty()); return *begin(); }
+ inline const T& constFirst() const { return first(); }
inline const T& first() const { Q_ASSERT(!isEmpty()); return at(0); }
T& last() { Q_ASSERT(!isEmpty()); return *(--end()); }
const T& last() const { Q_ASSERT(!isEmpty()); return at(count() - 1); }
+ inline const T& constLast() const { return last(); }
inline void removeFirst() { Q_ASSERT(!isEmpty()); erase(begin()); }
inline void removeLast() { Q_ASSERT(!isEmpty()); erase(--end()); }
inline bool startsWith(const T &t) const { return !isEmpty() && first() == t; }
@@ -378,7 +398,7 @@ private:
void node_copy(Node *from, Node *to, Node *src);
void node_destruct(Node *from, Node *to);
- bool isValidIterator(const iterator &i) const
+ bool isValidIterator(const iterator &i) const Q_DECL_NOTHROW
{
return (constBegin().i <= i.i) && (i.i <= constEnd().i);
}
@@ -1020,6 +1040,43 @@ inline int QList<T>::count_impl(const T &t, QListData::ArrayCompatibleLayout) co
Q_DECLARE_SEQUENTIAL_ITERATOR(List)
Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(List)
+template <typename T>
+uint qHash(const QList<T> &key, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHashRange(key.cbegin(), key.cend(), seed)))
+{
+ return qHashRange(key.cbegin(), key.cend(), seed);
+}
+
+template <typename T>
+bool operator<(const QList<T> &lhs, const QList<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end())))
+{
+ return std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end());
+}
+
+template <typename T>
+inline bool operator>(const QList<T> &lhs, const QList<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return rhs < lhs;
+}
+
+template <typename T>
+inline bool operator<=(const QList<T> &lhs, const QList<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs > rhs);
+}
+
+template <typename T>
+inline bool operator>=(const QList<T> &lhs, const QList<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs < rhs);
+}
+
QT_END_NAMESPACE
#include <QtCore/qbytearraylist.h>
diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp
index 824b70c3fd..703341cc36 100644
--- a/src/corelib/tools/qlocale.cpp
+++ b/src/corelib/tools/qlocale.cpp
@@ -42,6 +42,7 @@
#include "qdatastream.h"
#include "qdebug.h"
+#include "qhashfunctions.h"
#include "qstring.h"
#include "qlocale.h"
#include "qlocale_p.h"
@@ -420,7 +421,7 @@ bool qt_splitLocaleName(const QString &name, QString &lang, QString &script, QSt
state = ScriptState;
break;
case ScriptState: {
- QString scripts = QString::fromLatin1((const char *)script_code_list, sizeof(script_code_list));
+ QString scripts = QString::fromLatin1((const char *)script_code_list, sizeof(script_code_list) - 1);
if (value.length() == 4 && scripts.indexOf(value) % 4 == 0) {
// script name is always 4 characters
script = value;
@@ -866,6 +867,21 @@ bool QLocale::operator!=(const QLocale &other) const
}
/*!
+ \since 5.6
+ \relates QLocale
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QLocale &key, uint seed) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(seed, key.d->m_data);
+ seed = hash(seed, key.d->m_numberOptions);
+ return seed;
+}
+
+/*!
\since 4.2
Sets the \a options related to number conversions for this
diff --git a/src/corelib/tools/qlocale.h b/src/corelib/tools/qlocale.h
index 61574ba44f..0cbfa6710c 100644
--- a/src/corelib/tools/qlocale.h
+++ b/src/corelib/tools/qlocale.h
@@ -45,6 +45,7 @@ QT_BEGIN_NAMESPACE
class QDataStream;
class QDate;
class QDateTime;
+class QLocale;
class QTime;
class QVariant;
class QTextStream;
@@ -52,6 +53,8 @@ class QTextStreamPrivate;
class QLocalePrivate;
+Q_CORE_EXPORT uint qHash(const QLocale &key, uint seed = 0) Q_DECL_NOTHROW;
+
class Q_CORE_EXPORT QLocale
{
Q_GADGET
@@ -868,23 +871,23 @@ public:
QString nativeLanguageName() const;
QString nativeCountryName() const;
- short toShort(const QString &s, bool *ok = 0) const;
- ushort toUShort(const QString &s, bool *ok = 0) const;
- int toInt(const QString &s, bool *ok = 0) const;
- uint toUInt(const QString &s, bool *ok = 0) const;
- qlonglong toLongLong(const QString &s, bool *ok = 0) const;
- qulonglong toULongLong(const QString &s, bool *ok = 0) const;
- float toFloat(const QString &s, bool *ok = 0) const;
- double toDouble(const QString &s, bool *ok = 0) const;
-
- short toShort(const QStringRef &s, bool *ok = 0) const;
- ushort toUShort(const QStringRef &s, bool *ok = 0) const;
- int toInt(const QStringRef &s, bool *ok = 0) const;
- uint toUInt(const QStringRef &s, bool *ok = 0) const;
- qlonglong toLongLong(const QStringRef &s, bool *ok = 0) const;
- qulonglong toULongLong(const QStringRef &s, bool *ok = 0) const;
- float toFloat(const QStringRef &s, bool *ok = 0) const;
- double toDouble(const QStringRef &s, bool *ok = 0) const;
+ short toShort(const QString &s, bool *ok = Q_NULLPTR) const;
+ ushort toUShort(const QString &s, bool *ok = Q_NULLPTR) const;
+ int toInt(const QString &s, bool *ok = Q_NULLPTR) const;
+ uint toUInt(const QString &s, bool *ok = Q_NULLPTR) const;
+ qlonglong toLongLong(const QString &s, bool *ok = Q_NULLPTR) const;
+ qulonglong toULongLong(const QString &s, bool *ok = Q_NULLPTR) const;
+ float toFloat(const QString &s, bool *ok = Q_NULLPTR) const;
+ double toDouble(const QString &s, bool *ok = Q_NULLPTR) const;
+
+ short toShort(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ ushort toUShort(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ int toInt(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ uint toUInt(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ qlonglong toLongLong(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ qulonglong toULongLong(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ float toFloat(const QStringRef &s, bool *ok = Q_NULLPTR) const;
+ double toDouble(const QStringRef &s, bool *ok = Q_NULLPTR) const;
QString toString(qlonglong i) const;
QString toString(qulonglong i) const;
@@ -979,6 +982,8 @@ public:
private:
QLocale(QLocalePrivate &dd);
friend class QLocalePrivate;
+ friend Q_CORE_EXPORT uint qHash(const QLocale &key, uint seed) Q_DECL_NOTHROW;
+
QSharedDataPointer<QLocalePrivate> d;
};
Q_DECLARE_TYPEINFO(QLocale, Q_MOVABLE_TYPE);
diff --git a/src/corelib/tools/qlocale_mac.mm b/src/corelib/tools/qlocale_mac.mm
index 37a63a2ca4..c0818f07d7 100644
--- a/src/corelib/tools/qlocale_mac.mm
+++ b/src/corelib/tools/qlocale_mac.mm
@@ -44,18 +44,6 @@
QT_BEGIN_NAMESPACE
-namespace {
-class AutoReleasePool
-{
-public:
- AutoReleasePool(): pool([[NSAutoreleasePool alloc] init]) {}
- ~AutoReleasePool() { [pool release]; }
-
-private:
- NSAutoreleasePool *pool;
-};
-}
-
/******************************************************************************
** Wrappers for Mac locale system functions
*/
@@ -426,7 +414,7 @@ QLocale QSystemLocale::fallbackUiLocale() const
QVariant QSystemLocale::query(QueryType type, QVariant in = QVariant()) const
{
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
switch(type) {
// case Name:
// return getMacLocaleName();
diff --git a/src/corelib/tools/qlocale_p.h b/src/corelib/tools/qlocale_p.h
index 430f95dcda..b3fd7a96b8 100644
--- a/src/corelib/tools/qlocale_p.h
+++ b/src/corelib/tools/qlocale_p.h
@@ -122,6 +122,8 @@ private:
QSystemLocale(bool);
friend class QSystemLocaleSingleton;
};
+Q_DECLARE_TYPEINFO(QSystemLocale::QueryType, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QSystemLocale::CurrencyToStringArgument, Q_MOVABLE_TYPE);
#endif
#ifdef QT_USE_ICU
@@ -153,6 +155,7 @@ struct QLocaleId
ushort language_id, script_id, country_id;
};
+Q_DECLARE_TYPEINFO(QLocaleId, Q_PRIMITIVE_TYPE);
struct QLocaleData
{
diff --git a/src/corelib/tools/qmap.cpp b/src/corelib/tools/qmap.cpp
index 1b7a8007cd..e49a1a098d 100644
--- a/src/corelib/tools/qmap.cpp
+++ b/src/corelib/tools/qmap.cpp
@@ -858,6 +858,15 @@ void QMapDataBase::freeData(QMapDataBase *d)
\sa begin(), constEnd()
*/
+/*! \fn QMap::key_iterator QMap::keyBegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first key
+ in the map.
+
+ \sa keyEnd(), firstKey()
+*/
+
/*! \fn QMap::iterator QMap::end()
Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary item
@@ -888,6 +897,15 @@ void QMapDataBase::freeData(QMapDataBase *d)
\sa constBegin(), end()
*/
+/*! \fn QMap::key_iterator QMap::keyEnd() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
+ item after the last key in the map.
+
+ \sa keyBegin(), lastKey()
+*/
+
/*! \fn const Key &QMap::firstKey() const
\since 5.2
@@ -896,7 +914,7 @@ void QMapDataBase::freeData(QMapDataBase *d)
This executes in \l{constant time}.
- \sa lastKey(), first(), isEmpty()
+ \sa lastKey(), first(), keyBegin(), isEmpty()
*/
/*! \fn const Key &QMap::lastKey() const
@@ -907,7 +925,7 @@ void QMapDataBase::freeData(QMapDataBase *d)
This executes in \l{logarithmic time}.
- \sa firstKey(), last(), isEmpty()
+ \sa firstKey(), last(), keyEnd(), isEmpty()
*/
/*! \fn T &QMap::first()
@@ -1161,6 +1179,12 @@ void QMapDataBase::freeData(QMapDataBase *d)
are stored under \a key.
*/
+/*!
+ \fn QPair<const_iterator, const_iterator> QMap::equal_range(const Key &key) const
+ \overload
+ \since 5.6
+*/
+
/*! \class QMap::iterator
\inmodule QtCore
@@ -1229,7 +1253,7 @@ void QMapDataBase::freeData(QMapDataBase *d)
while iterators are active on that container. For more information,
read \l{Implicit sharing iterator problem}.
- \sa QMap::const_iterator, QMutableMapIterator
+ \sa QMap::const_iterator, QMap::key_iterator, QMutableMapIterator
*/
/*! \typedef QMap::iterator::difference_type
@@ -1452,7 +1476,7 @@ void QMapDataBase::freeData(QMapDataBase *d)
while iterators are active on that container. For more information,
read \l{Implicit sharing iterator problem}.
- \sa QMap::iterator, QMapIterator
+ \sa QMap::iterator, QMap::key_iterator, QMapIterator
*/
/*! \typedef QMap::const_iterator::difference_type
@@ -1628,6 +1652,134 @@ void QMapDataBase::freeData(QMapDataBase *d)
\sa operator+=(), operator-()
*/
+/*! \class QMap::key_iterator
+ \inmodule QtCore
+ \since 5.6
+ \brief The QMap::key_iterator class provides an STL-style const iterator for QMap and QMultiMap keys.
+
+ QMap::key_iterator is essentially the same as QMap::const_iterator
+ with the difference that operator*() and operator->() return a key
+ instead of a value.
+
+ For most uses QMap::iterator and QMap::const_iterator should be used,
+ you can easily access the key by calling QMap::iterator::key():
+
+ \snippet code/src_corelib_tools_qmap.cpp keyiterator1
+
+ However, to have interoperability between QMap's keys and STL-style
+ algorithms we need an iterator that dereferences to a key instead
+ of a value. With QMap::key_iterator we can apply an algorithm to a
+ range of keys without having to call QMap::keys(), which is inefficient
+ as it costs one QMap iteration and memory allocation to create a temporary
+ QList.
+
+ \snippet code/src_corelib_tools_qmap.cpp keyiterator2
+
+ QMap::key_iterator is const, it's not possible to modify the key.
+
+ The default QMap::key_iterator constructor creates an uninitialized
+ iterator. You must initialize it using a QMap function like
+ QMap::keyBegin() or QMap::keyEnd().
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QMap::const_iterator, QMap::iterator
+*/
+
+/*! \typedef QMap::key_iterator::difference_type
+ \internal
+*/
+
+/*! \typedef QMap::key_iterator::iterator_category
+ \internal
+*/
+
+/*! \typedef QMap::key_iterator::pointer
+ \internal
+*/
+
+/*! \typedef QMap::key_iterator::reference
+ \internal
+*/
+
+/*! \typedef QMap::key_iterator::value_type
+ \internal
+*/
+
+/*! \fn const T &QMap::key_iterator::operator*() const
+
+ Returns the current item's key.
+*/
+
+/*! \fn const T *QMap::key_iterator::operator->() const
+
+ Returns a pointer to the current item's key.
+*/
+
+/*! \fn bool QMap::key_iterator::operator==(key_iterator other) const
+
+ Returns \c true if \a other points to the same item as this
+ iterator; otherwise returns \c false.
+
+ \sa operator!=()
+*/
+
+/*! \fn bool QMap::key_iterator::operator!=(key_iterator other) const
+
+ Returns \c true if \a other points to a different item than this
+ iterator; otherwise returns \c false.
+
+ \sa operator==()
+*/
+
+/*!
+ \fn QMap::key_iterator &QMap::key_iterator::operator++()
+
+ The prefix ++ operator (\c{++i}) advances the iterator to the
+ next item in the hash and returns an iterator to the new current
+ item.
+
+ Calling this function on QMap::keyEnd() leads to undefined results.
+
+ \sa operator--()
+*/
+
+/*! \fn QMap::key_iterator QMap::key_iterator::operator++(int)
+
+ \overload
+
+ The postfix ++ operator (\c{i++}) advances the iterator to the
+ next item in the hash and returns an iterator to the previous
+ item.
+*/
+
+/*! \fn QMap::key_iterator &QMap::key_iterator::operator--()
+
+ The prefix -- operator (\c{--i}) makes the preceding item
+ current and returns an iterator pointing to the new current item.
+
+ Calling this function on QMap::keyBegin() leads to undefined
+ results.
+
+ \sa operator++()
+*/
+
+/*! \fn QMap::key_iterator QMap::key_iterator::operator--(int)
+
+ \overload
+
+ The postfix -- operator (\c{i--}) makes the preceding item
+ current and returns an iterator pointing to the previous
+ item.
+*/
+
+/*! \fn const_iterator QMap::key_iterator::base() const
+ Returns the underlying const_iterator this key_iterator is based on.
+*/
+
/*! \fn QDataStream &operator<<(QDataStream &out, const QMap<Key, T> &map)
\relates QMap
diff --git a/src/corelib/tools/qmap.h b/src/corelib/tools/qmap.h
index 1f80e8f0f4..b7bd268bda 100644
--- a/src/corelib/tools/qmap.h
+++ b/src/corelib/tools/qmap.h
@@ -38,6 +38,7 @@
#include <QtCore/qlist.h>
#include <QtCore/qrefcount.h>
#include <QtCore/qpair.h>
+#include <QtCore/qtypetraits.h>
#ifdef Q_MAP_DEBUG
#include <QtCore/qdebug.h>
@@ -94,6 +95,13 @@ struct Q_CORE_EXPORT QMapNodeBase
void setColor(Color c) { if (c == Black) p |= Black; else p &= ~Black; }
QMapNodeBase *parent() const { return reinterpret_cast<QMapNodeBase *>(p & ~Mask); }
void setParent(QMapNodeBase *pp) { p = (p & Mask) | quintptr(pp); }
+
+ template <typename T>
+ static typename QtPrivate::QEnableIf<QTypeInfo<T>::isComplex>::Type
+ callDestructorIfNecessary(T &t) Q_DECL_NOTHROW { Q_UNUSED(t); t.~T(); } // Q_UNUSED: silence MSVC unused 't' warning
+ template <typename T>
+ static typename QtPrivate::QEnableIf<!QTypeInfo<T>::isComplex>::Type
+ callDestructorIfNecessary(T &) Q_DECL_NOTHROW {}
};
template <class Key, class T>
@@ -112,12 +120,26 @@ struct QMapNode : public QMapNodeBase
QMapNode<Key, T> *copy(QMapData<Key, T> *d) const;
- void destroySubTree();
+ void destroySubTree()
+ {
+ callDestructorIfNecessary(key);
+ callDestructorIfNecessary(value);
+ doDestroySubTree(QtPrivate::integral_constant<bool, QTypeInfo<T>::isComplex || QTypeInfo<Key>::isComplex>());
+ }
QMapNode<Key, T> *lowerBound(const Key &key);
QMapNode<Key, T> *upperBound(const Key &key);
private:
+ void doDestroySubTree(QtPrivate::false_type) {}
+ void doDestroySubTree(QtPrivate::true_type)
+ {
+ if (left)
+ leftNode()->destroySubTree();
+ if (right)
+ rightNode()->destroySubTree();
+ }
+
QMapNode() Q_DECL_EQ_DELETE;
Q_DISABLE_COPY(QMapNode)
};
@@ -126,7 +148,7 @@ template <class Key, class T>
inline QMapNode<Key, T> *QMapNode<Key, T>::lowerBound(const Key &akey)
{
QMapNode<Key, T> *n = this;
- QMapNode<Key, T> *lastNode = 0;
+ QMapNode<Key, T> *lastNode = Q_NULLPTR;
while (n) {
if (!qMapLessThanKey(n->key, akey)) {
lastNode = n;
@@ -142,7 +164,7 @@ template <class Key, class T>
inline QMapNode<Key, T> *QMapNode<Key, T>::upperBound(const Key &akey)
{
QMapNode<Key, T> *n = this;
- QMapNode<Key, T> *lastNode = 0;
+ QMapNode<Key, T> *lastNode = Q_NULLPTR;
while (n) {
if (qMapLessThanKey(akey, n->key)) {
lastNode = n;
@@ -194,7 +216,7 @@ struct QMapData : public QMapDataBase
Node *findNode(const Key &akey) const;
void nodeRange(const Key &akey, Node **firstNode, Node **lastNode);
- Node *createNode(const Key &k, const T &v, Node *parent = 0, bool left = false)
+ Node *createNode(const Key &k, const T &v, Node *parent = Q_NULLPTR, bool left = false)
{
Node *n = static_cast<Node *>(QMapDataBase::createNode(sizeof(Node), Q_ALIGNOF(Node),
parent, left));
@@ -235,48 +257,22 @@ QMapNode<Key, T> *QMapNode<Key, T>::copy(QMapData<Key, T> *d) const
n->left = leftNode()->copy(d);
n->left->setParent(n);
} else {
- n->left = 0;
+ n->left = Q_NULLPTR;
}
if (right) {
n->right = rightNode()->copy(d);
n->right->setParent(n);
} else {
- n->right = 0;
+ n->right = Q_NULLPTR;
}
return n;
}
-#if defined(Q_CC_MSVC)
-#pragma warning( push )
-#pragma warning( disable : 4127 ) // conditional expression is constant
-#endif
-
-template <class Key, class T>
-void QMapNode<Key, T>::destroySubTree()
-{
- if (QTypeInfo<Key>::isComplex)
- key.~Key();
- if (QTypeInfo<T>::isComplex)
- value.~T();
- if (QTypeInfo<Key>::isComplex || QTypeInfo<T>::isComplex) {
- if (left)
- leftNode()->destroySubTree();
- if (right)
- rightNode()->destroySubTree();
- }
-}
-
-#if defined(Q_CC_MSVC)
-#pragma warning( pop )
-#endif
-
template <class Key, class T>
void QMapData<Key, T>::deleteNode(QMapNode<Key, T> *z)
{
- if (QTypeInfo<Key>::isComplex)
- z->key.~Key();
- if (QTypeInfo<T>::isComplex)
- z->value.~T();
+ QMapNodeBase::callDestructorIfNecessary(z->key);
+ QMapNodeBase::callDestructorIfNecessary(z->value);
freeNodeAndRebalance(z);
}
@@ -288,7 +284,7 @@ QMapNode<Key, T> *QMapData<Key, T>::findNode(const Key &akey) const
if (lb && !qMapLessThanKey(akey, lb->key))
return lb;
}
- return 0;
+ return Q_NULLPTR;
}
@@ -304,10 +300,10 @@ void QMapData<Key, T>::nodeRange(const Key &akey, QMapNode<Key, T> **firstNode,
} else if (qMapLessThanKey(n->key, akey)) {
n = n->rightNode();
} else {
- *firstNode = n->leftNode() ? n->leftNode()->lowerBound(akey) : 0;
+ *firstNode = n->leftNode() ? n->leftNode()->lowerBound(akey) : Q_NULLPTR;
if (!*firstNode)
*firstNode = n;
- *lastNode = n->rightNode() ? n->rightNode()->upperBound(akey) : 0;
+ *lastNode = n->rightNode() ? n->rightNode()->upperBound(akey) : Q_NULLPTR;
if (!*lastNode)
*lastNode = l;
return;
@@ -348,7 +344,7 @@ public:
}
inline QMap<Key, T> &operator=(QMap<Key, T> &&other)
- { qSwap(d, other.d); return *this; }
+ { QMap moved(std::move(other)); swap(moved); return *this; }
#endif
inline void swap(QMap<Key, T> &other) { qSwap(d, other.d); }
explicit QMap(const typename std::map<Key, T> &other);
@@ -416,7 +412,7 @@ public:
typedef T *pointer;
typedef T &reference;
- inline iterator() : i(0) { }
+ inline iterator() : i(Q_NULLPTR) { }
inline iterator(Node *node) : i(node) { }
inline const Key &key() const { return i->key; }
@@ -473,7 +469,7 @@ public:
typedef const T *pointer;
typedef const T &reference;
- inline const_iterator() : i(0) { }
+ inline const_iterator() : i(Q_NULLPTR) { }
inline const_iterator(const Node *node) : i(node) { }
#ifdef QT_STRICT_ITERATORS
explicit inline const_iterator(const iterator &o)
@@ -522,6 +518,32 @@ public:
};
friend class const_iterator;
+ class key_iterator
+ {
+ const_iterator i;
+
+ public:
+ typedef typename const_iterator::iterator_category iterator_category;
+ typedef typename const_iterator::difference_type difference_type;
+ typedef Key value_type;
+ typedef const Key *pointer;
+ typedef const Key &reference;
+
+ explicit key_iterator(const_iterator o) : i(o) { }
+
+ const Key &operator*() const { return i.key(); }
+ const Key *operator->() const { return &i.key(); }
+ bool operator==(key_iterator o) const { return i == o.i; }
+ bool operator!=(key_iterator o) const { return i != o.i; }
+
+ inline key_iterator &operator++() { ++i; return *this; }
+ inline key_iterator operator++(int) { return key_iterator(i++);}
+ inline key_iterator &operator--() { --i; return *this; }
+ inline key_iterator operator--(int) { return key_iterator(i--); }
+ const_iterator base() const { return i; }
+ };
+
+
// STL style
inline iterator begin() { detach(); return iterator(d->begin()); }
inline const_iterator begin() const { return const_iterator(d->begin()); }
@@ -531,6 +553,8 @@ public:
inline const_iterator end() const { return const_iterator(d->end()); }
inline const_iterator constEnd() const { return const_iterator(d->end()); }
inline const_iterator cend() const { return const_iterator(d->end()); }
+ inline key_iterator keyBegin() const { return key_iterator(begin()); }
+ inline key_iterator keyEnd() const { return key_iterator(end()); }
iterator erase(iterator it);
// more Qt
@@ -557,6 +581,7 @@ public:
typedef int size_type;
inline bool empty() const { return isEmpty(); }
QPair<iterator, iterator> equal_range(const Key &akey);
+ QPair<const_iterator, const_iterator> equal_range(const Key &akey) const;
#ifdef Q_MAP_DEBUG
void dump() const;
@@ -653,7 +678,7 @@ Q_INLINE_TEMPLATE int QMap<Key, T>::count(const Key &akey) const
template <class Key, class T>
Q_INLINE_TEMPLATE bool QMap<Key, T>::contains(const Key &akey) const
{
- return d->findNode(akey) != 0;
+ return d->findNode(akey) != Q_NULLPTR;
}
template <class Key, class T>
@@ -662,7 +687,7 @@ Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator QMap<Key, T>::insert(const Key
detach();
Node *n = d->root();
Node *y = d->end();
- Node *lastNode = 0;
+ Node *lastNode = Q_NULLPTR;
bool left = true;
while (n) {
y = n;
@@ -737,15 +762,15 @@ typename QMap<Key, T>::iterator QMap<Key, T>::insert(const_iterator pos, const K
}
// we need to insert (not overwrite)
- if (prev->right == 0) {
+ if (prev->right == Q_NULLPTR) {
Node *z = d->createNode(akey, avalue, prev, false);
return iterator(z);
}
- if (next->left == 0) {
+ if (next->left == Q_NULLPTR) {
Node *z = d->createNode(akey, avalue, next, true);
return iterator(z);
}
- Q_ASSERT(false); // We should have prev->right == 0 or next->left == 0.
+ Q_ASSERT(false); // We should have prev->right == Q_NULLPTR or next->left == Q_NULLPTR.
return this->insert(akey, avalue);
}
}
@@ -759,7 +784,7 @@ Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator QMap<Key, T>::insertMulti(cons
Node* y = d->end();
Node* x = static_cast<Node *>(d->root());
bool left = true;
- while (x != 0) {
+ while (x != Q_NULLPTR) {
left = !qMapLessThanKey(x->key, akey);
y = x;
x = left ? x->leftNode() : x->rightNode();
@@ -806,15 +831,15 @@ typename QMap<Key, T>::iterator QMap<Key, T>::insertMulti(const_iterator pos, co
return this->insertMulti(akey, avalue); // ignore hint
// Hint is ok - do insert
- if (prev->right == 0) {
+ if (prev->right == Q_NULLPTR) {
Node *z = d->createNode(akey, avalue, prev, false);
return iterator(z);
}
- if (next->left == 0) {
+ if (next->left == Q_NULLPTR) {
Node *z = d->createNode(akey, avalue, next, true);
return iterator(z);
}
- Q_ASSERT(false); // We should have prev->right == 0 or next->left == 0.
+ Q_ASSERT(false); // We should have prev->right == Q_NULLPTR or next->left == Q_NULLPTR.
return this->insertMulti(akey, avalue);
}
}
@@ -864,6 +889,15 @@ QPair<typename QMap<Key, T>::iterator, typename QMap<Key, T>::iterator> QMap<Key
return QPair<iterator, iterator>(iterator(firstNode), iterator(lastNode));
}
+template <class Key, class T>
+QPair<typename QMap<Key, T>::const_iterator, typename QMap<Key, T>::const_iterator>
+QMap<Key, T>::equal_range(const Key &akey) const
+{
+ Node *firstNode, *lastNode;
+ d->nodeRange(akey, &firstNode, &lastNode);
+ return qMakePair(const_iterator(firstNode), const_iterator(lastNode));
+}
+
#ifdef Q_MAP_DEBUG
template <class Key, class T>
void QMap<Key, T>::dump() const
@@ -1051,7 +1085,7 @@ Q_OUTOFLINE_TEMPLATE QList<T> QMap<Key, T>::values(const Key &akey) const
template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::const_iterator QMap<Key, T>::lowerBound(const Key &akey) const
{
- Node *lb = d->root() ? d->root()->lowerBound(akey) : 0;
+ Node *lb = d->root() ? d->root()->lowerBound(akey) : Q_NULLPTR;
if (!lb)
lb = d->end();
return const_iterator(lb);
@@ -1061,7 +1095,7 @@ template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator QMap<Key, T>::lowerBound(const Key &akey)
{
detach();
- Node *lb = d->root() ? d->root()->lowerBound(akey) : 0;
+ Node *lb = d->root() ? d->root()->lowerBound(akey) : Q_NULLPTR;
if (!lb)
lb = d->end();
return iterator(lb);
@@ -1071,7 +1105,7 @@ template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::const_iterator
QMap<Key, T>::upperBound(const Key &akey) const
{
- Node *ub = d->root() ? d->root()->upperBound(akey) : 0;
+ Node *ub = d->root() ? d->root()->upperBound(akey) : Q_NULLPTR;
if (!ub)
ub = d->end();
return const_iterator(ub);
@@ -1081,7 +1115,7 @@ template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator QMap<Key, T>::upperBound(const Key &akey)
{
detach();
- Node *ub = d->root() ? d->root()->upperBound(akey) : 0;
+ Node *ub = d->root() ? d->root()->upperBound(akey) : Q_NULLPTR;
if (!ub)
ub = d->end();
return iterator(ub);
diff --git a/src/corelib/tools/qqueue.cpp b/src/corelib/tools/qqueue.cpp
index 65b50c4e03..a8b5051616 100644
--- a/src/corelib/tools/qqueue.cpp
+++ b/src/corelib/tools/qqueue.cpp
@@ -71,19 +71,6 @@
*/
/*!
- \fn QQueue::QQueue()
-
- Constructs an empty queue.
-*/
-
-/*!
- \fn QQueue::~QQueue()
-
- Destroys the queue. References to the values in the queue, and all
- iterators over this queue, become invalid.
-*/
-
-/*!
\fn void QQueue::swap(QQueue<T> &other)
\since 4.8
diff --git a/src/corelib/tools/qqueue.h b/src/corelib/tools/qqueue.h
index 9d5bda1210..7a7abab070 100644
--- a/src/corelib/tools/qqueue.h
+++ b/src/corelib/tools/qqueue.h
@@ -43,8 +43,7 @@ template <class T>
class QQueue : public QList<T>
{
public:
- inline QQueue() {}
- inline ~QQueue() {}
+ // compiler-generated special member functions are fine!
inline void swap(QQueue<T> &other) { QList<T>::swap(other); } // prevent QList<->QQueue swaps
#ifndef Q_QDOC
// bring in QList::swap(int, int). We cannot say using QList<T>::swap,
diff --git a/src/corelib/tools/qrect.cpp b/src/corelib/tools/qrect.cpp
index b2174745e4..847f650a70 100644
--- a/src/corelib/tools/qrect.cpp
+++ b/src/corelib/tools/qrect.cpp
@@ -2403,7 +2403,6 @@ QRect QRectF::toAlignedRect() const Q_DECL_NOTHROW
/*!
\fn QRectF QRectF::marginsAdded(const QMarginsF &margins) const
- \relates QRectF
\since 5.3
Returns a rectangle grown by the \a margins.
@@ -2413,7 +2412,6 @@ QRect QRectF::toAlignedRect() const Q_DECL_NOTHROW
/*!
\fn QRectF QRectF::marginsRemoved(const QMarginsF &margins) const
- \relates QRectF
\since 5.3
Removes the \a margins from the rectangle, shrinking it.
@@ -2423,7 +2421,6 @@ QRect QRectF::toAlignedRect() const Q_DECL_NOTHROW
/*!
\fn QRectF QRectF::operator+=(const QMarginsF &margins)
- \relates QRectF
\since 5.3
Adds the \a margins to the rectangle, growing it.
@@ -2433,7 +2430,6 @@ QRect QRectF::toAlignedRect() const Q_DECL_NOTHROW
/*!
\fn QRectF QRectF::operator-=(const QMarginsF &margins)
- \relates QRectF
\since 5.3
Returns a rectangle shrunk by the \a margins.
diff --git a/src/corelib/tools/qregexp.cpp b/src/corelib/tools/qregexp.cpp
index f896828e2e..c52e4b5a7c 100644
--- a/src/corelib/tools/qregexp.cpp
+++ b/src/corelib/tools/qregexp.cpp
@@ -38,6 +38,7 @@
#include "qcache.h"
#include "qdatastream.h"
#include "qdebug.h"
+#include "qhashfunctions.h"
#include "qlist.h"
#include "qmap.h"
#include "qmutex.h"
@@ -886,6 +887,15 @@ static bool operator==(const QRegExpEngineKey &key1, const QRegExpEngineKey &key
&& key1.cs == key2.cs;
}
+static uint qHash(const QRegExpEngineKey &key, uint seed = 0) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(seed, key.pattern);
+ seed = hash(seed, key.patternSyntax);
+ seed = hash(seed, key.cs);
+ return seed;
+}
+
class QRegExpEngine;
//Q_DECLARE_TYPEINFO(QVector<int>, Q_MOVABLE_TYPE);
@@ -1019,9 +1029,6 @@ class QRegExpCharClass
{
public:
QRegExpCharClass();
- inline QRegExpCharClass(const QRegExpCharClass &cc) { operator=(cc); }
-
- QRegExpCharClass &operator=(const QRegExpCharClass &cc);
void clear();
bool negative() const { return n; }
@@ -2319,17 +2326,6 @@ QRegExpCharClass::QRegExpCharClass()
#endif
}
-QRegExpCharClass &QRegExpCharClass::operator=(const QRegExpCharClass &cc)
-{
- c = cc.c;
- r = cc.r;
- n = cc.n;
-#ifndef QT_NO_REGEXP_OPTIM
- occ1 = cc.occ1;
-#endif
- return *this;
-}
-
void QRegExpCharClass::clear()
{
c = 0;
@@ -3811,11 +3807,6 @@ struct QRegExpPrivate
};
#if !defined(QT_NO_REGEXP_OPTIM)
-uint qHash(const QRegExpEngineKey &key, uint seed = 0) Q_DECL_NOTHROW
-{
- return qHash(key.pattern, seed);
-}
-
typedef QCache<QRegExpEngineKey, QRegExpEngine> EngineCache;
Q_GLOBAL_STATIC(EngineCache, globalEngineCache)
static QBasicMutex globalEngineCacheMutex;
@@ -4037,6 +4028,21 @@ bool QRegExp::operator==(const QRegExp &rx) const
}
/*!
+ \since 5.6
+ \relates QRegExp
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QRegExp &key, uint seed) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(seed, key.priv->engineKey);
+ seed = hash(seed, key.priv->minimal);
+ return seed;
+}
+
+/*!
\fn bool QRegExp::operator!=(const QRegExp &rx) const
Returns \c true if this regular expression is not equal to \a rx;
diff --git a/src/corelib/tools/qregexp.h b/src/corelib/tools/qregexp.h
index b08a8bd282..f384e6c51f 100644
--- a/src/corelib/tools/qregexp.h
+++ b/src/corelib/tools/qregexp.h
@@ -45,6 +45,9 @@ QT_BEGIN_NAMESPACE
struct QRegExpPrivate;
class QStringList;
+class QRegExp;
+
+Q_CORE_EXPORT uint qHash(const QRegExp &key, uint seed = 0) Q_DECL_NOTHROW;
class Q_CORE_EXPORT QRegExp
{
@@ -104,6 +107,8 @@ public:
static QString escape(const QString &str);
+ friend Q_CORE_EXPORT uint qHash(const QRegExp &key, uint seed) Q_DECL_NOTHROW;
+
private:
QRegExpPrivate *priv;
};
diff --git a/src/corelib/tools/qregularexpression.cpp b/src/corelib/tools/qregularexpression.cpp
index 070e68154f..d8b0bf6e9f 100644
--- a/src/corelib/tools/qregularexpression.cpp
+++ b/src/corelib/tools/qregularexpression.cpp
@@ -38,6 +38,7 @@
#ifndef QT_NO_REGULAREXPRESSION
#include <QtCore/qcoreapplication.h>
+#include <QtCore/qhashfunctions.h>
#include <QtCore/qmutex.h>
#include <QtCore/qvector.h>
#include <QtCore/qstringlist.h>
@@ -1842,6 +1843,21 @@ bool QRegularExpression::operator==(const QRegularExpression &re) const
*/
/*!
+ \since 5.6
+ \relates QRegularExpression
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QRegularExpression &key, uint seed) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(seed, key.d->pattern);
+ seed = hash(seed, key.d->patternOptions);
+ return seed;
+}
+
+/*!
Escapes all characters of \a str so that they no longer have any special
meaning when used as a regular expression pattern string, and returns
the escaped string. For instance:
@@ -2109,7 +2125,8 @@ QStringRef QRegularExpressionMatch::capturedRef(const QString &name) const
QStringList QRegularExpressionMatch::capturedTexts() const
{
QStringList texts;
- for (int i = 0; i <= lastCapturedIndex(); ++i)
+ texts.reserve(d->capturedCount);
+ for (int i = 0; i < d->capturedCount; ++i)
texts << captured(i);
return texts;
}
diff --git a/src/corelib/tools/qregularexpression.h b/src/corelib/tools/qregularexpression.h
index d2abfc7701..2bca6a211b 100644
--- a/src/corelib/tools/qregularexpression.h
+++ b/src/corelib/tools/qregularexpression.h
@@ -49,6 +49,9 @@ QT_BEGIN_NAMESPACE
class QRegularExpressionMatch;
class QRegularExpressionMatchIterator;
struct QRegularExpressionPrivate;
+class QRegularExpression;
+
+Q_CORE_EXPORT uint qHash(const QRegularExpression &key, uint seed = 0) Q_DECL_NOTHROW;
class Q_CORE_EXPORT QRegularExpression
{
@@ -139,6 +142,7 @@ private:
friend class QRegularExpressionMatch;
friend struct QRegularExpressionMatchPrivate;
friend class QRegularExpressionMatchIterator;
+ friend Q_CORE_EXPORT uint qHash(const QRegularExpression &key, uint seed) Q_DECL_NOTHROW;
QRegularExpression(QRegularExpressionPrivate &dd);
QExplicitlySharedDataPointer<QRegularExpressionPrivate> d;
diff --git a/src/corelib/tools/qringbuffer.cpp b/src/corelib/tools/qringbuffer.cpp
new file mode 100644
index 0000000000..85cfdaf129
--- /dev/null
+++ b/src/corelib/tools/qringbuffer.cpp
@@ -0,0 +1,314 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Alex Trotsenko <alex1973tr@gmail.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "private/qringbuffer_p.h"
+#include "private/qbytearray_p.h"
+#include <string.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \internal
+
+ Access the bytes at a specified position the out-variable length will
+ contain the amount of bytes readable from there, e.g. the amount still
+ the same QByteArray
+*/
+const char *QRingBuffer::readPointerAtPosition(qint64 pos, qint64 &length) const
+{
+ if (pos >= 0) {
+ pos += head;
+ for (int i = 0; i < buffers.size(); ++i) {
+ length = (i == tailBuffer ? tail : buffers[i].size());
+ if (length > pos) {
+ length -= pos;
+ return buffers[i].constData() + pos;
+ }
+ pos -= length;
+ }
+ }
+
+ length = 0;
+ return 0;
+}
+
+void QRingBuffer::free(qint64 bytes)
+{
+ while (bytes > 0) {
+ const qint64 blockSize = buffers.first().size() - head;
+
+ if (tailBuffer == 0 || blockSize > bytes) {
+ // keep a single block around if it does not exceed
+ // the basic block size, to avoid repeated allocations
+ // between uses of the buffer
+ if (bufferSize <= bytes) {
+ if (buffers.first().size() <= basicBlockSize) {
+ bufferSize = 0;
+ head = tail = 0;
+ } else {
+ clear(); // try to minify/squeeze us
+ }
+ } else {
+ Q_ASSERT(bytes < MaxByteArraySize);
+ head += int(bytes);
+ bufferSize -= bytes;
+ }
+ return;
+ }
+
+ bufferSize -= blockSize;
+ bytes -= blockSize;
+ buffers.removeFirst();
+ --tailBuffer;
+ head = 0;
+ }
+}
+
+char *QRingBuffer::reserve(qint64 bytes)
+{
+ if (bytes <= 0 || bytes >= MaxByteArraySize)
+ return 0;
+
+ const qint64 newSize = bytes + tail;
+ // if need buffer reallocation
+ if (newSize > buffers.last().size()) {
+ if (newSize > buffers.last().capacity() && (tail >= basicBlockSize
+ || newSize >= MaxByteArraySize)) {
+ // shrink this buffer to its current size
+ buffers.last().resize(tail);
+
+ // create a new QByteArray
+ buffers.append(QByteArray());
+ ++tailBuffer;
+ tail = 0;
+ }
+ buffers.last().resize(qMax(basicBlockSize, tail + int(bytes)));
+ }
+
+ char *writePtr = buffers.last().data() + tail;
+ bufferSize += bytes;
+ Q_ASSERT(bytes < MaxByteArraySize);
+ tail += int(bytes);
+ return writePtr;
+}
+
+/*!
+ \internal
+
+ Allocate data at buffer head
+*/
+char *QRingBuffer::reserveFront(qint64 bytes)
+{
+ if (bytes <= 0 || bytes >= MaxByteArraySize)
+ return 0;
+
+ if (head < bytes) {
+ buffers.first().remove(0, head);
+ if (tailBuffer == 0)
+ tail -= head;
+
+ head = qMax(basicBlockSize, int(bytes));
+ if (bufferSize == 0) {
+ tail = head;
+ } else {
+ buffers.prepend(QByteArray());
+ ++tailBuffer;
+ }
+ buffers.first().resize(head);
+ }
+
+ head -= int(bytes);
+ bufferSize += bytes;
+ return buffers.first().data() + head;
+}
+
+void QRingBuffer::chop(qint64 bytes)
+{
+ while (bytes > 0) {
+ if (tailBuffer == 0 || tail > bytes) {
+ // keep a single block around if it does not exceed
+ // the basic block size, to avoid repeated allocations
+ // between uses of the buffer
+ if (bufferSize <= bytes) {
+ if (buffers.first().size() <= basicBlockSize) {
+ bufferSize = 0;
+ head = tail = 0;
+ } else {
+ clear(); // try to minify/squeeze us
+ }
+ } else {
+ Q_ASSERT(bytes < MaxByteArraySize);
+ tail -= int(bytes);
+ bufferSize -= bytes;
+ }
+ return;
+ }
+
+ bufferSize -= tail;
+ bytes -= tail;
+ buffers.removeLast();
+ --tailBuffer;
+ tail = buffers.last().size();
+ }
+}
+
+void QRingBuffer::clear()
+{
+ buffers.erase(buffers.begin() + 1, buffers.end());
+ buffers.first().clear();
+
+ head = tail = 0;
+ tailBuffer = 0;
+ bufferSize = 0;
+}
+
+qint64 QRingBuffer::indexOf(char c, qint64 maxLength) const
+{
+ qint64 index = 0;
+ qint64 j = head;
+ for (int i = 0; index < maxLength && i < buffers.size(); ++i) {
+ const char *ptr = buffers[i].constData() + j;
+ j = qMin(index + (i == tailBuffer ? tail : buffers[i].size()) - j, maxLength);
+
+ while (index < j) {
+ if (*ptr++ == c)
+ return index;
+ ++index;
+ }
+ j = 0;
+ }
+ return -1;
+}
+
+qint64 QRingBuffer::read(char *data, qint64 maxLength)
+{
+ const qint64 bytesToRead = qMin(size(), maxLength);
+ qint64 readSoFar = 0;
+ while (readSoFar < bytesToRead) {
+ const qint64 bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
+ nextDataBlockSize());
+ if (data)
+ memcpy(data + readSoFar, readPointer(), bytesToReadFromThisBlock);
+ readSoFar += bytesToReadFromThisBlock;
+ free(bytesToReadFromThisBlock);
+ }
+ return readSoFar;
+}
+
+/*!
+ \internal
+
+ Read an unspecified amount (will read the first buffer)
+*/
+QByteArray QRingBuffer::read()
+{
+ if (bufferSize == 0)
+ return QByteArray();
+
+ QByteArray qba(buffers.takeFirst());
+
+ qba.reserve(0); // avoid that resizing needlessly reallocates
+ if (tailBuffer == 0) {
+ qba.resize(tail);
+ tail = 0;
+ buffers.append(QByteArray());
+ } else {
+ --tailBuffer;
+ }
+ qba.remove(0, head); // does nothing if head is 0
+ head = 0;
+ bufferSize -= qba.size();
+ return qba;
+}
+
+/*!
+ \internal
+
+ Peek the bytes from a specified position
+*/
+qint64 QRingBuffer::peek(char *data, qint64 maxLength, qint64 pos) const
+{
+ qint64 readSoFar = 0;
+
+ if (pos >= 0) {
+ pos += head;
+ for (int i = 0; readSoFar < maxLength && i < buffers.size(); ++i) {
+ qint64 blockLength = (i == tailBuffer ? tail : buffers[i].size());
+
+ if (pos < blockLength) {
+ blockLength = qMin(blockLength - pos, maxLength - readSoFar);
+ memcpy(data + readSoFar, buffers[i].constData() + pos, blockLength);
+ readSoFar += blockLength;
+ pos = 0;
+ } else {
+ pos -= blockLength;
+ }
+ }
+ }
+
+ return readSoFar;
+}
+
+/*!
+ \internal
+
+ Append a new buffer to the end
+*/
+void QRingBuffer::append(const QByteArray &qba)
+{
+ if (tail == 0) {
+ buffers.last() = qba;
+ } else {
+ buffers.last().resize(tail);
+ buffers.append(qba);
+ ++tailBuffer;
+ }
+ tail = qba.size();
+ bufferSize += tail;
+}
+
+qint64 QRingBuffer::readLine(char *data, qint64 maxLength)
+{
+ if (!data || --maxLength <= 0)
+ return -1;
+
+ qint64 i = indexOf('\n', maxLength);
+ i = read(data, i >= 0 ? (i + 1) : maxLength);
+
+ // Terminate it.
+ data[i] = '\0';
+ return i;
+}
+
+QT_END_NAMESPACE
diff --git a/src/corelib/tools/qringbuffer_p.h b/src/corelib/tools/qringbuffer_p.h
index ead85e9da0..68509a6a80 100644
--- a/src/corelib/tools/qringbuffer_p.h
+++ b/src/corelib/tools/qringbuffer_p.h
@@ -58,7 +58,7 @@ public:
buffers.append(QByteArray());
}
- inline int nextDataBlockSize() const {
+ inline qint64 nextDataBlockSize() const {
return (tailBuffer == 0 ? tail : buffers.first().size()) - head;
}
@@ -66,112 +66,17 @@ public:
return bufferSize == 0 ? Q_NULLPTR : (buffers.first().constData() + head);
}
- // access the bytes at a specified position
- // the out-variable length will contain the amount of bytes readable
- // from there, e.g. the amount still the same QByteArray
- inline const char *readPointerAtPosition(qint64 pos, qint64 &length) const {
- if (pos >= 0) {
- pos += head;
- for (int i = 0; i < buffers.size(); ++i) {
- length = (i == tailBuffer ? tail : buffers[i].size());
- if (length > pos) {
- length -= pos;
- return buffers[i].constData() + pos;
- }
- pos -= length;
- }
- }
-
- length = 0;
- return 0;
- }
-
- inline void free(int bytes) {
- while (bytes > 0) {
- int blockSize = buffers.first().size() - head;
-
- if (tailBuffer == 0 || blockSize > bytes) {
- // keep a single block around if it does not exceed
- // the basic block size, to avoid repeated allocations
- // between uses of the buffer
- if (bufferSize <= bytes) {
- if (buffers.first().size() <= basicBlockSize) {
- bufferSize = 0;
- head = tail = 0;
- } else {
- clear(); // try to minify/squeeze us
- }
- } else {
- head += bytes;
- bufferSize -= bytes;
- }
- return;
- }
-
- bufferSize -= blockSize;
- bytes -= blockSize;
- buffers.removeFirst();
- --tailBuffer;
- head = 0;
- }
- }
-
- inline char *reserve(int bytes) {
- if (bytes <= 0)
- return 0;
-
- // if need buffer reallocation
- if (tail + bytes > buffers.last().size()) {
- if (tail + bytes > buffers.last().capacity() && tail >= basicBlockSize) {
- // shrink this buffer to its current size
- buffers.last().resize(tail);
-
- // create a new QByteArray
- buffers.append(QByteArray());
- ++tailBuffer;
- tail = 0;
- }
- buffers.last().resize(qMax(basicBlockSize, tail + bytes));
- }
+ Q_CORE_EXPORT const char *readPointerAtPosition(qint64 pos, qint64 &length) const;
+ Q_CORE_EXPORT void free(qint64 bytes);
+ Q_CORE_EXPORT char *reserve(qint64 bytes);
+ Q_CORE_EXPORT char *reserveFront(qint64 bytes);
- char *writePtr = buffers.last().data() + tail;
- bufferSize += bytes;
- tail += bytes;
- return writePtr;
- }
-
- inline void truncate(int pos) {
+ inline void truncate(qint64 pos) {
if (pos < size())
chop(size() - pos);
}
- inline void chop(int bytes) {
- while (bytes > 0) {
- if (tailBuffer == 0 || tail > bytes) {
- // keep a single block around if it does not exceed
- // the basic block size, to avoid repeated allocations
- // between uses of the buffer
- if (bufferSize <= bytes) {
- if (buffers.first().size() <= basicBlockSize) {
- bufferSize = 0;
- head = tail = 0;
- } else {
- clear(); // try to minify/squeeze us
- }
- } else {
- tail -= bytes;
- bufferSize -= bytes;
- }
- return;
- }
-
- bufferSize -= tail;
- bytes -= tail;
- buffers.removeLast();
- --tailBuffer;
- tail = buffers.last().size();
- }
- }
+ Q_CORE_EXPORT void chop(qint64 bytes);
inline bool isEmpty() const {
return bufferSize == 0;
@@ -190,131 +95,36 @@ public:
*ptr = c;
}
- inline void ungetChar(char c) {
- --head;
- if (head < 0) {
- if (bufferSize != 0) {
- buffers.prepend(QByteArray());
- ++tailBuffer;
- } else {
- tail = basicBlockSize;
- }
- buffers.first().resize(basicBlockSize);
- head = basicBlockSize - 1;
- }
- buffers.first()[head] = c;
- ++bufferSize;
- }
-
- inline int size() const {
- return bufferSize;
- }
-
- inline void clear() {
- buffers.erase(buffers.begin() + 1, buffers.end());
- buffers.first().clear();
-
- head = tail = 0;
- tailBuffer = 0;
- bufferSize = 0;
- }
-
- inline int indexOf(char c) const {
- int index = 0;
- int j = head;
- for (int i = 0; i < buffers.size(); ++i) {
- const char *ptr = buffers[i].constData() + j;
- j = index + (i == tailBuffer ? tail : buffers[i].size()) - j;
-
- while (index < j) {
- if (*ptr++ == c)
- return index;
- ++index;
- }
- j = 0;
- }
- return -1;
- }
-
- inline int indexOf(char c, int maxLength) const {
- int index = 0;
- int j = head;
- for (int i = 0; index < maxLength && i < buffers.size(); ++i) {
- const char *ptr = buffers[i].constData() + j;
- j = qMin(index + (i == tailBuffer ? tail : buffers[i].size()) - j, maxLength);
-
- while (index < j) {
- if (*ptr++ == c)
- return index;
- ++index;
- }
- j = 0;
- }
- return -1;
- }
-
- inline int read(char *data, int maxLength) {
- int bytesToRead = qMin(size(), maxLength);
- int readSoFar = 0;
- while (readSoFar < bytesToRead) {
- int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar, nextDataBlockSize());
- if (data)
- memcpy(data + readSoFar, readPointer(), bytesToReadFromThisBlock);
- readSoFar += bytesToReadFromThisBlock;
- free(bytesToReadFromThisBlock);
+ void ungetChar(char c)
+ {
+ if (head > 0) {
+ --head;
+ buffers.first()[head] = c;
+ ++bufferSize;
+ } else {
+ char *ptr = reserveFront(1);
+ *ptr = c;
}
- return readSoFar;
}
- // read an unspecified amount (will read the first buffer)
- inline QByteArray read() {
- if (bufferSize == 0)
- return QByteArray();
- QByteArray qba(buffers.takeFirst());
-
- qba.reserve(0); // avoid that resizing needlessly reallocates
- if (tailBuffer == 0) {
- qba.resize(tail);
- tail = 0;
- buffers.append(QByteArray());
- } else {
- --tailBuffer;
- }
- qba.remove(0, head); // does nothing if head is 0
- head = 0;
- bufferSize -= qba.size();
- return qba;
+ inline qint64 size() const {
+ return bufferSize;
}
- // append a new buffer to the end
- inline void append(const QByteArray &qba) {
- if (tail == 0) {
- buffers.last() = qba;
- } else {
- buffers.last().resize(tail);
- buffers.append(qba);
- ++tailBuffer;
- }
- tail = qba.size();
- bufferSize += tail;
- }
+ Q_CORE_EXPORT void clear();
+ inline qint64 indexOf(char c) const { return indexOf(c, size()); }
+ Q_CORE_EXPORT qint64 indexOf(char c, qint64 maxLength) const;
+ Q_CORE_EXPORT qint64 read(char *data, qint64 maxLength);
+ Q_CORE_EXPORT QByteArray read();
+ Q_CORE_EXPORT qint64 peek(char *data, qint64 maxLength, qint64 pos = 0) const;
+ Q_CORE_EXPORT void append(const QByteArray &qba);
- inline int skip(int length) {
+ inline qint64 skip(qint64 length) {
return read(0, length);
}
- inline int readLine(char *data, int maxLength) {
- if (!data || --maxLength <= 0)
- return -1;
-
- int i = indexOf('\n', maxLength);
- i = read(data, i >= 0 ? (i + 1) : maxLength);
-
- // Terminate it.
- data[i] = '\0';
- return i;
- }
+ Q_CORE_EXPORT qint64 readLine(char *data, qint64 maxLength);
inline bool canReadLine() const {
return indexOf('\n') >= 0;
@@ -325,7 +135,7 @@ private:
int head, tail;
int tailBuffer; // always buffers.size() - 1
const int basicBlockSize;
- int bufferSize;
+ qint64 bufferSize;
};
QT_END_NAMESPACE
diff --git a/src/corelib/tools/qscopedpointer.h b/src/corelib/tools/qscopedpointer.h
index 819ab00584..8d478f81f9 100644
--- a/src/corelib/tools/qscopedpointer.h
+++ b/src/corelib/tools/qscopedpointer.h
@@ -91,7 +91,7 @@ class QScopedPointer
{
typedef T *QScopedPointer:: *RestrictedBool;
public:
- explicit inline QScopedPointer(T *p = 0) : d(p)
+ explicit inline QScopedPointer(T *p = Q_NULLPTR) : d(p)
{
}
@@ -121,12 +121,12 @@ public:
#if defined(Q_QDOC)
inline operator bool() const
{
- return isNull() ? 0 : &QScopedPointer::d;
+ return isNull() ? Q_NULLPTR : &QScopedPointer::d;
}
#else
inline operator RestrictedBool() const
{
- return isNull() ? 0 : &QScopedPointer::d;
+ return isNull() ? Q_NULLPTR : &QScopedPointer::d;
}
#endif
@@ -140,7 +140,7 @@ public:
return !d;
}
- inline void reset(T *other = 0)
+ inline void reset(T *other = Q_NULLPTR)
{
if (d == other)
return;
@@ -152,7 +152,7 @@ public:
inline T *take()
{
T *oldD = d;
- d = 0;
+ d = Q_NULLPTR;
return oldD;
}
@@ -206,10 +206,10 @@ template <typename T, typename Cleanup = QScopedPointerArrayDeleter<T> >
class QScopedArrayPointer : public QScopedPointer<T, Cleanup>
{
public:
- inline QScopedArrayPointer() : QScopedPointer<T, Cleanup>(0) {}
+ inline QScopedArrayPointer() : QScopedPointer<T, Cleanup>(Q_NULLPTR) {}
template <typename D>
- explicit inline QScopedArrayPointer(D *p, typename QtPrivate::QScopedArrayEnsureSameType<T,D>::Type = 0)
+ explicit inline QScopedArrayPointer(D *p, typename QtPrivate::QScopedArrayEnsureSameType<T,D>::Type = Q_NULLPTR)
: QScopedPointer<T, Cleanup>(p)
{
}
diff --git a/src/corelib/tools/qset.h b/src/corelib/tools/qset.h
index e4688711d6..aeba6cf68d 100644
--- a/src/corelib/tools/qset.h
+++ b/src/corelib/tools/qset.h
@@ -57,15 +57,9 @@ public:
insert(*it);
}
#endif
- inline QSet(const QSet<T> &other) : q_hash(other.q_hash) {}
-
- inline QSet<T> &operator=(const QSet<T> &other)
- { q_hash = other.q_hash; return *this; }
-#ifdef Q_COMPILER_RVALUE_REFS
- inline QSet(QSet &&other) : q_hash(qMove(other.q_hash)) {}
- inline QSet<T> &operator=(QSet<T> &&other)
- { qSwap(q_hash, other.q_hash); return *this; }
-#endif
+ // compiler-generated copy/move ctor/assignment operators are fine!
+ // compiler-generated destructor is fine!
+
inline void swap(QSet<T> &other) { q_hash.swap(other.q_hash); }
inline bool operator==(const QSet<T> &other) const
@@ -137,6 +131,7 @@ public:
typedef QHash<T, QHashDummyValue> Hash;
typename Hash::const_iterator i;
friend class iterator;
+ friend class QSet<T>;
public:
typedef std::bidirectional_iterator_tag iterator_category;
@@ -191,6 +186,7 @@ public:
inline const_iterator constFind(const T &value) const { return find(value); }
QSet<T> &unite(const QSet<T> &other);
QSet<T> &intersect(const QSet<T> &other);
+ bool intersects(const QSet<T> &other) const;
QSet<T> &subtract(const QSet<T> &other);
// STL compatibility
@@ -284,6 +280,34 @@ Q_INLINE_TEMPLATE QSet<T> &QSet<T>::intersect(const QSet<T> &other)
}
template <class T>
+Q_INLINE_TEMPLATE bool QSet<T>::intersects(const QSet<T> &other) const
+{
+ const bool otherIsBigger = other.size() > size();
+ const QSet &smallestSet = otherIsBigger ? *this : other;
+ const QSet &biggestSet = otherIsBigger ? other : *this;
+ const bool equalSeeds = q_hash.d->seed == other.q_hash.d->seed;
+ typename QSet::const_iterator i = smallestSet.cbegin();
+ typename QSet::const_iterator e = smallestSet.cend();
+
+ if (Q_LIKELY(equalSeeds)) {
+ // If seeds are equal we take the fast path so no hash is recalculated.
+ while (i != e) {
+ if (*biggestSet.q_hash.findNode(*i, i.i.i->h) != biggestSet.q_hash.e)
+ return true;
+ ++i;
+ }
+ } else {
+ while (i != e) {
+ if (biggestSet.contains(*i))
+ return true;
+ ++i;
+ }
+ }
+
+ return false;
+}
+
+template <class T>
Q_INLINE_TEMPLATE QSet<T> &QSet<T>::subtract(const QSet<T> &other)
{
QSet<T> copy1(*this);
diff --git a/src/corelib/tools/qset.qdoc b/src/corelib/tools/qset.qdoc
index 072e65af0e..d91a589aa1 100644
--- a/src/corelib/tools/qset.qdoc
+++ b/src/corelib/tools/qset.qdoc
@@ -114,40 +114,6 @@
*/
/*!
- \fn QSet::QSet(const QSet<T> &other)
-
- Constructs a copy of \a other.
-
- This operation occurs in \l{constant time}, because QSet is
- \l{implicitly shared}. This makes returning a QSet from a
- function very fast. If a shared instance is modified, it will be
- copied (copy-on-write), and this takes \l{linear time}.
-
- \sa operator=()
-*/
-
-/*!
- \fn QSet::QSet(QSet && other)
-
- Move-constructs a QSet instance, making it point to the same object that
- \a other was pointing to.
-*/
-
-
-/*!
- \fn QSet<T> &QSet::operator=(const QSet<T> &other)
-
- Assigns the \a other set to this set and returns a reference to
- this set.
-*/
-
-/*!
- \fn QSet<T> &QSet::operator=(QSet<T> &&other)
-
- Move-assigns the \a other set to this set.
-*/
-
-/*!
\fn void QSet::swap(QSet<T> &other)
Swaps set \a other with this set. This operation is very fast and
@@ -504,7 +470,17 @@
Removes all items from this set that are not contained in the
\a other set. A reference to this set is returned.
- \sa operator&=(), unite(), subtract()
+ \sa intersects(), operator&=(), unite(), subtract()
+*/
+
+/*!
+ \fn bool QSet::intersects(const QSet<T> &other) const
+ \since 5.6
+
+ Returns \c true if this set has at least one item in common with
+ \a other.
+
+ \sa contains(), intersect()
*/
/*!
diff --git a/src/corelib/tools/qshareddata.h b/src/corelib/tools/qshareddata.h
index 9dd8fff9cb..6a0900cf3f 100644
--- a/src/corelib/tools/qshareddata.h
+++ b/src/corelib/tools/qshareddata.h
@@ -36,7 +36,10 @@
#include <QtCore/qglobal.h>
#include <QtCore/qatomic.h>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
+#include <QtCore/qhashfunctions.h>
QT_BEGIN_NAMESPACE
@@ -76,7 +79,7 @@ public:
inline bool operator==(const QSharedDataPointer<T> &other) const { return d == other.d; }
inline bool operator!=(const QSharedDataPointer<T> &other) const { return d != other.d; }
- inline QSharedDataPointer() { d = 0; }
+ inline QSharedDataPointer() { d = Q_NULLPTR; }
inline ~QSharedDataPointer() { if (d && !d->ref.deref()) delete d; }
explicit QSharedDataPointer(T *data) Q_DECL_NOTHROW;
@@ -142,17 +145,17 @@ public:
if(d && !d->ref.deref())
delete d;
- d = 0;
+ d = Q_NULLPTR;
}
- inline operator bool () const { return d != 0; }
+ inline operator bool () const { return d != Q_NULLPTR; }
inline bool operator==(const QExplicitlySharedDataPointer<T> &other) const { return d == other.d; }
inline bool operator!=(const QExplicitlySharedDataPointer<T> &other) const { return d != other.d; }
inline bool operator==(const T *ptr) const { return d == ptr; }
inline bool operator!=(const T *ptr) const { return d != ptr; }
- inline QExplicitlySharedDataPointer() { d = 0; }
+ inline QExplicitlySharedDataPointer() { d = Q_NULLPTR; }
inline ~QExplicitlySharedDataPointer() { if (d && !d->ref.deref()) delete d; }
explicit QExplicitlySharedDataPointer(T *data) Q_DECL_NOTHROW;
diff --git a/src/corelib/tools/qsharedpointer_impl.h b/src/corelib/tools/qsharedpointer_impl.h
index 9e6b48a97d..1323dd6b1c 100644
--- a/src/corelib/tools/qsharedpointer_impl.h
+++ b/src/corelib/tools/qsharedpointer_impl.h
@@ -55,7 +55,10 @@ QT_END_NAMESPACE
#include <new>
#include <QtCore/qatomic.h>
#include <QtCore/qobject.h> // for qobject_cast
-#include <QtCore/qhash.h> // for qHash
+#if QT_DEPRECATED_SINCE(5, 5)
+#include <QtCore/qhash.h>
+#endif
+#include <QtCore/qhashfunctions.h>
#if defined(Q_COMPILER_RVALUE_REFS) && defined(Q_COMPILER_VARIADIC_TEMPLATES)
# include <utility> // for std::forward
@@ -297,12 +300,12 @@ public:
inline T *data() const { return value; }
inline bool isNull() const { return !data(); }
- inline operator RestrictedBool() const { return isNull() ? 0 : &QSharedPointer::value; }
+ inline operator RestrictedBool() const { return isNull() ? Q_NULLPTR : &QSharedPointer::value; }
inline bool operator !() const { return isNull(); }
inline T &operator*() const { return *data(); }
inline T *operator->() const { return data(); }
- QSharedPointer() : value(0), d(0) { }
+ QSharedPointer() : value(Q_NULLPTR), d(Q_NULLPTR) { }
~QSharedPointer() { deref(); }
inline explicit QSharedPointer(T *ptr) : value(ptr) // noexcept
@@ -324,14 +327,32 @@ public:
inline QSharedPointer(QSharedPointer &&other)
: value(other.value), d(other.d)
{
- other.d = 0;
- other.value = 0;
+ other.d = Q_NULLPTR;
+ other.value = Q_NULLPTR;
}
inline QSharedPointer &operator=(QSharedPointer &&other)
{
- swap(other);
+ QSharedPointer moved(std::move(other));
+ swap(moved);
+ return *this;
+ }
+
+ template <class X>
+ QSharedPointer(QSharedPointer<X> &&other) Q_DECL_NOTHROW
+ : value(other.value), d(other.d)
+ {
+ other.d = Q_NULLPTR;
+ other.value = Q_NULLPTR;
+ }
+
+ template <class X>
+ QSharedPointer &operator=(QSharedPointer<X> &&other) Q_DECL_NOTHROW
+ {
+ QSharedPointer moved(std::move(other));
+ swap(moved);
return *this;
}
+
#endif
template <class X>
@@ -341,13 +362,13 @@ public:
template <class X>
inline QSharedPointer &operator=(const QSharedPointer<X> &other)
{
- QSHAREDPOINTER_VERIFY_AUTO_CAST(T, X); // if you get an error in this line, the cast is invalid
- internalCopy(other);
+ QSharedPointer copy(other);
+ swap(copy);
return *this;
}
template <class X>
- inline QSharedPointer(const QWeakPointer<X> &other) : value(0), d(0)
+ inline QSharedPointer(const QWeakPointer<X> &other) : value(Q_NULLPTR), d(Q_NULLPTR)
{ *this = other; }
template <class X>
@@ -463,9 +484,9 @@ public:
private:
explicit QSharedPointer(Qt::Initialization) {}
- inline void deref()
+ void deref() Q_DECL_NOTHROW
{ deref(d); }
- static inline void deref(Data *d)
+ static void deref(Data *d) Q_DECL_NOTHROW
{
if (!d) return;
if (!d->strongref.deref()) {
@@ -487,7 +508,7 @@ private:
inline void internalConstruct(T *ptr, Deleter deleter)
{
if (!ptr) {
- d = 0;
+ d = Q_NULLPTR;
return;
}
@@ -506,19 +527,7 @@ private:
enableSharedFromThis(ptr);
}
- template <class X>
- inline void internalCopy(const QSharedPointer<X> &other)
- {
- Data *o = other.d;
- T *actual = other.value;
- if (o)
- other.ref();
- qSwap(d, o);
- qSwap(this->value, actual);
- deref(o);
- }
-
- inline void internalSwap(QSharedPointer &other)
+ void internalSwap(QSharedPointer &other) Q_DECL_NOTHROW
{
qSwap(d, other.d);
qSwap(this->value, other.value);
@@ -531,7 +540,7 @@ public:
template <class X> friend class QWeakPointer;
template <class X, class Y> friend QSharedPointer<X> QtSharedPointer::copyAndSetPointer(X * ptr, const QSharedPointer<Y> &src);
#endif
- inline void ref() const { d->weakref.ref(); d->strongref.ref(); }
+ void ref() const Q_DECL_NOTHROW { d->weakref.ref(); d->strongref.ref(); }
inline void internalSet(Data *o, T *actual)
{
@@ -550,14 +559,14 @@ public:
o->weakref.ref();
} else {
o->checkQObjectShared(actual);
- o = 0;
+ o = Q_NULLPTR;
}
}
qSwap(d, o);
qSwap(this->value, actual);
if (!d || d->strongref.load() == 0)
- this->value = 0;
+ this->value = Q_NULLPTR;
// dereference saved data
deref(o);
@@ -582,19 +591,19 @@ public:
typedef const value_type &const_reference;
typedef qptrdiff difference_type;
- inline bool isNull() const { return d == 0 || d->strongref.load() == 0 || value == 0; }
- inline operator RestrictedBool() const { return isNull() ? 0 : &QWeakPointer::value; }
+ inline bool isNull() const { return d == Q_NULLPTR || d->strongref.load() == 0 || value == Q_NULLPTR; }
+ inline operator RestrictedBool() const { return isNull() ? Q_NULLPTR : &QWeakPointer::value; }
inline bool operator !() const { return isNull(); }
- inline T *data() const { return d == 0 || d->strongref.load() == 0 ? 0 : value; }
+ inline T *data() const { return d == Q_NULLPTR || d->strongref.load() == 0 ? Q_NULLPTR : value; }
- Q_DECL_CONSTEXPR inline QWeakPointer() : d(0), value(0) { }
+ inline QWeakPointer() : d(Q_NULLPTR), value(Q_NULLPTR) { }
inline ~QWeakPointer() { if (d && !d->weakref.deref()) delete d; }
#ifndef QT_NO_QOBJECT
// special constructor that is enabled only if X derives from QObject
#if QT_DEPRECATED_SINCE(5, 0)
template <class X>
- QT_DEPRECATED inline QWeakPointer(X *ptr) : d(ptr ? Data::getAndRef(ptr) : 0), value(ptr)
+ QT_DEPRECATED inline QWeakPointer(X *ptr) : d(ptr ? Data::getAndRef(ptr) : Q_NULLPTR), value(ptr)
{ }
#endif
#endif
@@ -628,7 +637,7 @@ public:
}
template <class X>
- inline QWeakPointer(const QWeakPointer<X> &o) : d(0), value(0)
+ inline QWeakPointer(const QWeakPointer<X> &o) : d(Q_NULLPTR), value(Q_NULLPTR)
{ *this = o; }
template <class X>
@@ -649,7 +658,7 @@ public:
{ return !(*this == o); }
template <class X>
- inline QWeakPointer(const QSharedPointer<X> &o) : d(0), value(0)
+ inline QWeakPointer(const QSharedPointer<X> &o) : d(Q_NULLPTR), value(Q_NULLPTR)
{ *this = o; }
template <class X>
@@ -693,7 +702,7 @@ public:
#ifndef QT_NO_QOBJECT
template <class X>
- inline QWeakPointer(X *ptr, bool) : d(ptr ? Data::getAndRef(ptr) : 0), value(ptr)
+ inline QWeakPointer(X *ptr, bool) : d(ptr ? Data::getAndRef(ptr) : Q_NULLPTR), value(ptr)
{ }
#endif
diff --git a/src/corelib/tools/qsimd.cpp b/src/corelib/tools/qsimd.cpp
index 4459d89e07..e7917ffdac 100644
--- a/src/corelib/tools/qsimd.cpp
+++ b/src/corelib/tools/qsimd.cpp
@@ -43,7 +43,9 @@
#if defined(Q_OS_WIN)
# if defined(Q_OS_WINCE)
# include <qt_windows.h>
-# include <cmnintrin.h>
+# if _WIN32_WCE < 0x800
+# include <cmnintrin.h>
+# endif
# endif
# if !defined(Q_CC_GNU)
# ifndef Q_OS_WINCE
diff --git a/src/corelib/tools/qsimd_p.h b/src/corelib/tools/qsimd_p.h
index dd93b4fd26..8523fb09c1 100644
--- a/src/corelib/tools/qsimd_p.h
+++ b/src/corelib/tools/qsimd_p.h
@@ -54,9 +54,9 @@
* for the x86 and ARM intrinsics:
* - GCC: the -mXXX or march=YYY flag is necessary before #include
* up to 4.8; GCC >= 4.9 can include unconditionally
+ * - Clang: same as GCC, with unconditional inclusion with version 3.7
* - Intel CC: #include can happen unconditionally
* - MSVC: #include can happen unconditionally
- * - RVCT: ???
*
* We will try to include all headers possible under this configuration.
*
@@ -138,7 +138,8 @@
#define QT_COMPILER_SUPPORTS(x) (QT_COMPILER_SUPPORTS_ ## x - 0)
#if (defined(Q_CC_INTEL) || defined(Q_CC_MSVC) \
- || (defined(Q_CC_GNU) && !defined(Q_CC_CLANG) && (__GNUC__-0) * 100 + (__GNUC_MINOR__-0) >= 409)) \
+ || (defined(Q_CC_GNU) && !defined(Q_CC_CLANG) && (__GNUC__-0) * 100 + (__GNUC_MINOR__-0) >= 409) \
+ || (defined(Q_CC_CLANG) && Q_CC_CLANG >= 307)) \
&& !defined(QT_BOOTSTRAPPED)
# define QT_COMPILER_SUPPORTS_SIMD_ALWAYS
# define QT_COMPILER_SUPPORTS_HERE(x) QT_COMPILER_SUPPORTS(x)
diff --git a/src/corelib/tools/qstack.cpp b/src/corelib/tools/qstack.cpp
index e367622c0d..224f72926b 100644
--- a/src/corelib/tools/qstack.cpp
+++ b/src/corelib/tools/qstack.cpp
@@ -71,19 +71,6 @@
*/
/*!
- \fn QStack::QStack()
-
- Constructs an empty stack.
-*/
-
-/*!
- \fn QStack::~QStack()
-
- Destroys the stack. References to the values in the stack, and all
- iterators over this stack, become invalid.
-*/
-
-/*!
\fn void QStack::swap(QStack<T> &other)
\since 4.8
diff --git a/src/corelib/tools/qstack.h b/src/corelib/tools/qstack.h
index fa05e22de1..278e89ca2f 100644
--- a/src/corelib/tools/qstack.h
+++ b/src/corelib/tools/qstack.h
@@ -43,8 +43,7 @@ template<class T>
class QStack : public QVector<T>
{
public:
- inline QStack() {}
- inline ~QStack() {}
+ // compiler-generated special member functions are fine!
inline void swap(QStack<T> &other) { QVector<T>::swap(other); } // prevent QVector<->QStack swaps
inline void push(const T &t) { QVector<T>::append(t); }
T pop();
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
index b623c62043..e3a3cc79c6 100644
--- a/src/corelib/tools/qstring.cpp
+++ b/src/corelib/tools/qstring.cpp
@@ -50,7 +50,6 @@
#include "qstringmatcher.h"
#include "qvarlengtharray.h"
#include "qtools_p.h"
-#include "qhash.h"
#include "qdebug.h"
#include "qendian.h"
#include "qcollator.h"
@@ -1201,6 +1200,22 @@ const QString::Null QString::null = { };
\sa QString::const_iterator
*/
+/*! \typedef QString::const_reverse_iterator
+ \since 5.6
+
+ This typedef provides an STL-style const reverse iterator for QString.
+
+ \sa QString::reverse_iterator, QString::const_iterator
+*/
+
+/*! \typedef QString::reverse_iterator
+ \since 5.6
+
+ This typedef provides an STL-style non-const reverse iterator for QString.
+
+ \sa QString::const_reverse_iterator, QString::iterator
+*/
+
/*!
\typedef QString::size_type
@@ -1304,6 +1319,52 @@ const QString::Null QString::null = { };
\sa constBegin(), end()
*/
+/*! \fn QString::reverse_iterator QString::rbegin()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ character in the string, in reverse order.
+
+ \sa begin(), crbegin(), rend()
+*/
+
+/*! \fn QString::const_reverse_iterator QString::rbegin() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QString::const_reverse_iterator QString::crbegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ character in the string, in reverse order.
+
+ \sa begin(), rbegin(), rend()
+*/
+
+/*! \fn QString::reverse_iterator QString::rend()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
+ the last character in the string, in reverse order.
+
+ \sa end(), crend(), rbegin()
+*/
+
+/*! \fn QString::const_reverse_iterator QString::rend() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QString::const_reverse_iterator QString::crend() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
+ past the last character in the string, in reverse order.
+
+ \sa end(), rend(), rbegin()
+*/
+
/*!
\fn QString::QString()
@@ -1828,6 +1889,51 @@ QString &QString::operator=(QChar ch)
/*!
+ \fn QString& QString::insert(int position, const QStringRef &str)
+ \since 5.5
+ \overload insert()
+
+ Inserts the string reference \a str at the given index \a position and
+ returns a reference to this string.
+
+ If the given \a position is greater than size(), the array is
+ first extended using resize().
+*/
+
+
+/*!
+ \fn QString& QString::insert(int position, const char *str)
+ \since 5.5
+ \overload insert()
+
+ Inserts the C string \a str at the given index \a position and
+ returns a reference to this string.
+
+ If the given \a position is greater than size(), the array is
+ first extended using resize().
+
+ This function is not available when QT_NO_CAST_FROM_ASCII is
+ defined.
+*/
+
+
+/*!
+ \fn QString& QString::insert(int position, const QByteArray &str)
+ \since 5.5
+ \overload insert()
+
+ Inserts the byte array \a str at the given index \a position and
+ returns a reference to this string.
+
+ If the given \a position is greater than size(), the array is
+ first extended using resize().
+
+ This function is not available when QT_NO_CAST_FROM_ASCII is
+ defined.
+*/
+
+
+/*!
\fn QString &QString::insert(int position, QLatin1String str)
\overload insert()
@@ -2027,6 +2133,22 @@ QString &QString::append(QChar ch)
Prepends the Latin-1 string \a str to this string.
*/
+/*! \fn QString &QString::prepend(const QChar *str, int len)
+ \since 5.5
+ \overload prepend()
+
+ Prepends \a len characters from the QChar array \a str to this string and
+ returns a reference to this string.
+*/
+
+/*! \fn QString &QString::prepend(const QStringRef &str)
+ \since 5.5
+ \overload prepend()
+
+ Prepends the string reference \a str to the beginning of this string and
+ returns a reference to this string.
+*/
+
/*! \fn QString &QString::prepend(const QByteArray &ba)
\overload prepend()
@@ -2558,6 +2680,8 @@ bool operator==(const QString &s1, const QString &s2)
/*!
\overload operator==()
+ Returns \c true if this string is equal to \a other; otherwise
+ returns \c false.
*/
bool QString::operator==(QLatin1String other) const
{
@@ -2616,7 +2740,7 @@ bool operator<(const QString &s1, const QString &s2)
}
/*!
\overload operator<()
- \relates QString
+
Returns \c true if this string is lexically less than the parameter
string called \a other; otherwise returns \c false.
*/
@@ -2659,9 +2783,9 @@ bool QString::operator<(QLatin1String other) const
go through QObject::tr(), for example.
*/
-/*! \fn bool QString::operator<=(const QString &s1, const QString &s2)
+/*! \fn bool operator<=(const QString &s1, const QString &s2)
- \relates Qstring
+ \relates QString
Returns \c true if string \a s1 is lexically less than or equal to
string \a s2; otherwise returns \c false.
@@ -2707,7 +2831,7 @@ bool QString::operator<(QLatin1String other) const
go through QObject::tr(), for example.
*/
-/*! \fn bool QString::operator>(const QString &s1, const QString &s2)
+/*! \fn bool operator>(const QString &s1, const QString &s2)
\relates QString
Returns \c true if string \a s1 is lexically greater than string \a s2;
@@ -2721,7 +2845,7 @@ bool QString::operator<(QLatin1String other) const
/*!
\overload operator>()
- \relates QString
+
Returns \c true if this string is lexically greater than the parameter
string \a other; otherwise returns \c false.
*/
@@ -3184,6 +3308,7 @@ struct QStringCapture
int len;
int no;
};
+Q_DECLARE_TYPEINFO(QStringCapture, Q_PRIMITIVE_TYPE);
#endif
#ifndef QT_NO_REGEXP
@@ -3491,9 +3616,14 @@ int QString::count(const QString &str, Qt::CaseSensitivity cs) const
}
/*!
- \overload count()
+ \overload count()
+
+ Returns the number of occurrences of character \a ch in the string.
- Returns the number of occurrences of character \a ch in the string.
+ If \a cs is Qt::CaseSensitive (default), the search is
+ case sensitive; otherwise the search is case insensitive.
+
+ \sa contains(), indexOf()
*/
int QString::count(QChar ch, Qt::CaseSensitivity cs) const
@@ -3939,10 +4069,9 @@ int QString::count(const QRegularExpression &re) const
QString QString::section(const QString &sep, int start, int end, SectionFlags flags) const
{
- QStringList sections = split(sep, KeepEmptyParts,
- (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
+ const QVector<QStringRef> sections = splitRef(sep, KeepEmptyParts,
+ (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
const int sectionsSize = sections.size();
-
if (!(flags & SectionSkipEmpty)) {
if (start < 0)
start += sectionsSize;
@@ -3962,11 +4091,10 @@ QString QString::section(const QString &sep, int start, int end, SectionFlags fl
if (start >= sectionsSize || end < 0 || start > end)
return QString();
- int x = 0;
QString ret;
int first_i = start, last_i = end;
- for (int i = 0; x <= end && i < sectionsSize; ++i) {
- QString section = sections.at(i);
+ for (int x = 0, i = 0; x <= end && i < sectionsSize; ++i) {
+ const QStringRef &section = sections.at(i);
const bool empty = section.isEmpty();
if (x >= start) {
if(x == start)
@@ -3991,9 +4119,9 @@ QString QString::section(const QString &sep, int start, int end, SectionFlags fl
class qt_section_chunk {
public:
qt_section_chunk() {}
- qt_section_chunk(int l, QString s) : length(l), string(qMove(s)) {}
+ qt_section_chunk(int l, QStringRef s) : length(l), string(qMove(s)) {}
int length;
- QString string;
+ QStringRef string;
};
Q_DECLARE_TYPEINFO(qt_section_chunk, Q_MOVABLE_TYPE);
@@ -4086,12 +4214,12 @@ QString QString::section(const QRegExp &reg, int start, int end, SectionFlags fl
QVector<qt_section_chunk> sections;
int n = length(), m = 0, last_m = 0, last_len = 0;
while ((m = sep.indexIn(*this, m)) != -1) {
- sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
+ sections.append(qt_section_chunk(last_len, QStringRef(this, last_m, m - last_m)));
last_m = m;
last_len = sep.matchedLength();
m += qMax(sep.matchedLength(), 1);
}
- sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
+ sections.append(qt_section_chunk(last_len, QStringRef(this, last_m, n - last_m)));
return extractSections(sections, start, end, flags);
}
@@ -4134,11 +4262,11 @@ QString QString::section(const QRegularExpression &re, int start, int end, Secti
while (iterator.hasNext()) {
QRegularExpressionMatch match = iterator.next();
m = match.capturedStart();
- sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
+ sections.append(qt_section_chunk(last_len, QStringRef(this, last_m, m - last_m)));
last_m = m;
last_len = match.capturedLength();
}
- sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
+ sections.append(qt_section_chunk(last_len, QStringRef(this, last_m, n - last_m)));
return extractSections(sections, start, end, flags);
}
@@ -4149,8 +4277,8 @@ QString QString::section(const QRegularExpression &re, int start, int end, Secti
Returns a substring that contains the \a n leftmost characters
of the string.
- The entire string is returned if \a n is greater than size() or
- less than zero.
+ The entire string is returned if \a n is greater than or equal
+ to size(), or less than zero.
\snippet qstring/main.cpp 31
@@ -4167,8 +4295,8 @@ QString QString::left(int n) const
Returns a substring that contains the \a n rightmost characters
of the string.
- The entire string is returned if \a n is greater than size() or
- less than zero.
+ The entire string is returned if \a n is greater than or equal
+ to size(), or less than zero.
\snippet qstring/main.cpp 48
@@ -4822,7 +4950,7 @@ modifiable reference.
If \a position is negative, it is equivalent to passing zero.
- \sa chop(), resize(), left()
+ \sa chop(), resize(), left(), QStringRef::truncate()
*/
void QString::truncate(int pos)
@@ -4835,7 +4963,8 @@ void QString::truncate(int pos)
/*!
Removes \a n characters from the end of the string.
- If \a n is greater than size(), the result is an empty string.
+ If \a n is greater than or equal to size(), the result is an
+ empty string.
Example:
\snippet qstring/main.cpp 15
@@ -7622,86 +7751,155 @@ static int getEscape(const QChar *uc, int *pos, int len, int maxNumber = 999)
return -1;
}
+/*
+ Algorithm for multiArg:
+
+ 1. Parse the string as a sequence of verbatim text and placeholders (%L?\d{,3}).
+ The L is parsed and accepted for compatibility with non-multi-arg, but since
+ multiArg only accepts strings as replacements, the localization request can
+ be safely ignored.
+ 2. The result of step (1) is a list of (string-ref,int)-tuples. The string-ref
+ either points at text to be copied verbatim (in which case the int is -1),
+ or, initially, at the textual representation of the placeholder. In that case,
+ the int contains the numerical number as parsed from the placeholder.
+ 3. Next, collect all the non-negative ints found, sort them in ascending order and
+ remove duplicates.
+ 3a. If the result has more entires than multiArg() was given replacement strings,
+ we have found placeholders we can't satisfy with replacement strings. That is
+ fine (there could be another .arg() call coming after this one), so just
+ truncate the result to the number of actual multiArg() replacement strings.
+ 3b. If the result has less entries than multiArg() was given replacement strings,
+ the string is missing placeholders. This is an error that the user should be
+ warned about.
+ 4. The result of step (3) is a mapping from the index of any replacement string to
+ placeholder number. This is the wrong way around, but since placeholder
+ numbers could get as large as 999, while we typically don't have more than 9
+ replacement strings, we trade 4K of sparsely-used memory for doing a reverse lookup
+ each time we need to map a placeholder number to a replacement string index
+ (that's a linear search; but still *much* faster than using an associative container).
+ 5. Next, for each of the tuples found in step (1), do the following:
+ 5a. If the int is negative, do nothing.
+ 5b. Otherwise, if the int is found in the result of step (3) at index I, replace
+ the string-ref with a string-ref for the (complete) I'th replacement string.
+ 5c. Otherwise, do nothing.
+ 6. Concatenate all string refs into a single result string.
+*/
+
namespace {
-class ArgMapper {
- QVarLengthArray<int, 16> argPosToNumberMap; // maps from argument position to number
-public:
- void found(int n) { argPosToNumberMap.push_back(n); }
+struct Part
+{
+ Part() : stringRef(), number(0) {}
+ Part(const QString &s, int pos, int len, int num = -1) Q_DECL_NOTHROW
+ : stringRef(&s, pos, len), number(num) {}
- struct AssignmentResult {
- int numArgs;
- int lastNumber;
- };
+ QStringRef stringRef;
+ int number;
+};
+} // unnamed namespace
- AssignmentResult assignArgumentNumberToEachOfTheNs(int numArgs)
- {
- std::sort(argPosToNumberMap.begin(), argPosToNumberMap.end());
- argPosToNumberMap.erase(std::unique(argPosToNumberMap.begin(), argPosToNumberMap.end()),
- argPosToNumberMap.end());
+template <>
+class QTypeInfo<Part> : public QTypeInfoMerger<Part, QStringRef, int> {}; // Q_DECLARE_METATYPE
- if (argPosToNumberMap.size() > numArgs)
- argPosToNumberMap.resize(numArgs);
- int lastNumber = argPosToNumberMap.empty() ? -1 : argPosToNumberMap.back();
- int arg = argPosToNumberMap.size();
+namespace {
- const AssignmentResult result = {arg, lastNumber};
- return result;
- }
+enum { ExpectedParts = 32 };
- int numberToArgsIndex(int number) const
- {
- if (number != -1) {
- const int * const it = std::find(argPosToNumberMap.begin(), argPosToNumberMap.end(), number);
- return it == argPosToNumberMap.end() ? -1 : it - argPosToNumberMap.begin();
- } else {
- return -1;
- }
- }
-};
-} // unnamed namespace
+typedef QVarLengthArray<Part, ExpectedParts> ParseResult;
+typedef QVarLengthArray<int, ExpectedParts/2> ArgIndexToPlaceholderMap;
-QString QString::multiArg(int numArgs, const QString **args) const
+static ParseResult parseMultiArgFormatString(const QString &s)
{
- QString result;
- ArgMapper mapper;
- const QChar *uc = (const QChar *) d->data();
- const int len = d->size;
+ ParseResult result;
+
+ const QChar *uc = s.constData();
+ const int len = s.size();
const int end = len - 1;
int i = 0;
+ int last = 0;
- // populate the arg-mapper with the %n's that actually occur in the string
while (i < end) {
if (uc[i] == QLatin1Char('%')) {
+ int percent = i;
int number = getEscape(uc, &i, len);
if (number != -1) {
- mapper.found(number);
+ if (last != percent)
+ result.push_back(Part(s, last, percent - last)); // literal text (incl. failed placeholders)
+ result.push_back(Part(s, percent, i - percent, number)); // parsed placeholder
+ last = i;
continue;
}
}
++i;
}
- const ArgMapper::AssignmentResult r = mapper.assignArgumentNumberToEachOfTheNs(numArgs);
+ if (last < len)
+ result.push_back(Part(s, last, len - last)); // trailing literal text
- // sanity
- if (numArgs > r.numArgs) {
- qWarning("QString::arg: %d argument(s) missing in %s", numArgs - r.numArgs, toLocal8Bit().data());
- numArgs = r.numArgs;
+ return result;
+}
+
+static ArgIndexToPlaceholderMap makeArgIndexToPlaceholderMap(const ParseResult &parts)
+{
+ ArgIndexToPlaceholderMap result;
+
+ for (ParseResult::const_iterator it = parts.begin(), end = parts.end(); it != end; ++it) {
+ if (it->number >= 0)
+ result.push_back(it->number);
}
- i = 0;
- while (i < len) {
- if (uc[i] == QLatin1Char('%') && i != end) {
- int number = getEscape(uc, &i, len, r.lastNumber);
- int arg = mapper.numberToArgsIndex(number);
- if (number != -1 && arg != -1) {
- result += *args[arg];
- continue;
- }
+ std::sort(result.begin(), result.end());
+ result.erase(std::unique(result.begin(), result.end()),
+ result.end());
+
+ return result;
+}
+
+static int resolveStringRefsAndReturnTotalSize(ParseResult &parts, const ArgIndexToPlaceholderMap &argIndexToPlaceholderMap, const QString *args[])
+{
+ int totalSize = 0;
+ for (ParseResult::iterator pit = parts.begin(), end = parts.end(); pit != end; ++pit) {
+ if (pit->number != -1) {
+ const ArgIndexToPlaceholderMap::const_iterator ait
+ = std::find(argIndexToPlaceholderMap.begin(), argIndexToPlaceholderMap.end(), pit->number);
+ if (ait != argIndexToPlaceholderMap.end())
+ pit->stringRef = QStringRef(args[ait - argIndexToPlaceholderMap.begin()]);
}
- result += uc[i++];
+ totalSize += pit->stringRef.size();
}
+ return totalSize;
+}
+
+} // unnamed namespace
+
+QString QString::multiArg(int numArgs, const QString **args) const
+{
+ // Step 1-2 above
+ ParseResult parts = parseMultiArgFormatString(*this);
+
+ // 3-4
+ ArgIndexToPlaceholderMap argIndexToPlaceholderMap = makeArgIndexToPlaceholderMap(parts);
+
+ if (argIndexToPlaceholderMap.size() > numArgs) // 3a
+ argIndexToPlaceholderMap.resize(numArgs);
+ else if (argIndexToPlaceholderMap.size() < numArgs) // 3b
+ qWarning("QString::arg: %d argument(s) missing in %s",
+ numArgs - argIndexToPlaceholderMap.size(), toLocal8Bit().data());
+
+ // 5
+ const int totalSize = resolveStringRefsAndReturnTotalSize(parts, argIndexToPlaceholderMap, args);
+
+ // 6:
+ QString result(totalSize, Qt::Uninitialized);
+ QChar *out = result.data();
+
+ for (ParseResult::const_iterator it = parts.begin(), end = parts.end(); it != end; ++it) {
+ if (const int sz = it->stringRef.size()) {
+ memcpy(out, it->stringRef.constData(), sz * sizeof(QChar));
+ out += sz;
+ }
+ }
+
return result;
}
@@ -9125,8 +9323,8 @@ QString &QString::append(const QStringRef &str)
Returns a substring reference to the \a n leftmost characters
of the string.
- If \a n is greater than size() or less than zero, a reference to the entire
- string is returned.
+ If \a n is greater than or equal to size(), or less than zero,
+ a reference to the entire string is returned.
\sa right(), mid(), startsWith()
*/
@@ -9143,8 +9341,8 @@ QStringRef QStringRef::left(int n) const
Returns a substring reference to the \a n leftmost characters
of the string.
- If \a n is greater than size() or less than zero, a reference to the entire
- string is returned.
+ If \a n is greater than or equal to size(), or less than zero,
+ a reference to the entire string is returned.
\snippet qstring/main.cpp leftRef
@@ -9164,8 +9362,8 @@ QStringRef QString::leftRef(int n) const
Returns a substring reference to the \a n rightmost characters
of the string.
- If \a n is greater than size() or less than zero, a reference to the entire
- string is returned.
+ If \a n is greater than or equal to size(), or less than zero,
+ a reference to the entire string is returned.
\sa left(), mid(), endsWith()
*/
@@ -9182,8 +9380,8 @@ QStringRef QStringRef::right(int n) const
Returns a substring reference to the \a n rightmost characters
of the string.
- If \a n is greater than size() or less than zero, a reference to the entire
- string is returned.
+ If \a n is greater than or equal to size(), or less than zero,
+ a reference to the entire string is returned.
\snippet qstring/main.cpp rightRef
@@ -9268,6 +9466,20 @@ QStringRef QString::midRef(int position, int n) const
}
/*!
+ \fn void QStringRef::truncate(int position)
+ \since 5.6
+
+ Truncates the string at the given \a position index.
+
+ If the specified \a position index is beyond the end of the
+ string, nothing happens.
+
+ If \a position is negative, it is equivalent to passing zero.
+
+ \sa QString::truncate()
+*/
+
+/*!
\since 4.8
Returns the index position of the first occurrence of the string \a
diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h
index 63107ff688..643378a7bd 100644
--- a/src/corelib/tools/qstring.h
+++ b/src/corelib/tools/qstring.h
@@ -44,6 +44,7 @@
#include <QtCore/qnamespace.h>
#include <string>
+#include <iterator>
#if defined(Q_OS_ANDROID)
// std::wstring is disabled on android's glibc, as bionic lacks certain features
@@ -84,7 +85,7 @@ class QLatin1String
public:
Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s) : m_size(s ? int(strlen(s)) : 0), m_data(s) {}
Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s, int sz) : m_size(sz), m_data(s) {}
- inline explicit QLatin1String(const QByteArray &s) : m_size(int(qstrnlen(s.constData(), s.size()))), m_data(s.constData()) {}
+ inline explicit QLatin1String(const QByteArray &s) : m_size(s.size()), m_data(s.constData()) {}
inline const char *latin1() const { return m_data; }
inline int size() const { return m_size; }
@@ -420,6 +421,7 @@ public:
QString &insert(int i, QChar c);
QString &insert(int i, const QChar *uc, int len);
inline QString &insert(int i, const QString &s) { return insert(i, s.constData(), s.length()); }
+ inline QString &insert(int i, const QStringRef &s);
QString &insert(int i, QLatin1String s);
QString &append(QChar c);
QString &append(const QChar *uc, int len);
@@ -427,7 +429,9 @@ public:
QString &append(const QStringRef &s);
QString &append(QLatin1String s);
inline QString &prepend(QChar c) { return insert(0, c); }
+ inline QString &prepend(const QChar *uc, int len) { return insert(0, uc, len); }
inline QString &prepend(const QString &s) { return insert(0, s); }
+ inline QString &prepend(const QStringRef &s) { return insert(0, s); }
inline QString &prepend(QLatin1String s) { return insert(0, s); }
inline QString &operator+=(QChar c) {
@@ -534,11 +538,11 @@ public:
return fromLocal8Bit_helper(str, (str && size == -1) ? int(strlen(str)) : size);
}
static inline QString fromLatin1(const QByteArray &str)
- { return fromLatin1(str.data(), qstrnlen(str.constData(), str.size())); }
+ { return str.isNull() ? QString() : fromLatin1(str.data(), str.size()); }
static inline QString fromUtf8(const QByteArray &str)
- { return fromUtf8(str.data(), qstrnlen(str.constData(), str.size())); }
+ { return str.isNull() ? QString() : fromUtf8(str.data(), str.size()); }
static inline QString fromLocal8Bit(const QByteArray &str)
- { return fromLocal8Bit(str.data(), qstrnlen(str.constData(), str.size())); }
+ { return str.isNull() ? QString() : fromLocal8Bit(str.data(), str.size()); }
static QString fromUtf16(const ushort *, int size = -1);
static QString fromUcs4(const uint *, int size = -1);
static QString fromRawData(const QChar *, int size);
@@ -591,16 +595,16 @@ public:
static int localeAwareCompare(const QString& s1, const QStringRef& s2);
// ### Qt6: make inline except for the long long versions
- short toShort(bool *ok=0, int base=10) const;
- ushort toUShort(bool *ok=0, int base=10) const;
- int toInt(bool *ok=0, int base=10) const;
- uint toUInt(bool *ok=0, int base=10) const;
- long toLong(bool *ok=0, int base=10) const;
- ulong toULong(bool *ok=0, int base=10) const;
- qlonglong toLongLong(bool *ok=0, int base=10) const;
- qulonglong toULongLong(bool *ok=0, int base=10) const;
- float toFloat(bool *ok=0) const;
- double toDouble(bool *ok=0) const;
+ short toShort(bool *ok=Q_NULLPTR, int base=10) const;
+ ushort toUShort(bool *ok=Q_NULLPTR, int base=10) const;
+ int toInt(bool *ok=Q_NULLPTR, int base=10) const;
+ uint toUInt(bool *ok=Q_NULLPTR, int base=10) const;
+ long toLong(bool *ok=Q_NULLPTR, int base=10) const;
+ ulong toULong(bool *ok=Q_NULLPTR, int base=10) const;
+ qlonglong toLongLong(bool *ok=Q_NULLPTR, int base=10) const;
+ qulonglong toULongLong(bool *ok=Q_NULLPTR, int base=10) const;
+ float toFloat(bool *ok=Q_NULLPTR) const;
+ double toDouble(bool *ok=Q_NULLPTR) const;
QString &setNum(short, int base=10);
QString &setNum(ushort, int base=10);
@@ -650,7 +654,7 @@ public:
: d(fromAscii_helper(ch, ch ? int(strlen(ch)) : -1))
{}
inline QT_ASCII_CAST_WARN QString(const QByteArray &a)
- : d(fromAscii_helper(a.constData(), qstrnlen(a.constData(), a.size())))
+ : d(fromAscii_helper(a.constData(), a.size()))
{}
inline QT_ASCII_CAST_WARN QString &operator=(const char *ch)
{ return (*this = fromUtf8(ch)); }
@@ -668,6 +672,10 @@ public:
{ return append(QString::fromUtf8(s)); }
inline QT_ASCII_CAST_WARN QString &append(const QByteArray &s)
{ return append(QString::fromUtf8(s)); }
+ inline QT_ASCII_CAST_WARN QString &insert(int i, const char *s)
+ { return insert(i, QString::fromUtf8(s)); }
+ inline QT_ASCII_CAST_WARN QString &insert(int i, const QByteArray &s)
+ { return insert(i, QString::fromUtf8(s)); }
inline QT_ASCII_CAST_WARN QString &operator+=(const char *s)
{ return append(QString::fromUtf8(s)); }
inline QT_ASCII_CAST_WARN QString &operator+=(const QByteArray &s)
@@ -708,14 +716,22 @@ public:
typedef const QChar *const_iterator;
typedef iterator Iterator;
typedef const_iterator ConstIterator;
- iterator begin();
- const_iterator begin() const;
- const_iterator cbegin() const;
- const_iterator constBegin() const;
- iterator end();
- const_iterator end() const;
- const_iterator cend() const;
- const_iterator constEnd() const;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ inline iterator begin();
+ inline const_iterator begin() const;
+ inline const_iterator cbegin() const;
+ inline const_iterator constBegin() const;
+ inline iterator end();
+ inline const_iterator end() const;
+ inline const_iterator cend() const;
+ inline const_iterator constEnd() const;
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
+ const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
// STL compatibility
typedef int size_type;
@@ -1211,30 +1227,30 @@ inline QT_ASCII_CAST_WARN bool QLatin1String::operator>=(const QByteArray &s) co
{ return QString::fromUtf8(s) <= *this; }
inline QT_ASCII_CAST_WARN bool QString::operator==(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) == 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) == 0; }
inline QT_ASCII_CAST_WARN bool QString::operator!=(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) != 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) != 0; }
inline QT_ASCII_CAST_WARN bool QString::operator<(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) < 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) < 0; }
inline QT_ASCII_CAST_WARN bool QString::operator>(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) > 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) > 0; }
inline QT_ASCII_CAST_WARN bool QString::operator<=(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) <= 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) <= 0; }
inline QT_ASCII_CAST_WARN bool QString::operator>=(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) >= 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) >= 0; }
inline bool QByteArray::operator==(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) == 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) == 0; }
inline bool QByteArray::operator!=(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) != 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) != 0; }
inline bool QByteArray::operator<(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) < 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) < 0; }
inline bool QByteArray::operator>(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) > 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) > 0; }
inline bool QByteArray::operator<=(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) <= 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) <= 0; }
inline bool QByteArray::operator>=(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) >= 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) >= 0; }
#endif // !defined(QT_NO_CAST_FROM_ASCII) && !defined(QT_RESTRICTED_CAST_FROM_ASCII)
#ifndef QT_NO_CAST_TO_ASCII
@@ -1343,28 +1359,32 @@ public:
typedef QString::const_reference const_reference;
// ### Qt 6: make this constructor constexpr, after the destructor is made trivial
- inline QStringRef():m_string(0), m_position(0), m_size(0){}
+ inline QStringRef() : m_string(Q_NULLPTR), m_position(0), m_size(0) {}
inline QStringRef(const QString *string, int position, int size);
inline QStringRef(const QString *string);
- // ### Qt 6: remove this copy constructor, the implicit one is fine
- inline QStringRef(const QStringRef &other)
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+ // ### Qt 6: remove all of these, the implicit ones are fine
+ QStringRef(const QStringRef &other) Q_DECL_NOTHROW
:m_string(other.m_string), m_position(other.m_position), m_size(other.m_size)
{}
-
- // ### Qt 6: remove this destructor, the implicit one is fine
+#ifdef Q_COMPILER_RVALUE_REFS
+ QStringRef(QStringRef &&other) Q_DECL_NOTHROW : m_string(other.m_string), m_position(other.m_position), m_size(other.m_size) {}
+ QStringRef &operator=(QStringRef &&other) Q_DECL_NOTHROW { return *this = other; }
+#endif
+ QStringRef &operator=(const QStringRef &other) Q_DECL_NOTHROW {
+ m_string = other.m_string; m_position = other.m_position;
+ m_size = other.m_size; return *this;
+ }
inline ~QStringRef(){}
+#endif // Qt < 6.0.0
+
inline const QString *string() const { return m_string; }
inline int position() const { return m_position; }
inline int size() const { return m_size; }
inline int count() const { return m_size; }
inline int length() const { return m_size; }
- inline QStringRef &operator=(const QStringRef &other) {
- m_string = other.m_string; m_position = other.m_position;
- m_size = other.m_size; return *this;
- }
-
int indexOf(const QString &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
int indexOf(QChar ch, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
int indexOf(QLatin1String str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
@@ -1392,6 +1412,8 @@ public:
QStringRef right(int n) const Q_REQUIRED_RESULT;
QStringRef mid(int pos, int n = -1) const Q_REQUIRED_RESULT;
+ void truncate(int pos) Q_DECL_NOTHROW { m_size = qBound(0, pos, m_size); }
+
bool startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
bool startsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
bool startsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
@@ -1425,10 +1447,10 @@ public:
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT;
QVector<uint> toUcs4() const Q_REQUIRED_RESULT;
- inline void clear() { m_string = 0; m_position = m_size = 0; }
+ inline void clear() { m_string = Q_NULLPTR; m_position = m_size = 0; }
QString toString() const;
inline bool isEmpty() const { return m_size == 0; }
- inline bool isNull() const { return m_string == 0 || m_string->isNull(); }
+ inline bool isNull() const { return m_string == Q_NULLPTR || m_string->isNull(); }
QStringRef appendTo(QString *string) const;
@@ -1461,16 +1483,16 @@ public:
static int localeAwareCompare(const QStringRef &s1, const QStringRef &s2);
QStringRef trimmed() const Q_REQUIRED_RESULT;
- short toShort(bool *ok = 0, int base = 10) const;
- ushort toUShort(bool *ok = 0, int base = 10) const;
- int toInt(bool *ok = 0, int base = 10) const;
- uint toUInt(bool *ok = 0, int base = 10) const;
- long toLong(bool *ok = 0, int base = 10) const;
- ulong toULong(bool *ok = 0, int base = 10) const;
- qlonglong toLongLong(bool *ok = 0, int base = 10) const;
- qulonglong toULongLong(bool *ok = 0, int base = 10) const;
- float toFloat(bool *ok = 0) const;
- double toDouble(bool *ok = 0) const;
+ short toShort(bool *ok = Q_NULLPTR, int base = 10) const;
+ ushort toUShort(bool *ok = Q_NULLPTR, int base = 10) const;
+ int toInt(bool *ok = Q_NULLPTR, int base = 10) const;
+ uint toUInt(bool *ok = Q_NULLPTR, int base = 10) const;
+ long toLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ ulong toULong(bool *ok = Q_NULLPTR, int base = 10) const;
+ qlonglong toLongLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ qulonglong toULongLong(bool *ok = Q_NULLPTR, int base = 10) const;
+ float toFloat(bool *ok = Q_NULLPTR) const;
+ double toDouble(bool *ok = Q_NULLPTR) const;
};
Q_DECLARE_TYPEINFO(QStringRef, Q_PRIMITIVE_TYPE);
@@ -1576,6 +1598,9 @@ inline bool QStringRef::contains(QChar c, Qt::CaseSensitivity cs) const
inline bool QStringRef::contains(const QStringRef &s, Qt::CaseSensitivity cs) const
{ return indexOf(s, 0, cs) != -1; }
+inline QString &QString::insert(int i, const QStringRef &s)
+{ return insert(i, s.constData(), s.length()); }
+
namespace Qt {
#if QT_DEPRECATED_SINCE(5, 0)
QT_DEPRECATED inline QString escape(const QString &plain) {
diff --git a/src/corelib/tools/qtextboundaryfinder.h b/src/corelib/tools/qtextboundaryfinder.h
index beec5de607..a79fb50dad 100644
--- a/src/corelib/tools/qtextboundaryfinder.h
+++ b/src/corelib/tools/qtextboundaryfinder.h
@@ -68,7 +68,7 @@ public:
Q_DECLARE_FLAGS( BoundaryReasons, BoundaryReason )
QTextBoundaryFinder(BoundaryType type, const QString &string);
- QTextBoundaryFinder(BoundaryType type, const QChar *chars, int length, unsigned char *buffer = 0, int bufferSize = 0);
+ QTextBoundaryFinder(BoundaryType type, const QChar *chars, int length, unsigned char *buffer = Q_NULLPTR, int bufferSize = 0);
inline bool isValid() const { return d; }
diff --git a/src/corelib/tools/qtimeline.h b/src/corelib/tools/qtimeline.h
index 21139b37a8..94e60dce45 100644
--- a/src/corelib/tools/qtimeline.h
+++ b/src/corelib/tools/qtimeline.h
@@ -70,7 +70,7 @@ public:
CosineCurve
};
- explicit QTimeLine(int duration = 1000, QObject *parent = 0);
+ explicit QTimeLine(int duration = 1000, QObject *parent = Q_NULLPTR);
virtual ~QTimeLine();
State state() const;
diff --git a/src/corelib/tools/qtimezone.cpp b/src/corelib/tools/qtimezone.cpp
index 3627045a40..900c8ff14e 100644
--- a/src/corelib/tools/qtimezone.cpp
+++ b/src/corelib/tools/qtimezone.cpp
@@ -310,9 +310,8 @@ Q_GLOBAL_STATIC(QTimeZoneSingleton, global_tz);
/*!
\typedef QTimeZone::OffsetDataList
- \relates QTimeZone
- Synonym for QList<OffsetData>.
+ Synonym for QVector<OffsetData>.
*/
/*!
@@ -764,6 +763,7 @@ QTimeZone::OffsetDataList QTimeZone::transitions(const QDateTime &fromDateTime,
if (hasTransitions()) {
QTimeZonePrivate::DataList plist = d->transitions(fromDateTime.toMSecsSinceEpoch(),
toDateTime.toMSecsSinceEpoch());
+ list.reserve(plist.count());
foreach (const QTimeZonePrivate::Data &pdata, plist)
list.append(d->toOffsetData(pdata));
}
diff --git a/src/corelib/tools/qtimezoneprivate.cpp b/src/corelib/tools/qtimezoneprivate.cpp
index 8e6a0a0578..5bc3610af0 100644
--- a/src/corelib/tools/qtimezoneprivate.cpp
+++ b/src/corelib/tools/qtimezoneprivate.cpp
@@ -700,6 +700,7 @@ QByteArray QUtcTimeZonePrivate::systemTimeZoneId() const
QList<QByteArray> QUtcTimeZonePrivate::availableTimeZoneIds() const
{
QList<QByteArray> result;
+ result.reserve(utcDataTableSize);
for (int i = 0; i < utcDataTableSize; ++i)
result << utcId(utcData(i));
std::sort(result.begin(), result.end()); // ### or already sorted??
diff --git a/src/corelib/tools/qtimezoneprivate_p.h b/src/corelib/tools/qtimezoneprivate_p.h
index e15ac801bc..14aeac3a02 100644
--- a/src/corelib/tools/qtimezoneprivate_p.h
+++ b/src/corelib/tools/qtimezoneprivate_p.h
@@ -165,6 +165,7 @@ public:
protected:
QByteArray m_id;
};
+Q_DECLARE_TYPEINFO(QTimeZonePrivate::Data, Q_MOVABLE_TYPE);
template<> QTimeZonePrivate *QSharedDataPointer<QTimeZonePrivate>::clone();
diff --git a/src/corelib/tools/qtimezoneprivate_tz.cpp b/src/corelib/tools/qtimezoneprivate_tz.cpp
index 35380b882a..90ce8e3b68 100644
--- a/src/corelib/tools/qtimezoneprivate_tz.cpp
+++ b/src/corelib/tools/qtimezoneprivate_tz.cpp
@@ -637,6 +637,7 @@ void QTzTimeZonePrivate::init(const QByteArray &ianaId)
}
// Now for each transition time calculate our rule and save them
+ m_tranTimes.reserve(tranList.count());
foreach (const QTzTransition &tz_tran, tranList) {
QTzTransitionTime tran;
QTzTransitionRule rule;
diff --git a/src/corelib/tools/qvarlengtharray.h b/src/corelib/tools/qvarlengtharray.h
index 90b54b7297..bb15d66439 100644
--- a/src/corelib/tools/qvarlengtharray.h
+++ b/src/corelib/tools/qvarlengtharray.h
@@ -45,6 +45,7 @@
#ifdef Q_COMPILER_INITIALIZER_LISTS
#include <initializer_list>
#endif
+#include <iterator>
QT_BEGIN_NAMESPACE
@@ -174,6 +175,8 @@ public:
typedef T* iterator;
typedef const T* const_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
inline iterator begin() { return ptr; }
inline const_iterator begin() const { return ptr; }
@@ -183,6 +186,12 @@ public:
inline const_iterator end() const { return ptr + s; }
inline const_iterator cend() const { return ptr + s; }
inline const_iterator constEnd() const { return ptr + s; }
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
+ const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
+ const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
iterator insert(const_iterator before, int n, const T &x);
inline iterator insert(const_iterator before, const T &x) { return insert(before, 1, x); }
iterator erase(const_iterator begin, const_iterator end);
@@ -489,6 +498,36 @@ bool operator!=(const QVarLengthArray<T, Prealloc1> &l, const QVarLengthArray<T,
return !(l == r);
}
+template <typename T, int Prealloc1, int Prealloc2>
+bool operator<(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end())))
+{
+ return std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end());
+}
+
+template <typename T, int Prealloc1, int Prealloc2>
+inline bool operator>(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return rhs < lhs;
+}
+
+template <typename T, int Prealloc1, int Prealloc2>
+inline bool operator<=(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs > rhs);
+}
+
+template <typename T, int Prealloc1, int Prealloc2>
+inline bool operator>=(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs < rhs);
+}
+
QT_END_NAMESPACE
#endif // QVARLENGTHARRAY_H
diff --git a/src/corelib/tools/qvarlengtharray.qdoc b/src/corelib/tools/qvarlengtharray.qdoc
index a2d4c55f7a..2b7f9c5241 100644
--- a/src/corelib/tools/qvarlengtharray.qdoc
+++ b/src/corelib/tools/qvarlengtharray.qdoc
@@ -468,6 +468,20 @@
Typedef for T *. Provided for STL compatibility.
*/
+/*!
+ \typedef QVarLengthArray::const_reverse_iterator
+ \since 5.6
+
+ Typedef for \c{std::reverse_iterator<const T*>}. Provided for STL compatibility.
+*/
+
+/*!
+ \typedef QVarLengthArray::reverse_iterator
+ \since 5.6
+
+ Typedef for \c{std::reverse_iterator<T*>}. Provided for STL compatibility.
+*/
+
/*! \fn void QVarLengthArray::prepend(const T &value)
\since 4.8
@@ -582,6 +596,52 @@
\sa constBegin(), end()
*/
+/*! \fn QVarLengthArray::reverse_iterator QVarLengthArray::rbegin()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the variable length array, in reverse order.
+
+ \sa begin(), crbegin(), rend()
+*/
+
+/*! \fn QVarLengthArray::const_reverse_iterator QVarLengthArray::rbegin() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QVarLengthArray::const_reverse_iterator QVarLengthArray::crbegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the variable length array, in reverse order.
+
+ \sa begin(), rbegin(), rend()
+*/
+
+/*! \fn QVarLengthArray::reverse_iterator QVarLengthArray::rend()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
+ the last item in the variable length array, in reverse order.
+
+ \sa end(), crend(), rbegin()
+*/
+
+/*! \fn QVarLengthArray::const_reverse_iterator QVarLengthArray::rend() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QVarLengthArray::const_reverse_iterator QVarLengthArray::crend() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
+ past the last item in the variable length array, in reverse order.
+
+ \sa end(), rend(), rbegin()
+*/
+
/*! \fn QVarLengthArray::iterator QVarLengthArray::erase(const_iterator pos)
\since 4.8
@@ -676,6 +736,54 @@
\sa operator==()
*/
+/*! \fn bool operator<(const QVarLengthArray<T,Prealloc1> &lhs, const QVarLengthArray<T,Prealloc2> &rhs)
+ \since 5.6
+ \relates QVarLengthArray
+
+ Returns \c true if variable length array \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator<=(const QVarLengthArray<T,Prealloc1> &lhs, const QVarLengthArray<T,Prealloc2> &rhs)
+ \since 5.6
+ \relates QVarLengthArray
+
+ Returns \c true if variable length array \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>(const QVarLengthArray<T,Prealloc1> &lhs, const QVarLengthArray<T,Prealloc2> &rhs)
+ \since 5.6
+ \relates QVarLengthArray
+
+ Returns \c true if variable length array \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>=(const QVarLengthArray<T,Prealloc1> &lhs, const QVarLengthArray<T,Prealloc2> &rhs)
+ \since 5.6
+ \relates QVarLengthArray
+
+ Returns \c true if variable length array \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
/*! \fn QVarLengthArray &QVarLengthArray::operator<<(const T &value)
\since 4.8
diff --git a/src/corelib/tools/qvector.cpp b/src/corelib/tools/qvector.cpp
index d10f82fbb4..9afd2c624a 100644
--- a/src/corelib/tools/qvector.cpp
+++ b/src/corelib/tools/qvector.cpp
@@ -45,34 +45,42 @@
stores its items in adjacent memory locations and provides fast
index-based access.
- QList\<T\>, QLinkedList\<T\>, and QVarLengthArray\<T\> provide
- similar functionality. Here's an overview:
+ QList\<T\>, QLinkedList\<T\>, QVector\<T\>, and QVarLengthArray\<T\>
+ provide similar APIs and functionality. They are often interchangeable,
+ but there are performance consequences. Here is an overview of use cases:
\list
- \li For most purposes, QList is the right class to use. Operations
- like prepend() and insert() are usually faster than with
- QVector because of the way QList stores its items in memory
- (see \l{Algorithmic Complexity} for details),
- and its index-based API is more convenient than QLinkedList's
- iterator-based API. It also expands to less code in your
- executable.
- \li If you need a real linked list, with guarantees of \l{constant
- time} insertions in the middle of the list and iterators to
- items rather than indexes, use QLinkedList.
- \li If you want the items to occupy adjacent memory positions, or
- if your items are larger than a pointer and you want to avoid
- the overhead of allocating them on the heap individually at
- insertion time, then use QVector.
- \li If you want a low-level variable-size array, QVarLengthArray
- may be sufficient.
+ \li QVector should be your default first choice.
+ QVector\<T\> will usually give better performance than QList\<T\>,
+ because QVector\<T\> always stores its items sequentially in memory,
+ where QList\<T\> will allocate its items on the heap unless
+ \c {sizeof(T) <= sizeof(void*)} and T has been declared to be
+ either a \c{Q_MOVABLE_TYPE} or a \c{Q_PRIMITIVE_TYPE} using
+ \l {Q_DECLARE_TYPEINFO}. See the \l {Pros and Cons of Using QList}
+ for an explanation.
+ \li However, QList is used throughout the Qt APIs for passing
+ parameters and for returning values. Use QList to interface with
+ those APIs.
+ \li If you need a real linked list, which guarantees
+ \l{Algorithmic Complexity}{constant time} insertions mid-list and
+ uses iterators to items rather than indexes, use QLinkedList.
\endlist
+ \note QVector and QVarLengthArray both guarantee C-compatible
+ array layout. QList does not. This might be important if your
+ application must interface with a C API.
+
+ \note Iterators into a QLinkedList and references into
+ heap-allocating QLists remain valid long as the referenced items
+ remain in the container. This is not true for iterators and
+ references into a QVector and non-heap-allocating QLists.
+
Here's an example of a QVector that stores integers and a QVector
that stores QString values:
\snippet code/src_corelib_tools_qvector.cpp 0
- QVector stores a vector (or array) of items. Typically, vectors
+ QVector stores its items in a vector (array). Typically, vectors
are created with an initial size. For example, the following code
constructs a QVector with 200 elements:
@@ -166,6 +174,11 @@
with references to its own values. Doing so will cause your application to
abort with an error message.
+ \section2 More Information on Using Qt Containers
+
+ For a detailed discussion comparing Qt containers with each other and
+ with STL containers, see \l {Understand the Qt Containers}.
+
\sa QVectorIterator, QMutableVectorIterator, QList, QLinkedList
*/
@@ -218,10 +231,11 @@
Constructs a copy of \a other.
- This operation takes \l{constant time}, because QVector is
- \l{implicitly shared}. This makes returning a QVector from a
- function very fast. If a shared instance is modified, it will be
- copied (copy-on-write), and that takes \l{linear time}.
+ This operation takes \l{Algorithmic Complexity}{constant time},
+ because QVector is \l{implicitly shared}. This makes returning
+ a QVector from a function very fast. If a shared instance is
+ modified, it will be copied (copy-on-write), and that takes
+ \l{Algorithmic Complexity}{linear time}.
\sa operator=()
*/
@@ -290,6 +304,65 @@
\sa operator==()
*/
+/*! \fn bool operator<(const QVector<T> &lhs, const QVector<T> &rhs)
+ \since 5.6
+ \relates QVector
+
+ Returns \c true if vector \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator<=(const QVector<T> &lhs, const QVector<T> &rhs)
+ \since 5.6
+ \relates QVector
+
+ Returns \c true if vector \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically less than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>(const QVector<T> &lhs, const QVector<T> &rhs)
+ \since 5.6
+ \relates QVector
+
+ Returns \c true if vector \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*! \fn bool operator>=(const QVector<T> &lhs, const QVector<T> &rhs)
+ \since 5.6
+ \relates QVector
+
+ Returns \c true if vector \a lhs is
+ \l{http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare}
+ {lexicographically greater than or equal to} \a rhs; otherwise returns \c false.
+
+ This function requires the value type to have an implementation
+ of \c operator<().
+*/
+
+/*!
+ \fn uint qHash(const QVector<T> &key, uint seed = 0)
+ \since 5.6
+ \relates QVector
+
+ Returns the hash value for \a key,
+ using \a seed to seed the calculation.
+
+ This function requires qHash() to be overloaded for the value type \c T.
+*/
+
/*! \fn int QVector::size() const
Returns the number of items in the vector.
@@ -463,6 +536,16 @@
\sa operator<<(), prepend(), insert()
*/
+/*!
+ \fn void QVector::append(T &&value)
+ \since 5.6
+
+ \overload
+
+ Example:
+ \snippet code/src_corelib_tools_qvector.cpp move-append
+*/
+
/*! \fn void QVector::append(const QVector<T> &value)
\overload
@@ -629,6 +712,16 @@
\sa takeFirst(), takeLast(), QList::takeAt()
*/
+/*! \fn void QVector::move(int from, int to)
+ \since 5.6
+
+ Moves the item at index position \a from to index position \a to.
+
+ Provided for compatibility with QList.
+
+ \sa QList::move()
+*/
+
/*! \fn void QVector::removeFirst()
\since 5.1
Removes the first item in the vector. Calling this function is
@@ -823,6 +916,52 @@
\sa constBegin(), end()
*/
+/*! \fn QVector::reverse_iterator QVector::rbegin()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the vector, in reverse order.
+
+ \sa begin(), crbegin(), rend()
+*/
+
+/*! \fn QVector::const_reverse_iterator QVector::rbegin() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QVector::const_reverse_iterator QVector::crbegin() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
+ item in the vector, in reverse order.
+
+ \sa begin(), rbegin(), rend()
+*/
+
+/*! \fn QVector::reverse_iterator QVector::rend()
+ \since 5.6
+
+ Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
+ the last item in the vector, in reverse order.
+
+ \sa end(), crend(), rbegin()
+*/
+
+/*! \fn QVector::const_reverse_iterator QVector::rend() const
+ \since 5.6
+ \overload
+*/
+
+/*! \fn QVector::const_reverse_iterator QVector::crend() const
+ \since 5.6
+
+ Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
+ past the last item in the vector, in reverse order.
+
+ \sa end(), rend(), rbegin()
+*/
+
/*! \fn QVector::iterator QVector::erase(iterator pos)
Removes the item pointed to by the iterator \a pos from the
@@ -846,7 +985,7 @@
Returns a reference to the first item in the vector. This
function assumes that the vector isn't empty.
- \sa last(), isEmpty()
+ \sa last(), isEmpty(), constFirst()
*/
/*! \fn const T& QVector::first() const
@@ -854,12 +993,21 @@
\overload
*/
+/*! \fn const T& QVector::constFirst() const
+ \since 5.6
+
+ Returns a const reference to the first item in the vector. This
+ function assumes that the vector isn't empty.
+
+ \sa constLast(), isEmpty(), first()
+*/
+
/*! \fn T& QVector::last()
Returns a reference to the last item in the vector. This function
assumes that the vector isn't empty.
- \sa first(), isEmpty()
+ \sa first(), isEmpty(), constLast()
*/
/*! \fn const T& QVector::last() const
@@ -867,6 +1015,15 @@
\overload
*/
+/*! \fn const T& QVector::constLast() const
+ \since 5.6
+
+ Returns a const reference to the last item in the vector. This function
+ assumes that the vector isn't empty.
+
+ \sa constFirst(), isEmpty(), last()
+*/
+
/*! \fn T QVector::value(int i) const
Returns the value at index position \a i in the vector.
@@ -893,6 +1050,11 @@
to append(\a value).
*/
+/*! \fn void QVector::push_back(T &&value)
+ \since 5.6
+ \overload
+*/
+
/*! \fn void QVector::push_front(const T &value)
This function is provided for STL compatibility. It is equivalent
@@ -1013,6 +1175,38 @@
\sa QVector::constBegin(), QVector::constEnd(), QVector::iterator, QVectorIterator
*/
+/*! \typedef QVector::reverse_iterator
+ \since 5.6
+
+ The QVector::reverse_iterator typedef provides an STL-style non-const
+ reverse iterator for QVector.
+
+ It is simply a typedef for \c{std::reverse_iterator<T*>}.
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QVector::rbegin(), QVector::rend(), QVector::const_reverse_iterator, QVector::iterator
+*/
+
+/*! \typedef QVector::const_reverse_iterator
+ \since 5.6
+
+ The QVector::const_reverse_iterator typedef provides an STL-style const
+ reverse iterator for QVector.
+
+ It is simply a typedef for \c{std::reverse_iterator<const T*>}.
+
+ \warning Iterators on implicitly shared containers do not work
+ exactly like STL-iterators. You should avoid copying a container
+ while iterators are active on that container. For more information,
+ read \l{Implicit sharing iterator problem}.
+
+ \sa QVector::rbegin(), QVector::rend(), QVector::reverse_iterator, QVector::const_iterator
+*/
+
/*! \typedef QVector::Iterator
Qt-style synonym for QVector::iterator.
diff --git a/src/corelib/tools/qvector.h b/src/corelib/tools/qvector.h
index eed5d17cad..890dbd317d 100644
--- a/src/corelib/tools/qvector.h
+++ b/src/corelib/tools/qvector.h
@@ -39,6 +39,7 @@
#include <QtCore/qlist.h>
#include <QtCore/qrefcount.h>
#include <QtCore/qarraydata.h>
+#include <QtCore/qhashfunctions.h>
#include <iterator>
#include <vector>
@@ -68,11 +69,11 @@ public:
inline ~QVector() { if (!d->ref.deref()) freeData(d); }
QVector<T> &operator=(const QVector<T> &v);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QVector(QVector<T> &&other) : d(other.d) { other.d = Data::sharedNull(); }
- inline QVector<T> operator=(QVector<T> &&other)
- { qSwap(d, other.d); return *this; }
+ QVector(QVector<T> &&other) Q_DECL_NOTHROW : d(other.d) { other.d = Data::sharedNull(); }
+ QVector<T> &operator=(QVector<T> &&other) Q_DECL_NOTHROW
+ { QVector moved(std::move(other)); swap(moved); return *this; }
#endif
- inline void swap(QVector<T> &other) { qSwap(d, other.d); }
+ void swap(QVector<T> &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
#ifdef Q_COMPILER_INITIALIZER_LISTS
inline QVector(std::initializer_list<T> args);
#endif
@@ -128,6 +129,9 @@ public:
T &operator[](int i);
const T &operator[](int i) const;
void append(const T &t);
+#ifdef Q_COMPILER_RVALUE_REFS
+ void append(T &&t);
+#endif
inline void append(const QVector<T> &l) { *this += l; }
void prepend(const T &t);
void insert(int i, const T &t);
@@ -171,29 +175,50 @@ public:
}
int length() const { return size(); }
T takeAt(int i) { T t = at(i); remove(i); return t; }
+ void move(int from, int to)
+ {
+ Q_ASSERT_X(from >= 0 && from < size(), "QVector::move(int,int)", "'from' is out-of-range");
+ Q_ASSERT_X(to >= 0 && to < size(), "QVector::move(int,int)", "'to' is out-of-range");
+ if (from == to) // don't detach when no-op
+ return;
+ detach();
+ T * const b = d->begin();
+ if (from < to)
+ std::rotate(b + from, b + from + 1, b + to + 1);
+ else
+ std::rotate(b + to, b + from, b + from + 1);
+ }
// STL-style
typedef typename Data::iterator iterator;
typedef typename Data::const_iterator const_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
#if !defined(QT_STRICT_ITERATORS) || defined(Q_QDOC)
inline iterator begin() { detach(); return d->begin(); }
- inline const_iterator begin() const { return d->constBegin(); }
- inline const_iterator cbegin() const { return d->constBegin(); }
- inline const_iterator constBegin() const { return d->constBegin(); }
+ inline const_iterator begin() const Q_DECL_NOTHROW { return d->constBegin(); }
+ inline const_iterator cbegin() const Q_DECL_NOTHROW { return d->constBegin(); }
+ inline const_iterator constBegin() const Q_DECL_NOTHROW { return d->constBegin(); }
inline iterator end() { detach(); return d->end(); }
- inline const_iterator end() const { return d->constEnd(); }
- inline const_iterator cend() const { return d->constEnd(); }
- inline const_iterator constEnd() const { return d->constEnd(); }
+ inline const_iterator end() const Q_DECL_NOTHROW { return d->constEnd(); }
+ inline const_iterator cend() const Q_DECL_NOTHROW { return d->constEnd(); }
+ inline const_iterator constEnd() const Q_DECL_NOTHROW { return d->constEnd(); }
#else
inline iterator begin(iterator = iterator()) { detach(); return d->begin(); }
- inline const_iterator begin(const_iterator = const_iterator()) const { return d->constBegin(); }
- inline const_iterator cbegin(const_iterator = const_iterator()) const { return d->constBegin(); }
- inline const_iterator constBegin(const_iterator = const_iterator()) const { return d->constBegin(); }
+ inline const_iterator begin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
+ inline const_iterator cbegin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
+ inline const_iterator constBegin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
inline iterator end(iterator = iterator()) { detach(); return d->end(); }
- inline const_iterator end(const_iterator = const_iterator()) const { return d->constEnd(); }
- inline const_iterator cend(const_iterator = const_iterator()) const { return d->constEnd(); }
- inline const_iterator constEnd(const_iterator = const_iterator()) const { return d->constEnd(); }
+ inline const_iterator end(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
+ inline const_iterator cend(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
+ inline const_iterator constEnd(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
#endif
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
+ const_reverse_iterator rend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
+ const_reverse_iterator crbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
+ const_reverse_iterator crend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
iterator insert(iterator before, int n, const T &x);
inline iterator insert(iterator before, const T &x) { return insert(before, 1, x); }
iterator erase(iterator begin, iterator end);
@@ -203,8 +228,10 @@ public:
inline int count() const { return d->size; }
inline T& first() { Q_ASSERT(!isEmpty()); return *begin(); }
inline const T &first() const { Q_ASSERT(!isEmpty()); return *begin(); }
+ inline const T &constFirst() const { Q_ASSERT(!isEmpty()); return *begin(); }
inline T& last() { Q_ASSERT(!isEmpty()); return *(end()-1); }
inline const T &last() const { Q_ASSERT(!isEmpty()); return *(end()-1); }
+ inline const T &constLast() const { Q_ASSERT(!isEmpty()); return *(end()-1); }
inline bool startsWith(const T &t) const { return !isEmpty() && first() == t; }
inline bool endsWith(const T &t) const { return !isEmpty() && last() == t; }
QVector<T> mid(int pos, int len = -1) const;
@@ -223,6 +250,9 @@ public:
typedef const_iterator ConstIterator;
typedef int size_type;
inline void push_back(const T &t) { append(t); }
+#ifdef Q_COMPILER_RVALUE_REFS
+ void push_back(T &&t) { append(std::move(t)); }
+#endif
inline void push_front(const T &t) { prepend(t); }
void pop_back() { removeLast(); }
void pop_front() { removeFirst(); }
@@ -265,7 +295,6 @@ private:
{
return (i <= d->end()) && (d->begin() <= i);
}
- iterator c2m(const_iterator it) { return begin() + (it - cbegin()); }
class AlignmentDummy { Data header; T array[1]; };
};
@@ -602,14 +631,14 @@ void QVector<T>::append(const T &t)
{
const bool isTooSmall = uint(d->size + 1) > d->alloc;
if (!isDetached() || isTooSmall) {
- const T copy(t);
+ T copy(t);
QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
reallocData(d->size, isTooSmall ? d->size + 1 : d->alloc, opt);
if (QTypeInfo<T>::isComplex)
- new (d->end()) T(copy);
+ new (d->end()) T(qMove(copy));
else
- *d->end() = copy;
+ *d->end() = qMove(copy);
} else {
if (QTypeInfo<T>::isComplex)
@@ -620,6 +649,22 @@ void QVector<T>::append(const T &t)
++d->size;
}
+#ifdef Q_COMPILER_RVALUE_REFS
+template <typename T>
+void QVector<T>::append(T &&t)
+{
+ const bool isTooSmall = uint(d->size + 1) > d->alloc;
+ if (!isDetached() || isTooSmall) {
+ QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
+ reallocData(d->size, isTooSmall ? d->size + 1 : d->alloc, opt);
+ }
+
+ new (d->end()) T(std::move(t));
+
+ ++d->size;
+}
+#endif
+
template <typename T>
void QVector<T>::removeLast()
{
@@ -873,6 +918,43 @@ QList<T> QList<T>::fromVector(const QVector<T> &vector)
Q_DECLARE_SEQUENTIAL_ITERATOR(Vector)
Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(Vector)
+template <typename T>
+uint qHash(const QVector<T> &key, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHashRange(key.cbegin(), key.cend(), seed)))
+{
+ return qHashRange(key.cbegin(), key.cend(), seed);
+}
+
+template <typename T>
+bool operator<(const QVector<T> &lhs, const QVector<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end())))
+{
+ return std::lexicographical_compare(lhs.begin(), lhs.end(),
+ rhs.begin(), rhs.end());
+}
+
+template <typename T>
+inline bool operator>(const QVector<T> &lhs, const QVector<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return rhs < lhs;
+}
+
+template <typename T>
+inline bool operator<=(const QVector<T> &lhs, const QVector<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs > rhs);
+}
+
+template <typename T>
+inline bool operator>=(const QVector<T> &lhs, const QVector<T> &rhs)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
+{
+ return !(lhs < rhs);
+}
+
/*
### Qt 5:
### This needs to be removed for next releases of Qt. It is a workaround for vc++ because
diff --git a/src/corelib/tools/qversionnumber.cpp b/src/corelib/tools/qversionnumber.cpp
index 660f40b107..4197fc47b1 100644
--- a/src/corelib/tools/qversionnumber.cpp
+++ b/src/corelib/tools/qversionnumber.cpp
@@ -32,7 +32,7 @@
**
****************************************************************************/
-#include <QtCore/private/qversionnumber_p.h>
+#include <QtCore/qversionnumber.h>
#include <QtCore/qhash.h>
#include <QtCore/private/qlocale_tools_p.h>
#include <QtCore/qcollator.h>
@@ -53,8 +53,7 @@ QT_BEGIN_NAMESPACE
/*!
\class QVersionNumber
\inmodule QtCore
- \internal
- \since 5.4
+ \since 5.6
\brief The QVersionNumber class contains a version number with an arbitrary
number of segments.
@@ -168,6 +167,17 @@ QT_BEGIN_NAMESPACE
\sa majorVersion(), minorVersion(), microVersion()
*/
+QVector<int> QVersionNumber::segments() const
+{
+ if (m_segments.isUsingPointer())
+ return *m_segments.pointer_segments;
+
+ QVector<int> result;
+ result.resize(segmentCount());
+ for (int i = 0; i < segmentCount(); ++i)
+ result[i] = segmentAt(i);
+ return result;
+}
/*!
\fn int QVersionNumber::segmentAt(int index) const
@@ -196,6 +206,17 @@ QT_BEGIN_NAMESPACE
\snippet qversionnumber/main.cpp 4
*/
+QVersionNumber QVersionNumber::normalized() const
+{
+ int i;
+ for (i = m_segments.size(); i; --i)
+ if (m_segments.at(i - 1) != 0)
+ break;
+
+ QVersionNumber result(*this);
+ result.m_segments.resize(i);
+ return result;
+}
/*!
\fn bool QVersionNumber::isPrefixOf(const QVersionNumber &other) const
@@ -209,8 +230,13 @@ QT_BEGIN_NAMESPACE
*/
bool QVersionNumber::isPrefixOf(const QVersionNumber &other) const Q_DECL_NOTHROW
{
- return m_segments.size() <= other.m_segments.size() &&
- std::equal(m_segments.begin(), m_segments.end(), other.m_segments.begin());
+ if (segmentCount() > other.segmentCount())
+ return false;
+ for (int i = 0; i < segmentCount(); ++i) {
+ if (segmentAt(i) != other.segmentAt(i))
+ return false;
+ }
+ return true;
}
/*!
@@ -228,30 +254,37 @@ bool QVersionNumber::isPrefixOf(const QVersionNumber &other) const Q_DECL_NOTHRO
*/
int QVersionNumber::compare(const QVersionNumber &v1, const QVersionNumber &v2) Q_DECL_NOTHROW
{
- QVector<int>::const_iterator i1 = v1.m_segments.constBegin();
- const QVector<int>::const_iterator e1 = v1.m_segments.constEnd();
- QVector<int>::const_iterator i2 = v2.m_segments.constBegin();
- const QVector<int>::const_iterator e2 = v2.m_segments.constEnd();
-
- while (i1 != e1 && i2 != e2) {
- if (*i1 != *i2)
- return (*i1 - *i2);
- ++i1;
- ++i2;
+ int commonlen;
+
+ if (Q_LIKELY(!v1.m_segments.isUsingPointer() && !v2.m_segments.isUsingPointer())) {
+ // we can't use memcmp because it interprets the data as unsigned bytes
+ const qint8 *ptr1 = v1.m_segments.inline_segments + InlineSegmentStartIdx;
+ const qint8 *ptr2 = v2.m_segments.inline_segments + InlineSegmentStartIdx;
+ commonlen = qMin(v1.m_segments.size(),
+ v2.m_segments.size());
+ for (int i = 0; i < commonlen; ++i)
+ if (int x = ptr1[i] - ptr2[i])
+ return x;
+ } else {
+ commonlen = qMin(v1.segmentCount(), v2.segmentCount());
+ for (int i = 0; i < commonlen; ++i) {
+ if (v1.segmentAt(i) != v2.segmentAt(i))
+ return v1.segmentAt(i) - v2.segmentAt(i);
+ }
}
// ran out of segments in v1 and/or v2 and need to check the first trailing
// segment to finish the compare
- if (i1 != e1) {
+ if (v1.segmentCount() > commonlen) {
// v1 is longer
- if (*i1 != 0)
- return *i1;
+ if (v1.segmentAt(commonlen) != 0)
+ return v1.segmentAt(commonlen);
else
return 1;
- } else if (i2 != e2) {
+ } else if (v2.segmentCount() > commonlen) {
// v2 is longer
- if (*i2 != 0)
- return -*i2;
+ if (v2.segmentAt(commonlen) != 0)
+ return -v2.segmentAt(commonlen);
else
return -1;
}
@@ -271,13 +304,20 @@ int QVersionNumber::compare(const QVersionNumber &v1, const QVersionNumber &v2)
QVersionNumber QVersionNumber::commonPrefix(const QVersionNumber &v1,
const QVersionNumber &v2)
{
- int min = qMin(v1.m_segments.size(), v2.m_segments.size());
- QVector<int>::const_iterator i1 = v1.m_segments.begin();
- QVector<int>::const_iterator e1;
- e1 = std::mismatch(i1,
- v1.m_segments.begin() + min,
- v2.m_segments.begin()).first;
- return QVersionNumber(v1.m_segments.mid(0, e1 - i1));
+ int commonlen = qMin(v1.segmentCount(), v2.segmentCount());
+ int i;
+ for (i = 0; i < commonlen; ++i) {
+ if (v1.segmentAt(i) != v2.segmentAt(i))
+ break;
+ }
+
+ if (i == 0)
+ return QVersionNumber();
+
+ // try to use the one with inline segments, if there's one
+ QVersionNumber result(!v1.m_segments.isUsingPointer() ? v1 : v2);
+ result.m_segments.resize(i);
+ return result;
}
/*!
@@ -348,12 +388,12 @@ QVersionNumber QVersionNumber::commonPrefix(const QVersionNumber &v1,
QString QVersionNumber::toString() const
{
QString version;
- version.reserve(qMax(m_segments.size() * 2 - 1, 0));
+ version.reserve(qMax(segmentCount() * 2 - 1, 0));
bool first = true;
- for (QVector<int>::const_iterator it = m_segments.begin(), end = m_segments.end(); it != end; ++it) {
+ for (int i = 0; i < segmentCount(); ++i) {
if (!first)
version += QLatin1Char('.');
- version += QString::number(*it);
+ version += QString::number(segmentAt(i));
first = false;
}
return version;
@@ -401,19 +441,17 @@ QVersionNumber QVersionNumber::fromString(const QString &string, int *suffixInde
return QVersionNumber(qMove(seg));
}
-/*!
- \fn QVersionNumber QVersionNumber::normalizedImpl(QVector<int> &segs)
-
- Implementation of the normalized() function. Takes the movable list \a segs
- and normalizes them.
-
- \internal
- */
-QVersionNumber QVersionNumber::normalizedImpl(QVector<int> &segs)
+void QVersionNumber::SegmentStorage::setVector(int len, int maj, int min, int mic)
{
- while (segs.size() && segs.last() == 0)
- segs.pop_back();
- return QVersionNumber(qMove(segs));
+ pointer_segments = new QVector<int>;
+ pointer_segments->resize(len);
+ pointer_segments->data()[0] = maj;
+ if (len > 1) {
+ pointer_segments->data()[1] = min;
+ if (len > 2) {
+ pointer_segments->data()[2] = mic;
+ }
+ }
}
#ifndef QT_NO_DATASTREAM
@@ -442,7 +480,9 @@ QDataStream& operator<<(QDataStream &out, const QVersionNumber &version)
*/
QDataStream& operator>>(QDataStream &in, QVersionNumber &version)
{
- in >> version.m_segments;
+ if (!version.m_segments.isUsingPointer())
+ version.m_segments.pointer_segments = new QVector<int>;
+ in >> *version.m_segments.pointer_segments;
return in;
}
#endif
@@ -459,14 +499,18 @@ QDebug operator<<(QDebug debug, const QVersionNumber &version)
/*!
\fn uint qHash(const QVersionNumber &key, uint seed)
\relates QHash
- \since 5.4
+ \since 5.6
Returns the hash value for the \a key, using \a seed to seed the
calculation.
*/
uint qHash(const QVersionNumber &key, uint seed)
{
- return qHashRange(key.m_segments.begin(), key.m_segments.end(), seed);
+ QtPrivate::QHashCombine hash;
+ for (int i = 0; i < key.segmentCount(); ++i)
+ seed = hash(seed, key.segmentAt(i));
+ return seed;
}
QT_END_NAMESPACE
+
diff --git a/src/corelib/tools/qversionnumber.h b/src/corelib/tools/qversionnumber.h
new file mode 100644
index 0000000000..ebf1844f38
--- /dev/null
+++ b/src/corelib/tools/qversionnumber.h
@@ -0,0 +1,313 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2014 Keith Gardner <kreios4004@gmail.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QVERSIONNUMBER_H
+#define QVERSIONNUMBER_H
+
+#include <QtCore/qnamespace.h>
+#include <QtCore/qstring.h>
+#include <QtCore/qvector.h>
+#include <QtCore/qmetatype.h>
+#include <QtCore/qtypeinfo.h>
+
+QT_BEGIN_NAMESPACE
+
+class QVersionNumber;
+Q_CORE_EXPORT uint qHash(const QVersionNumber &key, uint seed = 0);
+
+#ifndef QT_NO_DATASTREAM
+Q_CORE_EXPORT QDataStream& operator<<(QDataStream &out, const QVersionNumber &version);
+Q_CORE_EXPORT QDataStream& operator>>(QDataStream &in, QVersionNumber &version);
+#endif
+
+class QVersionNumber
+{
+ /*
+ * QVersionNumber stores small values inline, without memory allocation.
+ * We do that by setting the LSB in the pointer that would otherwise hold
+ * the longer form of the segments.
+ * The constants below help us deal with the permutations for 32- and 64-bit,
+ * little- and big-endian architectures.
+ */
+ enum {
+ // in little-endian, inline_segments[0] is shared with the pointer's LSB, while
+ // in big-endian, it's inline_segments[7]
+ InlineSegmentMarker = Q_BYTE_ORDER == Q_LITTLE_ENDIAN ? 0 : sizeof(void*) - 1,
+ InlineSegmentStartIdx = !InlineSegmentMarker, // 0 for BE, 1 for LE
+ InlineSegmentCount = sizeof(void*) - 1
+ };
+ Q_STATIC_ASSERT(InlineSegmentCount >= 3); // at least major, minor, micro
+
+ struct SegmentStorage {
+ // Note: we alias the use of dummy and inline_segments in the use of the
+ // union below. This is undefined behavior in C++98, but most compilers implement
+ // the C++11 behavior. The one known exception is older versions of Sun Studio.
+ union {
+ quintptr dummy;
+ qint8 inline_segments[sizeof(void*)];
+ QVector<int> *pointer_segments;
+ };
+
+ // set the InlineSegmentMarker and set length to zero
+ SegmentStorage() Q_DECL_NOTHROW : dummy(1) {}
+
+ SegmentStorage(const QVector<int> &seg)
+ {
+ if (dataFitsInline(seg.begin(), seg.size()))
+ setInlineData(seg.begin(), seg.size());
+ else
+ pointer_segments = new QVector<int>(seg);
+ }
+
+ SegmentStorage(const SegmentStorage &other)
+ {
+ if (other.isUsingPointer())
+ pointer_segments = new QVector<int>(*other.pointer_segments);
+ else
+ dummy = other.dummy;
+ }
+
+ SegmentStorage &operator=(const SegmentStorage &other)
+ {
+ if (isUsingPointer() && other.isUsingPointer()) {
+ *pointer_segments = *other.pointer_segments;
+ } else if (other.isUsingPointer()) {
+ pointer_segments = new QVector<int>(*other.pointer_segments);
+ } else {
+ if (isUsingPointer())
+ delete pointer_segments;
+ dummy = other.dummy;
+ }
+ return *this;
+ }
+
+#ifdef Q_COMPILER_RVALUE_REFS
+ SegmentStorage(SegmentStorage &&other) Q_DECL_NOTHROW
+ : dummy(other.dummy)
+ {
+ other.dummy = 1;
+ }
+
+ SegmentStorage &operator=(SegmentStorage &&other) Q_DECL_NOTHROW
+ {
+ qSwap(dummy, other.dummy);
+ return *this;
+ }
+
+ explicit SegmentStorage(QVector<int> &&seg)
+ {
+ if (dataFitsInline(seg.begin(), seg.size()))
+ setInlineData(seg.begin(), seg.size());
+ else
+ pointer_segments = new QVector<int>(std::move(seg));
+ }
+#endif
+#ifdef Q_COMPILER_INITIALIZER_LISTS
+ SegmentStorage(std::initializer_list<int> args)
+ {
+ if (dataFitsInline(args.begin(), int(args.size()))) {
+ setInlineData(args.begin(), int(args.size()));
+ } else {
+ pointer_segments = new QVector<int>(args);
+ }
+ }
+#endif
+
+ ~SegmentStorage() { if (isUsingPointer()) delete pointer_segments; }
+
+ bool isUsingPointer() const Q_DECL_NOTHROW
+ { return (inline_segments[InlineSegmentMarker] & 1) == 0; }
+
+ int size() const Q_DECL_NOTHROW
+ { return isUsingPointer() ? pointer_segments->size() : (inline_segments[InlineSegmentMarker] >> 1); }
+
+ void setInlineSize(int len)
+ { inline_segments[InlineSegmentMarker] = 1 + 2 * len; }
+
+ void resize(int len)
+ {
+ if (isUsingPointer())
+ pointer_segments->resize(len);
+ else
+ setInlineSize(len);
+ }
+
+ int at(int index) const
+ {
+ return isUsingPointer() ?
+ pointer_segments->at(index) :
+ inline_segments[InlineSegmentStartIdx + index];
+ }
+
+ void setSegments(int len, int maj, int min = 0, int mic = 0)
+ {
+ if (maj == qint8(maj) && min == qint8(min) && mic == qint8(mic)) {
+ int data[] = { maj, min, mic };
+ setInlineData(data, len);
+ } else {
+ setVector(len, maj, min, mic);
+ }
+ }
+
+ private:
+ static bool dataFitsInline(const int *data, int len)
+ {
+ if (len > InlineSegmentCount)
+ return false;
+ for (int i = 0; i < len; ++i)
+ if (data[i] != qint8(data[i]))
+ return false;
+ return true;
+ }
+ void setInlineData(const int *data, int len)
+ {
+ dummy = 1 + len * 2;
+#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
+ for (int i = 0; i < len; ++i)
+ dummy |= quintptr(data[i] & 0xFF) << (8 * (i + 1));
+#elif Q_BYTE_ORDER == Q_BIG_ENDIAN
+ for (int i = 0; i < len; ++i)
+ dummy |= quintptr(data[i] & 0xFF) << (8 * (sizeof(void *) - i - 1));
+#else
+ // the code above is equivalent to:
+ setInlineSize(len);
+ for (int i = 0; i < len; ++i)
+ inline_segments[InlineSegmentStartIdx + i] = data[i] & 0xFF;
+#endif
+ }
+
+ Q_CORE_EXPORT void setVector(int len, int maj, int min, int mic);
+ } m_segments;
+
+public:
+ inline QVersionNumber() Q_DECL_NOTHROW
+ : m_segments()
+ {}
+ inline explicit QVersionNumber(const QVector<int> &seg)
+ : m_segments(seg)
+ {}
+
+ // compiler-generated copy/move ctor/assignment operators and the destructor are ok
+
+#ifdef Q_COMPILER_RVALUE_REFS
+ explicit QVersionNumber(QVector<int> &&seg)
+ : m_segments(std::move(seg))
+ {}
+#endif
+
+#ifdef Q_COMPILER_INITIALIZER_LISTS
+ inline QVersionNumber(std::initializer_list<int> args)
+ : m_segments(args)
+ {}
+#endif
+
+ inline explicit QVersionNumber(int maj)
+ { m_segments.setSegments(1, maj); }
+
+ inline explicit QVersionNumber(int maj, int min)
+ { m_segments.setSegments(2, maj, min); }
+
+ inline explicit QVersionNumber(int maj, int min, int mic)
+ { m_segments.setSegments(3, maj, min, mic); }
+
+ inline bool isNull() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return segmentCount() == 0; }
+
+ inline bool isNormalized() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return isNull() || segmentAt(segmentCount() - 1) != 0; }
+
+ inline int majorVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return segmentAt(0); }
+
+ inline int minorVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return segmentAt(1); }
+
+ inline int microVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return segmentAt(2); }
+
+ Q_CORE_EXPORT QVersionNumber normalized() const Q_REQUIRED_RESULT;
+
+ Q_CORE_EXPORT QVector<int> segments() const Q_REQUIRED_RESULT;
+
+ inline int segmentAt(int index) const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return (m_segments.size() > index) ? m_segments.at(index) : 0; }
+
+ inline int segmentCount() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
+ { return m_segments.size(); }
+
+ Q_CORE_EXPORT bool isPrefixOf(const QVersionNumber &other) const Q_DECL_NOTHROW Q_REQUIRED_RESULT;
+
+ Q_CORE_EXPORT static int compare(const QVersionNumber &v1, const QVersionNumber &v2) Q_DECL_NOTHROW Q_REQUIRED_RESULT;
+
+ Q_CORE_EXPORT static Q_DECL_PURE_FUNCTION QVersionNumber commonPrefix(const QVersionNumber &v1, const QVersionNumber &v2) Q_REQUIRED_RESULT;
+
+ Q_CORE_EXPORT QString toString() const Q_REQUIRED_RESULT;
+ Q_CORE_EXPORT static Q_DECL_PURE_FUNCTION QVersionNumber fromString(const QString &string, int *suffixIndex = 0) Q_REQUIRED_RESULT;
+
+private:
+#ifndef QT_NO_DATASTREAM
+ friend Q_CORE_EXPORT QDataStream& operator>>(QDataStream &in, QVersionNumber &version);
+#endif
+ friend Q_CORE_EXPORT uint qHash(const QVersionNumber &key, uint seed);
+};
+
+Q_DECLARE_TYPEINFO(QVersionNumber, Q_MOVABLE_TYPE);
+
+#ifndef QT_NO_DEBUG_STREAM
+Q_CORE_EXPORT QDebug operator<<(QDebug, const QVersionNumber &version);
+#endif
+
+Q_REQUIRED_RESULT inline bool operator> (const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) > 0; }
+
+Q_REQUIRED_RESULT inline bool operator>=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) >= 0; }
+
+Q_REQUIRED_RESULT inline bool operator< (const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) < 0; }
+
+Q_REQUIRED_RESULT inline bool operator<=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) <= 0; }
+
+Q_REQUIRED_RESULT inline bool operator==(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) == 0; }
+
+Q_REQUIRED_RESULT inline bool operator!=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
+{ return QVersionNumber::compare(lhs, rhs) != 0; }
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(QVersionNumber)
+
+#endif //QVERSIONNUMBER_H
diff --git a/src/corelib/tools/qversionnumber_p.h b/src/corelib/tools/qversionnumber_p.h
deleted file mode 100644
index 2da3103be3..0000000000
--- a/src/corelib/tools/qversionnumber_p.h
+++ /dev/null
@@ -1,193 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Copyright (C) 2014 Keith Gardner <kreios4004@gmail.com>
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QVERSIONNUMBER_H
-#define QVERSIONNUMBER_H
-
-#include <QtCore/qnamespace.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qvector.h>
-#include <QtCore/qmetatype.h>
-#include <QtCore/qtypeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-class QVersionNumber;
-Q_CORE_EXPORT uint qHash(const QVersionNumber &key, uint seed = 0);
-
-#ifndef QT_NO_DATASTREAM
-Q_CORE_EXPORT QDataStream& operator<<(QDataStream &out, const QVersionNumber &version);
-Q_CORE_EXPORT QDataStream& operator>>(QDataStream &in, QVersionNumber &version);
-#endif
-
-class QVersionNumber
-{
-public:
- inline QVersionNumber() Q_DECL_NOTHROW
- : m_segments()
- {}
- // compiler-generated copy/move ctor/assignment operators are ok
-
- inline explicit QVersionNumber(const QVector<int> &seg) Q_DECL_NOTHROW
- : m_segments(seg)
- {}
-#ifdef Q_COMPILER_RVALUE_REFS
- inline explicit QVersionNumber(QVector<int> &&seg) Q_DECL_NOTHROW
- : m_segments(qMove(seg))
- {}
-#endif
-#ifdef Q_COMPILER_INITIALIZER_LISTS
- inline QVersionNumber(std::initializer_list<int> args)
- : m_segments(args)
- {}
-#endif
-
- inline explicit QVersionNumber(int maj)
- { m_segments.reserve(1); m_segments << maj; }
-
- inline explicit QVersionNumber(int maj, int min)
- { m_segments.reserve(2); m_segments << maj << min; }
-
- inline explicit QVersionNumber(int maj, int min, int mic)
- { m_segments.reserve(3); m_segments << maj << min << mic; }
-
- inline bool isNull() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return m_segments.isEmpty(); }
-
- inline bool isNormalized() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return isNull() || m_segments.last() != 0; }
-
- inline int majorVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return segmentAt(0); }
-
- inline int minorVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return segmentAt(1); }
-
- inline int microVersion() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return segmentAt(2); }
-
-#if defined(Q_COMPILER_REF_QUALIFIERS)
-# if defined(Q_CC_GNU)
- // required due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61941
-# pragma push_macro("Q_REQUIRED_RESULT")
-# undef Q_REQUIRED_RESULT
-# define Q_REQUIRED_RESULT
-# define Q_REQUIRED_RESULT_pushed
-# endif
- inline QVersionNumber normalized() const & Q_REQUIRED_RESULT
- {
- QVector<int> segs(m_segments);
- return normalizedImpl(segs);
- }
-
- inline QVersionNumber normalized() && Q_REQUIRED_RESULT
- {
- return normalizedImpl(m_segments);
- }
-
- inline QVector<int> segments() const & Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return m_segments; }
-
- inline QVector<int> segments() && Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return qMove(m_segments); }
-
-# ifdef Q_REQUIRED_RESULT_pushed
-# pragma pop_macro("Q_REQUIRED_RESULT")
-# endif
-#else
- inline QVersionNumber normalized() const Q_REQUIRED_RESULT
- {
- QVector<int> segs(m_segments);
- return normalizedImpl(segs);
- }
-
- inline QVector<int> segments() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return m_segments; }
-#endif
-
- inline int segmentAt(int index) const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return (m_segments.size() > index) ? m_segments.at(index) : 0; }
-
- inline int segmentCount() const Q_DECL_NOTHROW Q_REQUIRED_RESULT
- { return m_segments.size(); }
-
- Q_CORE_EXPORT bool isPrefixOf(const QVersionNumber &other) const Q_DECL_NOTHROW Q_REQUIRED_RESULT;
-
- Q_CORE_EXPORT static int compare(const QVersionNumber &v1, const QVersionNumber &v2) Q_DECL_NOTHROW Q_REQUIRED_RESULT;
-
- Q_CORE_EXPORT static Q_DECL_PURE_FUNCTION QVersionNumber commonPrefix(const QVersionNumber &v1, const QVersionNumber &v2) Q_REQUIRED_RESULT;
-
- Q_CORE_EXPORT QString toString() const Q_REQUIRED_RESULT;
- Q_CORE_EXPORT static Q_DECL_PURE_FUNCTION QVersionNumber fromString(const QString &string, int *suffixIndex = 0) Q_REQUIRED_RESULT;
-
-private:
- Q_CORE_EXPORT static QVersionNumber normalizedImpl(QVector<int> &segs) Q_REQUIRED_RESULT;
-
-#ifndef QT_NO_DATASTREAM
- friend Q_CORE_EXPORT QDataStream& operator>>(QDataStream &in, QVersionNumber &version);
-#endif
- friend Q_CORE_EXPORT uint qHash(const QVersionNumber &key, uint seed);
-
- QVector<int> m_segments;
-};
-
-Q_DECLARE_TYPEINFO(QVersionNumber, Q_MOVABLE_TYPE);
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_CORE_EXPORT QDebug operator<<(QDebug, const QVersionNumber &version);
-#endif
-
-Q_REQUIRED_RESULT inline bool operator> (const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) > 0; }
-
-Q_REQUIRED_RESULT inline bool operator>=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) >= 0; }
-
-Q_REQUIRED_RESULT inline bool operator< (const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) < 0; }
-
-Q_REQUIRED_RESULT inline bool operator<=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) <= 0; }
-
-Q_REQUIRED_RESULT inline bool operator==(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) == 0; }
-
-Q_REQUIRED_RESULT inline bool operator!=(const QVersionNumber &lhs, const QVersionNumber &rhs) Q_DECL_NOTHROW
-{ return QVersionNumber::compare(lhs, rhs) != 0; }
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QVersionNumber)
-
-#endif //QVERSIONNUMBER_H
diff --git a/src/corelib/tools/tools.pri b/src/corelib/tools/tools.pri
index 5de0c09a4d..c43fd761d8 100644
--- a/src/corelib/tools/tools.pri
+++ b/src/corelib/tools/tools.pri
@@ -9,6 +9,7 @@ HEADERS += \
tools/qarraydatapointer.h \
tools/qbitarray.h \
tools/qbytearray.h \
+ tools/qbytearray_p.h \
tools/qbytearraylist.h \
tools/qbytearraymatcher.h \
tools/qbytedata_p.h \
@@ -26,6 +27,7 @@ HEADERS += \
tools/qeasingcurve.h \
tools/qfreelist_p.h \
tools/qhash.h \
+ tools/qhashfunctions.h \
tools/qiterator.h \
tools/qline.h \
tools/qlinkedlist.h \
@@ -73,7 +75,7 @@ HEADERS += \
tools/qunicodetools_p.h \
tools/qvarlengtharray.h \
tools/qvector.h \
- tools/qversionnumber_p.h
+ tools/qversionnumber.h
SOURCES += \
@@ -105,6 +107,7 @@ SOURCES += \
tools/qrect.cpp \
tools/qregexp.cpp \
tools/qrefcount.cpp \
+ tools/qringbuffer.cpp \
tools/qshareddata.cpp \
tools/qsharedpointer.cpp \
tools/qsimd.cpp \
diff --git a/src/corelib/xml/qxmlstream.h b/src/corelib/xml/qxmlstream.h
index 21188bc5e0..7b1ea624c5 100644
--- a/src/corelib/xml/qxmlstream.h
+++ b/src/corelib/xml/qxmlstream.h
@@ -75,6 +75,28 @@ public:
QXmlStreamAttribute(const QString &qualifiedName, const QString &value);
QXmlStreamAttribute(const QString &namespaceUri, const QString &name, const QString &value);
QXmlStreamAttribute(const QXmlStreamAttribute &);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QXmlStreamAttribute(QXmlStreamAttribute &&other) Q_DECL_NOTHROW // = default;
+ : m_name(std::move(other.m_name)),
+ m_namespaceUri(std::move(other.m_namespaceUri)),
+ m_qualifiedName(std::move(other.m_qualifiedName)),
+ m_value(std::move(other.m_value)),
+ reserved(other.reserved),
+ m_isDefault(other.m_isDefault)
+ {
+ other.reserved = Q_NULLPTR;
+ }
+ QXmlStreamAttribute &operator=(QXmlStreamAttribute &&other) Q_DECL_NOTHROW // = default;
+ {
+ m_name = std::move(other.m_name);
+ m_namespaceUri = std::move(other.m_namespaceUri);
+ m_qualifiedName = std::move(other.m_qualifiedName);
+ m_value = std::move(other.m_value);
+ qSwap(reserved, other.reserved);
+ m_isDefault = other.m_isDefault;
+ return *this;
+ }
+#endif
QXmlStreamAttribute& operator=(const QXmlStreamAttribute &);
~QXmlStreamAttribute();
inline QStringRef namespaceUri() const { return m_namespaceUri; }
diff --git a/src/dbus/qdbus_symbols.cpp b/src/dbus/qdbus_symbols.cpp
index b82d92b561..395a436869 100644
--- a/src/dbus/qdbus_symbols.cpp
+++ b/src/dbus/qdbus_symbols.cpp
@@ -48,7 +48,7 @@ void (*qdbus_resolve_me(const char *name))();
#if !defined QT_LINKED_LIBDBUS
-#ifndef QT_BOOTSTRAPPED
+#ifndef QT_NO_LIBRARY
static QLibrary *qdbus_libdbus = 0;
void qdbus_unloadLibDBus()
@@ -65,7 +65,7 @@ void qdbus_unloadLibDBus()
bool qdbus_loadLibDBus()
{
-#ifndef QT_BOOTSTRAPPED
+#ifndef QT_NO_LIBRARY
#ifdef QT_BUILD_INTERNAL
// this is to simulate a library load failure for our autotest suite.
if (!qEnvironmentVariableIsEmpty("QT_SIMULATE_DBUS_LIBFAIL"))
@@ -118,7 +118,7 @@ bool qdbus_loadLibDBus()
#endif
}
-#ifndef QT_BOOTSTRAPPED
+#ifndef QT_NO_LIBRARY
void (*qdbus_resolve_conditionally(const char *name))()
{
if (qdbus_loadLibDBus())
@@ -129,7 +129,7 @@ void (*qdbus_resolve_conditionally(const char *name))()
void (*qdbus_resolve_me(const char *name))()
{
-#ifndef QT_BOOTSTRAPPED
+#ifndef QT_NO_LIBRARY
if (!qdbus_loadLibDBus())
qFatal("Cannot find libdbus-1 in your system to resolve symbol '%s'.", name);
@@ -144,7 +144,7 @@ void (*qdbus_resolve_me(const char *name))()
#endif
}
-#else // QT_LINKED_LIBDBUS
+#else
static void qdbus_unloadLibDBus()
{
if (qEnvironmentVariableIsSet("QDBUS_FORCE_SHUTDOWN"))
@@ -153,7 +153,7 @@ static void qdbus_unloadLibDBus()
#endif // !QT_LINKED_LIBDBUS
-#ifndef QT_BOOTSTRAPPED
+#if defined(QT_LINKED_LIBDBUS) || !defined(QT_NO_LIBRARY)
Q_DESTRUCTOR_FUNCTION(qdbus_unloadLibDBus)
#endif
diff --git a/src/dbus/qdbusabstractadaptor.cpp b/src/dbus/qdbusabstractadaptor.cpp
index e7529f794e..2864e076e9 100644
--- a/src/dbus/qdbusabstractadaptor.cpp
+++ b/src/dbus/qdbusabstractadaptor.cpp
@@ -317,7 +317,9 @@ void QDBusAdaptorConnector::relay(QObject *senderObj, int lastSignalIdx, void **
}
QVariantList args;
- for (int i = 1; i < types.count(); ++i)
+ const int numTypes = types.count();
+ args.reserve(numTypes - 1);
+ for (int i = 1; i < numTypes; ++i)
args << QVariant(types.at(i), argv[i]);
// now emit the signal with all the information
diff --git a/src/dbus/qdbusabstractadaptor_p.h b/src/dbus/qdbusabstractadaptor_p.h
index 9e9375cefc..5ff33f8bef 100644
--- a/src/dbus/qdbusabstractadaptor_p.h
+++ b/src/dbus/qdbusabstractadaptor_p.h
@@ -50,7 +50,6 @@
#include <QtCore/qobject.h>
#include <QtCore/qmap.h>
-#include <QtCore/qhash.h>
#include <QtCore/qreadwritelock.h>
#include <QtCore/qvariant.h>
#include <QtCore/qvector.h>
@@ -127,6 +126,7 @@ public: // member variables
private:
static int relaySlotMethodIndex();
};
+Q_DECLARE_TYPEINFO(QDBusAdaptorConnector::AdaptorData, Q_PRIMITIVE_TYPE);
extern QDBusAdaptorConnector *qDBusFindAdaptorConnector(QObject *object);
extern QDBusAdaptorConnector *qDBusCreateAdaptorConnector(QObject *object);
diff --git a/src/dbus/qdbusargument.h b/src/dbus/qdbusargument.h
index 42b266792a..a6bc396861 100644
--- a/src/dbus/qdbusargument.h
+++ b/src/dbus/qdbusargument.h
@@ -70,9 +70,15 @@ public:
QDBusArgument();
QDBusArgument(const QDBusArgument &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDBusArgument(QDBusArgument &&other) Q_DECL_NOTHROW : d(other.d) { other.d = Q_NULLPTR; }
+ QDBusArgument &operator=(QDBusArgument &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDBusArgument &operator=(const QDBusArgument &other);
~QDBusArgument();
+ void swap(QDBusArgument &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
+
// used for marshalling (Qt -> D-BUS)
QDBusArgument &operator<<(uchar arg);
QDBusArgument &operator<<(bool arg);
@@ -140,6 +146,7 @@ protected:
friend class QDBusArgumentPrivate;
mutable QDBusArgumentPrivate *d;
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusArgument)
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QDBusArgument)
@@ -147,7 +154,7 @@ QT_BEGIN_NAMESPACE
template<typename T> inline T qdbus_cast(const QDBusArgument &arg
#ifndef Q_QDOC
-, T * = 0
+, T * = Q_NULLPTR
#endif
)
{
@@ -158,7 +165,7 @@ template<typename T> inline T qdbus_cast(const QDBusArgument &arg
template<typename T> inline T qdbus_cast(const QVariant &v
#ifndef Q_QDOC
-, T * = 0
+, T * = Q_NULLPTR
#endif
)
{
diff --git a/src/dbus/qdbusconnection.h b/src/dbus/qdbusconnection.h
index 10598c0b7b..8b2e9234aa 100644
--- a/src/dbus/qdbusconnection.h
+++ b/src/dbus/qdbusconnection.h
@@ -99,11 +99,12 @@ public:
ExportChildObjects = 0x1000
// Reserved = 0xff000000
};
+ Q_DECLARE_FLAGS(RegisterOptions, RegisterOption)
+
enum UnregisterMode {
UnregisterNode,
UnregisterTree
};
- Q_DECLARE_FLAGS(RegisterOptions, RegisterOption)
enum VirtualObjectRegisterOption {
SingleNode = 0x0,
@@ -121,9 +122,14 @@ public:
explicit QDBusConnection(const QString &name);
QDBusConnection(const QDBusConnection &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDBusConnection(QDBusConnection &&other) Q_DECL_NOTHROW : d(other.d) { other.d = Q_NULLPTR; }
+ QDBusConnection &operator=(QDBusConnection &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDBusConnection &operator=(const QDBusConnection &other);
~QDBusConnection();
- QDBusConnection &operator=(const QDBusConnection &other);
+ void swap(QDBusConnection &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isConnected() const;
QString baseService() const;
@@ -199,9 +205,11 @@ private:
friend class QDBusConnectionPrivate;
QDBusConnectionPrivate *d;
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusConnection)
Q_DECLARE_OPERATORS_FOR_FLAGS(QDBusConnection::RegisterOptions)
Q_DECLARE_OPERATORS_FOR_FLAGS(QDBusConnection::VirtualObjectRegisterOptions)
+Q_DECLARE_OPERATORS_FOR_FLAGS(QDBusConnection::ConnectionCapabilities)
QT_END_NAMESPACE
diff --git a/src/dbus/qdbusconnection_p.h b/src/dbus/qdbusconnection_p.h
index 5d8777c622..752ca9c37a 100644
--- a/src/dbus/qdbusconnection_p.h
+++ b/src/dbus/qdbusconnection_p.h
@@ -166,7 +166,7 @@ public:
// typedefs
typedef QMultiHash<int, Watcher> WatcherHash;
typedef QHash<int, DBusTimeout *> TimeoutHash;
- typedef QList<QPair<DBusTimeout *, int> > PendingTimeoutList;
+ typedef QVector<QPair<DBusTimeout *, int> > PendingTimeoutList;
typedef QMultiHash<QString, SignalHook> SignalHookHash;
typedef QHash<QString, QDBusMetaObject* > MetaObjectHash;
diff --git a/src/dbus/qdbuserror.cpp b/src/dbus/qdbuserror.cpp
index 2b13f90fac..40e97ae483 100644
--- a/src/dbus/qdbuserror.cpp
+++ b/src/dbus/qdbuserror.cpp
@@ -142,6 +142,7 @@ static inline const char *get(QDBusError::ErrorType code)
return errorMessages_string + errorMessages_indices[intcode];
}
+#ifndef QT_BOOTSTRAPPED
static inline QDBusError::ErrorType get(const char *name)
{
if (!name || !*name)
@@ -151,6 +152,7 @@ static inline QDBusError::ErrorType get(const char *name)
return QDBusError::ErrorType(i + int(QDBusError::Other));
return QDBusError::Other;
}
+#endif
/*!
\class QDBusError
diff --git a/src/dbus/qdbuserror.h b/src/dbus/qdbuserror.h
index c2c0ff8fc5..ce5275dee9 100644
--- a/src/dbus/qdbuserror.h
+++ b/src/dbus/qdbuserror.h
@@ -92,11 +92,25 @@ public:
#endif
QDBusError(ErrorType error, const QString &message);
QDBusError(const QDBusError &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDBusError(QDBusError &&other) Q_DECL_NOTHROW
+ : code(other.code), msg(std::move(other.msg)), nm(std::move(other.nm)), unused(other.unused)
+ { other.unused = Q_NULLPTR; }
+ QDBusError &operator=(QDBusError &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDBusError &operator=(const QDBusError &other);
#ifndef QT_BOOTSTRAPPED
QDBusError &operator=(const QDBusMessage &msg);
#endif
+ void swap(QDBusError &other) Q_DECL_NOTHROW
+ {
+ qSwap(code, other.code);
+ qSwap(msg, other.msg);
+ qSwap(nm, other.nm);
+ qSwap(unused, other.unused);
+ }
+
ErrorType type() const;
QString name() const;
QString message() const;
@@ -110,6 +124,7 @@ private:
QString nm;
void *unused;
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusError)
#ifndef QT_NO_DEBUG_STREAM
Q_DBUS_EXPORT QDebug operator<<(QDebug, const QDBusError &);
diff --git a/src/dbus/qdbusextratypes.h b/src/dbus/qdbusextratypes.h
index 390ff6c91c..8495b3a320 100644
--- a/src/dbus/qdbusextratypes.h
+++ b/src/dbus/qdbusextratypes.h
@@ -39,7 +39,10 @@
#include <QtCore/qvariant.h>
#include <QtCore/qstring.h>
#include <QtDBus/qdbusmacros.h>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
+#include <QtCore/qhashfunctions.h>
#ifndef QT_NO_DBUS
@@ -50,11 +53,18 @@ class Q_DBUS_EXPORT QDBusObjectPath
{
QString m_path;
public:
- inline QDBusObjectPath() { }
+ QDBusObjectPath() Q_DECL_NOTHROW : m_path() {}
+ // compiler-generated copy/move constructor/assignment operators are ok!
+ // compiler-generated destructor is ok!
inline explicit QDBusObjectPath(const char *path);
inline explicit QDBusObjectPath(QLatin1String path);
inline explicit QDBusObjectPath(const QString &path);
+#ifdef Q_COMPILER_RVALUE_REFS
+ explicit QDBusObjectPath(QString &&p) : m_path(std::move(p)) { doCheck(); }
+#endif
+
+ void swap(QDBusObjectPath &other) Q_DECL_NOTHROW { qSwap(m_path, other.m_path); }
inline void setPath(const QString &path);
@@ -64,6 +74,7 @@ public:
private:
void doCheck();
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusObjectPath)
inline QDBusObjectPath::QDBusObjectPath(const char *objectPath)
: m_path(QString::fromLatin1(objectPath))
@@ -89,7 +100,7 @@ inline bool operator!=(const QDBusObjectPath &lhs, const QDBusObjectPath &rhs)
inline bool operator<(const QDBusObjectPath &lhs, const QDBusObjectPath &rhs)
{ return lhs.path() < rhs.path(); }
-inline uint qHash(const QDBusObjectPath &objectPath, uint seed)
+inline uint qHash(const QDBusObjectPath &objectPath, uint seed = 0)
{ return qHash(objectPath.path(), seed); }
@@ -97,11 +108,18 @@ class Q_DBUS_EXPORT QDBusSignature
{
QString m_signature;
public:
- inline QDBusSignature() { }
+ QDBusSignature() Q_DECL_NOTHROW : m_signature() {}
+ // compiler-generated copy/move constructor/assignment operators are ok!
+ // compiler-generated destructor is ok!
inline explicit QDBusSignature(const char *signature);
inline explicit QDBusSignature(QLatin1String signature);
inline explicit QDBusSignature(const QString &signature);
+#ifdef Q_COMPILER_RVALUE_REFS
+ explicit QDBusSignature(QString &&sig) : m_signature(std::move(sig)) { doCheck(); }
+#endif
+
+ void swap(QDBusSignature &other) Q_DECL_NOTHROW { qSwap(m_signature, other.m_signature); }
inline void setSignature(const QString &signature);
@@ -111,6 +129,7 @@ public:
private:
void doCheck();
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusSignature)
inline QDBusSignature::QDBusSignature(const char *dBusSignature)
: m_signature(QString::fromLatin1(dBusSignature))
@@ -136,21 +155,30 @@ inline bool operator!=(const QDBusSignature &lhs, const QDBusSignature &rhs)
inline bool operator<(const QDBusSignature &lhs, const QDBusSignature &rhs)
{ return lhs.signature() < rhs.signature(); }
-inline uint qHash(const QDBusSignature &signature, uint seed)
+inline uint qHash(const QDBusSignature &signature, uint seed = 0)
{ return qHash(signature.signature(), seed); }
class QDBusVariant
{
QVariant m_variant;
public:
- inline QDBusVariant() { }
+ QDBusVariant() Q_DECL_NOTHROW : m_variant() {}
+ // compiler-generated copy/move constructor/assignment operators are ok!
+ // compiler-generated destructor is ok!
+
inline explicit QDBusVariant(const QVariant &variant);
+#ifdef Q_COMPILER_RVALUE_REFS
+ explicit QDBusVariant(QVariant &&v) Q_DECL_NOTHROW : m_variant(std::move(v)) {}
+#endif
+
+ void swap(QDBusVariant &other) Q_DECL_NOTHROW { qSwap(m_variant, other.m_variant); }
inline void setVariant(const QVariant &variant);
inline QVariant variant() const
{ return m_variant; }
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusVariant)
inline QDBusVariant::QDBusVariant(const QVariant &dBusVariant)
: m_variant(dBusVariant) { }
diff --git a/src/dbus/qdbusintegrator.cpp b/src/dbus/qdbusintegrator.cpp
index cce8b9c28d..22c1a3e363 100644
--- a/src/dbus/qdbusintegrator.cpp
+++ b/src/dbus/qdbusintegrator.cpp
@@ -160,7 +160,7 @@ static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
{
- Q_ASSERT(d->timeouts.keys(timeout).isEmpty());
+ Q_ASSERT(d->timeouts.key(timeout, 0) == 0);
int timerId = d->startTimer(ms);
if (!timerId)
@@ -952,14 +952,19 @@ void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const Q
}
// output arguments
+ const int numMetaTypes = metaTypes.count();
QVariantList outputArgs;
void *null = 0;
if (metaTypes[0] != QMetaType::Void && metaTypes[0] != QMetaType::UnknownType) {
+ outputArgs.reserve(numMetaTypes - i + 1);
QVariant arg(metaTypes[0], null);
outputArgs.append( arg );
params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
+ } else {
+ outputArgs.reserve(numMetaTypes - i);
}
- for ( ; i < metaTypes.count(); ++i) {
+
+ for ( ; i < numMetaTypes; ++i) {
QVariant arg(metaTypes[i], null);
outputArgs.append( arg );
params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
@@ -1730,7 +1735,7 @@ static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnecti
# if DBUS_VERSION-0 >= 0x010400
can_send_type = dbus_connection_can_send_type;
# endif
-#else
+#elif !defined(QT_NO_LIBRARY)
// run-time check if the next functions are available
can_send_type = (can_send_type_t)qdbus_resolve_conditionally("dbus_connection_can_send_type");
#endif
@@ -1898,7 +1903,8 @@ int QDBusConnectionPrivate::send(const QDBusMessage& message)
qPrintable(message.interface()), qPrintable(message.member()),
qPrintable(error.message()));
else if (message.type() == QDBusMessage::SignalMessage)
- qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
+ qWarning("QDBusConnection: error: could not send signal to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
+ qPrintable(message.service()),
qPrintable(message.path()), qPrintable(message.interface()),
qPrintable(message.member()),
qPrintable(error.message()));
diff --git a/src/dbus/qdbusintegrator_p.h b/src/dbus/qdbusintegrator_p.h
index 3e4f79c43c..95eeed3fff 100644
--- a/src/dbus/qdbusintegrator_p.h
+++ b/src/dbus/qdbusintegrator_p.h
@@ -50,7 +50,6 @@
#include "qcoreevent.h"
#include "qeventloop.h"
-#include "qhash.h"
#include "qobject.h"
#include "private/qobject_p.h"
#include "qlist.h"
@@ -77,10 +76,21 @@ struct QDBusSlotCache
int flags;
int slotIdx;
QVector<int> metaTypes;
+
+ void swap(Data &other) Q_DECL_NOTHROW
+ {
+ qSwap(flags, other.flags);
+ qSwap(slotIdx, other.slotIdx);
+ qSwap(metaTypes, other.metaTypes);
+ }
};
typedef QMultiHash<QString, Data> Hash;
Hash hash;
+
+ void swap(QDBusSlotCache &other) Q_DECL_NOTHROW { qSwap(hash, other.hash); }
};
+Q_DECLARE_SHARED(QDBusSlotCache::Data)
+Q_DECLARE_SHARED(QDBusSlotCache)
class QDBusCallDeliveryEvent: public QMetaCallEvent
{
diff --git a/src/dbus/qdbusinterface.cpp b/src/dbus/qdbusinterface.cpp
index 1fc313d8cc..421fc0bdb6 100644
--- a/src/dbus/qdbusinterface.cpp
+++ b/src/dbus/qdbusinterface.cpp
@@ -278,6 +278,7 @@ int QDBusInterfacePrivate::metacall(QMetaObject::Call c, int id, void **argv)
// we will assume that the input arguments were passed correctly
QVariantList args;
+ args.reserve(inputTypesCount);
int i = 1;
for ( ; i <= inputTypesCount; ++i)
args << QVariant(inputTypes[i], argv[i]);
diff --git a/src/dbus/qdbusinterface.h b/src/dbus/qdbusinterface.h
index b63df10763..b48a206644 100644
--- a/src/dbus/qdbusinterface.h
+++ b/src/dbus/qdbusinterface.h
@@ -52,7 +52,7 @@ private:
public:
QDBusInterface(const QString &service, const QString &path, const QString &interface = QString(),
const QDBusConnection &connection = QDBusConnection::sessionBus(),
- QObject *parent = 0);
+ QObject *parent = Q_NULLPTR);
~QDBusInterface();
virtual const QMetaObject *metaObject() const Q_DECL_OVERRIDE;
diff --git a/src/dbus/qdbusintrospection_p.h b/src/dbus/qdbusintrospection_p.h
index ce3be00733..f34e336eb3 100644
--- a/src/dbus/qdbusintrospection_p.h
+++ b/src/dbus/qdbusintrospection_p.h
@@ -46,7 +46,7 @@
//
#include <QtCore/qstring.h>
-#include <QtCore/qlist.h>
+#include <QtCore/qvector.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qmap.h>
#include <QtCore/qpair.h>
@@ -71,7 +71,7 @@ public:
// typedefs
typedef QMap<QString, QString> Annotations;
- typedef QList<Argument> Arguments;
+ typedef QVector<Argument> Arguments;
typedef QMultiMap<QString, Method> Methods;
typedef QMultiMap<QString, Signal> Signals;
typedef QMap<QString, Property> Properties;
diff --git a/src/dbus/qdbusmacros.h b/src/dbus/qdbusmacros.h
index 1f774b0f08..2a1d0a22d7 100644
--- a/src/dbus/qdbusmacros.h
+++ b/src/dbus/qdbusmacros.h
@@ -45,7 +45,9 @@
#ifdef Q_CC_MSVC
#include <QtCore/qlist.h>
#include <QtCore/qset.h>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
#include <QtCore/qvector.h>
#endif
diff --git a/src/dbus/qdbusmessage.cpp b/src/dbus/qdbusmessage.cpp
index b92e7f5cd7..302d94696d 100644
--- a/src/dbus/qdbusmessage.cpp
+++ b/src/dbus/qdbusmessage.cpp
@@ -153,8 +153,10 @@ DBusMessage *QDBusMessagePrivate::toDBusMessage(const QDBusMessage &message, QDB
}
break;
case QDBusMessage::SignalMessage:
- // nothing can be empty here
+ // only the service name can be empty here
if (!d_ptr->parametersValidated) {
+ if (!QDBusUtil::checkBusName(d_ptr->service, QDBusUtil::EmptyAllowed, error))
+ return 0;
if (!QDBusUtil::checkObjectPath(d_ptr->path, QDBusUtil::EmptyNotAllowed, error))
return 0;
if (!QDBusUtil::checkInterfaceName(d_ptr->interface, QDBusUtil::EmptyAllowed, error))
@@ -165,6 +167,7 @@ DBusMessage *QDBusMessagePrivate::toDBusMessage(const QDBusMessage &message, QDB
msg = q_dbus_message_new_signal(d_ptr->path.toUtf8(), d_ptr->interface.toUtf8(),
d_ptr->name.toUtf8());
+ q_dbus_message_set_destination(msg, data(d_ptr->service.toUtf8()));
break;
}
@@ -372,6 +375,31 @@ QDBusMessage QDBusMessage::createSignal(const QString &path, const QString &inte
}
/*!
+ \since 5.6
+
+ Constructs a new DBus message with the given \a path, \a interface
+ and \a name, representing a signal emission to \a destination.
+
+ A DBus signal is emitted from one application and is received only by
+ the application owning the destination service name.
+
+ The QDBusMessage object that is returned can be sent using the
+ QDBusConnection::send() function.
+*/
+QDBusMessage QDBusMessage::createTargetedSignal(const QString &service, const QString &path,
+ const QString &interface, const QString &name)
+{
+ QDBusMessage message;
+ message.d_ptr->type = SignalMessage;
+ message.d_ptr->service = service;
+ message.d_ptr->path = path;
+ message.d_ptr->interface = interface;
+ message.d_ptr->name = name;
+
+ return message;
+}
+
+/*!
Constructs a new DBus message representing a method call.
A method call always informs its destination address
(\a service, \a path, \a interface and \a method).
diff --git a/src/dbus/qdbusmessage.h b/src/dbus/qdbusmessage.h
index 77f34ec5e2..e85d600080 100644
--- a/src/dbus/qdbusmessage.h
+++ b/src/dbus/qdbusmessage.h
@@ -62,11 +62,18 @@ public:
QDBusMessage();
QDBusMessage(const QDBusMessage &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDBusMessage &operator=(QDBusMessage &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDBusMessage &operator=(const QDBusMessage &other);
~QDBusMessage();
+ void swap(QDBusMessage &other) Q_DECL_NOTHROW { qSwap(d_ptr, other.d_ptr); }
+
static QDBusMessage createSignal(const QString &path, const QString &interface,
const QString &name);
+ static QDBusMessage createTargetedSignal(const QString &service, const QString &path,
+ const QString &interface, const QString &name);
static QDBusMessage createMethodCall(const QString &destination, const QString &path,
const QString &interface, const QString &method);
static QDBusMessage createError(const QString &name, const QString &msg);
@@ -115,6 +122,7 @@ private:
friend class QDBusMessagePrivate;
QDBusMessagePrivate *d_ptr;
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QDBusMessage)
#ifndef QT_NO_DEBUG_STREAM
Q_DBUS_EXPORT QDebug operator<<(QDebug, const QDBusMessage &);
diff --git a/src/dbus/qdbuspendingcall.h b/src/dbus/qdbuspendingcall.h
index 99d261d05b..3bcacffd22 100644
--- a/src/dbus/qdbuspendingcall.h
+++ b/src/dbus/qdbuspendingcall.h
@@ -56,9 +56,12 @@ class Q_DBUS_EXPORT QDBusPendingCall
public:
QDBusPendingCall(const QDBusPendingCall &other);
~QDBusPendingCall();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDBusPendingCall &operator=(QDBusPendingCall &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDBusPendingCall &operator=(const QDBusPendingCall &other);
- void swap(QDBusPendingCall &other) { qSwap(d, other.d); }
+ void swap(QDBusPendingCall &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
#ifndef Q_QDOC
// pretend that they aren't here
@@ -93,7 +96,7 @@ class Q_DBUS_EXPORT QDBusPendingCallWatcher: public QObject, public QDBusPending
{
Q_OBJECT
public:
- explicit QDBusPendingCallWatcher(const QDBusPendingCall &call, QObject *parent = 0);
+ explicit QDBusPendingCallWatcher(const QDBusPendingCall &call, QObject *parent = Q_NULLPTR);
~QDBusPendingCallWatcher();
#ifdef Q_QDOC
diff --git a/src/dbus/qdbusreply.h b/src/dbus/qdbusreply.h
index 56830f698a..4cfe8db161 100644
--- a/src/dbus/qdbusreply.h
+++ b/src/dbus/qdbusreply.h
@@ -125,7 +125,7 @@ private:
template<> inline QDBusReply<QVariant>&
QDBusReply<QVariant>::operator=(const QDBusMessage &reply)
{
- void *null = 0;
+ void *null = Q_NULLPTR;
QVariant data(qMetaTypeId<QDBusVariant>(), null);
qDBusReplyFill(reply, m_error, data);
m_data = qvariant_cast<QDBusVariant>(data).variant();
diff --git a/src/dbus/qdbusserver.h b/src/dbus/qdbusserver.h
index cdd531802a..db21f268b0 100644
--- a/src/dbus/qdbusserver.h
+++ b/src/dbus/qdbusserver.h
@@ -50,8 +50,8 @@ class Q_DBUS_EXPORT QDBusServer: public QObject
{
Q_OBJECT
public:
- explicit QDBusServer(const QString &address, QObject *parent = 0);
- explicit QDBusServer(QObject *parent = 0);
+ explicit QDBusServer(const QString &address, QObject *parent = Q_NULLPTR);
+ explicit QDBusServer(QObject *parent = Q_NULLPTR);
virtual ~QDBusServer();
bool isConnected() const;
diff --git a/src/dbus/qdbusservicewatcher.h b/src/dbus/qdbusservicewatcher.h
index 020ce13c30..6f6ce917af 100644
--- a/src/dbus/qdbusservicewatcher.h
+++ b/src/dbus/qdbusservicewatcher.h
@@ -58,9 +58,9 @@ public:
};
Q_DECLARE_FLAGS(WatchMode, WatchModeFlag)
- explicit QDBusServiceWatcher(QObject *parent = 0);
+ explicit QDBusServiceWatcher(QObject *parent = Q_NULLPTR);
QDBusServiceWatcher(const QString &service, const QDBusConnection &connection,
- WatchMode watchMode = WatchForOwnerChange, QObject *parent = 0);
+ WatchMode watchMode = WatchForOwnerChange, QObject *parent = Q_NULLPTR);
~QDBusServiceWatcher();
QStringList watchedServices() const;
diff --git a/src/dbus/qdbusunixfiledescriptor.h b/src/dbus/qdbusunixfiledescriptor.h
index 35e9d87cf3..9fb6eb44c7 100644
--- a/src/dbus/qdbusunixfiledescriptor.h
+++ b/src/dbus/qdbusunixfiledescriptor.h
@@ -55,10 +55,13 @@ public:
QDBusUnixFileDescriptor();
explicit QDBusUnixFileDescriptor(int fileDescriptor);
QDBusUnixFileDescriptor(const QDBusUnixFileDescriptor &other);
+#if defined(Q_COMPILER_RVALUE_REFS)
+ QDBusUnixFileDescriptor &operator=(QDBusUnixFileDescriptor &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QDBusUnixFileDescriptor &operator=(const QDBusUnixFileDescriptor &other);
~QDBusUnixFileDescriptor();
- void swap(QDBusUnixFileDescriptor &other)
+ void swap(QDBusUnixFileDescriptor &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool isValid() const;
@@ -71,11 +74,6 @@ public:
static bool isSupported();
-#if defined(Q_COMPILER_RVALUE_REFS)
- inline QDBusUnixFileDescriptor &operator=(QDBusUnixFileDescriptor &&other)
- { d.swap(other.d); return *this; }
-#endif
-
protected:
typedef QExplicitlySharedDataPointer<QDBusUnixFileDescriptorPrivate> Data;
Data d;
diff --git a/src/dbus/qdbusvirtualobject.h b/src/dbus/qdbusvirtualobject.h
index 469c41f363..740c5f712e 100644
--- a/src/dbus/qdbusvirtualobject.h
+++ b/src/dbus/qdbusvirtualobject.h
@@ -51,7 +51,7 @@ class Q_DBUS_EXPORT QDBusVirtualObject : public QObject
{
Q_OBJECT
public:
- explicit QDBusVirtualObject(QObject *parent = 0);
+ explicit QDBusVirtualObject(QObject *parent = Q_NULLPTR);
virtual ~QDBusVirtualObject();
virtual QString introspect(const QString &path) const = 0;
diff --git a/src/gui/accessible/qaccessible.cpp b/src/gui/accessible/qaccessible.cpp
index e0ebcd18ce..e9995045b1 100644
--- a/src/gui/accessible/qaccessible.cpp
+++ b/src/gui/accessible/qaccessible.cpp
@@ -443,14 +443,14 @@ QT_BEGIN_NAMESPACE
*/
/*!
- \fn QAccessibleInterface::~QAccessibleInterface()
-
- Destroys the object.
+ Destroys the QAccessibleInterface.
*/
+QAccessibleInterface::~QAccessibleInterface()
+{
+}
/*!
\typedef QAccessible::Id
- \relates QAccessible
Synonym for unsigned, used by the QAccessibleInterface cache.
*/
@@ -461,12 +461,12 @@ QT_BEGIN_NAMESPACE
#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QAccessibleFactoryInterface_iid, QLatin1String("/accessible")))
+typedef QHash<QString, QAccessiblePlugin*> QAccessiblePluginsHash;
+Q_GLOBAL_STATIC(QAccessiblePluginsHash, qAccessiblePlugins)
#endif
// FIXME turn this into one global static struct
Q_GLOBAL_STATIC(QList<QAccessible::InterfaceFactory>, qAccessibleFactories)
-typedef QHash<QString, QAccessiblePlugin*> QAccessiblePluginsHash;
-Q_GLOBAL_STATIC(QAccessiblePluginsHash, qAccessiblePlugins)
Q_GLOBAL_STATIC(QList<QAccessible::ActivationObserver *>, qAccessibleActivationObservers)
QAccessible::UpdateHandler QAccessible::updateHandler = 0;
@@ -608,6 +608,11 @@ QAccessible::RootObjectHandler QAccessible::installRootObjectHandler(RootObjectH
\sa installActivationObserver()
*/
+QAccessible::ActivationObserver::~ActivationObserver()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
\internal
@@ -1254,10 +1259,6 @@ QColor QAccessibleInterface::backgroundColor() const
return QColor();
}
-QAccessibleInterface::~QAccessibleInterface()
-{
-}
-
/*!
\fn QAccessibleTextInterface *QAccessibleInterface::textInterface()
*/
@@ -1329,9 +1330,13 @@ QAccessibleInterface::~QAccessibleInterface()
the overload taking a \l QObject parameter as it might be cheaper.
*/
-/*! \fn QAccessibleEvent::~QAccessibleEvent()
+/*!
Destroys the event.
*/
+QAccessibleEvent::~QAccessibleEvent()
+{
+ // must be empty until ### Qt 6
+}
/*! \fn QAccessible::Event QAccessibleEvent::type() const
Returns the event type.
@@ -1400,6 +1405,13 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Returns the new value of the accessible object of this event.
*/
+/*!
+ \internal
+*/
+QAccessibleValueChangeEvent::~QAccessibleValueChangeEvent()
+{
+ // must be empty until ### Qt 6
+}
/*!
\class QAccessibleStateChangeEvent
@@ -1437,7 +1449,13 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
other hand tells about the change and has focused set to \c true since
the focus state is changed from \c true to \c false.
*/
-
+/*!
+ \internal
+*/
+QAccessibleStateChangeEvent::~QAccessibleStateChangeEvent()
+{
+ // must be empty until ### Qt 6
+}
/*!
\class QAccessibleTableModelChangeEvent
@@ -1512,7 +1530,14 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
change type \a changeType.
*/
/*!
- \class QAccessibleTextCursorEvent
+ \internal
+*/
+QAccessibleTableModelChangeEvent::~QAccessibleTableModelChangeEvent()
+{
+ // must be empty until ### Qt 6
+}
+/*!
+ \class QAccessibleTextCursorEvent
\ingroup accessibility
\inmodule QtGui
@@ -1533,6 +1558,14 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Sets the cursor \a position for this event.
*/
+/*!
+ \internal
+*/
+QAccessibleTextCursorEvent::~QAccessibleTextCursorEvent()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
\fn QAccessibleTextCursorEvent(QAccessibleInterface *iface, int cursorPos)
@@ -1566,6 +1599,14 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Returns the text that has been inserted.
*/
+/*!
+ \internal
+*/
+QAccessibleTextInsertEvent::~QAccessibleTextInsertEvent()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
\class QAccessibleTextRemoveEvent
@@ -1602,6 +1643,14 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Returns the text that has been removed.
*/
/*!
+ \internal
+*/
+QAccessibleTextRemoveEvent::~QAccessibleTextRemoveEvent()
+{
+ // must be empty until ### Qt 6
+}
+
+/*!
\fn QAccessibleTextSelectionEvent::QAccessibleTextSelectionEvent(QAccessibleInterface *iface, int start, int end)
Constructs a new QAccessibleTextSelectionEvent for \a iface. The new selection this
@@ -1655,6 +1704,14 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Returns the removed text.
*/
+/*!
+ \internal
+*/
+QAccessibleTextUpdateEvent::~QAccessibleTextUpdateEvent()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
\class QAccessibleTextSelectionEvent
@@ -1682,6 +1739,13 @@ QAccessible::Id QAccessibleEvent::uniqueId() const
Sets the selection for this event from position \a start to \a end.
*/
+/*!
+ \internal
+*/
+QAccessibleTextSelectionEvent::~QAccessibleTextSelectionEvent()
+{
+ // must be empty until ### Qt 6
+}
@@ -1920,10 +1984,13 @@ QDebug operator<<(QDebug d, const QAccessibleEvent &ev)
*/
/*!
- \fn QAccessibleTextInterface::~QAccessibleTextInterface()
Destroys the QAccessibleTextInterface.
*/
+QAccessibleTextInterface::~QAccessibleTextInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn void QAccessibleTextInterface::addSelection(int startOffset, int endOffset)
@@ -2306,10 +2373,13 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
- \fn QAccessibleEditableTextInterface::~QAccessibleEditableTextInterface()
Destroys the QAccessibleEditableTextInterface.
*/
+QAccessibleEditableTextInterface::~QAccessibleEditableTextInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn void QAccessibleEditableTextInterface::deleteText(int startOffset, int endOffset)
@@ -2348,10 +2418,13 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
- \fn QAccessibleValueInterface::~QAccessibleValueInterface()
+ Destroys the QAccessibleValueInterface.
- Destructor.
*/
+QAccessibleValueInterface::~QAccessibleValueInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn QVariant QAccessibleValueInterface::currentValue() const
@@ -2410,6 +2483,14 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
+ Destroys the QAccessibleImageInterface.
+*/
+QAccessibleImageInterface::~QAccessibleImageInterface()
+{
+ // must be empty until ### Qt 6
+}
+
+/*!
\class QAccessibleTableCellInterface
\inmodule QtGui
\ingroup accessibility
@@ -2421,10 +2502,13 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
- \fn virtual QAccessibleTableCellInterface::~QAccessibleTableCellInterface()
Destroys the QAccessibleTableCellInterface.
*/
+QAccessibleTableCellInterface::~QAccessibleTableCellInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn virtual int QAccessibleTableCellInterface::columnExtent() const
@@ -2486,10 +2570,13 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
- \fn virtual QAccessibleTableInterface::~QAccessibleTableInterface()
Destroys the QAccessibleTableInterface.
*/
+QAccessibleTableInterface::~QAccessibleTableInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn virtual QAccessibleInterface *QAccessibleTableInterface::cellAt(int row, int column) const
@@ -2659,10 +2746,13 @@ QString QAccessibleTextInterface::textAtOffset(int offset, QAccessible::TextBoun
*/
/*!
- \fn QAccessibleActionInterface::~QAccessibleActionInterface()
Destroys the QAccessibleActionInterface.
*/
+QAccessibleActionInterface::~QAccessibleActionInterface()
+{
+ // must be empty until ### Qt 6
+}
/*!
\fn QStringList QAccessibleActionInterface::actionNames() const
diff --git a/src/gui/accessible/qaccessible.h b/src/gui/accessible/qaccessible.h
index bfe1e6c542..63658260fc 100644
--- a/src/gui/accessible/qaccessible.h
+++ b/src/gui/accessible/qaccessible.h
@@ -396,10 +396,10 @@ public:
static UpdateHandler installUpdateHandler(UpdateHandler);
static RootObjectHandler installRootObjectHandler(RootObjectHandler);
- class ActivationObserver
+ class Q_GUI_EXPORT ActivationObserver
{
public:
- virtual ~ActivationObserver() {}
+ virtual ~ActivationObserver();
virtual void accessibilityActiveChanged(bool active) = 0;
};
static void installActivationObserver(ActivationObserver *);
@@ -505,7 +505,7 @@ public:
virtual void virtual_hook(int id, void *data);
virtual void *interface_cast(QAccessible::InterfaceType)
- { return 0; }
+ { return Q_NULLPTR; }
protected:
friend class QAccessibleCache;
@@ -514,7 +514,7 @@ protected:
class Q_GUI_EXPORT QAccessibleTextInterface
{
public:
- virtual ~QAccessibleTextInterface() {}
+ virtual ~QAccessibleTextInterface();
// selection
virtual void selection(int selectionIndex, int *startOffset, int *endOffset) const = 0;
virtual int selectionCount() const = 0;
@@ -547,7 +547,7 @@ public:
class Q_GUI_EXPORT QAccessibleEditableTextInterface
{
public:
- virtual ~QAccessibleEditableTextInterface() {}
+ virtual ~QAccessibleEditableTextInterface();
virtual void deleteText(int startOffset, int endOffset) = 0;
virtual void insertText(int offset, const QString &text) = 0;
@@ -557,8 +557,7 @@ public:
class Q_GUI_EXPORT QAccessibleValueInterface
{
public:
-
- virtual ~QAccessibleValueInterface() {}
+ virtual ~QAccessibleValueInterface();
virtual QVariant currentValue() const = 0;
virtual void setCurrentValue(const QVariant &value) = 0;
@@ -570,7 +569,7 @@ public:
class Q_GUI_EXPORT QAccessibleTableCellInterface
{
public:
- virtual ~QAccessibleTableCellInterface() {}
+ virtual ~QAccessibleTableCellInterface();
virtual bool isSelected() const = 0;
@@ -587,7 +586,7 @@ public:
class Q_GUI_EXPORT QAccessibleTableInterface
{
public:
- virtual ~QAccessibleTableInterface() {}
+ virtual ~QAccessibleTableInterface();
virtual QAccessibleInterface *caption() const = 0;
virtual QAccessibleInterface *summary() const = 0;
@@ -622,7 +621,7 @@ class Q_GUI_EXPORT QAccessibleActionInterface
{
Q_DECLARE_TR_FUNCTIONS(QAccessibleActionInterface)
public:
- virtual ~QAccessibleActionInterface() {}
+ virtual ~QAccessibleActionInterface();
virtual QStringList actionNames() const = 0;
virtual QString localizedActionName(const QString &name) const;
@@ -647,7 +646,7 @@ public:
class Q_GUI_EXPORT QAccessibleImageInterface
{
public:
- virtual ~QAccessibleImageInterface() {}
+ virtual ~QAccessibleImageInterface();
virtual QString imageDescription() const = 0;
virtual QSize imageSize() const = 0;
@@ -677,7 +676,7 @@ public:
}
inline QAccessibleEvent(QAccessibleInterface *iface, QAccessible::Event typ)
- : m_type(typ), m_object(0)
+ : m_type(typ), m_object(Q_NULLPTR)
{
Q_ASSERT(iface);
Q_ASSERT(m_type != QAccessible::ValueChanged);
@@ -691,8 +690,7 @@ public:
m_uniqueId = QAccessible::uniqueId(iface);
}
- virtual ~QAccessibleEvent()
- {}
+ virtual ~QAccessibleEvent();
QAccessible::Event type() const { return m_type; }
QObject *object() const { return m_object; }
@@ -726,6 +724,7 @@ public:
{
m_type = QAccessible::StateChanged;
}
+ ~QAccessibleStateChangeEvent();
QAccessible::State changedStates() const {
return m_changedStates;
@@ -752,6 +751,8 @@ public:
m_type = QAccessible::TextCaretMoved;
}
+ ~QAccessibleTextCursorEvent();
+
void setCursorPosition(int position) { m_cursorPosition = position; }
int cursorPosition() const { return m_cursorPosition; }
@@ -776,6 +777,8 @@ public:
m_type = QAccessible::TextSelectionChanged;
}
+ ~QAccessibleTextSelectionEvent();
+
void setSelection(int start, int end) {
m_selectionStart = start;
m_selectionEnd = end;
@@ -805,6 +808,8 @@ public:
m_type = QAccessible::TextInserted;
}
+ ~QAccessibleTextInsertEvent();
+
QString textInserted() const {
return m_text;
}
@@ -833,6 +838,8 @@ public:
m_type = QAccessible::TextRemoved;
}
+ ~QAccessibleTextRemoveEvent();
+
QString textRemoved() const {
return m_text;
}
@@ -860,6 +867,9 @@ public:
{
m_type = QAccessible::TextUpdated;
}
+
+ ~QAccessibleTextUpdateEvent();
+
QString textRemoved() const {
return m_oldText;
}
@@ -892,6 +902,8 @@ public:
m_type = QAccessible::ValueChanged;
}
+ ~QAccessibleValueChangeEvent();
+
void setValue(const QVariant & val) { m_value= val; }
QVariant value() const { return m_value; }
@@ -926,6 +938,8 @@ public:
m_type = QAccessible::TableModelChanged;
}
+ ~QAccessibleTableModelChangeEvent();
+
void setModelChangeType(ModelChangeType changeType) { m_modelChangeType = changeType; }
ModelChangeType modelChangeType() const { return m_modelChangeType; }
diff --git a/src/gui/accessible/qaccessiblebridge.h b/src/gui/accessible/qaccessiblebridge.h
index f0df5e1f39..277a8d201b 100644
--- a/src/gui/accessible/qaccessiblebridge.h
+++ b/src/gui/accessible/qaccessiblebridge.h
@@ -59,7 +59,7 @@ class Q_GUI_EXPORT QAccessibleBridgePlugin : public QObject
{
Q_OBJECT
public:
- explicit QAccessibleBridgePlugin(QObject *parent = 0);
+ explicit QAccessibleBridgePlugin(QObject *parent = Q_NULLPTR);
~QAccessibleBridgePlugin();
virtual QAccessibleBridge *create(const QString &key) = 0;
diff --git a/src/gui/accessible/qaccessibleplugin.h b/src/gui/accessible/qaccessibleplugin.h
index a4b782af11..44261788c7 100644
--- a/src/gui/accessible/qaccessibleplugin.h
+++ b/src/gui/accessible/qaccessibleplugin.h
@@ -53,7 +53,7 @@ class Q_GUI_EXPORT QAccessiblePlugin : public QObject
{
Q_OBJECT
public:
- explicit QAccessiblePlugin(QObject *parent = 0);
+ explicit QAccessiblePlugin(QObject *parent = Q_NULLPTR);
~QAccessiblePlugin();
virtual QAccessibleInterface *create(const QString &key, QObject *object) = 0;
diff --git a/src/gui/image/qbitmap.h b/src/gui/image/qbitmap.h
index f3ad90be20..be693af1cf 100644
--- a/src/gui/image/qbitmap.h
+++ b/src/gui/image/qbitmap.h
@@ -48,7 +48,7 @@ public:
QBitmap(const QPixmap &);
QBitmap(int w, int h);
explicit QBitmap(const QSize &);
- explicit QBitmap(const QString &fileName, const char *format=0);
+ explicit QBitmap(const QString &fileName, const char *format = Q_NULLPTR);
~QBitmap();
QBitmap &operator=(const QPixmap &);
diff --git a/src/gui/image/qicon.cpp b/src/gui/image/qicon.cpp
index 66bb77795e..7a59adffb8 100644
--- a/src/gui/image/qicon.cpp
+++ b/src/gui/image/qicon.cpp
@@ -46,11 +46,6 @@
#include "qdebug.h"
#include "qpalette.h"
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
#include "private/qhexstring_p.h"
#include "private/qguiapplication_p.h"
#include "qpa/qplatformtheme.h"
@@ -134,7 +129,8 @@ static qreal qt_effective_device_pixel_ratio(QWindow *window = 0)
QIconPrivate::QIconPrivate()
: engine(0), ref(1),
serialNum(serialNumCounter.fetchAndAddRelaxed(1)),
- detach_no(0)
+ detach_no(0),
+ is_mask(false)
{
}
@@ -362,7 +358,7 @@ static inline int origIcoDepth(const QImage &image)
return s.isEmpty() ? 32 : s.toInt();
}
-static inline int findBySize(const QList<QImage> &images, const QSize &size)
+static inline int findBySize(const QVector<QImage> &images, const QSize &size)
{
for (int i = 0; i < images.size(); ++i) {
if (images.at(i).size() == size)
@@ -426,7 +422,7 @@ void QPixmapIconEngine::addFile(const QString &fileName, const QSize &size, QIco
// these files may contain low-resolution images. As this information is lost,
// ICOReader sets the original format as an image text key value. Read all matching
// images into a list trying to find the highest quality per size.
- QList<QImage> icoImages;
+ QVector<QImage> icoImages;
while (imageReader.read(&image)) {
if (ignoreSize || image.size() == size) {
const int position = findBySize(icoImages, image.size());
@@ -599,6 +595,8 @@ QFactoryLoader *qt_iconEngineFactoryLoader()
\image icon.png QIcon
+ \note QIcon needs a QGuiApplication instance before the icon is created.
+
\sa {fowler}{GUI Design Handbook: Iconic Label}, {Icons Example}
*/
@@ -1185,8 +1183,6 @@ QIcon QIcon::fromTheme(const QString &name, const QIcon &fallback)
qtIconCache()->insert(name, 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;
@@ -1208,6 +1204,31 @@ bool QIcon::hasThemeIcon(const QString &name)
return icon.name() == name;
}
+/*!
+ \since 5.6
+
+ Indicate that this icon is a mask image, and hence can potentially
+ be modified based on where it's displayed.
+ \sa isMask()
+*/
+void QIcon::setIsMask(bool isMask)
+{
+ d->is_mask = isMask;
+}
+
+/*!
+ \since 5.6
+
+ Returns \c true if this icon has been marked as a mask image.
+ Certain platforms render mask icons differently (for example,
+ menu icons on OS X).
+
+ \sa setIsMask()
+*/
+bool QIcon::isMask() const
+{
+ return d->is_mask;
+}
/*****************************************************************************
QIcon stream functions
diff --git a/src/gui/image/qicon.h b/src/gui/image/qicon.h
index 63e77eef99..ccddf69101 100644
--- a/src/gui/image/qicon.h
+++ b/src/gui/image/qicon.h
@@ -56,8 +56,8 @@ public:
QIcon(const QIcon &other);
#ifdef Q_COMPILER_RVALUE_REFS
QIcon(QIcon &&other) Q_DECL_NOEXCEPT
- : d(0)
- { qSwap(d, other.d); }
+ : d(other.d)
+ { other.d = Q_NULLPTR; }
#endif
explicit QIcon(const QString &fileName); // file or resource name
explicit QIcon(QIconEngine *engine);
@@ -65,7 +65,7 @@ public:
QIcon &operator=(const QIcon &other);
#ifdef Q_COMPILER_RVALUE_REFS
inline QIcon &operator=(QIcon &&other) Q_DECL_NOEXCEPT
- { qSwap(d, other.d); return *this; }
+ { swap(other); return *this; }
#endif
inline void swap(QIcon &other) Q_DECL_NOEXCEPT
{ qSwap(d, other.d); }
@@ -102,6 +102,9 @@ public:
QList<QSize> availableSizes(Mode mode = Normal, State state = Off) const;
+ void setIsMask(bool isMask);
+ bool isMask() const;
+
static QIcon fromTheme(const QString &name, const QIcon &fallback = QIcon());
static bool hasThemeIcon(const QString &name);
diff --git a/src/gui/image/qicon_p.h b/src/gui/image/qicon_p.h
index 8b42e770fa..2a4f584a0d 100644
--- a/src/gui/image/qicon_p.h
+++ b/src/gui/image/qicon_p.h
@@ -71,6 +71,7 @@ public:
QAtomicInt ref;
int serialNum;
int detach_no;
+ bool is_mask;
};
diff --git a/src/gui/image/qiconengineplugin.h b/src/gui/image/qiconengineplugin.h
index 66684c871d..b05969f283 100644
--- a/src/gui/image/qiconengineplugin.h
+++ b/src/gui/image/qiconengineplugin.h
@@ -48,7 +48,7 @@ class Q_GUI_EXPORT QIconEnginePlugin : public QObject
{
Q_OBJECT
public:
- QIconEnginePlugin(QObject *parent = 0);
+ QIconEnginePlugin(QObject *parent = Q_NULLPTR);
~QIconEnginePlugin();
virtual QIconEngine *create(const QString &filename = QString()) = 0;
diff --git a/src/gui/image/qiconloader.cpp b/src/gui/image/qiconloader.cpp
index fa14c84e83..3ead72dfbb 100644
--- a/src/gui/image/qiconloader.cpp
+++ b/src/gui/image/qiconloader.cpp
@@ -42,15 +42,10 @@
#include <QtGui/QIconEngine>
#include <QtGui/QPalette>
#include <QtCore/QList>
-#include <QtCore/QHash>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtGui/QPainter>
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
#include <private/qhexstring_p.h>
QT_BEGIN_NAMESPACE
@@ -73,9 +68,6 @@ QIconLoader::QIconLoader() :
{
}
-// We lazily initialize the loader to make static icons
-// work. Though we do not officially support this.
-
static inline QString systemThemeName()
{
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
@@ -398,9 +390,6 @@ void QIconLoaderEngine::paint(QPainter *painter, const QRect &rect,
QIcon::Mode mode, QIcon::State state)
{
QSize pixmapSize = rect.size();
-#if defined(Q_DEAD_CODE_FROM_QT4_MAC)
- pixmapSize *= qt_mac_get_scalefactor();
-#endif
painter->drawPixmap(rect, pixmap(pixmapSize, mode, state));
}
diff --git a/src/gui/image/qiconloader_p.h b/src/gui/image/qiconloader_p.h
index 5b0362e218..ccf0a9d438 100644
--- a/src/gui/image/qiconloader_p.h
+++ b/src/gui/image/qiconloader_p.h
@@ -76,7 +76,7 @@ struct QIconDirInfo
short maxSize;
short minSize;
short threshold;
- Type type : 4;
+ Type type;
};
Q_DECLARE_TYPEINFO(QIconDirInfo, Q_MOVABLE_TYPE);
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index 176cdfe09f..045e36323f 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -476,6 +476,10 @@ bool QImageData::checkForAlphaPixels() const
\snippet code/src_gui_image_qimage.cpp 1
\endtable
+ For images with more than 8-bit per color-channel. The methods
+ setPixelColor() and pixelColor() can be used to set and get
+ with QColor values.
+
QImage also provide the scanLine() function which returns a
pointer to the pixel data at the scanline with the given index,
and the bits() function which returns a pointer to the first pixel
@@ -1770,11 +1774,11 @@ void QImage::fill(const QColor &color)
break;
case QImage::Format_BGR30:
case QImage::Format_A2BGR30_Premultiplied:
- fill(qConvertArgb32ToA2rgb30<PixelOrderBGR>(color.rgba()));
+ fill(qConvertRgb64ToRgb30<PixelOrderBGR>(color.rgba64()));
break;
case QImage::Format_RGB30:
case QImage::Format_A2RGB30_Premultiplied:
- fill(qConvertArgb32ToA2rgb30<PixelOrderRGB>(color.rgba()));
+ fill(qConvertRgb64ToRgb30<PixelOrderRGB>(color.rgba64()));
break;
case QImage::Format_RGB16:
fill((uint) qConvertRgb32To16(color.rgba()));
@@ -2191,9 +2195,10 @@ int QImage::pixelIndex(int x, int y) const
If the \a position is not valid, the results are undefined.
\warning This function is expensive when used for massive pixel
- manipulations.
+ manipulations. Use constBits() or constScanLine() when many
+ pixels needs to be read.
- \sa setPixel(), valid(), {QImage#Pixel Manipulation}{Pixel
+ \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
Manipulation}
*/
@@ -2243,25 +2248,23 @@ QRgb QImage::pixel(int x, int y) const
return *layout->convertToARGB32PM(&result, ptr, 1, layout, 0);
}
-
/*!
\fn void QImage::setPixel(const QPoint &position, uint index_or_rgb)
Sets the pixel index or color at the given \a position to \a
index_or_rgb.
- If the image's format is either monochrome or 8-bit, the given \a
+ If the image's format is either monochrome or paletted, the given \a
index_or_rgb value must be an index in the image's color table,
otherwise the parameter must be a QRgb value.
If \a position is not a valid coordinate pair in the image, or if
\a index_or_rgb >= colorCount() in the case of monochrome and
- 8-bit images, the result is undefined.
+ paletted images, the result is undefined.
\warning This function is expensive due to the call of the internal
\c{detach()} function called within; if performance is a concern, we
- recommend the use of \l{QImage::}{scanLine()} to access pixel data
- directly.
+ recommend the use of scanLine() or bits() to access pixel data directly.
\sa pixel(), {QImage#Pixel Manipulation}{Pixel Manipulation}
*/
@@ -2349,6 +2352,102 @@ void QImage::setPixel(int x, int y, uint index_or_rgb)
}
/*!
+ \fn QColor QImage::pixelColor(const QPoint &position) const
+ \since 5.6
+
+ Returns the color of the pixel at the given \a position as a QColor.
+
+ If the \a position is not valid, an invalid QColor is returned.
+
+ \warning This function is expensive when used for massive pixel
+ manipulations. Use constBits() or constScanLine() when many
+ pixels needs to be read.
+
+ \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
+ Manipulation}
+*/
+
+/*!
+ \overload
+ \since 5.6
+
+ Returns the color of the pixel at coordinates (\a x, \a y) as a QColor.
+*/
+QColor QImage::pixelColor(int x, int y) const
+{
+ if (!d || x < 0 || x >= d->width || y < 0 || y >= height()) {
+ qWarning("QImage::pixelColor: coordinate (%d,%d) out of range", x, y);
+ return QColor();
+ }
+
+ const uchar * s = constScanLine(y);
+ switch (d->format) {
+ case Format_BGR30:
+ case Format_A2BGR30_Premultiplied:
+ return QColor(qConvertA2rgb30ToRgb64<PixelOrderBGR>(reinterpret_cast<const quint32 *>(s)[x]));
+ case Format_RGB30:
+ case Format_A2RGB30_Premultiplied:
+ return QColor(qConvertA2rgb30ToRgb64<PixelOrderRGB>(reinterpret_cast<const quint32 *>(s)[x]));
+ default:
+ return QColor(pixel(x, y));
+ }
+}
+
+/*!
+ \fn void QImage::setPixelColor(const QPoint &position, const QColor &color)
+ \since 5.6
+
+ Sets the color at the given \a position to \a color.
+
+ If \a position is not a valid coordinate pair in the image, or
+ the image's format is either monochrome or paletted, the result is undefined.
+
+ \warning This function is expensive due to the call of the internal
+ \c{detach()} function called within; if performance is a concern, we
+ recommend the use of scanLine() or bits() to access pixel data directly.
+
+ \sa pixel(), bits(), scanLine(), {QImage#Pixel Manipulation}{Pixel Manipulation}
+*/
+
+/*!
+ \overload
+ \since 5.6
+
+ Sets the pixel color at (\a x, \a y) to \a color.
+*/
+void QImage::setPixelColor(int x, int y, const QColor &color)
+{
+ if (!d || x < 0 || x >= width() || y < 0 || y >= height() || !color.isValid()) {
+ qWarning("QImage::setPixelColor: coordinate (%d,%d) out of range", x, y);
+ return;
+ }
+ // detach is called from within scanLine
+ uchar * s = scanLine(y);
+ switch (d->format) {
+ case Format_Mono:
+ case Format_MonoLSB:
+ case Format_Indexed8:
+ qWarning("QImage::setPixelColor: called on monochrome or indexed format");
+ return;
+ case Format_BGR30:
+ ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(color.rgba64()) | 0xc0000000;
+ return;
+ case Format_A2BGR30_Premultiplied:
+ ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(color.rgba64());
+ return;
+ case Format_RGB30:
+ ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(color.rgba64()) | 0xc0000000;
+ return;
+ case Format_A2RGB30_Premultiplied:
+ ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(color.rgba64());
+ return;
+ default:
+ setPixel(x, y, color.rgba());
+ return;
+ }
+}
+
+/*!
Returns \c true if all the colors in the image are shades of gray
(i.e. their red, green and blue components are equal); otherwise
false.
@@ -3793,6 +3892,10 @@ int QImage::metric(PaintDeviceMetric metric) const
return d->devicePixelRatio;
break;
+ case PdmDevicePixelRatioScaled:
+ return d->devicePixelRatio * QPaintDevice::devicePixelRatioFScale();
+ break;
+
default:
qWarning("QImage::metric(): Unhandled metric type %d", metric);
break;
diff --git a/src/gui/image/qimage.h b/src/gui/image/qimage.h
index 26057f366c..888c7beb32 100644
--- a/src/gui/image/qimage.h
+++ b/src/gui/image/qimage.h
@@ -34,10 +34,11 @@
#ifndef QIMAGE_H
#define QIMAGE_H
-#include <QtGui/qtransform.h>
-#include <QtGui/qpaintdevice.h>
+#include <QtGui/qcolor.h>
#include <QtGui/qrgb.h>
+#include <QtGui/qpaintdevice.h>
#include <QtGui/qpixelformat.h>
+#include <QtGui/qtransform.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qrect.h>
#include <QtCore/qstring.h>
@@ -124,15 +125,15 @@ public:
QImage() Q_DECL_NOEXCEPT;
QImage(const QSize &size, Format format);
QImage(int width, int height, Format format);
- QImage(uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = 0, void *cleanupInfo = 0);
- QImage(const uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = 0, void *cleanupInfo = 0);
- QImage(uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = 0, void *cleanupInfo = 0);
- QImage(const uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = 0, void *cleanupInfo = 0);
+ QImage(uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = Q_NULLPTR, void *cleanupInfo = Q_NULLPTR);
+ QImage(const uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = Q_NULLPTR, void *cleanupInfo = Q_NULLPTR);
+ QImage(uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = Q_NULLPTR, void *cleanupInfo = Q_NULLPTR);
+ QImage(const uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = Q_NULLPTR, void *cleanupInfo = Q_NULLPTR);
#ifndef QT_NO_IMAGEFORMAT_XPM
explicit QImage(const char * const xpm[]);
#endif
- explicit QImage(const QString &fileName, const char *format = 0);
+ explicit QImage(const QString &fileName, const char *format = Q_NULLPTR);
QImage(const QImage &);
#ifdef Q_COMPILER_RVALUE_REFS
@@ -220,6 +221,12 @@ public:
void setPixel(int x, int y, uint index_or_rgb);
void setPixel(const QPoint &pt, uint index_or_rgb);
+ QColor pixelColor(int x, int y) const;
+ QColor pixelColor(const QPoint &pt) const;
+
+ void setPixelColor(int x, int y, const QColor &c);
+ void setPixelColor(const QPoint &pt, const QColor &c);
+
QVector<QRgb> colorTable() const;
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void setColorTable(const QVector<QRgb> &colors);
@@ -272,16 +279,16 @@ public:
bool load(QIODevice *device, const char* format);
- bool load(const QString &fileName, const char* format=0);
- bool loadFromData(const uchar *buf, int len, const char *format = 0);
- inline bool loadFromData(const QByteArray &data, const char* aformat=0)
+ bool load(const QString &fileName, const char *format = Q_NULLPTR);
+ bool loadFromData(const uchar *buf, int len, const char *format = Q_NULLPTR);
+ inline bool loadFromData(const QByteArray &data, const char *aformat = Q_NULLPTR)
{ return loadFromData(reinterpret_cast<const uchar *>(data.constData()), data.size(), aformat); }
- bool save(const QString &fileName, const char* format=0, int quality=-1) const;
- bool save(QIODevice *device, const char* format=0, int quality=-1) const;
+ bool save(const QString &fileName, const char *format = Q_NULLPTR, int quality = -1) const;
+ bool save(QIODevice *device, const char *format = Q_NULLPTR, int quality = -1) const;
- static QImage fromData(const uchar *data, int size, const char *format = 0);
- inline static QImage fromData(const QByteArray &data, const char *format = 0)
+ static QImage fromData(const uchar *data, int size, const char *format = Q_NULLPTR);
+ inline static QImage fromData(const QByteArray &data, const char *format = Q_NULLPTR)
{ return fromData(reinterpret_cast<const uchar *>(data.constData()), data.size(), format); }
#if QT_DEPRECATED_SINCE(5, 0)
@@ -352,6 +359,8 @@ inline bool QImage::valid(const QPoint &pt) const { return valid(pt.x(), pt.y())
inline int QImage::pixelIndex(const QPoint &pt) const { return pixelIndex(pt.x(), pt.y());}
inline QRgb QImage::pixel(const QPoint &pt) const { return pixel(pt.x(), pt.y()); }
inline void QImage::setPixel(const QPoint &pt, uint index_or_rgb) { setPixel(pt.x(), pt.y(), index_or_rgb); }
+inline QColor QImage::pixelColor(const QPoint &pt) const { return pixelColor(pt.x(), pt.y()); }
+inline void QImage::setPixelColor(const QPoint &pt, const QColor &c) { setPixelColor(pt.x(), pt.y(), c); }
#if QT_DEPRECATED_SINCE(5, 0)
diff --git a/src/gui/image/qimageiohandler.h b/src/gui/image/qimageiohandler.h
index 80cd87c4c3..47a8a2b7c6 100644
--- a/src/gui/image/qimageiohandler.h
+++ b/src/gui/image/qimageiohandler.h
@@ -133,7 +133,7 @@ class Q_GUI_EXPORT QImageIOPlugin : public QObject
{
Q_OBJECT
public:
- explicit QImageIOPlugin(QObject *parent = 0);
+ explicit QImageIOPlugin(QObject *parent = Q_NULLPTR);
virtual ~QImageIOPlugin();
enum Capability {
diff --git a/src/gui/image/qimagereader.cpp b/src/gui/image/qimagereader.cpp
index ba79bf40e5..618352d363 100644
--- a/src/gui/image/qimagereader.cpp
+++ b/src/gui/image/qimagereader.cpp
@@ -252,7 +252,7 @@ static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
#ifdef QIMAGEREADER_DEBUG
qDebug() << "QImageReader::createReadHandler( device =" << (void *)device << ", format =" << format << "),"
- << keyMap.values().size() << "plugins available: " << keyMap.values();
+ << keyMap.size() << "plugins available: " << keyMap.values();
#endif
int suffixPluginIndex = -1;
@@ -312,7 +312,7 @@ static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
const qint64 pos = device ? device->pos() : 0;
if (autoDetectImageFormat) {
- const int keyCount = keyMap.keys().size();
+ const int keyCount = keyMap.size();
for (int i = 0; i < keyCount; ++i) {
if (i != suffixPluginIndex) {
QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(i));
@@ -392,7 +392,7 @@ static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
if (!handler && (autoDetectImageFormat || ignoresFormatAndExtension)) {
// check if any of our plugins recognize the file from its contents.
const qint64 pos = device ? device->pos() : 0;
- const int keyCount = keyMap.keys().size();
+ const int keyCount = keyMap.size();
for (int i = 0; i < keyCount; ++i) {
if (i != suffixPluginIndex) {
QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(i));
@@ -1168,9 +1168,10 @@ QImageIOHandler::Transformations QImageReader::transformation() const
/*!
\since 5.5
- Sets if images returned by read() should have transformation metadata automatically applied.
+ Determines that images returned by read() should have transformation metadata automatically
+ applied if \a enabled is \c true.
- \sa autoTransform(), transform(), read()
+ \sa autoTransform(), read()
*/
void QImageReader::setAutoTransform(bool enabled)
{
@@ -1203,6 +1204,39 @@ bool QImageReader::autoTransform() const
}
/*!
+ \since 5.6
+
+ This is an image format specific function that forces images with
+ gamma information to be gamma corrected to \a gamma. For image formats
+ that do not support gamma correction, this value is ignored.
+
+ To gamma correct to a standard PC color-space, set gamma to \c 1/2.2.
+
+ \sa gamma()
+*/
+void QImageReader::setGamma(float gamma)
+{
+ if (d->initHandler() && d->handler->supportsOption(QImageIOHandler::Gamma))
+ d->handler->setOption(QImageIOHandler::Gamma, gamma);
+}
+
+/*!
+ \since 5.6
+
+ Returns the gamma level of the decoded image. If setGamma() has been
+ called and gamma correction is supported it will return the gamma set.
+ If gamma level is not supported by the image format, \c 0.0 is returned.
+
+ \sa setGamma()
+*/
+float QImageReader::gamma() const
+{
+ if (d->initHandler() && d->handler->supportsOption(QImageIOHandler::Gamma))
+ return d->handler->option(QImageIOHandler::Gamma).toFloat();
+ return 0.0;
+}
+
+/*!
Returns \c true if an image can be read for the device (i.e., the
image format is supported, and the device seems to contain valid
data); otherwise returns \c false.
diff --git a/src/gui/image/qimagereader.h b/src/gui/image/qimagereader.h
index 27a29bed49..6745c55b97 100644
--- a/src/gui/image/qimagereader.h
+++ b/src/gui/image/qimagereader.h
@@ -110,6 +110,9 @@ public:
void setAutoTransform(bool enabled);
bool autoTransform() const;
+ void setGamma(float gamma);
+ float gamma() const;
+
QByteArray subType() const;
QList<QByteArray> supportedSubTypes() const;
diff --git a/src/gui/image/qimagewriter.cpp b/src/gui/image/qimagewriter.cpp
index e9de1db4b2..1cf75d8688 100644
--- a/src/gui/image/qimagewriter.cpp
+++ b/src/gui/image/qimagewriter.cpp
@@ -212,7 +212,7 @@ static QImageIOHandler *createWriteHandlerHelper(QIODevice *device,
#ifndef QT_NO_IMAGEFORMATPLUGIN
if (!testFormat.isEmpty()) {
- const int keyCount = keyMap.keys().size();
+ const int keyCount = keyMap.size();
for (int i = 0; i < keyCount; ++i) {
QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(i));
if (plugin && (plugin->capabilities(device, testFormat) & QImageIOPlugin::CanWrite)) {
@@ -621,7 +621,7 @@ bool QImageWriter::progressiveScanWrite() const
/*!
\since 5.5
- Sets the image transformations metadata including orientation.
+ Sets the image transformations metadata including orientation to \a transform.
If transformation metadata is not supported by the image format,
the transform is applied before writing.
diff --git a/src/gui/image/qmovie.h b/src/gui/image/qmovie.h
index 13bc381f8e..a750e4a9fc 100644
--- a/src/gui/image/qmovie.h
+++ b/src/gui/image/qmovie.h
@@ -73,9 +73,9 @@ public:
};
Q_ENUM(CacheMode)
- explicit QMovie(QObject *parent = 0);
- explicit QMovie(QIODevice *device, const QByteArray &format = QByteArray(), QObject *parent = 0);
- explicit QMovie(const QString &fileName, const QByteArray &format = QByteArray(), QObject *parent = 0);
+ explicit QMovie(QObject *parent = Q_NULLPTR);
+ explicit QMovie(QIODevice *device, const QByteArray &format = QByteArray(), QObject *parent = Q_NULLPTR);
+ explicit QMovie(const QString &fileName, const QByteArray &format = QByteArray(), QObject *parent = Q_NULLPTR);
~QMovie();
static QList<QByteArray> supportedFormats();
diff --git a/src/gui/image/qpaintengine_pic.cpp b/src/gui/image/qpaintengine_pic.cpp
index 9ab1e2c30b..47480ebbae 100644
--- a/src/gui/image/qpaintengine_pic.cpp
+++ b/src/gui/image/qpaintengine_pic.cpp
@@ -398,6 +398,7 @@ void QPicturePaintEngine::drawPolygon(const QPointF *points, int numPoints, Poly
int pos;
QPolygonF polygon;
+ polygon.reserve(numPoints);
for (int i=0; i<numPoints; ++i)
polygon << points[i];
diff --git a/src/gui/image/qpicture.cpp b/src/gui/image/qpicture.cpp
index b63be19153..2b184466f4 100644
--- a/src/gui/image/qpicture.cpp
+++ b/src/gui/image/qpicture.cpp
@@ -961,6 +961,9 @@ int QPicture::metric(PaintDeviceMetric m) const
case PdmDevicePixelRatio:
val = 1;
break;
+ case PdmDevicePixelRatioScaled:
+ val = 1 * QPaintDevice::devicePixelRatioFScale();
+ break;
default:
val = 0;
qWarning("QPicture::metric: Invalid metric command");
@@ -1216,7 +1219,9 @@ QList<QByteArray> QPicture::inputFormats()
static QStringList qToStringList(const QList<QByteArray> &arr)
{
QStringList list;
- for (int i = 0; i < arr.count(); ++i)
+ const int count = arr.count();
+ list.reserve(count);
+ for (int i = 0; i < count; ++i)
list.append(QString::fromLatin1(arr.at(i)));
return list;
}
diff --git a/src/gui/image/qpicture.h b/src/gui/image/qpicture.h
index c3897a1935..a71d1deb02 100644
--- a/src/gui/image/qpicture.h
+++ b/src/gui/image/qpicture.h
@@ -62,10 +62,10 @@ public:
bool play(QPainter *p);
- bool load(QIODevice *dev, const char *format = 0);
- bool load(const QString &fileName, const char *format = 0);
- bool save(QIODevice *dev, const char *format = 0);
- bool save(const QString &fileName, const char *format = 0);
+ bool load(QIODevice *dev, const char *format = Q_NULLPTR);
+ bool load(const QString &fileName, const char *format = Q_NULLPTR);
+ bool save(QIODevice *dev, const char *format = Q_NULLPTR);
+ bool save(const QString &fileName, const char *format = Q_NULLPTR);
QRect boundingRect() const;
void setBoundingRect(const QRect &r);
diff --git a/src/gui/image/qpicture_p.h b/src/gui/image/qpicture_p.h
index 56e6e1249c..a414a122f1 100644
--- a/src/gui/image/qpicture_p.h
+++ b/src/gui/image/qpicture_p.h
@@ -48,6 +48,7 @@
#include "QtCore/qatomic.h"
#include "QtCore/qbuffer.h"
#include "QtCore/qobjectdefs.h"
+#include "QtCore/qvector.h"
#include "QtGui/qpicture.h"
#include "QtGui/qpixmap.h"
#include "QtGui/qpen.h"
@@ -150,8 +151,8 @@ public:
QRect override_rect;
QScopedPointer<QPaintEngine> paintEngine;
bool in_memory_only;
- QList<QImage> image_list;
- QList<QPixmap> pixmap_list;
+ QVector<QImage> image_list;
+ QVector<QPixmap> pixmap_list;
QList<QBrush> brush_list;
QList<QPen> pen_list;
};
diff --git a/src/gui/image/qpictureformatplugin.h b/src/gui/image/qpictureformatplugin.h
index 773c0180d3..9ad938fa79 100644
--- a/src/gui/image/qpictureformatplugin.h
+++ b/src/gui/image/qpictureformatplugin.h
@@ -53,7 +53,7 @@ class Q_GUI_EXPORT QPictureFormatPlugin : public QObject
{
Q_OBJECT
public:
- explicit QPictureFormatPlugin(QObject *parent = 0);
+ explicit QPictureFormatPlugin(QObject *parent = Q_NULLPTR);
~QPictureFormatPlugin();
virtual bool loadPicture(const QString &format, const QString &filename, QPicture *pic);
diff --git a/src/gui/image/qpixmap.h b/src/gui/image/qpixmap.h
index 51b02acfcf..48db7a3840 100644
--- a/src/gui/image/qpixmap.h
+++ b/src/gui/image/qpixmap.h
@@ -58,7 +58,7 @@ public:
explicit QPixmap(QPlatformPixmap *data);
QPixmap(int w, int h);
explicit QPixmap(const QSize &);
- QPixmap(const QString& fileName, const char *format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor);
+ QPixmap(const QString& fileName, const char *format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor);
#ifndef QT_NO_IMAGEFORMAT_XPM
explicit QPixmap(const char * const xpm[]);
#endif
@@ -131,19 +131,19 @@ public:
}
#endif
- bool load(const QString& fileName, const char *format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor);
- bool loadFromData(const uchar *buf, uint len, const char* format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor);
- inline bool loadFromData(const QByteArray &data, const char* format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor);
- bool save(const QString& fileName, const char* format = 0, int quality = -1) const;
- bool save(QIODevice* device, const char* format = 0, int quality = -1) const;
+ bool load(const QString& fileName, const char *format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor);
+ bool loadFromData(const uchar *buf, uint len, const char* format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor);
+ inline bool loadFromData(const QByteArray &data, const char* format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor);
+ bool save(const QString& fileName, const char* format = Q_NULLPTR, int quality = -1) const;
+ bool save(QIODevice* device, const char* format = Q_NULLPTR, int quality = -1) const;
bool convertFromImage(const QImage &img, Qt::ImageConversionFlags flags = Qt::AutoColor);
inline QPixmap copy(int x, int y, int width, int height) const;
QPixmap copy(const QRect &rect = QRect()) const;
- inline void scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed = 0);
- void scroll(int dx, int dy, const QRect &rect, QRegion *exposed = 0);
+ inline void scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed = Q_NULLPTR);
+ void scroll(int dx, int dy, const QRect &rect, QRegion *exposed = Q_NULLPTR);
#if QT_DEPRECATED_SINCE(5, 0)
QT_DEPRECATED inline int serialNumber() const { return cacheKey() >> 32; }
diff --git a/src/gui/image/qpixmap_blitter.cpp b/src/gui/image/qpixmap_blitter.cpp
index f24cbc3db9..b254c5a2af 100644
--- a/src/gui/image/qpixmap_blitter.cpp
+++ b/src/gui/image/qpixmap_blitter.cpp
@@ -115,6 +115,8 @@ int QBlittablePlatformPixmap::metric(QPaintDevice::PaintDeviceMetric metric) con
return qt_defaultDpiY();
case QPaintDevice::PdmDevicePixelRatio:
return devicePixelRatio();
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ return devicePixelRatio() * QPaintDevice::devicePixelRatioFScale();
default:
qWarning("QRasterPlatformPixmap::metric(): Unhandled metric type %d", metric);
break;
diff --git a/src/gui/image/qpixmap_raster.cpp b/src/gui/image/qpixmap_raster.cpp
index 9c8835a7a0..a2b84b358e 100644
--- a/src/gui/image/qpixmap_raster.cpp
+++ b/src/gui/image/qpixmap_raster.cpp
@@ -288,6 +288,9 @@ int QRasterPlatformPixmap::metric(QPaintDevice::PaintDeviceMetric metric) const
return qt_defaultDpiY();
case QPaintDevice::PdmDevicePixelRatio:
return image.devicePixelRatio();
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ return image.devicePixelRatio() * QPaintDevice::devicePixelRatioFScale();
+
default:
qWarning("QRasterPlatformPixmap::metric(): Unhandled metric type %d", metric);
break;
diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp
index 3836976975..71a79745e8 100644
--- a/src/gui/image/qpixmapcache.cpp
+++ b/src/gui/image/qpixmapcache.cpp
@@ -138,6 +138,24 @@ bool QPixmapCache::Key::operator ==(const Key &key) const
*/
/*!
+ \fn QPixmapCache::Key::Key(Key &&)
+ \internal
+ \since 5.6
+*/
+
+/*!
+ \fn QPixmapCache::Key &QPixmapCache::Key::operator=(Key &&)
+ \internal
+ \since 5.6
+*/
+
+/*!
+ \fn void QPixmapCache::Key::swap(Key &)
+ \internal
+ \since 5.6
+*/
+
+/*!
\internal
*/
QPixmapCache::Key &QPixmapCache::Key::operator =(const Key &other)
@@ -179,7 +197,6 @@ public:
static QPixmapCache::KeyData* getKeyData(QPixmapCache::Key *key);
- QList< QPair<QString,QPixmap> > allPixmaps() const;
bool flushDetachedPixmaps(bool nt);
private:
@@ -423,20 +440,6 @@ QPixmapCache::KeyData* QPMCache::getKeyData(QPixmapCache::Key *key)
return key->d;
}
-QList< QPair<QString,QPixmap> > QPMCache::allPixmaps() const
-{
- QList< QPair<QString,QPixmap> > r;
- QHash<QString, QPixmapCache::Key>::const_iterator it = cacheKeys.begin();
- while (it != cacheKeys.end()) {
- QPixmap *ptr = QCache<QPixmapCache::Key, QPixmapCacheEntry>::object(it.value());
- if (ptr)
- r.append(QPair<QString,QPixmap>(it.key(),*ptr));
- ++it;
- }
- return r;
-}
-
-
Q_GLOBAL_STATIC(QPMCache, pm_cache)
int Q_AUTOTEST_EXPORT q_QPixmapCache_keyHashSize()
@@ -656,10 +659,6 @@ int QPixmapCache::totalUsed()
return (pm_cache()->totalCost()+1023) / 1024;
}
-QList< QPair<QString,QPixmap> > QPixmapCache::allPixmaps()
-{
- return pm_cache()->allPixmaps();
-}
/*!
\fn QPixmapCache::KeyData::KeyData()
@@ -667,7 +666,6 @@ QList< QPair<QString,QPixmap> > QPixmapCache::allPixmaps()
*/
/*!
\fn QPixmapCache::KeyData::KeyData(const KeyData &other)
-
\internal
*/
/*!
diff --git a/src/gui/image/qpixmapcache.h b/src/gui/image/qpixmapcache.h
index 345389e987..37a0588e06 100644
--- a/src/gui/image/qpixmapcache.h
+++ b/src/gui/image/qpixmapcache.h
@@ -36,10 +36,6 @@
#include <QtGui/qpixmap.h>
-#ifdef Q_TEST_QPIXMAPCACHE
-#include <QtCore/qpair.h>
-#endif
-
QT_BEGIN_NAMESPACE
@@ -52,12 +48,18 @@ public:
public:
Key();
Key(const Key &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ Key(Key &&other) Q_DECL_NOTHROW : d(other.d) { other.d = Q_NULLPTR; }
+ Key &operator =(Key &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
~Key();
bool operator ==(const Key &key) const;
inline bool operator !=(const Key &key) const
{ return !operator==(key); }
Key &operator =(const Key &other);
+ void swap(Key &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
+
private:
KeyData *d;
friend class QPMCache;
@@ -80,9 +82,9 @@ public:
#ifdef Q_TEST_QPIXMAPCACHE
static void flushDetachedPixmaps();
static int totalUsed();
- static QList< QPair<QString,QPixmap> > allPixmaps();
#endif
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QPixmapCache::Key)
QT_END_NAMESPACE
diff --git a/src/gui/image/qpnghandler.cpp b/src/gui/image/qpnghandler.cpp
index 7fbd24787e..776a61d8fe 100644
--- a/src/gui/image/qpnghandler.cpp
+++ b/src/gui/image/qpnghandler.cpp
@@ -108,10 +108,11 @@ public:
};
QPngHandlerPrivate(QPngHandler *qq)
- : gamma(0.0), quality(2), png_ptr(0), info_ptr(0), end_info(0), state(Ready), q(qq)
+ : gamma(0.0), fileGamma(0.0), quality(2), png_ptr(0), info_ptr(0), end_info(0), state(Ready), q(qq)
{ }
float gamma;
+ float fileGamma;
int quality;
QString description;
QSize scaledSize;
@@ -234,13 +235,10 @@ void CALLBACK_CALL_TYPE qpiw_flush_fn(png_structp /* png_ptr */)
}
static
-void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead, float screen_gamma=0.0)
+void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead, float screen_gamma=0.0, float file_gamma=0.0)
{
- if (screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
- double file_gamma;
- png_get_gAMA(png_ptr, info_ptr, &file_gamma);
- png_set_gamma(png_ptr, screen_gamma, file_gamma);
- }
+ if (screen_gamma != 0.0 && file_gamma != 0.0)
+ png_set_gamma(png_ptr, 1.0f / screen_gamma, file_gamma);
png_uint_32 width;
png_uint_32 height;
@@ -557,6 +555,12 @@ bool Q_INTERNAL_WIN_NO_THROW QPngHandlerPrivate::readPngHeader()
readPngTexts(info_ptr);
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
+ double file_gamma = 0.0;
+ png_get_gAMA(png_ptr, info_ptr, &file_gamma);
+ fileGamma = file_gamma;
+ }
+
state = ReadHeader;
return true;
}
@@ -580,7 +584,7 @@ bool Q_INTERNAL_WIN_NO_THROW QPngHandlerPrivate::readPngImage(QImage *outImage)
}
bool doScaledRead = false;
- setup_qt(*outImage, png_ptr, info_ptr, scaledSize, &doScaledRead, gamma);
+ setup_qt(*outImage, png_ptr, info_ptr, scaledSize, &doScaledRead, gamma, fileGamma);
if (outImage->isNull()) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
@@ -1063,7 +1067,7 @@ QVariant QPngHandler::option(ImageOption option) const
return QVariant();
if (option == Gamma)
- return d->gamma;
+ return d->gamma == 0.0 ? d->fileGamma : d->gamma;
else if (option == Quality)
return d->quality;
else if (option == Description)
diff --git a/src/gui/itemmodels/qstandarditemmodel.cpp b/src/gui/itemmodels/qstandarditemmodel.cpp
index 8d848b662f..25b82b94b5 100644
--- a/src/gui/itemmodels/qstandarditemmodel.cpp
+++ b/src/gui/itemmodels/qstandarditemmodel.cpp
@@ -1224,7 +1224,7 @@ void QStandardItem::setSelectable(bool selectable)
The item delegate will render a checkable item with a check box next to the
item's text.
- \sa isCheckable(), setCheckState(), setTristate()
+ \sa isCheckable(), setCheckState(), setUserTristate(), setAutoTristate()
*/
void QStandardItem::setCheckable(bool checkable)
{
@@ -1244,34 +1244,88 @@ void QStandardItem::setCheckable(bool checkable)
The default value is false.
- \sa setCheckable(), checkState(), isTristate()
+ \sa setCheckable(), checkState(), isUserTristate(), isAutoTristate()
*/
/*!
- 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().)
+ \fn void QStandardItem::setTristate(bool tristate)
+ \obsolete
- \sa isTristate(), setCheckable(), setCheckState()
+ Use QStandardItem::setAutoTristate(bool tristate) instead.
+ For a tristate checkbox that the user can change between all three
+ states, use QStandardItem::setUserTristate(bool tristate) instead.
*/
-void QStandardItem::setTristate(bool tristate)
+
+/*!
+ \fn void QStandardItem::isTristate() const
+ \obsolete
+
+ Use QStandardItem::isAutoTristate() instead.
+ For a tristate checkbox that the user can change between all three
+ states, use QStandardItem::isUserTristate() instead.
+*/
+
+/*!
+ Determines that the item is tristate and controlled by QTreeWidget if \a tristate
+ is \c true.
+ This enables automatic management of the state of parent items in QTreeWidget
+ (checked if all children are checked, unchecked if all children are unchecked,
+ or partially checked if only some children are checked).
+
+ \since 5.6
+ \sa isAutoTristate(), setCheckable(), setCheckState()
+*/
+void QStandardItem::setAutoTristate(bool tristate)
{
Q_D(QStandardItem);
- d->changeFlags(tristate, Qt::ItemIsTristate);
+ d->changeFlags(tristate, Qt::ItemIsAutoTristate);
}
/*!
- \fn bool QStandardItem::isTristate() const
+ \fn bool QStandardItem::isAutoTristate() const
+
+ Returns whether the item is tristate and is controlled by QTreeWidget.
+
+ The default value is false.
+
+ \since 5.6
+ \sa setAutoTristate(), isCheckable(), checkState()
+*/
+
+/*!
+ Sets whether the item is tristate and controlled by the user.
+ If \a tristate is true, the user can cycle through three separate states;
+ otherwise, the item is checkable with two states.
+ (Note that this also requires that the item is checkable; see isCheckable().)
+
+ \since 5.6
+ \sa isUserTristate(), setCheckable(), setCheckState()
+*/
+void QStandardItem::setUserTristate(bool tristate)
+{
+ Q_D(QStandardItem);
+ d->changeFlags(tristate, Qt::ItemIsUserTristate);
+}
+
+/*!
+ \fn bool QStandardItem::isUserTristate() const
+ \since 5.6
Returns whether the item is tristate; that is, if it's checkable with three
- separate states.
+ separate states and the user can cycle through all three states.
The default value is false.
- \sa setTristate(), isCheckable(), checkState()
+ \sa setUserTristate(), isCheckable(), checkState()
*/
+#if QT_DEPRECATED_SINCE(5, 6)
+void QStandardItem::setTristate(bool tristate)
+{
+ setAutoTristate(tristate);
+}
+#endif
+
#ifndef QT_NO_DRAGANDDROP
/*!
@@ -1750,6 +1804,7 @@ QList<QStandardItem*> QStandardItem::takeRow(int row)
int index = d->childIndex(row, 0); // Will return -1 if there are no columns
if (index != -1) {
int col_count = d->columnCount();
+ items.reserve(col_count);
for (int column = 0; column < col_count; ++column) {
QStandardItem *ch = d->children.at(index + column);
if (ch)
@@ -2467,7 +2522,9 @@ QList<QStandardItem*> QStandardItemModel::findItems(const QString &text,
QModelIndexList indexes = match(index(0, column, QModelIndex()),
Qt::DisplayRole, text, -1, flags);
QList<QStandardItem*> items;
- for (int i = 0; i < indexes.size(); ++i)
+ const int numIndexes = indexes.size();
+ items.reserve(numIndexes);
+ for (int i = 0; i < numIndexes; ++i)
items.append(itemFromIndex(indexes.at(i)));
return items;
}
diff --git a/src/gui/itemmodels/qstandarditemmodel.h b/src/gui/itemmodels/qstandarditemmodel.h
index 3dd613f907..8740f7940b 100644
--- a/src/gui/itemmodels/qstandarditemmodel.h
+++ b/src/gui/itemmodels/qstandarditemmodel.h
@@ -158,10 +158,20 @@ public:
}
void setCheckable(bool checkable);
- inline bool isTristate() const {
- return (flags() & Qt::ItemIsTristate) != 0;
+ inline bool isAutoTristate() const {
+ return (flags() & Qt::ItemIsAutoTristate) != 0;
}
- void setTristate(bool tristate);
+ void setAutoTristate(bool tristate);
+
+ inline bool isUserTristate() const {
+ return (flags() & Qt::ItemIsUserTristate) != 0;
+ }
+ void setUserTristate(bool tristate);
+
+#if QT_DEPRECATED_SINCE(5, 6)
+ QT_DEPRECATED bool isTristate() const { return isAutoTristate(); }
+ QT_DEPRECATED void setTristate(bool tristate);
+#endif
#ifndef QT_NO_DRAGANDDROP
inline bool isDragEnabled() const {
@@ -310,8 +320,8 @@ class Q_GUI_EXPORT QStandardItemModel : public QAbstractItemModel
Q_PROPERTY(int sortRole READ sortRole WRITE setSortRole)
public:
- explicit QStandardItemModel(QObject *parent = 0);
- QStandardItemModel(int rows, int columns, QObject *parent = 0);
+ explicit QStandardItemModel(QObject *parent = Q_NULLPTR);
+ QStandardItemModel(int rows, int columns, QObject *parent = Q_NULLPTR);
~QStandardItemModel();
void setItemRoleNames(const QHash<int,QByteArray> &roleNames);
@@ -405,7 +415,7 @@ Q_SIGNALS:
void itemChanged(QStandardItem *item);
protected:
- QStandardItemModel(QStandardItemModelPrivate &dd, QObject *parent = 0);
+ QStandardItemModel(QStandardItemModelPrivate &dd, QObject *parent = Q_NULLPTR);
private:
friend class QStandardItemPrivate;
diff --git a/src/gui/itemmodels/qstandarditemmodel_p.h b/src/gui/itemmodels/qstandarditemmodel_p.h
index 491a49f9c2..b49045d283 100644
--- a/src/gui/itemmodels/qstandarditemmodel_p.h
+++ b/src/gui/itemmodels/qstandarditemmodel_p.h
@@ -61,7 +61,7 @@ class QStandardItemData
{
public:
inline QStandardItemData() : role(-1) {}
- inline QStandardItemData(int r, QVariant v) : role(r), value(v) {}
+ inline QStandardItemData(int r, const QVariant &v) : role(r), value(v) {}
int role;
QVariant value;
inline bool operator==(const QStandardItemData &other) const { return role == other.role && value == other.value; }
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
index af6a417608..73a5a7b6ab 100644
--- a/src/gui/kernel/kernel.pri
+++ b/src/gui/kernel/kernel.pri
@@ -75,7 +75,9 @@ HEADERS += \
kernel/qplatformgraphicsbuffer.h \
kernel/qplatformgraphicsbufferhelper.h \
kernel/qinputdevicemanager_p.h \
- kernel/qinputdevicemanager_p_p.h
+ kernel/qinputdevicemanager_p_p.h \
+ kernel/qhighdpiscaling_p.h
+
SOURCES += \
kernel/qgenericpluginfactory.cpp \
@@ -131,7 +133,9 @@ SOURCES += \
kernel/qrasterwindow.cpp \
kernel/qplatformgraphicsbuffer.cpp \
kernel/qplatformgraphicsbufferhelper.cpp \
- kernel/qinputdevicemanager.cpp
+ kernel/qinputdevicemanager.cpp \
+ kernel/qhighdpiscaling.cpp
+
contains(QT_CONFIG, opengl)|contains(QT_CONFIG, opengles2) {
HEADERS += \
diff --git a/src/gui/kernel/qcursor.cpp b/src/gui/kernel/qcursor.cpp
index 6ed750eda1..dbf2b3c21f 100644
--- a/src/gui/kernel/qcursor.cpp
+++ b/src/gui/kernel/qcursor.cpp
@@ -43,6 +43,7 @@
#include <qpa/qplatformcursor.h>
#include <private/qguiapplication_p.h>
+#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
@@ -177,9 +178,14 @@ QT_BEGIN_NAMESPACE
*/
QPoint QCursor::pos(const QScreen *screen)
{
- if (screen)
- if (const QPlatformCursor *cursor = screen->handle()->cursor())
- return cursor->pos();
+ if (screen) {
+ if (const QPlatformCursor *cursor = screen->handle()->cursor()) {
+ const QPlatformScreen *ps = screen->handle();
+ QPoint nativePos = cursor->pos();
+ ps = ps->screenForPosition(nativePos);
+ return QHighDpi::fromNativePixels(nativePos, ps->screen());
+ }
+ }
return QGuiApplicationPrivate::lastCursorPosition.toPoint();
}
@@ -231,12 +237,12 @@ void QCursor::setPos(QScreen *screen, int x, int y)
{
if (screen) {
if (QPlatformCursor *cursor = screen->handle()->cursor()) {
- const QPoint pos = QPoint(x, y);
+ const QPoint devicePos = QHighDpi::toNativePixels(QPoint(x, y), screen);
// 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 (pos != cursor->pos())
- cursor->setPos(pos);
+ if (devicePos != cursor->pos())
+ cursor->setPos(devicePos);
}
}
}
diff --git a/src/gui/kernel/qdnd.cpp b/src/gui/kernel/qdnd.cpp
index 3ce8ab95ec..b05da1bfd0 100644
--- a/src/gui/kernel/qdnd.cpp
+++ b/src/gui/kernel/qdnd.cpp
@@ -147,7 +147,9 @@ static QStringList imageReadMimeFormats()
{
QStringList formats;
QList<QByteArray> imageFormats = QImageReader::supportedImageFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
+ const int numImageFormats = imageFormats.size();
+ formats.reserve(numImageFormats);
+ for (int i = 0; i < numImageFormats; ++i) {
QString format = QLatin1String("image/");
format += QString::fromLatin1(imageFormats.at(i).toLower());
formats.append(format);
@@ -166,7 +168,9 @@ static QStringList imageWriteMimeFormats()
{
QStringList formats;
QList<QByteArray> imageFormats = QImageWriter::supportedImageFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
+ const int numImageFormats = imageFormats.size();
+ formats.reserve(numImageFormats);
+ for (int i = 0; i < numImageFormats; ++i) {
QString format = QLatin1String("image/");
format += QString::fromLatin1(imageFormats.at(i).toLower());
formats.append(format);
diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp
index c231c47576..780a102644 100644
--- a/src/gui/kernel/qevent.cpp
+++ b/src/gui/kernel/qevent.cpp
@@ -171,6 +171,8 @@ QInputEvent::~QInputEvent()
\fn ulong QInputEvent::timestamp() const
Returns the window system's timestamp for this event.
+ It will normally be in milliseconds since some arbitrary point
+ in time, such as the time when the system was started.
*/
/*! \fn void QInputEvent::setTimestamp(ulong atimestamp)
@@ -309,6 +311,36 @@ QMouseEvent::QMouseEvent(Type type, const QPointF &localPos, const QPointF &wind
{}
/*!
+ \since 5.6
+
+ Constructs a mouse event object.
+
+ The \a type parameter must be QEvent::MouseButtonPress,
+ QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick,
+ or QEvent::MouseMove.
+
+ The points \a localPos, \a windowPos and \a screenPos specify the
+ mouse cursor's position relative to the receiving widget or item,
+ window, and screen, respectively.
+
+ The \a button that caused the event is given as a value from the
+ \l Qt::MouseButton enum. If the event \a type is \l MouseMove,
+ the appropriate button for this event is Qt::NoButton. \a buttons
+ is the state of all buttons at the time of the event, \a modifiers
+ is the state of all keyboard modifiers.
+
+ The source of the event is specified by \a source.
+
+*/
+QMouseEvent::QMouseEvent(QEvent::Type type, const QPointF &localPos, const QPointF &windowPos, const QPointF &screenPos,
+ Qt::MouseButton button, Qt::MouseButtons buttons,
+ Qt::KeyboardModifiers modifiers, Qt::MouseEventSource source)
+ : QInputEvent(type, modifiers), l(localPos), w(windowPos), s(screenPos), b(button), mouseState(buttons), caps(0)
+{
+ QGuiApplicationPrivate::setMouseEventSource(this, source);
+}
+
+/*!
\internal
*/
QMouseEvent::~QMouseEvent()
@@ -1987,6 +2019,11 @@ QInputMethodEvent::QInputMethodEvent(const QInputMethodEvent &other)
{
}
+QInputMethodEvent::~QInputMethodEvent()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
Sets the commit string to \a commitString.
diff --git a/src/gui/kernel/qevent.h b/src/gui/kernel/qevent.h
index a1f32026ac..b90fce97e0 100644
--- a/src/gui/kernel/qevent.h
+++ b/src/gui/kernel/qevent.h
@@ -106,6 +106,9 @@ public:
QMouseEvent(Type type, const QPointF &localPos, const QPointF &windowPos, const QPointF &screenPos,
Qt::MouseButton button, Qt::MouseButtons buttons,
Qt::KeyboardModifiers modifiers);
+ QMouseEvent(Type type, const QPointF &localPos, const QPointF &windowPos, const QPointF &screenPos,
+ Qt::MouseButton button, Qt::MouseButtons buttons,
+ Qt::KeyboardModifiers modifiers, Qt::MouseEventSource source);
~QMouseEvent();
#ifndef QT_NO_INTEGER_EVENT_COORDINATES
@@ -519,7 +522,7 @@ public:
};
class Attribute {
public:
- Attribute(AttributeType t, int s, int l, QVariant val) : type(t), start(s), length(l), value(val) {}
+ Attribute(AttributeType t, int s, int l, QVariant val) : type(t), start(s), length(l), value(qMove(val)) {}
AttributeType type;
int start;
@@ -528,6 +531,8 @@ public:
};
QInputMethodEvent();
QInputMethodEvent(const QString &preeditText, const QList<Attribute> &attributes);
+ ~QInputMethodEvent();
+
void setCommitString(const QString &commitString, int replaceFrom = 0, int replaceLength = 0);
inline const QList<Attribute> &attributes() const { return attrs; }
inline const QString &preeditString() const { return preedit; }
@@ -694,7 +699,7 @@ class Q_GUI_EXPORT QActionEvent : public QEvent
{
QAction *act, *bef;
public:
- QActionEvent(int type, QAction *action, QAction *before = 0);
+ QActionEvent(int type, QAction *action, QAction *before = Q_NULLPTR);
~QActionEvent();
inline QAction *action() const { return act; }
@@ -871,9 +876,9 @@ public:
#endif
explicit QTouchEvent(QEvent::Type eventType,
- QTouchDevice *device = 0,
+ QTouchDevice *device = Q_NULLPTR,
Qt::KeyboardModifiers modifiers = Qt::NoModifier,
- Qt::TouchPointStates touchPointStates = 0,
+ Qt::TouchPointStates touchPointStates = Qt::TouchPointStates(),
const QList<QTouchEvent::TouchPoint> &touchPoints = QList<QTouchEvent::TouchPoint>());
~QTouchEvent();
diff --git a/src/gui/kernel/qgenericplugin.h b/src/gui/kernel/qgenericplugin.h
index cfab34d081..03c1df7fba 100644
--- a/src/gui/kernel/qgenericplugin.h
+++ b/src/gui/kernel/qgenericplugin.h
@@ -48,7 +48,7 @@ class Q_GUI_EXPORT QGenericPlugin : public QObject
{
Q_OBJECT
public:
- explicit QGenericPlugin(QObject *parent = 0);
+ explicit QGenericPlugin(QObject *parent = Q_NULLPTR);
~QGenericPlugin();
virtual QObject* create(const QString& name, const QString &spec) = 0;
diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp
index 7dc8444163..d0aab734dd 100644
--- a/src/gui/kernel/qguiapplication.cpp
+++ b/src/gui/kernel/qguiapplication.cpp
@@ -958,8 +958,10 @@ QWindow *QGuiApplication::topLevelAt(const QPoint &pos)
QList<QScreen *>::const_iterator end = screens.constEnd();
while (screen != end) {
- if ((*screen)->geometry().contains(pos))
- return (*screen)->handle()->topLevelAt(pos);
+ if ((*screen)->geometry().contains(pos)) {
+ const QPoint devicePosition = QHighDpi::toNativePixels(pos, *screen);
+ return (*screen)->handle()->topLevelAt(devicePosition);
+ }
++screen;
}
return 0;
@@ -1115,6 +1117,9 @@ void QGuiApplicationPrivate::createPlatformIntegration()
// this flag.
QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar, true);
+
+ QHighDpiScaling::initHighDpiScaling();
+
// Load the platform integration
QString platformPluginPath = QLatin1String(qgetenv("QT_QPA_PLATFORM_PLUGIN_PATH"));
@@ -1204,6 +1209,10 @@ void QGuiApplicationPrivate::eventDispatcherReady()
createPlatformIntegration();
platform_integration->initialize();
+
+ // Do this here in order to play nice with platforms that add screens only
+ // in initialize().
+ QHighDpiScaling::updateHighDpiScaling();
}
void QGuiApplicationPrivate::init()
@@ -1328,6 +1337,9 @@ void QGuiApplicationPrivate::init()
#endif
#ifndef QT_NO_LIBRARY
+ if (qEnvironmentVariableIntValue("QT_LOAD_TESTABILITY") > 0)
+ loadTestability = true;
+
if (loadTestability) {
QLibrary testLib(QStringLiteral("qttestability"));
if (testLib.load()) {
@@ -1342,6 +1354,8 @@ void QGuiApplicationPrivate::init()
qCritical() << "Library qttestability load failed:" << testLib.errorString();
}
}
+#else
+ Q_UNUSED(loadTestability);
#endif // QT_NO_LIBRARY
}
@@ -1691,12 +1705,14 @@ void QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::Mo
// A mouse event should not change both position and buttons at the same time. Instead we
// should first send a move event followed by a button changed event. Since this is not the case
// with the current event, we split it in two.
- QWindowSystemInterfacePrivate::MouseEvent *mouseButtonEvent = new QWindowSystemInterfacePrivate::MouseEvent(
+ QWindowSystemInterfacePrivate::MouseEvent mouseButtonEvent(
e->window.data(), e->timestamp, e->type, e->localPos, e->globalPos, e->buttons, e->modifiers);
if (e->flags & QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic)
- mouseButtonEvent->flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
- QWindowSystemInterfacePrivate::windowSystemEventQueue.prepend(mouseButtonEvent);
- stateChange = Qt::NoButton;
+ mouseButtonEvent.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
+ e->buttons = buttons;
+ processMouseEvent(e);
+ processMouseEvent(&mouseButtonEvent);
+ return;
}
QWindow *window = e->window.data();
@@ -1765,9 +1781,8 @@ void QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::Mo
if (!window)
return;
- QMouseEvent ev(type, localPoint, localPoint, globalPoint, button, buttons, e->modifiers);
+ QMouseEvent ev(type, localPoint, localPoint, globalPoint, button, buttons, e->modifiers, e->source);
ev.setTimestamp(e->timestamp);
- setMouseEventSource(&ev, e->source);
#ifndef QT_NO_CURSOR
if (!e->synthetic()) {
if (const QScreen *screen = window->screen())
@@ -1815,7 +1830,7 @@ void QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::Mo
points << point;
QEvent::Type type;
- QList<QTouchEvent::TouchPoint> touchPoints = QWindowSystemInterfacePrivate::convertTouchPoints(points, &type);
+ QList<QTouchEvent::TouchPoint> touchPoints = QWindowSystemInterfacePrivate::fromNativeTouchPoints(points, window, &type);
QWindowSystemInterfacePrivate::TouchEvent fake(window, e->timestamp, type, m_fakeTouchDevice, touchPoints, e->modifiers);
fake.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
@@ -1826,9 +1841,8 @@ void QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::Mo
if (!e->window.isNull() || e->nullWindow()) { // QTBUG-36364, check if window closed in response to press
const QEvent::Type doubleClickType = frameStrut ? QEvent::NonClientAreaMouseButtonDblClick : QEvent::MouseButtonDblClick;
QMouseEvent dblClickEvent(doubleClickType, localPoint, localPoint, globalPoint,
- button, buttons, e->modifiers);
+ button, buttons, e->modifiers, e->source);
dblClickEvent.setTimestamp(e->timestamp);
- setMouseEventSource(&dblClickEvent, e->source);
QGuiApplication::sendSpontaneousEvent(window, &dblClickEvent);
}
}
@@ -1920,6 +1934,7 @@ void QGuiApplicationPrivate::processKeyEvent(QWindowSystemInterfacePrivate::KeyE
}
}
#endif
+ e->eventAccepted = ev.isAccepted();
}
void QGuiApplicationPrivate::processEnterEvent(QWindowSystemInterfacePrivate::EnterEvent *e)
@@ -2032,6 +2047,11 @@ void QGuiApplicationPrivate::processWindowScreenChangedEvent(QWindowSystemInterf
window->d_func()->setTopLevelScreen(screen, false /* recreate */);
else // Fall back to default behavior, and try to find some appropriate screen
window->setScreen(0);
+ // we may have changed scaling, so trigger resize event if needed
+ if (window->handle()) {
+ QWindowSystemInterfacePrivate::GeometryChangeEvent gce(window, QHighDpi::fromNativePixels(window->handle()->geometry(), window), QRect());
+ processGeometryChangeEvent(&gce);
+ }
}
}
diff --git a/src/gui/kernel/qhighdpiscaling.cpp b/src/gui/kernel/qhighdpiscaling.cpp
new file mode 100644
index 0000000000..de586ac46c
--- /dev/null
+++ b/src/gui/kernel/qhighdpiscaling.cpp
@@ -0,0 +1,322 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qhighdpiscaling_p.h"
+#include "qguiapplication.h"
+#include "qscreen.h"
+#include "qplatformintegration.h"
+#include "private/qscreen_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+Q_LOGGING_CATEGORY(lcScaling, "qt.scaling");
+
+#ifndef QT_NO_HIGHDPISCALING
+static const char legacyDevicePixelEnvVar[] = "QT_DEVICE_PIXEL_RATIO";
+static const char scaleFactorEnvVar[] = "QT_SCALE_FACTOR";
+static const char autoScreenEnvVar[] = "QT_AUTO_SCREEN_SCALE_FACTOR";
+static const char screenFactorsEnvVar[] = "QT_SCREEN_SCALE_FACTORS";
+
+static inline qreal initialScaleFactor()
+{
+
+ qreal result = 1;
+ if (qEnvironmentVariableIsSet(scaleFactorEnvVar)) {
+ bool ok;
+ const qreal f = qgetenv(scaleFactorEnvVar).toDouble(&ok);
+ if (ok && f > 0) {
+ qCDebug(lcScaling) << "Apply " << scaleFactorEnvVar << f;
+ result = f;
+ }
+ } else {
+ if (qEnvironmentVariableIsSet(legacyDevicePixelEnvVar)) {
+ qWarning() << "Warning:" << legacyDevicePixelEnvVar << "is deprecated. Instead use:";
+ qWarning() << " " << autoScreenEnvVar << "to enable platform plugin controlled per-screen factors.";
+ qWarning() << " " << screenFactorsEnvVar << "to set per-screen factors.";
+ qWarning() << " " << scaleFactorEnvVar << "to set the application global scale factor.";
+
+ int dpr = qEnvironmentVariableIntValue(legacyDevicePixelEnvVar);
+ if (dpr > 0)
+ result = dpr;
+ }
+ }
+ return result;
+}
+
+/*!
+ \class QHighDpiScaling
+ \since 5.6
+ \internal
+ \preliminary
+ \ingroup qpa
+
+ \brief Collection of utility functions for UI scaling.
+
+ QHighDpiScaling implements utility functions for high-dpi scaling for use
+ on operating systems that provide limited support for native scaling. In
+ addition this functionality can be used for simulation and testing purposes.
+
+ The functions support scaling between the device independent coordinate
+ system used by Qt applications and the native coordinate system used by
+ the platform plugins. Intended usage locations are the low level / platform
+ plugin interfacing parts of QtGui, for example the QWindow, QScreen and
+ QWindowSystemInterface implementation.
+
+ The coordinate system scaling is enabled by setting one or more scale
+ factors. These will then be factored into the value returned by the
+ devicePixelRatio() accessors (any native scale factor will also be
+ included in this value). Several setters are available:
+
+ - A process-global scale factor
+ - QT_SCALE_FACTOR (environment variable)
+ - QHighDpiScaling::setGlobalFactor()
+
+ - A per-screen scale factor
+ - QT_AUTO_SCALE_FACTOR (environment variable)
+ Setting this to a true-ish value will make QHighDpiScaling
+ call QPlatformScreen::pixelDensity()
+ - QHighDpiScaling::setScreenFactor(screen, factor);
+ - QT_SCREEN_SCALE_FACTORS (environment variable)
+ Set this to a semicolon-separated list of scale factors
+ (matching the order of QGuiApplications::screens()),
+ or to a list of name=value pairs (where name matches
+ QScreen::name()).
+
+ All scale factors are of type qreal.
+
+ The main scaling functions for use in QtGui are:
+ T toNativePixels(T, QWindow *)
+ T fromNativePixels(T, QWindow*)
+ Where T is QPoint, QSize, QRect etc.
+*/
+
+qreal QHighDpiScaling::m_factor = 1.0;
+bool QHighDpiScaling::m_active = false; //"overall active" - is there any scale factor set.
+bool QHighDpiScaling::m_usePixelDensity = false; // use scale factor from platform plugin
+bool QHighDpiScaling::m_pixelDensityScalingActive = false; // pixel density scale factor > 1
+bool QHighDpiScaling::m_globalScalingActive = false; // global scale factor is active
+bool QHighDpiScaling::m_screenFactorSet = false; // QHighDpiScaling::setScreenFactor has been used
+QDpi QHighDpiScaling::m_logicalDpi = QDpi(-1,-1); // The scaled logical DPI of the primary screen
+
+/*
+ Initializes the QHighDpiScaling global variables. Called before the
+ platform plugin is created.
+*/
+void QHighDpiScaling::initHighDpiScaling()
+{
+ if (QCoreApplication::testAttribute(Qt::AA_NoHighDpiScaling)) {
+ m_factor = 1;
+ m_active = false;
+ return;
+ }
+ m_factor = initialScaleFactor();
+ bool usePlatformPluginPixelDensity = qEnvironmentVariableIsSet(autoScreenEnvVar)
+ || qgetenv(legacyDevicePixelEnvVar).toLower() == "auto";
+
+ m_globalScalingActive = !qFuzzyCompare(m_factor, qreal(1));
+ m_usePixelDensity = usePlatformPluginPixelDensity;
+ m_pixelDensityScalingActive = false; //set in updateHighDpiScaling below
+
+ // we update m_active in updateHighDpiScaling, but while we create the
+ // screens, we have to assume that m_usePixelDensity implies scaling
+ m_active = m_globalScalingActive || m_usePixelDensity;
+}
+
+void QHighDpiScaling::updateHighDpiScaling()
+{
+ if (QCoreApplication::testAttribute(Qt::AA_NoHighDpiScaling))
+ return;
+
+ if (m_usePixelDensity && !m_pixelDensityScalingActive) {
+ Q_FOREACH (QScreen *screen, QGuiApplication::screens()) {
+ if (!qFuzzyCompare(screenSubfactor(screen->handle()), qreal(1))) {
+ m_pixelDensityScalingActive = true;
+ break;
+ }
+ }
+ }
+ if (qEnvironmentVariableIsSet(screenFactorsEnvVar)) {
+ int i = 0;
+ Q_FOREACH (const QByteArray &spec, qgetenv(screenFactorsEnvVar).split(';')) {
+ QScreen *screen = 0;
+ int equalsPos = spec.lastIndexOf('=');
+ double factor = 0;
+ if (equalsPos > 0) {
+ // support "name=factor"
+ QByteArray name = spec.mid(0, equalsPos);
+ QByteArray f = spec.mid(equalsPos + 1);
+ bool ok;
+ factor = f.toDouble(&ok);
+ if (ok) {
+ Q_FOREACH (QScreen *s, QGuiApplication::screens()) {
+ if (s->name() == QString::fromLocal8Bit(name)) {
+ screen = s;
+ break;
+ }
+ }
+ }
+ } else {
+ // listing screens in order
+ bool ok;
+ factor = spec.toDouble(&ok);
+ if (ok && i < QGuiApplication::screens().count())
+ screen = QGuiApplication::screens().at(i);
+ }
+ if (screen)
+ setScreenFactor(screen, factor);
+ ++i;
+ }
+ }
+ m_active = m_globalScalingActive || m_screenFactorSet || m_pixelDensityScalingActive;
+
+ QPlatformScreen *primaryScreen = QGuiApplication::primaryScreen()->handle();
+ qreal sf = screenSubfactor(primaryScreen);
+ QDpi primaryDpi = primaryScreen->logicalDpi();
+ m_logicalDpi = QDpi(primaryDpi.first / sf, primaryDpi.second / sf);
+}
+
+/*
+ Sets the global scale factor which is applied to all windows.
+*/
+void QHighDpiScaling::setGlobalFactor(qreal factor)
+{
+ if (qFuzzyCompare(factor, m_factor))
+ return;
+ if (!QGuiApplication::allWindows().isEmpty())
+ qWarning() << Q_FUNC_INFO << "QHighDpiScaling::setFactor: Should only be called when no windows exist.";
+
+ m_globalScalingActive = !qFuzzyCompare(factor, qreal(1));
+ m_factor = m_globalScalingActive ? factor : qreal(1);
+ m_active = m_globalScalingActive || m_screenFactorSet || m_pixelDensityScalingActive;
+ Q_FOREACH (QScreen *screen, QGuiApplication::screens())
+ screen->d_func()->updateHighDpi();
+}
+
+static const char scaleFactorProperty[] = "_q_scaleFactor";
+
+/*
+ Sets a per-screen scale factor.
+*/
+void QHighDpiScaling::setScreenFactor(QScreen *screen, qreal factor)
+{
+ m_screenFactorSet = true;
+ m_active = true;
+ screen->setProperty(scaleFactorProperty, QVariant(factor));
+
+ // hack to force re-evaluation of screen geometry
+ if (screen->handle())
+ screen->d_func()->setPlatformScreen(screen->handle()); // updates geometries based on scale factor
+}
+
+QPoint QHighDpiScaling::mapPositionToNative(const QPoint &pos, const QPlatformScreen *platformScreen)
+{
+ if (!platformScreen)
+ return pos;
+ const qreal scaleFactor = factor(platformScreen);
+ const QPoint topLeft = platformScreen->geometry().topLeft();
+ return (pos - topLeft) * scaleFactor + topLeft;
+}
+
+QPoint QHighDpiScaling::mapPositionFromNative(const QPoint &pos, const QPlatformScreen *platformScreen)
+{
+ if (!platformScreen)
+ return pos;
+ const qreal scaleFactor = factor(platformScreen);
+ const QPoint topLeft = platformScreen->geometry().topLeft();
+ return (pos - topLeft) / scaleFactor + topLeft;
+}
+
+qreal QHighDpiScaling::screenSubfactor(const QPlatformScreen *screen)
+{
+ qreal factor = qreal(1.0);
+ if (screen) {
+ if (m_usePixelDensity)
+ factor *= screen->pixelDensity();
+ if (m_screenFactorSet) {
+ QVariant screenFactor = screen->screen()->property(scaleFactorProperty);
+ if (screenFactor.isValid())
+ factor *= screenFactor.toReal();
+ }
+ }
+ return factor;
+}
+
+QDpi QHighDpiScaling::logicalDpi()
+{
+ return m_logicalDpi;
+}
+
+qreal QHighDpiScaling::factor(const QScreen *screen)
+{
+ // Fast path for when scaling in Qt is not used at all.
+ if (!m_active)
+ return qreal(1.0);
+
+ // The effective factor for a given screen is the product of the
+ // screen and global sub-factors
+ qreal factor = m_factor;
+ if (screen)
+ factor *= screenSubfactor(screen->handle());
+ return factor;
+}
+
+qreal QHighDpiScaling::factor(const QPlatformScreen *platformScreen)
+{
+ if (!m_active)
+ return qreal(1.0);
+
+ return m_factor * screenSubfactor(platformScreen);
+}
+
+qreal QHighDpiScaling::factor(const QWindow *window)
+{
+ if (!m_active)
+ return qreal(1.0);
+
+ return factor(window ? window->screen() : QGuiApplication::primaryScreen());
+}
+
+QPoint QHighDpiScaling::origin(const QScreen *screen)
+{
+ return screen->geometry().topLeft();
+}
+
+QPoint QHighDpiScaling::origin(const QPlatformScreen *platformScreen)
+{
+ return platformScreen->geometry().topLeft();
+}
+
+#endif //QT_NO_HIGHDPISCALING
+QT_END_NAMESPACE
diff --git a/src/gui/kernel/qhighdpiscaling_p.h b/src/gui/kernel/qhighdpiscaling_p.h
new file mode 100644
index 0000000000..9e33787f53
--- /dev/null
+++ b/src/gui/kernel/qhighdpiscaling_p.h
@@ -0,0 +1,514 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QHIGHDPISCALING_P_H
+#define QHIGHDPISCALING_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/qmargins.h>
+#include <QtCore/qrect.h>
+#include <QtCore/qvector.h>
+#include <QtCore/qloggingcategory.h>
+#include <QtGui/qregion.h>
+#include <QtGui/qscreen.h>
+#include <QtGui/qwindow.h>
+
+QT_BEGIN_NAMESPACE
+
+Q_DECLARE_LOGGING_CATEGORY(lcScaling);
+
+class QScreen;
+class QPlatformScreen;
+typedef QPair<qreal, qreal> QDpi;
+
+#ifndef QT_NO_HIGHDPISCALING
+class Q_GUI_EXPORT QHighDpiScaling {
+public:
+ static void initHighDpiScaling();
+ static void updateHighDpiScaling();
+ static void setGlobalFactor(qreal factor);
+ static void setScreenFactor(QScreen *window, qreal factor);
+
+ static bool isActive() { return m_active; }
+ static qreal factor(const QWindow *window);
+ static qreal factor(const QScreen *screen);
+ static qreal factor(const QPlatformScreen *platformScreen);
+ static QPoint origin(const QScreen *screen);
+ static QPoint origin(const QPlatformScreen *platformScreen);
+ static QPoint mapPositionFromNative(const QPoint &pos, const QPlatformScreen *platformScreen);
+ static QPoint mapPositionToNative(const QPoint &pos, const QPlatformScreen *platformScreen);
+ static QDpi logicalDpi();
+
+private:
+ static qreal screenSubfactor(const QPlatformScreen *screen);
+
+ static qreal m_factor;
+ static bool m_active;
+ static bool m_usePixelDensity;
+ static bool m_globalScalingActive;
+ static bool m_pixelDensityScalingActive;
+ static bool m_screenFactorSet;
+ static QDpi m_logicalDpi;
+};
+
+// Coordinate system conversion functions:
+// QHighDpi::fromNativePixels : from physical(screen/backing) to logical pixels
+// QHighDpi::toNativePixels : from logical to physical pixels
+
+namespace QHighDpi {
+
+inline QPointF fromNative(const QPointF &pos, qreal scaleFactor, const QPointF &origin)
+{
+ return (pos - origin) / scaleFactor + origin;
+}
+
+inline QPointF toNative(const QPointF &pos, qreal scaleFactor, const QPointF &origin)
+{
+ return (pos - origin) * scaleFactor + origin;
+}
+
+inline QPoint fromNative(const QPoint &pos, qreal scaleFactor, const QPoint &origin)
+{
+ return (pos - origin) / scaleFactor + origin;
+}
+
+inline QPoint toNative(const QPoint &pos, qreal scaleFactor, const QPoint &origin)
+{
+ return (pos - origin) * scaleFactor + origin;
+}
+
+inline QPoint fromNative(const QPoint &pos, qreal scaleFactor)
+{
+ return pos / scaleFactor;
+}
+
+inline QPoint toNative(const QPoint &pos, qreal scaleFactor)
+{
+ return pos * scaleFactor;
+}
+
+inline QSize fromNative(const QSize &size, qreal scaleFactor)
+{
+ return size / scaleFactor; // TODO: should we round up?
+}
+
+inline QSize toNative(const QSize &size, qreal scaleFactor)
+{
+ return size * scaleFactor;
+}
+
+inline QSizeF fromNative(const QSizeF &size, qreal scaleFactor)
+{
+ return size / scaleFactor;
+}
+
+inline QSizeF toNative(const QSizeF &size, qreal scaleFactor)
+{
+ return size * scaleFactor;
+}
+
+inline QRect fromNative(const QRect &rect, qreal scaleFactor, const QPoint &origin)
+{
+ return QRect(fromNative(rect.topLeft(), scaleFactor, origin), fromNative(rect.size(), scaleFactor));
+}
+
+inline QRect toNative(const QRect &rect, qreal scaleFactor, const QPoint &origin)
+{
+ return QRect(toNative(rect.topLeft(), scaleFactor, origin), toNative(rect.size(), scaleFactor));
+
+}
+
+inline QRect fromNative(const QRect &rect, const QScreen *screen, const QPoint &screenOrigin)
+{
+ return toNative(rect, QHighDpiScaling::factor(screen), screenOrigin);
+}
+
+inline QRect fromNativeScreenGeometry(const QRect &nativeScreenGeometry, const QScreen *screen)
+{
+ return QRect(nativeScreenGeometry.topLeft(),
+ fromNative(nativeScreenGeometry.size(), QHighDpiScaling::factor(screen)));
+}
+
+inline QPoint fromNativeLocalPosition(const QPoint &pos, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return pos / scaleFactor;
+}
+
+inline QPoint toNativeLocalPosition(const QPoint &pos, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return pos * scaleFactor;
+}
+
+inline QPointF fromNativeLocalPosition(const QPointF &pos, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return pos / scaleFactor;
+}
+
+inline QPointF toNativeLocalPosition(const QPointF &pos, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return pos * scaleFactor;
+}
+
+inline QRect fromNativePixels(const QRect &pixelRect, const QPlatformScreen *platformScreen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(platformScreen);
+ const QPoint origin = QHighDpiScaling::origin(platformScreen);
+ return QRect(fromNative(pixelRect.topLeft(), scaleFactor, origin),
+ fromNative(pixelRect.size(), scaleFactor));
+}
+
+inline QRect toNativePixels(const QRect &pointRect, const QPlatformScreen *platformScreen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(platformScreen);
+ const QPoint origin = QHighDpiScaling::origin(platformScreen);
+ return QRect(toNative(pointRect.topLeft(), scaleFactor, origin),
+ toNative(pointRect.size(), scaleFactor));
+}
+
+inline QRect fromNativePixels(const QRect &pixelRect, const QScreen *screen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(screen);
+ const QPoint origin = QHighDpiScaling::origin(screen);
+ return QRect(fromNative(pixelRect.topLeft(), scaleFactor, origin),
+ fromNative(pixelRect.size(), scaleFactor));
+}
+
+inline QRect toNativePixels(const QRect &pointRect, const QScreen *screen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(screen);
+ const QPoint origin = QHighDpiScaling::origin(screen);
+ return QRect(toNative(pointRect.topLeft(), scaleFactor, origin),
+ toNative(pointRect.size(), scaleFactor));
+}
+
+inline QRect fromNativePixels(const QRect &pixelRect, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen()) {
+ return fromNativePixels(pixelRect, window->screen());
+ } else {
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QRect(pixelRect.topLeft() / scaleFactor, fromNative(pixelRect.size(), scaleFactor));
+ }
+}
+
+inline QRectF toNativePixels(const QRectF &pointRect, const QScreen *screen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(screen);
+ const QPoint origin = QHighDpiScaling::origin(screen);
+ return QRectF(toNative(pointRect.topLeft(), scaleFactor, origin),
+ toNative(pointRect.size(), scaleFactor));
+}
+
+inline QRect toNativePixels(const QRect &pointRect, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen()) {
+ return toNativePixels(pointRect, window->screen());
+ } else {
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QRect(pointRect.topLeft() * scaleFactor, toNative(pointRect.size(), scaleFactor));
+ }
+}
+
+inline QRectF fromNativePixels(const QRectF &pixelRect, const QScreen *screen)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(screen);
+ const QPoint origin = QHighDpiScaling::origin(screen);
+ return QRectF(fromNative(pixelRect.topLeft(), scaleFactor, origin),
+ fromNative(pixelRect.size(), scaleFactor));
+}
+
+inline QRectF fromNativePixels(const QRectF &pixelRect, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen()) {
+ return fromNativePixels(pixelRect, window->screen());
+ } else {
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QRectF(pixelRect.topLeft() / scaleFactor, pixelRect.size() / scaleFactor);
+ }
+}
+
+inline QRectF toNativePixels(const QRectF &pointRect, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen()) {
+ return toNativePixels(pointRect, window->screen());
+ } else {
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QRectF(pointRect.topLeft() * scaleFactor, pointRect.size() * scaleFactor);
+ }
+}
+
+inline QSize fromNativePixels(const QSize &pixelSize, const QWindow *window)
+{
+ return pixelSize / QHighDpiScaling::factor(window);
+}
+
+inline QSize toNativePixels(const QSize &pointSize, const QWindow *window)
+{
+ return pointSize * QHighDpiScaling::factor(window);
+}
+
+inline QSizeF fromNativePixels(const QSizeF &pixelSize, const QWindow *window)
+{
+ return pixelSize / QHighDpiScaling::factor(window);
+}
+
+inline QSizeF toNativePixels(const QSizeF &pointSize, const QWindow *window)
+{
+ return pointSize * QHighDpiScaling::factor(window);
+}
+
+inline QPoint fromNativePixels(const QPoint &pixelPoint, const QScreen *screen)
+{
+ return fromNative(pixelPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen));
+}
+
+inline QPoint fromNativePixels(const QPoint &pixelPoint, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen())
+ return fromNativePixels(pixelPoint, window->screen());
+ else
+ return pixelPoint / QHighDpiScaling::factor(window);
+}
+
+inline QPoint toNativePixels(const QPoint &pointPoint, const QScreen *screen)
+{
+ return toNative(pointPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen));
+}
+
+inline QPoint toNativePixels(const QPoint &pointPoint, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen())
+ return toNativePixels(pointPoint, window->screen());
+ else
+ return pointPoint * QHighDpiScaling::factor(window);
+}
+
+inline QPointF fromNativePixels(const QPointF &pixelPoint, const QScreen *screen)
+{
+ return fromNative(pixelPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen));
+}
+
+inline QPointF fromNativePixels(const QPointF &pixelPoint, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen())
+ return fromNativePixels(pixelPoint, window->screen());
+ else
+ return pixelPoint / QHighDpiScaling::factor(window);
+}
+
+inline QPointF toNativePixels(const QPointF &pointPoint, const QScreen *screen)
+{
+ return toNative(pointPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen));
+}
+
+inline QPointF toNativePixels(const QPointF &pointPoint, const QWindow *window)
+{
+ if (window && window->isTopLevel() && window->screen())
+ return toNativePixels(pointPoint, window->screen());
+ else
+ return pointPoint * QHighDpiScaling::factor(window);
+}
+
+inline QMargins fromNativePixels(const QMargins &pixelMargins, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QMargins(pixelMargins.left() / scaleFactor, pixelMargins.top() / scaleFactor,
+ pixelMargins.right() / scaleFactor, pixelMargins.bottom() / scaleFactor);
+}
+
+inline QMargins toNativePixels(const QMargins &pointMargins, const QWindow *window)
+{
+ const qreal scaleFactor = QHighDpiScaling::factor(window);
+ return QMargins(pointMargins.left() * scaleFactor, pointMargins.top() * scaleFactor,
+ pointMargins.right() * scaleFactor, pointMargins.bottom() * scaleFactor);
+}
+
+inline QRegion fromNativeLocalRegion(const QRegion &pixelRegion, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pixelRegion;
+
+ qreal scaleFactor = QHighDpiScaling::factor(window);
+ QRegion pointRegion;
+ foreach (const QRect &rect, pixelRegion.rects()) {
+ pointRegion += QRect(fromNative(rect.topLeft(), scaleFactor),
+ fromNative(rect.size(), scaleFactor));
+ }
+ return pointRegion;
+}
+
+inline QRegion toNativeLocalRegion(const QRegion &pointRegion, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pointRegion;
+
+ qreal scaleFactor = QHighDpiScaling::factor(window);
+ QRegion pixelRegon;
+ foreach (const QRect &rect, pointRegion.rects()) {
+ pixelRegon += QRect(toNative(rect.topLeft(), scaleFactor),
+ toNative(rect.size(), scaleFactor));
+ }
+ return pixelRegon;
+}
+
+// Any T that has operator/()
+template <typename T>
+T fromNativePixels(const T &pixelValue, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pixelValue;
+
+ return pixelValue / QHighDpiScaling::factor(window);
+
+}
+
+ //##### ?????
+template <typename T>
+T fromNativePixels(const T &pixelValue, const QScreen *screen)
+{
+ if (!QHighDpiScaling::isActive())
+ return pixelValue;
+
+ return pixelValue / QHighDpiScaling::factor(screen);
+
+}
+
+// Any T that has operator*()
+template <typename T>
+T toNativePixels(const T &pointValue, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pointValue;
+
+ return pointValue * QHighDpiScaling::factor(window);
+}
+
+template <typename T>
+T toNativePixels(const T &pointValue, const QScreen *screen)
+{
+ if (!QHighDpiScaling::isActive())
+ return pointValue;
+
+ return pointValue * QHighDpiScaling::factor(screen);
+}
+
+
+// Any QVector<T> where T has operator/()
+template <typename T>
+QVector<T> fromNativePixels(const QVector<T> &pixelValues, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pixelValues;
+
+ QVector<T> pointValues;
+ foreach (const T& pixelValue, pixelValues)
+ pointValues.append(pixelValue / QHighDpiScaling::factor(window));
+ return pointValues;
+}
+
+// Any QVector<T> where T has operator*()
+template <typename T>
+QVector<T> toNativePixels(const QVector<T> &pointValues, const QWindow *window)
+{
+ if (!QHighDpiScaling::isActive())
+ return pointValues;
+
+ QVector<T> pixelValues;
+ foreach (const T& pointValue, pointValues)
+ pixelValues.append(pointValue * QHighDpiScaling::factor(window));
+ return pixelValues;
+}
+
+} // namespace QHighDpi
+#else // QT_NO_HIGHDPISCALING
+class Q_GUI_EXPORT QHighDpiScaling {
+public:
+ static inline void initHighDpiScaling() {}
+ static inline void updateHighDpiScaling() {}
+ static inline void setGlobalFactor(qreal) {}
+ static inline void setScreenFactor(QScreen *, qreal) {}
+
+ static inline bool isActive() { return false; }
+ static inline qreal factor(const QWindow *) { return 1.0; }
+ static inline qreal factor(const QScreen *) { return 1.0; }
+ static inline qreal factor(const QPlatformScreen *) { return 1.0; }
+ static inline QPoint origin(const QScreen *) { return QPoint(); }
+ static inline QPoint origin(const QPlatformScreen *) { return QPoint(); }
+ static inline QPoint mapPositionFromNative(const QPoint &pos, const QPlatformScreen *) { return pos; }
+ static inline QPoint mapPositionToNative(const QPoint &pos, const QPlatformScreen *) { return pos; }
+ static inline QDpi logicalDpi() { return QDpi(-1,-1); }
+};
+
+namespace QHighDpi {
+ template <typename T> inline
+ T toNative(const T &value, ...) { return value; }
+ template <typename T> inline
+ T fromNative(const T &value, ...) { return value; }
+
+ template <typename T> inline
+ T fromNativeLocalPosition(const T &value, ...) { return value; }
+ template <typename T> inline
+ T toNativeLocalPosition(const T &value, ...) { return value; }
+
+ template <typename T> inline
+ T fromNativeLocalRegion(const T &value, ...) { return value; }
+ template <typename T> inline
+ T toNativeLocalRegion(const T &value, ...) { return value; }
+
+ template <typename T> inline
+ T fromNativeScreenGeometry(const T &value, ...) { return value; }
+
+ template <typename T, typename U> inline
+ T toNativePixels(const T &value, const U*) {return value;}
+ template <typename T, typename U> inline
+ T fromNativePixels(const T &value, const U*) {return value;}
+}
+#endif // QT_NO_HIGHDPISCALING
+QT_END_NAMESPACE
+
+#endif // QHIGHDPISCALING_P_H
diff --git a/src/gui/kernel/qinputmethod.h b/src/gui/kernel/qinputmethod.h
index 3e801bff3c..d7a7b1db8a 100644
--- a/src/gui/kernel/qinputmethod.h
+++ b/src/gui/kernel/qinputmethod.h
@@ -82,7 +82,7 @@ public:
QLocale locale() const;
Qt::LayoutDirection inputDirection() const;
- static QVariant queryFocusObject(Qt::InputMethodQuery query, QVariant argument);
+ static QVariant queryFocusObject(Qt::InputMethodQuery query, QVariant argument); // ### Qt 6: QVariant by const-ref
public Q_SLOTS:
void show();
diff --git a/src/gui/kernel/qkeymapper_p.h b/src/gui/kernel/qkeymapper_p.h
index 20dcbbc139..34003cdf41 100644
--- a/src/gui/kernel/qkeymapper_p.h
+++ b/src/gui/kernel/qkeymapper_p.h
@@ -50,7 +50,6 @@
#include <qlist.h>
#include <qlocale.h>
#include <qevent.h>
-#include <qhash.h>
QT_BEGIN_NAMESPACE
diff --git a/src/gui/kernel/qkeysequence.cpp b/src/gui/kernel/qkeysequence.cpp
index 5bf22b9394..ffa9b87147 100644
--- a/src/gui/kernel/qkeysequence.cpp
+++ b/src/gui/kernel/qkeysequence.cpp
@@ -39,6 +39,7 @@
#ifndef QT_NO_SHORTCUT
#include "qdebug.h"
+#include <QtCore/qhashfunctions.h>
#ifndef QT_NO_REGEXP
# include "qregexp.h"
#endif
@@ -818,6 +819,7 @@ QKeySequence::QKeySequence(const QString &key, QKeySequence::SequenceFormat form
assign(key, format);
}
+Q_STATIC_ASSERT_X(QKeySequencePrivate::MaxKeyCount == 4, "Change docs and ctor impl below");
/*!
Constructs a key sequence with up to 4 keys \a k1, \a k2,
\a k3 and \a k4.
@@ -876,26 +878,19 @@ QKeySequence::~QKeySequence()
void QKeySequence::setKey(int key, int index)
{
- Q_ASSERT_X(index >= 0 && index < 4, "QKeySequence::setKey", "index out of range");
+ Q_ASSERT_X(index >= 0 && index < QKeySequencePrivate::MaxKeyCount, "QKeySequence::setKey", "index out of range");
qAtomicDetach(d);
d->key[index] = key;
}
+Q_STATIC_ASSERT_X(QKeySequencePrivate::MaxKeyCount == 4, "Change docs below");
/*!
Returns the number of keys in the key sequence.
The maximum is 4.
*/
int QKeySequence::count() const
{
- if (!d->key[0])
- return 0;
- if (!d->key[1])
- return 1;
- if (!d->key[2])
- return 2;
- if (!d->key[3])
- return 3;
- return 4;
+ return int(std::distance(d->key, std::find(d->key, d->key + QKeySequencePrivate::MaxKeyCount, 0)));
}
@@ -987,8 +982,8 @@ int QKeySequence::assign(const QString &ks, QKeySequence::SequenceFormat format)
int p = 0, diff = 0;
// Run through the whole string, but stop
- // if we have 4 keys before the end.
- while (keyseq.length() && n < 4) {
+ // if we have MaxKeyCount keys before the end.
+ while (keyseq.length() && n < QKeySequencePrivate::MaxKeyCount) {
// We MUST use something to separate each sequence, and space
// does not cut it, since some of the key names have space
// in them.. (Let's hope no one translate with a comma in it:)
@@ -1022,9 +1017,10 @@ struct QModifKeyName {
int qt_key;
QString name;
};
+Q_DECLARE_TYPEINFO(QModifKeyName, Q_MOVABLE_TYPE);
-Q_GLOBAL_STATIC(QList<QModifKeyName>, globalModifs)
-Q_GLOBAL_STATIC(QList<QModifKeyName>, globalPortableModifs)
+Q_GLOBAL_STATIC(QVector<QModifKeyName>, globalModifs)
+Q_GLOBAL_STATIC(QVector<QModifKeyName>, globalPortableModifs)
/*!
Constructs a single key from the string \a str.
@@ -1040,7 +1036,7 @@ int QKeySequencePrivate::decodeString(const QString &str, QKeySequence::Sequence
QString accel = str.toLower();
bool nativeText = (format == QKeySequence::NativeText);
- QList<QModifKeyName> *gmodifs;
+ QVector<QModifKeyName> *gmodifs;
if (nativeText) {
gmodifs = globalModifs();
if (gmodifs->isEmpty()) {
@@ -1076,7 +1072,7 @@ int QKeySequencePrivate::decodeString(const QString &str, QKeySequence::Sequence
if (!gmodifs) return ret;
- QList<QModifKeyName> modifs;
+ QVector<QModifKeyName> modifs;
if (nativeText) {
modifs << QModifKeyName(Qt::CTRL, QCoreApplication::translate("QShortcut", "Ctrl").toLower().append(QLatin1Char('+')))
<< QModifKeyName(Qt::SHIFT, QCoreApplication::translate("QShortcut", "Shift").toLower().append(QLatin1Char('+')))
@@ -1100,7 +1096,7 @@ int QKeySequencePrivate::decodeString(const QString &str, QKeySequence::Sequence
int i = 0;
int lastI = 0;
while ((i = sl.indexOf(QLatin1Char('+'), i + 1)) != -1) {
- const QString sub = sl.mid(lastI, i - lastI + 1);
+ const QStringRef sub = sl.midRef(lastI, i - lastI + 1);
// If we get here the shortcuts contains at least one '+'. We break up
// along the following strategy:
// Meta+Ctrl++ ( "Meta+", "Ctrl+", "+" )
@@ -1366,7 +1362,7 @@ QKeySequence::operator QVariant() const
*/
int QKeySequence::operator[](uint index) const
{
- Q_ASSERT_X(index < 4, "QKeySequence::operator[]", "index out of range");
+ Q_ASSERT_X(index < QKeySequencePrivate::MaxKeyCount, "QKeySequence::operator[]", "index out of range");
return d->key[index];
}
@@ -1409,6 +1405,16 @@ bool QKeySequence::operator==(const QKeySequence &other) const
d->key[3] == other.d->key[3]);
}
+/*!
+ \since 5.6
+
+ Calculates the hash value of \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QKeySequence &key, uint seed) Q_DECL_NOTHROW
+{
+ return qHashRange(key.d->key, key.d->key + QKeySequencePrivate::MaxKeyCount, seed);
+}
/*!
Provides an arbitrary comparison of this key sequence and
@@ -1424,10 +1430,8 @@ bool QKeySequence::operator==(const QKeySequence &other) const
*/
bool QKeySequence::operator< (const QKeySequence &other) const
{
- for (int i = 0; i < 4; ++i)
- if (d->key[i] != other.d->key[i])
- return d->key[i] < other.d->key[i];
- return false;
+ return std::lexicographical_compare(d->key, d->key + QKeySequencePrivate::MaxKeyCount,
+ other.d->key, other.d->key + QKeySequencePrivate::MaxKeyCount);
}
/*!
@@ -1523,6 +1527,7 @@ QList<QKeySequence> QKeySequence::listFromString(const QString &str, SequenceFor
QList<QKeySequence> result;
QStringList strings = str.split(QLatin1String("; "));
+ result.reserve(strings.count());
foreach (const QString &string, strings) {
result << fromString(string, format);
}
@@ -1565,15 +1570,14 @@ QString QKeySequence::listToString(const QList<QKeySequence> &list, SequenceForm
*/
QDataStream &operator<<(QDataStream &s, const QKeySequence &keysequence)
{
- QList<quint32> list;
- list << keysequence.d->key[0];
-
- if (s.version() >= 5 && keysequence.count() > 1) {
- list << keysequence.d->key[1];
- list << keysequence.d->key[2];
- list << keysequence.d->key[3];
+ Q_STATIC_ASSERT_X(QKeySequencePrivate::MaxKeyCount == 4, "Forgot to adapt QDataStream &operator<<(QDataStream &s, const QKeySequence &keysequence) to new QKeySequence::MaxKeyCount");
+ const bool extended = s.version() >= 5 && keysequence.count() > 1;
+ s << quint32(extended ? 4 : 1) << quint32(keysequence.d->key[0]);
+ if (extended) {
+ s << quint32(keysequence.d->key[1])
+ << quint32(keysequence.d->key[2])
+ << quint32(keysequence.d->key[3]);
}
- s << list;
return s;
}
@@ -1588,11 +1592,19 @@ QDataStream &operator<<(QDataStream &s, const QKeySequence &keysequence)
*/
QDataStream &operator>>(QDataStream &s, QKeySequence &keysequence)
{
+ const quint32 MaxKeys = QKeySequencePrivate::MaxKeyCount;
+ quint32 c;
+ s >> c;
+ quint32 keys[MaxKeys] = {0};
+ for (uint i = 0; i < qMin(c, MaxKeys); ++i) {
+ if (s.atEnd()) {
+ qWarning("Premature EOF while reading QKeySequence");
+ return s;
+ }
+ s >> keys[i];
+ }
qAtomicDetach(keysequence.d);
- QList<quint32> list;
- s >> list;
- for (int i = 0; i < 4; ++i)
- keysequence.d->key[i] = list.value(i);
+ std::copy(keys, keys + MaxKeys, keysequence.d->key);
return s;
}
diff --git a/src/gui/kernel/qkeysequence.h b/src/gui/kernel/qkeysequence.h
index cd7af5718f..d6171c86f2 100644
--- a/src/gui/kernel/qkeysequence.h
+++ b/src/gui/kernel/qkeysequence.h
@@ -43,11 +43,12 @@ QT_BEGIN_NAMESPACE
#ifndef QT_NO_SHORTCUT
+class QKeySequence;
+
/*****************************************************************************
QKeySequence stream functions
*****************************************************************************/
#ifndef QT_NO_DATASTREAM
-class QKeySequence;
Q_GUI_EXPORT QDataStream &operator<<(QDataStream &in, const QKeySequence &ks);
Q_GUI_EXPORT QDataStream &operator>>(QDataStream &out, QKeySequence &ks);
#endif
@@ -59,6 +60,8 @@ void qt_set_sequence_auto_mnemonic(bool b);
class QVariant;
class QKeySequencePrivate;
+Q_GUI_EXPORT Q_DECL_PURE_FUNCTION uint qHash(const QKeySequence &key, uint seed = 0) Q_DECL_NOTHROW;
+
class Q_GUI_EXPORT QKeySequence
{
Q_GADGET
@@ -177,10 +180,10 @@ public:
int operator[](uint i) const;
QKeySequence &operator=(const QKeySequence &other);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QKeySequence &operator=(QKeySequence &&other)
- { qSwap(d, other.d); return *this; }
+ QKeySequence &operator=(QKeySequence &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QKeySequence &other) { qSwap(d, other.d); }
+ void swap(QKeySequence &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
+
bool operator==(const QKeySequence &other) const;
inline bool operator!= (const QKeySequence &other) const
{ return !(*this == other); }
@@ -204,6 +207,7 @@ private:
friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &in, const QKeySequence &ks);
friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QKeySequence &ks);
+ friend Q_GUI_EXPORT uint qHash(const QKeySequence &key, uint seed) Q_DECL_NOTHROW;
friend class QShortcutMap;
friend class QShortcut;
diff --git a/src/gui/kernel/qkeysequence_p.h b/src/gui/kernel/qkeysequence_p.h
index 97416943d0..3e4c5bae88 100644
--- a/src/gui/kernel/qkeysequence_p.h
+++ b/src/gui/kernel/qkeysequence_p.h
@@ -47,6 +47,8 @@
#include "qkeysequence.h"
+#include <algorithm>
+
QT_BEGIN_NAMESPACE
#ifndef QT_NO_SHORTCUT
@@ -61,20 +63,17 @@ struct Q_AUTOTEST_EXPORT QKeyBinding
class Q_AUTOTEST_EXPORT QKeySequencePrivate
{
public:
- enum { MaxKeyCount = 4 }; // used in QKeySequenceEdit
+ enum { MaxKeyCount = 4 }; // also used in QKeySequenceEdit
inline QKeySequencePrivate() : ref(1)
{
- key[0] = key[1] = key[2] = key[3] = 0;
+ std::fill_n(key, uint(MaxKeyCount), 0);
}
inline QKeySequencePrivate(const QKeySequencePrivate &copy) : ref(1)
{
- key[0] = copy.key[0];
- key[1] = copy.key[1];
- key[2] = copy.key[2];
- key[3] = copy.key[3];
+ std::copy(copy.key, copy.key + MaxKeyCount, key);
}
QAtomicInt ref;
- int key[4];
+ int key[MaxKeyCount];
static QString encodeString(int key, QKeySequence::SequenceFormat format);
static int decodeString(const QString &keyStr, QKeySequence::SequenceFormat format);
};
diff --git a/src/gui/kernel/qoffscreensurface.h b/src/gui/kernel/qoffscreensurface.h
index 909a1ef256..17bc8a7d17 100644
--- a/src/gui/kernel/qoffscreensurface.h
+++ b/src/gui/kernel/qoffscreensurface.h
@@ -51,7 +51,7 @@ class Q_GUI_EXPORT QOffscreenSurface : public QObject, public QSurface
public:
- explicit QOffscreenSurface(QScreen *screen = 0);
+ explicit QOffscreenSurface(QScreen *screen = Q_NULLPTR);
virtual ~QOffscreenSurface();
SurfaceType surfaceType() const Q_DECL_OVERRIDE;
diff --git a/src/gui/kernel/qopenglcontext.cpp b/src/gui/kernel/qopenglcontext.cpp
index 56a3729a4a..9e5767658f 100644
--- a/src/gui/kernel/qopenglcontext.cpp
+++ b/src/gui/kernel/qopenglcontext.cpp
@@ -226,7 +226,7 @@ public:
QOpenGLContext *context;
};
-static QThreadStorage<QGuiGLThreadContext *> qwindow_context_storage;
+Q_GLOBAL_STATIC(QThreadStorage<QGuiGLThreadContext *>, qwindow_context_storage);
static QOpenGLContext *global_share_context = 0;
#ifndef QT_NO_DEBUG
@@ -336,14 +336,14 @@ QOpenGLContext *qt_gl_global_share_context()
*/
QOpenGLContext *QOpenGLContextPrivate::setCurrentContext(QOpenGLContext *context)
{
- QGuiGLThreadContext *threadContext = qwindow_context_storage.localData();
+ QGuiGLThreadContext *threadContext = qwindow_context_storage()->localData();
if (!threadContext) {
if (!QThread::currentThread()) {
qWarning("No QTLS available. currentContext won't work");
return 0;
}
threadContext = new QGuiGLThreadContext;
- qwindow_context_storage.setLocalData(threadContext);
+ qwindow_context_storage()->setLocalData(threadContext);
}
QOpenGLContext *previous = threadContext->context;
threadContext->context = context;
@@ -412,8 +412,8 @@ int QOpenGLContextPrivate::maxTextureSize()
*/
QOpenGLContext* QOpenGLContext::currentContext()
{
- QGuiGLThreadContext *threadContext = qwindow_context_storage.localData();
- if(threadContext) {
+ QGuiGLThreadContext *threadContext = qwindow_context_storage()->localData();
+ if (threadContext) {
return threadContext->context;
}
return 0;
@@ -719,6 +719,28 @@ QOpenGLFunctions *QOpenGLContext::functions() const
}
/*!
+ Get the QOpenGLExtraFunctions instance for this context.
+
+ QOpenGLContext offers this as a convenient way to access QOpenGLExtraFunctions
+ without having to manage it manually.
+
+ The context or a sharing context must be current.
+
+ The returned QOpenGLExtraFunctions instance is ready to be used and it
+ does not need initializeOpenGLFunctions() to be called.
+
+ \note QOpenGLExtraFunctions contains functionality that is not guaranteed to
+ be available at runtime. Runtime availability depends on the platform,
+ graphics driver, and the OpenGL version requested by the application.
+
+ \sa QOpenGLFunctions, QOpenGLExtraFunctions
+*/
+QOpenGLExtraFunctions *QOpenGLContext::extraFunctions() const
+{
+ return static_cast<QOpenGLExtraFunctions *>(functions());
+}
+
+/*!
\fn T *QOpenGLContext::versionFunctions() const
\overload versionFunctions()
diff --git a/src/gui/kernel/qopenglcontext.h b/src/gui/kernel/qopenglcontext.h
index a529957ad6..85e7abfa26 100644
--- a/src/gui/kernel/qopenglcontext.h
+++ b/src/gui/kernel/qopenglcontext.h
@@ -54,7 +54,10 @@
#include <QtGui/qopengl.h>
#include <QtGui/qopenglversionfunctions.h>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
+#include <QtCore/qhashfunctions.h>
#include <QtCore/qpair.h>
#include <QtCore/qvariant.h>
@@ -63,6 +66,7 @@ QT_BEGIN_NAMESPACE
class QOpenGLContextPrivate;
class QOpenGLContextGroupPrivate;
class QOpenGLFunctions;
+class QOpenGLExtraFunctions;
class QPlatformOpenGLContext;
class QScreen;
@@ -140,7 +144,7 @@ class Q_GUI_EXPORT QOpenGLContext : public QObject
Q_OBJECT
Q_DECLARE_PRIVATE(QOpenGLContext)
public:
- explicit QOpenGLContext(QObject *parent = 0);
+ explicit QOpenGLContext(QObject *parent = Q_NULLPTR);
~QOpenGLContext();
void setFormat(const QSurfaceFormat &format);
@@ -174,6 +178,7 @@ public:
QPlatformOpenGLContext *shareHandle() const;
QOpenGLFunctions *functions() const;
+ QOpenGLExtraFunctions *extraFunctions() const;
QAbstractOpenGLFunctions *versionFunctions(const QOpenGLVersionProfile &versionProfile = QOpenGLVersionProfile()) const;
diff --git a/src/gui/kernel/qopenglwindow.cpp b/src/gui/kernel/qopenglwindow.cpp
index b2025faaf1..3a1126d318 100644
--- a/src/gui/kernel/qopenglwindow.cpp
+++ b/src/gui/kernel/qopenglwindow.cpp
@@ -664,15 +664,10 @@ int QOpenGLWindow::metric(PaintDeviceMetric metric) const
if (d->paintDevice)
return d->paintDevice->depth();
break;
- case PdmDevicePixelRatio:
- if (d->paintDevice)
- return devicePixelRatio();
- break;
default:
break;
}
return QPaintDeviceWindow::metric(metric);
-
}
/*!
diff --git a/src/gui/kernel/qopenglwindow.h b/src/gui/kernel/qopenglwindow.h
index f274275c3f..0c2b44c1c7 100644
--- a/src/gui/kernel/qopenglwindow.h
+++ b/src/gui/kernel/qopenglwindow.h
@@ -58,8 +58,8 @@ public:
PartialUpdateBlend
};
- explicit QOpenGLWindow(UpdateBehavior updateBehavior = NoPartialUpdate, QWindow *parent = 0);
- explicit QOpenGLWindow(QOpenGLContext *shareContext, UpdateBehavior updateBehavior = NoPartialUpdate, QWindow *parent = 0);
+ explicit QOpenGLWindow(UpdateBehavior updateBehavior = NoPartialUpdate, QWindow *parent = Q_NULLPTR);
+ explicit QOpenGLWindow(QOpenGLContext *shareContext, UpdateBehavior updateBehavior = NoPartialUpdate, QWindow *parent = Q_NULLPTR);
~QOpenGLWindow();
UpdateBehavior updateBehavior() const;
diff --git a/src/gui/kernel/qpaintdevicewindow.cpp b/src/gui/kernel/qpaintdevicewindow.cpp
index ff661d017d..cd894866c3 100644
--- a/src/gui/kernel/qpaintdevicewindow.cpp
+++ b/src/gui/kernel/qpaintdevicewindow.cpp
@@ -155,8 +155,10 @@ int QPaintDeviceWindow::metric(PaintDeviceMetric metric) const
return qRound(screen->physicalDotsPerInchY());
break;
case PdmDevicePixelRatio:
- if (screen)
- return screen->devicePixelRatio();
+ return int(QWindow::devicePixelRatio());
+ break;
+ case PdmDevicePixelRatioScaled:
+ return int(QWindow::devicePixelRatio() * devicePixelRatioFScale());
break;
default:
break;
diff --git a/src/gui/kernel/qplatformcursor.cpp b/src/gui/kernel/qplatformcursor.cpp
index 7239ac7ba4..cd43fc42fe 100644
--- a/src/gui/kernel/qplatformcursor.cpp
+++ b/src/gui/kernel/qplatformcursor.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the QtOpenVG module of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
diff --git a/src/gui/kernel/qplatformcursor.h b/src/gui/kernel/qplatformcursor.h
index 4f4f9cc6ae..8c788fd27b 100644
--- a/src/gui/kernel/qplatformcursor.h
+++ b/src/gui/kernel/qplatformcursor.h
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the QtOpenVG module of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
diff --git a/src/gui/kernel/qplatformdialoghelper.cpp b/src/gui/kernel/qplatformdialoghelper.cpp
index 3d37088182..25894fd504 100644
--- a/src/gui/kernel/qplatformdialoghelper.cpp
+++ b/src/gui/kernel/qplatformdialoghelper.cpp
@@ -36,7 +36,6 @@
#include <QtCore/QVariant>
#include <QtCore/QSharedData>
#include <QtCore/QSettings>
-#include <QtCore/QHash>
#include <QtCore/QUrl>
#include <QtGui/QColor>
@@ -423,6 +422,7 @@ public:
QUrl initialDirectory;
QString initiallySelectedNameFilter;
QList<QUrl> initiallySelectedFiles;
+ QStringList supportedSchemes;
};
QFileDialogOptions::QFileDialogOptions() : d(new QFileDialogOptionsPrivate)
@@ -614,6 +614,18 @@ void QFileDialogOptions::setInitiallySelectedFiles(const QList<QUrl> &files)
d->initiallySelectedFiles = files;
}
+// Schemes supported by the application
+void QFileDialogOptions::setSupportedSchemes(const QStringList &schemes)
+{
+ d->supportedSchemes = schemes;
+}
+
+QStringList QFileDialogOptions::supportedSchemes() const
+{
+ return d->supportedSchemes;
+}
+
+// Return true if the URL is supported by the filedialog implementation *and* by the application.
bool QPlatformFileDialogHelper::isSupportedUrl(const QUrl &url) const
{
return url.isLocalFile();
diff --git a/src/gui/kernel/qplatformdialoghelper.h b/src/gui/kernel/qplatformdialoghelper.h
index 8b2b9881b7..ec88770862 100644
--- a/src/gui/kernel/qplatformdialoghelper.h
+++ b/src/gui/kernel/qplatformdialoghelper.h
@@ -348,6 +348,9 @@ public:
QList<QUrl> initiallySelectedFiles() const;
void setInitiallySelectedFiles(const QList<QUrl> &);
+ void setSupportedSchemes(const QStringList &schemes);
+ QStringList supportedSchemes() const;
+
private:
QSharedDataPointer<QFileDialogOptionsPrivate> d;
};
diff --git a/src/gui/kernel/qplatforminputcontextfactory.cpp b/src/gui/kernel/qplatforminputcontextfactory.cpp
index a7660e76ae..9d55b778ce 100644
--- a/src/gui/kernel/qplatforminputcontextfactory.cpp
+++ b/src/gui/kernel/qplatforminputcontextfactory.cpp
@@ -56,48 +56,32 @@ QStringList QPlatformInputContextFactory::keys()
#endif
}
-QPlatformInputContext *QPlatformInputContextFactory::create(const QString& key)
+QString QPlatformInputContextFactory::requested()
{
- QStringList paramList = key.split(QLatin1Char(':'));
- const QString platform = paramList.takeFirst().toLower();
-
-#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- if (QPlatformInputContext *ret = qLoadPlugin1<QPlatformInputContext, QPlatformInputContextPlugin>(loader(), platform, paramList))
- return ret;
-#endif
- return 0;
+ QByteArray env = qgetenv("QT_IM_MODULE");
+ return env.isNull() ? QString() : QString::fromLocal8Bit(env);
}
-QPlatformInputContext *QPlatformInputContextFactory::create()
+QPlatformInputContext *QPlatformInputContextFactory::create(const QString& key)
{
- QPlatformInputContext *ic = 0;
-
- QString icString = QString::fromLatin1(qgetenv("QT_IM_MODULE"));
-
- if (icString == QLatin1String("none"))
- return 0;
+#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
+ QStringList paramList = key.split(QLatin1Char(':'));
+ const QString platform = paramList.takeFirst().toLower();
- ic = create(icString);
+ QPlatformInputContext *ic = qLoadPlugin1<QPlatformInputContext, QPlatformInputContextPlugin>
+ (loader(), platform, paramList);
if (ic && ic->isValid())
return ic;
delete ic;
- ic = 0;
-
- QStringList k = keys();
- for (int i = 0; i < k.size(); ++i) {
- if (k.at(i) == icString)
- continue;
- ic = create(k.at(i));
- if (ic && ic->isValid())
- return ic;
- delete ic;
- ic = 0;
- }
-
+#endif
return 0;
}
+QPlatformInputContext *QPlatformInputContextFactory::create()
+{
+ return create(requested());
+}
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qplatforminputcontextfactory_p.h b/src/gui/kernel/qplatforminputcontextfactory_p.h
index a74c4f5f80..38f4358287 100644
--- a/src/gui/kernel/qplatforminputcontextfactory_p.h
+++ b/src/gui/kernel/qplatforminputcontextfactory_p.h
@@ -56,6 +56,7 @@ class Q_GUI_EXPORT QPlatformInputContextFactory
{
public:
static QStringList keys();
+ static QString requested();
static QPlatformInputContext *create(const QString &key);
static QPlatformInputContext *create();
};
diff --git a/src/gui/kernel/qplatformintegration.cpp b/src/gui/kernel/qplatformintegration.cpp
index 4d973d47a5..e935907a62 100644
--- a/src/gui/kernel/qplatformintegration.cpp
+++ b/src/gui/kernel/qplatformintegration.cpp
@@ -39,7 +39,6 @@
#include <qpa/qplatformtheme.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/private/qpixmap_raster_p.h>
-#include <qpa/qplatformscreen_p.h>
#include <private/qdnd_p.h>
#include <private/qsimpledrag_p.h>
@@ -450,7 +449,7 @@ QList<int> QPlatformIntegration::possibleKeys(const QKeyEvent *) const
void QPlatformIntegration::screenAdded(QPlatformScreen *ps, bool isPrimary)
{
QScreen *screen = new QScreen(ps);
- ps->d_func()->screen = screen;
+
if (isPrimary) {
QGuiApplicationPrivate::screen_list.prepend(screen);
} else {
@@ -469,8 +468,9 @@ void QPlatformIntegration::screenAdded(QPlatformScreen *ps, bool isPrimary)
*/
void QPlatformIntegration::destroyScreen(QPlatformScreen *screen)
{
- QGuiApplicationPrivate::screen_list.removeOne(screen->d_func()->screen);
- delete screen->d_func()->screen;
+ QScreen *qScreen = screen->screen();
+ QGuiApplicationPrivate::screen_list.removeOne(qScreen);
+ delete qScreen;
delete screen;
}
diff --git a/src/gui/kernel/qplatformintegrationfactory.cpp b/src/gui/kernel/qplatformintegrationfactory.cpp
index d58ac3a33f..5a1fb3ca83 100644
--- a/src/gui/kernel/qplatformintegrationfactory.cpp
+++ b/src/gui/kernel/qplatformintegrationfactory.cpp
@@ -72,6 +72,12 @@ QPlatformIntegration *QPlatformIntegrationFactory::create(const QString &platfor
}
if (QPlatformIntegration *ret = loadIntegration(loader(), platform, paramList, argc, argv))
return ret;
+#else
+ Q_UNUSED(platform);
+ Q_UNUSED(paramList);
+ Q_UNUSED(argc);
+ Q_UNUSED(argv);
+ Q_UNUSED(platformPluginPath);
#endif
return 0;
}
@@ -102,6 +108,7 @@ QStringList QPlatformIntegrationFactory::keys(const QString &platformPluginPath)
list.append(loader()->keyMap().values());
return list;
#else
+ Q_UNUSED(platformPluginPath);
return QStringList();
#endif
}
diff --git a/src/gui/kernel/qplatformscreen.cpp b/src/gui/kernel/qplatformscreen.cpp
index edf546799f..2fb53fe16b 100644
--- a/src/gui/kernel/qplatformscreen.cpp
+++ b/src/gui/kernel/qplatformscreen.cpp
@@ -40,6 +40,7 @@
#include <qpa/qplatformintegration.h>
#include <QtGui/qscreen.h>
#include <QtGui/qwindow.h>
+#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
@@ -97,6 +98,23 @@ QWindow *QPlatformScreen::topLevelAt(const QPoint & pos) const
}
/*!
+ Find the sibling screen corresponding to \a globalPos.
+
+ Returns this screen if no suitable screen is found at the position.
+ */
+const QPlatformScreen *QPlatformScreen::screenForPosition(const QPoint &point) const
+{
+ if (!geometry().contains(point)) {
+ Q_FOREACH (const QPlatformScreen* screen, virtualSiblings()) {
+ if (screen->geometry().contains(point))
+ return screen;
+ }
+ }
+ return this;
+}
+
+
+/*!
Returns a list of all the platform screens that are part of the same
virtual desktop.
@@ -156,11 +174,13 @@ QDpi QPlatformScreen::logicalDpi() const
}
/*!
- Reimplement this function in subclass to return the device pixel
- ratio for the screen. This is the ratio between physical pixels
- and device-independent pixels.
+ Reimplement this function in subclass to return the device pixel ratio
+ for the screen. This is the ratio between physical pixels and the
+ device-independent pixels of the windowing system. The default
+ implementation returns 1.0.
- \sa QPlatformWindow::devicePixelRatio();
+ \sa QPlatformWindow::devicePixelRatio()
+ \sa QPlatformScreen::pixelDensity()
*/
qreal QPlatformScreen::devicePixelRatio() const
{
@@ -168,6 +188,24 @@ qreal QPlatformScreen::devicePixelRatio() const
}
/*!
+ Reimplement this function in subclass to return the pixel density of the
+ screen. This is the scale factor needed to make a low-dpi application
+ usable on this screen. The default implementation returns 1.0.
+
+ Returning something else than 1.0 from this function causes Qt to
+ apply the scale factor to the application's coordinate system.
+ This is different from devicePixelRatio, which reports a scale
+ factor already applied by the windowing system. A platform plugin
+ typically implements one (or none) of these two functions.
+
+ \sa QPlatformWindow::devicePixelRatio()
+*/
+qreal QPlatformScreen::pixelDensity() const
+{
+ return 1.0;
+}
+
+/*!
Reimplement this function in subclass to return the vertical refresh rate
of the screen, in Hz.
@@ -290,8 +328,8 @@ void QPlatformScreen::resizeMaximizedWindows()
// 'screen()' still has the old geometry info while 'this' has the new geometry info
const QRect oldGeometry = screen()->geometry();
const QRect oldAvailableGeometry = screen()->availableGeometry();
- const QRect newGeometry = geometry();
- const QRect newAvailableGeometry = availableGeometry();
+ const QRect newGeometry = deviceIndependentGeometry();
+ const QRect newAvailableGeometry = QHighDpi::fromNative(availableGeometry(), QHighDpiScaling::factor(this), newGeometry.topLeft());
// make sure maximized and fullscreen windows are updated
for (int i = 0; i < windows.size(); ++i) {
@@ -393,6 +431,13 @@ QRect QPlatformScreen::mapBetween(Qt::ScreenOrientation a, Qt::ScreenOrientation
return rect;
}
+QRect QPlatformScreen::deviceIndependentGeometry() const
+{
+ qreal scaleFactor = QHighDpiScaling::factor(this);
+ QRect nativeGeometry = geometry();
+ return QRect(nativeGeometry.topLeft(), QHighDpi::fromNative(nativeGeometry.size(), scaleFactor));
+}
+
/*!
Returns a hint about this screen's subpixel layout structure.
@@ -420,4 +465,22 @@ QPlatformScreen::SubpixelAntialiasingType QPlatformScreen::subpixelAntialiasingT
return static_cast<QPlatformScreen::SubpixelAntialiasingType>(type);
}
+/*!
+ Returns the current power state.
+
+ The default implementation always returns PowerStateOn.
+*/
+QPlatformScreen::PowerState QPlatformScreen::powerState() const
+{
+ return PowerStateOn;
+}
+
+/*!
+ Sets the power state for this screen.
+*/
+void QPlatformScreen::setPowerState(PowerState state)
+{
+ Q_UNUSED(state);
+}
+
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qplatformscreen.h b/src/gui/kernel/qplatformscreen.h
index 551cb788c9..b32f9cf97c 100644
--- a/src/gui/kernel/qplatformscreen.h
+++ b/src/gui/kernel/qplatformscreen.h
@@ -82,6 +82,13 @@ public:
Subpixel_VBGR
};
+ enum PowerState {
+ PowerStateOn,
+ PowerStateStandby,
+ PowerStateSuspend,
+ PowerStateOff
+ };
+
QPlatformScreen();
virtual ~QPlatformScreen();
@@ -96,6 +103,7 @@ public:
virtual QSizeF physicalSize() const;
virtual QDpi logicalDpi() const;
virtual qreal devicePixelRatio() const;
+ virtual qreal pixelDensity() const;
virtual qreal refreshRate() const;
@@ -105,6 +113,7 @@ public:
virtual QWindow *topLevelAt(const QPoint &point) const;
virtual QList<QPlatformScreen *> virtualSiblings() const;
+ const QPlatformScreen *screenForPosition(const QPoint &point) const;
QScreen *screen() const;
@@ -117,10 +126,16 @@ public:
virtual QPlatformCursor *cursor() const;
virtual SubpixelAntialiasingType subpixelAntialiasingTypeHint() const;
+ virtual PowerState powerState() const;
+ virtual void setPowerState(PowerState state);
+
static int angleBetween(Qt::ScreenOrientation a, Qt::ScreenOrientation b);
static QTransform transformBetween(Qt::ScreenOrientation a, Qt::ScreenOrientation b, const QRect &target);
static QRect mapBetween(Qt::ScreenOrientation a, Qt::ScreenOrientation b, const QRect &rect);
+ // The platform screen's geometry in device independent coordinates
+ QRect deviceIndependentGeometry() const;
+
protected:
void resizeMaximizedWindows();
@@ -129,7 +144,7 @@ protected:
private:
Q_DISABLE_COPY(QPlatformScreen)
- friend class QPlatformIntegration;
+ friend class QScreenPrivate;
};
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qplatformthemefactory.cpp b/src/gui/kernel/qplatformthemefactory.cpp
index d4902ac163..bcc37dad06 100644
--- a/src/gui/kernel/qplatformthemefactory.cpp
+++ b/src/gui/kernel/qplatformthemefactory.cpp
@@ -63,6 +63,9 @@ QPlatformTheme *QPlatformThemeFactory::create(const QString& key, const QString
}
if (QPlatformTheme *ret = qLoadPlugin1<QPlatformTheme, QPlatformThemePlugin>(loader(), platform, paramList))
return ret;
+#else
+ Q_UNUSED(key);
+ Q_UNUSED(platformPluginPath);
#endif
return 0;
}
@@ -93,6 +96,7 @@ QStringList QPlatformThemeFactory::keys(const QString &platformPluginPath)
list += loader()->keyMap().values();
return list;
#else
+ Q_UNUSED(platformPluginPath);
return QStringList();
#endif
}
diff --git a/src/gui/kernel/qplatformwindow.cpp b/src/gui/kernel/qplatformwindow.cpp
index 114fcf8062..0430d5a4c6 100644
--- a/src/gui/kernel/qplatformwindow.cpp
+++ b/src/gui/kernel/qplatformwindow.cpp
@@ -39,8 +39,10 @@
#include <qpa/qwindowsysteminterface.h>
#include <QtGui/qwindow.h>
#include <QtGui/qscreen.h>
+#include <private/qhighdpiscaling_p.h>
#include <private/qwindow_p.h>
+
QT_BEGIN_NAMESPACE
/*!
@@ -481,13 +483,25 @@ QString QPlatformWindow::formatWindowTitle(const QString &title, const QString &
QPlatformScreen *QPlatformWindow::screenForGeometry(const QRect &newGeometry) const
{
QPlatformScreen *currentScreen = screen();
- if (!parent() && currentScreen && !currentScreen->geometry().intersects(newGeometry)) {
+ QPlatformScreen *fallback = currentScreen;
+ QPoint center = newGeometry.center();
+ if (!parent() && currentScreen && !currentScreen->geometry().contains(center)) {
Q_FOREACH (QPlatformScreen* screen, currentScreen->virtualSiblings()) {
- if (screen->geometry().intersects(newGeometry))
+ if (screen->geometry().contains(center))
return screen;
+ if (screen->geometry().intersects(newGeometry))
+ fallback = screen;
}
}
- return currentScreen;
+ return fallback;
+}
+
+/*!
+ Returns a size with both dimensions bounded to [0, QWINDOWSIZE_MAX]
+*/
+QSize QPlatformWindow::constrainWindowSize(const QSize &size)
+{
+ return size.expandedTo(QSize(0, 0)).boundedTo(QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX));
}
/*!
@@ -565,7 +579,7 @@ void QPlatformWindow::invalidateSurface()
QRect QPlatformWindow::initialGeometry(const QWindow *w,
const QRect &initialGeometry, int defaultWidth, int defaultHeight)
{
- QRect rect(initialGeometry);
+ QRect rect(QHighDpi::fromNativePixels(initialGeometry, w));
if (rect.width() == 0) {
const int minWidth = w->minimumWidth();
rect.setWidth(minWidth > 0 ? minWidth : defaultWidth);
@@ -593,7 +607,7 @@ QRect QPlatformWindow::initialGeometry(const QWindow *w,
}
}
}
- return rect;
+ return QHighDpi::toNativePixels(rect, w);
}
/*!
@@ -627,6 +641,77 @@ void QPlatformWindow::requestUpdate()
}
/*!
+ Returns the QWindow minimum size.
+*/
+QSize QPlatformWindow::windowMinimumSize() const
+{
+ return constrainWindowSize(QHighDpi::toNativePixels(window()->minimumSize(), window()));
+}
+
+/*!
+ Returns the QWindow maximum size.
+*/
+QSize QPlatformWindow::windowMaximumSize() const
+{
+ return constrainWindowSize(QHighDpi::toNativePixels(window()->maximumSize(), window()));
+}
+
+/*!
+ Returns the QWindow base size.
+*/
+QSize QPlatformWindow::windowBaseSize() const
+{
+ return QHighDpi::toNativePixels(window()->baseSize(), window());
+}
+
+/*!
+ Returns the QWindow size increment.
+*/
+QSize QPlatformWindow::windowSizeIncrement() const
+{
+ QSize increment = window()->sizeIncrement();
+ if (!QHighDpiScaling::isActive())
+ return increment;
+
+ // Normalize the increment. If not set the increment can be
+ // (-1, -1) or (0, 0). Make that (1, 1) which is scalable.
+ if (increment.isEmpty())
+ increment = QSize(1, 1);
+
+ return QHighDpi::toNativePixels(increment, window());
+}
+
+/*!
+ Returns the QWindow geometry.
+*/
+QRect QPlatformWindow::windowGeometry() const
+{
+ return QHighDpi::toNativePixels(window()->geometry(), window());
+}
+
+/*!
+ Returns the QWindow frame geometry.
+*/
+QRect QPlatformWindow::windowFrameGeometry() const
+{
+ return QHighDpi::toNativePixels(window()->frameGeometry(), window());
+}
+
+/*!
+ Returns the closest acceptable geometry for a given geometry before
+ a resize/move event for platforms that support it, for example to
+ implement heightForWidth().
+*/
+QRectF QPlatformWindow::windowClosestAcceptableGeometry(const QRectF &nativeRect) const
+{
+ QWindow *qWindow = window();
+ const QRectF rectF = QHighDpi::fromNativePixels(nativeRect, qWindow);
+ const QRectF correctedGeometryF = qt_window_private(qWindow)->closestAcceptableGeometry(rectF);
+ return !correctedGeometryF.isEmpty() && rectF != correctedGeometryF
+ ? QHighDpi::toNativePixels(correctedGeometryF, qWindow) : nativeRect;
+}
+
+/*!
\class QPlatformWindow
\since 4.8
\internal
diff --git a/src/gui/kernel/qplatformwindow.h b/src/gui/kernel/qplatformwindow.h
index c7c1efdc58..1b283dbb4f 100644
--- a/src/gui/kernel/qplatformwindow.h
+++ b/src/gui/kernel/qplatformwindow.h
@@ -130,9 +130,21 @@ public:
const QRect &initialGeometry, int defaultWidth, int defaultHeight);
virtual void requestUpdate();
+
+ // Window property accessors. Platform plugins should use these
+ // instead of accessing QWindow directly.
+ QSize windowMinimumSize() const;
+ QSize windowMaximumSize() const;
+ QSize windowBaseSize() const;
+ QSize windowSizeIncrement() const;
+ QRect windowGeometry() const;
+ QRect windowFrameGeometry() const;
+ QRectF windowClosestAcceptableGeometry(const QRectF &nativeRect) const;
+
protected:
static QString formatWindowTitle(const QString &title, const QString &separator);
QPlatformScreen *screenForGeometry(const QRect &newGeometry) const;
+ static QSize constrainWindowSize(const QSize &size);
QScopedPointer<QPlatformWindowPrivate> d_ptr;
private:
diff --git a/src/gui/kernel/qrasterwindow.cpp b/src/gui/kernel/qrasterwindow.cpp
index c04eb71420..fc1739ca0e 100644
--- a/src/gui/kernel/qrasterwindow.cpp
+++ b/src/gui/kernel/qrasterwindow.cpp
@@ -108,8 +108,6 @@ int QRasterWindow::metric(PaintDeviceMetric metric) const
switch (metric) {
case PdmDepth:
return d->backingstore->paintDevice()->depth();
- case PdmDevicePixelRatio:
- return d->backingstore->paintDevice()->devicePixelRatio();
default:
break;
}
diff --git a/src/gui/kernel/qrasterwindow.h b/src/gui/kernel/qrasterwindow.h
index 4912efad37..6db6baa8f5 100644
--- a/src/gui/kernel/qrasterwindow.h
+++ b/src/gui/kernel/qrasterwindow.h
@@ -46,7 +46,7 @@ class Q_GUI_EXPORT QRasterWindow : public QPaintDeviceWindow
Q_DECLARE_PRIVATE(QRasterWindow)
public:
- explicit QRasterWindow(QWindow *parent = 0);
+ explicit QRasterWindow(QWindow *parent = Q_NULLPTR);
protected:
int metric(PaintDeviceMetric metric) const Q_DECL_OVERRIDE;
diff --git a/src/gui/kernel/qscreen.cpp b/src/gui/kernel/qscreen.cpp
index 038be09dc7..b6b50372ae 100644
--- a/src/gui/kernel/qscreen.cpp
+++ b/src/gui/kernel/qscreen.cpp
@@ -36,7 +36,9 @@
#include "qpixmap.h"
#include "qguiapplication_p.h"
#include <qpa/qplatformscreen.h>
+#include <qpa/qplatformscreen_p.h>
+#include <QtCore/QDebug>
#include <QtCore/private/qobject_p.h>
QT_BEGIN_NAMESPACE
@@ -62,8 +64,33 @@ QT_BEGIN_NAMESPACE
*/
QScreen::QScreen(QPlatformScreen *screen)
- : QObject(*new QScreenPrivate(screen), 0)
+ : QObject(*new QScreenPrivate(), 0)
{
+ Q_D(QScreen);
+ d->setPlatformScreen(screen);
+}
+
+void QScreenPrivate::setPlatformScreen(QPlatformScreen *screen)
+{
+ Q_Q(QScreen);
+ platformScreen = screen;
+ platformScreen->d_func()->screen = q;
+ orientation = platformScreen->orientation();
+ geometry = platformScreen->deviceIndependentGeometry();
+ availableGeometry = QHighDpi::fromNative(platformScreen->availableGeometry(), QHighDpiScaling::factor(platformScreen), geometry.topLeft());
+ logicalDpi = platformScreen->logicalDpi();
+ refreshRate = platformScreen->refreshRate();
+ // safeguard ourselves against buggy platform behavior...
+ if (refreshRate < 1.0)
+ refreshRate = 60.0;
+
+ updatePrimaryOrientation();
+
+ filteredOrientation = orientation;
+ if (filteredOrientation == Qt::PrimaryOrientation)
+ filteredOrientation = primaryOrientation;
+
+ updateHighDpi();
}
@@ -207,6 +234,8 @@ qreal QScreen::physicalDotsPerInch() const
qreal QScreen::logicalDotsPerInchX() const
{
Q_D(const QScreen);
+ if (QHighDpiScaling::isActive())
+ return QHighDpiScaling::logicalDpi().first;
return d->logicalDpi.first;
}
@@ -221,6 +250,8 @@ qreal QScreen::logicalDotsPerInchX() const
qreal QScreen::logicalDotsPerInchY() const
{
Q_D(const QScreen);
+ if (QHighDpiScaling::isActive())
+ return QHighDpiScaling::logicalDpi().second;
return d->logicalDpi.second;
}
@@ -239,7 +270,7 @@ qreal QScreen::logicalDotsPerInchY() const
qreal QScreen::logicalDotsPerInch() const
{
Q_D(const QScreen);
- QDpi dpi = d->logicalDpi;
+ QDpi dpi = QHighDpiScaling::isActive() ? QHighDpiScaling::logicalDpi() : d->logicalDpi;
return (dpi.first + dpi.second) * qreal(0.5);
}
@@ -258,7 +289,7 @@ qreal QScreen::logicalDotsPerInch() const
qreal QScreen::devicePixelRatio() const
{
Q_D(const QScreen);
- return d->platformScreen->devicePixelRatio();
+ return d->platformScreen->devicePixelRatio() * QHighDpiScaling::factor(this);
}
/*!
@@ -328,6 +359,7 @@ QList<QScreen *> QScreen::virtualSiblings() const
Q_D(const QScreen);
QList<QPlatformScreen *> platformScreens = d->platformScreen->virtualSiblings();
QList<QScreen *> screens;
+ screens.reserve(platformScreens.count());
foreach (QPlatformScreen *platformScreen, platformScreens)
screens << platformScreen->screen();
return screens;
@@ -589,7 +621,7 @@ bool QScreen::isLandscape(Qt::ScreenOrientation o) const
\fn void QScreen::orientationChanged(Qt::ScreenOrientation orientation)
This signal is emitted when the orientation of the screen
- changes.
+ changes with \a orientation as an argument.
\sa orientation()
*/
@@ -598,7 +630,7 @@ bool QScreen::isLandscape(Qt::ScreenOrientation o) const
\fn void QScreen::primaryOrientationChanged(Qt::ScreenOrientation orientation)
This signal is emitted when the primary orientation of the screen
- changes.
+ changes with \a orientation as an argument.
\sa primaryOrientation()
*/
@@ -654,4 +686,41 @@ QPixmap QScreen::grabWindow(WId window, int x, int y, int width, int height)
return platformScreen->grabWindow(window, x, y, width, height);
}
+#ifndef QT_NO_DEBUG_STREAM
+
+static inline void formatRect(QDebug &debug, const QRect r)
+{
+ debug << r.width() << 'x' << r.height()
+ << forcesign << r.x() << r.y() << noforcesign;
+}
+
+Q_GUI_EXPORT QDebug operator<<(QDebug debug, const QScreen *screen)
+{
+ const QDebugStateSaver saver(debug);
+ debug.nospace();
+ debug << "QScreen(" << (const void *)screen;
+ if (screen) {
+ debug << ", name=" << screen->name();
+ if (debug.verbosity() > 2) {
+ if (screen == QGuiApplication::primaryScreen())
+ debug << ", primary";
+ debug << ", geometry=";
+ formatRect(debug, screen->geometry());
+ debug << ", available=";
+ formatRect(debug, screen->availableGeometry());
+ debug << ", logical DPI=" << screen->logicalDotsPerInchX()
+ << ',' << screen->logicalDotsPerInchY()
+ << ", physical DPI=" << screen->physicalDotsPerInchX()
+ << ',' << screen->physicalDotsPerInchY()
+ << ", devicePixelRatio=" << screen->devicePixelRatio()
+ << ", orientation=" << screen->orientation()
+ << ", physical size=" << screen->physicalSize().width()
+ << 'x' << screen->physicalSize().height() << "mm";
+ }
+ }
+ debug << ')';
+ return debug;
+}
+#endif // !QT_NO_DEBUG_STREAM
+
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qscreen.h b/src/gui/kernel/qscreen.h
index 255e735baf..a6018128e2 100644
--- a/src/gui/kernel/qscreen.h
+++ b/src/gui/kernel/qscreen.h
@@ -52,6 +52,9 @@ class QScreenPrivate;
class QWindow;
class QRect;
class QPixmap;
+#ifndef QT_NO_DEBUG_STREAM
+class QDebug;
+#endif
class Q_GUI_EXPORT QScreen : public QObject
{
@@ -151,8 +154,13 @@ private:
friend class QGuiApplicationPrivate;
friend class QPlatformIntegration;
friend class QPlatformScreen;
+ friend class QHighDpiScaling;
};
+#ifndef QT_NO_DEBUG_STREAM
+Q_GUI_EXPORT QDebug operator<<(QDebug, const QScreen *);
+#endif
+
QT_END_NAMESPACE
#endif // QSCREEN_H
diff --git a/src/gui/kernel/qscreen_p.h b/src/gui/kernel/qscreen_p.h
index d341b71932..4492eddd45 100644
--- a/src/gui/kernel/qscreen_p.h
+++ b/src/gui/kernel/qscreen_p.h
@@ -47,6 +47,7 @@
#include <QtGui/qscreen.h>
#include <qpa/qplatformscreen.h>
+#include "qhighdpiscaling_p.h"
#include <QtCore/private/qobject_p.h>
@@ -54,25 +55,19 @@ QT_BEGIN_NAMESPACE
class QScreenPrivate : public QObjectPrivate
{
+ Q_DECLARE_PUBLIC(QScreen)
public:
- QScreenPrivate(QPlatformScreen *screen)
- : platformScreen(screen)
+ QScreenPrivate()
+ : platformScreen(0)
, orientationUpdateMask(0)
{
- orientation = platformScreen->orientation();
- geometry = platformScreen->geometry();
- availableGeometry = platformScreen->availableGeometry();
- logicalDpi = platformScreen->logicalDpi();
- refreshRate = platformScreen->refreshRate();
- // safeguard ourselves against buggy platform behavior...
- if (refreshRate < 1.0)
- refreshRate = 60.0;
-
- updatePrimaryOrientation();
+ }
- filteredOrientation = orientation;
- if (filteredOrientation == Qt::PrimaryOrientation)
- filteredOrientation = primaryOrientation;
+ void setPlatformScreen(QPlatformScreen *screen);
+ void updateHighDpi()
+ {
+ geometry = platformScreen->deviceIndependentGeometry();
+ availableGeometry = QHighDpi::fromNative(platformScreen->availableGeometry(), QHighDpiScaling::factor(platformScreen), geometry.topLeft());
}
void updatePrimaryOrientation();
diff --git a/src/gui/kernel/qsimpledrag.cpp b/src/gui/kernel/qsimpledrag.cpp
index b850f53014..6e574d82e4 100644
--- a/src/gui/kernel/qsimpledrag.cpp
+++ b/src/gui/kernel/qsimpledrag.cpp
@@ -55,6 +55,7 @@
#include <private/qdnd_p.h>
#include <private/qshapedpixmapdndwindow_p.h>
+#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
@@ -106,6 +107,12 @@ void QBasicDrag::disableEventFilter()
qApp->removeEventFilter(this);
}
+
+static inline QPoint getNativeMousePos(QEvent *e, QObject *o)
+{
+ return QHighDpi::toNativePixels(static_cast<QMouseEvent *>(e)->globalPos(), qobject_cast<QWindow*>(o));
+}
+
bool QBasicDrag::eventFilter(QObject *o, QEvent *e)
{
Q_UNUSED(o);
@@ -139,19 +146,21 @@ bool QBasicDrag::eventFilter(QObject *o, QEvent *e)
}
case QEvent::MouseMove:
- move(static_cast<QMouseEvent *>(e));
+ {
+ QPoint nativePosition = getNativeMousePos(e, o);
+ move(nativePosition);
return true; // Eat all mouse events
-
+ }
case QEvent::MouseButtonRelease:
disableEventFilter();
if (canDrop()) {
- drop(static_cast<QMouseEvent *>(e));
+ QPoint nativePosition = getNativeMousePos(e, o);
+ drop(nativePosition);
} else {
cancel();
}
exitDndEventLoop();
return true; // Eat all mouse events
-
case QEvent::MouseButtonPress:
case QEvent::MouseButtonDblClick:
case QEvent::Wheel:
@@ -227,13 +236,18 @@ void QBasicDrag::cancel()
m_drag_icon_window->setVisible(false);
}
-void QBasicDrag::move(const QMouseEvent *e)
+/*!
+ Move the drag label to \a globalPos, which is
+ interpreted in device independent coordinates. Typically called from reimplementations of move().
+ */
+
+void QBasicDrag::moveShapedPixmapWindow(const QPoint &globalPos)
{
if (m_drag)
- m_drag_icon_window->updateGeometry(e->globalPos());
+ m_drag_icon_window->updateGeometry(globalPos);
}
-void QBasicDrag::drop(const QMouseEvent *)
+void QBasicDrag::drop(const QPoint &)
{
disableEventFilter();
restoreCursor();
@@ -330,14 +344,15 @@ void QSimpleDrag::cancel()
}
}
-void QSimpleDrag::move(const QMouseEvent *me)
+void QSimpleDrag::move(const QPoint &globalPos)
{
- QBasicDrag::move(me);
- QWindow *window = topLevelAt(me->globalPos());
+ //### not high-DPI aware
+ moveShapedPixmapWindow(globalPos);
+ QWindow *window = topLevelAt(globalPos);
if (!window)
return;
- const QPoint pos = me->globalPos() - window->geometry().topLeft();
+ const QPoint pos = globalPos - window->geometry().topLeft();
const QPlatformDragQtResponse qt_response =
QWindowSystemInterface::handleDrag(window, drag()->mimeData(), pos, drag()->supportedActions());
@@ -345,14 +360,16 @@ void QSimpleDrag::move(const QMouseEvent *me)
setCanDrop(qt_response.isAccepted());
}
-void QSimpleDrag::drop(const QMouseEvent *me)
+void QSimpleDrag::drop(const QPoint &globalPos)
{
- QBasicDrag::drop(me);
- QWindow *window = topLevelAt(me->globalPos());
+ //### not high-DPI aware
+
+ QBasicDrag::drop(globalPos);
+ QWindow *window = topLevelAt(globalPos);
if (!window)
return;
- const QPoint pos = me->globalPos() - window->geometry().topLeft();
+ const QPoint pos = globalPos - window->geometry().topLeft();
const QPlatformDropQtResponse response =
QWindowSystemInterface::handleDrop(window, drag()->mimeData(),pos, drag()->supportedActions());
if (response.isAccepted()) {
diff --git a/src/gui/kernel/qsimpledrag_p.h b/src/gui/kernel/qsimpledrag_p.h
index 7812f8b863..a011475381 100644
--- a/src/gui/kernel/qsimpledrag_p.h
+++ b/src/gui/kernel/qsimpledrag_p.h
@@ -73,10 +73,12 @@ protected:
virtual void startDrag();
virtual void cancel();
- virtual void move(const QMouseEvent *me);
- virtual void drop(const QMouseEvent *me);
+ virtual void move(const QPoint &globalPos) = 0;
+ virtual void drop(const QPoint &globalPos) = 0;
virtual void endDrag();
+
+ void moveShapedPixmapWindow(const QPoint &deviceIndependentPosition);
QShapedPixmapWindow *shapedPixmapWindow() const { return m_drag_icon_window; }
void updateCursor(Qt::DropAction action);
@@ -111,8 +113,8 @@ public:
protected:
virtual void startDrag() Q_DECL_OVERRIDE;
virtual void cancel() Q_DECL_OVERRIDE;
- virtual void move(const QMouseEvent *me) Q_DECL_OVERRIDE;
- virtual void drop(const QMouseEvent *me) Q_DECL_OVERRIDE;
+ virtual void move(const QPoint &globalPos) Q_DECL_OVERRIDE;
+ virtual void drop(const QPoint &globalPos) Q_DECL_OVERRIDE;
private:
QWindow *m_current_window;
diff --git a/src/gui/kernel/qtouchdevice.cpp b/src/gui/kernel/qtouchdevice.cpp
index 1a6e9deba8..9d19fa4b92 100644
--- a/src/gui/kernel/qtouchdevice.cpp
+++ b/src/gui/kernel/qtouchdevice.cpp
@@ -195,7 +195,7 @@ void QTouchDevice::setName(const QString &name)
d->name = name;
}
-typedef QList<QTouchDevice *> TouchDevices;
+typedef QList<const QTouchDevice *> TouchDevices;
Q_GLOBAL_STATIC(TouchDevices, deviceList)
static QBasicMutex devicesMutex;
@@ -214,26 +214,22 @@ static void cleanupDevicesList()
QList<const QTouchDevice *> QTouchDevice::devices()
{
QMutexLocker lock(&devicesMutex);
- QList<QTouchDevice *> *devList = deviceList();
- QList<const QTouchDevice *> constDevList;
- for (int i = 0, count = devList->count(); i != count; ++i)
- constDevList.append(devList->at(i));
- return constDevList;
+ return *deviceList();
}
/*!
\internal
*/
-bool QTouchDevicePrivate::isRegistered(QTouchDevice *dev)
+bool QTouchDevicePrivate::isRegistered(const QTouchDevice *dev)
{
- QMutexLocker lock(&devicesMutex);
+ QMutexLocker locker(&devicesMutex);
return deviceList()->contains(dev);
}
/*!
\internal
*/
-void QTouchDevicePrivate::registerDevice(QTouchDevice *dev)
+void QTouchDevicePrivate::registerDevice(const QTouchDevice *dev)
{
QMutexLocker lock(&devicesMutex);
if (deviceList()->isEmpty())
diff --git a/src/gui/kernel/qtouchdevice_p.h b/src/gui/kernel/qtouchdevice_p.h
index 9c0bcf3414..4aff8f2f33 100644
--- a/src/gui/kernel/qtouchdevice_p.h
+++ b/src/gui/kernel/qtouchdevice_p.h
@@ -45,7 +45,6 @@
// We mean it.
//
-#include <QtCore/qobject.h>
#include <QtGui/qtouchdevice.h>
QT_BEGIN_NAMESPACE
@@ -65,8 +64,8 @@ public:
QString name;
int maxTouchPoints;
- static void registerDevice(QTouchDevice *dev);
- static bool isRegistered(QTouchDevice *dev);
+ static void registerDevice(const QTouchDevice *dev);
+ static bool isRegistered(const QTouchDevice *dev);
};
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qwindow.cpp b/src/gui/kernel/qwindow.cpp
index b54e85a1d3..89bd119564 100644
--- a/src/gui/kernel/qwindow.cpp
+++ b/src/gui/kernel/qwindow.cpp
@@ -47,6 +47,7 @@
#ifndef QT_NO_ACCESSIBILITY
# include "qaccessible.h"
#endif
+#include "qhighdpiscaling_p.h"
#include <private/qevent_p.h>
@@ -1085,13 +1086,13 @@ qreal QWindow::devicePixelRatio() const
{
Q_D(const QWindow);
- // If there is no platform window, do the second best thing and
- // return the app global devicePixelRatio. This is the highest
- // devicePixelRatio found on the system screens, and will be
- // correct for single-display systems (a very common case).
+ // If there is no platform window use the app global devicePixelRatio,
+ // which is the the highest devicePixelRatio found on the system
+ // screens, and will be correct for single-display systems (a very common case).
if (!d->platformWindow)
return qApp->devicePixelRatio();
- return d->platformWindow->devicePixelRatio();
+
+ return d->platformWindow->devicePixelRatio() * QHighDpiScaling::factor(this);
}
/*!
@@ -1431,7 +1432,13 @@ void QWindow::setGeometry(const QRect &rect)
d->positionPolicy = QWindowPrivate::WindowFrameExclusive;
if (d->platformWindow) {
- d->platformWindow->setGeometry(rect);
+ QRect nativeRect;
+ QScreen *newScreen = d->screenForGeometry(rect);
+ if (newScreen && isTopLevel())
+ nativeRect = QHighDpi::toNativePixels(rect, newScreen);
+ else
+ nativeRect = QHighDpi::toNativePixels(rect, this);
+ d->platformWindow->setGeometry(nativeRect);
} else {
d->geometry = rect;
@@ -1446,6 +1453,30 @@ void QWindow::setGeometry(const QRect &rect)
}
}
+/*
+ This is equivalent to QPlatformWindow::screenForGeometry, but in platform
+ independent coordinates. The duplication is unfortunate, but there is a
+ chicken and egg problem here: we cannot convert to native coordinates
+ before we know which screen we are on.
+*/
+QScreen *QWindowPrivate::screenForGeometry(const QRect &newGeometry)
+{
+ Q_Q(QWindow);
+ QScreen *currentScreen = q->screen();
+ QScreen *fallback = currentScreen;
+ QPoint center = newGeometry.center();
+ if (!q->parent() && currentScreen && !currentScreen->geometry().contains(center)) {
+ Q_FOREACH (QScreen* screen, currentScreen->virtualSiblings()) {
+ if (screen->geometry().contains(center))
+ return screen;
+ if (screen->geometry().intersects(newGeometry))
+ fallback = screen;
+ }
+ }
+ return fallback;
+}
+
+
/*!
Returns the geometry of the window, excluding its window frame.
@@ -1455,7 +1486,7 @@ QRect QWindow::geometry() const
{
Q_D(const QWindow);
if (d->platformWindow)
- return d->platformWindow->geometry();
+ return QHighDpi::fromNativePixels(d->platformWindow->geometry(), this);
return d->geometry;
}
@@ -1468,7 +1499,7 @@ QMargins QWindow::frameMargins() const
{
Q_D(const QWindow);
if (d->platformWindow)
- return d->platformWindow->frameMargins();
+ return QHighDpi::fromNativePixels(d->platformWindow->frameMargins(), this);
return QMargins();
}
@@ -1482,7 +1513,7 @@ QRect QWindow::frameGeometry() const
Q_D(const QWindow);
if (d->platformWindow) {
QMargins m = frameMargins();
- return d->platformWindow->geometry().adjusted(-m.left(), -m.top(), m.right(), m.bottom());
+ return QHighDpi::fromNativePixels(d->platformWindow->geometry(), this).adjusted(-m.left(), -m.top(), m.right(), m.bottom());
}
return d->geometry;
}
@@ -1499,7 +1530,7 @@ QPoint QWindow::framePosition() const
Q_D(const QWindow);
if (d->platformWindow) {
QMargins margins = frameMargins();
- return d->platformWindow->geometry().topLeft() - QPoint(margins.left(), margins.top());
+ return QHighDpi::fromNativePixels(d->platformWindow->geometry().topLeft(), this) - QPoint(margins.left(), margins.top());
}
return d->geometry.topLeft();
}
@@ -1515,7 +1546,7 @@ void QWindow::setFramePosition(const QPoint &point)
d->positionPolicy = QWindowPrivate::WindowFrameInclusive;
d->positionAutomatic = false;
if (d->platformWindow) {
- d->platformWindow->setGeometry(QRect(point, size()));
+ d->platformWindow->setGeometry(QHighDpi::toNativePixels(QRect(point, size()), this));
} else {
d->geometry.moveTopLeft(point);
}
@@ -1575,7 +1606,7 @@ void QWindow::resize(const QSize &newSize)
{
Q_D(QWindow);
if (d->platformWindow) {
- d->platformWindow->setGeometry(QRect(position(), newSize));
+ d->platformWindow->setGeometry(QHighDpi::toNativePixels(QRect(position(), newSize), this));
} else {
const QSize oldSize = d->geometry.size();
d->geometry.setSize(newSize);
@@ -2471,6 +2502,45 @@ void QWindowPrivate::applyCursor()
}
#endif // QT_NO_CURSOR
+#ifndef QT_NO_DEBUG_STREAM
+QDebug operator<<(QDebug debug, const QWindow *window)
+{
+ QDebugStateSaver saver(debug);
+ debug.nospace();
+ if (window) {
+ debug << window->metaObject()->className() << '(' << (const void *)window;
+ if (!window->objectName().isEmpty())
+ debug << ", name=" << window->objectName();
+ if (debug.verbosity() > 2) {
+ const QRect geometry = window->geometry();
+ if (window->isVisible())
+ debug << ", visible";
+ if (window->isExposed())
+ debug << ", exposed";
+ debug << ", state=" << window->windowState()
+ << ", type=" << window->type() << ", flags=" << window->flags()
+ << ", surface type=" << window->surfaceType();
+ if (window->isTopLevel())
+ debug << ", toplevel";
+ debug << ", " << geometry.width() << 'x' << geometry.height()
+ << forcesign << geometry.x() << geometry.y() << noforcesign;
+ const QMargins margins = window->frameMargins();
+ if (!margins.isNull())
+ debug << ", margins=" << margins;
+ debug << ", devicePixelRatio=" << window->devicePixelRatio();
+ if (const QPlatformWindow *platformWindow = window->handle())
+ debug << ", winId=0x" << hex << platformWindow->winId() << dec;
+ if (const QScreen *screen = window->screen())
+ debug << ", on " << screen->name();
+ }
+ debug << ')';
+ } else {
+ debug << "QWindow(0x0)";
+ }
+ return debug;
+}
+#endif // !QT_NO_DEBUG_STREAM
+
QT_END_NAMESPACE
#include "moc_qwindow.cpp"
diff --git a/src/gui/kernel/qwindow.h b/src/gui/kernel/qwindow.h
index f9fe37718c..b29e7aaae7 100644
--- a/src/gui/kernel/qwindow.h
+++ b/src/gui/kernel/qwindow.h
@@ -78,6 +78,9 @@ class QBackingStore;
class QScreen;
class QAccessibleInterface;
class QWindowContainer;
+#ifndef QT_NO_DEBUG_STREAM
+class QDebug;
+#endif
class Q_GUI_EXPORT QWindow : public QObject, public QSurface
{
@@ -122,7 +125,7 @@ public:
};
Q_ENUM(Visibility)
- explicit QWindow(QScreen *screen = 0);
+ explicit QWindow(QScreen *screen = Q_NULLPTR);
explicit QWindow(QWindow *parent);
virtual ~QWindow();
@@ -357,16 +360,20 @@ private:
#ifndef Q_QDOC
template <> inline QWindow *qobject_cast<QWindow*>(QObject *o)
{
- if (!o || !o->isWindowType()) return 0;
+ if (!o || !o->isWindowType()) return Q_NULLPTR;
return static_cast<QWindow*>(o);
}
template <> inline const QWindow *qobject_cast<const QWindow*>(const QObject *o)
{
- if (!o || !o->isWindowType()) return 0;
+ if (!o || !o->isWindowType()) return Q_NULLPTR;
return static_cast<const QWindow*>(o);
}
#endif // !Q_QDOC
+#ifndef QT_NO_DEBUG_STREAM
+Q_GUI_EXPORT QDebug operator<<(QDebug, const QWindow *);
+#endif
+
QT_END_NAMESPACE
#endif // QWINDOW_H
diff --git a/src/gui/kernel/qwindow_p.h b/src/gui/kernel/qwindow_p.h
index 4fc63acf28..23a6d800c0 100644
--- a/src/gui/kernel/qwindow_p.h
+++ b/src/gui/kernel/qwindow_p.h
@@ -136,6 +136,7 @@ public:
void connectToScreen(QScreen *topLevelScreen);
void disconnectFromScreen();
void emitScreenChangedRecursion(QScreen *newScreen);
+ QScreen *screenForGeometry(const QRect &rect);
virtual void clearFocusObject();
virtual QRectF closestAcceptableGeometry(const QRectF &rect) const;
diff --git a/src/gui/kernel/qwindowsysteminterface.cpp b/src/gui/kernel/qwindowsysteminterface.cpp
index 9a9eab2fe7..88cf2dac93 100644
--- a/src/gui/kernel/qwindowsysteminterface.cpp
+++ b/src/gui/kernel/qwindowsysteminterface.cpp
@@ -40,14 +40,16 @@
#include <qpa/qplatformdrag.h>
#include <qpa/qplatformintegration.h>
#include <qdebug.h>
+#include "qhighdpiscaling_p.h"
QT_BEGIN_NAMESPACE
QElapsedTimer QWindowSystemInterfacePrivate::eventTime;
-bool QWindowSystemInterfacePrivate::synchronousWindowsSystemEvents = false;
+bool QWindowSystemInterfacePrivate::synchronousWindowSystemEvents = false;
QWaitCondition QWindowSystemInterfacePrivate::eventsFlushed;
QMutex QWindowSystemInterfacePrivate::flushEventMutex;
+QWindowSystemEventHandler *QWindowSystemInterfacePrivate::eventHandler;
//------------------------------------------------------------
//
@@ -93,14 +95,14 @@ void QWindowSystemInterface::handleLeaveEvent(QWindow *tlw)
*/
void QWindowSystemInterface::handleEnterLeaveEvent(QWindow *enter, QWindow *leave, const QPointF &local, const QPointF& global)
{
- bool wasSynchronous = QWindowSystemInterfacePrivate::synchronousWindowsSystemEvents;
+ bool wasSynchronous = QWindowSystemInterfacePrivate::synchronousWindowSystemEvents;
if (wasSynchronous)
- setSynchronousWindowsSystemEvents(false);
+ setSynchronousWindowSystemEvents(false);
handleLeaveEvent(leave);
handleEnterEvent(enter, local, global);
if (wasSynchronous) {
flushWindowSystemEvents();
- setSynchronousWindowsSystemEvents(true);
+ setSynchronousWindowSystemEvents(true);
}
}
@@ -138,7 +140,7 @@ void QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState
*/
void QWindowSystemInterface::handleGeometryChange(QWindow *tlw, const QRect &newRect, const QRect &oldRect)
{
- QWindowSystemInterfacePrivate::GeometryChangeEvent *e = new QWindowSystemInterfacePrivate::GeometryChangeEvent(tlw,newRect, oldRect);
+ QWindowSystemInterfacePrivate::GeometryChangeEvent *e = new QWindowSystemInterfacePrivate::GeometryChangeEvent(tlw, QHighDpi::fromNativePixels(newRect, tlw), QHighDpi::fromNativePixels(oldRect, tlw));
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -167,7 +169,7 @@ void QWindowSystemInterface::handleMouseEvent(QWindow *w, ulong timestamp, const
Qt::KeyboardModifiers mods, Qt::MouseEventSource source)
{
QWindowSystemInterfacePrivate::MouseEvent * e =
- new QWindowSystemInterfacePrivate::MouseEvent(w, timestamp, local, global, b, mods, source);
+ new QWindowSystemInterfacePrivate::MouseEvent(w, timestamp, QHighDpi::fromNativeLocalPosition(local, w), QHighDpi::fromNativePixels(global, w), b, mods, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -184,7 +186,7 @@ void QWindowSystemInterface::handleFrameStrutMouseEvent(QWindow *w, ulong timest
QWindowSystemInterfacePrivate::MouseEvent * e =
new QWindowSystemInterfacePrivate::MouseEvent(w, timestamp,
QWindowSystemInterfacePrivate::FrameStrutMouse,
- local, global, b, mods, source);
+ QHighDpi::fromNativeLocalPosition(local, w), QHighDpi::fromNativePixels(global, w), b, mods, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -301,24 +303,24 @@ bool QWindowSystemInterface::tryHandleExtendedShortcutEvent(QWindow *w, ulong ti
}
-void QWindowSystemInterface::handleKeyEvent(QWindow *w, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text, bool autorep, ushort count) {
+bool QWindowSystemInterface::handleKeyEvent(QWindow *w, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text, bool autorep, ushort count) {
unsigned long time = QWindowSystemInterfacePrivate::eventTime.elapsed();
- handleKeyEvent(w, time, t, k, mods, text, autorep, count);
+ return handleKeyEvent(w, time, t, k, mods, text, autorep, count);
}
-void QWindowSystemInterface::handleKeyEvent(QWindow *tlw, ulong timestamp, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text, bool autorep, ushort count)
+bool QWindowSystemInterface::handleKeyEvent(QWindow *tlw, ulong timestamp, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text, bool autorep, ushort count)
{
// This is special handling needed for OS X which eventually will call sendEvent(), on other platforms
// this might not be safe, e.g., on Android. See: QGuiApplicationPrivate::processKeyEvent() for
// shortcut overriding on other platforms.
#if defined(Q_OS_OSX)
if (t == QEvent::KeyPress && QWindowSystemInterface::tryHandleShortcutEvent(tlw, timestamp, k, mods, text))
- return;
+ return true;
#endif // Q_OS_OSX
QWindowSystemInterfacePrivate::KeyEvent * e =
new QWindowSystemInterfacePrivate::KeyEvent(tlw, timestamp, t, k, mods, text, autorep, count);
- QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
+ return QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
void QWindowSystemInterface::handleExtendedKeyEvent(QWindow *w, QEvent::Type type, int key, Qt::KeyboardModifiers modifiers,
@@ -381,14 +383,14 @@ void QWindowSystemInterface::handleWheelEvent(QWindow *tlw, ulong timestamp, con
// Simple case: vertical deltas only:
if (angleDelta.y() != 0 && angleDelta.x() == 0) {
- e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, local, global, pixelDelta, angleDelta, angleDelta.y(), Qt::Vertical, mods, phase, source);
+ e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, QHighDpi::fromNativeLocalPosition(local, tlw), QHighDpi::fromNativePixels(global, tlw), pixelDelta, angleDelta, angleDelta.y(), Qt::Vertical, mods, phase, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
return;
}
// Simple case: horizontal deltas only:
if (angleDelta.y() == 0 && angleDelta.x() != 0) {
- e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, local, global, pixelDelta, angleDelta, angleDelta.x(), Qt::Horizontal, mods, phase, source);
+ e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, QHighDpi::fromNativeLocalPosition(local, tlw), QHighDpi::fromNativePixels(global, tlw), pixelDelta, angleDelta, angleDelta.x(), Qt::Horizontal, mods, phase, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
return;
}
@@ -396,12 +398,12 @@ void QWindowSystemInterface::handleWheelEvent(QWindow *tlw, ulong timestamp, con
// Both horizontal and vertical deltas: Send two wheel events.
// The first event contains the Qt 5 pixel and angle delta as points,
// and in addition the Qt 4 compatibility vertical angle delta.
- e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, local, global, pixelDelta, angleDelta, angleDelta.y(), Qt::Vertical, mods, phase, source);
+ e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, QHighDpi::fromNativeLocalPosition(local, tlw), QHighDpi::fromNativePixels(global, tlw), pixelDelta, angleDelta, angleDelta.y(), Qt::Vertical, mods, phase, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
// The second event contains null pixel and angle points and the
// Qt 4 compatibility horizontal angle delta.
- e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, local, global, QPoint(), QPoint(), angleDelta.x(), Qt::Horizontal, mods, phase, source);
+ e = new QWindowSystemInterfacePrivate::WheelEvent(tlw, timestamp, QHighDpi::fromNativeLocalPosition(local, tlw), QHighDpi::fromNativePixels(global, tlw), QPoint(), QPoint(), angleDelta.x(), Qt::Horizontal, mods, phase, source);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -439,16 +441,20 @@ void QWindowSystemInterfacePrivate::removeWindowSystemEvent(WindowSystemEvent *e
windowSystemEventQueue.remove(event);
}
-void QWindowSystemInterfacePrivate::handleWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *ev)
+bool QWindowSystemInterfacePrivate::handleWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *ev)
{
- if (synchronousWindowsSystemEvents) {
+ bool accepted = true;
+ if (synchronousWindowSystemEvents) {
QGuiApplicationPrivate::processWindowSystemEvent(ev);
+ accepted = ev->eventAccepted;
+ delete ev;
} else {
windowSystemEventQueue.append(ev);
QAbstractEventDispatcher *dispatcher = QGuiApplicationPrivate::qt_qpa_core_dispatcher();
if (dispatcher)
dispatcher->wakeUp();
}
+ return accepted;
}
void QWindowSystemInterface::registerTouchDevice(QTouchDevice *device)
@@ -463,12 +469,16 @@ void QWindowSystemInterface::handleTouchEvent(QWindow *w, QTouchDevice *device,
handleTouchEvent(w, time, device, points, mods);
}
-QList<QTouchEvent::TouchPoint> QWindowSystemInterfacePrivate::convertTouchPoints(const QList<QWindowSystemInterface::TouchPoint> &points, QEvent::Type *type)
+QList<QTouchEvent::TouchPoint>
+ QWindowSystemInterfacePrivate::fromNativeTouchPoints(const QList<QWindowSystemInterface::TouchPoint> &points,
+ const QWindow *window,
+ QEvent::Type *type)
{
QList<QTouchEvent::TouchPoint> touchPoints;
Qt::TouchPointStates states;
QTouchEvent::TouchPoint p;
+ touchPoints.reserve(points.count());
QList<QWindowSystemInterface::TouchPoint>::const_iterator point = points.constBegin();
QList<QWindowSystemInterface::TouchPoint>::const_iterator end = points.constEnd();
while (point != end) {
@@ -478,16 +488,16 @@ QList<QTouchEvent::TouchPoint> QWindowSystemInterfacePrivate::convertTouchPoints
p.setState(point->state);
const QPointF screenPos = point->area.center();
- p.setScreenPos(screenPos);
- p.setScreenRect(point->area);
+ p.setScreenPos(QHighDpi::fromNativePixels(screenPos, window));
+ p.setScreenRect(QHighDpi::fromNativePixels(point->area, window));
// The local pos and rect are not set, they will be calculated
// when the event gets processed by QGuiApplication.
- p.setNormalizedPos(point->normalPosition);
- p.setVelocity(point->velocity);
+ p.setNormalizedPos(QHighDpi::fromNativePixels(point->normalPosition, window));
+ p.setVelocity(QHighDpi::fromNativePixels(point->velocity, window));
p.setFlags(point->flags);
- p.setRawScreenPositions(point->rawPositions);
+ p.setRawScreenPositions(QHighDpi::fromNativePixels(point->rawPositions, window));
touchPoints.append(p);
++point;
@@ -505,6 +515,27 @@ QList<QTouchEvent::TouchPoint> QWindowSystemInterfacePrivate::convertTouchPoints
return touchPoints;
}
+QList<QWindowSystemInterface::TouchPoint>
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(const QList<QTouchEvent::TouchPoint>& pointList,
+ const QWindow *window)
+{
+ QList<QWindowSystemInterface::TouchPoint> newList;
+ newList.reserve(pointList.size());
+ foreach (const QTouchEvent::TouchPoint &pt, pointList) {
+ QWindowSystemInterface::TouchPoint p;
+ p.id = pt.id();
+ p.flags = pt.flags();
+ p.normalPosition = QHighDpi::toNativeLocalPosition(pt.normalizedPos(), window);
+ p.area = QHighDpi::toNativePixels(pt.screenRect(), window);
+ p.pressure = pt.pressure();
+ p.state = pt.state();
+ p.velocity = pt.velocity();
+ p.rawPositions = pt.rawScreenPositions();
+ newList.append(p);
+ }
+ return newList;
+}
+
void QWindowSystemInterface::handleTouchEvent(QWindow *tlw, ulong timestamp, QTouchDevice *device,
const QList<TouchPoint> &points, Qt::KeyboardModifiers mods)
{
@@ -515,7 +546,7 @@ void QWindowSystemInterface::handleTouchEvent(QWindow *tlw, ulong timestamp, QTo
return;
QEvent::Type type;
- QList<QTouchEvent::TouchPoint> touchPoints = QWindowSystemInterfacePrivate::convertTouchPoints(points, &type);
+ QList<QTouchEvent::TouchPoint> touchPoints = QWindowSystemInterfacePrivate::fromNativeTouchPoints(points, tlw, &type);
QWindowSystemInterfacePrivate::TouchEvent *e =
new QWindowSystemInterfacePrivate::TouchEvent(tlw, timestamp, type, device, touchPoints, mods);
@@ -548,14 +579,14 @@ void QWindowSystemInterface::handleScreenOrientationChange(QScreen *screen, Qt::
void QWindowSystemInterface::handleScreenGeometryChange(QScreen *screen, const QRect &geometry, const QRect &availableGeometry)
{
QWindowSystemInterfacePrivate::ScreenGeometryEvent *e =
- new QWindowSystemInterfacePrivate::ScreenGeometryEvent(screen, geometry, availableGeometry);
+ new QWindowSystemInterfacePrivate::ScreenGeometryEvent(screen, QHighDpi::fromNativeScreenGeometry(geometry, screen), QHighDpi::fromNative(availableGeometry, screen, geometry.topLeft()));
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
void QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(QScreen *screen, qreal dpiX, qreal dpiY)
{
QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInchEvent *e =
- new QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInchEvent(screen, dpiX, dpiY);
+ new QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInchEvent(screen, dpiX, dpiY); // ### tja
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -574,7 +605,7 @@ void QWindowSystemInterface::handleThemeChange(QWindow *tlw)
void QWindowSystemInterface::handleExposeEvent(QWindow *tlw, const QRegion &region)
{
- QWindowSystemInterfacePrivate::ExposeEvent *e = new QWindowSystemInterfacePrivate::ExposeEvent(tlw, region);
+ QWindowSystemInterfacePrivate::ExposeEvent *e = new QWindowSystemInterfacePrivate::ExposeEvent(tlw, QHighDpi::fromNativeLocalRegion(region, tlw));
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -583,7 +614,7 @@ void QWindowSystemInterface::deferredFlushWindowSystemEvents(QEventLoop::Process
Q_ASSERT(QThread::currentThread() == QGuiApplication::instance()->thread());
QMutexLocker locker(&QWindowSystemInterfacePrivate::flushEventMutex);
- flushWindowSystemEvents(flags);
+ sendWindowSystemEvents(flags);
QWindowSystemInterfacePrivate::eventsFlushed.wakeOne();
}
@@ -620,17 +651,35 @@ bool QWindowSystemInterface::sendWindowSystemEvents(QEventLoop::ProcessEventsFla
QWindowSystemInterfacePrivate::getWindowSystemEvent();
if (!event)
break;
- nevents++;
- QGuiApplicationPrivate::processWindowSystemEvent(event);
+
+ if (QWindowSystemInterfacePrivate::eventHandler) {
+ if (QWindowSystemInterfacePrivate::eventHandler->sendEvent(event))
+ nevents++;
+ } else {
+ nevents++;
+ QGuiApplicationPrivate::processWindowSystemEvent(event);
+ }
delete event;
}
return (nevents > 0);
}
-void QWindowSystemInterface::setSynchronousWindowsSystemEvents(bool enable)
+void QWindowSystemInterfacePrivate::installWindowSystemEventHandler(QWindowSystemEventHandler *handler)
+{
+ if (!eventHandler)
+ eventHandler = handler;
+}
+
+void QWindowSystemInterfacePrivate::removeWindowSystemEventhandler(QWindowSystemEventHandler *handler)
+{
+ if (eventHandler == handler)
+ eventHandler = 0;
+}
+
+void QWindowSystemInterface::setSynchronousWindowSystemEvents(bool enable)
{
- QWindowSystemInterfacePrivate::synchronousWindowsSystemEvents = enable;
+ QWindowSystemInterfacePrivate::synchronousWindowSystemEvents = enable;
}
int QWindowSystemInterface::windowSystemEventsQueued()
@@ -641,12 +690,12 @@ int QWindowSystemInterface::windowSystemEventsQueued()
#ifndef QT_NO_DRAGANDDROP
QPlatformDragQtResponse QWindowSystemInterface::handleDrag(QWindow *w, const QMimeData *dropData, const QPoint &p, Qt::DropActions supportedActions)
{
- return QGuiApplicationPrivate::processDrag(w, dropData, p,supportedActions);
+ return QGuiApplicationPrivate::processDrag(w, dropData, QHighDpi::fromNativeLocalPosition(p, w) ,supportedActions);
}
QPlatformDropQtResponse QWindowSystemInterface::handleDrop(QWindow *w, const QMimeData *dropData, const QPoint &p, Qt::DropActions supportedActions)
{
- return QGuiApplicationPrivate::processDrop(w, dropData, p,supportedActions);
+ return QGuiApplicationPrivate::processDrop(w, dropData, QHighDpi::fromNativeLocalPosition(p, w),supportedActions);
}
#endif // QT_NO_DRAGANDDROP
@@ -680,8 +729,11 @@ void QWindowSystemInterface::handleTabletEvent(QWindow *w, ulong timestamp, cons
Qt::KeyboardModifiers modifiers)
{
QWindowSystemInterfacePrivate::TabletEvent *e =
- new QWindowSystemInterfacePrivate::TabletEvent(w, timestamp, local, global, device, pointerType, buttons, pressure,
- xTilt, yTilt, tangentialPressure, rotation, z, uid, modifiers);
+ new QWindowSystemInterfacePrivate::TabletEvent(w,timestamp,
+ QHighDpi::fromNativeLocalPosition(local, w),
+ QHighDpi::fromNativePixels(global, w),
+ device, pointerType, buttons, pressure,
+ xTilt, yTilt, tangentialPressure, rotation, z, uid, modifiers);
QWindowSystemInterfacePrivate::handleWindowSystemEvent(e);
}
@@ -806,13 +858,26 @@ Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QWindowSystemInterface::TouchPo
}
#endif
-Q_GUI_EXPORT void qt_handleMouseEvent(QWindow *w, const QPointF & local, const QPointF & global, Qt::MouseButtons b, Qt::KeyboardModifiers mods = Qt::NoModifier) {
- QWindowSystemInterface::handleMouseEvent(w, local, global, b, mods);
+Q_GUI_EXPORT void qt_handleMouseEvent(QWindow *w, const QPointF &local, const QPointF &global, Qt::MouseButtons b, Qt::KeyboardModifiers mods, int timestamp)
+{
+ QWindowSystemInterfacePrivate::MouseEvent e(w, timestamp, local, global, b, mods, Qt::MouseEventNotSynthesized);
+ QGuiApplicationPrivate::processWindowSystemEvent(&e);
}
Q_GUI_EXPORT void qt_handleKeyEvent(QWindow *w, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text = QString(), bool autorep = false, ushort count = 1)
{
- QWindowSystemInterface::handleKeyEvent(w, t, k, mods, text, autorep, count);
+ unsigned long timestamp = QWindowSystemInterfacePrivate::eventTime.elapsed();
+
+ // This is special handling needed for OS X which eventually will call sendEvent(), on other platforms
+ // this might not be safe, e.g., on Android. See: QGuiApplicationPrivate::processKeyEvent() for
+ // shortcut overriding on other platforms.
+#if defined(Q_OS_OSX)
+ if (t == QEvent::KeyPress && QWindowSystemInterface::tryHandleShortcutEvent(w, timestamp, k, mods, text))
+ return;
+#endif // Q_OS_OSX
+
+ QWindowSystemInterfacePrivate::KeyEvent e(w, timestamp, t, k, mods, text, autorep, count);
+ QGuiApplicationPrivate::processWindowSystemEvent(&e);
}
Q_GUI_EXPORT bool qt_sendShortcutOverrideEvent(QObject *o, ulong timestamp, int k, Qt::KeyboardModifiers mods, const QString &text = QString(), bool autorep = false, ushort count = 1)
@@ -820,35 +885,49 @@ Q_GUI_EXPORT bool qt_sendShortcutOverrideEvent(QObject *o, ulong timestamp, int
return QWindowSystemInterface::tryHandleShortcutEventToObject(o, timestamp, k, mods, text, autorep, count);
}
-static QWindowSystemInterface::TouchPoint touchPoint(const QTouchEvent::TouchPoint& pt)
-{
- QWindowSystemInterface::TouchPoint p;
- p.id = pt.id();
- p.flags = pt.flags();
- p.normalPosition = pt.normalizedPos();
- p.area = pt.screenRect();
- p.pressure = pt.pressure();
- p.state = pt.state();
- p.velocity = pt.velocity();
- p.rawPositions = pt.rawScreenPositions();
- return p;
-}
-static QList<struct QWindowSystemInterface::TouchPoint> touchPointList(const QList<QTouchEvent::TouchPoint>& pointList)
+Q_GUI_EXPORT void qt_handleTouchEvent(QWindow *w, QTouchDevice *device,
+ const QList<QTouchEvent::TouchPoint> &points,
+ Qt::KeyboardModifiers mods = Qt::NoModifier)
{
- QList<struct QWindowSystemInterface::TouchPoint> newList;
+ unsigned long timestamp = QWindowSystemInterfacePrivate::eventTime.elapsed();
+
+ if (!points.size()) // Touch events must have at least one point
+ return;
+
+ if (!QTouchDevicePrivate::isRegistered(device)) // Disallow passing bogus, non-registered devices.
+ return;
+
+ QEvent::Type type;
+ Qt::TouchPointStates states;
- Q_FOREACH (QTouchEvent::TouchPoint p, pointList)
- {
- newList.append(touchPoint(p));
+ QList<QTouchEvent::TouchPoint>::const_iterator point = points.constBegin();
+ QList<QTouchEvent::TouchPoint>::const_iterator end = points.constEnd();
+ while (point != end) {
+ states |= point->state();
+ ++point;
}
- return newList;
+
+ // Determine the event type based on the combined point states.
+ type = QEvent::TouchUpdate;
+ if (states == Qt::TouchPointPressed)
+ type = QEvent::TouchBegin;
+ else if (states == Qt::TouchPointReleased)
+ type = QEvent::TouchEnd;
+
+ QWindowSystemInterfacePrivate::TouchEvent e(w, timestamp, type, device, points, mods);
+ QGuiApplicationPrivate::processWindowSystemEvent(&e);
}
-Q_GUI_EXPORT void qt_handleTouchEvent(QWindow *w, QTouchDevice *device,
- const QList<QTouchEvent::TouchPoint> &points,
- Qt::KeyboardModifiers mods = Qt::NoModifier)
+QWindowSystemEventHandler::~QWindowSystemEventHandler()
+{
+ QWindowSystemInterfacePrivate::removeWindowSystemEventhandler(this);
+}
+
+bool QWindowSystemEventHandler::sendEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *e)
{
- QWindowSystemInterface::handleTouchEvent(w, device, touchPointList(points), mods);
+ QGuiApplicationPrivate::processWindowSystemEvent(e);
+ return true;
}
+
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qwindowsysteminterface.h b/src/gui/kernel/qwindowsysteminterface.h
index 448c5d0893..ace1a4fe24 100644
--- a/src/gui/kernel/qwindowsysteminterface.h
+++ b/src/gui/kernel/qwindowsysteminterface.h
@@ -95,8 +95,8 @@ public:
quint32 nativeScanCode, quint32 nativeVirtualKey, quint32 nativeModifiers,
const QString & text = QString(), bool autorep = false, ushort count = 1);
- static void handleKeyEvent(QWindow *w, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text = QString(), bool autorep = false, ushort count = 1);
- static void handleKeyEvent(QWindow *w, ulong timestamp, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text = QString(), bool autorep = false, ushort count = 1);
+ static bool handleKeyEvent(QWindow *w, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text = QString(), bool autorep = false, ushort count = 1);
+ static bool handleKeyEvent(QWindow *w, ulong timestamp, QEvent::Type t, int k, Qt::KeyboardModifiers mods, const QString & text = QString(), bool autorep = false, ushort count = 1);
static void handleExtendedKeyEvent(QWindow *w, QEvent::Type type, int key, Qt::KeyboardModifiers modifiers,
quint32 nativeScanCode, quint32 nativeVirtualKey,
@@ -212,7 +212,7 @@ public:
// For event dispatcher implementations
static bool sendWindowSystemEvents(QEventLoop::ProcessEventsFlags flags);
- static void setSynchronousWindowsSystemEvents(bool enable);
+ static void setSynchronousWindowSystemEvents(bool enable);
static void flushWindowSystemEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents);
static void deferredFlushWindowSystemEvents(QEventLoop::ProcessEventsFlags flags);
static int windowSystemEventsQueued();
diff --git a/src/gui/kernel/qwindowsysteminterface_p.h b/src/gui/kernel/qwindowsysteminterface_p.h
index 2ec402a1e9..cc0ca6bf81 100644
--- a/src/gui/kernel/qwindowsysteminterface_p.h
+++ b/src/gui/kernel/qwindowsysteminterface_p.h
@@ -54,6 +54,8 @@
QT_BEGIN_NAMESPACE
+class QWindowSystemEventHandler;
+
class Q_GUI_EXPORT QWindowSystemInterfacePrivate {
public:
enum EventType {
@@ -99,7 +101,7 @@ public:
};
explicit WindowSystemEvent(EventType t)
- : type(t), flags(0) { }
+ : type(t), flags(0), eventAccepted(true) { }
virtual ~WindowSystemEvent() { }
bool synthetic() const { return flags & Synthetic; }
@@ -107,6 +109,7 @@ public:
EventType type;
int flags;
+ bool eventAccepted;
};
class CloseEvent : public WindowSystemEvent {
@@ -478,15 +481,31 @@ public:
static WindowSystemEvent *getNonUserInputWindowSystemEvent();
static WindowSystemEvent *peekWindowSystemEvent(EventType t);
static void removeWindowSystemEvent(WindowSystemEvent *event);
- static void handleWindowSystemEvent(WindowSystemEvent *ev);
+ static bool handleWindowSystemEvent(WindowSystemEvent *ev);
static QElapsedTimer eventTime;
- static bool synchronousWindowsSystemEvents;
+ static bool synchronousWindowSystemEvents;
static QWaitCondition eventsFlushed;
static QMutex flushEventMutex;
- static QList<QTouchEvent::TouchPoint> convertTouchPoints(const QList<QWindowSystemInterface::TouchPoint> &points, QEvent::Type *type);
+ static QList<QTouchEvent::TouchPoint>
+ fromNativeTouchPoints(const QList<QWindowSystemInterface::TouchPoint> &points,
+ const QWindow *window, QEvent::Type *type = Q_NULLPTR);
+ static QList<QWindowSystemInterface::TouchPoint>
+ toNativeTouchPoints(const QList<QTouchEvent::TouchPoint>& pointList,
+ const QWindow *window);
+
+ static void installWindowSystemEventHandler(QWindowSystemEventHandler *handler);
+ static void removeWindowSystemEventhandler(QWindowSystemEventHandler *handler);
+ static QWindowSystemEventHandler *eventHandler;
+};
+
+class Q_GUI_EXPORT QWindowSystemEventHandler
+{
+public:
+ virtual ~QWindowSystemEventHandler();
+ virtual bool sendEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *event);
};
QT_END_NAMESPACE
diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h
index 6f6ff235cf..cd5686be94 100644
--- a/src/gui/math3d/qmatrix4x4.h
+++ b/src/gui/math3d/qmatrix4x4.h
@@ -86,7 +86,7 @@ public:
inline void fill(float value);
double determinant() const;
- QMatrix4x4 inverted(bool *invertible = 0) const;
+ QMatrix4x4 inverted(bool *invertible = Q_NULLPTR) const;
QMatrix4x4 transposed() const;
QMatrix3x3 normalMatrix() const;
diff --git a/src/gui/math3d/qquaternion.h b/src/gui/math3d/qquaternion.h
index 5b0006ac56..3716220a60 100644
--- a/src/gui/math3d/qquaternion.h
+++ b/src/gui/math3d/qquaternion.h
@@ -164,12 +164,12 @@ inline QQuaternion::QQuaternion(float aScalar, float xpos, float ypos, float zpo
inline bool QQuaternion::isNull() const
{
- return xp == 0.0f && yp == 0.0f && zp == 0.0f && wp == 0.0f;
+ return wp == 0.0f && xp == 0.0f && yp == 0.0f && zp == 0.0f;
}
inline bool QQuaternion::isIdentity() const
{
- return xp == 0.0f && yp == 0.0f && zp == 0.0f && wp == 1.0f;
+ return wp == 1.0f && xp == 0.0f && yp == 0.0f && zp == 0.0f;
}
inline float QQuaternion::x() const { return xp; }
@@ -184,16 +184,16 @@ inline void QQuaternion::setScalar(float aScalar) { wp = aScalar; }
Q_DECL_CONSTEXPR inline float QQuaternion::dotProduct(const QQuaternion &q1, const QQuaternion &q2)
{
- return q1.xp * q2.xp + q1.yp * q2.yp + q1.zp * q2.zp + q1.wp * q2.wp;
+ return q1.wp * q2.wp + q1.xp * q2.xp + q1.yp * q2.yp + q1.zp * q2.zp;
}
inline QQuaternion QQuaternion::inverted() const
{
// Need some extra precision if the length is very small.
- double len = double(xp) * double(xp) +
+ double len = double(wp) * double(wp) +
+ double(xp) * double(xp) +
double(yp) * double(yp) +
- double(zp) * double(zp) +
- double(wp) * double(wp);
+ double(zp) * double(zp);
if (!qFuzzyIsNull(len))
return QQuaternion(wp / len, -xp / len, -yp / len, -zp / len);
return QQuaternion(0.0f, 0.0f, 0.0f, 0.0f);
@@ -213,28 +213,28 @@ inline QQuaternion QQuaternion::conjugate() const
inline QQuaternion &QQuaternion::operator+=(const QQuaternion &quaternion)
{
+ wp += quaternion.wp;
xp += quaternion.xp;
yp += quaternion.yp;
zp += quaternion.zp;
- wp += quaternion.wp;
return *this;
}
inline QQuaternion &QQuaternion::operator-=(const QQuaternion &quaternion)
{
+ wp -= quaternion.wp;
xp -= quaternion.xp;
yp -= quaternion.yp;
zp -= quaternion.zp;
- wp -= quaternion.wp;
return *this;
}
inline QQuaternion &QQuaternion::operator*=(float factor)
{
+ wp *= factor;
xp *= factor;
yp *= factor;
zp *= factor;
- wp *= factor;
return *this;
}
@@ -262,16 +262,16 @@ inline QQuaternion &QQuaternion::operator*=(const QQuaternion &quaternion)
inline QQuaternion &QQuaternion::operator/=(float divisor)
{
+ wp /= divisor;
xp /= divisor;
yp /= divisor;
zp /= divisor;
- wp /= divisor;
return *this;
}
inline bool operator==(const QQuaternion &q1, const QQuaternion &q2)
{
- return q1.xp == q2.xp && q1.yp == q2.yp && q1.zp == q2.zp && q1.wp == q2.wp;
+ return q1.wp == q2.wp && q1.xp == q2.xp && q1.yp == q2.yp && q1.zp == q2.zp;
}
inline bool operator!=(const QQuaternion &q1, const QQuaternion &q2)
@@ -311,10 +311,10 @@ inline const QQuaternion operator/(const QQuaternion &quaternion, float divisor)
inline bool qFuzzyCompare(const QQuaternion& q1, const QQuaternion& q2)
{
- return qFuzzyCompare(q1.xp, q2.xp) &&
+ return qFuzzyCompare(q1.wp, q2.wp) &&
+ qFuzzyCompare(q1.xp, q2.xp) &&
qFuzzyCompare(q1.yp, q2.yp) &&
- qFuzzyCompare(q1.zp, q2.zp) &&
- qFuzzyCompare(q1.wp, q2.wp);
+ qFuzzyCompare(q1.zp, q2.zp);
}
#ifndef QT_NO_VECTOR3D
diff --git a/src/gui/math3d/qvector2d.h b/src/gui/math3d/qvector2d.h
index 137142f381..c4e62710d9 100644
--- a/src/gui/math3d/qvector2d.h
+++ b/src/gui/math3d/qvector2d.h
@@ -122,7 +122,7 @@ private:
friend class QVector4D;
};
-Q_DECLARE_TYPEINFO(QVector2D, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QVector2D, Q_PRIMITIVE_TYPE);
Q_DECL_CONSTEXPR inline QVector2D::QVector2D() : xp(0.0f), yp(0.0f) {}
diff --git a/src/gui/math3d/qvector3d.h b/src/gui/math3d/qvector3d.h
index 5be637e0c5..b62d33da71 100644
--- a/src/gui/math3d/qvector3d.h
+++ b/src/gui/math3d/qvector3d.h
@@ -141,7 +141,7 @@ private:
#endif
};
-Q_DECLARE_TYPEINFO(QVector3D, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QVector3D, Q_PRIMITIVE_TYPE);
Q_DECL_CONSTEXPR inline QVector3D::QVector3D() : xp(0.0f), yp(0.0f), zp(0.0f) {}
diff --git a/src/gui/math3d/qvector4d.h b/src/gui/math3d/qvector4d.h
index 72db8ac754..0543f0fbe3 100644
--- a/src/gui/math3d/qvector4d.h
+++ b/src/gui/math3d/qvector4d.h
@@ -131,7 +131,7 @@ private:
#endif
};
-Q_DECLARE_TYPEINFO(QVector4D, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QVector4D, Q_PRIMITIVE_TYPE);
Q_DECL_CONSTEXPR inline QVector4D::QVector4D() : xp(0.0f), yp(0.0f), zp(0.0f), wp(0.0f) {}
diff --git a/src/gui/opengl/opengl.pri b/src/gui/opengl/opengl.pri
index 8659bd6dea..b13f258fda 100644
--- a/src/gui/opengl/opengl.pri
+++ b/src/gui/opengl/opengl.pri
@@ -36,7 +36,8 @@ contains(QT_CONFIG, opengl)|contains(QT_CONFIG, opengles2) {
opengl/qopengltexture.h \
opengl/qopengltexture_p.h \
opengl/qopengltexturehelper_p.h \
- opengl/qopenglpixeltransferoptions.h
+ opengl/qopenglpixeltransferoptions.h \
+ opengl/qopenglextrafunctions.h
SOURCES += opengl/qopengl.cpp \
opengl/qopenglfunctions.cpp \
diff --git a/src/gui/opengl/qopengl.cpp b/src/gui/opengl/qopengl.cpp
index 1c008ccb42..68cd8a82b4 100644
--- a/src/gui/opengl/qopengl.cpp
+++ b/src/gui/opengl/qopengl.cpp
@@ -135,20 +135,42 @@ static const char operators[][3] = {"!=", "<", "<=", "=", ">", ">="};
static inline QString valueKey() { return QStringLiteral("value"); }
static inline QString opKey() { return QStringLiteral("op"); }
static inline QString versionKey() { return QStringLiteral("version"); }
+static inline QString releaseKey() { return QStringLiteral("release"); }
static inline QString typeKey() { return QStringLiteral("type"); }
static inline QString osKey() { return QStringLiteral("os"); }
static inline QString vendorIdKey() { return QStringLiteral("vendor_id"); }
static inline QString glVendorKey() { return QStringLiteral("gl_vendor"); }
static inline QString deviceIdKey() { return QStringLiteral("device_id"); }
static inline QString driverVersionKey() { return QStringLiteral("driver_version"); }
+static inline QString driverDescriptionKey() { return QStringLiteral("driver_description"); }
static inline QString featuresKey() { return QStringLiteral("features"); }
static inline QString idKey() { return QStringLiteral("id"); }
static inline QString descriptionKey() { return QStringLiteral("description"); }
static inline QString exceptionsKey() { return QStringLiteral("exceptions"); }
+typedef QJsonArray::ConstIterator JsonArrayConstIt;
+
+static inline bool contains(const QJsonArray &haystack, unsigned needle)
+{
+ for (JsonArrayConstIt it = haystack.constBegin(), cend = haystack.constEnd(); it != cend; ++it) {
+ if (needle == it->toString().toUInt(Q_NULLPTR, /* base */ 0))
+ return true;
+ }
+ return false;
+}
+
+static inline bool contains(const QJsonArray &haystack, const QString &needle)
+{
+ for (JsonArrayConstIt it = haystack.constBegin(), cend = haystack.constEnd(); it != cend; ++it) {
+ if (needle == it->toString())
+ return true;
+ }
+ return false;
+}
+
namespace {
// VersionTerm describing a version term consisting of number and operator
-// found in "os", "driver_version", "gl_version".
+// found in os.version and driver_version.
struct VersionTerm {
VersionTerm() : op(NotEqual) {}
static VersionTerm fromJson(const QJsonValue &v);
@@ -206,9 +228,38 @@ struct OsTypeTerm
static OsTypeTerm fromJson(const QJsonValue &v);
static QString hostOs();
static QVersionNumber hostKernelVersion() { return QVersionNumber::fromString(QSysInfo::kernelVersion()); }
+ static QString hostOsRelease() {
+ QString ver;
+#ifdef Q_OS_WIN
+ switch (QSysInfo::windowsVersion()) {
+ case QSysInfo::WV_XP:
+ case QSysInfo::WV_2003:
+ ver = QStringLiteral("xp");
+ break;
+ case QSysInfo::WV_VISTA:
+ ver = QStringLiteral("vista");
+ break;
+ case QSysInfo::WV_WINDOWS7:
+ ver = QStringLiteral("7");
+ break;
+ case QSysInfo::WV_WINDOWS8:
+ ver = QStringLiteral("8");
+ break;
+ case QSysInfo::WV_WINDOWS8_1:
+ ver = QStringLiteral("8.1");
+ break;
+ case QSysInfo::WV_WINDOWS10:
+ ver = QStringLiteral("10");
+ break;
+ default:
+ break;
+ }
+#endif
+ return ver;
+ }
bool isNull() const { return type.isEmpty(); }
- bool matches(const QString &osName, const QVersionNumber &kernelVersion) const
+ bool matches(const QString &osName, const QVersionNumber &kernelVersion, const QString &osRelease) const
{
if (isNull() || osName.isEmpty() || kernelVersion.isNull()) {
qWarning() << Q_FUNC_INFO << "called with invalid parameters";
@@ -216,11 +267,17 @@ struct OsTypeTerm
}
if (type != osName)
return false;
- return versionTerm.isNull() || versionTerm.matches(kernelVersion);
+ if (!versionTerm.isNull() && !versionTerm.matches(kernelVersion))
+ return false;
+ // release is a list of Windows versions where the rule should match
+ if (!release.isEmpty() && !contains(release, osRelease))
+ return false;
+ return true;
}
QString type;
VersionTerm versionTerm;
+ QJsonArray release;
};
OsTypeTerm OsTypeTerm::fromJson(const QJsonValue &v)
@@ -231,6 +288,7 @@ OsTypeTerm OsTypeTerm::fromJson(const QJsonValue &v)
const QJsonObject o = v.toObject();
result.type = o.value(typeKey()).toString();
result.versionTerm = VersionTerm::fromJson(o.value(versionKey()));
+ result.release = o.value(releaseKey()).toArray();
return result;
}
@@ -251,17 +309,6 @@ QString OsTypeTerm::hostOs()
}
} // anonymous namespace
-typedef QJsonArray::ConstIterator JsonArrayConstIt;
-
-static inline bool contains(const QJsonArray &a, unsigned needle)
-{
- for (JsonArrayConstIt it = a.constBegin(), cend = a.constEnd(); it != cend; ++it) {
- if (needle == it->toString().toUInt(Q_NULLPTR, /* base */ 0))
- return true;
- }
- return false;
-}
-
static QString msgSyntaxWarning(const QJsonObject &object, const QString &what)
{
QString result;
@@ -277,17 +324,18 @@ static QString msgSyntaxWarning(const QJsonObject &object, const QString &what)
static bool matches(const QJsonObject &object,
const QString &osName,
const QVersionNumber &kernelVersion,
+ const QString &osRelease,
const QOpenGLConfig::Gpu &gpu)
{
const OsTypeTerm os = OsTypeTerm::fromJson(object.value(osKey()));
- if (!os.isNull() && !os.matches(osName, kernelVersion))
+ if (!os.isNull() && !os.matches(osName, kernelVersion, osRelease))
return false;
const QJsonValue exceptionsV = object.value(exceptionsKey());
if (exceptionsV.isArray()) {
const QJsonArray exceptionsA = exceptionsV.toArray();
for (JsonArrayConstIt it = exceptionsA.constBegin(), cend = exceptionsA.constEnd(); it != cend; ++it) {
- if (matches(it->toObject(), osName, kernelVersion, gpu))
+ if (matches(it->toObject(), osName, kernelVersion, osRelease, gpu))
return false;
}
}
@@ -336,12 +384,22 @@ static bool matches(const QJsonObject &object,
QLatin1String("Driver version must be of type object."));
}
}
+
+ if (!gpu.driverDescription.isEmpty()) {
+ const QJsonValue driverDescriptionV = object.value(driverDescriptionKey());
+ if (driverDescriptionV.isString()) {
+ if (!gpu.driverDescription.contains(driverDescriptionV.toString().toUtf8()))
+ return false;
+ }
+ }
+
return true;
}
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
const QString &osName,
const QVersionNumber &kernelVersion,
+ const QString &osRelease,
const QJsonDocument &doc,
QSet<QString> *result,
QString *errorMessage)
@@ -358,7 +416,7 @@ static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
for (JsonArrayConstIt eit = entriesA.constBegin(), ecend = entriesA.constEnd(); eit != ecend; ++eit) {
if (eit->isObject()) {
const QJsonObject object = eit->toObject();
- if (matches(object, osName, kernelVersion, gpu)) {
+ if (matches(object, osName, kernelVersion, osRelease, gpu)) {
const QJsonValue featuresListV = object.value(featuresKey());
if (featuresListV.isArray()) {
const QJsonArray featuresListA = featuresListV.toArray();
@@ -374,6 +432,7 @@ static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
const QString &osName,
const QVersionNumber &kernelVersion,
+ const QString &osRelease,
const QByteArray &jsonAsciiData,
QSet<QString> *result, QString *errorMessage)
{
@@ -389,12 +448,13 @@ static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
<< error.offset << ").";
return false;
}
- return readGpuFeatures(gpu, osName, kernelVersion, document, result, errorMessage);
+ return readGpuFeatures(gpu, osName, kernelVersion, osRelease, document, result, errorMessage);
}
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
const QString &osName,
const QVersionNumber &kernelVersion,
+ const QString &osRelease,
const QString &fileName,
QSet<QString> *result, QString *errorMessage)
{
@@ -407,7 +467,7 @@ static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
<< file.errorString();
return false;
}
- const bool success = readGpuFeatures(gpu, osName, kernelVersion, file.readAll(), result, errorMessage);
+ const bool success = readGpuFeatures(gpu, osName, kernelVersion, osRelease, file.readAll(), result, errorMessage);
if (!success) {
errorMessage->prepend(QLatin1String("Error reading \"")
+ QDir::toNativeSeparators(fileName)
@@ -417,37 +477,39 @@ static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
}
QSet<QString> QOpenGLConfig::gpuFeatures(const QOpenGLConfig::Gpu &gpu,
- const QString &osName,
- const QVersionNumber &kernelVersion,
- const QJsonDocument &doc)
+ const QString &osName,
+ const QVersionNumber &kernelVersion,
+ const QString &osRelease,
+ const QJsonDocument &doc)
{
QSet<QString> result;
QString errorMessage;
- if (!readGpuFeatures(gpu, osName, kernelVersion, doc, &result, &errorMessage))
+ if (!readGpuFeatures(gpu, osName, kernelVersion, osRelease, doc, &result, &errorMessage))
qWarning().noquote() << errorMessage;
return result;
}
QSet<QString> QOpenGLConfig::gpuFeatures(const QOpenGLConfig::Gpu &gpu,
- const QString &osName,
- const QVersionNumber &kernelVersion,
- const QString &fileName)
+ const QString &osName,
+ const QVersionNumber &kernelVersion,
+ const QString &osRelease,
+ const QString &fileName)
{
QSet<QString> result;
QString errorMessage;
- if (!readGpuFeatures(gpu, osName, kernelVersion, fileName, &result, &errorMessage))
+ if (!readGpuFeatures(gpu, osName, kernelVersion, osRelease, fileName, &result, &errorMessage))
qWarning().noquote() << errorMessage;
return result;
}
QSet<QString> QOpenGLConfig::gpuFeatures(const Gpu &gpu, const QJsonDocument &doc)
{
- return gpuFeatures(gpu, OsTypeTerm::hostOs(), OsTypeTerm::hostKernelVersion(), doc);
+ return gpuFeatures(gpu, OsTypeTerm::hostOs(), OsTypeTerm::hostKernelVersion(), OsTypeTerm::hostOsRelease(), doc);
}
QSet<QString> QOpenGLConfig::gpuFeatures(const Gpu &gpu, const QString &fileName)
{
- return gpuFeatures(gpu, OsTypeTerm::hostOs(), OsTypeTerm::hostKernelVersion(), fileName);
+ return gpuFeatures(gpu, OsTypeTerm::hostOs(), OsTypeTerm::hostKernelVersion(), OsTypeTerm::hostOsRelease(), fileName);
}
QOpenGLConfig::Gpu QOpenGLConfig::Gpu::fromContext()
diff --git a/src/gui/opengl/qopengl.h b/src/gui/opengl/qopengl.h
index 72abce760d..87dc2a830e 100644
--- a/src/gui/opengl/qopengl.h
+++ b/src/gui/opengl/qopengl.h
@@ -83,13 +83,11 @@ typedef void* GLeglImageOES;
// include headers on top of each other, meaning that applications can
// include gl2.h even if gl31.h gets included here.
-// This compile time differentation is important inside Qt because,
-// unlike desktop GL, GLES is different when it comes to versioning
-// and extensions: Standard functions that are new in a given version
-// are always available in a version-specific header and are not
-// guaranteed to be dynamically resolvable via eglGetProcAddress (and
-// are typically not available as extensions even if they were part of
-// an extension for a previous version).
+// NB! This file contains the only usages of the ES_3 and ES_3_1
+// macros. They are useless for pretty much anything else. The fact
+// that Qt was built against an SDK with f.ex. ES 2 only does not mean
+// applications cannot target ES 3. Therefore QOpenGLFunctions and
+// friends do everything dynamically and never rely on these macros.
# if defined(QT_OPENGL_ES_3_1)
# include <GLES3/gl31.h>
diff --git a/src/gui/opengl/qopengl_p.h b/src/gui/opengl/qopengl_p.h
index 980e02aea6..6b66a3ba57 100644
--- a/src/gui/opengl/qopengl_p.h
+++ b/src/gui/opengl/qopengl_p.h
@@ -49,7 +49,7 @@
#include <private/qopenglcontext_p.h>
#include <QtCore/qset.h>
#include <QtCore/qstring.h>
-#include <private/qversionnumber_p.h>
+#include <QtCore/qversionnumber.h>
QT_BEGIN_NAMESPACE
@@ -79,19 +79,21 @@ public:
bool isValid() const { return deviceId || !glVendor.isEmpty(); }
bool equals(const Gpu &other) const {
return vendorId == other.vendorId && deviceId == other.deviceId && driverVersion == other.driverVersion
- && glVendor == other.glVendor;
+ && driverDescription == other.driverDescription && glVendor == other.glVendor;
}
uint vendorId;
uint deviceId;
QVersionNumber driverVersion;
+ QByteArray driverDescription;
QByteArray glVendor;
- static Gpu fromDevice(uint vendorId, uint deviceId, QVersionNumber driverVersion) {
+ static Gpu fromDevice(uint vendorId, uint deviceId, QVersionNumber driverVersion, const QByteArray &driverDescription) {
Gpu gpu;
gpu.vendorId = vendorId;
gpu.deviceId = deviceId;
gpu.driverVersion = driverVersion;
+ gpu.driverDescription = driverDescription;
return gpu;
}
@@ -105,10 +107,10 @@ public:
};
static QSet<QString> gpuFeatures(const Gpu &gpu,
- const QString &osName, const QVersionNumber &kernelVersion,
+ const QString &osName, const QVersionNumber &kernelVersion, const QString &osVersion,
const QJsonDocument &doc);
static QSet<QString> gpuFeatures(const Gpu &gpu,
- const QString &osName, const QVersionNumber &kernelVersion,
+ const QString &osName, const QVersionNumber &kernelVersion, const QString &osVersion,
const QString &fileName);
static QSet<QString> gpuFeatures(const Gpu &gpu, const QJsonDocument &doc);
static QSet<QString> gpuFeatures(const Gpu &gpu, const QString &fileName);
diff --git a/src/gui/opengl/qopenglbuffer.h b/src/gui/opengl/qopenglbuffer.h
index 847c1efaa0..ca3d85d8e0 100644
--- a/src/gui/opengl/qopenglbuffer.h
+++ b/src/gui/opengl/qopenglbuffer.h
@@ -118,7 +118,7 @@ public:
void write(int offset, const void *data, int count);
void allocate(const void *data, int count);
- inline void allocate(int count) { allocate(0, count); }
+ inline void allocate(int count) { allocate(Q_NULLPTR, count); }
void *map(QOpenGLBuffer::Access access);
void *mapRange(int offset, int count, QOpenGLBuffer::RangeAccessFlags access);
diff --git a/src/gui/opengl/qopengldebug.h b/src/gui/opengl/qopengldebug.h
index 425ab78d7a..3e93ad4120 100644
--- a/src/gui/opengl/qopengldebug.h
+++ b/src/gui/opengl/qopengldebug.h
@@ -97,14 +97,14 @@ public:
QOpenGLDebugMessage();
QOpenGLDebugMessage(const QOpenGLDebugMessage &debugMessage);
- ~QOpenGLDebugMessage();
QOpenGLDebugMessage &operator=(const QOpenGLDebugMessage &debugMessage);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QOpenGLDebugMessage &operator=(QOpenGLDebugMessage &&debugMessage)
- { d.swap(debugMessage.d); return *this; }
+ QOpenGLDebugMessage &operator=(QOpenGLDebugMessage &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- inline void swap(QOpenGLDebugMessage &debugMessage) { d.swap(debugMessage.d); }
+ ~QOpenGLDebugMessage();
+
+ void swap(QOpenGLDebugMessage &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
Source source() const;
Type type() const;
@@ -156,7 +156,7 @@ public:
};
Q_ENUM(LoggingMode)
- explicit QOpenGLDebugLogger(QObject *parent = 0);
+ explicit QOpenGLDebugLogger(QObject *parent = Q_NULLPTR);
~QOpenGLDebugLogger();
bool initialize();
diff --git a/src/gui/opengl/qopenglengineshadermanager.cpp b/src/gui/opengl/qopenglengineshadermanager.cpp
index 7e53c01cba..40f4ce94c2 100644
--- a/src/gui/opengl/qopenglengineshadermanager.cpp
+++ b/src/gui/opengl/qopenglengineshadermanager.cpp
@@ -427,11 +427,10 @@ QOpenGLEngineShaderProg *QOpenGLEngineSharedShaders::findProgramInCache(const QO
if (!inCache)
shaderCache.store(newProg->program, QOpenGLContext::currentContext());
} else {
- QLatin1String none("none");
- QLatin1String br("\n");
QString error;
error = QLatin1String("Shader program failed to link,");
#if defined(QT_DEBUG)
+ QLatin1String br("\n");
error += QLatin1String("\n Shaders Used:\n");
for (int i = 0; i < newProg->program->shaders().count(); ++i) {
QOpenGLShader *shader = newProg->program->shaders().at(i);
diff --git a/src/gui/opengl/qopenglextensions_p.h b/src/gui/opengl/qopenglextensions_p.h
index 7def687f49..aa2a08242d 100644
--- a/src/gui/opengl/qopenglextensions_p.h
+++ b/src/gui/opengl/qopenglextensions_p.h
@@ -45,7 +45,7 @@
// We mean it.
//
-#include "qopenglfunctions.h"
+#include "qopenglextrafunctions.h"
#include <QtCore/qlibrary.h>
QT_BEGIN_NAMESPACE
@@ -57,32 +57,194 @@ class QOpenGLES3Helper
public:
QOpenGLES3Helper();
- GLvoid* (QOPENGLF_APIENTRYP MapBufferRange)(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr length, GLbitfield access);
+ // GLES3
+ void (QOPENGLF_APIENTRYP ReadBuffer)(GLenum mode);
+ void (QOPENGLF_APIENTRYP DrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);
+ void (QOPENGLF_APIENTRYP TexImage3D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);
+ void (QOPENGLF_APIENTRYP TexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);
+ void (QOPENGLF_APIENTRYP CopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP CompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
+ void (QOPENGLF_APIENTRYP CompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
+ void (QOPENGLF_APIENTRYP GenQueries)(GLsizei n, GLuint *ids);
+ void (QOPENGLF_APIENTRYP DeleteQueries)(GLsizei n, const GLuint *ids);
+ GLboolean (QOPENGLF_APIENTRYP IsQuery)(GLuint id);
+ void (QOPENGLF_APIENTRYP BeginQuery)(GLenum target, GLuint id);
+ void (QOPENGLF_APIENTRYP EndQuery)(GLenum target);
+ void (QOPENGLF_APIENTRYP GetQueryiv)(GLenum target, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetQueryObjectuiv)(GLuint id, GLenum pname, GLuint *params);
GLboolean (QOPENGLF_APIENTRYP UnmapBuffer)(GLenum target);
+ void (QOPENGLF_APIENTRYP GetBufferPointerv)(GLenum target, GLenum pname, void **params);
+ void (QOPENGLF_APIENTRYP DrawBuffers)(GLsizei n, const GLenum *bufs);
+ void (QOPENGLF_APIENTRYP UniformMatrix2x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix3x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix2x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix4x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix3x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix4x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void (QOPENGLF_APIENTRYP BlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
- void (QOPENGLF_APIENTRYP RenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height);
-
- void (QOPENGLF_APIENTRYP GenVertexArrays)(GLsizei n, GLuint *arrays);
- void (QOPENGLF_APIENTRYP DeleteVertexArrays)(GLsizei n, const GLuint *arrays);
+ void (QOPENGLF_APIENTRYP RenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP FramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+ void *(QOPENGLF_APIENTRYP MapBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+ void (QOPENGLF_APIENTRYP FlushMappedBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length);
void (QOPENGLF_APIENTRYP BindVertexArray)(GLuint array);
+ void (QOPENGLF_APIENTRYP DeleteVertexArrays)(GLsizei n, const GLuint *arrays);
+ void (QOPENGLF_APIENTRYP GenVertexArrays)(GLsizei n, GLuint *arrays);
GLboolean (QOPENGLF_APIENTRYP IsVertexArray)(GLuint array);
-
- void (QOPENGLF_APIENTRYP TexImage3D)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
- void (QOPENGLF_APIENTRYP TexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
- void (QOPENGLF_APIENTRYP CompressedTexImage3D)(GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
- void (QOPENGLF_APIENTRYP CompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
-
- void (QOPENGLF_APIENTRYP TexStorage3D)(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth);
- void (QOPENGLF_APIENTRYP TexStorage2D)(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP GetIntegeri_v)(GLenum target, GLuint index, GLint *data);
+ void (QOPENGLF_APIENTRYP BeginTransformFeedback)(GLenum primitiveMode);
+ void (QOPENGLF_APIENTRYP EndTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP BindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+ void (QOPENGLF_APIENTRYP BindBufferBase)(GLenum target, GLuint index, GLuint buffer);
+ void (QOPENGLF_APIENTRYP TransformFeedbackVaryings)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);
+ void (QOPENGLF_APIENTRYP GetTransformFeedbackVarying)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+ void (QOPENGLF_APIENTRYP VertexAttribIPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);
+ void (QOPENGLF_APIENTRYP GetVertexAttribIiv)(GLuint index, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetVertexAttribIuiv)(GLuint index, GLenum pname, GLuint *params);
+ void (QOPENGLF_APIENTRYP VertexAttribI4i)(GLuint index, GLint x, GLint y, GLint z, GLint w);
+ void (QOPENGLF_APIENTRYP VertexAttribI4ui)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+ void (QOPENGLF_APIENTRYP VertexAttribI4iv)(GLuint index, const GLint *v);
+ void (QOPENGLF_APIENTRYP VertexAttribI4uiv)(GLuint index, const GLuint *v);
+ void (QOPENGLF_APIENTRYP GetUniformuiv)(GLuint program, GLint location, GLuint *params);
+ GLint (QOPENGLF_APIENTRYP GetFragDataLocation)(GLuint program, const GLchar *name);
+ void (QOPENGLF_APIENTRYP Uniform1ui)(GLint location, GLuint v0);
+ void (QOPENGLF_APIENTRYP Uniform2ui)(GLint location, GLuint v0, GLuint v1);
+ void (QOPENGLF_APIENTRYP Uniform3ui)(GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void (QOPENGLF_APIENTRYP Uniform4ui)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void (QOPENGLF_APIENTRYP Uniform1uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform2uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform3uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform4uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferuiv)(GLenum buffer, GLint drawbuffer, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferfv)(GLenum buffer, GLint drawbuffer, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ClearBufferfi)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
+ const GLubyte *(QOPENGLF_APIENTRYP GetStringi)(GLenum name, GLuint index);
+ void (QOPENGLF_APIENTRYP CopyBufferSubData)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+ void (QOPENGLF_APIENTRYP GetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices);
+ void (QOPENGLF_APIENTRYP GetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);
+ GLuint (QOPENGLF_APIENTRYP GetUniformBlockIndex)(GLuint program, const GLchar *uniformBlockName);
+ void (QOPENGLF_APIENTRYP GetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);
+ void (QOPENGLF_APIENTRYP UniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+ void (QOPENGLF_APIENTRYP DrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
+ void (QOPENGLF_APIENTRYP DrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount);
+ GLsync (QOPENGLF_APIENTRYP FenceSync)(GLenum condition, GLbitfield flags);
+ GLboolean (QOPENGLF_APIENTRYP IsSync)(GLsync sync);
+ void (QOPENGLF_APIENTRYP DeleteSync)(GLsync sync);
+ GLenum (QOPENGLF_APIENTRYP ClientWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void (QOPENGLF_APIENTRYP WaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void (QOPENGLF_APIENTRYP GetInteger64v)(GLenum pname, GLint64 *data);
+ void (QOPENGLF_APIENTRYP GetSynciv)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+ void (QOPENGLF_APIENTRYP GetInteger64i_v)(GLenum target, GLuint index, GLint64 *data);
+ void (QOPENGLF_APIENTRYP GetBufferParameteri64v)(GLenum target, GLenum pname, GLint64 *params);
+ void (QOPENGLF_APIENTRYP GenSamplers)(GLsizei count, GLuint *samplers);
+ void (QOPENGLF_APIENTRYP DeleteSamplers)(GLsizei count, const GLuint *samplers);
+ GLboolean (QOPENGLF_APIENTRYP IsSampler)(GLuint sampler);
+ void (QOPENGLF_APIENTRYP BindSampler)(GLuint unit, GLuint sampler);
+ void (QOPENGLF_APIENTRYP SamplerParameteri)(GLuint sampler, GLenum pname, GLint param);
+ void (QOPENGLF_APIENTRYP SamplerParameteriv)(GLuint sampler, GLenum pname, const GLint *param);
+ void (QOPENGLF_APIENTRYP SamplerParameterf)(GLuint sampler, GLenum pname, GLfloat param);
+ void (QOPENGLF_APIENTRYP SamplerParameterfv)(GLuint sampler, GLenum pname, const GLfloat *param);
+ void (QOPENGLF_APIENTRYP GetSamplerParameteriv)(GLuint sampler, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetSamplerParameterfv)(GLuint sampler, GLenum pname, GLfloat *params);
+ void (QOPENGLF_APIENTRYP VertexAttribDivisor)(GLuint index, GLuint divisor);
+ void (QOPENGLF_APIENTRYP BindTransformFeedback)(GLenum target, GLuint id);
+ void (QOPENGLF_APIENTRYP DeleteTransformFeedbacks)(GLsizei n, const GLuint *ids);
+ void (QOPENGLF_APIENTRYP GenTransformFeedbacks)(GLsizei n, GLuint *ids);
+ GLboolean (QOPENGLF_APIENTRYP IsTransformFeedback)(GLuint id);
+ void (QOPENGLF_APIENTRYP PauseTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP ResumeTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP GetProgramBinary)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+ void (QOPENGLF_APIENTRYP ProgramBinary)(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length);
+ void (QOPENGLF_APIENTRYP ProgramParameteri)(GLuint program, GLenum pname, GLint value);
+ void (QOPENGLF_APIENTRYP InvalidateFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum *attachments);
+ void (QOPENGLF_APIENTRYP InvalidateSubFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP TexStorage2D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP TexStorage3D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+ void (QOPENGLF_APIENTRYP GetInternalformativ)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+
+ // GLES 3.1
+ void (QOPENGLF_APIENTRYP DispatchCompute)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
+ void (QOPENGLF_APIENTRYP DispatchComputeIndirect)(GLintptr indirect);
+ void (QOPENGLF_APIENTRYP DrawArraysIndirect)(GLenum mode, const void *indirect);
+ void (QOPENGLF_APIENTRYP DrawElementsIndirect)(GLenum mode, GLenum type, const void *indirect);
+ void (QOPENGLF_APIENTRYP FramebufferParameteri)(GLenum target, GLenum pname, GLint param);
+ void (QOPENGLF_APIENTRYP GetFramebufferParameteriv)(GLenum target, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetProgramInterfaceiv)(GLuint program, GLenum programInterface, GLenum pname, GLint *params);
+ GLuint (QOPENGLF_APIENTRYP GetProgramResourceIndex)(GLuint program, GLenum programInterface, const GLchar *name);
+ void (QOPENGLF_APIENTRYP GetProgramResourceName)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name);
+ void (QOPENGLF_APIENTRYP GetProgramResourceiv)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params);
+ GLint (QOPENGLF_APIENTRYP GetProgramResourceLocation)(GLuint program, GLenum programInterface, const GLchar *name);
+ void (QOPENGLF_APIENTRYP UseProgramStages)(GLuint pipeline, GLbitfield stages, GLuint program);
+ void (QOPENGLF_APIENTRYP ActiveShaderProgram)(GLuint pipeline, GLuint program);
+ GLuint (QOPENGLF_APIENTRYP CreateShaderProgramv)(GLenum type, GLsizei count, const GLchar *const*strings);
+ void (QOPENGLF_APIENTRYP BindProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP DeleteProgramPipelines)(GLsizei n, const GLuint *pipelines);
+ void (QOPENGLF_APIENTRYP GenProgramPipelines)(GLsizei n, GLuint *pipelines);
+ GLboolean (QOPENGLF_APIENTRYP IsProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP GetProgramPipelineiv)(GLuint pipeline, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP ProgramUniform1i)(GLuint program, GLint location, GLint v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2i)(GLuint program, GLint location, GLint v0, GLint v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1ui)(GLuint program, GLint location, GLuint v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2ui)(GLuint program, GLint location, GLuint v0, GLuint v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1f)(GLuint program, GLint location, GLfloat v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2f)(GLuint program, GLint location, GLfloat v0, GLfloat v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform1uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform1fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ValidateProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP GetProgramPipelineInfoLog)(GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+ void (QOPENGLF_APIENTRYP BindImageTexture)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+ void (QOPENGLF_APIENTRYP GetBooleani_v)(GLenum target, GLuint index, GLboolean *data);
+ void (QOPENGLF_APIENTRYP MemoryBarrierFunc)(GLbitfield barriers);
+ void (QOPENGLF_APIENTRYP MemoryBarrierByRegion)(GLbitfield barriers);
+ void (QOPENGLF_APIENTRYP TexStorage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+ void (QOPENGLF_APIENTRYP GetMultisamplefv)(GLenum pname, GLuint index, GLfloat *val);
+ void (QOPENGLF_APIENTRYP SampleMaski)(GLuint maskNumber, GLbitfield mask);
+ void (QOPENGLF_APIENTRYP GetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params);
+ void (QOPENGLF_APIENTRYP BindVertexBuffer)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
+ void (QOPENGLF_APIENTRYP VertexAttribFormat)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
+ void (QOPENGLF_APIENTRYP VertexAttribIFormat)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
+ void (QOPENGLF_APIENTRYP VertexAttribBinding)(GLuint attribindex, GLuint bindingindex);
+ void (QOPENGLF_APIENTRYP VertexBindingDivisor)(GLuint bindingindex, GLuint divisor);
+
+ QPair<int, int> supportedVersion() const { return m_supportedVersion; }
private:
bool init();
QFunctionPointer resolve(const char *name);
-
+#ifndef QT_NO_LIBRARY
QLibrary m_gl;
+#endif
+ QPair<int, int> m_supportedVersion;
};
-class Q_GUI_EXPORT QOpenGLExtensions : public QOpenGLFunctions
+class Q_GUI_EXPORT QOpenGLExtensions : public QOpenGLExtraFunctions
{
Q_DECLARE_PRIVATE(QOpenGLExtensions)
public:
@@ -113,7 +275,8 @@ public:
GeometryShaders = 0x00080000,
MapBufferRange = 0x00100000,
Sized8Formats = 0x00200000,
- DiscardFramebuffer = 0x00400000
+ DiscardFramebuffer = 0x00400000,
+ Sized16Formats = 0x00800000
};
Q_DECLARE_FLAGS(OpenGLExtensions, OpenGLExtension)
@@ -121,19 +284,7 @@ public:
bool hasOpenGLExtension(QOpenGLExtensions::OpenGLExtension extension) const;
GLvoid *glMapBuffer(GLenum target, GLenum access);
- GLvoid *glMapBufferRange(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr length, GLbitfield access);
- GLboolean glUnmapBuffer(GLenum target);
-
- void glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
- GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
- GLbitfield mask, GLenum filter);
-
- void glRenderbufferStorageMultisample(GLenum target, GLsizei samples,
- GLenum internalFormat,
- GLsizei width, GLsizei height);
-
void glGetBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, GLvoid *data);
-
void glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments);
QOpenGLES3Helper *gles3Helper();
@@ -146,21 +297,12 @@ private:
Q_DECLARE_OPERATORS_FOR_FLAGS(QOpenGLExtensions::OpenGLExtensions)
-class QOpenGLExtensionsPrivate : public QOpenGLFunctionsPrivate
+class QOpenGLExtensionsPrivate : public QOpenGLExtraFunctionsPrivate
{
public:
explicit QOpenGLExtensionsPrivate(QOpenGLContext *ctx);
GLvoid* (QOPENGLF_APIENTRYP MapBuffer)(GLenum target, GLenum access);
- GLvoid* (QOPENGLF_APIENTRYP MapBufferRange)(GLenum target, qopengl_GLintptr offset,
- qopengl_GLsizeiptr length, GLbitfield access);
- GLboolean (QOPENGLF_APIENTRYP UnmapBuffer)(GLenum target);
- void (QOPENGLF_APIENTRYP BlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
- GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
- GLbitfield mask, GLenum filter);
- void (QOPENGLF_APIENTRYP RenderbufferStorageMultisample)(GLenum target, GLsizei samples,
- GLenum internalFormat,
- GLsizei width, GLsizei height);
void (QOPENGLF_APIENTRYP GetBufferSubData)(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, GLvoid *data);
void (QOPENGLF_APIENTRYP DiscardFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum *attachments);
@@ -177,45 +319,6 @@ inline GLvoid *QOpenGLExtensions::glMapBuffer(GLenum target, GLenum access)
return result;
}
-inline GLvoid *QOpenGLExtensions::glMapBufferRange(GLenum target, qopengl_GLintptr offset,
- qopengl_GLsizeiptr length, GLbitfield access)
-{
- Q_D(QOpenGLExtensions);
- Q_ASSERT(QOpenGLExtensions::isInitialized(d));
- GLvoid *result = d->MapBufferRange(target, offset, length, access);
- Q_OPENGL_FUNCTIONS_DEBUG
- return result;
-}
-
-inline GLboolean QOpenGLExtensions::glUnmapBuffer(GLenum target)
-{
- Q_D(QOpenGLExtensions);
- Q_ASSERT(QOpenGLExtensions::isInitialized(d));
- GLboolean result = d->UnmapBuffer(target);
- Q_OPENGL_FUNCTIONS_DEBUG
- return result;
-}
-
-inline void QOpenGLExtensions::glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
- GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
- GLbitfield mask, GLenum filter)
-{
- Q_D(QOpenGLExtensions);
- Q_ASSERT(QOpenGLExtensions::isInitialized(d));
- d->BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
- Q_OPENGL_FUNCTIONS_DEBUG
-}
-
-inline void QOpenGLExtensions::glRenderbufferStorageMultisample(GLenum target, GLsizei samples,
- GLenum internalFormat,
- GLsizei width, GLsizei height)
-{
- Q_D(QOpenGLExtensions);
- Q_ASSERT(QOpenGLExtensions::isInitialized(d));
- d->RenderbufferStorageMultisample(target, samples, internalFormat, width, height);
- Q_OPENGL_FUNCTIONS_DEBUG
-}
-
inline void QOpenGLExtensions::glGetBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, GLvoid *data)
{
Q_D(QOpenGLExtensions);
diff --git a/src/gui/opengl/qopenglextrafunctions.h b/src/gui/opengl/qopenglextrafunctions.h
new file mode 100644
index 0000000000..6558284bd0
--- /dev/null
+++ b/src/gui/opengl/qopenglextrafunctions.h
@@ -0,0 +1,1990 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QOPENGLEXTRAFUNCTIONS_H
+#define QOPENGLEXTRAFUNCTIONS_H
+
+#include <QtCore/qglobal.h>
+
+#ifndef QT_NO_OPENGL
+
+#include <QtGui/qopenglfunctions.h>
+
+QT_BEGIN_NAMESPACE
+
+class QOpenGLExtraFunctionsPrivate;
+
+#undef glReadBuffer
+#undef glDrawRangeElements
+#undef glTexImage3D
+#undef glTexSubImage3D
+#undef glCopyTexSubImage3D
+#undef glCompressedTexImage3D
+#undef glCompressedTexSubImage3D
+#undef glGenQueries
+#undef glDeleteQueries
+#undef glIsQuery
+#undef glBeginQuery
+#undef glEndQuery
+#undef glGetQueryiv
+#undef glGetQueryObjectuiv
+#undef glUnmapBuffer
+#undef glGetBufferPointerv
+#undef glDrawBuffers
+#undef glUniformMatrix2x3fv
+#undef glUniformMatrix3x2fv
+#undef glUniformMatrix2x4fv
+#undef glUniformMatrix4x2fv
+#undef glUniformMatrix3x4fv
+#undef glUniformMatrix4x3fv
+#undef glBlitFramebuffer
+#undef glRenderbufferStorageMultisample
+#undef glFramebufferTextureLayer
+#undef glMapBufferRange
+#undef glFlushMappedBufferRange
+#undef glBindVertexArray
+#undef glDeleteVertexArrays
+#undef glGenVertexArrays
+#undef glIsVertexArray
+#undef glGetIntegeri_v
+#undef glBeginTransformFeedback
+#undef glEndTransformFeedback
+#undef glBindBufferRange
+#undef glBindBufferBase
+#undef glTransformFeedbackVaryings
+#undef glGetTransformFeedbackVarying
+#undef glVertexAttribIPointer
+#undef glGetVertexAttribIiv
+#undef glGetVertexAttribIuiv
+#undef glVertexAttribI4i
+#undef glVertexAttribI4ui
+#undef glVertexAttribI4iv
+#undef glVertexAttribI4uiv
+#undef glGetUniformuiv
+#undef glGetFragDataLocation
+#undef glUniform1ui
+#undef glUniform2ui
+#undef glUniform3ui
+#undef glUniform4ui
+#undef glUniform1uiv
+#undef glUniform2uiv
+#undef glUniform3uiv
+#undef glUniform4uiv
+#undef glClearBufferiv
+#undef glClearBufferuiv
+#undef glClearBufferfv
+#undef glClearBufferfi
+#undef glGetStringi
+#undef glCopyBufferSubData
+#undef glGetUniformIndices
+#undef glGetActiveUniformsiv
+#undef glGetUniformBlockIndex
+#undef glGetActiveUniformBlockiv
+#undef glGetActiveUniformBlockName
+#undef glUniformBlockBinding
+#undef glDrawArraysInstanced
+#undef glDrawElementsInstanced
+#undef glFenceSync
+#undef glIsSync
+#undef glDeleteSync
+#undef glClientWaitSync
+#undef glWaitSync
+#undef glGetInteger64v
+#undef glGetSynciv
+#undef glGetInteger64i_v
+#undef glGetBufferParameteri64v
+#undef glGenSamplers
+#undef glDeleteSamplers
+#undef glIsSampler
+#undef glBindSampler
+#undef glSamplerParameteri
+#undef glSamplerParameteriv
+#undef glSamplerParameterf
+#undef glSamplerParameterfv
+#undef glGetSamplerParameteriv
+#undef glGetSamplerParameterfv
+#undef glVertexAttribDivisor
+#undef glBindTransformFeedback
+#undef glDeleteTransformFeedbacks
+#undef glGenTransformFeedbacks
+#undef glIsTransformFeedback
+#undef glPauseTransformFeedback
+#undef glResumeTransformFeedback
+#undef glGetProgramBinary
+#undef glProgramBinary
+#undef glProgramParameteri
+#undef glInvalidateFramebuffer
+#undef glInvalidateSubFramebuffer
+#undef glTexStorage2D
+#undef glTexStorage3D
+#undef glGetInternalformativ
+
+#undef glDispatchCompute
+#undef glDispatchComputeIndirect
+#undef glDrawArraysIndirect
+#undef glDrawElementsIndirect
+#undef glFramebufferParameteri
+#undef glGetFramebufferParameteriv
+#undef glGetProgramInterfaceiv
+#undef glGetProgramResourceIndex
+#undef glGetProgramResourceName
+#undef glGetProgramResourceiv
+#undef glGetProgramResourceLocation
+#undef glUseProgramStages
+#undef glActiveShaderProgram
+#undef glCreateShaderProgramv
+#undef glBindProgramPipeline
+#undef glDeleteProgramPipelines
+#undef glGenProgramPipelines
+#undef glIsProgramPipeline
+#undef glGetProgramPipelineiv
+#undef glProgramUniform1i
+#undef glProgramUniform2i
+#undef glProgramUniform3i
+#undef glProgramUniform4i
+#undef glProgramUniform1ui
+#undef glProgramUniform2ui
+#undef glProgramUniform3ui
+#undef glProgramUniform4ui
+#undef glProgramUniform1f
+#undef glProgramUniform2f
+#undef glProgramUniform3f
+#undef glProgramUniform4f
+#undef glProgramUniform1iv
+#undef glProgramUniform2iv
+#undef glProgramUniform3iv
+#undef glProgramUniform4iv
+#undef glProgramUniform1uiv
+#undef glProgramUniform2uiv
+#undef glProgramUniform3uiv
+#undef glProgramUniform4uiv
+#undef glProgramUniform1fv
+#undef glProgramUniform2fv
+#undef glProgramUniform3fv
+#undef glProgramUniform4fv
+#undef glProgramUniformMatrix2fv
+#undef glProgramUniformMatrix3fv
+#undef glProgramUniformMatrix4fv
+#undef glProgramUniformMatrix2x3fv
+#undef glProgramUniformMatrix3x2fv
+#undef glProgramUniformMatrix2x4fv
+#undef glProgramUniformMatrix4x2fv
+#undef glProgramUniformMatrix3x4fv
+#undef glProgramUniformMatrix4x3fv
+#undef glValidateProgramPipeline
+#undef glGetProgramPipelineInfoLog
+#undef glBindImageTexture
+#undef glGetBooleani_v
+#undef glMemoryBarrier
+#undef glMemoryBarrierByRegion
+#undef glTexStorage2DMultisample
+#undef glGetMultisamplefv
+#undef glSampleMaski
+#undef glGetTexLevelParameteriv
+#undef glGetTexLevelParameterfv
+#undef glBindVertexBuffer
+#undef glVertexAttribFormat
+#undef glVertexAttribIFormat
+#undef glVertexAttribBinding
+#undef glVertexBindingDivisor
+
+class Q_GUI_EXPORT QOpenGLExtraFunctions : public QOpenGLFunctions
+{
+ Q_DECLARE_PRIVATE(QOpenGLExtraFunctions)
+
+public:
+ QOpenGLExtraFunctions();
+ QOpenGLExtraFunctions(QOpenGLContext *context);
+ ~QOpenGLExtraFunctions() {}
+
+ // GLES3
+ void glReadBuffer(GLenum mode);
+ void glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);
+ void glTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);
+ void glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);
+ void glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+ void glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
+ void glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
+ void glGenQueries(GLsizei n, GLuint *ids);
+ void glDeleteQueries(GLsizei n, const GLuint *ids);
+ GLboolean glIsQuery(GLuint id);
+ void glBeginQuery(GLenum target, GLuint id);
+ void glEndQuery(GLenum target);
+ void glGetQueryiv(GLenum target, GLenum pname, GLint *params);
+ void glGetQueryObjectuiv(GLuint id, GLenum pname, GLuint *params);
+ GLboolean glUnmapBuffer(GLenum target);
+ void glGetBufferPointerv(GLenum target, GLenum pname, void **params);
+ void glDrawBuffers(GLsizei n, const GLenum *bufs);
+ void glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+ void glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+ void glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+ void *glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+ void glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length);
+ void glBindVertexArray(GLuint array);
+ void glDeleteVertexArrays(GLsizei n, const GLuint *arrays);
+ void glGenVertexArrays(GLsizei n, GLuint *arrays);
+ GLboolean glIsVertexArray(GLuint array);
+ void glGetIntegeri_v(GLenum target, GLuint index, GLint *data);
+ void glBeginTransformFeedback(GLenum primitiveMode);
+ void glEndTransformFeedback(void);
+ void glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+ void glBindBufferBase(GLenum target, GLuint index, GLuint buffer);
+ void glTransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);
+ void glGetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+ void glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);
+ void glGetVertexAttribIiv(GLuint index, GLenum pname, GLint *params);
+ void glGetVertexAttribIuiv(GLuint index, GLenum pname, GLuint *params);
+ void glVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w);
+ void glVertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+ void glVertexAttribI4iv(GLuint index, const GLint *v);
+ void glVertexAttribI4uiv(GLuint index, const GLuint *v);
+ void glGetUniformuiv(GLuint program, GLint location, GLuint *params);
+ GLint glGetFragDataLocation(GLuint program, const GLchar *name);
+ void glUniform1ui(GLint location, GLuint v0);
+ void glUniform2ui(GLint location, GLuint v0, GLuint v1);
+ void glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void glUniform1uiv(GLint location, GLsizei count, const GLuint *value);
+ void glUniform2uiv(GLint location, GLsizei count, const GLuint *value);
+ void glUniform3uiv(GLint location, GLsizei count, const GLuint *value);
+ void glUniform4uiv(GLint location, GLsizei count, const GLuint *value);
+ void glClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint *value);
+ void glClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint *value);
+ void glClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat *value);
+ void glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
+ const GLubyte *glGetStringi(GLenum name, GLuint index);
+ void glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+ void glGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices);
+ void glGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);
+ GLuint glGetUniformBlockIndex(GLuint program, const GLchar *uniformBlockName);
+ void glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);
+ void glGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);
+ void glUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+ void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
+ void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount);
+ GLsync glFenceSync(GLenum condition, GLbitfield flags);
+ GLboolean glIsSync(GLsync sync);
+ void glDeleteSync(GLsync sync);
+ GLenum glClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void glWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void glGetInteger64v(GLenum pname, GLint64 *data);
+ void glGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+ void glGetInteger64i_v(GLenum target, GLuint index, GLint64 *data);
+ void glGetBufferParameteri64v(GLenum target, GLenum pname, GLint64 *params);
+ void glGenSamplers(GLsizei count, GLuint *samplers);
+ void glDeleteSamplers(GLsizei count, const GLuint *samplers);
+ GLboolean glIsSampler(GLuint sampler);
+ void glBindSampler(GLuint unit, GLuint sampler);
+ void glSamplerParameteri(GLuint sampler, GLenum pname, GLint param);
+ void glSamplerParameteriv(GLuint sampler, GLenum pname, const GLint *param);
+ void glSamplerParameterf(GLuint sampler, GLenum pname, GLfloat param);
+ void glSamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat *param);
+ void glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLint *params);
+ void glGetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat *params);
+ void glVertexAttribDivisor(GLuint index, GLuint divisor);
+ void glBindTransformFeedback(GLenum target, GLuint id);
+ void glDeleteTransformFeedbacks(GLsizei n, const GLuint *ids);
+ void glGenTransformFeedbacks(GLsizei n, GLuint *ids);
+ GLboolean glIsTransformFeedback(GLuint id);
+ void glPauseTransformFeedback(void);
+ void glResumeTransformFeedback(void);
+ void glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+ void glProgramBinary(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length);
+ void glProgramParameteri(GLuint program, GLenum pname, GLint value);
+ void glInvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments);
+ void glInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height);
+ void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+ void glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+ void glGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+
+ // GLES 3.1
+ void glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
+ void glDispatchComputeIndirect(GLintptr indirect);
+ void glDrawArraysIndirect(GLenum mode, const void *indirect);
+ void glDrawElementsIndirect(GLenum mode, GLenum type, const void *indirect);
+ void glFramebufferParameteri(GLenum target, GLenum pname, GLint param);
+ void glGetFramebufferParameteriv(GLenum target, GLenum pname, GLint *params);
+ void glGetProgramInterfaceiv(GLuint program, GLenum programInterface, GLenum pname, GLint *params);
+ GLuint glGetProgramResourceIndex(GLuint program, GLenum programInterface, const GLchar *name);
+ void glGetProgramResourceName(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name);
+ void glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params);
+ GLint glGetProgramResourceLocation(GLuint program, GLenum programInterface, const GLchar *name);
+ void glUseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program);
+ void glActiveShaderProgram(GLuint pipeline, GLuint program);
+ GLuint glCreateShaderProgramv(GLenum type, GLsizei count, const GLchar *const*strings);
+ void glBindProgramPipeline(GLuint pipeline);
+ void glDeleteProgramPipelines(GLsizei n, const GLuint *pipelines);
+ void glGenProgramPipelines(GLsizei n, GLuint *pipelines);
+ GLboolean glIsProgramPipeline(GLuint pipeline);
+ void glGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint *params);
+ void glProgramUniform1i(GLuint program, GLint location, GLint v0);
+ void glProgramUniform2i(GLuint program, GLint location, GLint v0, GLint v1);
+ void glProgramUniform3i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+ void glProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+ void glProgramUniform1ui(GLuint program, GLint location, GLuint v0);
+ void glProgramUniform2ui(GLuint program, GLint location, GLuint v0, GLuint v1);
+ void glProgramUniform3ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void glProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void glProgramUniform1f(GLuint program, GLint location, GLfloat v0);
+ void glProgramUniform2f(GLuint program, GLint location, GLfloat v0, GLfloat v1);
+ void glProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+ void glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+ void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void glProgramUniform1uiv(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void glProgramUniform2uiv(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void glProgramUniform3uiv(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void glProgramUniform4uiv(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void glProgramUniform1fv(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void glProgramUniform2fv(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void glProgramUniform3fv(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void glProgramUniform4fv(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void glProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void glValidateProgramPipeline(GLuint pipeline);
+ void glGetProgramPipelineInfoLog(GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+ void glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+ void glGetBooleani_v(GLenum target, GLuint index, GLboolean *data);
+ void glMemoryBarrier(GLbitfield barriers);
+ void glMemoryBarrierByRegion(GLbitfield barriers);
+ void glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+ void glGetMultisamplefv(GLenum pname, GLuint index, GLfloat *val);
+ void glSampleMaski(GLuint maskNumber, GLbitfield mask);
+ void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params);
+ void glGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params);
+ void glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
+ void glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
+ void glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
+ void glVertexAttribBinding(GLuint attribindex, GLuint bindingindex);
+ void glVertexBindingDivisor(GLuint bindingindex, GLuint divisor);
+
+private:
+ static bool isInitialized(const QOpenGLExtraFunctionsPrivate *d) { return d != 0; }
+};
+
+class QOpenGLExtraFunctionsPrivate : public QOpenGLFunctionsPrivate
+{
+public:
+ QOpenGLExtraFunctionsPrivate(QOpenGLContext *ctx);
+
+ // GLES3
+ void (QOPENGLF_APIENTRYP ReadBuffer)(GLenum mode);
+ void (QOPENGLF_APIENTRYP DrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);
+ void (QOPENGLF_APIENTRYP TexImage3D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);
+ void (QOPENGLF_APIENTRYP TexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);
+ void (QOPENGLF_APIENTRYP CopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP CompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
+ void (QOPENGLF_APIENTRYP CompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
+ void (QOPENGLF_APIENTRYP GenQueries)(GLsizei n, GLuint *ids);
+ void (QOPENGLF_APIENTRYP DeleteQueries)(GLsizei n, const GLuint *ids);
+ GLboolean (QOPENGLF_APIENTRYP IsQuery)(GLuint id);
+ void (QOPENGLF_APIENTRYP BeginQuery)(GLenum target, GLuint id);
+ void (QOPENGLF_APIENTRYP EndQuery)(GLenum target);
+ void (QOPENGLF_APIENTRYP GetQueryiv)(GLenum target, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetQueryObjectuiv)(GLuint id, GLenum pname, GLuint *params);
+ GLboolean (QOPENGLF_APIENTRYP UnmapBuffer)(GLenum target);
+ void (QOPENGLF_APIENTRYP GetBufferPointerv)(GLenum target, GLenum pname, void **params);
+ void (QOPENGLF_APIENTRYP DrawBuffers)(GLsizei n, const GLenum *bufs);
+ void (QOPENGLF_APIENTRYP UniformMatrix2x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix3x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix2x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix4x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix3x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP UniformMatrix4x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP BlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+ void (QOPENGLF_APIENTRYP RenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP FramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+ void *(QOPENGLF_APIENTRYP MapBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+ void (QOPENGLF_APIENTRYP FlushMappedBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length);
+ void (QOPENGLF_APIENTRYP BindVertexArray)(GLuint array);
+ void (QOPENGLF_APIENTRYP DeleteVertexArrays)(GLsizei n, const GLuint *arrays);
+ void (QOPENGLF_APIENTRYP GenVertexArrays)(GLsizei n, GLuint *arrays);
+ GLboolean (QOPENGLF_APIENTRYP IsVertexArray)(GLuint array);
+ void (QOPENGLF_APIENTRYP GetIntegeri_v)(GLenum target, GLuint index, GLint *data);
+ void (QOPENGLF_APIENTRYP BeginTransformFeedback)(GLenum primitiveMode);
+ void (QOPENGLF_APIENTRYP EndTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP BindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+ void (QOPENGLF_APIENTRYP BindBufferBase)(GLenum target, GLuint index, GLuint buffer);
+ void (QOPENGLF_APIENTRYP TransformFeedbackVaryings)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);
+ void (QOPENGLF_APIENTRYP GetTransformFeedbackVarying)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+ void (QOPENGLF_APIENTRYP VertexAttribIPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);
+ void (QOPENGLF_APIENTRYP GetVertexAttribIiv)(GLuint index, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetVertexAttribIuiv)(GLuint index, GLenum pname, GLuint *params);
+ void (QOPENGLF_APIENTRYP VertexAttribI4i)(GLuint index, GLint x, GLint y, GLint z, GLint w);
+ void (QOPENGLF_APIENTRYP VertexAttribI4ui)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+ void (QOPENGLF_APIENTRYP VertexAttribI4iv)(GLuint index, const GLint *v);
+ void (QOPENGLF_APIENTRYP VertexAttribI4uiv)(GLuint index, const GLuint *v);
+ void (QOPENGLF_APIENTRYP GetUniformuiv)(GLuint program, GLint location, GLuint *params);
+ GLint (QOPENGLF_APIENTRYP GetFragDataLocation)(GLuint program, const GLchar *name);
+ void (QOPENGLF_APIENTRYP Uniform1ui)(GLint location, GLuint v0);
+ void (QOPENGLF_APIENTRYP Uniform2ui)(GLint location, GLuint v0, GLuint v1);
+ void (QOPENGLF_APIENTRYP Uniform3ui)(GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void (QOPENGLF_APIENTRYP Uniform4ui)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void (QOPENGLF_APIENTRYP Uniform1uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform2uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform3uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP Uniform4uiv)(GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferuiv)(GLenum buffer, GLint drawbuffer, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ClearBufferfv)(GLenum buffer, GLint drawbuffer, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ClearBufferfi)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
+ const GLubyte *(QOPENGLF_APIENTRYP GetStringi)(GLenum name, GLuint index);
+ void (QOPENGLF_APIENTRYP CopyBufferSubData)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+ void (QOPENGLF_APIENTRYP GetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices);
+ void (QOPENGLF_APIENTRYP GetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);
+ GLuint (QOPENGLF_APIENTRYP GetUniformBlockIndex)(GLuint program, const GLchar *uniformBlockName);
+ void (QOPENGLF_APIENTRYP GetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);
+ void (QOPENGLF_APIENTRYP UniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+ void (QOPENGLF_APIENTRYP DrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
+ void (QOPENGLF_APIENTRYP DrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount);
+ GLsync (QOPENGLF_APIENTRYP FenceSync)(GLenum condition, GLbitfield flags);
+ GLboolean (QOPENGLF_APIENTRYP IsSync)(GLsync sync);
+ void (QOPENGLF_APIENTRYP DeleteSync)(GLsync sync);
+ GLenum (QOPENGLF_APIENTRYP ClientWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void (QOPENGLF_APIENTRYP WaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
+ void (QOPENGLF_APIENTRYP GetInteger64v)(GLenum pname, GLint64 *data);
+ void (QOPENGLF_APIENTRYP GetSynciv)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+ void (QOPENGLF_APIENTRYP GetInteger64i_v)(GLenum target, GLuint index, GLint64 *data);
+ void (QOPENGLF_APIENTRYP GetBufferParameteri64v)(GLenum target, GLenum pname, GLint64 *params);
+ void (QOPENGLF_APIENTRYP GenSamplers)(GLsizei count, GLuint *samplers);
+ void (QOPENGLF_APIENTRYP DeleteSamplers)(GLsizei count, const GLuint *samplers);
+ GLboolean (QOPENGLF_APIENTRYP IsSampler)(GLuint sampler);
+ void (QOPENGLF_APIENTRYP BindSampler)(GLuint unit, GLuint sampler);
+ void (QOPENGLF_APIENTRYP SamplerParameteri)(GLuint sampler, GLenum pname, GLint param);
+ void (QOPENGLF_APIENTRYP SamplerParameteriv)(GLuint sampler, GLenum pname, const GLint *param);
+ void (QOPENGLF_APIENTRYP SamplerParameterf)(GLuint sampler, GLenum pname, GLfloat param);
+ void (QOPENGLF_APIENTRYP SamplerParameterfv)(GLuint sampler, GLenum pname, const GLfloat *param);
+ void (QOPENGLF_APIENTRYP GetSamplerParameteriv)(GLuint sampler, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetSamplerParameterfv)(GLuint sampler, GLenum pname, GLfloat *params);
+ void (QOPENGLF_APIENTRYP VertexAttribDivisor)(GLuint index, GLuint divisor);
+ void (QOPENGLF_APIENTRYP BindTransformFeedback)(GLenum target, GLuint id);
+ void (QOPENGLF_APIENTRYP DeleteTransformFeedbacks)(GLsizei n, const GLuint *ids);
+ void (QOPENGLF_APIENTRYP GenTransformFeedbacks)(GLsizei n, GLuint *ids);
+ GLboolean (QOPENGLF_APIENTRYP IsTransformFeedback)(GLuint id);
+ void (QOPENGLF_APIENTRYP PauseTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP ResumeTransformFeedback)(void);
+ void (QOPENGLF_APIENTRYP GetProgramBinary)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+ void (QOPENGLF_APIENTRYP ProgramBinary)(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length);
+ void (QOPENGLF_APIENTRYP ProgramParameteri)(GLuint program, GLenum pname, GLint value);
+ void (QOPENGLF_APIENTRYP InvalidateFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum *attachments);
+ void (QOPENGLF_APIENTRYP InvalidateSubFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP TexStorage2D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+ void (QOPENGLF_APIENTRYP TexStorage3D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+ void (QOPENGLF_APIENTRYP GetInternalformativ)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+
+ // GLES 3.1
+ void (QOPENGLF_APIENTRYP DispatchCompute)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
+ void (QOPENGLF_APIENTRYP DispatchComputeIndirect)(GLintptr indirect);
+ void (QOPENGLF_APIENTRYP DrawArraysIndirect)(GLenum mode, const void *indirect);
+ void (QOPENGLF_APIENTRYP DrawElementsIndirect)(GLenum mode, GLenum type, const void *indirect);
+ void (QOPENGLF_APIENTRYP FramebufferParameteri)(GLenum target, GLenum pname, GLint param);
+ void (QOPENGLF_APIENTRYP GetFramebufferParameteriv)(GLenum target, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetProgramInterfaceiv)(GLuint program, GLenum programInterface, GLenum pname, GLint *params);
+ GLuint (QOPENGLF_APIENTRYP GetProgramResourceIndex)(GLuint program, GLenum programInterface, const GLchar *name);
+ void (QOPENGLF_APIENTRYP GetProgramResourceName)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name);
+ void (QOPENGLF_APIENTRYP GetProgramResourceiv)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params);
+ GLint (QOPENGLF_APIENTRYP GetProgramResourceLocation)(GLuint program, GLenum programInterface, const GLchar *name);
+ void (QOPENGLF_APIENTRYP UseProgramStages)(GLuint pipeline, GLbitfield stages, GLuint program);
+ void (QOPENGLF_APIENTRYP ActiveShaderProgram)(GLuint pipeline, GLuint program);
+ GLuint (QOPENGLF_APIENTRYP CreateShaderProgramv)(GLenum type, GLsizei count, const GLchar *const*strings);
+ void (QOPENGLF_APIENTRYP BindProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP DeleteProgramPipelines)(GLsizei n, const GLuint *pipelines);
+ void (QOPENGLF_APIENTRYP GenProgramPipelines)(GLsizei n, GLuint *pipelines);
+ GLboolean (QOPENGLF_APIENTRYP IsProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP GetProgramPipelineiv)(GLuint pipeline, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP ProgramUniform1i)(GLuint program, GLint location, GLint v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2i)(GLuint program, GLint location, GLint v0, GLint v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1ui)(GLuint program, GLint location, GLuint v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2ui)(GLuint program, GLint location, GLuint v0, GLuint v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1f)(GLuint program, GLint location, GLfloat v0);
+ void (QOPENGLF_APIENTRYP ProgramUniform2f)(GLuint program, GLint location, GLfloat v0, GLfloat v1);
+ void (QOPENGLF_APIENTRYP ProgramUniform3f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+ void (QOPENGLF_APIENTRYP ProgramUniform4f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+ void (QOPENGLF_APIENTRYP ProgramUniform1iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4iv)(GLuint program, GLint location, GLsizei count, const GLint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform1uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4uiv)(GLuint program, GLint location, GLsizei count, const GLuint *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform1fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform2fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform3fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniform4fv)(GLuint program, GLint location, GLsizei count, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix2x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix3x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ProgramUniformMatrix4x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+ void (QOPENGLF_APIENTRYP ValidateProgramPipeline)(GLuint pipeline);
+ void (QOPENGLF_APIENTRYP GetProgramPipelineInfoLog)(GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+ void (QOPENGLF_APIENTRYP BindImageTexture)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+ void (QOPENGLF_APIENTRYP GetBooleani_v)(GLenum target, GLuint index, GLboolean *data);
+ void (QOPENGLF_APIENTRYP MemoryBarrierFunc)(GLbitfield barriers);
+ void (QOPENGLF_APIENTRYP MemoryBarrierByRegion)(GLbitfield barriers);
+ void (QOPENGLF_APIENTRYP TexStorage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+ void (QOPENGLF_APIENTRYP GetMultisamplefv)(GLenum pname, GLuint index, GLfloat *val);
+ void (QOPENGLF_APIENTRYP SampleMaski)(GLuint maskNumber, GLbitfield mask);
+ void (QOPENGLF_APIENTRYP GetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params);
+ void (QOPENGLF_APIENTRYP GetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params);
+ void (QOPENGLF_APIENTRYP BindVertexBuffer)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
+ void (QOPENGLF_APIENTRYP VertexAttribFormat)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
+ void (QOPENGLF_APIENTRYP VertexAttribIFormat)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
+ void (QOPENGLF_APIENTRYP VertexAttribBinding)(GLuint attribindex, GLuint bindingindex);
+ void (QOPENGLF_APIENTRYP VertexBindingDivisor)(GLuint bindingindex, GLuint divisor);
+};
+
+// GLES 3.0 and 3.1
+
+inline void QOpenGLExtraFunctions::glBeginQuery(GLenum target, GLuint id)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BeginQuery(target, id);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBeginTransformFeedback(GLenum primitiveMode)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BeginTransformFeedback(primitiveMode);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindBufferBase(GLenum target, GLuint index, GLuint buffer)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindBufferBase(target, index, buffer);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindBufferRange(target, index, buffer, offset, size);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindSampler(GLuint unit, GLuint sampler)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindSampler(unit, sampler);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindTransformFeedback(GLenum target, GLuint id)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindTransformFeedback(target, id);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindVertexArray(GLuint array)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindVertexArray(array);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ClearBufferfi(buffer, drawbuffer, depth, stencil);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ClearBufferfv(buffer, drawbuffer, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ClearBufferiv(buffer, drawbuffer, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ClearBufferuiv(buffer, drawbuffer, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLenum QOpenGLExtraFunctions::glClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLenum result = d->ClientWaitSync(sync, flags, timeout);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->CopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->CopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDeleteQueries(GLsizei n, const GLuint * ids)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteQueries(n, ids);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDeleteSamplers(GLsizei count, const GLuint * samplers)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteSamplers(count, samplers);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDeleteSync(GLsync sync)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteSync(sync);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDeleteTransformFeedbacks(GLsizei n, const GLuint * ids)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteTransformFeedbacks(n, ids);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDeleteVertexArrays(GLsizei n, const GLuint * arrays)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteVertexArrays(n, arrays);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawArraysInstanced(mode, first, count, instancecount);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawBuffers(GLsizei n, const GLenum * bufs)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawBuffers(n, bufs);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawElementsInstanced(mode, count, type, indices, instancecount);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawRangeElements(mode, start, end, count, type, indices);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glEndQuery(GLenum target)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->EndQuery(target);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glEndTransformFeedback()
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->EndTransformFeedback();
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLsync QOpenGLExtraFunctions::glFenceSync(GLenum condition, GLbitfield flags)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLsync result = d->FenceSync(condition, flags);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->FlushMappedBufferRange(target, offset, length);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->FramebufferTextureLayer(target, attachment, texture, level, layer);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGenQueries(GLsizei n, GLuint* ids)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GenQueries(n, ids);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGenSamplers(GLsizei count, GLuint* samplers)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GenSamplers(count, samplers);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGenTransformFeedbacks(GLsizei n, GLuint* ids)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GenTransformFeedbacks(n, ids);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGenVertexArrays(GLsizei n, GLuint* arrays)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GenVertexArrays(n, arrays);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetBufferParameteri64v(target, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetBufferPointerv(GLenum target, GLenum pname, void ** params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetBufferPointerv(target, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLint QOpenGLExtraFunctions::glGetFragDataLocation(GLuint program, const GLchar * name)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLint result = d->GetFragDataLocation(program, name);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glGetInteger64i_v(GLenum target, GLuint index, GLint64* data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetInteger64i_v(target, index, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetInteger64v(GLenum pname, GLint64* data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetInteger64v(pname, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetIntegeri_v(GLenum target, GLuint index, GLint* data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetIntegeri_v(target, index, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetInternalformativ(target, internalformat, pname, bufSize, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, void * binary)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramBinary(program, bufSize, length, binaryFormat, binary);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetQueryObjectuiv(id, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetQueryiv(GLenum target, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetQueryiv(target, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetSamplerParameterfv(sampler, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetSamplerParameteriv(sampler, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline const GLubyte * QOpenGLExtraFunctions::glGetStringi(GLenum name, GLuint index)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ const GLubyte * result = d->GetStringi(name, index);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetSynciv(sync, pname, bufSize, length, values);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetTransformFeedbackVarying(program, index, bufSize, length, size, type, name);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLuint QOpenGLExtraFunctions::glGetUniformBlockIndex(GLuint program, const GLchar * uniformBlockName)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLuint result = d->GetUniformBlockIndex(program, uniformBlockName);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint* uniformIndices)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetUniformIndices(program, uniformCount, uniformNames, uniformIndices);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetUniformuiv(GLuint program, GLint location, GLuint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetUniformuiv(program, location, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetVertexAttribIiv(GLuint index, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetVertexAttribIiv(index, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetVertexAttribIuiv(index, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glInvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->InvalidateFramebuffer(target, numAttachments, attachments);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->InvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsQuery(GLuint id)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsQuery(id);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsSampler(GLuint sampler)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsSampler(sampler);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsSync(GLsync sync)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsSync(sync);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsTransformFeedback(GLuint id)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsTransformFeedback(id);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsVertexArray(GLuint array)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsVertexArray(array);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void * QOpenGLExtraFunctions::glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ void *result = d->MapBufferRange(target, offset, length, access);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glPauseTransformFeedback()
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->PauseTransformFeedback();
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramBinary(GLuint program, GLenum binaryFormat, const void * binary, GLsizei length)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramBinary(program, binaryFormat, binary, length);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramParameteri(GLuint program, GLenum pname, GLint value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramParameteri(program, pname, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glReadBuffer(GLenum src)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ReadBuffer(src);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->RenderbufferStorageMultisample(target, samples, internalformat, width, height);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glResumeTransformFeedback()
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ResumeTransformFeedback();
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glSamplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->SamplerParameterf(sampler, pname, param);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glSamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat * param)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->SamplerParameterfv(sampler, pname, param);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glSamplerParameteri(GLuint sampler, GLenum pname, GLint param)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->SamplerParameteri(sampler, pname, param);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glSamplerParameteriv(GLuint sampler, GLenum pname, const GLint * param)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->SamplerParameteriv(sampler, pname, param);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TexStorage2D(target, levels, internalformat, width, height);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TexStorage3D(target, levels, internalformat, width, height, depth);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TransformFeedbackVaryings(program, count, varyings, bufferMode);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform1ui(GLint location, GLuint v0)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform1ui(location, v0);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform1uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform1uiv(location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform2ui(GLint location, GLuint v0, GLuint v1)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform2ui(location, v0, v1);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform2uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform2uiv(location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform3ui(location, v0, v1, v2);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform3uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform3uiv(location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform4ui(location, v0, v1, v2, v3);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniform4uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->Uniform4uiv(location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix2x3fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix2x4fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix3x2fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix3x4fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix4x2fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UniformMatrix4x3fv(location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLboolean QOpenGLExtraFunctions::glUnmapBuffer(GLenum target)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->UnmapBuffer(target);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribDivisor(GLuint index, GLuint divisor)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribDivisor(index, divisor);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribI4i(index, x, y, z, w);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribI4iv(GLuint index, const GLint * v)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribI4iv(index, v);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribI4ui(index, x, y, z, w);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribI4uiv(GLuint index, const GLuint * v)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribI4uiv(index, v);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribIPointer(index, size, type, stride, pointer);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->WaitSync(sync, flags, timeout);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glActiveShaderProgram(GLuint pipeline, GLuint program)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ActiveShaderProgram(pipeline, program);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindImageTexture(unit, texture, level, layered, layer, access, format);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindProgramPipeline(GLuint pipeline)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindProgramPipeline(pipeline);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->BindVertexBuffer(bindingindex, buffer, offset, stride);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLuint QOpenGLExtraFunctions::glCreateShaderProgramv(GLenum type, GLsizei count, const GLchar *const* strings)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLuint result = d->CreateShaderProgramv(type, count, strings);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glDeleteProgramPipelines(GLsizei n, const GLuint * pipelines)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DeleteProgramPipelines(n, pipelines);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DispatchCompute(num_groups_x, num_groups_y, num_groups_z);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDispatchComputeIndirect(GLintptr indirect)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DispatchComputeIndirect(indirect);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawArraysIndirect(GLenum mode, const void * indirect)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawArraysIndirect(mode, indirect);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glDrawElementsIndirect(GLenum mode, GLenum type, const void * indirect)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->DrawElementsIndirect(mode, type, indirect);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glFramebufferParameteri(GLenum target, GLenum pname, GLint param)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->FramebufferParameteri(target, pname, param);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGenProgramPipelines(GLsizei n, GLuint* pipelines)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GenProgramPipelines(n, pipelines);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetBooleani_v(GLenum target, GLuint index, GLboolean* data)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetBooleani_v(target, index, data);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetFramebufferParameteriv(GLenum target, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetFramebufferParameteriv(target, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetMultisamplefv(GLenum pname, GLuint index, GLfloat* val)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetMultisamplefv(pname, index, val);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramInterfaceiv(GLuint program, GLenum programInterface, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramInterfaceiv(program, programInterface, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramPipelineInfoLog(GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramPipelineInfoLog(pipeline, bufSize, length, infoLog);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramPipelineiv(pipeline, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLuint QOpenGLExtraFunctions::glGetProgramResourceIndex(GLuint program, GLenum programInterface, const GLchar * name)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLuint result = d->GetProgramResourceIndex(program, programInterface, name);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline GLint QOpenGLExtraFunctions::glGetProgramResourceLocation(GLuint program, GLenum programInterface, const GLchar * name)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLint result = d->GetProgramResourceLocation(program, programInterface, name);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramResourceName(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei* length, GLchar* name)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramResourceName(program, programInterface, index, bufSize, length, name);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum * props, GLsizei bufSize, GLsizei* length, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetProgramResourceiv(program, programInterface, index, propCount, props, bufSize, length, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetTexLevelParameterfv(target, level, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->GetTexLevelParameteriv(target, level, pname, params);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline GLboolean QOpenGLExtraFunctions::glIsProgramPipeline(GLuint pipeline)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ GLboolean result = d->IsProgramPipeline(pipeline);
+ Q_OPENGL_FUNCTIONS_DEBUG
+ return result;
+}
+
+inline void QOpenGLExtraFunctions::glMemoryBarrier(GLbitfield barriers)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->MemoryBarrierFunc(barriers);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glMemoryBarrierByRegion(GLbitfield barriers)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->MemoryBarrierByRegion(barriers);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1f(GLuint program, GLint location, GLfloat v0)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1f(program, location, v0);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1fv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1i(GLuint program, GLint location, GLint v0)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1i(program, location, v0);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1iv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1ui(GLuint program, GLint location, GLuint v0)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1ui(program, location, v0);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform1uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform1uiv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2f(GLuint program, GLint location, GLfloat v0, GLfloat v1)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2f(program, location, v0, v1);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2fv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2i(GLuint program, GLint location, GLint v0, GLint v1)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2i(program, location, v0, v1);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2iv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2ui(GLuint program, GLint location, GLuint v0, GLuint v1)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2ui(program, location, v0, v1);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform2uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform2uiv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3f(program, location, v0, v1, v2);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3fv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3i(program, location, v0, v1, v2);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3iv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3ui(program, location, v0, v1, v2);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform3uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform3uiv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4f(program, location, v0, v1, v2, v3);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4fv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4i(program, location, v0, v1, v2, v3);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4iv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4ui(program, location, v0, v1, v2, v3);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniform4uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniform4uiv(program, location, count, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix2fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix2x3fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix2x4fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix3fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix3x2fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix3x4fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix4fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix4x2fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ProgramUniformMatrix4x3fv(program, location, count, transpose, value);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glSampleMaski(GLuint maskNumber, GLbitfield mask)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->SampleMaski(maskNumber, mask);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->TexStorage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glUseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->UseProgramStages(pipeline, stages, program);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glValidateProgramPipeline(GLuint pipeline)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->ValidateProgramPipeline(pipeline);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribBinding(GLuint attribindex, GLuint bindingindex)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribBinding(attribindex, bindingindex);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribFormat(attribindex, size, type, normalized, relativeoffset);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexAttribIFormat(attribindex, size, type, relativeoffset);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+inline void QOpenGLExtraFunctions::glVertexBindingDivisor(GLuint bindingindex, GLuint divisor)
+{
+ Q_D(QOpenGLExtraFunctions);
+ Q_ASSERT(QOpenGLExtraFunctions::isInitialized(d));
+ d->VertexBindingDivisor(bindingindex, divisor);
+ Q_OPENGL_FUNCTIONS_DEBUG
+}
+
+QT_END_NAMESPACE
+
+#endif // QT_NO_OPENGL
+
+#endif
diff --git a/src/gui/opengl/qopenglframebufferobject.cpp b/src/gui/opengl/qopenglframebufferobject.cpp
index 8d298496df..3596591cf6 100644
--- a/src/gui/opengl/qopenglframebufferobject.cpp
+++ b/src/gui/opengl/qopenglframebufferobject.cpp
@@ -166,7 +166,7 @@ void QOpenGLFramebufferObjectFormat::detach()
the format of an OpenGL framebuffer object.
By default the format specifies a non-multisample framebuffer object with no
- attachments, texture target \c GL_TEXTURE_2D, and internal format \c GL_RGBA8.
+ depth/stencil attachments, texture target \c GL_TEXTURE_2D, and internal format \c GL_RGBA8.
On OpenGL/ES systems, the default internal format is \c GL_RGBA.
\sa samples(), attachment(), internalTextureFormat()
@@ -436,10 +436,10 @@ namespace
}
}
-void QOpenGLFramebufferObjectPrivate::init(QOpenGLFramebufferObject *, const QSize &sz,
- QOpenGLFramebufferObject::Attachment attachment,
- GLenum texture_target, GLenum internal_format,
- GLint samples, bool mipmap)
+void QOpenGLFramebufferObjectPrivate::init(QOpenGLFramebufferObject *, const QSize &size,
+ QOpenGLFramebufferObject::Attachment attachment,
+ GLenum texture_target, GLenum internal_format,
+ GLint samples, bool mipmap)
{
QOpenGLContext *ctx = QOpenGLContext::currentContext();
@@ -458,9 +458,13 @@ void QOpenGLFramebufferObjectPrivate::init(QOpenGLFramebufferObject *, const QSi
samples = qBound(0, int(samples), int(maxSamples));
}
+ colorAttachments.append(ColorAttachment(size, internal_format));
+
+ dsSize = size;
+
samples = qMax(0, samples);
requestedSamples = samples;
- size = sz;
+
target = texture_target;
QT_RESET_GLERROR(); // reset error state
@@ -471,64 +475,30 @@ void QOpenGLFramebufferObjectPrivate::init(QOpenGLFramebufferObject *, const QSi
QOpenGLContextPrivate::get(ctx)->qgl_current_fbo_invalid = true;
- GLuint color_buffer = 0;
-
QT_CHECK_GLERROR();
- // init texture
- if (samples == 0) {
- initTexture(texture_target, internal_format, size, mipmap);
- } else {
- GLenum storageFormat = internal_format;
- // ES requires a sized format. The older desktop extension does not. Correct the format on ES.
- if (ctx->isOpenGLES() && internal_format == GL_RGBA) {
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::Sized8Formats))
- storageFormat = GL_RGBA8;
- else
- storageFormat = GL_RGBA4;
- }
-
- mipmap = false;
- funcs.glGenRenderbuffers(1, &color_buffer);
- funcs.glBindRenderbuffer(GL_RENDERBUFFER, color_buffer);
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, storageFormat, size.width(), size.height());
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_RENDERBUFFER, color_buffer);
- QT_CHECK_GLERROR();
- valid = checkFramebufferStatus(ctx);
-
- if (valid) {
- // Query the actual number of samples. This can be greater than the requested
- // value since the typically supported values are 0, 4, 8, ..., and the
- // requests are mapped to the next supported value.
- funcs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
- color_buffer_guard = new QOpenGLSharedResourceGuard(ctx, color_buffer, freeRenderbufferFunc);
- }
- }
format.setTextureTarget(target);
- format.setSamples(int(samples));
format.setInternalTextureFormat(internal_format);
format.setMipmap(mipmap);
- initAttachments(ctx, attachment);
+ if (samples == 0)
+ initTexture(0);
+ else
+ initColorBuffer(0, &samples);
+
+ format.setSamples(int(samples));
- if (valid) {
+ initDepthStencilAttachments(ctx, attachment);
+
+ if (valid)
fbo_guard = new QOpenGLSharedResourceGuard(ctx, fbo, freeFramebufferFunc);
- } else {
- if (color_buffer_guard) {
- color_buffer_guard->free();
- color_buffer_guard = 0;
- } else if (texture_guard) {
- texture_guard->free();
- texture_guard = 0;
- }
+ else
funcs.glDeleteFramebuffers(1, &fbo);
- }
+
QT_CHECK_GLERROR();
}
-void QOpenGLFramebufferObjectPrivate::initTexture(GLenum target, GLenum internal_format,
- const QSize &size, bool mipmap)
+void QOpenGLFramebufferObjectPrivate::initTexture(int idx)
{
QOpenGLContext *ctx = QOpenGLContext::currentContext();
GLuint texture = 0;
@@ -541,37 +511,76 @@ void QOpenGLFramebufferObjectPrivate::initTexture(GLenum target, GLenum internal
funcs.glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
funcs.glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ ColorAttachment &color(colorAttachments[idx]);
+
GLuint pixelType = GL_UNSIGNED_BYTE;
- if (internal_format == GL_RGB10_A2 || internal_format == GL_RGB10)
+ if (color.internalFormat == GL_RGB10_A2 || color.internalFormat == GL_RGB10)
pixelType = GL_UNSIGNED_INT_2_10_10_10_REV;
- funcs.glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0,
+ funcs.glTexImage2D(target, 0, color.internalFormat, color.size.width(), color.size.height(), 0,
GL_RGBA, pixelType, NULL);
- if (mipmap) {
- int width = size.width();
- int height = size.height();
+ if (format.mipmap()) {
+ int width = color.size.width();
+ int height = color.size.height();
int level = 0;
while (width > 1 || height > 1) {
width = qMax(1, width >> 1);
height = qMax(1, height >> 1);
++level;
- funcs.glTexImage2D(target, level, internal_format, width, height, 0,
+ funcs.glTexImage2D(target, level, color.internalFormat, width, height, 0,
GL_RGBA, pixelType, NULL);
}
}
- funcs.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
+ funcs.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + idx,
target, texture, 0);
QT_CHECK_GLERROR();
funcs.glBindTexture(target, 0);
valid = checkFramebufferStatus(ctx);
- if (valid)
- texture_guard = new QOpenGLSharedResourceGuard(ctx, texture, freeTextureFunc);
- else
+ if (valid) {
+ color.guard = new QOpenGLSharedResourceGuard(ctx, texture, freeTextureFunc);
+ } else {
funcs.glDeleteTextures(1, &texture);
+ }
+}
+
+void QOpenGLFramebufferObjectPrivate::initColorBuffer(int idx, GLint *samples)
+{
+ QOpenGLContext *ctx = QOpenGLContext::currentContext();
+ GLuint color_buffer = 0;
+
+ ColorAttachment &color(colorAttachments[idx]);
+
+ GLenum storageFormat = color.internalFormat;
+ // ES requires a sized format. The older desktop extension does not. Correct the format on ES.
+ if (ctx->isOpenGLES() && color.internalFormat == GL_RGBA) {
+ if (funcs.hasOpenGLExtension(QOpenGLExtensions::Sized8Formats))
+ storageFormat = GL_RGBA8;
+ else
+ storageFormat = GL_RGBA4;
+ }
+
+ funcs.glGenRenderbuffers(1, &color_buffer);
+ funcs.glBindRenderbuffer(GL_RENDERBUFFER, color_buffer);
+ funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, *samples, storageFormat, color.size.width(), color.size.height());
+ funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + idx,
+ GL_RENDERBUFFER, color_buffer);
+
+ QT_CHECK_GLERROR();
+ valid = checkFramebufferStatus(ctx);
+ if (valid) {
+ // Query the actual number of samples. This can be greater than the requested
+ // value since the typically supported values are 0, 4, 8, ..., and the
+ // requests are mapped to the next supported value.
+ funcs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, samples);
+ color.guard = new QOpenGLSharedResourceGuard(ctx, color_buffer, freeRenderbufferFunc);
+ } else {
+ funcs.glDeleteRenderbuffers(1, &color_buffer);
+ }
}
-void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpenGLFramebufferObject::Attachment attachment)
+void QOpenGLFramebufferObjectPrivate::initDepthStencilAttachments(QOpenGLContext *ctx,
+ QOpenGLFramebufferObject::Attachment attachment)
{
// Use the same sample count for all attachments. format.samples() already contains
// the actual number of samples for the color attachment and is not suitable. Use
@@ -608,10 +617,10 @@ void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpen
Q_ASSERT(funcs.glIsRenderbuffer(depth_buffer));
if (samples != 0 && funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample))
funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH24_STENCIL8, size.width(), size.height());
+ GL_DEPTH24_STENCIL8, dsSize.width(), dsSize.height());
else
funcs.glRenderbufferStorage(GL_RENDERBUFFER,
- GL_DEPTH24_STENCIL8, size.width(), size.height());
+ GL_DEPTH24_STENCIL8, dsSize.width(), dsSize.height());
stencil_buffer = depth_buffer;
funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
@@ -636,25 +645,25 @@ void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpen
if (ctx->isOpenGLES()) {
if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24))
funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT24, size.width(), size.height());
+ GL_DEPTH_COMPONENT24, dsSize.width(), dsSize.height());
else
funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT16, size.width(), size.height());
+ GL_DEPTH_COMPONENT16, dsSize.width(), dsSize.height());
} else {
funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT, size.width(), size.height());
+ GL_DEPTH_COMPONENT, dsSize.width(), dsSize.height());
}
} else {
if (ctx->isOpenGLES()) {
if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24)) {
funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24,
- size.width(), size.height());
+ dsSize.width(), dsSize.height());
} else {
funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16,
- size.width(), size.height());
+ dsSize.width(), dsSize.height());
}
} else {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, size.width(), size.height());
+ funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, dsSize.width(), dsSize.height());
}
}
funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
@@ -678,9 +687,9 @@ void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpen
#endif
if (samples != 0 && funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample))
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, storage, size.width(), size.height());
+ funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, storage, dsSize.width(), dsSize.height());
else
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, storage, size.width(), size.height());
+ funcs.glRenderbufferStorage(GL_RENDERBUFFER, storage, dsSize.width(), dsSize.height());
funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, stencil_buffer);
@@ -756,6 +765,11 @@ void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpen
format, and will be bound to the \c GL_COLOR_ATTACHMENT0
attachment in the framebuffer object.
+ Multiple render targets are also supported, in case the OpenGL
+ implementation supports this. Here there will be multiple textures (or, in
+ case of multisampling, renderbuffers) present and each of them will get
+ attached to \c GL_COLOR_ATTACHMENT0, \c 1, \c 2, ...
+
If you want to use a framebuffer object with multisampling enabled
as a texture, you first need to copy from it to a regular framebuffer
object using QOpenGLContext::blitFramebuffer().
@@ -785,6 +799,16 @@ void QOpenGLFramebufferObjectPrivate::initAttachments(QOpenGLContext *ctx, QOpen
\sa attachment()
*/
+static inline GLenum effectiveInternalFormat(GLenum internalFormat)
+{
+ if (!internalFormat)
+#ifdef QT_OPENGL_ES_2
+ internalFormat = GL_RGBA;
+#else
+ internalFormat = QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
+#endif
+ return internalFormat;
+}
/*! \fn QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, GLenum target)
@@ -814,13 +838,7 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, GLenum tar
: d_ptr(new QOpenGLFramebufferObjectPrivate)
{
Q_D(QOpenGLFramebufferObject);
- d->init(this, size, NoAttachment, target,
-#ifndef QT_OPENGL_ES_2
- QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8
-#else
- GL_RGBA
-#endif
- );
+ d->init(this, size, NoAttachment, target, effectiveInternalFormat(0));
}
/*! \overload
@@ -834,13 +852,7 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, GLenum
: d_ptr(new QOpenGLFramebufferObjectPrivate)
{
Q_D(QOpenGLFramebufferObject);
- d->init(this, QSize(width, height), NoAttachment, target,
-#ifndef QT_OPENGL_ES_2
- QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8
-#else
- GL_RGBA
-#endif
- );
+ d->init(this, QSize(width, height), NoAttachment, target, effectiveInternalFormat(0));
}
/*! \overload
@@ -877,7 +889,7 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, const
buffer of the given \a width and \a height.
The \a attachment parameter describes the depth/stencil buffer
- configuration, \a target the texture target and \a internal_format
+ configuration, \a target the texture target and \a internalFormat
the internal texture format. The default texture target is \c
GL_TEXTURE_2D, while the default internal format is \c GL_RGBA8
for desktop OpenGL and \c GL_RGBA for OpenGL/ES.
@@ -885,17 +897,11 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, const
\sa size(), texture(), attachment()
*/
QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, Attachment attachment,
- GLenum target, GLenum internal_format)
+ GLenum target, GLenum internalFormat)
: d_ptr(new QOpenGLFramebufferObjectPrivate)
{
Q_D(QOpenGLFramebufferObject);
- if (!internal_format)
-#ifdef QT_OPENGL_ES_2
- internal_format = GL_RGBA;
-#else
- internal_format = QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
-#endif
- d->init(this, QSize(width, height), attachment, target, internal_format);
+ d->init(this, QSize(width, height), attachment, target, effectiveInternalFormat(internalFormat));
}
/*! \overload
@@ -904,7 +910,7 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, Attach
buffer of the given \a size.
The \a attachment parameter describes the depth/stencil buffer
- configuration, \a target the texture target and \a internal_format
+ configuration, \a target the texture target and \a internalFormat
the internal texture format. The default texture target is \c
GL_TEXTURE_2D, while the default internal format is \c GL_RGBA8
for desktop OpenGL and \c GL_RGBA for OpenGL/ES.
@@ -912,17 +918,11 @@ QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, Attach
\sa size(), texture(), attachment()
*/
QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, Attachment attachment,
- GLenum target, GLenum internal_format)
+ GLenum target, GLenum internalFormat)
: d_ptr(new QOpenGLFramebufferObjectPrivate)
{
Q_D(QOpenGLFramebufferObject);
- if (!internal_format)
-#ifdef QT_OPENGL_ES_2
- internal_format = GL_RGBA;
-#else
- internal_format = QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
-#endif
- d->init(this, size, attachment, target, internal_format);
+ d->init(this, size, attachment, target, effectiveInternalFormat(internalFormat));
}
/*!
@@ -936,10 +936,12 @@ QOpenGLFramebufferObject::~QOpenGLFramebufferObject()
if (isBound())
release();
- if (d->texture_guard)
- d->texture_guard->free();
- if (d->color_buffer_guard)
- d->color_buffer_guard->free();
+ foreach (const QOpenGLFramebufferObjectPrivate::ColorAttachment &color, d->colorAttachments) {
+ if (color.guard)
+ color.guard->free();
+ }
+ d->colorAttachments.clear();
+
if (d->depth_buffer_guard)
d->depth_buffer_guard->free();
if (d->stencil_buffer_guard && d->stencil_buffer_guard != d->depth_buffer_guard)
@@ -949,6 +951,70 @@ QOpenGLFramebufferObject::~QOpenGLFramebufferObject()
}
/*!
+ Creates and attaches an additional texture or renderbuffer of size \a width
+ and \a height.
+
+ There is always an attachment at GL_COLOR_ATTACHMENT0. Call this function
+ to set up additional attachments at GL_COLOR_ATTACHMENT1,
+ GL_COLOR_ATTACHMENT2, ...
+
+ When \a internalFormat is not \c 0, it specifies the internal format of the
+ texture or renderbuffer. Otherwise a default of GL_RGBA or GL_RGBA8 is
+ used.
+
+ \note This is only functional when multiple render targets are supported by
+ the OpenGL implementation. When that is not the case, the function will not
+ add any additional color attachments. Call
+ QOpenGLFunctions::hasOpenGLFeature() with
+ QOpenGLFunctions::MultipleRenderTargets at runtime to check if MRT is
+ supported.
+
+ \note The internal format of the color attachments may differ but there may
+ be limitations on the supported combinations, depending on the drivers.
+
+ \note The size of the color attachments may differ but rendering is limited
+ to the area that fits all the attachments, according to the OpenGL
+ specification. Some drivers may not be fully conformant in this respect,
+ however.
+
+ \since 5.6
+ */
+void QOpenGLFramebufferObject::addColorAttachment(const QSize &size, GLenum internalFormat)
+{
+ Q_D(QOpenGLFramebufferObject);
+
+ if (!QOpenGLContext::currentContext()->functions()->hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets)) {
+ qWarning("Multiple render targets not supported, ignoring extra color attachment request");
+ return;
+ }
+
+ QOpenGLFramebufferObjectPrivate::ColorAttachment color(size, effectiveInternalFormat(internalFormat));
+ d->colorAttachments.append(color);
+ const int idx = d->colorAttachments.count() - 1;
+
+ if (d->requestedSamples == 0) {
+ d->initTexture(idx);
+ } else {
+ GLint samples = d->requestedSamples;
+ d->initColorBuffer(idx, &samples);
+ }
+}
+
+/*! \overload
+
+ Creates and attaches an additional texture or renderbuffer of size \a width and \a height.
+
+ When \a internalFormat is not \c 0, it specifies the internal format of the texture or
+ renderbuffer. Otherwise a default of GL_RGBA or GL_RGBA8 is used.
+
+ \since 5.6
+ */
+void QOpenGLFramebufferObject::addColorAttachment(int width, int height, GLenum internalFormat)
+{
+ addColorAttachment(QSize(width, height), internalFormat);
+}
+
+/*!
\fn bool QOpenGLFramebufferObject::isValid() const
Returns \c true if the framebuffer object is valid.
@@ -1002,10 +1068,16 @@ bool QOpenGLFramebufferObject::bind()
QOpenGLContextPrivate::get(current)->qgl_current_fbo_invalid = true;
- if (d->texture_guard || d->format.samples() != 0)
- d->valid = d->checkFramebufferStatus(current);
- else
- d->initTexture(d->format.textureTarget(), d->format.internalTextureFormat(), d->size, d->format.mipmap());
+ if (d->format.samples() == 0) {
+ // Create new textures to replace the ones stolen via takeTexture().
+ for (int i = 0; i < d->colorAttachments.count(); ++i) {
+ if (!d->colorAttachments[i].guard)
+ d->initTexture(i);
+ }
+ }
+
+ d->valid = d->checkFramebufferStatus(current);
+
return d->valid;
}
@@ -1052,12 +1124,36 @@ bool QOpenGLFramebufferObject::release()
If a multisample framebuffer object is used then the value returned
from this function will be invalid.
- \sa takeTexture()
+ When multiple textures are attached, the return value is the ID of
+ the first one.
+
+ \sa takeTexture(), textures()
*/
GLuint QOpenGLFramebufferObject::texture() const
{
Q_D(const QOpenGLFramebufferObject);
- return d->texture_guard ? d->texture_guard->id() : 0;
+ return d->colorAttachments[0].guard ? d->colorAttachments[0].guard->id() : 0;
+}
+
+/*!
+ Returns the texture id for all attached textures.
+
+ If a multisample framebuffer object is used, then an empty vector is returned.
+
+ \since 5.6
+
+ \sa takeTextures(), texture()
+*/
+QVector<GLuint> QOpenGLFramebufferObject::textures() const
+{
+ Q_D(const QOpenGLFramebufferObject);
+ QVector<GLuint> ids;
+ if (d->format.samples() != 0)
+ return ids;
+ ids.reserve(d->colorAttachments.count());
+ foreach (const QOpenGLFramebufferObjectPrivate::ColorAttachment &color, d->colorAttachments)
+ ids.append(color.guard ? color.guard->id() : 0);
+ return ids;
}
/*!
@@ -1076,34 +1172,72 @@ GLuint QOpenGLFramebufferObject::texture() const
\since 5.3
- \sa texture(), bind(), release()
+ \sa texture(), bind(), release(), takeTextures()
*/
GLuint QOpenGLFramebufferObject::takeTexture()
{
+ return takeTexture(0);
+}
+
+/*! \overload
+
+ Returns the texture id for the texture attached to the color attachment of
+ index \a colorAttachmentIndex of this framebuffer object. The ownership of
+ the texture is transferred to the caller.
+
+ When \a colorAttachmentIndex is \c 0, the behavior is identical to the
+ parameter-less variant of this function.
+
+ If the framebuffer object is currently bound, an implicit release()
+ will be done. During the next call to bind() a new texture will be
+ created.
+
+ If a multisample framebuffer object is used, then there is no
+ texture and the return value from this function will be invalid.
+ Similarly, incomplete framebuffer objects will also return 0.
+
+ \since 5.6
+ */
+GLuint QOpenGLFramebufferObject::takeTexture(int colorAttachmentIndex)
+{
Q_D(QOpenGLFramebufferObject);
GLuint id = 0;
- if (isValid() && d->texture_guard) {
+ if (isValid() && d->format.samples() == 0 && d->colorAttachments.count() > colorAttachmentIndex) {
QOpenGLContext *current = QOpenGLContext::currentContext();
if (current && current->shareGroup() == d->fbo_guard->group() && isBound())
release();
- id = d->texture_guard->id();
+ id = d->colorAttachments[colorAttachmentIndex].guard ? d->colorAttachments[colorAttachmentIndex].guard->id() : 0;
// Do not call free() on texture_guard, just null it out.
// This way the texture will not be deleted when the guard is destroyed.
- d->texture_guard = 0;
+ d->colorAttachments[colorAttachmentIndex].guard = 0;
}
return id;
}
/*!
- \fn QSize QOpenGLFramebufferObject::size() const
+ \return the size of the color and depth/stencil attachments attached to
+ this framebuffer object.
+*/
+QSize QOpenGLFramebufferObject::size() const
+{
+ Q_D(const QOpenGLFramebufferObject);
+ return d->dsSize;
+}
- Returns the size of the texture attached to this framebuffer
+/*!
+ \return the sizes of all color attachments attached to this framebuffer
object.
+
+ \since 5.6
*/
-QSize QOpenGLFramebufferObject::size() const
+QVector<QSize> QOpenGLFramebufferObject::sizes() const
{
Q_D(const QOpenGLFramebufferObject);
- return d->size;
+ QVector<QSize> sz;
+ sz.reserve(d->colorAttachments.size());
+ foreach (const QOpenGLFramebufferObjectPrivate::ColorAttachment &color, d->colorAttachments)
+ sz.append(color.size);
+ return sz;
}
/*!
@@ -1232,6 +1366,37 @@ Q_GUI_EXPORT QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format,
QImage QOpenGLFramebufferObject::toImage(bool flipped) const
{
+ return toImage(flipped, 0);
+}
+
+/*!
+ \fn QImage QOpenGLFramebufferObject::toImage() const
+ \overload
+
+ Returns the contents of this framebuffer object as a QImage. This method flips
+ the image from OpenGL coordinates to raster coordinates.
+*/
+// ### Qt 6: Remove this method and make it a default argument instead.
+QImage QOpenGLFramebufferObject::toImage() const
+{
+ return toImage(true, 0);
+}
+
+/*! \overload
+
+ Returns the contents of the color attachment of index \a
+ colorAttachmentIndex of this framebuffer object as a QImage. This method
+ flips the image from OpenGL coordinates to raster coordinates when \a
+ flipped is set to \c true.
+
+ \note This overload is only fully functional when multiple render targets are
+ supported by the OpenGL implementation. When that is not the case, only one
+ color attachment will be set up.
+
+ \since 5.6
+*/
+QImage QOpenGLFramebufferObject::toImage(bool flipped, int colorAttachmentIndex) const
+{
Q_D(const QOpenGLFramebufferObject);
if (!d->valid)
return QImage();
@@ -1242,6 +1407,11 @@ QImage QOpenGLFramebufferObject::toImage(bool flipped) const
return QImage();
}
+ if (d->colorAttachments.count() <= colorAttachmentIndex) {
+ qWarning("QOpenGLFramebufferObject::toImage() called for missing color attachment");
+ return QImage();
+ }
+
GLuint prevFbo = 0;
ctx->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *) &prevFbo);
@@ -1249,16 +1419,33 @@ QImage QOpenGLFramebufferObject::toImage(bool flipped) const
const_cast<QOpenGLFramebufferObject *>(this)->bind();
QImage image;
+ QOpenGLExtraFunctions *extraFuncs = ctx->extraFunctions();
// qt_gl_read_framebuffer doesn't work on a multisample FBO
if (format().samples() != 0) {
- QOpenGLFramebufferObject temp(size(), QOpenGLFramebufferObjectFormat());
-
QRect rect(QPoint(0, 0), size());
- blitFramebuffer(&temp, rect, const_cast<QOpenGLFramebufferObject *>(this), rect);
-
- image = temp.toImage(flipped);
+ if (extraFuncs->hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets)) {
+ QOpenGLFramebufferObject temp(d->colorAttachments[colorAttachmentIndex].size, QOpenGLFramebufferObjectFormat());
+ blitFramebuffer(&temp, rect, const_cast<QOpenGLFramebufferObject *>(this), rect,
+ GL_COLOR_BUFFER_BIT, GL_NEAREST,
+ colorAttachmentIndex, 0);
+ image = temp.toImage(flipped);
+ } else {
+ QOpenGLFramebufferObject temp(size(), QOpenGLFramebufferObjectFormat());
+ blitFramebuffer(&temp, rect, const_cast<QOpenGLFramebufferObject *>(this), rect);
+ image = temp.toImage(flipped);
+ }
} else {
- image = qt_gl_read_framebuffer(d->size, format().internalTextureFormat(), true, flipped);
+ if (extraFuncs->hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets)) {
+ extraFuncs->glReadBuffer(GL_COLOR_ATTACHMENT0 + colorAttachmentIndex);
+ image = qt_gl_read_framebuffer(d->colorAttachments[colorAttachmentIndex].size,
+ d->colorAttachments[colorAttachmentIndex].internalFormat,
+ true, flipped);
+ extraFuncs->glReadBuffer(GL_COLOR_ATTACHMENT0);
+ } else {
+ image = qt_gl_read_framebuffer(d->colorAttachments[0].size,
+ d->colorAttachments[0].internalFormat,
+ true, flipped);
+ }
}
if (prevFbo != d->fbo())
@@ -1268,19 +1455,6 @@ QImage QOpenGLFramebufferObject::toImage(bool flipped) const
}
/*!
- \fn QImage QOpenGLFramebufferObject::toImage() const
- \overload
-
- Returns the contents of this framebuffer object as a QImage. This method flips
- the image from OpenGL coordinates to raster coordinates.
-*/
-// ### Qt 6: Remove this method and make it a default argument instead.
-QImage QOpenGLFramebufferObject::toImage() const
-{
- return toImage(true);
-}
-
-/*!
\fn bool QOpenGLFramebufferObject::bindDefault()
Switches rendering back to the default, windowing system provided
@@ -1366,7 +1540,7 @@ void QOpenGLFramebufferObject::setAttachment(QOpenGLFramebufferObject::Attachmen
#endif
d->funcs.glBindFramebuffer(GL_FRAMEBUFFER, d->fbo());
QOpenGLContextPrivate::get(current)->qgl_current_fbo_invalid = true;
- d->initAttachments(current, attachment);
+ d->initDepthStencilAttachments(current, attachment);
}
/*!
@@ -1428,6 +1602,18 @@ void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target,
buffers, filter);
}
+/*! \overload
+ *
+ Convenience overload to blit between two framebuffer objects.
+*/
+void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect,
+ QOpenGLFramebufferObject *source, const QRect &sourceRect,
+ GLbitfield buffers,
+ GLenum filter)
+{
+ blitFramebuffer(target, targetRect, source, sourceRect, buffers, filter, 0, 0);
+}
+
/*!
Blits from the \a sourceRect rectangle in the \a source framebuffer
object to the \a targetRect rectangle in the \a target framebuffer object.
@@ -1456,12 +1642,18 @@ void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target,
\note The scissor test will restrict the blit area if enabled.
+ When multiple render targets are in use, \a readColorAttachmentIndex and \a
+ drawColorAttachmentIndex specify the index of the color attachments in the
+ source and destination framebuffers.
+
\sa hasOpenGLFramebufferBlit()
*/
void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect,
- QOpenGLFramebufferObject *source, const QRect &sourceRect,
- GLbitfield buffers,
- GLenum filter)
+ QOpenGLFramebufferObject *source, const QRect &sourceRect,
+ GLbitfield buffers,
+ GLenum filter,
+ int readColorAttachmentIndex,
+ int drawColorAttachmentIndex)
{
QOpenGLContext *ctx = QOpenGLContext::currentContext();
if (!ctx)
@@ -1489,10 +1681,21 @@ void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target,
extensions.glBindFramebuffer(GL_READ_FRAMEBUFFER, source ? source->handle() : defaultFboId);
extensions.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target ? target->handle() : defaultFboId);
+ if (extensions.hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets)) {
+ extensions.glReadBuffer(GL_COLOR_ATTACHMENT0 + readColorAttachmentIndex);
+ if (target) {
+ GLenum drawBuf = GL_COLOR_ATTACHMENT0 + drawColorAttachmentIndex;
+ extensions.glDrawBuffers(1, &drawBuf);
+ }
+ }
+
extensions.glBlitFramebuffer(sx0, sy0, sx1, sy1,
tx0, ty0, tx1, ty1,
buffers, filter);
+ if (extensions.hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets))
+ extensions.glReadBuffer(GL_COLOR_ATTACHMENT0);
+
ctx->functions()->glBindFramebuffer(GL_FRAMEBUFFER, prevFbo); // sets both READ and DRAW
}
diff --git a/src/gui/opengl/qopenglframebufferobject.h b/src/gui/opengl/qopenglframebufferobject.h
index 4ce0ee26cb..cead4ad10f 100644
--- a/src/gui/opengl/qopenglframebufferobject.h
+++ b/src/gui/opengl/qopenglframebufferobject.h
@@ -63,15 +63,18 @@ public:
QOpenGLFramebufferObject(int width, int height, GLenum target = GL_TEXTURE_2D);
QOpenGLFramebufferObject(const QSize &size, Attachment attachment,
- GLenum target = GL_TEXTURE_2D, GLenum internal_format = 0);
+ GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0);
QOpenGLFramebufferObject(int width, int height, Attachment attachment,
- GLenum target = GL_TEXTURE_2D, GLenum internal_format = 0);
+ GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0);
QOpenGLFramebufferObject(const QSize &size, const QOpenGLFramebufferObjectFormat &format);
QOpenGLFramebufferObject(int width, int height, const QOpenGLFramebufferObjectFormat &format);
virtual ~QOpenGLFramebufferObject();
+ void addColorAttachment(const QSize &size, GLenum internalFormat = 0);
+ void addColorAttachment(int width, int height, GLenum internalFormat = 0);
+
QOpenGLFramebufferObjectFormat format() const;
bool isValid() const;
@@ -83,12 +86,19 @@ public:
int height() const { return size().height(); }
GLuint texture() const;
+ QVector<GLuint> textures() const;
+
GLuint takeTexture();
+ GLuint takeTexture(int colorAttachmentIndex);
+
QSize size() const;
+ QVector<QSize> sizes() const;
+
QImage toImage() const;
QImage toImage(bool flipped) const;
- Attachment attachment() const;
+ QImage toImage(bool flipped, int colorAttachmentIndex) const;
+ Attachment attachment() const;
void setAttachment(Attachment attachment);
GLuint handle() const;
@@ -100,6 +110,12 @@ public:
static bool hasOpenGLFramebufferBlit();
static void blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect,
QOpenGLFramebufferObject *source, const QRect &sourceRect,
+ GLbitfield buffers,
+ GLenum filter,
+ int readColorAttachmentIndex,
+ int drawColorAttachmentIndex);
+ static void blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect,
+ QOpenGLFramebufferObject *source, const QRect &sourceRect,
GLbitfield buffers = GL_COLOR_BUFFER_BIT,
GLenum filter = GL_NEAREST);
static void blitFramebuffer(QOpenGLFramebufferObject *target,
diff --git a/src/gui/opengl/qopenglframebufferobject_p.h b/src/gui/opengl/qopenglframebufferobject_p.h
index 7f0068dfc4..6c45fda57f 100644
--- a/src/gui/opengl/qopenglframebufferobject_p.h
+++ b/src/gui/opengl/qopenglframebufferobject_p.h
@@ -102,32 +102,41 @@ public:
class QOpenGLFramebufferObjectPrivate
{
public:
- QOpenGLFramebufferObjectPrivate() : fbo_guard(0), texture_guard(0), depth_buffer_guard(0)
- , stencil_buffer_guard(0), color_buffer_guard(0)
+ QOpenGLFramebufferObjectPrivate() : fbo_guard(0), depth_buffer_guard(0)
+ , stencil_buffer_guard(0)
, valid(false) {}
~QOpenGLFramebufferObjectPrivate() {}
- void init(QOpenGLFramebufferObject *q, const QSize& sz,
+ void init(QOpenGLFramebufferObject *q, const QSize &size,
QOpenGLFramebufferObject::Attachment attachment,
- GLenum internal_format, GLenum texture_target,
+ GLenum texture_target, GLenum internal_format,
GLint samples = 0, bool mipmap = false);
- void initTexture(GLenum target, GLenum internal_format, const QSize &size, bool mipmap);
- void initAttachments(QOpenGLContext *ctx, QOpenGLFramebufferObject::Attachment attachment);
+ void initTexture(int idx);
+ void initColorBuffer(int idx, GLint *samples);
+ void initDepthStencilAttachments(QOpenGLContext *ctx, QOpenGLFramebufferObject::Attachment attachment);
bool checkFramebufferStatus(QOpenGLContext *ctx) const;
QOpenGLSharedResourceGuard *fbo_guard;
- QOpenGLSharedResourceGuard *texture_guard;
QOpenGLSharedResourceGuard *depth_buffer_guard;
QOpenGLSharedResourceGuard *stencil_buffer_guard;
- QOpenGLSharedResourceGuard *color_buffer_guard;
GLenum target;
- QSize size;
+ QSize dsSize;
QOpenGLFramebufferObjectFormat format;
int requestedSamples;
uint valid : 1;
QOpenGLFramebufferObject::Attachment fbo_attachment;
QOpenGLExtensions funcs;
+ struct ColorAttachment {
+ ColorAttachment() : internalFormat(0), guard(0) { }
+ ColorAttachment(const QSize &size, GLenum internalFormat)
+ : size(size), internalFormat(internalFormat), guard(0) { }
+ QSize size;
+ GLenum internalFormat;
+ QOpenGLSharedResourceGuard *guard;
+ };
+ QVector<ColorAttachment> colorAttachments;
+
inline GLuint fbo() const { return fbo_guard ? fbo_guard->id() : 0; }
};
diff --git a/src/gui/opengl/qopenglfunctions.cpp b/src/gui/opengl/qopenglfunctions.cpp
index 8ddb693e73..d614ad8401 100644
--- a/src/gui/opengl/qopenglfunctions.cpp
+++ b/src/gui/opengl/qopenglfunctions.cpp
@@ -32,12 +32,14 @@
****************************************************************************/
#include "qopenglfunctions.h"
+#include "qopenglextrafunctions.h"
#include "qopenglextensions_p.h"
#include "qdebug.h"
#include <QtGui/private/qopenglcontext_p.h>
#include <QtGui/private/qopengl_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
+#include <QtCore/qloggingcategory.h>
#ifdef Q_OS_IOS
#include <dlfcn.h>
@@ -49,6 +51,8 @@
QT_BEGIN_NAMESPACE
+Q_LOGGING_CATEGORY(lcGLES3, "qt.opengl.es3")
+
/*!
\class QOpenGLFunctions
\brief The QOpenGLFunctions class provides cross-platform access to the OpenGL ES 2.0 API.
@@ -155,6 +159,8 @@ QT_BEGIN_NAMESPACE
QOpenGLFunctions funcs(QOpenGLContext::currentContext());
bool npot = funcs.hasOpenGLFeature(QOpenGLFunctions::NPOTTextures);
\endcode
+
+ \sa QOpenGLContext, QSurfaceFormat
*/
/*!
@@ -178,6 +184,7 @@ QT_BEGIN_NAMESPACE
\value NPOTTextureRepeat Non power of two textures can use GL_REPEAT as wrap parameter.
\value FixedFunctionPipeline The fixed function pipeline is available.
\value TextureRGFormats The GL_RED and GL_RG texture formats are available.
+ \value MultipleRenderTargets Multiple color attachments to framebuffer objects are available.
*/
// Hidden private fields for additional extension data.
@@ -251,12 +258,11 @@ QOpenGLFunctions::QOpenGLFunctions(QOpenGLContext *context)
}
QOpenGLExtensions::QOpenGLExtensions()
- : QOpenGLFunctions()
{
}
QOpenGLExtensions::QOpenGLExtensions(QOpenGLContext *context)
- : QOpenGLFunctions(context)
+ : QOpenGLExtraFunctions(context)
{
}
@@ -270,7 +276,7 @@ static int qt_gl_resolve_features()
{
QOpenGLContext *ctx = QOpenGLContext::currentContext();
if (ctx->isOpenGLES()) {
- // OpenGL ES 2
+ // OpenGL ES
int features = QOpenGLFunctions::Multitexture |
QOpenGLFunctions::Shaders |
QOpenGLFunctions::Buffers |
@@ -295,6 +301,8 @@ static int qt_gl_resolve_features()
if (!(renderer && strstr(renderer, "Mesa")))
features |= QOpenGLFunctions::TextureRGFormats;
}
+ if (ctx->format().majorVersion() >= 3)
+ features |= QOpenGLFunctions::MultipleRenderTargets;
return features;
} else {
// OpenGL
@@ -303,10 +311,9 @@ static int qt_gl_resolve_features()
QOpenGLExtensionMatcher extensions;
if (format.majorVersion() >= 3)
- features |= QOpenGLFunctions::Framebuffers;
- else if (extensions.match("GL_EXT_framebuffer_object") ||
- extensions.match("GL_ARB_framebuffer_object"))
- features |= QOpenGLFunctions::Framebuffers;
+ features |= QOpenGLFunctions::Framebuffers | QOpenGLFunctions::MultipleRenderTargets;
+ else if (extensions.match("GL_EXT_framebuffer_object") || extensions.match("GL_ARB_framebuffer_object"))
+ features |= QOpenGLFunctions::Framebuffers | QOpenGLFunctions::MultipleRenderTargets;
if (format.majorVersion() >= 2) {
features |= QOpenGLFunctions::BlendColor |
@@ -423,11 +430,14 @@ static int qt_gl_resolve_extensions()
// We don't match GL_APPLE_texture_format_BGRA8888 here because it has different semantics.
if (extensionMatcher.match("GL_IMG_texture_format_BGRA8888") || extensionMatcher.match("GL_EXT_texture_format_BGRA8888"))
extensions |= QOpenGLExtensions::BGRATextureFormat;
-
if (extensionMatcher.match("GL_EXT_discard_framebuffer"))
extensions |= QOpenGLExtensions::DiscardFramebuffer;
+ if (extensionMatcher.match("GL_EXT_texture_norm16"))
+ extensions |= QOpenGLExtensions::Sized16Formats;
} else {
- extensions |= QOpenGLExtensions::ElementIndexUint | QOpenGLExtensions::MapBuffer;
+ extensions |= QOpenGLExtensions::ElementIndexUint
+ | QOpenGLExtensions::MapBuffer
+ | QOpenGLExtensions::Sized16Formats;
if (format.version() >= qMakePair(1, 2))
extensions |= QOpenGLExtensions::BGRATextureFormat;
@@ -2121,6 +2131,9 @@ public:
template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10>
ReturnType operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10);
+ template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10, typename P11>
+ ReturnType operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11);
+
private:
FuncType Base::*funcPointerName;
FuncType fallbackFuncPointer;
@@ -2172,6 +2185,9 @@ public:
template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10>
void operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10);
+ template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10, typename P11>
+ void operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11);
+
private:
FuncType Base::*funcPointerName;
FuncType fallbackFuncPointer;
@@ -2421,6 +2437,14 @@ void Resolver<Base, FuncType, Policy, void>::operator()(P1 p1, P2 p2, P3 p3, P4
(funcs->*funcPointerName)(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
}
+template <typename Base, typename FuncType, int Policy> template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10, typename P11>
+void Resolver<Base, FuncType, Policy, void>::operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11)
+{
+ RESOLVER_COMMON_VOID
+
+ (funcs->*funcPointerName)(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11);
+}
+
template <typename ReturnType, int Policy, typename Base, typename FuncType>
Resolver<Base, FuncType, Policy, ReturnType> functionResolverWithFallback(FuncType Base::*func, FuncType fallback, const char *name, const char *alternate = 0)
{
@@ -2433,7 +2457,7 @@ Resolver<Base, FuncType, Policy, ReturnType> functionResolver(FuncType Base::*fu
return Resolver<Base, FuncType, Policy, ReturnType>(func, 0, name, alternate);
}
-}
+} // namespace
#define RESOLVE_FUNC(RETURN_TYPE, POLICY, NAME) \
return functionResolver<RETURN_TYPE, POLICY>(&QOpenGLExtensionsPrivate::NAME, "gl" #NAME)
@@ -3201,79 +3225,7 @@ static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribPointer(GLuint indx, GL
#endif // !QT_OPENGL_ES_2
-// Functions part of the OpenGL ES 3.0+ standard need special handling. These,
-// just like the 2.0 functions, are not guaranteed to be resolvable via
-// eglGetProcAddress or similar. Calling them directly is, unlike the 2.0
-// functions, not feasible because one may build the binaries on a GLES3-capable
-// system and then deploy on a GLES2-only system that does not have these
-// symbols. Until ES3 gets universally available, they have to be dlsym'ed.
-
-Q_GLOBAL_STATIC(QOpenGLES3Helper, qgles3Helper)
-
-bool QOpenGLES3Helper::init()
-{
-#ifndef Q_OS_IOS
-# ifdef Q_OS_WIN
-# ifndef QT_DEBUG
- m_gl.setFileName(QStringLiteral("libGLESv2"));
-# else
- m_gl.setFileName(QStringLiteral("libGLESv2d"));
-# endif
-# else
-# ifdef Q_OS_ANDROID
- m_gl.setFileName(QStringLiteral("GLESv2"));
-# else
- m_gl.setFileNameAndVersion(QStringLiteral("GLESv2"), 2);
-# endif
-# endif // Q_OS_WIN
- return m_gl.load();
-#else
- return true;
-#endif // Q_OS_IOS
-}
-
-QFunctionPointer QOpenGLES3Helper::resolve(const char *name)
-{
-#ifdef Q_OS_IOS
- return QFunctionPointer(dlsym(RTLD_DEFAULT, name));
-#else
- return m_gl.resolve(name);
-#endif
-}
-
-QOpenGLES3Helper::QOpenGLES3Helper()
-{
- if (init()) {
- MapBufferRange = (GLvoid* (QOPENGLF_APIENTRYP)(GLenum, qopengl_GLintptr, qopengl_GLsizeiptr, GLbitfield)) resolve("glMapBufferRange");
- UnmapBuffer = (GLboolean (QOPENGLF_APIENTRYP)(GLenum)) resolve("glUnmapBuffer");
- BlitFramebuffer = (void (QOPENGLF_APIENTRYP)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum)) resolve("glBlitFramebuffer");
- RenderbufferStorageMultisample = (void (QOPENGLF_APIENTRYP)(GLenum, GLsizei, GLenum, GLsizei, GLsizei)) resolve("glRenderbufferStorageMultisample");
-
- GenVertexArrays = (void (QOPENGLF_APIENTRYP)(GLsizei, GLuint *)) resolve("glGenVertexArrays");
- DeleteVertexArrays = (void (QOPENGLF_APIENTRYP)(GLsizei, const GLuint *)) resolve("glDeleteVertexArrays");
- BindVertexArray = (void (QOPENGLF_APIENTRYP)(GLuint)) resolve("glBindVertexArray");
- IsVertexArray = (GLboolean (QOPENGLF_APIENTRYP)(GLuint)) resolve("glIsVertexArray");
-
- TexImage3D = (void (QOPENGLF_APIENTRYP)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *)) resolve("glTexImage3D");
- TexSubImage3D = (void (QOPENGLF_APIENTRYP)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *)) resolve("glTexSubImage3D");
- CompressedTexImage3D = (void (QOPENGLF_APIENTRYP)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *)) resolve("glCompressedTexImage3D");
- CompressedTexSubImage3D = (void (QOPENGLF_APIENTRYP)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *)) resolve("glCompressedTexSubImage3D");
-
- TexStorage3D = (void (QOPENGLF_APIENTRYP)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei)) resolve("glTexStorage3D");
- TexStorage2D = (void (QOPENGLF_APIENTRYP)(GLenum, GLsizei, GLenum, GLsizei, GLsizei)) resolve("glTexStorage2D");
-
- if (!MapBufferRange || !GenVertexArrays || !TexImage3D || !TexStorage3D)
- qFatal("OpenGL ES 3.0 entry points not found");
- } else {
- qFatal("Failed to load libGLESv2");
- }
-}
-
-static inline bool isES3()
-{
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- return ctx->isOpenGLES() && ctx->format().majorVersion() >= 3;
-}
+// Extensions not standard in any ES version
static GLvoid *QOPENGLF_APIENTRY qopenglfResolveMapBuffer(GLenum target, GLenum access)
{
@@ -3281,7 +3233,8 @@ static GLvoid *QOPENGLF_APIENTRY qopenglfResolveMapBuffer(GLenum target, GLenum
// differentiate between glUnmapBufferOES and glUnmapBuffer causes extra
// headache. QOpenGLBuffer::map() will handle this automatically, while direct
// calls are better off with migrating to the standard glMapBufferRange.
- if (isES3()) {
+ QOpenGLContext *ctx = QOpenGLContext::currentContext();
+ if (ctx->isOpenGLES() && ctx->format().majorVersion() >= 3) {
qWarning("QOpenGLFunctions: glMapBuffer is not available in OpenGL ES 3.0 and up. Use glMapBufferRange instead.");
return 0;
} else {
@@ -3289,44 +3242,6 @@ static GLvoid *QOPENGLF_APIENTRY qopenglfResolveMapBuffer(GLenum target, GLenum
}
}
-static GLvoid *QOPENGLF_APIENTRY qopenglfResolveMapBufferRange(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr length, GLbitfield access)
-{
- if (isES3())
- return qgles3Helper()->MapBufferRange(target, offset, length, access);
- else
- RESOLVE_FUNC(GLvoid *, 0, MapBufferRange)(target, offset, length, access);
-}
-
-static GLboolean QOPENGLF_APIENTRY qopenglfResolveUnmapBuffer(GLenum target)
-{
- if (isES3())
- return qgles3Helper()->UnmapBuffer(target);
- else
- RESOLVE_FUNC(GLboolean, ResolveOES, UnmapBuffer)(target);
-}
-
-static void QOPENGLF_APIENTRY qopenglfResolveBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
- GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
- GLbitfield mask, GLenum filter)
-{
- if (isES3())
- qgles3Helper()->BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
- else
- RESOLVE_FUNC_VOID(ResolveEXT | ResolveANGLE | ResolveNV, BlitFramebuffer)
- (srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
-}
-
-static void QOPENGLF_APIENTRY qopenglfResolveRenderbufferStorageMultisample(GLenum target, GLsizei samples,
- GLenum internalFormat,
- GLsizei width, GLsizei height)
-{
- if (isES3())
- qgles3Helper()->RenderbufferStorageMultisample(target, samples, internalFormat, width, height);
- else
- RESOLVE_FUNC_VOID(ResolveEXT | ResolveANGLE | ResolveNV, RenderbufferStorageMultisample)
- (target, samples, internalFormat, width, height);
-}
-
static void QOPENGLF_APIENTRY qopenglfResolveGetBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, GLvoid *data)
{
RESOLVE_FUNC_VOID(ResolveEXT, GetBufferSubData)
@@ -3567,15 +3482,4129 @@ QOpenGLFunctionsPrivate::QOpenGLFunctionsPrivate(QOpenGLContext *)
#endif // !QT_OPENGL_ES_2
}
-QOpenGLExtensionsPrivate::QOpenGLExtensionsPrivate(QOpenGLContext *ctx)
- : QOpenGLFunctionsPrivate(ctx),
- flushVendorChecked(false)
+/*!
+ \class QOpenGLExtraFunctions
+ \brief The QOpenGLExtraFunctions class provides cross-platform access to the OpenGL ES 3.0 and 3.1 API.
+ \since 5.6
+ \ingroup painting-3D
+ \inmodule QtGui
+
+ This subclass of QOpenGLFunctions includes the OpenGL ES 3.0 and 3.1
+ functions. These will only work when an OpenGL ES 3.0 or 3.1 context, or an
+ OpenGL context of a version containing the functions in question either in
+ core or as extension, is in use. This allows developing GLES 3.0 and 3.1
+ applications in a cross-platform manner: development can happen on a desktop
+ platform with OpenGL 3.x or 4.x, deploying to a real GLES 3.1 device later
+ on will require no or minimal changes to the application.
+
+ \note This class is different from the versioned OpenGL wrappers, for
+ instance QOpenGLFunctions_3_2_Core. The versioned function wrappers target a
+ given version and profile of OpenGL. They are therefore not suitable for
+ cross-OpenGL-OpenGLES development.
+ */
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBeginQuery(GLenum target, GLuint id)
+
+ Convenience function that calls glBeginQuery(\a target, \a id).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBeginQuery.xml}{glBeginQuery()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBeginTransformFeedback(GLenum primitiveMode)
+
+ Convenience function that calls glBeginTransformFeedback(\a primitiveMode).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBeginTransformFeedback.xml}{glBeginTransformFeedback()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindBufferBase(GLenum target, GLuint index, GLuint buffer)
+
+ Convenience function that calls glBindBufferBase(\a target, \a index, \a buffer).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindBufferBase.xml}{glBindBufferBase()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
+
+ Convenience function that calls glBindBufferRange(\a target, \a index, \a buffer, \a offset, \a size).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindBufferRange.xml}{glBindBufferRange()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindSampler(GLuint unit, GLuint sampler)
+
+ Convenience function that calls glBindSampler(\a unit, \a sampler).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindSampler.xml}{glBindSampler()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindTransformFeedback(GLenum target, GLuint id)
+
+ Convenience function that calls glBindTransformFeedback(\a target, \a id).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindTransformFeedback.xml}{glBindTransformFeedback()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindVertexArray(GLuint array)
+
+ Convenience function that calls glBindVertexArray(\a array).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindVertexArray.xml}{glBindVertexArray()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
+
+ Convenience function that calls glBlitFramebuffer(\a srcX0, \a srcY0, \a srcX1, \a srcY1, \a dstX0, \a dstY0, \a dstX1, \a dstY1, \a mask, \a filter).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBlitFramebuffer.xml}{glBlitFramebuffer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
+
+ Convenience function that calls glClearBufferfi(\a buffer, \a drawbuffer, \a depth, \a stencil).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glClearBufferfi.xml}{glClearBufferfi()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat * value)
+
+ Convenience function that calls glClearBufferfv(\a buffer, \a drawbuffer, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glClearBufferfv.xml}{glClearBufferfv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint * value)
+
+ Convenience function that calls glClearBufferiv(\a buffer, \a drawbuffer, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glClearBufferiv.xml}{glClearBufferiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint * value)
+
+ Convenience function that calls glClearBufferuiv(\a buffer, \a drawbuffer, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glClearBufferuiv.xml}{glClearBufferuiv()}.
+*/
+
+/*!
+ \fn GLenum QOpenGLExtraFunctions::glClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+
+ Convenience function that calls glClientWaitSync(\a sync, \a flags, \a timeout).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glClientWaitSync.xml}{glClientWaitSync()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)
+
+ Convenience function that calls glCompressedTexImage3D(\a target, \a level, \a internalformat, \a width, \a height, \a depth, \a border, \a imageSize, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glCompressedTexImage3D.xml}{glCompressedTexImage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data)
+
+ Convenience function that calls glCompressedTexSubImage3D(\a target, \a level, \a xoffset, \a yoffset, \a zoffset, \a width, \a height, \a depth, \a format, \a imageSize, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glCompressedTexSubImage3D.xml}{glCompressedTexSubImage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
+
+ Convenience function that calls glCopyBufferSubData(\a readTarget, \a writeTarget, \a readOffset, \a writeOffset, \a size).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glCopyBufferSubData.xml}{glCopyBufferSubData()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+
+ Convenience function that calls glCopyTexSubImage3D(\a target, \a level, \a xoffset, \a yoffset, \a zoffset, \a x, \a y, \a width, \a height).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glCopyTexSubImage3D.xml}{glCopyTexSubImage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteQueries(GLsizei n, const GLuint * ids)
+
+ Convenience function that calls glDeleteQueries(\a n, \a ids).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteQueries.xml}{glDeleteQueries()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteSamplers(GLsizei count, const GLuint * samplers)
+
+ Convenience function that calls glDeleteSamplers(\a count, \a samplers).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteSamplers.xml}{glDeleteSamplers()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteSync(GLsync sync)
+
+ Convenience function that calls glDeleteSync(\a sync).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteSync.xml}{glDeleteSync()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteTransformFeedbacks(GLsizei n, const GLuint * ids)
+
+ Convenience function that calls glDeleteTransformFeedbacks(\a n, \a ids).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteTransformFeedbacks.xml}{glDeleteTransformFeedbacks()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteVertexArrays(GLsizei n, const GLuint * arrays)
+
+ Convenience function that calls glDeleteVertexArrays(\a n, \a arrays).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteVertexArrays.xml}{glDeleteVertexArrays()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount)
+
+ Convenience function that calls glDrawArraysInstanced(\a mode, \a first, \a count, \a instancecount).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawArraysInstanced.xml}{glDrawArraysInstanced()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawBuffers(GLsizei n, const GLenum * bufs)
+
+ Convenience function that calls glDrawBuffers(\a n, \a bufs).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawBuffers.xml}{glDrawBuffers()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)
+
+ Convenience function that calls glDrawElementsInstanced(\a mode, \a count, \a type, \a indices, \a instancecount).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawElementsInstanced.xml}{glDrawElementsInstanced()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices)
+
+ Convenience function that calls glDrawRangeElements(\a mode, \a start, \a end, \a count, \a type, \a indices).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawRangeElements.xml}{glDrawRangeElements()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glEndQuery(GLenum target)
+
+ Convenience function that calls glEndQuery(\a target).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glEndQuery.xml}{glEndQuery()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glEndTransformFeedback(void)
+
+ Convenience function that calls glEndTransformFeedback().
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glEndTransformFeedback.xml}{glEndTransformFeedback()}.
+*/
+
+/*!
+ \fn GLsync QOpenGLExtraFunctions::glFenceSync(GLenum condition, GLbitfield flags)
+
+ Convenience function that calls glFenceSync(\a condition, \a flags).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glFenceSync.xml}{glFenceSync()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
+
+ Convenience function that calls glFlushMappedBufferRange(\a target, \a offset, \a length).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glFlushMappedBufferRange.xml}{glFlushMappedBufferRange()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
+
+ Convenience function that calls glFramebufferTextureLayer(\a target, \a attachment, \a texture, \a level, \a layer).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glFramebufferTextureLayer.xml}{glFramebufferTextureLayer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGenQueries(GLsizei n, GLuint* ids)
+
+ Convenience function that calls glGenQueries(\a n, \a ids).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGenQueries.xml}{glGenQueries()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGenSamplers(GLsizei count, GLuint* samplers)
+
+ Convenience function that calls glGenSamplers(\a count, \a samplers).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGenSamplers.xml}{glGenSamplers()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGenTransformFeedbacks(GLsizei n, GLuint* ids)
+
+ Convenience function that calls glGenTransformFeedbacks(\a n, \a ids).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGenTransformFeedbacks.xml}{glGenTransformFeedbacks()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGenVertexArrays(GLsizei n, GLuint* arrays)
+
+ Convenience function that calls glGenVertexArrays(\a n, \a arrays).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGenVertexArrays.xml}{glGenVertexArrays()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName)
+
+ Convenience function that calls glGetActiveUniformBlockName(\a program, \a uniformBlockIndex, \a bufSize, \a length, \a uniformBlockName).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetActiveUniformBlockName.xml}{glGetActiveUniformBlockName()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetActiveUniformBlockiv(\a program, \a uniformBlockIndex, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetActiveUniformBlockiv.xml}{glGetActiveUniformBlockiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetActiveUniformsiv(\a program, \a uniformCount, \a uniformIndices, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetActiveUniformsiv.xml}{glGetActiveUniformsiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params)
+
+ Convenience function that calls glGetBufferParameteri64v(\a target, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetBufferParameteri64v.xml}{glGetBufferParameteri64v()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetBufferPointerv(GLenum target, GLenum pname, void ** params)
+
+ Convenience function that calls glGetBufferPointerv(\a target, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetBufferPointerv.xml}{glGetBufferPointerv()}.
+*/
+
+/*!
+ \fn GLint QOpenGLExtraFunctions::glGetFragDataLocation(GLuint program, const GLchar * name)
+
+ Convenience function that calls glGetFragDataLocation(\a program, \a name).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetFragDataLocation.xml}{glGetFragDataLocation()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetInteger64i_v(GLenum target, GLuint index, GLint64* data)
+
+ Convenience function that calls glGetInteger64i_v(\a target, \a index, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetInteger64i_v.xml}{glGetInteger64i_v()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetInteger64v(GLenum pname, GLint64* data)
+
+ Convenience function that calls glGetInteger64v(\a pname, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetInteger64v.xml}{glGetInteger64v()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetIntegeri_v(GLenum target, GLuint index, GLint* data)
+
+ Convenience function that calls glGetIntegeri_v(\a target, \a index, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetIntegeri_v.xml}{glGetIntegeri_v()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params)
+
+ Convenience function that calls glGetInternalformativ(\a target, \a internalformat, \a pname, \a bufSize, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetInternalformativ.xml}{glGetInternalformativ()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, void * binary)
+
+ Convenience function that calls glGetProgramBinary(\a program, \a bufSize, \a length, \a binaryFormat, \a binary).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramBinary.xml}{glGetProgramBinary()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params)
+
+ Convenience function that calls glGetQueryObjectuiv(\a id, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetQueryObjectuiv.xml}{glGetQueryObjectuiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetQueryiv(GLenum target, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetQueryiv(\a target, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetQueryiv.xml}{glGetQueryiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params)
+
+ Convenience function that calls glGetSamplerParameterfv(\a sampler, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetSamplerParameterfv.xml}{glGetSamplerParameterfv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetSamplerParameteriv(\a sampler, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetSamplerParameteriv.xml}{glGetSamplerParameteriv()}.
+*/
+
+/*!
+ \fn const GLubyte * QOpenGLExtraFunctions::glGetStringi(GLenum name, GLuint index)
+
+ Convenience function that calls glGetStringi(\a name, \a index).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetStringi.xml}{glGetStringi()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values)
+
+ Convenience function that calls glGetSynciv(\a sync, \a pname, \a bufSize, \a length, \a values).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetSynciv.xml}{glGetSynciv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name)
+
+ Convenience function that calls glGetTransformFeedbackVarying(\a program, \a index, \a bufSize, \a length, \a size, \a type, \a name).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetTransformFeedbackVarying.xml}{glGetTransformFeedbackVarying()}.
+*/
+
+/*!
+ \fn GLuint QOpenGLExtraFunctions::glGetUniformBlockIndex(GLuint program, const GLchar * uniformBlockName)
+
+ Convenience function that calls glGetUniformBlockIndex(\a program, \a uniformBlockName).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetUniformBlockIndex.xml}{glGetUniformBlockIndex()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint* uniformIndices)
+
+ Convenience function that calls glGetUniformIndices(\a program, \a uniformCount, \a uniformNames, \a uniformIndices).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetUniformIndices.xml}{glGetUniformIndices()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetUniformuiv(GLuint program, GLint location, GLuint* params)
+
+ Convenience function that calls glGetUniformuiv(\a program, \a location, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetUniformuiv.xml}{glGetUniformuiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetVertexAttribIiv(GLuint index, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetVertexAttribIiv(\a index, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetVertexAttribIiv.xml}{glGetVertexAttribIiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params)
+
+ Convenience function that calls glGetVertexAttribIuiv(\a index, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetVertexAttribIuiv.xml}{glGetVertexAttribIuiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glInvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments)
+
+ Convenience function that calls glInvalidateFramebuffer(\a target, \a numAttachments, \a attachments).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glInvalidateFramebuffer.xml}{glInvalidateFramebuffer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height)
+
+ Convenience function that calls glInvalidateSubFramebuffer(\a target, \a numAttachments, \a attachments, \a x, \a y, \a width, \a height).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glInvalidateSubFramebuffer.xml}{glInvalidateSubFramebuffer()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsQuery(GLuint id)
+
+ Convenience function that calls glIsQuery(\a id).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsQuery.xml}{glIsQuery()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsSampler(GLuint sampler)
+
+ Convenience function that calls glIsSampler(\a sampler).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsSampler.xml}{glIsSampler()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsSync(GLsync sync)
+
+ Convenience function that calls glIsSync(\a sync).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsSync.xml}{glIsSync()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsTransformFeedback(GLuint id)
+
+ Convenience function that calls glIsTransformFeedback(\a id).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsTransformFeedback.xml}{glIsTransformFeedback()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsVertexArray(GLuint array)
+
+ Convenience function that calls glIsVertexArray(\a array).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsVertexArray.xml}{glIsVertexArray()}.
+*/
+
+/*!
+ \fn void * QOpenGLExtraFunctions::glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
+
+ Convenience function that calls glMapBufferRange(\a target, \a offset, \a length, \a access).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glMapBufferRange.xml}{glMapBufferRange()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glPauseTransformFeedback(void)
+
+ Convenience function that calls glPauseTransformFeedback().
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glPauseTransformFeedback.xml}{glPauseTransformFeedback()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramBinary(GLuint program, GLenum binaryFormat, const void * binary, GLsizei length)
+
+ Convenience function that calls glProgramBinary(\a program, \a binaryFormat, \a binary, \a length).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramBinary.xml}{glProgramBinary()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramParameteri(GLuint program, GLenum pname, GLint value)
+
+ Convenience function that calls glProgramParameteri(\a program, \a pname, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramParameteri.xml}{glProgramParameteri()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glReadBuffer(GLenum src)
+
+ Convenience function that calls glReadBuffer(\a src).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glReadBuffer.xml}{glReadBuffer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
+
+ Convenience function that calls glRenderbufferStorageMultisample(\a target, \a samples, \a internalformat, \a width, \a height).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glRenderbufferStorageMultisample.xml}{glRenderbufferStorageMultisample()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glResumeTransformFeedback(void)
+
+ Convenience function that calls glResumeTransformFeedback().
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glResumeTransformFeedback.xml}{glResumeTransformFeedback()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glSamplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
+
+ Convenience function that calls glSamplerParameterf(\a sampler, \a pname, \a param).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glSamplerParameterf.xml}{glSamplerParameterf()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glSamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat * param)
+
+ Convenience function that calls glSamplerParameterfv(\a sampler, \a pname, \a param).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glSamplerParameterfv.xml}{glSamplerParameterfv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glSamplerParameteri(GLuint sampler, GLenum pname, GLint param)
+
+ Convenience function that calls glSamplerParameteri(\a sampler, \a pname, \a param).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glSamplerParameteri.xml}{glSamplerParameteri()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glSamplerParameteriv(GLuint sampler, GLenum pname, const GLint * param)
+
+ Convenience function that calls glSamplerParameteriv(\a sampler, \a pname, \a param).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glSamplerParameteriv.xml}{glSamplerParameteriv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels)
+
+ Convenience function that calls glTexImage3D(\a target, \a level, \a internalformat, \a width, \a height, \a depth, \a border, \a format, \a type, \a pixels).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTexImage3D.xml}{glTexImage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
+
+ Convenience function that calls glTexStorage2D(\a target, \a levels, \a internalformat, \a width, \a height).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTexStorage2D.xml}{glTexStorage2D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
+
+ Convenience function that calls glTexStorage3D(\a target, \a levels, \a internalformat, \a width, \a height, \a depth).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTexStorage3D.xml}{glTexStorage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels)
+
+ Convenience function that calls glTexSubImage3D(\a target, \a level, \a xoffset, \a yoffset, \a zoffset, \a width, \a height, \a depth, \a format, \a type, \a pixels).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTexSubImage3D.xml}{glTexSubImage3D()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode)
+
+ Convenience function that calls glTransformFeedbackVaryings(\a program, \a count, \a varyings, \a bufferMode).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTransformFeedbackVaryings.xml}{glTransformFeedbackVaryings()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform1ui(GLint location, GLuint v0)
+
+ Convenience function that calls glUniform1ui(\a location, \a v0).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform1ui.xml}{glUniform1ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform1uiv(GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glUniform1uiv(\a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform1uiv.xml}{glUniform1uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform2ui(GLint location, GLuint v0, GLuint v1)
+
+ Convenience function that calls glUniform2ui(\a location, \a v0, \a v1).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform2ui.xml}{glUniform2ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform2uiv(GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glUniform2uiv(\a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform2uiv.xml}{glUniform2uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
+
+ Convenience function that calls glUniform3ui(\a location, \a v0, \a v1, \a v2).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform3ui.xml}{glUniform3ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform3uiv(GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glUniform3uiv(\a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform3uiv.xml}{glUniform3uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+
+ Convenience function that calls glUniform4ui(\a location, \a v0, \a v1, \a v2, \a v3).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform4ui.xml}{glUniform4ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniform4uiv(GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glUniform4uiv(\a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniform4uiv.xml}{glUniform4uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
+
+ Convenience function that calls glUniformBlockBinding(\a program, \a uniformBlockIndex, \a uniformBlockBinding).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformBlockBinding.xml}{glUniformBlockBinding()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix2x3fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix2x3fv.xml}{glUniformMatrix2x3fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix2x4fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix2x4fv.xml}{glUniformMatrix2x4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix3x2fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix3x2fv.xml}{glUniformMatrix3x2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix3x4fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix3x4fv.xml}{glUniformMatrix3x4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix4x2fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix4x2fv.xml}{glUniformMatrix4x2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glUniformMatrix4x3fv(\a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUniformMatrix4x3fv.xml}{glUniformMatrix4x3fv()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glUnmapBuffer(GLenum target)
+
+ Convenience function that calls glUnmapBuffer(\a target).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUnmapBuffer.xml}{glUnmapBuffer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribDivisor(GLuint index, GLuint divisor)
+
+ Convenience function that calls glVertexAttribDivisor(\a index, \a divisor).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribDivisor.xml}{glVertexAttribDivisor()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w)
+
+ Convenience function that calls glVertexAttribI4i(\a index, \a x, \a y, \a z, \a w).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribI4i.xml}{glVertexAttribI4i()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribI4iv(GLuint index, const GLint * v)
+
+ Convenience function that calls glVertexAttribI4iv(\a index, \a v).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribI4iv.xml}{glVertexAttribI4iv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w)
+
+ Convenience function that calls glVertexAttribI4ui(\a index, \a x, \a y, \a z, \a w).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribI4ui.xml}{glVertexAttribI4ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribI4uiv(GLuint index, const GLuint * v)
+
+ Convenience function that calls glVertexAttribI4uiv(\a index, \a v).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribI4uiv.xml}{glVertexAttribI4uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer)
+
+ Convenience function that calls glVertexAttribIPointer(\a index, \a size, \a type, \a stride, \a pointer).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribIPointer.xml}{glVertexAttribIPointer()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+
+ Convenience function that calls glWaitSync(\a sync, \a flags, \a timeout).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glWaitSync.xml}{glWaitSync()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glActiveShaderProgram(GLuint pipeline, GLuint program)
+
+ Convenience function that calls glActiveShaderProgram(\a pipeline, \a program).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glActiveShaderProgram.xml}{glActiveShaderProgram()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)
+
+ Convenience function that calls glBindImageTexture(\a unit, \a texture, \a level, \a layered, \a layer, \a access, \a format).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindImageTexture.xml}{glBindImageTexture()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindProgramPipeline(GLuint pipeline)
+
+ Convenience function that calls glBindProgramPipeline(\a pipeline).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindProgramPipeline.xml}{glBindProgramPipeline()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride)
+
+ Convenience function that calls glBindVertexBuffer(\a bindingindex, \a buffer, \a offset, \a stride).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glBindVertexBuffer.xml}{glBindVertexBuffer()}.
+*/
+
+/*!
+ \fn GLuint QOpenGLExtraFunctions::glCreateShaderProgramv(GLenum type, GLsizei count, const GLchar *const* strings)
+
+ Convenience function that calls glCreateShaderProgramv(\a type, \a count, \a strings).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glCreateShaderProgramv.xml}{glCreateShaderProgramv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDeleteProgramPipelines(GLsizei n, const GLuint * pipelines)
+
+ Convenience function that calls glDeleteProgramPipelines(\a n, \a pipelines).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDeleteProgramPipelines.xml}{glDeleteProgramPipelines()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
+
+ Convenience function that calls glDispatchCompute(\a num_groups_x, \a num_groups_y, \a num_groups_z).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDispatchCompute.xml}{glDispatchCompute()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDispatchComputeIndirect(GLintptr indirect)
+
+ Convenience function that calls glDispatchComputeIndirect(\a indirect).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDispatchComputeIndirect.xml}{glDispatchComputeIndirect()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawArraysIndirect(GLenum mode, const void * indirect)
+
+ Convenience function that calls glDrawArraysIndirect(\a mode, \a indirect).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawArraysIndirect.xml}{glDrawArraysIndirect()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glDrawElementsIndirect(GLenum mode, GLenum type, const void * indirect)
+
+ Convenience function that calls glDrawElementsIndirect(\a mode, \a type, \a indirect).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glDrawElementsIndirect.xml}{glDrawElementsIndirect()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glFramebufferParameteri(GLenum target, GLenum pname, GLint param)
+
+ Convenience function that calls glFramebufferParameteri(\a target, \a pname, \a param).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glFramebufferParameteri.xml}{glFramebufferParameteri()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGenProgramPipelines(GLsizei n, GLuint* pipelines)
+
+ Convenience function that calls glGenProgramPipelines(\a n, \a pipelines).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGenProgramPipelines.xml}{glGenProgramPipelines()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetBooleani_v(GLenum target, GLuint index, GLboolean* data)
+
+ Convenience function that calls glGetBooleani_v(\a target, \a index, \a data).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetBooleani_v.xml}{glGetBooleani_v()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetFramebufferParameteriv(GLenum target, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetFramebufferParameteriv(\a target, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetFramebufferParameteriv.xml}{glGetFramebufferParameteriv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetMultisamplefv(GLenum pname, GLuint index, GLfloat* val)
+
+ Convenience function that calls glGetMultisamplefv(\a pname, \a index, \a val).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetMultisamplefv.xml}{glGetMultisamplefv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramInterfaceiv(GLuint program, GLenum programInterface, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetProgramInterfaceiv(\a program, \a programInterface, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramInterfaceiv.xml}{glGetProgramInterfaceiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramPipelineInfoLog(GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog)
+
+ Convenience function that calls glGetProgramPipelineInfoLog(\a pipeline, \a bufSize, \a length, \a infoLog).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramPipelineInfoLog.xml}{glGetProgramPipelineInfoLog()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetProgramPipelineiv(\a pipeline, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramPipelineiv.xml}{glGetProgramPipelineiv()}.
+*/
+
+/*!
+ \fn GLuint QOpenGLExtraFunctions::glGetProgramResourceIndex(GLuint program, GLenum programInterface, const GLchar * name)
+
+ Convenience function that calls glGetProgramResourceIndex(\a program, \a programInterface, \a name).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramResourceIndex.xml}{glGetProgramResourceIndex()}.
+*/
+
+/*!
+ \fn GLint QOpenGLExtraFunctions::glGetProgramResourceLocation(GLuint program, GLenum programInterface, const GLchar * name)
+
+ Convenience function that calls glGetProgramResourceLocation(\a program, \a programInterface, \a name).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramResourceLocation.xml}{glGetProgramResourceLocation()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramResourceName(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei* length, GLchar* name)
+
+ Convenience function that calls glGetProgramResourceName(\a program, \a programInterface, \a index, \a bufSize, \a length, \a name).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramResourceName.xml}{glGetProgramResourceName()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum * props, GLsizei bufSize, GLsizei* length, GLint* params)
+
+ Convenience function that calls glGetProgramResourceiv(\a program, \a programInterface, \a index, \a propCount, \a props, \a bufSize, \a length, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetProgramResourceiv.xml}{glGetProgramResourceiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat* params)
+
+ Convenience function that calls glGetTexLevelParameterfv(\a target, \a level, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetTexLevelParameterfv.xml}{glGetTexLevelParameterfv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params)
+
+ Convenience function that calls glGetTexLevelParameteriv(\a target, \a level, \a pname, \a params).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glGetTexLevelParameteriv.xml}{glGetTexLevelParameteriv()}.
+*/
+
+/*!
+ \fn GLboolean QOpenGLExtraFunctions::glIsProgramPipeline(GLuint pipeline)
+
+ Convenience function that calls glIsProgramPipeline(\a pipeline).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glIsProgramPipeline.xml}{glIsProgramPipeline()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glMemoryBarrier(GLbitfield barriers)
+
+ Convenience function that calls glMemoryBarrier(\a barriers).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glMemoryBarrier.xml}{glMemoryBarrier()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glMemoryBarrierByRegion(GLbitfield barriers)
+
+ Convenience function that calls glMemoryBarrierByRegion(\a barriers).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glMemoryBarrierByRegion.xml}{glMemoryBarrierByRegion()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1f(GLuint program, GLint location, GLfloat v0)
+
+ Convenience function that calls glProgramUniform1f(\a program, \a location, \a v0).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1f.xml}{glProgramUniform1f()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+
+ Convenience function that calls glProgramUniform1fv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1fv.xml}{glProgramUniform1fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1i(GLuint program, GLint location, GLint v0)
+
+ Convenience function that calls glProgramUniform1i(\a program, \a location, \a v0).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1i.xml}{glProgramUniform1i()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+
+ Convenience function that calls glProgramUniform1iv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1iv.xml}{glProgramUniform1iv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1ui(GLuint program, GLint location, GLuint v0)
+
+ Convenience function that calls glProgramUniform1ui(\a program, \a location, \a v0).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1ui.xml}{glProgramUniform1ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform1uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glProgramUniform1uiv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform1uiv.xml}{glProgramUniform1uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2f(GLuint program, GLint location, GLfloat v0, GLfloat v1)
+
+ Convenience function that calls glProgramUniform2f(\a program, \a location, \a v0, \a v1).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2f.xml}{glProgramUniform2f()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+
+ Convenience function that calls glProgramUniform2fv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2fv.xml}{glProgramUniform2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2i(GLuint program, GLint location, GLint v0, GLint v1)
+
+ Convenience function that calls glProgramUniform2i(\a program, \a location, \a v0, \a v1).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2i.xml}{glProgramUniform2i()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+
+ Convenience function that calls glProgramUniform2iv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2iv.xml}{glProgramUniform2iv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2ui(GLuint program, GLint location, GLuint v0, GLuint v1)
+
+ Convenience function that calls glProgramUniform2ui(\a program, \a location, \a v0, \a v1).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2ui.xml}{glProgramUniform2ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform2uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glProgramUniform2uiv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform2uiv.xml}{glProgramUniform2uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
+
+ Convenience function that calls glProgramUniform3f(\a program, \a location, \a v0, \a v1, \a v2).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3f.xml}{glProgramUniform3f()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+
+ Convenience function that calls glProgramUniform3fv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3fv.xml}{glProgramUniform3fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2)
+
+ Convenience function that calls glProgramUniform3i(\a program, \a location, \a v0, \a v1, \a v2).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3i.xml}{glProgramUniform3i()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+
+ Convenience function that calls glProgramUniform3iv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3iv.xml}{glProgramUniform3iv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2)
+
+ Convenience function that calls glProgramUniform3ui(\a program, \a location, \a v0, \a v1, \a v2).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3ui.xml}{glProgramUniform3ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform3uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glProgramUniform3uiv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform3uiv.xml}{glProgramUniform3uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
+
+ Convenience function that calls glProgramUniform4f(\a program, \a location, \a v0, \a v1, \a v2, \a v3).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4f.xml}{glProgramUniform4f()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+
+ Convenience function that calls glProgramUniform4fv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4fv.xml}{glProgramUniform4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
+
+ Convenience function that calls glProgramUniform4i(\a program, \a location, \a v0, \a v1, \a v2, \a v3).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4i.xml}{glProgramUniform4i()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+
+ Convenience function that calls glProgramUniform4iv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4iv.xml}{glProgramUniform4iv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+
+ Convenience function that calls glProgramUniform4ui(\a program, \a location, \a v0, \a v1, \a v2, \a v3).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4ui.xml}{glProgramUniform4ui()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniform4uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+
+ Convenience function that calls glProgramUniform4uiv(\a program, \a location, \a count, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniform4uiv.xml}{glProgramUniform4uiv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix2fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix2fv.xml}{glProgramUniformMatrix2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix2x3fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix2x3fv.xml}{glProgramUniformMatrix2x3fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix2x4fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix2x4fv.xml}{glProgramUniformMatrix2x4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix3fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix3fv.xml}{glProgramUniformMatrix3fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix3x2fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix3x2fv.xml}{glProgramUniformMatrix3x2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix3x4fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix3x4fv.xml}{glProgramUniformMatrix3x4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix4fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix4fv.xml}{glProgramUniformMatrix4fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix4x2fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix4x2fv.xml}{glProgramUniformMatrix4x2fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+
+ Convenience function that calls glProgramUniformMatrix4x3fv(\a program, \a location, \a count, \a transpose, \a value).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glProgramUniformMatrix4x3fv.xml}{glProgramUniformMatrix4x3fv()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glSampleMaski(GLuint maskNumber, GLbitfield mask)
+
+ Convenience function that calls glSampleMaski(\a maskNumber, \a mask).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glSampleMaski.xml}{glSampleMaski()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
+
+ Convenience function that calls glTexStorage2DMultisample(\a target, \a samples, \a internalformat, \a width, \a height, \a fixedsamplelocations).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glTexStorage2DMultisample.xml}{glTexStorage2DMultisample()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glUseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program)
+
+ Convenience function that calls glUseProgramStages(\a pipeline, \a stages, \a program).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glUseProgramStages.xml}{glUseProgramStages()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glValidateProgramPipeline(GLuint pipeline)
+
+ Convenience function that calls glValidateProgramPipeline(\a pipeline).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glValidateProgramPipeline.xml}{glValidateProgramPipeline()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribBinding(GLuint attribindex, GLuint bindingindex)
+
+ Convenience function that calls glVertexAttribBinding(\a attribindex, \a bindingindex).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribBinding.xml}{glVertexAttribBinding()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset)
+
+ Convenience function that calls glVertexAttribFormat(\a attribindex, \a size, \a type, \a normalized, \a relativeoffset).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribFormat.xml}{glVertexAttribFormat()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset)
+
+ Convenience function that calls glVertexAttribIFormat(\a attribindex, \a size, \a type, \a relativeoffset).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexAttribIFormat.xml}{glVertexAttribIFormat()}.
+*/
+
+/*!
+ \fn void QOpenGLExtraFunctions::glVertexBindingDivisor(GLuint bindingindex, GLuint divisor)
+
+ Convenience function that calls glVertexBindingDivisor(\a bindingindex, \a divisor).
+
+ This function is only available in OpenGL ES 3.x, or OpenGL 3.x or 4.x contexts. When running
+ with plain OpenGL, the function is only usable when the given profile and version contains the
+ function either in core or as an extension.
+
+ For more information, see the OpenGL ES 3.x documentation for
+ \l{http://www.khronos.org/opengles/sdk/docs/man31/glVertexBindingDivisor.xml}{glVertexBindingDivisor()}.
+*/
+
+/*!
+ \fn bool QOpenGLExtraFunctions::isInitialized(const QOpenGLExtraFunctionsPrivate *d)
+ \internal
+*/
+
+// Functions part of the OpenGL ES 3.0+ standard need special handling. These, just like
+// the 2.0 functions, are not guaranteed to be resolvable via eglGetProcAddress or
+// similar. (we cannot count on EGL_KHR_(client_)get_all_proc_addresses being available)
+
+// Calling them directly is, unlike the 2.0 functions, not feasible because one may build
+// the binaries on a GLES3-capable system and then deploy on a GLES2-only system that does
+// not have these symbols, and vice versa. Until ES3 becomes universally available, they
+// have to be dlsym'ed.
+
+Q_GLOBAL_STATIC(QOpenGLES3Helper, qgles3Helper)
+
+bool QOpenGLES3Helper::init()
{
- MapBuffer = qopenglfResolveMapBuffer;
- MapBufferRange = qopenglfResolveMapBufferRange;
+#ifdef QT_NO_LIBRARY
+ return false;
+#elif !defined(Q_OS_IOS)
+# ifdef Q_OS_WIN
+# ifndef QT_DEBUG
+ m_gl.setFileName(QStringLiteral("libGLESv2"));
+# else
+ m_gl.setFileName(QStringLiteral("libGLESv2d"));
+# endif
+# else
+# ifdef Q_OS_ANDROID
+ m_gl.setFileName(QStringLiteral("GLESv2"));
+# else
+ m_gl.setFileNameAndVersion(QStringLiteral("GLESv2"), 2);
+# endif
+# endif // Q_OS_WIN
+ return m_gl.load();
+#else
+ return true;
+#endif // Q_OS_IOS
+}
+
+QFunctionPointer QOpenGLES3Helper::resolve(const char *name)
+{
+#ifdef Q_OS_IOS
+ return QFunctionPointer(dlsym(RTLD_DEFAULT, name));
+#elif !defined(QT_NO_LIBRARY)
+ return m_gl.resolve(name);
+#else
+ Q_UNUSED(name);
+ return 0;
+#endif
+}
+
+QOpenGLES3Helper::QOpenGLES3Helper()
+{
+ m_supportedVersion = qMakePair(2, 0);
+
+ if (init()) {
+ const QPair<int, int> contextVersion = QOpenGLContext::currentContext()->format().version();
+
+ qCDebug(lcGLES3, "Resolving OpenGL ES 3.0 entry points");
+
+ BeginQuery = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint)) resolve("glBeginQuery");
+ BeginTransformFeedback = (void (QOPENGLF_APIENTRYP) (GLenum)) resolve("glBeginTransformFeedback");
+ BindBufferBase = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLuint)) resolve("glBindBufferBase");
+ BindBufferRange = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr)) resolve("glBindBufferRange");
+ BindSampler = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint)) resolve("glBindSampler");
+ BindTransformFeedback = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint)) resolve("glBindTransformFeedback");
+ BindVertexArray = (void (QOPENGLF_APIENTRYP) (GLuint)) resolve("glBindVertexArray");
+ BlitFramebuffer = (void (QOPENGLF_APIENTRYP) (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum)) resolve("glBlitFramebuffer");
+ ClearBufferfi = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLfloat, GLint)) resolve("glClearBufferfi");
+ ClearBufferfv = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, const GLfloat *)) resolve("glClearBufferfv");
+ ClearBufferiv = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, const GLint *)) resolve("glClearBufferiv");
+ ClearBufferuiv = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, const GLuint *)) resolve("glClearBufferuiv");
+ ClientWaitSync = (GLenum (QOPENGLF_APIENTRYP) (GLsync, GLbitfield, GLuint64)) resolve("glClientWaitSync");
+ CompressedTexImage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const void *)) resolve("glCompressedTexImage3D");
+ CompressedTexSubImage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const void *)) resolve("glCompressedTexSubImage3D");
+ CopyBufferSubData = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr)) resolve("glCopyBufferSubData");
+ CopyTexSubImage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei)) resolve("glCopyTexSubImage3D");
+ DeleteQueries = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLuint *)) resolve("glDeleteQueries");
+ DeleteSamplers = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLuint *)) resolve("glDeleteSamplers");
+ DeleteSync = (void (QOPENGLF_APIENTRYP) (GLsync)) resolve("glDeleteSync");
+ DeleteTransformFeedbacks = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLuint *)) resolve("glDeleteTransformFeedbacks");
+ DeleteVertexArrays = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLuint *)) resolve("glDeleteVertexArrays");
+ DrawArraysInstanced = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLsizei, GLsizei)) resolve("glDrawArraysInstanced");
+ DrawBuffers = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLenum *)) resolve("glDrawBuffers");
+ DrawElementsInstanced = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, GLenum, const void *, GLsizei)) resolve("glDrawElementsInstanced");
+ DrawRangeElements = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLuint, GLsizei, GLenum, const void *)) resolve("glDrawRangeElements");
+ EndQuery = (void (QOPENGLF_APIENTRYP) (GLenum)) resolve("glEndQuery");
+ EndTransformFeedback = (void (QOPENGLF_APIENTRYP) ()) resolve("glEndTransformFeedback");
+ FenceSync = (GLsync (QOPENGLF_APIENTRYP) (GLenum, GLbitfield)) resolve("glFenceSync");
+ FlushMappedBufferRange = (void (QOPENGLF_APIENTRYP) (GLenum, GLintptr, GLsizeiptr)) resolve("glFlushMappedBufferRange");
+ FramebufferTextureLayer = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLuint, GLint, GLint)) resolve("glFramebufferTextureLayer");
+ GenQueries = (void (QOPENGLF_APIENTRYP) (GLsizei, GLuint*)) resolve("glGenQueries");
+ GenSamplers = (void (QOPENGLF_APIENTRYP) (GLsizei, GLuint*)) resolve("glGenSamplers");
+ GenTransformFeedbacks = (void (QOPENGLF_APIENTRYP) (GLsizei, GLuint*)) resolve("glGenTransformFeedbacks");
+ GenVertexArrays = (void (QOPENGLF_APIENTRYP) (GLsizei, GLuint*)) resolve("glGenVertexArrays");
+ GetActiveUniformBlockName = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLsizei, GLsizei*, GLchar*)) resolve("glGetActiveUniformBlockName");
+ GetActiveUniformBlockiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLenum, GLint*)) resolve("glGetActiveUniformBlockiv");
+ GetActiveUniformsiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLsizei, const GLuint *, GLenum, GLint*)) resolve("glGetActiveUniformsiv");
+ GetBufferParameteri64v = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLint64*)) resolve("glGetBufferParameteri64v");
+ GetBufferPointerv = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, void **)) resolve("glGetBufferPointerv");
+ GetFragDataLocation = (GLint (QOPENGLF_APIENTRYP) (GLuint, const GLchar *)) resolve("glGetFragDataLocation");
+ GetInteger64i_v = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLint64*)) resolve("glGetInteger64i_v");
+ GetInteger64v = (void (QOPENGLF_APIENTRYP) (GLenum, GLint64*)) resolve("glGetInteger64v");
+ GetIntegeri_v = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLint*)) resolve("glGetIntegeri_v");
+ GetInternalformativ = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLenum, GLsizei, GLint*)) resolve("glGetInternalformativ");
+ GetProgramBinary = (void (QOPENGLF_APIENTRYP) (GLuint, GLsizei, GLsizei*, GLenum*, void *)) resolve("glGetProgramBinary");
+ GetQueryObjectuiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLuint*)) resolve("glGetQueryObjectuiv");
+ GetQueryiv = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLint*)) resolve("glGetQueryiv");
+ GetSamplerParameterfv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLfloat*)) resolve("glGetSamplerParameterfv");
+ GetSamplerParameteriv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLint*)) resolve("glGetSamplerParameteriv");
+ GetStringi = (const GLubyte * (QOPENGLF_APIENTRYP) (GLenum, GLuint)) resolve("glGetStringi");
+ GetSynciv = (void (QOPENGLF_APIENTRYP) (GLsync, GLenum, GLsizei, GLsizei*, GLint*)) resolve("glGetSynciv");
+ GetTransformFeedbackVarying = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*)) resolve("glGetTransformFeedbackVarying");
+ GetUniformBlockIndex = (GLuint (QOPENGLF_APIENTRYP) (GLuint, const GLchar *)) resolve("glGetUniformBlockIndex");
+ GetUniformIndices = (void (QOPENGLF_APIENTRYP) (GLuint, GLsizei, const GLchar *const*, GLuint*)) resolve("glGetUniformIndices");
+ GetUniformuiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLuint*)) resolve("glGetUniformuiv");
+ GetVertexAttribIiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLint*)) resolve("glGetVertexAttribIiv");
+ GetVertexAttribIuiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLuint*)) resolve("glGetVertexAttribIuiv");
+ InvalidateFramebuffer = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, const GLenum *)) resolve("glInvalidateFramebuffer");
+ InvalidateSubFramebuffer = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei)) resolve("glInvalidateSubFramebuffer");
+ IsQuery = (GLboolean (QOPENGLF_APIENTRYP) (GLuint)) resolve("glIsQuery");
+ IsSampler = (GLboolean (QOPENGLF_APIENTRYP) (GLuint)) resolve("glIsSampler");
+ IsSync = (GLboolean (QOPENGLF_APIENTRYP) (GLsync)) resolve("glIsSync");
+ IsTransformFeedback = (GLboolean (QOPENGLF_APIENTRYP) (GLuint)) resolve("glIsTransformFeedback");
+ IsVertexArray = (GLboolean (QOPENGLF_APIENTRYP) (GLuint)) resolve("glIsVertexArray");
+ MapBufferRange = (void * (QOPENGLF_APIENTRYP) (GLenum, GLintptr, GLsizeiptr, GLbitfield)) resolve("glMapBufferRange");
+ PauseTransformFeedback = (void (QOPENGLF_APIENTRYP) ()) resolve("glPauseTransformFeedback");
+ ProgramBinary = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, const void *, GLsizei)) resolve("glProgramBinary");
+ ProgramParameteri = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLint)) resolve("glProgramParameteri");
+ ReadBuffer = (void (QOPENGLF_APIENTRYP) (GLenum)) resolve("glReadBuffer");
+ RenderbufferStorageMultisample = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, GLenum, GLsizei, GLsizei)) resolve("glRenderbufferStorageMultisample");
+ ResumeTransformFeedback = (void (QOPENGLF_APIENTRYP) ()) resolve("glResumeTransformFeedback");
+ SamplerParameterf = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLfloat)) resolve("glSamplerParameterf");
+ SamplerParameterfv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, const GLfloat *)) resolve("glSamplerParameterfv");
+ SamplerParameteri = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLint)) resolve("glSamplerParameteri");
+ SamplerParameteriv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, const GLint *)) resolve("glSamplerParameteriv");
+ TexImage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) resolve("glTexImage3D");
+ TexStorage2D = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, GLenum, GLsizei, GLsizei)) resolve("glTexStorage2D");
+ TexStorage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei)) resolve("glTexStorage3D");
+ TexSubImage3D = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const void *)) resolve("glTexSubImage3D");
+ TransformFeedbackVaryings = (void (QOPENGLF_APIENTRYP) (GLuint, GLsizei, const GLchar *const*, GLenum)) resolve("glTransformFeedbackVaryings");
+ Uniform1ui = (void (QOPENGLF_APIENTRYP) (GLint, GLuint)) resolve("glUniform1ui");
+ Uniform1uiv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, const GLuint *)) resolve("glUniform1uiv");
+ Uniform2ui = (void (QOPENGLF_APIENTRYP) (GLint, GLuint, GLuint)) resolve("glUniform2ui");
+ Uniform2uiv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, const GLuint *)) resolve("glUniform2uiv");
+ Uniform3ui = (void (QOPENGLF_APIENTRYP) (GLint, GLuint, GLuint, GLuint)) resolve("glUniform3ui");
+ Uniform3uiv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, const GLuint *)) resolve("glUniform3uiv");
+ Uniform4ui = (void (QOPENGLF_APIENTRYP) (GLint, GLuint, GLuint, GLuint, GLuint)) resolve("glUniform4ui");
+ Uniform4uiv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, const GLuint *)) resolve("glUniform4uiv");
+ UniformBlockBinding = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLuint)) resolve("glUniformBlockBinding");
+ UniformMatrix2x3fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix2x3fv");
+ UniformMatrix2x4fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix2x4fv");
+ UniformMatrix3x2fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix3x2fv");
+ UniformMatrix3x4fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix3x4fv");
+ UniformMatrix4x2fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix4x2fv");
+ UniformMatrix4x3fv = (void (QOPENGLF_APIENTRYP) (GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glUniformMatrix4x3fv");
+ UnmapBuffer = (GLboolean (QOPENGLF_APIENTRYP) (GLenum)) resolve("glUnmapBuffer");
+ VertexAttribDivisor = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint)) resolve("glVertexAttribDivisor");
+ VertexAttribI4i = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLint, GLint, GLint)) resolve("glVertexAttribI4i");
+ VertexAttribI4iv = (void (QOPENGLF_APIENTRYP) (GLuint, const GLint *)) resolve("glVertexAttribI4iv");
+ VertexAttribI4ui = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLuint, GLuint, GLuint)) resolve("glVertexAttribI4ui");
+ VertexAttribI4uiv = (void (QOPENGLF_APIENTRYP) (GLuint, const GLuint *)) resolve("glVertexAttribI4uiv");
+ VertexAttribIPointer = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLenum, GLsizei, const void *)) resolve("glVertexAttribIPointer");
+ WaitSync = (void (QOPENGLF_APIENTRYP) (GLsync, GLbitfield, GLuint64)) resolve("glWaitSync");
+
+ if (!BeginQuery || !BlitFramebuffer || !GenTransformFeedbacks || !GenVertexArrays || !MapBufferRange
+ || !RenderbufferStorageMultisample || !TexStorage2D || !WaitSync) {
+ qWarning("OpenGL ES 3.0 entry points not found. This is odd because the driver returned a context of version %d.%d",
+ contextVersion.first, contextVersion.second);
+ return;
+ }
+ m_supportedVersion = qMakePair(3, 0);
+
+ if (contextVersion >= qMakePair(3, 1)) {
+ qCDebug(lcGLES3, "Resolving OpenGL ES 3.1 entry points");
+
+ ActiveShaderProgram = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint)) resolve("glActiveShaderProgram");
+ BindImageTexture = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLint, GLboolean, GLint, GLenum, GLenum)) resolve("glBindImageTexture");
+ BindProgramPipeline = (void (QOPENGLF_APIENTRYP) (GLuint)) resolve("glBindProgramPipeline");
+ BindVertexBuffer = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLintptr, GLsizei)) resolve("glBindVertexBuffer");
+ CreateShaderProgramv = (GLuint (QOPENGLF_APIENTRYP) (GLenum, GLsizei, const GLchar *const*)) resolve("glCreateShaderProgramv");
+ DeleteProgramPipelines = (void (QOPENGLF_APIENTRYP) (GLsizei, const GLuint *)) resolve("glDeleteProgramPipelines");
+ DispatchCompute = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint, GLuint)) resolve("glDispatchCompute");
+ DispatchComputeIndirect = (void (QOPENGLF_APIENTRYP) (GLintptr)) resolve("glDispatchComputeIndirect");
+ DrawArraysIndirect = (void (QOPENGLF_APIENTRYP) (GLenum, const void *)) resolve("glDrawArraysIndirect");
+ DrawElementsIndirect = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, const void *)) resolve("glDrawElementsIndirect");
+ FramebufferParameteri = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLint)) resolve("glFramebufferParameteri");
+ GenProgramPipelines = (void (QOPENGLF_APIENTRYP) (GLsizei, GLuint*)) resolve("glGenProgramPipelines");
+ GetBooleani_v = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLboolean*)) resolve("glGetBooleani_v");
+ GetFramebufferParameteriv = (void (QOPENGLF_APIENTRYP) (GLenum, GLenum, GLint*)) resolve("glGetFramebufferParameteriv");
+ GetMultisamplefv = (void (QOPENGLF_APIENTRYP) (GLenum, GLuint, GLfloat*)) resolve("glGetMultisamplefv");
+ GetProgramInterfaceiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLenum, GLint*)) resolve("glGetProgramInterfaceiv");
+ GetProgramPipelineInfoLog = (void (QOPENGLF_APIENTRYP) (GLuint, GLsizei, GLsizei*, GLchar*)) resolve("glGetProgramPipelineInfoLog");
+ GetProgramPipelineiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLint*)) resolve("glGetProgramPipelineiv");
+ GetProgramResourceIndex = (GLuint (QOPENGLF_APIENTRYP) (GLuint, GLenum, const GLchar *)) resolve("glGetProgramResourceIndex");
+ GetProgramResourceLocation = (GLint (QOPENGLF_APIENTRYP) (GLuint, GLenum, const GLchar *)) resolve("glGetProgramResourceLocation");
+ GetProgramResourceName = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLuint, GLsizei, GLsizei*, GLchar*)) resolve("glGetProgramResourceName");
+ GetProgramResourceiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLenum, GLuint, GLsizei, const GLenum *, GLsizei, GLsizei*, GLint*)) resolve("glGetProgramResourceiv");
+ GetTexLevelParameterfv = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLenum, GLfloat*)) resolve("glGetTexLevelParameterfv");
+ GetTexLevelParameteriv = (void (QOPENGLF_APIENTRYP) (GLenum, GLint, GLenum, GLint*)) resolve("glGetTexLevelParameteriv");
+ IsProgramPipeline = (GLboolean (QOPENGLF_APIENTRYP) (GLuint)) resolve("glIsProgramPipeline");
+ MemoryBarrierFunc = (void (QOPENGLF_APIENTRYP) (GLbitfield)) resolve("glMemoryBarrier");
+ MemoryBarrierByRegion = (void (QOPENGLF_APIENTRYP) (GLbitfield)) resolve("glMemoryBarrierByRegion");
+ ProgramUniform1f = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLfloat)) resolve("glProgramUniform1f");
+ ProgramUniform1fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLfloat *)) resolve("glProgramUniform1fv");
+ ProgramUniform1i = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLint)) resolve("glProgramUniform1i");
+ ProgramUniform1iv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLint *)) resolve("glProgramUniform1iv");
+ ProgramUniform1ui = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLuint)) resolve("glProgramUniform1ui");
+ ProgramUniform1uiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLuint *)) resolve("glProgramUniform1uiv");
+ ProgramUniform2f = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLfloat, GLfloat)) resolve("glProgramUniform2f");
+ ProgramUniform2fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLfloat *)) resolve("glProgramUniform2fv");
+ ProgramUniform2i = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLint, GLint)) resolve("glProgramUniform2i");
+ ProgramUniform2iv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLint *)) resolve("glProgramUniform2iv");
+ ProgramUniform2ui = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLuint, GLuint)) resolve("glProgramUniform2ui");
+ ProgramUniform2uiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLuint *)) resolve("glProgramUniform2uiv");
+ ProgramUniform3f = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLfloat, GLfloat, GLfloat)) resolve("glProgramUniform3f");
+ ProgramUniform3fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLfloat *)) resolve("glProgramUniform3fv");
+ ProgramUniform3i = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLint, GLint, GLint)) resolve("glProgramUniform3i");
+ ProgramUniform3iv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLint *)) resolve("glProgramUniform3iv");
+ ProgramUniform3ui = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLuint, GLuint, GLuint)) resolve("glProgramUniform3ui");
+ ProgramUniform3uiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLuint *)) resolve("glProgramUniform3uiv");
+ ProgramUniform4f = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLfloat, GLfloat, GLfloat, GLfloat)) resolve("glProgramUniform4f");
+ ProgramUniform4fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLfloat *)) resolve("glProgramUniform4fv");
+ ProgramUniform4i = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLint, GLint, GLint, GLint)) resolve("glProgramUniform4i");
+ ProgramUniform4iv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLint *)) resolve("glProgramUniform4iv");
+ ProgramUniform4ui = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLuint, GLuint, GLuint, GLuint)) resolve("glProgramUniform4ui");
+ ProgramUniform4uiv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, const GLuint *)) resolve("glProgramUniform4uiv");
+ ProgramUniformMatrix2fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix2fv");
+ ProgramUniformMatrix2x3fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix2x3fv");
+ ProgramUniformMatrix2x4fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix2x4fv");
+ ProgramUniformMatrix3fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix3fv");
+ ProgramUniformMatrix3x2fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix3x2fv");
+ ProgramUniformMatrix3x4fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix3x4fv");
+ ProgramUniformMatrix4fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix4fv");
+ ProgramUniformMatrix4x2fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix4x2fv");
+ ProgramUniformMatrix4x3fv = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLsizei, GLboolean, const GLfloat *)) resolve("glProgramUniformMatrix4x3fv");
+ SampleMaski = (void (QOPENGLF_APIENTRYP) (GLuint, GLbitfield)) resolve("glSampleMaski");
+ TexStorage2DMultisample = (void (QOPENGLF_APIENTRYP) (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean)) resolve("glTexStorage2DMultisample");
+ UseProgramStages = (void (QOPENGLF_APIENTRYP) (GLuint, GLbitfield, GLuint)) resolve("glUseProgramStages");
+ ValidateProgramPipeline = (void (QOPENGLF_APIENTRYP) (GLuint)) resolve("glValidateProgramPipeline");
+ VertexAttribBinding = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint)) resolve("glVertexAttribBinding");
+ VertexAttribFormat = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLenum, GLboolean, GLuint)) resolve("glVertexAttribFormat");
+ VertexAttribIFormat = (void (QOPENGLF_APIENTRYP) (GLuint, GLint, GLenum, GLuint)) resolve("glVertexAttribIFormat");
+ VertexBindingDivisor = (void (QOPENGLF_APIENTRYP) (GLuint, GLuint)) resolve("glVertexBindingDivisor");
+
+ if (!ActiveShaderProgram || !BindImageTexture || !DispatchCompute || !DrawArraysIndirect
+ || !GenProgramPipelines || !MemoryBarrierFunc) {
+ qWarning("OpenGL ES 3.1 entry points not found. This is odd because the driver returned a context of version %d.%d",
+ contextVersion.first, contextVersion.second);
+ return;
+ }
+ m_supportedVersion = qMakePair(3, 1);
+ }
+ } else {
+ qFatal("Failed to load libGLESv2");
+ }
+}
+
+// GLES 3.0 and 3.1
+
+// Checks for true OpenGL ES 3.x. OpenGL with GL_ARB_ES3_compatibility
+// does not count because there the plain resolvers work anyhow.
+static inline bool isES3(int minor)
+{
+ QOpenGLContext *ctx = QOpenGLContext::currentContext();
+
+ const bool libMatches = QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES;
+ const bool contextMatches = ctx->isOpenGLES() && ctx->format().version() >= qMakePair(3, minor);
+
+ // Resolving happens whenever qgles3Helper() is called first. So do it only
+ // when the driver gives a 3.0+ context.
+ if (libMatches && contextMatches)
+ return qgles3Helper()->supportedVersion() >= qMakePair(3, minor);
+
+ return false;
+}
+
+// Go through the dlsym-based helper for real ES 3, resolve using
+// wglGetProcAddress or similar when on plain OpenGL.
+
+static void QOPENGLF_APIENTRY qopenglfResolveBeginQuery(GLenum target, GLuint id)
+{
+ if (isES3(0))
+ qgles3Helper()->BeginQuery(target, id);
+ else
+ RESOLVE_FUNC_VOID(0, BeginQuery)(target, id);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBeginTransformFeedback(GLenum primitiveMode)
+{
+ if (isES3(0))
+ qgles3Helper()->BeginTransformFeedback(primitiveMode);
+ else
+ RESOLVE_FUNC_VOID(0, BeginTransformFeedback)(primitiveMode);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindBufferBase(GLenum target, GLuint index, GLuint buffer)
+{
+ if (isES3(0))
+ qgles3Helper()->BindBufferBase(target, index, buffer);
+ else
+ RESOLVE_FUNC_VOID(0, BindBufferBase)(target, index, buffer);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
+{
+ if (isES3(0))
+ qgles3Helper()->BindBufferRange(target, index, buffer, offset, size);
+ else
+ RESOLVE_FUNC_VOID(0, BindBufferRange)(target, index, buffer, offset, size);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindSampler(GLuint unit, GLuint sampler)
+{
+ if (isES3(0))
+ qgles3Helper()->BindSampler(unit, sampler);
+ else
+ RESOLVE_FUNC_VOID(0, BindSampler)(unit, sampler);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindTransformFeedback(GLenum target, GLuint id)
+{
+ if (isES3(0))
+ qgles3Helper()->BindTransformFeedback(target, id);
+ else
+ RESOLVE_FUNC_VOID(0, BindTransformFeedback)(target, id);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindVertexArray(GLuint array)
+{
+ if (isES3(0))
+ qgles3Helper()->BindVertexArray(array);
+ else
+ RESOLVE_FUNC_VOID(0, BindVertexArray)(array);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
+{
+ if (isES3(0))
+ qgles3Helper()->BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+ else
+ RESOLVE_FUNC_VOID(ResolveEXT | ResolveANGLE | ResolveNV, BlitFramebuffer)
+ (srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
+{
+ if (isES3(0))
+ qgles3Helper()->ClearBufferfi(buffer, drawbuffer, depth, stencil);
+ else
+ RESOLVE_FUNC_VOID(0, ClearBufferfi)(buffer, drawbuffer, depth, stencil);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->ClearBufferfv(buffer, drawbuffer, value);
+ else
+ RESOLVE_FUNC_VOID(0, ClearBufferfv)(buffer, drawbuffer, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->ClearBufferiv(buffer, drawbuffer, value);
+ else
+ RESOLVE_FUNC_VOID(0, ClearBufferiv)(buffer, drawbuffer, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->ClearBufferuiv(buffer, drawbuffer, value);
+ else
+ RESOLVE_FUNC_VOID(0, ClearBufferuiv)(buffer, drawbuffer, value);
+}
+
+static GLenum QOPENGLF_APIENTRY qopenglfResolveClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+{
+ if (isES3(0))
+ return qgles3Helper()->ClientWaitSync(sync, flags, timeout);
+ else
+ RESOLVE_FUNC(GLenum, 0, ClientWaitSync)(sync, flags, timeout);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)
+{
+ if (isES3(0))
+ qgles3Helper()->CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data);
+ else
+ RESOLVE_FUNC_VOID(0, CompressedTexImage3D)(target, level, internalformat, width, height, depth, border, imageSize, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data)
+{
+ if (isES3(0))
+ qgles3Helper()->CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+ else
+ RESOLVE_FUNC_VOID(0, CompressedTexSubImage3D)(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
+{
+ if (isES3(0))
+ qgles3Helper()->CopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size);
+ else
+ RESOLVE_FUNC_VOID(0, CopyBufferSubData)(readTarget, writeTarget, readOffset, writeOffset, size);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ if (isES3(0))
+ qgles3Helper()->CopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
+ else
+ RESOLVE_FUNC_VOID(0, CopyTexSubImage3D)(target, level, xoffset, yoffset, zoffset, x, y, width, height);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteQueries(GLsizei n, const GLuint * ids)
+{
+ if (isES3(0))
+ qgles3Helper()->DeleteQueries(n, ids);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteQueries)(n, ids);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteSamplers(GLsizei count, const GLuint * samplers)
+{
+ if (isES3(0))
+ qgles3Helper()->DeleteSamplers(count, samplers);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteSamplers)(count, samplers);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteSync(GLsync sync)
+{
+ if (isES3(0))
+ qgles3Helper()->DeleteSync(sync);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteSync)(sync);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteTransformFeedbacks(GLsizei n, const GLuint * ids)
+{
+ if (isES3(0))
+ qgles3Helper()->DeleteTransformFeedbacks(n, ids);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteTransformFeedbacks)(n, ids);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteVertexArrays(GLsizei n, const GLuint * arrays)
+{
+ if (isES3(0))
+ qgles3Helper()->DeleteVertexArrays(n, arrays);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteVertexArrays)(n, arrays);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount)
+{
+ if (isES3(0))
+ qgles3Helper()->DrawArraysInstanced(mode, first, count, instancecount);
+ else
+ RESOLVE_FUNC_VOID(0, DrawArraysInstanced)(mode, first, count, instancecount);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawBuffers(GLsizei n, const GLenum * bufs)
+{
+ if (isES3(0))
+ qgles3Helper()->DrawBuffers(n, bufs);
+ else
+ RESOLVE_FUNC_VOID(0, DrawBuffers)(n, bufs);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)
+{
+ if (isES3(0))
+ qgles3Helper()->DrawElementsInstanced(mode, count, type, indices, instancecount);
+ else
+ RESOLVE_FUNC_VOID(0, DrawElementsInstanced)(mode, count, type, indices, instancecount);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices)
+{
+ if (isES3(0))
+ qgles3Helper()->DrawRangeElements(mode, start, end, count, type, indices);
+ else
+ RESOLVE_FUNC_VOID(0, DrawRangeElements)(mode, start, end, count, type, indices);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveEndQuery(GLenum target)
+{
+ if (isES3(0))
+ qgles3Helper()->EndQuery(target);
+ else
+ RESOLVE_FUNC_VOID(0, EndQuery)(target);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveEndTransformFeedback()
+{
+ if (isES3(0))
+ qgles3Helper()->EndTransformFeedback();
+ else
+ RESOLVE_FUNC_VOID(0, EndTransformFeedback)();
+}
+
+static GLsync QOPENGLF_APIENTRY qopenglfResolveFenceSync(GLenum condition, GLbitfield flags)
+{
+ if (isES3(0))
+ return qgles3Helper()->FenceSync(condition, flags);
+ else
+ RESOLVE_FUNC(GLsync, 0, FenceSync)(condition, flags);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
+{
+ if (isES3(0))
+ qgles3Helper()->FlushMappedBufferRange(target, offset, length);
+ else
+ RESOLVE_FUNC_VOID(0, FlushMappedBufferRange)(target, offset, length);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
+{
+ if (isES3(0))
+ qgles3Helper()->FramebufferTextureLayer(target, attachment, texture, level, layer);
+ else
+ RESOLVE_FUNC_VOID(0, FramebufferTextureLayer)(target, attachment, texture, level, layer);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGenQueries(GLsizei n, GLuint* ids)
+{
+ if (isES3(0))
+ qgles3Helper()->GenQueries(n, ids);
+ else
+ RESOLVE_FUNC_VOID(0, GenQueries)(n, ids);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGenSamplers(GLsizei count, GLuint* samplers)
+{
+ if (isES3(0))
+ qgles3Helper()->GenSamplers(count, samplers);
+ else
+ RESOLVE_FUNC_VOID(0, GenSamplers)(count, samplers);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGenTransformFeedbacks(GLsizei n, GLuint* ids)
+{
+ if (isES3(0))
+ qgles3Helper()->GenTransformFeedbacks(n, ids);
+ else
+ RESOLVE_FUNC_VOID(0, GenTransformFeedbacks)(n, ids);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGenVertexArrays(GLsizei n, GLuint* arrays)
+{
+ if (isES3(0))
+ qgles3Helper()->GenVertexArrays(n, arrays);
+ else
+ RESOLVE_FUNC_VOID(0, GenVertexArrays)(n, arrays);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName)
+{
+ if (isES3(0))
+ qgles3Helper()->GetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName);
+ else
+ RESOLVE_FUNC_VOID(0, GetActiveUniformBlockName)(program, uniformBlockIndex, bufSize, length, uniformBlockName);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetActiveUniformBlockiv)(program, uniformBlockIndex, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetActiveUniformsiv)(program, uniformCount, uniformIndices, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetBufferParameteri64v(target, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetBufferParameteri64v)(target, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetBufferPointerv(GLenum target, GLenum pname, void ** params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetBufferPointerv(target, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetBufferPointerv)(target, pname, params);
+}
+
+static GLint QOPENGLF_APIENTRY qopenglfResolveGetFragDataLocation(GLuint program, const GLchar * name)
+{
+ if (isES3(0))
+ return qgles3Helper()->GetFragDataLocation(program, name);
+ else
+ RESOLVE_FUNC(GLint, 0, GetFragDataLocation)(program, name);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetInteger64i_v(GLenum target, GLuint index, GLint64* data)
+{
+ if (isES3(0))
+ qgles3Helper()->GetInteger64i_v(target, index, data);
+ else
+ RESOLVE_FUNC_VOID(0, GetInteger64i_v)(target, index, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetInteger64v(GLenum pname, GLint64* data)
+{
+ if (isES3(0))
+ qgles3Helper()->GetInteger64v(pname, data);
+ else
+ RESOLVE_FUNC_VOID(0, GetInteger64v)(pname, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetIntegeri_v(GLenum target, GLuint index, GLint* data)
+{
+ if (isES3(0))
+ qgles3Helper()->GetIntegeri_v(target, index, data);
+ else
+ RESOLVE_FUNC_VOID(0, GetIntegeri_v)(target, index, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetInternalformativ(target, internalformat, pname, bufSize, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetInternalformativ)(target, internalformat, pname, bufSize, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, void * binary)
+{
+ if (isES3(0))
+ qgles3Helper()->GetProgramBinary(program, bufSize, length, binaryFormat, binary);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramBinary)(program, bufSize, length, binaryFormat, binary);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetQueryObjectuiv(id, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetQueryObjectuiv)(id, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetQueryiv(GLenum target, GLenum pname, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetQueryiv(target, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetQueryiv)(target, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetSamplerParameterfv(sampler, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetSamplerParameterfv)(sampler, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetSamplerParameteriv(sampler, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetSamplerParameteriv)(sampler, pname, params);
+}
+
+static const GLubyte * QOPENGLF_APIENTRY qopenglfResolveGetStringi(GLenum name, GLuint index)
+{
+ if (isES3(0))
+ return qgles3Helper()->GetStringi(name, index);
+ else
+ RESOLVE_FUNC(const GLubyte *, 0, GetStringi)(name, index);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values)
+{
+ if (isES3(0))
+ qgles3Helper()->GetSynciv(sync, pname, bufSize, length, values);
+ else
+ RESOLVE_FUNC_VOID(0, GetSynciv)(sync, pname, bufSize, length, values);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name)
+{
+ if (isES3(0))
+ qgles3Helper()->GetTransformFeedbackVarying(program, index, bufSize, length, size, type, name);
+ else
+ RESOLVE_FUNC_VOID(0, GetTransformFeedbackVarying)(program, index, bufSize, length, size, type, name);
+}
+
+static GLuint QOPENGLF_APIENTRY qopenglfResolveGetUniformBlockIndex(GLuint program, const GLchar * uniformBlockName)
+{
+ if (isES3(0))
+ return qgles3Helper()->GetUniformBlockIndex(program, uniformBlockName);
+ else
+ RESOLVE_FUNC(GLuint, 0, GetUniformBlockIndex)(program, uniformBlockName);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint* uniformIndices)
+{
+ if (isES3(0))
+ qgles3Helper()->GetUniformIndices(program, uniformCount, uniformNames, uniformIndices);
+ else
+ RESOLVE_FUNC_VOID(0, GetUniformIndices)(program, uniformCount, uniformNames, uniformIndices);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetUniformuiv(GLuint program, GLint location, GLuint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetUniformuiv(program, location, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetUniformuiv)(program, location, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetVertexAttribIiv(GLuint index, GLenum pname, GLint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetVertexAttribIiv(index, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetVertexAttribIiv)(index, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params)
+{
+ if (isES3(0))
+ qgles3Helper()->GetVertexAttribIuiv(index, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetVertexAttribIuiv)(index, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveInvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments)
+{
+ if (isES3(0))
+ qgles3Helper()->InvalidateFramebuffer(target, numAttachments, attachments);
+ else
+ RESOLVE_FUNC_VOID(0, InvalidateFramebuffer)(target, numAttachments, attachments);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ if (isES3(0))
+ qgles3Helper()->InvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height);
+ else
+ RESOLVE_FUNC_VOID(0, InvalidateSubFramebuffer)(target, numAttachments, attachments, x, y, width, height);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsQuery(GLuint id)
+{
+ if (isES3(0))
+ return qgles3Helper()->IsQuery(id);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsQuery)(id);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsSampler(GLuint sampler)
+{
+ if (isES3(0))
+ return qgles3Helper()->IsSampler(sampler);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsSampler)(sampler);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsSync(GLsync sync)
+{
+ if (isES3(0))
+ return qgles3Helper()->IsSync(sync);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsSync)(sync);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsTransformFeedback(GLuint id)
+{
+ if (isES3(0))
+ return qgles3Helper()->IsTransformFeedback(id);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsTransformFeedback)(id);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsVertexArray(GLuint array)
+{
+ if (isES3(0))
+ return qgles3Helper()->IsVertexArray(array);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsVertexArray)(array);
+}
+
+static void * QOPENGLF_APIENTRY qopenglfResolveMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
+{
+ if (isES3(0))
+ return qgles3Helper()->MapBufferRange(target, offset, length, access);
+ else
+ RESOLVE_FUNC(void *, 0, MapBufferRange)(target, offset, length, access);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolvePauseTransformFeedback()
+{
+ if (isES3(0))
+ qgles3Helper()->PauseTransformFeedback();
+ else
+ RESOLVE_FUNC_VOID(0, PauseTransformFeedback)();
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramBinary(GLuint program, GLenum binaryFormat, const void * binary, GLsizei length)
+{
+ if (isES3(0))
+ qgles3Helper()->ProgramBinary(program, binaryFormat, binary, length);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramBinary)(program, binaryFormat, binary, length);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramParameteri(GLuint program, GLenum pname, GLint value)
+{
+ if (isES3(0))
+ qgles3Helper()->ProgramParameteri(program, pname, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramParameteri)(program, pname, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveReadBuffer(GLenum src)
+{
+ if (isES3(0))
+ qgles3Helper()->ReadBuffer(src);
+ else
+ RESOLVE_FUNC_VOID(0, ReadBuffer)(src);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
+{
+ if (isES3(0))
+ qgles3Helper()->RenderbufferStorageMultisample(target, samples, internalformat, width, height);
+ else
+ RESOLVE_FUNC_VOID(ResolveEXT | ResolveANGLE | ResolveNV, RenderbufferStorageMultisample)
+ (target, samples, internalformat, width, height);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveResumeTransformFeedback()
+{
+ if (isES3(0))
+ qgles3Helper()->ResumeTransformFeedback();
+ else
+ RESOLVE_FUNC_VOID(0, ResumeTransformFeedback)();
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveSamplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
+{
+ if (isES3(0))
+ qgles3Helper()->SamplerParameterf(sampler, pname, param);
+ else
+ RESOLVE_FUNC_VOID(0, SamplerParameterf)(sampler, pname, param);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveSamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat * param)
+{
+ if (isES3(0))
+ qgles3Helper()->SamplerParameterfv(sampler, pname, param);
+ else
+ RESOLVE_FUNC_VOID(0, SamplerParameterfv)(sampler, pname, param);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveSamplerParameteri(GLuint sampler, GLenum pname, GLint param)
+{
+ if (isES3(0))
+ qgles3Helper()->SamplerParameteri(sampler, pname, param);
+ else
+ RESOLVE_FUNC_VOID(0, SamplerParameteri)(sampler, pname, param);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveSamplerParameteriv(GLuint sampler, GLenum pname, const GLint * param)
+{
+ if (isES3(0))
+ qgles3Helper()->SamplerParameteriv(sampler, pname, param);
+ else
+ RESOLVE_FUNC_VOID(0, SamplerParameteriv)(sampler, pname, param);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels)
+{
+ if (isES3(0))
+ qgles3Helper()->TexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
+ else
+ RESOLVE_FUNC_VOID(0, TexImage3D)(target, level, internalformat, width, height, depth, border, format, type, pixels);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
+{
+ if (isES3(0))
+ qgles3Helper()->TexStorage2D(target, levels, internalformat, width, height);
+ else
+ RESOLVE_FUNC_VOID(0, TexStorage2D)(target, levels, internalformat, width, height);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
+{
+ if (isES3(0))
+ qgles3Helper()->TexStorage3D(target, levels, internalformat, width, height, depth);
+ else
+ RESOLVE_FUNC_VOID(0, TexStorage3D)(target, levels, internalformat, width, height, depth);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels)
+{
+ if (isES3(0))
+ qgles3Helper()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+ else
+ RESOLVE_FUNC_VOID(0, TexSubImage3D)(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode)
+{
+ if (isES3(0))
+ qgles3Helper()->TransformFeedbackVaryings(program, count, varyings, bufferMode);
+ else
+ RESOLVE_FUNC_VOID(0, TransformFeedbackVaryings)(program, count, varyings, bufferMode);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform1ui(GLint location, GLuint v0)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform1ui(location, v0);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform1ui)(location, v0);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform1uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform1uiv(location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform1uiv)(location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform2ui(GLint location, GLuint v0, GLuint v1)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform2ui(location, v0, v1);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform2ui)(location, v0, v1);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform2uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform2uiv(location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform2uiv)(location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform3ui(location, v0, v1, v2);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform3ui)(location, v0, v1, v2);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform3uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform3uiv(location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform3uiv)(location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform4ui(location, v0, v1, v2, v3);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform4ui)(location, v0, v1, v2, v3);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniform4uiv(GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(0))
+ qgles3Helper()->Uniform4uiv(location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, Uniform4uiv)(location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
+ else
+ RESOLVE_FUNC_VOID(0, UniformBlockBinding)(program, uniformBlockIndex, uniformBlockBinding);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix2x3fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix2x3fv)(location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix2x4fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix2x4fv)(location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix3x2fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix3x2fv)(location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix3x4fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix3x4fv)(location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix4x2fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix4x2fv)(location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(0))
+ qgles3Helper()->UniformMatrix4x3fv(location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, UniformMatrix4x3fv)(location, count, transpose, value);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveUnmapBuffer(GLenum target)
+{
+ if (isES3(0))
+ return qgles3Helper()->UnmapBuffer(target);
+ else
+ RESOLVE_FUNC(GLboolean, ResolveOES, UnmapBuffer)(target);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribDivisor(GLuint index, GLuint divisor)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribDivisor(index, divisor);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribDivisor)(index, divisor);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribI4i(index, x, y, z, w);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribI4i)(index, x, y, z, w);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribI4iv(GLuint index, const GLint * v)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribI4iv(index, v);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribI4iv)(index, v);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribI4ui(index, x, y, z, w);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribI4ui)(index, x, y, z, w);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribI4uiv(GLuint index, const GLuint * v)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribI4uiv(index, v);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribI4uiv)(index, v);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer)
+{
+ if (isES3(0))
+ qgles3Helper()->VertexAttribIPointer(index, size, type, stride, pointer);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribIPointer)(index, size, type, stride, pointer);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+{
+ if (isES3(0))
+ qgles3Helper()->WaitSync(sync, flags, timeout);
+ else
+ RESOLVE_FUNC_VOID(0, WaitSync)(sync, flags, timeout);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveActiveShaderProgram(GLuint pipeline, GLuint program)
+{
+ if (isES3(1))
+ qgles3Helper()->ActiveShaderProgram(pipeline, program);
+ else
+ RESOLVE_FUNC_VOID(0, ActiveShaderProgram)(pipeline, program);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)
+{
+ if (isES3(1))
+ qgles3Helper()->BindImageTexture(unit, texture, level, layered, layer, access, format);
+ else
+ RESOLVE_FUNC_VOID(0, BindImageTexture)(unit, texture, level, layered, layer, access, format);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindProgramPipeline(GLuint pipeline)
+{
+ if (isES3(1))
+ qgles3Helper()->BindProgramPipeline(pipeline);
+ else
+ RESOLVE_FUNC_VOID(0, BindProgramPipeline)(pipeline);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride)
+{
+ if (isES3(1))
+ qgles3Helper()->BindVertexBuffer(bindingindex, buffer, offset, stride);
+ else
+ RESOLVE_FUNC_VOID(0, BindVertexBuffer)(bindingindex, buffer, offset, stride);
+}
+
+static GLuint QOPENGLF_APIENTRY qopenglfResolveCreateShaderProgramv(GLenum type, GLsizei count, const GLchar *const* strings)
+{
+ if (isES3(1))
+ return qgles3Helper()->CreateShaderProgramv(type, count, strings);
+ else
+ RESOLVE_FUNC(GLuint, 0, CreateShaderProgramv)(type, count, strings);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDeleteProgramPipelines(GLsizei n, const GLuint * pipelines)
+{
+ if (isES3(1))
+ qgles3Helper()->DeleteProgramPipelines(n, pipelines);
+ else
+ RESOLVE_FUNC_VOID(0, DeleteProgramPipelines)(n, pipelines);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
+{
+ if (isES3(1))
+ qgles3Helper()->DispatchCompute(num_groups_x, num_groups_y, num_groups_z);
+ else
+ RESOLVE_FUNC_VOID(0, DispatchCompute)(num_groups_x, num_groups_y, num_groups_z);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDispatchComputeIndirect(GLintptr indirect)
+{
+ if (isES3(1))
+ qgles3Helper()->DispatchComputeIndirect(indirect);
+ else
+ RESOLVE_FUNC_VOID(0, DispatchComputeIndirect)(indirect);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawArraysIndirect(GLenum mode, const void * indirect)
+{
+ if (isES3(1))
+ qgles3Helper()->DrawArraysIndirect(mode, indirect);
+ else
+ RESOLVE_FUNC_VOID(0, DrawArraysIndirect)(mode, indirect);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveDrawElementsIndirect(GLenum mode, GLenum type, const void * indirect)
+{
+ if (isES3(1))
+ qgles3Helper()->DrawElementsIndirect(mode, type, indirect);
+ else
+ RESOLVE_FUNC_VOID(0, DrawElementsIndirect)(mode, type, indirect);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveFramebufferParameteri(GLenum target, GLenum pname, GLint param)
+{
+ if (isES3(1))
+ qgles3Helper()->FramebufferParameteri(target, pname, param);
+ else
+ RESOLVE_FUNC_VOID(0, FramebufferParameteri)(target, pname, param);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGenProgramPipelines(GLsizei n, GLuint* pipelines)
+{
+ if (isES3(1))
+ qgles3Helper()->GenProgramPipelines(n, pipelines);
+ else
+ RESOLVE_FUNC_VOID(0, GenProgramPipelines)(n, pipelines);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetBooleani_v(GLenum target, GLuint index, GLboolean* data)
+{
+ if (isES3(1))
+ qgles3Helper()->GetBooleani_v(target, index, data);
+ else
+ RESOLVE_FUNC_VOID(0, GetBooleani_v)(target, index, data);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetFramebufferParameteriv(GLenum target, GLenum pname, GLint* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetFramebufferParameteriv(target, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetFramebufferParameteriv)(target, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetMultisamplefv(GLenum pname, GLuint index, GLfloat* val)
+{
+ if (isES3(1))
+ qgles3Helper()->GetMultisamplefv(pname, index, val);
+ else
+ RESOLVE_FUNC_VOID(0, GetMultisamplefv)(pname, index, val);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramInterfaceiv(GLuint program, GLenum programInterface, GLenum pname, GLint* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetProgramInterfaceiv(program, programInterface, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramInterfaceiv)(program, programInterface, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramPipelineInfoLog(GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog)
+{
+ if (isES3(1))
+ qgles3Helper()->GetProgramPipelineInfoLog(pipeline, bufSize, length, infoLog);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramPipelineInfoLog)(pipeline, bufSize, length, infoLog);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetProgramPipelineiv(pipeline, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramPipelineiv)(pipeline, pname, params);
+}
+
+static GLuint QOPENGLF_APIENTRY qopenglfResolveGetProgramResourceIndex(GLuint program, GLenum programInterface, const GLchar * name)
+{
+ if (isES3(1))
+ return qgles3Helper()->GetProgramResourceIndex(program, programInterface, name);
+ else
+ RESOLVE_FUNC(GLuint, 0, GetProgramResourceIndex)(program, programInterface, name);
+}
+
+static GLint QOPENGLF_APIENTRY qopenglfResolveGetProgramResourceLocation(GLuint program, GLenum programInterface, const GLchar * name)
+{
+ if (isES3(1))
+ return qgles3Helper()->GetProgramResourceLocation(program, programInterface, name);
+ else
+ RESOLVE_FUNC(GLint, 0, GetProgramResourceLocation)(program, programInterface, name);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramResourceName(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei* length, GLchar* name)
+{
+ if (isES3(1))
+ qgles3Helper()->GetProgramResourceName(program, programInterface, index, bufSize, length, name);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramResourceName)(program, programInterface, index, bufSize, length, name);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum * props, GLsizei bufSize, GLsizei* length, GLint* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetProgramResourceiv(program, programInterface, index, propCount, props, bufSize, length, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetProgramResourceiv)(program, programInterface, index, propCount, props, bufSize, length, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetTexLevelParameterfv(target, level, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetTexLevelParameterfv)(target, level, pname, params);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params)
+{
+ if (isES3(1))
+ qgles3Helper()->GetTexLevelParameteriv(target, level, pname, params);
+ else
+ RESOLVE_FUNC_VOID(0, GetTexLevelParameteriv)(target, level, pname, params);
+}
+
+static GLboolean QOPENGLF_APIENTRY qopenglfResolveIsProgramPipeline(GLuint pipeline)
+{
+ if (isES3(1))
+ return qgles3Helper()->IsProgramPipeline(pipeline);
+ else
+ RESOLVE_FUNC(GLboolean, 0, IsProgramPipeline)(pipeline);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveMemoryBarrier(GLbitfield barriers)
+{
+ if (isES3(1))
+ qgles3Helper()->MemoryBarrierFunc(barriers);
+ else
+ RESOLVE_FUNC_VOID(0, MemoryBarrierFunc)(barriers);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveMemoryBarrierByRegion(GLbitfield barriers)
+{
+ if (isES3(1))
+ qgles3Helper()->MemoryBarrierByRegion(barriers);
+ else
+ RESOLVE_FUNC_VOID(0, MemoryBarrierByRegion)(barriers);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1f(GLuint program, GLint location, GLfloat v0)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1f(program, location, v0);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1f)(program, location, v0);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1fv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1fv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1i(GLuint program, GLint location, GLint v0)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1i(program, location, v0);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1i)(program, location, v0);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1iv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1iv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1ui(GLuint program, GLint location, GLuint v0)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1ui(program, location, v0);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1ui)(program, location, v0);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform1uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform1uiv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform1uiv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2f(GLuint program, GLint location, GLfloat v0, GLfloat v1)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2f(program, location, v0, v1);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2f)(program, location, v0, v1);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2fv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2fv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2i(GLuint program, GLint location, GLint v0, GLint v1)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2i(program, location, v0, v1);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2i)(program, location, v0, v1);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2iv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2iv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2ui(GLuint program, GLint location, GLuint v0, GLuint v1)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2ui(program, location, v0, v1);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2ui)(program, location, v0, v1);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform2uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform2uiv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform2uiv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3f(program, location, v0, v1, v2);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3f)(program, location, v0, v1, v2);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3fv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3fv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3i(program, location, v0, v1, v2);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3i)(program, location, v0, v1, v2);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3iv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3iv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3ui(program, location, v0, v1, v2);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3ui)(program, location, v0, v1, v2);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform3uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform3uiv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform3uiv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4f(program, location, v0, v1, v2, v3);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4f)(program, location, v0, v1, v2, v3);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4fv(GLuint program, GLint location, GLsizei count, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4fv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4fv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4i(program, location, v0, v1, v2, v3);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4i)(program, location, v0, v1, v2, v3);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4iv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4iv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4ui(program, location, v0, v1, v2, v3);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4ui)(program, location, v0, v1, v2, v3);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniform4uiv(GLuint program, GLint location, GLsizei count, const GLuint * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniform4uiv(program, location, count, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniform4uiv)(program, location, count, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix2fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix2fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix2x3fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix2x3fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix2x4fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix2x4fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix3fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix3fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix3x2fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix3x2fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix3x4fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix3x4fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix4fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix4fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix4x2fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix4x2fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)
+{
+ if (isES3(1))
+ qgles3Helper()->ProgramUniformMatrix4x3fv(program, location, count, transpose, value);
+ else
+ RESOLVE_FUNC_VOID(0, ProgramUniformMatrix4x3fv)(program, location, count, transpose, value);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveSampleMaski(GLuint maskNumber, GLbitfield mask)
+{
+ if (isES3(1))
+ qgles3Helper()->SampleMaski(maskNumber, mask);
+ else
+ RESOLVE_FUNC_VOID(0, SampleMaski)(maskNumber, mask);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
+{
+ if (isES3(1))
+ qgles3Helper()->TexStorage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations);
+ else
+ RESOLVE_FUNC_VOID(0, TexStorage2DMultisample)(target, samples, internalformat, width, height, fixedsamplelocations);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveUseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program)
+{
+ if (isES3(1))
+ qgles3Helper()->UseProgramStages(pipeline, stages, program);
+ else
+ RESOLVE_FUNC_VOID(0, UseProgramStages)(pipeline, stages, program);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveValidateProgramPipeline(GLuint pipeline)
+{
+ if (isES3(1))
+ qgles3Helper()->ValidateProgramPipeline(pipeline);
+ else
+ RESOLVE_FUNC_VOID(0, ValidateProgramPipeline)(pipeline);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribBinding(GLuint attribindex, GLuint bindingindex)
+{
+ if (isES3(1))
+ qgles3Helper()->VertexAttribBinding(attribindex, bindingindex);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribBinding)(attribindex, bindingindex);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset)
+{
+ if (isES3(1))
+ qgles3Helper()->VertexAttribFormat(attribindex, size, type, normalized, relativeoffset);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribFormat)(attribindex, size, type, normalized, relativeoffset);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset)
+{
+ if (isES3(1))
+ qgles3Helper()->VertexAttribIFormat(attribindex, size, type, relativeoffset);
+ else
+ RESOLVE_FUNC_VOID(0, VertexAttribIFormat)(attribindex, size, type, relativeoffset);
+}
+
+static void QOPENGLF_APIENTRY qopenglfResolveVertexBindingDivisor(GLuint bindingindex, GLuint divisor)
+{
+ if (isES3(1))
+ qgles3Helper()->VertexBindingDivisor(bindingindex, divisor);
+ else
+ RESOLVE_FUNC_VOID(0, VertexBindingDivisor)(bindingindex, divisor);
+}
+
+/*!
+ Constructs a default function resolver. The resolver cannot be used until
+ \l {QOpenGLFunctions::}{initializeOpenGLFunctions()} is called to specify
+ the context.
+*/
+QOpenGLExtraFunctions::QOpenGLExtraFunctions()
+{
+}
+
+/*!
+ Constructs a function resolver for context. If \a context is null, then
+ the resolver will be created for the current QOpenGLContext.
+
+ The context or another context in the group must be current.
+
+ An object constructed in this way can only be used with context and other
+ contexts that share with it. Use \l {QOpenGLFunctions::}
+ {initializeOpenGLFunctions()} to change the object's context association.
+*/
+QOpenGLExtraFunctions::QOpenGLExtraFunctions(QOpenGLContext *context)
+ : QOpenGLFunctions(context)
+{
+}
+
+QOpenGLExtraFunctionsPrivate::QOpenGLExtraFunctionsPrivate(QOpenGLContext *ctx)
+ : QOpenGLFunctionsPrivate(ctx)
+{
+ ReadBuffer = qopenglfResolveReadBuffer;
+ DrawRangeElements = qopenglfResolveDrawRangeElements;
+ TexImage3D = qopenglfResolveTexImage3D;
+ TexSubImage3D = qopenglfResolveTexSubImage3D;
+ CopyTexSubImage3D = qopenglfResolveCopyTexSubImage3D;
+ CompressedTexImage3D = qopenglfResolveCompressedTexImage3D;
+ CompressedTexSubImage3D = qopenglfResolveCompressedTexSubImage3D;
+ GenQueries = qopenglfResolveGenQueries;
+ DeleteQueries = qopenglfResolveDeleteQueries;
+ IsQuery = qopenglfResolveIsQuery;
+ BeginQuery = qopenglfResolveBeginQuery;
+ EndQuery = qopenglfResolveEndQuery;
+ GetQueryiv = qopenglfResolveGetQueryiv;
+ GetQueryObjectuiv = qopenglfResolveGetQueryObjectuiv;
UnmapBuffer = qopenglfResolveUnmapBuffer;
+ GetBufferPointerv = qopenglfResolveGetBufferPointerv;
+ DrawBuffers = qopenglfResolveDrawBuffers;
+ UniformMatrix2x3fv = qopenglfResolveUniformMatrix2x3fv;
+ UniformMatrix3x2fv = qopenglfResolveUniformMatrix3x2fv;
+ UniformMatrix2x4fv = qopenglfResolveUniformMatrix2x4fv;
+ UniformMatrix4x2fv = qopenglfResolveUniformMatrix4x2fv;
+ UniformMatrix3x4fv = qopenglfResolveUniformMatrix3x4fv;
+ UniformMatrix4x3fv = qopenglfResolveUniformMatrix4x3fv;
BlitFramebuffer = qopenglfResolveBlitFramebuffer;
RenderbufferStorageMultisample = qopenglfResolveRenderbufferStorageMultisample;
+ FramebufferTextureLayer = qopenglfResolveFramebufferTextureLayer;
+ MapBufferRange = qopenglfResolveMapBufferRange;
+ FlushMappedBufferRange = qopenglfResolveFlushMappedBufferRange;
+ BindVertexArray = qopenglfResolveBindVertexArray;
+ DeleteVertexArrays = qopenglfResolveDeleteVertexArrays;
+ GenVertexArrays = qopenglfResolveGenVertexArrays;
+ IsVertexArray = qopenglfResolveIsVertexArray;
+ GetIntegeri_v = qopenglfResolveGetIntegeri_v;
+ BeginTransformFeedback = qopenglfResolveBeginTransformFeedback;
+ EndTransformFeedback = qopenglfResolveEndTransformFeedback;
+ BindBufferRange = qopenglfResolveBindBufferRange;
+ BindBufferBase = qopenglfResolveBindBufferBase;
+ TransformFeedbackVaryings = qopenglfResolveTransformFeedbackVaryings;
+ GetTransformFeedbackVarying = qopenglfResolveGetTransformFeedbackVarying;
+ VertexAttribIPointer = qopenglfResolveVertexAttribIPointer;
+ GetVertexAttribIiv = qopenglfResolveGetVertexAttribIiv;
+ GetVertexAttribIuiv = qopenglfResolveGetVertexAttribIuiv;
+ VertexAttribI4i = qopenglfResolveVertexAttribI4i;
+ VertexAttribI4ui = qopenglfResolveVertexAttribI4ui;
+ VertexAttribI4iv = qopenglfResolveVertexAttribI4iv;
+ VertexAttribI4uiv = qopenglfResolveVertexAttribI4uiv;
+ GetUniformuiv = qopenglfResolveGetUniformuiv;
+ GetFragDataLocation = qopenglfResolveGetFragDataLocation;
+ Uniform1ui = qopenglfResolveUniform1ui;
+ Uniform2ui = qopenglfResolveUniform2ui;
+ Uniform3ui = qopenglfResolveUniform3ui;
+ Uniform4ui = qopenglfResolveUniform4ui;
+ Uniform1uiv = qopenglfResolveUniform1uiv;
+ Uniform2uiv = qopenglfResolveUniform2uiv;
+ Uniform3uiv = qopenglfResolveUniform3uiv;
+ Uniform4uiv = qopenglfResolveUniform4uiv;
+ ClearBufferiv = qopenglfResolveClearBufferiv;
+ ClearBufferuiv = qopenglfResolveClearBufferuiv;
+ ClearBufferfv = qopenglfResolveClearBufferfv;
+ ClearBufferfi = qopenglfResolveClearBufferfi;
+ GetStringi = qopenglfResolveGetStringi;
+ CopyBufferSubData = qopenglfResolveCopyBufferSubData;
+ GetUniformIndices = qopenglfResolveGetUniformIndices;
+ GetActiveUniformsiv = qopenglfResolveGetActiveUniformsiv;
+ GetUniformBlockIndex = qopenglfResolveGetUniformBlockIndex;
+ GetActiveUniformBlockiv = qopenglfResolveGetActiveUniformBlockiv;
+ GetActiveUniformBlockName = qopenglfResolveGetActiveUniformBlockName;
+ UniformBlockBinding = qopenglfResolveUniformBlockBinding;
+ DrawArraysInstanced = qopenglfResolveDrawArraysInstanced;
+ DrawElementsInstanced = qopenglfResolveDrawElementsInstanced;
+ FenceSync = qopenglfResolveFenceSync;
+ IsSync = qopenglfResolveIsSync;
+ DeleteSync = qopenglfResolveDeleteSync;
+ ClientWaitSync = qopenglfResolveClientWaitSync;
+ WaitSync = qopenglfResolveWaitSync;
+ GetInteger64v = qopenglfResolveGetInteger64v;
+ GetSynciv = qopenglfResolveGetSynciv;
+ GetInteger64i_v = qopenglfResolveGetInteger64i_v;
+ GetBufferParameteri64v = qopenglfResolveGetBufferParameteri64v;
+ GenSamplers = qopenglfResolveGenSamplers;
+ DeleteSamplers = qopenglfResolveDeleteSamplers;
+ IsSampler = qopenglfResolveIsSampler;
+ BindSampler = qopenglfResolveBindSampler;
+ SamplerParameteri = qopenglfResolveSamplerParameteri;
+ SamplerParameteriv = qopenglfResolveSamplerParameteriv;
+ SamplerParameterf = qopenglfResolveSamplerParameterf;
+ SamplerParameterfv = qopenglfResolveSamplerParameterfv;
+ GetSamplerParameteriv = qopenglfResolveGetSamplerParameteriv;
+ GetSamplerParameterfv = qopenglfResolveGetSamplerParameterfv;
+ VertexAttribDivisor = qopenglfResolveVertexAttribDivisor;
+ BindTransformFeedback = qopenglfResolveBindTransformFeedback;
+ DeleteTransformFeedbacks = qopenglfResolveDeleteTransformFeedbacks;
+ GenTransformFeedbacks = qopenglfResolveGenTransformFeedbacks;
+ IsTransformFeedback = qopenglfResolveIsTransformFeedback;
+ PauseTransformFeedback = qopenglfResolvePauseTransformFeedback;
+ ResumeTransformFeedback = qopenglfResolveResumeTransformFeedback;
+ GetProgramBinary = qopenglfResolveGetProgramBinary;
+ ProgramBinary = qopenglfResolveProgramBinary;
+ ProgramParameteri = qopenglfResolveProgramParameteri;
+ InvalidateFramebuffer = qopenglfResolveInvalidateFramebuffer;
+ InvalidateSubFramebuffer = qopenglfResolveInvalidateSubFramebuffer;
+ TexStorage2D = qopenglfResolveTexStorage2D;
+ TexStorage3D = qopenglfResolveTexStorage3D;
+ GetInternalformativ = qopenglfResolveGetInternalformativ;
+
+ DispatchCompute = qopenglfResolveDispatchCompute;
+ DispatchComputeIndirect = qopenglfResolveDispatchComputeIndirect;
+ DrawArraysIndirect = qopenglfResolveDrawArraysIndirect;
+ DrawElementsIndirect = qopenglfResolveDrawElementsIndirect;
+ FramebufferParameteri = qopenglfResolveFramebufferParameteri;
+ GetFramebufferParameteriv = qopenglfResolveGetFramebufferParameteriv;
+ GetProgramInterfaceiv = qopenglfResolveGetProgramInterfaceiv;
+ GetProgramResourceIndex = qopenglfResolveGetProgramResourceIndex;
+ GetProgramResourceName = qopenglfResolveGetProgramResourceName;
+ GetProgramResourceiv = qopenglfResolveGetProgramResourceiv;
+ GetProgramResourceLocation = qopenglfResolveGetProgramResourceLocation;
+ UseProgramStages = qopenglfResolveUseProgramStages;
+ ActiveShaderProgram = qopenglfResolveActiveShaderProgram;
+ CreateShaderProgramv = qopenglfResolveCreateShaderProgramv;
+ BindProgramPipeline = qopenglfResolveBindProgramPipeline;
+ DeleteProgramPipelines = qopenglfResolveDeleteProgramPipelines;
+ GenProgramPipelines = qopenglfResolveGenProgramPipelines;
+ IsProgramPipeline = qopenglfResolveIsProgramPipeline;
+ GetProgramPipelineiv = qopenglfResolveGetProgramPipelineiv;
+ ProgramUniform1i = qopenglfResolveProgramUniform1i;
+ ProgramUniform2i = qopenglfResolveProgramUniform2i;
+ ProgramUniform3i = qopenglfResolveProgramUniform3i;
+ ProgramUniform4i = qopenglfResolveProgramUniform4i;
+ ProgramUniform1ui = qopenglfResolveProgramUniform1ui;
+ ProgramUniform2ui = qopenglfResolveProgramUniform2ui;
+ ProgramUniform3ui = qopenglfResolveProgramUniform3ui;
+ ProgramUniform4ui = qopenglfResolveProgramUniform4ui;
+ ProgramUniform1f = qopenglfResolveProgramUniform1f;
+ ProgramUniform2f = qopenglfResolveProgramUniform2f;
+ ProgramUniform3f = qopenglfResolveProgramUniform3f;
+ ProgramUniform4f = qopenglfResolveProgramUniform4f;
+ ProgramUniform1iv = qopenglfResolveProgramUniform1iv;
+ ProgramUniform2iv = qopenglfResolveProgramUniform2iv;
+ ProgramUniform3iv = qopenglfResolveProgramUniform3iv;
+ ProgramUniform4iv = qopenglfResolveProgramUniform4iv;
+ ProgramUniform1uiv = qopenglfResolveProgramUniform1uiv;
+ ProgramUniform2uiv = qopenglfResolveProgramUniform2uiv;
+ ProgramUniform3uiv = qopenglfResolveProgramUniform3uiv;
+ ProgramUniform4uiv = qopenglfResolveProgramUniform4uiv;
+ ProgramUniform1fv = qopenglfResolveProgramUniform1fv;
+ ProgramUniform2fv = qopenglfResolveProgramUniform2fv;
+ ProgramUniform3fv = qopenglfResolveProgramUniform3fv;
+ ProgramUniform4fv = qopenglfResolveProgramUniform4fv;
+ ProgramUniformMatrix2fv = qopenglfResolveProgramUniformMatrix2fv;
+ ProgramUniformMatrix3fv = qopenglfResolveProgramUniformMatrix3fv;
+ ProgramUniformMatrix4fv = qopenglfResolveProgramUniformMatrix4fv;
+ ProgramUniformMatrix2x3fv = qopenglfResolveProgramUniformMatrix2x3fv;
+ ProgramUniformMatrix3x2fv = qopenglfResolveProgramUniformMatrix3x2fv;
+ ProgramUniformMatrix2x4fv = qopenglfResolveProgramUniformMatrix2x4fv;
+ ProgramUniformMatrix4x2fv = qopenglfResolveProgramUniformMatrix4x2fv;
+ ProgramUniformMatrix3x4fv = qopenglfResolveProgramUniformMatrix3x4fv;
+ ProgramUniformMatrix4x3fv = qopenglfResolveProgramUniformMatrix4x3fv;
+ ValidateProgramPipeline = qopenglfResolveValidateProgramPipeline;
+ GetProgramPipelineInfoLog = qopenglfResolveGetProgramPipelineInfoLog;
+ BindImageTexture = qopenglfResolveBindImageTexture;
+ GetBooleani_v = qopenglfResolveGetBooleani_v;
+ MemoryBarrierFunc = qopenglfResolveMemoryBarrier;
+ MemoryBarrierByRegion = qopenglfResolveMemoryBarrierByRegion;
+ TexStorage2DMultisample = qopenglfResolveTexStorage2DMultisample;
+ GetMultisamplefv = qopenglfResolveGetMultisamplefv;
+ SampleMaski = qopenglfResolveSampleMaski;
+ GetTexLevelParameteriv = qopenglfResolveGetTexLevelParameteriv;
+ GetTexLevelParameterfv = qopenglfResolveGetTexLevelParameterfv;
+ BindVertexBuffer = qopenglfResolveBindVertexBuffer;
+ VertexAttribFormat = qopenglfResolveVertexAttribFormat;
+ VertexAttribIFormat = qopenglfResolveVertexAttribIFormat;
+ VertexAttribBinding = qopenglfResolveVertexAttribBinding;
+ VertexBindingDivisor = qopenglfResolveVertexBindingDivisor;
+}
+
+QOpenGLExtensionsPrivate::QOpenGLExtensionsPrivate(QOpenGLContext *ctx)
+ : QOpenGLExtraFunctionsPrivate(ctx),
+ flushVendorChecked(false)
+{
+ MapBuffer = qopenglfResolveMapBuffer;
GetBufferSubData = qopenglfResolveGetBufferSubData;
DiscardFramebuffer = qopenglfResolveDiscardFramebuffer;
}
diff --git a/src/gui/opengl/qopenglfunctions.h b/src/gui/opengl/qopenglfunctions.h
index b7cb4e53e9..e295f68e44 100644
--- a/src/gui/opengl/qopenglfunctions.h
+++ b/src/gui/opengl/qopenglfunctions.h
@@ -241,7 +241,8 @@ public:
NPOTTextures = 0x1000,
NPOTTextureRepeat = 0x2000,
FixedFunctionPipeline = 0x4000,
- TextureRGFormats = 0x8000
+ TextureRGFormats = 0x8000,
+ MultipleRenderTargets = 0x10000
};
Q_DECLARE_FLAGS(OpenGLFeatures, OpenGLFeature)
@@ -402,7 +403,7 @@ public:
protected:
QOpenGLFunctionsPrivate *d_ptr;
- static bool isInitialized(const QOpenGLFunctionsPrivate *d) { return d != 0; }
+ static bool isInitialized(const QOpenGLFunctionsPrivate *d) { return d != Q_NULLPTR; }
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QOpenGLFunctions::OpenGLFeatures)
diff --git a/src/gui/opengl/qopenglgradientcache.cpp b/src/gui/opengl/qopenglgradientcache.cpp
index ab493fa85c..13bad9aabb 100644
--- a/src/gui/opengl/qopenglgradientcache.cpp
+++ b/src/gui/opengl/qopenglgradientcache.cpp
@@ -34,8 +34,14 @@
#include "qopenglgradientcache_p.h"
#include <private/qdrawhelper_p.h>
#include <private/qopenglcontext_p.h>
+#include <private/qrgba64_p.h>
#include <QtCore/qmutex.h>
-#include <QtGui/qopenglfunctions.h>
+#include "qopenglfunctions.h"
+#include "qopenglextensions_p.h"
+
+#ifndef GL_RGBA16
+#define GL_RGBA16 0x805B
+#endif
QT_BEGIN_NAMESPACE
@@ -137,17 +143,79 @@ GLuint QOpenGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient
}
CacheInfo cache_entry(gradient.stops(), opacity, gradient.interpolationMode());
- uint buffer[1024];
- generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
funcs->glGenTextures(1, &cache_entry.texId);
funcs->glBindTexture(GL_TEXTURE_2D, cache_entry.texId);
- funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, paletteSize(), 1,
- 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
+ if (static_cast<QOpenGLExtensions *>(funcs)->hasOpenGLExtension(QOpenGLExtensions::Sized16Formats)) {
+ QRgba64 buffer[1024];
+ generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
+ funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, paletteSize(), 1,
+ 0, GL_RGBA, GL_UNSIGNED_SHORT, buffer);
+ } else {
+ uint buffer[1024];
+ generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
+ funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, paletteSize(), 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
+ }
return cache.insert(hash_val, cache_entry).value().texId;
}
//TODO: Let GL generate the texture using an FBO
+void QOpenGL2GradientCache::generateGradientColorTable(const QGradient& gradient, QRgba64 *colorTable, int size, qreal opacity) const
+{
+ int pos = 0;
+ QGradientStops s = gradient.stops();
+ QVector<QRgba64> colors(s.size());
+
+ for (int i = 0; i < s.size(); ++i)
+ colors[i] = s[i].second.rgba64();
+
+ bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
+
+ uint alpha = qRound(opacity * 256);
+ QRgba64 current_color = combineAlpha256(colors[0], alpha);
+ qreal incr = 1.0 / qreal(size);
+ qreal fpos = 1.5 * incr;
+ colorTable[pos++] = qPremultiply(current_color);
+
+ while (fpos <= s.first().first) {
+ colorTable[pos] = colorTable[pos - 1];
+ pos++;
+ fpos += incr;
+ }
+
+ if (colorInterpolation)
+ current_color = qPremultiply(current_color);
+
+ for (int i = 0; i < s.size() - 1; ++i) {
+ qreal delta = 1/(s[i+1].first - s[i].first);
+ QRgba64 next_color = combineAlpha256(colors[i+1], alpha);
+ if (colorInterpolation)
+ next_color = qPremultiply(next_color);
+
+ while (fpos < s[i+1].first && pos < size) {
+ int dist = int(256 * ((fpos - s[i].first) * delta));
+ int idist = 256 - dist;
+ if (colorInterpolation)
+ colorTable[pos] = interpolate256(current_color, idist, next_color, dist);
+ else
+ colorTable[pos] = qPremultiply(interpolate256(current_color, idist, next_color, dist));
+ ++pos;
+ fpos += incr;
+ }
+ current_color = next_color;
+ }
+
+ Q_ASSERT(s.size() > 0);
+
+ QRgba64 last_color = qPremultiply(combineAlpha256(colors[s.size() - 1], alpha));
+ for (;pos < size; ++pos)
+ colorTable[pos] = last_color;
+
+ // Make sure the last color stop is represented at the end of the table
+ colorTable[size-1] = last_color;
+}
+
void QOpenGL2GradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
{
int pos = 0;
diff --git a/src/gui/opengl/qopenglgradientcache_p.h b/src/gui/opengl/qopenglgradientcache_p.h
index bcdf3f4fcf..f2cc082250 100644
--- a/src/gui/opengl/qopenglgradientcache_p.h
+++ b/src/gui/opengl/qopenglgradientcache_p.h
@@ -50,6 +50,7 @@
#include <private/qopenglcontext_p.h>
#include <QtCore/qmutex.h>
#include <QGradient>
+#include <qrgba64.h>
QT_BEGIN_NAMESPACE
@@ -58,7 +59,7 @@ class QOpenGL2GradientCache : public QOpenGLSharedResource
struct CacheInfo
{
inline CacheInfo(QGradientStops s, qreal op, QGradient::InterpolationMode mode) :
- stops(s), opacity(op), interpolationMode(mode) {}
+ stops(qMove(s)), opacity(op), interpolationMode(mode) {}
GLuint texId;
QGradientStops stops;
@@ -83,6 +84,9 @@ public:
private:
inline int maxCacheSize() const { return 60; }
inline void generateGradientColorTable(const QGradient& gradient,
+ QRgba64 *colorTable,
+ int size, qreal opacity) const;
+ inline void generateGradientColorTable(const QGradient& gradient,
uint *colorTable,
int size, qreal opacity) const;
GLuint addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity);
diff --git a/src/gui/opengl/qopenglpaintdevice.cpp b/src/gui/opengl/qopenglpaintdevice.cpp
index c0657feaa0..17a32774d8 100644
--- a/src/gui/opengl/qopenglpaintdevice.cpp
+++ b/src/gui/opengl/qopenglpaintdevice.cpp
@@ -169,6 +169,10 @@ QOpenGLPaintDevicePrivate::QOpenGLPaintDevicePrivate(const QSize &sz)
{
}
+QOpenGLPaintDevicePrivate::~QOpenGLPaintDevicePrivate()
+{
+}
+
class QOpenGLEngineThreadStorage
{
public:
@@ -271,6 +275,9 @@ int QOpenGLPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const
return qRound(d_ptr->dpmy * 0.0254);
case PdmDevicePixelRatio:
return d_ptr->devicePixelRatio;
+ case PdmDevicePixelRatioScaled:
+ return d_ptr->devicePixelRatio * QPaintDevice::devicePixelRatioFScale();
+
default:
qWarning("QOpenGLPaintDevice::metric() - metric %d not known", metric);
return 0;
diff --git a/src/gui/opengl/qopenglpaintdevice_p.h b/src/gui/opengl/qopenglpaintdevice_p.h
index 57d93ee80a..54ea09240d 100644
--- a/src/gui/opengl/qopenglpaintdevice_p.h
+++ b/src/gui/opengl/qopenglpaintdevice_p.h
@@ -56,7 +56,7 @@ class Q_GUI_EXPORT QOpenGLPaintDevicePrivate
{
public:
QOpenGLPaintDevicePrivate(const QSize &size);
- virtual ~QOpenGLPaintDevicePrivate() { }
+ virtual ~QOpenGLPaintDevicePrivate();
static QOpenGLPaintDevicePrivate *get(QOpenGLPaintDevice *dev) { return dev->d_func(); }
diff --git a/src/gui/opengl/qopenglpixeltransferoptions.h b/src/gui/opengl/qopenglpixeltransferoptions.h
index bf726813bd..cb4697ec7c 100644
--- a/src/gui/opengl/qopenglpixeltransferoptions.h
+++ b/src/gui/opengl/qopenglpixeltransferoptions.h
@@ -49,15 +49,14 @@ class Q_GUI_EXPORT QOpenGLPixelTransferOptions
public:
QOpenGLPixelTransferOptions();
QOpenGLPixelTransferOptions(const QOpenGLPixelTransferOptions &);
- QOpenGLPixelTransferOptions &operator=(const QOpenGLPixelTransferOptions &);
- ~QOpenGLPixelTransferOptions();
-
#ifdef Q_COMPILER_RVALUE_REFS
- QOpenGLPixelTransferOptions &operator=(QOpenGLPixelTransferOptions &&other)
+ QOpenGLPixelTransferOptions &operator=(QOpenGLPixelTransferOptions &&other) Q_DECL_NOTHROW
{ swap(other); return *this; }
#endif
+ QOpenGLPixelTransferOptions &operator=(const QOpenGLPixelTransferOptions &);
+ ~QOpenGLPixelTransferOptions();
- void swap(QOpenGLPixelTransferOptions &other)
+ void swap(QOpenGLPixelTransferOptions &other) Q_DECL_NOTHROW
{ data.swap(other.data); }
void setAlignment(int alignment);
diff --git a/src/gui/opengl/qopenglshaderprogram.cpp b/src/gui/opengl/qopenglshaderprogram.cpp
index 04b796ddb0..9714aa4bec 100644
--- a/src/gui/opengl/qopenglshaderprogram.cpp
+++ b/src/gui/opengl/qopenglshaderprogram.cpp
@@ -1783,7 +1783,7 @@ void QOpenGLShaderProgram::setAttributeBuffer
Q_UNUSED(d);
if (location != -1) {
d->glfuncs->glVertexAttribPointer(location, tupleSize, type, GL_TRUE, stride,
- reinterpret_cast<const void *>(offset));
+ reinterpret_cast<const void *>(qintptr(offset)));
}
}
diff --git a/src/gui/opengl/qopenglshaderprogram.h b/src/gui/opengl/qopenglshaderprogram.h
index 9f5957e612..b959954718 100644
--- a/src/gui/opengl/qopenglshaderprogram.h
+++ b/src/gui/opengl/qopenglshaderprogram.h
@@ -66,7 +66,7 @@ public:
};
Q_DECLARE_FLAGS(ShaderType, ShaderTypeBit)
- explicit QOpenGLShader(QOpenGLShader::ShaderType type, QObject *parent = 0);
+ explicit QOpenGLShader(QOpenGLShader::ShaderType type, QObject *parent = Q_NULLPTR);
virtual ~QOpenGLShader();
QOpenGLShader::ShaderType shaderType() const;
@@ -83,7 +83,7 @@ public:
GLuint shaderId() const;
- static bool hasOpenGLShaders(ShaderType type, QOpenGLContext *context = 0);
+ static bool hasOpenGLShaders(ShaderType type, QOpenGLContext *context = Q_NULLPTR);
private:
friend class QOpenGLShaderProgram;
@@ -101,7 +101,7 @@ class Q_GUI_EXPORT QOpenGLShaderProgram : public QObject
{
Q_OBJECT
public:
- explicit QOpenGLShaderProgram(QObject *parent = 0);
+ explicit QOpenGLShaderProgram(QObject *parent = Q_NULLPTR);
virtual ~QOpenGLShaderProgram();
bool addShader(QOpenGLShader *shader);
@@ -288,7 +288,7 @@ public:
void setUniformValueArray(const char *name, const QMatrix4x3 *values, int count);
void setUniformValueArray(const char *name, const QMatrix4x4 *values, int count);
- static bool hasOpenGLShaderPrograms(QOpenGLContext *context = 0);
+ static bool hasOpenGLShaderPrograms(QOpenGLContext *context = Q_NULLPTR);
private Q_SLOTS:
void shaderDestroyed();
diff --git a/src/gui/opengl/qopengltexture.cpp b/src/gui/opengl/qopengltexture.cpp
index 5271826015..301b2ad13d 100644
--- a/src/gui/opengl/qopengltexture.cpp
+++ b/src/gui/opengl/qopengltexture.cpp
@@ -401,6 +401,9 @@ static bool isSizedTextureFormat(QOpenGLTexture::TextureFormat internalFormat)
case QOpenGLTexture::SRGB8_Alpha8_ETC2_EAC:
return true;
+ case QOpenGLTexture::RGB8_ETC1:
+ return false;
+
case QOpenGLTexture::DepthFormat:
case QOpenGLTexture::AlphaFormat:
@@ -442,20 +445,23 @@ static bool isTextureTargetMultisample(QOpenGLTexture::Target target)
return false;
}
-void QOpenGLTexturePrivate::allocateStorage(QOpenGLTexture::PixelFormat pixelFormat, QOpenGLTexture::PixelType pixelType)
+bool QOpenGLTexturePrivate::isUsingImmutableStorage() const
{
- // Resolve the actual number of mipmap levels we can use
- mipLevels = evaluateMipLevels();
-
// Use immutable storage whenever possible, falling back to mutable
// Note that if multisample textures are not supported at all, we'll still fail into
// the mutable storage allocation
- const bool useImmutableStorage = isSizedTextureFormat(format)
+ return isSizedTextureFormat(format)
&& (isTextureTargetMultisample(target)
? features.testFlag(QOpenGLTexture::ImmutableMultisampleStorage)
: features.testFlag(QOpenGLTexture::ImmutableStorage));
+}
+
+void QOpenGLTexturePrivate::allocateStorage(QOpenGLTexture::PixelFormat pixelFormat, QOpenGLTexture::PixelType pixelType)
+{
+ // Resolve the actual number of mipmap levels we can use
+ mipLevels = evaluateMipLevels();
- if (useImmutableStorage)
+ if (isUsingImmutableStorage())
allocateImmutableStorage();
else
allocateMutableStorage(pixelFormat, pixelType);
@@ -663,6 +669,7 @@ static QOpenGLTexture::PixelFormat pixelFormatCompatibleWithInternalFormat(QOpen
case QOpenGLTexture::SRGB_Alpha_DXT3:
case QOpenGLTexture::SRGB_Alpha_DXT5:
case QOpenGLTexture::SRGB_BP_UNorm:
+ case QOpenGLTexture::RGB8_ETC1:
return QOpenGLTexture::RGBA;
case QOpenGLTexture::R11_EAC_UNorm:
@@ -840,6 +847,7 @@ static QOpenGLTexture::PixelType pixelTypeCompatibleWithInternalFormat(QOpenGLTe
case QOpenGLTexture::SRGB8_PunchThrough_Alpha1_ETC2:
case QOpenGLTexture::RGBA8_ETC2_EAC:
case QOpenGLTexture::SRGB8_Alpha8_ETC2_EAC:
+ case QOpenGLTexture::RGB8_ETC1:
return QOpenGLTexture::UInt8;
case QOpenGLTexture::DepthFormat:
@@ -857,8 +865,133 @@ static QOpenGLTexture::PixelType pixelTypeCompatibleWithInternalFormat(QOpenGLTe
return QOpenGLTexture::NoPixelType;
}
+static bool isCompressedFormat(QOpenGLTexture::TextureFormat internalFormat)
+{
+ switch (internalFormat) {
+ case QOpenGLTexture::NoFormat:
+
+ case QOpenGLTexture::R8_UNorm:
+ case QOpenGLTexture::RG8_UNorm:
+ case QOpenGLTexture::RGB8_UNorm:
+ case QOpenGLTexture::RGBA8_UNorm:
+ case QOpenGLTexture::R16_UNorm:
+ case QOpenGLTexture::RG16_UNorm:
+ case QOpenGLTexture::RGB16_UNorm:
+ case QOpenGLTexture::RGBA16_UNorm:
+ case QOpenGLTexture::R8_SNorm:
+ case QOpenGLTexture::RG8_SNorm:
+ case QOpenGLTexture::RGB8_SNorm:
+ case QOpenGLTexture::RGBA8_SNorm:
+ case QOpenGLTexture::R16_SNorm:
+ case QOpenGLTexture::RG16_SNorm:
+ case QOpenGLTexture::RGB16_SNorm:
+ case QOpenGLTexture::RGBA16_SNorm:
+ case QOpenGLTexture::R8U:
+ case QOpenGLTexture::RG8U:
+ case QOpenGLTexture::RGB8U:
+ case QOpenGLTexture::RGBA8U:
+ case QOpenGLTexture::R16U:
+ case QOpenGLTexture::RG16U:
+ case QOpenGLTexture::RGB16U:
+ case QOpenGLTexture::RGBA16U:
+ case QOpenGLTexture::R32U:
+ case QOpenGLTexture::RG32U:
+ case QOpenGLTexture::RGB32U:
+ case QOpenGLTexture::RGBA32U:
+ case QOpenGLTexture::R8I:
+ case QOpenGLTexture::RG8I:
+ case QOpenGLTexture::RGB8I:
+ case QOpenGLTexture::RGBA8I:
+ case QOpenGLTexture::R16I:
+ case QOpenGLTexture::RG16I:
+ case QOpenGLTexture::RGB16I:
+ case QOpenGLTexture::RGBA16I:
+ case QOpenGLTexture::R32I:
+ case QOpenGLTexture::RG32I:
+ case QOpenGLTexture::RGB32I:
+ case QOpenGLTexture::RGBA32I:
+ case QOpenGLTexture::R16F:
+ case QOpenGLTexture::RG16F:
+ case QOpenGLTexture::RGB16F:
+ case QOpenGLTexture::RGBA16F:
+ case QOpenGLTexture::R32F:
+ case QOpenGLTexture::RG32F:
+ case QOpenGLTexture::RGB32F:
+ case QOpenGLTexture::RGBA32F:
+ case QOpenGLTexture::RGB9E5:
+ case QOpenGLTexture::RG11B10F:
+ case QOpenGLTexture::RG3B2:
+ case QOpenGLTexture::R5G6B5:
+ case QOpenGLTexture::RGB5A1:
+ case QOpenGLTexture::RGBA4:
+ case QOpenGLTexture::RGB10A2:
+
+ case QOpenGLTexture::D16:
+ case QOpenGLTexture::D24:
+ case QOpenGLTexture::D32:
+ case QOpenGLTexture::D32F:
+
+ case QOpenGLTexture::D24S8:
+ case QOpenGLTexture::D32FS8X24:
+
+ case QOpenGLTexture::S8:
+ return false;
+
+ case QOpenGLTexture::RGB_DXT1:
+ case QOpenGLTexture::RGBA_DXT1:
+ case QOpenGLTexture::RGBA_DXT3:
+ case QOpenGLTexture::RGBA_DXT5:
+ case QOpenGLTexture::R_ATI1N_UNorm:
+ case QOpenGLTexture::R_ATI1N_SNorm:
+ case QOpenGLTexture::RG_ATI2N_UNorm:
+ case QOpenGLTexture::RG_ATI2N_SNorm:
+ case QOpenGLTexture::RGB_BP_UNSIGNED_FLOAT:
+ case QOpenGLTexture::RGB_BP_SIGNED_FLOAT:
+ case QOpenGLTexture::RGB_BP_UNorm:
+ case QOpenGLTexture::SRGB8:
+ case QOpenGLTexture::SRGB8_Alpha8:
+ case QOpenGLTexture::SRGB_DXT1:
+ case QOpenGLTexture::SRGB_Alpha_DXT1:
+ case QOpenGLTexture::SRGB_Alpha_DXT3:
+ case QOpenGLTexture::SRGB_Alpha_DXT5:
+ case QOpenGLTexture::SRGB_BP_UNorm:
+ case QOpenGLTexture::R11_EAC_UNorm:
+ case QOpenGLTexture::R11_EAC_SNorm:
+ case QOpenGLTexture::RG11_EAC_UNorm:
+ case QOpenGLTexture::RG11_EAC_SNorm:
+ case QOpenGLTexture::RGB8_ETC2:
+ case QOpenGLTexture::SRGB8_ETC2:
+ case QOpenGLTexture::RGB8_PunchThrough_Alpha1_ETC2:
+ case QOpenGLTexture::SRGB8_PunchThrough_Alpha1_ETC2:
+ case QOpenGLTexture::RGBA8_ETC2_EAC:
+ case QOpenGLTexture::SRGB8_Alpha8_ETC2_EAC:
+ case QOpenGLTexture::RGB8_ETC1:
+ return true;
+
+ case QOpenGLTexture::DepthFormat:
+ case QOpenGLTexture::AlphaFormat:
+ case QOpenGLTexture::RGBFormat:
+ case QOpenGLTexture::RGBAFormat:
+ case QOpenGLTexture::LuminanceFormat:
+ case QOpenGLTexture::LuminanceAlphaFormat:
+ return false;
+ }
+
+ Q_UNREACHABLE();
+ return false;
+}
+
void QOpenGLTexturePrivate::allocateMutableStorage(QOpenGLTexture::PixelFormat pixelFormat, QOpenGLTexture::PixelType pixelType)
{
+ // There is no way to allocate mutable storage for compressed textures in in
+ // versions older than OpenGL 3.1 and OpenGL ES 3.0, because the older specs
+ // do not mandate accepting null data pointers for glCompressedTexImage*D,
+ // unlike glTexImage*D (which in turn does not accept compressed formats).
+ if (isCompressedFormat(format)) {
+ storageAllocated = true;
+ return;
+ }
+
switch (target) {
case QOpenGLTexture::TargetBuffer:
// Buffer textures get their storage from an external OpenGL buffer
@@ -1196,86 +1329,121 @@ void QOpenGLTexturePrivate::setCompressedData(int mipLevel, int layer, QOpenGLTe
int dataSize, const void *data,
const QOpenGLPixelTransferOptions * const options)
{
+ if (!isCompressedFormat(format)) {
+ qWarning("Cannot set compressed data for non-compressed format 0x%x", format);
+ return;
+ }
+
+ const bool needsFullSpec = !isUsingImmutableStorage(); // was allocateStorage() a no-op?
+
switch (target) {
case QOpenGLTexture::Target1D:
Q_UNUSED(layer);
Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage1D(textureId, target, bindingTarget, mipLevel,
- 0, mipLevelSize( mipLevel, dimensions[0] ),
- format, dataSize, data, options);
+ if (needsFullSpec) {
+ texFuncs->glCompressedTextureImage1D(textureId, target, bindingTarget, mipLevel,
+ format,
+ mipLevelSize(mipLevel, dimensions[0]),
+ 0, dataSize, data, options);
+ } else {
+ texFuncs->glCompressedTextureSubImage1D(textureId, target, bindingTarget, mipLevel,
+ 0, mipLevelSize( mipLevel, dimensions[0] ),
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::Target1DArray:
Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
- 0, layer,
- mipLevelSize(mipLevel, dimensions[0]),
- 1,
- format, dataSize, data, options);
+ if (!needsFullSpec) {
+ texFuncs->glCompressedTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
+ 0, layer,
+ mipLevelSize(mipLevel, dimensions[0]),
+ 1,
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::Target2D:
Q_UNUSED(layer);
Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
- 0, 0,
- mipLevelSize(mipLevel, dimensions[0]),
- mipLevelSize(mipLevel, dimensions[1]),
- format, dataSize, data, options);
+ if (needsFullSpec) {
+ texFuncs->glCompressedTextureImage2D(textureId, target, bindingTarget, mipLevel,
+ format,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ 0, dataSize, data, options);
+ } else {
+ texFuncs->glCompressedTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
+ 0, 0,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::Target2DArray:
Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
- 0, 0, layer,
- mipLevelSize(mipLevel, dimensions[0]),
- mipLevelSize(mipLevel, dimensions[1]),
- 1,
- format, dataSize, data, options);
+ if (!needsFullSpec) {
+ texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ 0, 0, layer,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ 1,
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::Target3D:
Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
- 0, 0, layer,
- mipLevelSize(mipLevel, dimensions[0]),
- mipLevelSize(mipLevel, dimensions[1]),
- mipLevelSize(mipLevel, dimensions[2]),
- format, dataSize, data, options);
+ if (needsFullSpec) {
+ texFuncs->glCompressedTextureImage3D(textureId, target, bindingTarget, mipLevel,
+ format,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ mipLevelSize(mipLevel, dimensions[2]),
+ 0, dataSize, data, options);
+ } else {
+ texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ 0, 0, layer,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ mipLevelSize(mipLevel, dimensions[2]),
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::TargetCubeMap:
Q_UNUSED(layer);
- texFuncs->glCompressedTextureSubImage2D(textureId, cubeFace, bindingTarget, mipLevel,
- 0, 0,
- mipLevelSize(mipLevel, dimensions[0]),
- mipLevelSize(mipLevel, dimensions[1]),
- format, dataSize, data, options);
+ if (needsFullSpec) {
+ texFuncs->glCompressedTextureImage2D(textureId, cubeFace, bindingTarget, mipLevel,
+ format,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ 0, dataSize, data, options);
+ } else {
+ texFuncs->glCompressedTextureSubImage2D(textureId, cubeFace, bindingTarget, mipLevel,
+ 0, 0,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ format, dataSize, data, options);
+ }
break;
case QOpenGLTexture::TargetCubeMapArray: {
int faceIndex = cubeFace - QOpenGLTexture::CubeMapPositiveX;
int layerFace = 6 * layer + faceIndex;
- texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
- 0, 0, layerFace,
- mipLevelSize(mipLevel, dimensions[0]),
- mipLevelSize(mipLevel, dimensions[1]),
- 1,
- format, dataSize, data, options);
+ if (!needsFullSpec) {
+ texFuncs->glCompressedTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ 0, 0, layerFace,
+ mipLevelSize(mipLevel, dimensions[0]),
+ mipLevelSize(mipLevel, dimensions[1]),
+ 1,
+ format, dataSize, data, options);
+ }
break;
}
case QOpenGLTexture::TargetRectangle:
- Q_UNUSED(mipLevel);
- Q_UNUSED(layer);
- Q_UNUSED(cubeFace);
- texFuncs->glCompressedTextureSubImage2D(textureId, target, bindingTarget, 0,
- 0, 0,
- dimensions[0],
- dimensions[1],
- format, dataSize, data, options);
- break;
-
case QOpenGLTexture::Target2DMultisample:
case QOpenGLTexture::Target2DMultisampleArray:
case QOpenGLTexture::TargetBuffer:
@@ -1857,6 +2025,7 @@ QOpenGLTexture *QOpenGLTexturePrivate::createTextureView(QOpenGLTexture::Target
\value SRGB8_PunchThrough_Alpha1_ETC2 Equivalent to GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
\value RGBA8_ETC2_EAC Equivalent to GL_COMPRESSED_RGBA8_ETC2_EAC
\value SRGB8_Alpha8_ETC2_EAC Equivalent to GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
+ \value RGB8_ETC1 Equivalent to GL_ETC1_RGB8_OES
\value SRGB8 Equivalent to GL_SRGB8
\value SRGB8_Alpha8 Equivalent to GL_SRGB8_ALPHA8
@@ -2394,6 +2563,7 @@ void QOpenGLTexture::setFormat(TextureFormat format)
case QOpenGLTexture::SRGB8_PunchThrough_Alpha1_ETC2:
case QOpenGLTexture::RGBA8_ETC2_EAC:
case QOpenGLTexture::SRGB8_Alpha8_ETC2_EAC:
+ case QOpenGLTexture::RGB8_ETC1:
case RG3B2:
case R5G6B5:
case RGB5A1:
@@ -3458,6 +3628,8 @@ QPair<int, int> QOpenGLTexture::mipLevelRange() const
The automatic mipmap generation is enabled by default.
+ \note Mipmap generation is not supported for compressed textures with OpenGL ES 2.0.
+
\sa isAutoMipMapGenerationEnabled(), generateMipMaps()
*/
void QOpenGLTexture::setAutoMipMapGenerationEnabled(bool enabled)
@@ -3483,6 +3655,9 @@ bool QOpenGLTexture::isAutoMipMapGenerationEnabled() const
have disabled automatic mipmap generation then you need to call this function
or the overload to create the mipmap chain.
+ \note Mipmap generation is not supported for compressed textures with OpenGL
+ ES 2.0.
+
\sa setAutoMipMapGenerationEnabled(), setMipLevels(), mipLevels()
*/
void QOpenGLTexture::generateMipMaps()
@@ -3490,6 +3665,11 @@ void QOpenGLTexture::generateMipMaps()
Q_D(QOpenGLTexture);
Q_ASSERT(d->texFuncs);
Q_ASSERT(d->textureId);
+ if (isCompressedFormat(d->format)) {
+ if (QOpenGLContext *ctx = QOpenGLContext::currentContext())
+ if (ctx->isOpenGLES() && ctx->format().majorVersion() < 3)
+ return;
+ }
d->texFuncs->glGenerateTextureMipmap(d->textureId, d->target, d->bindingTarget);
}
@@ -3510,6 +3690,11 @@ void QOpenGLTexture::generateMipMaps(int baseLevel, bool resetBaseLevel)
Q_D(QOpenGLTexture);
Q_ASSERT(d->texFuncs);
Q_ASSERT(d->textureId);
+ if (isCompressedFormat(d->format)) {
+ if (QOpenGLContext *ctx = QOpenGLContext::currentContext())
+ if (ctx->isOpenGLES() && ctx->format().majorVersion() < 3)
+ return;
+ }
int oldBaseLevel;
if (resetBaseLevel)
oldBaseLevel = mipBaseLevel();
diff --git a/src/gui/opengl/qopengltexture.h b/src/gui/opengl/qopengltexture.h
index 3017aac737..ec52a192fa 100644
--- a/src/gui/opengl/qopengltexture.h
+++ b/src/gui/opengl/qopengltexture.h
@@ -196,6 +196,7 @@ public:
SRGB8_PunchThrough_Alpha1_ETC2 = 0x9277, // GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
RGBA8_ETC2_EAC = 0x9278, // GL_COMPRESSED_RGBA8_ETC2_EAC
SRGB8_Alpha8_ETC2_EAC = 0x9279, // GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
+ RGB8_ETC1 = 0x8D64, // GL_ETC1_RGB8_OES
// sRGB formats
SRGB8 = 0x8C41, // GL_SRGB8
@@ -409,54 +410,54 @@ public:
#if QT_DEPRECATED_SINCE(5, 3)
QT_DEPRECATED void setData(int mipLevel, int layer, CubeMapFace cubeFace,
PixelFormat sourceFormat, PixelType sourceType,
- void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setData(int mipLevel, int layer,
PixelFormat sourceFormat, PixelType sourceType,
- void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setData(int mipLevel,
PixelFormat sourceFormat, PixelType sourceType,
- void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setData(PixelFormat sourceFormat, PixelType sourceType,
- void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
#endif // QT_DEPRECATED_SINCE(5, 3)
void setData(int mipLevel, int layer, CubeMapFace cubeFace,
PixelFormat sourceFormat, PixelType sourceType,
- const void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ const void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setData(int mipLevel, int layer,
PixelFormat sourceFormat, PixelType sourceType,
- const void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ const void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setData(int mipLevel,
PixelFormat sourceFormat, PixelType sourceType,
- const void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ const void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setData(PixelFormat sourceFormat, PixelType sourceType,
- const void *data, const QOpenGLPixelTransferOptions * const options = 0);
+ const void *data, const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
// Compressed data upload
// ### Qt 6: remove the non-const void * overloads
#if QT_DEPRECATED_SINCE(5, 3)
QT_DEPRECATED void setCompressedData(int mipLevel, int layer, CubeMapFace cubeFace,
int dataSize, void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setCompressedData(int mipLevel, int layer,
int dataSize, void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setCompressedData(int mipLevel, int dataSize, void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
QT_DEPRECATED void setCompressedData(int dataSize, void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
#endif // QT_DEPRECATED_SINCE(5, 3)
void setCompressedData(int mipLevel, int layer, CubeMapFace cubeFace,
int dataSize, const void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setCompressedData(int mipLevel, int layer,
int dataSize, const void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setCompressedData(int mipLevel, int dataSize, const void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
void setCompressedData(int dataSize, const void *data,
- const QOpenGLPixelTransferOptions * const options = 0);
+ const QOpenGLPixelTransferOptions * const options = Q_NULLPTR);
// Helpful overloads for setData
void setData(const QImage& image, MipMapGeneration genMipMaps = GenerateMipMaps);
diff --git a/src/gui/opengl/qopengltexture_p.h b/src/gui/opengl/qopengltexture_p.h
index be4bf0e93c..ac9d44db42 100644
--- a/src/gui/opengl/qopengltexture_p.h
+++ b/src/gui/opengl/qopengltexture_p.h
@@ -117,6 +117,8 @@ public:
return std::floor(double(qMax(1, baseLevelSize >> mipLevel)));
}
+ bool isUsingImmutableStorage() const;
+
QOpenGLTexture *q_ptr;
QOpenGLContext *context;
QOpenGLTexture::Target target;
diff --git a/src/gui/opengl/qopengltexturehelper_p.h b/src/gui/opengl/qopengltexturehelper_p.h
index 5a56516b49..d659fcedfb 100644
--- a/src/gui/opengl/qopengltexturehelper_p.h
+++ b/src/gui/opengl/qopengltexturehelper_p.h
@@ -253,23 +253,48 @@ public:
inline void glCompressedTextureImage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level,
GLenum internalFormat, GLsizei width,
- GLint border, GLsizei imageSize, const GLvoid *bits)
+ GLint border, GLsizei imageSize, const GLvoid *bits,
+ const QOpenGLPixelTransferOptions * const options = 0)
{
- (this->*CompressedTextureImage1D)(texture, target, bindingTarget, level, internalFormat, width, border, imageSize, bits);
+ if (options) {
+ QOpenGLPixelTransferOptions oldOptions = savePixelUploadOptions();
+ setPixelUploadOptions(*options);
+ (this->*CompressedTextureImage1D)(texture, target, bindingTarget, level, internalFormat, width, border, imageSize, bits);
+ setPixelUploadOptions(oldOptions);
+ } else {
+ (this->*CompressedTextureImage1D)(texture, target, bindingTarget, level, internalFormat, width, border, imageSize, bits);
+ }
}
inline void glCompressedTextureImage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level,
GLenum internalFormat, GLsizei width, GLsizei height,
- GLint border, GLsizei imageSize, const GLvoid *bits)
+ GLint border, GLsizei imageSize, const GLvoid *bits,
+ const QOpenGLPixelTransferOptions * const options = 0)
+
{
- (this->*CompressedTextureImage2D)(texture, target, bindingTarget, level, internalFormat, width, height, border, imageSize, bits);
+ if (options) {
+ QOpenGLPixelTransferOptions oldOptions = savePixelUploadOptions();
+ setPixelUploadOptions(*options);
+ (this->*CompressedTextureImage2D)(texture, target, bindingTarget, level, internalFormat, width, height, border, imageSize, bits);
+ setPixelUploadOptions(oldOptions);
+ } else {
+ (this->*CompressedTextureImage2D)(texture, target, bindingTarget, level, internalFormat, width, height, border, imageSize, bits);
+ }
}
inline void glCompressedTextureImage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level,
GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth,
- GLint border, GLsizei imageSize, const GLvoid *bits)
+ GLint border, GLsizei imageSize, const GLvoid *bits,
+ const QOpenGLPixelTransferOptions * const options = 0)
{
- (this->*CompressedTextureImage3D)(texture, target, bindingTarget, level, internalFormat, width, height, depth, border, imageSize, bits);
+ if (options) {
+ QOpenGLPixelTransferOptions oldOptions = savePixelUploadOptions();
+ setPixelUploadOptions(*options);
+ (this->*CompressedTextureImage3D)(texture, target, bindingTarget, level, internalFormat, width, height, depth, border, imageSize, bits);
+ setPixelUploadOptions(oldOptions);
+ } else {
+ (this->*CompressedTextureImage3D)(texture, target, bindingTarget, level, internalFormat, width, height, depth, border, imageSize, bits);
+ }
}
private:
diff --git a/src/gui/opengl/qopengltimerquery.h b/src/gui/opengl/qopengltimerquery.h
index 7e46250546..ad111dc03c 100644
--- a/src/gui/opengl/qopengltimerquery.h
+++ b/src/gui/opengl/qopengltimerquery.h
@@ -50,7 +50,7 @@ class Q_GUI_EXPORT QOpenGLTimerQuery : public QObject
Q_OBJECT
public:
- explicit QOpenGLTimerQuery(QObject *parent = 0);
+ explicit QOpenGLTimerQuery(QObject *parent = Q_NULLPTR);
~QOpenGLTimerQuery();
bool create();
@@ -78,7 +78,7 @@ class Q_GUI_EXPORT QOpenGLTimeMonitor : public QObject
Q_OBJECT
public:
- explicit QOpenGLTimeMonitor(QObject *parent = 0);
+ explicit QOpenGLTimeMonitor(QObject *parent = Q_NULLPTR);
~QOpenGLTimeMonitor();
void setSampleCount(int sampleCount);
diff --git a/src/gui/opengl/qopenglversionfunctions.h b/src/gui/opengl/qopenglversionfunctions.h
index fcf665f97e..a5d5677938 100644
--- a/src/gui/opengl/qopenglversionfunctions.h
+++ b/src/gui/opengl/qopenglversionfunctions.h
@@ -47,7 +47,10 @@
#ifndef QT_NO_OPENGL
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
+#include <QtCore/qhashfunctions.h>
#include <QtCore/qpair.h>
#include <QtGui/qopengl.h>
@@ -120,7 +123,7 @@ class QAbstractOpenGLFunctionsPrivate
{
public:
QAbstractOpenGLFunctionsPrivate()
- : owningContext(0),
+ : owningContext(Q_NULLPTR),
initialized(false)
{}
diff --git a/src/gui/opengl/qopenglvertexarrayobject.h b/src/gui/opengl/qopenglvertexarrayobject.h
index 3e01d31202..e8ebf41071 100644
--- a/src/gui/opengl/qopenglvertexarrayobject.h
+++ b/src/gui/opengl/qopenglvertexarrayobject.h
@@ -50,7 +50,7 @@ class Q_GUI_EXPORT QOpenGLVertexArrayObject : public QObject
Q_OBJECT
public:
- explicit QOpenGLVertexArrayObject(QObject* parent = 0);
+ explicit QOpenGLVertexArrayObject(QObject* parent = Q_NULLPTR);
~QOpenGLVertexArrayObject();
bool create();
diff --git a/src/gui/opengl/qtriangulatingstroker.cpp b/src/gui/opengl/qtriangulatingstroker.cpp
index cfbf8a75c5..5967bd6e89 100644
--- a/src/gui/opengl/qtriangulatingstroker.cpp
+++ b/src/gui/opengl/qtriangulatingstroker.cpp
@@ -127,7 +127,7 @@ void QTriangulatingStroker::process(const QVectorPath &path, const QPen &pen, co
m_roundness = 1;
} else if (cosmetic) {
m_curvyness_add = realWidth / 2;
- m_curvyness_mul = CURVE_FLATNESS;
+ m_curvyness_mul = float(CURVE_FLATNESS);
m_roundness = qMax<int>(4, realWidth * CURVE_FLATNESS);
} else {
m_curvyness_add = m_width;
@@ -543,7 +543,7 @@ void QDashedStrokeProcessor::process(const QVectorPath &path, const QPen &pen, c
curvynessMul = CURVE_FLATNESS / m_inv_scale;
} else if (cosmetic) {
curvynessAdd= width / 2;
- curvynessMul= CURVE_FLATNESS;
+ curvynessMul= float(CURVE_FLATNESS);
} else {
curvynessAdd = width * m_inv_scale;
curvynessMul = CURVE_FLATNESS / m_inv_scale;
diff --git a/src/gui/painting/painting.pri b/src/gui/painting/painting.pri
index a861516821..791b5f1a9a 100644
--- a/src/gui/painting/painting.pri
+++ b/src/gui/painting/painting.pri
@@ -43,6 +43,8 @@ HEADERS += \
painting/qrasterizer_p.h \
painting/qregion.h \
painting/qrgb.h \
+ painting/qrgba64.h \
+ painting/qrgba64_p.h \
painting/qstroker_p.h \
painting/qtextureglyphcache_p.h \
painting/qtransform.h \
@@ -58,6 +60,7 @@ SOURCES += \
painting/qbrush.cpp \
painting/qcolor.cpp \
painting/qcolor_p.cpp \
+ painting/qcompositionfunctions.cpp \
painting/qcosmeticstroker.cpp \
painting/qcssutil.cpp \
painting/qdrawhelper.cpp \
diff --git a/src/gui/painting/qbackingstore.cpp b/src/gui/painting/qbackingstore.cpp
index f2fee99b99..8a5a6d4fcf 100644
--- a/src/gui/painting/qbackingstore.cpp
+++ b/src/gui/painting/qbackingstore.cpp
@@ -38,10 +38,13 @@
#include <qpa/qplatformintegration.h>
#include <qscreen.h>
#include <qdebug.h>
+#include <qscopedpointer.h>
#include <private/qguiapplication_p.h>
#include <private/qwindow_p.h>
+#include <private/qhighdpiscaling_p.h>
+
QT_BEGIN_NAMESPACE
class QBackingStorePrivate
@@ -54,6 +57,7 @@ public:
QWindow *window;
QPlatformBackingStore *platformBackingStore;
+ QScopedPointer<QImage> highDpiBackingstore;
QRegion staticContents;
QSize size;
};
@@ -102,7 +106,7 @@ void QBackingStore::flush(const QRegion &region, QWindow *win, const QPoint &off
}
#endif
- d_ptr->platformBackingStore->flush(win, region, offset);
+ d_ptr->platformBackingStore->flush(win, QHighDpi::toNativeLocalRegion(region, d_ptr->window), offset);
}
/*!
@@ -112,7 +116,12 @@ void QBackingStore::flush(const QRegion &region, QWindow *win, const QPoint &off
*/
QPaintDevice *QBackingStore::paintDevice()
{
- return d_ptr->platformBackingStore->paintDevice();
+ QPaintDevice *device = d_ptr->platformBackingStore->paintDevice();
+
+ if (QHighDpiScaling::isActive() && device->devType() == QInternal::Image)
+ return d_ptr->highDpiBackingstore.data();
+
+ return device;
}
/*!
@@ -150,7 +159,37 @@ QWindow* QBackingStore::window() const
void QBackingStore::beginPaint(const QRegion &region)
{
- d_ptr->platformBackingStore->beginPaint(region);
+ if (d_ptr->highDpiBackingstore &&
+ d_ptr->highDpiBackingstore->devicePixelRatio() != d_ptr->window->devicePixelRatio())
+ resize(size());
+
+ d_ptr->platformBackingStore->beginPaint(QHighDpi::toNativeLocalRegion(region, d_ptr->window));
+
+ // When QtGui is applying a high-dpi scale factor the backing store
+ // creates a "large" backing store image. This image needs to be
+ // painted on as a high-dpi image, which is done by setting
+ // devicePixelRatio. Do this on a separate image instance that shares
+ // the image data to avoid having the new devicePixelRatio be propagated
+ // back to the platform plugin.
+ QPaintDevice *device = d_ptr->platformBackingStore->paintDevice();
+ if (QHighDpiScaling::isActive() && device->devType() == QInternal::Image) {
+ QImage *source = static_cast<QImage *>(device);
+ const bool needsNewImage = d_ptr->highDpiBackingstore.isNull()
+ || source->data_ptr() != d_ptr->highDpiBackingstore->data_ptr()
+ || source->size() != d_ptr->highDpiBackingstore->size()
+ || source->devicePixelRatio() != d_ptr->highDpiBackingstore->devicePixelRatio();
+ if (needsNewImage) {
+ qCDebug(lcScaling) << "QBackingStore::beginPaint new backingstore for" << d_ptr->window;
+ qCDebug(lcScaling) << " source size" << source->size() << "dpr" << source->devicePixelRatio();
+ d_ptr->highDpiBackingstore.reset(
+ new QImage(source->bits(), source->width(), source->height(), source->bytesPerLine(), source->format()));
+
+ qreal targetDevicePixelRatio = d_ptr->window->devicePixelRatio();
+ d_ptr->highDpiBackingstore->setDevicePixelRatio(targetDevicePixelRatio);
+ qCDebug(lcScaling) <<" destination size" << d_ptr->highDpiBackingstore->size()
+ << "dpr" << targetDevicePixelRatio;
+ }
+ }
}
/*!
@@ -171,7 +210,7 @@ void QBackingStore::endPaint()
void QBackingStore::resize(const QSize &size)
{
d_ptr->size = size;
- d_ptr->platformBackingStore->resize(size, d_ptr->staticContents);
+ d_ptr->platformBackingStore->resize(QHighDpi::toNativePixels(size, d_ptr->window), d_ptr->staticContents);
}
/*!
@@ -194,7 +233,7 @@ bool QBackingStore::scroll(const QRegion &area, int dx, int dy)
Q_UNUSED(dx);
Q_UNUSED(dy);
- return d_ptr->platformBackingStore->scroll(area, dx, dy);
+ return d_ptr->platformBackingStore->scroll(QHighDpi::toNativeLocalRegion(area, d_ptr->window), QHighDpi::toNativePixels(dx, d_ptr->window), QHighDpi::toNativePixels(dy, d_ptr->window));
}
/*!
diff --git a/src/gui/painting/qbackingstore.h b/src/gui/painting/qbackingstore.h
index ee3c05f7a9..331fa8c534 100644
--- a/src/gui/painting/qbackingstore.h
+++ b/src/gui/painting/qbackingstore.h
@@ -61,7 +61,7 @@ public:
// 'window' can be a child window, in which case 'region' is in child window coordinates and
// offset is the (child) window's offset in relation to the window surface.
- void flush(const QRegion &region, QWindow *window = 0, const QPoint &offset = QPoint());
+ void flush(const QRegion &region, QWindow *window = Q_NULLPTR, const QPoint &offset = QPoint());
void resize(const QSize &size);
QSize size() const;
diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp
index dbdd82e432..0898a20998 100644
--- a/src/gui/painting/qblendfunctions.cpp
+++ b/src/gui/painting/qblendfunctions.cpp
@@ -395,169 +395,6 @@ void qt_blend_rgb32_on_rgb32(uchar *destPixels, int dbpl,
}
}
-template<QtPixelOrder PixelOrder>
-static void qt_blend_argb32pm_on_a2rgb30pm(uchar *destPixels, int dbpl,
- const uchar *srcPixels, int sbpl,
- int w, int h,
- int const_alpha)
-{
-#ifdef QT_DEBUG_DRAW
- fprintf(stdout, "qt_blend_argb32pm_on_a2rgb30pm: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n",
- destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- fflush(stdout);
-#endif
-
- const uint *src = (const uint *) srcPixels;
- uint *dst = (uint *) destPixels;
- if (const_alpha == 256) {
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint s = src[x];
- dst[x] = qConvertArgb32ToA2rgb30<PixelOrder>(s) + BYTE_MUL_RGB30(dst[x], 255 - qAlpha(s));
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- } else if (const_alpha != 0) {
- const_alpha = (const_alpha * 255) >> 8;
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint s = src[x];
- dst[x] = BYTE_MUL_RGB30(qConvertArgb32ToA2rgb30<PixelOrder>(s), const_alpha) + BYTE_MUL_RGB30(dst[x], 255 - qt_div_255(qAlpha(s) * const_alpha));
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- }
-}
-
-template<QtPixelOrder PixelOrder>
-static void qt_blend_rgb32_on_rgb30(uchar *destPixels, int dbpl,
- const uchar *srcPixels, int sbpl,
- int w, int h,
- int const_alpha)
-{
-#ifdef QT_DEBUG_DRAW
- fprintf(stdout, "qt_blend_rgb32_on_rgb30: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n",
- destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- fflush(stdout);
-#endif
-
- if (const_alpha != 256) {
- qt_blend_argb32pm_on_a2rgb30pm<PixelOrder>(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- return;
- }
-
- const uint *src = (const uint *) srcPixels;
- uint *dst = (uint *) destPixels;
- for (int y = 0; y < h; ++y) {
- for (int x = 0; x < w; ++x) {
- dst[x] = qConvertRgb32ToRgb30<PixelOrder>(src[x]);
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
-}
-
-static void qt_blend_a2rgb30pm_on_a2rgb30pm(uchar *destPixels, int dbpl,
- const uchar *srcPixels, int sbpl,
- int w, int h,
- int const_alpha)
-{
-#ifdef QT_DEBUG_DRAW
- fprintf(stdout, "qt_blend_a2rgb30pm_on_a2rgb30pm: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n",
- destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- fflush(stdout);
-#endif
-
- const uint *src = (const uint *) srcPixels;
- uint *dst = (uint *) destPixels;
- if (const_alpha == 256) {
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint s = src[x];
- dst[x] = s + BYTE_MUL_RGB30(dst[x], 255 - qAlphaRgb30(s));
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- } else if (const_alpha != 0) {
- const uint const_alpha255 = (const_alpha * 255) >> 8;
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint a = (qAlphaRgb30(src[x]) * const_alpha) >> 8;
- uint s = BYTE_MUL_RGB30(src[x], const_alpha255);
- dst[x] = s + BYTE_MUL_RGB30(dst[x], 255 - a);
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- }
-}
-
-
-static void qt_blend_rgb30_on_rgb30(uchar *destPixels, int dbpl,
- const uchar *srcPixels, int sbpl,
- int w, int h,
- int const_alpha)
-{
-#ifdef QT_DEBUG_DRAW
- fprintf(stdout, "qt_blend_rgb30_on_rgb30: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n",
- destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- fflush(stdout);
-#endif
-
- if (const_alpha != 256) {
- qt_blend_a2rgb30pm_on_a2rgb30pm(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- return;
- }
-
- const uint *src = (const uint *) srcPixels;
- uint *dst = (uint *) destPixels;
- int len = w * 4;
- for (int y=0; y<h; ++y) {
- memcpy(dst, src, len);
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
-}
-
-static void qt_blend_a2bgr30pm_on_a2rgb30pm(uchar *destPixels, int dbpl,
- const uchar *srcPixels, int sbpl,
- int w, int h,
- int const_alpha)
-{
-#ifdef QT_DEBUG_DRAW
- fprintf(stdout, "qt_blend_a2bgr30pm_on_a2rgb32pm: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n",
- destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha);
- fflush(stdout);
-#endif
-
- const uint *src = (const uint *) srcPixels;
- uint *dst = (uint *) destPixels;
- if (const_alpha == 256) {
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint s = qRgbSwapRgb30(src[x]);
- dst[x] = s + BYTE_MUL_RGB30(dst[x], 255 - qAlphaRgb30(s));
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- } else if (const_alpha != 0) {
- const uint const_alpha255 = (const_alpha * 255) >> 8;
- for (int y=0; y<h; ++y) {
- for (int x=0; x<w; ++x) {
- uint a = (qAlphaRgb30(src[x]) * const_alpha) >> 8;
- uint s = BYTE_MUL_RGB30(src[x], const_alpha255);
- dst[x] = qRgbSwapRgb30(s) + BYTE_MUL_RGB30(dst[x], 255 - a);
- }
- dst = (quint32 *)(((uchar *) dst) + dbpl);
- src = (const quint32 *)(((const uchar *) src) + sbpl);
- }
- }
-}
-
struct Blend_RGB32_on_RGB32_NoAlpha {
inline void write(quint32 *dst, quint32 src) { *dst = src; }
@@ -772,30 +609,6 @@ void qInitBlendFunctions()
qBlendFunctions[QImage::Format_RGBA8888_Premultiplied][QImage::Format_RGBX8888] = qt_blend_rgb32_on_rgb32;
qBlendFunctions[QImage::Format_RGBA8888_Premultiplied][QImage::Format_RGBA8888_Premultiplied] = qt_blend_argb32_on_argb32;
#endif
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb30<PixelOrderBGR>;
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32pm_on_a2rgb30pm<PixelOrderBGR>;
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_BGR30] = qt_blend_rgb30_on_rgb30;
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_A2BGR30_Premultiplied] = qt_blend_a2rgb30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_RGB30] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_BGR30][QImage::Format_A2RGB30_Premultiplied] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb30<PixelOrderBGR>;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32pm_on_a2rgb30pm<PixelOrderBGR>;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_BGR30] = qt_blend_rgb30_on_rgb30;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_A2BGR30_Premultiplied] = qt_blend_a2rgb30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_RGB30] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2BGR30_Premultiplied][QImage::Format_A2RGB30_Premultiplied] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb30<PixelOrderRGB>;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32pm_on_a2rgb30pm<PixelOrderRGB>;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_BGR30] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_A2BGR30_Premultiplied] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_RGB30] = qt_blend_rgb30_on_rgb30;
- qBlendFunctions[QImage::Format_RGB30][QImage::Format_A2RGB30_Premultiplied] = qt_blend_a2rgb30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb30<PixelOrderRGB>;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32pm_on_a2rgb30pm<PixelOrderRGB>;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_BGR30] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_A2BGR30_Premultiplied] = qt_blend_a2bgr30pm_on_a2rgb30pm;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_RGB30] = qt_blend_rgb30_on_rgb30;
- qBlendFunctions[QImage::Format_A2RGB30_Premultiplied][QImage::Format_A2RGB30_Premultiplied] = qt_blend_a2rgb30pm_on_a2rgb30pm;
qTransformFunctions[QImage::Format_RGB32][QImage::Format_RGB32] = qt_transform_image_rgb32_on_rgb32;
qTransformFunctions[QImage::Format_RGB32][QImage::Format_ARGB32_Premultiplied] = qt_transform_image_argb32_on_argb32;
diff --git a/src/gui/painting/qbrush.cpp b/src/gui/painting/qbrush.cpp
index c3a0f5c615..9e039b7ae4 100644
--- a/src/gui/painting/qbrush.cpp
+++ b/src/gui/painting/qbrush.cpp
@@ -1163,6 +1163,7 @@ QDataStream &operator>>(QDataStream &s, QBrush &b)
QColor c;
s >> numStops;
+ stops.reserve(numStops);
for (quint32 i = 0; i < numStops; ++i) {
s >> n >> c;
stops << QPair<qreal, QColor>(n, c);
diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp
index d50c42f1ee..1012ed7c6d 100644
--- a/src/gui/painting/qcolor.cpp
+++ b/src/gui/painting/qcolor.cpp
@@ -416,6 +416,18 @@ QColor::QColor(QRgb color)
ct.argb.pad = 0;
}
+/*!
+ \since 5.6
+
+ Constructs a color with the value \a rgba64.
+
+ \sa fromRgba64()
+*/
+
+QColor::QColor(QRgba64 rgba64)
+{
+ setRgba64(rgba64);
+}
/*!
\internal
@@ -469,6 +481,7 @@ QColor::QColor(Spec spec)
\sa setNamedColor(), name(), isValid()
*/
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
/*!
\fn QColor::QColor(const QColor &color)
@@ -476,6 +489,7 @@ QColor::QColor(Spec spec)
\sa isValid()
*/
+#endif
/*!
\fn bool QColor::isValid() const
@@ -941,7 +955,7 @@ void QColor::setRgb(int r, int g, int b, int a)
For an invalid color, the alpha value of the returned color is unspecified.
- \sa setRgba(), rgb()
+ \sa setRgba(), rgb(), rgba64()
*/
QRgb QColor::rgba() const
@@ -954,7 +968,7 @@ QRgb QColor::rgba() const
/*!
Sets the RGB value to \a rgba, including its alpha.
- \sa rgba(), rgb()
+ \sa rgba(), rgb(), setRgba64()
*/
void QColor::setRgba(QRgb rgba)
{
@@ -967,6 +981,40 @@ void QColor::setRgba(QRgb rgba)
}
/*!
+ \since 5.6
+
+ Returns the RGB64 value of the color, including its alpha.
+
+ For an invalid color, the alpha value of the returned color is unspecified.
+
+ \sa setRgba64(), rgba(), rgb()
+*/
+
+QRgba64 QColor::rgba64() const
+{
+ if (cspec != Invalid && cspec != Rgb)
+ return toRgb().rgba64();
+ return qRgba64(ct.argb.red, ct.argb.green, ct.argb.blue, ct.argb.alpha);
+}
+
+/*!
+ \since 5.6
+
+ Sets the RGB64 value to \a rgba, including its alpha.
+
+ \sa \setRgba(), rgba64()
+*/
+void QColor::setRgba64(QRgba64 rgba)
+{
+ cspec = Rgb;
+ ct.argb.alpha = rgba.alpha();
+ ct.argb.red = rgba.red();
+ ct.argb.green = rgba.green();
+ ct.argb.blue = rgba.blue();
+ ct.argb.pad = 0;
+}
+
+/*!
\fn QRgb QColor::rgb() const
Returns the RGB value of the color. The alpha value is opaque.
@@ -1850,7 +1898,7 @@ QColor QColor::fromRgb(QRgb rgb)
Unlike the fromRgb() function, the alpha-channel specified by the given
QRgb value is included.
- \sa fromRgb(), isValid()
+ \sa fromRgb(), fromRgba64(), isValid()
*/
QColor QColor::fromRgba(QRgb rgba)
@@ -1865,7 +1913,7 @@ QColor QColor::fromRgba(QRgb rgba)
All the values must be in the range 0-255.
- \sa toRgb(), fromRgbF(), isValid()
+ \sa toRgb(), fromRgba64(), fromRgbF(), isValid()
*/
QColor QColor::fromRgb(int r, int g, int b, int a)
{
@@ -1894,7 +1942,7 @@ QColor QColor::fromRgb(int r, int g, int b, int a)
All the values must be in the range 0.0-1.0.
- \sa fromRgb(), toRgb(), isValid()
+ \sa fromRgb(), fromRgba64(), toRgb(), isValid()
*/
QColor QColor::fromRgbF(qreal r, qreal g, qreal b, qreal a)
{
@@ -1916,6 +1964,38 @@ QColor QColor::fromRgbF(qreal r, qreal g, qreal b, qreal a)
return color;
}
+
+/*!
+ \since 5.6
+
+ Static convenience function that returns a QColor constructed from the RGBA64
+ color values, \a r (red), \a g (green), \a b (blue), and \a a
+ (alpha-channel, i.e. transparency).
+
+ \sa fromRgb(), fromRgbF(), toRgb(), isValid()
+*/
+QColor QColor::fromRgba64(ushort r, ushort g, ushort b, ushort a)
+{
+ QColor color;
+ color.setRgba64(qRgba64(r, g, b, a));
+ return color;
+}
+
+/*!
+ \since 5.6
+
+ Static convenience function that returns a QColor constructed from the
+ given QRgba64 value \a rgba64.
+
+ \sa fromRgb(), fromRgbF(), toRgb(), isValid()
+*/
+QColor QColor::fromRgba64(QRgba64 rgba64)
+{
+ QColor color;
+ color.setRgba64(rgba64);
+ return color;
+}
+
/*!
Static convenience function that returns a QColor constructed from the HSV
color values, \a h (hue), \a s (saturation), \a v (value), and \a a
@@ -2307,6 +2387,7 @@ QColor QColor::dark(int factor) const
return hsv.convertTo(cspec);
}
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
/*!
Assigns a copy of \a color to this color, and returns a reference to it.
*/
@@ -2316,6 +2397,7 @@ QColor &QColor::operator=(const QColor &color)
ct.argb = color.ct.argb;
return *this;
}
+#endif
/*! \overload
Assigns a copy of \a color and returns a reference to this color.
diff --git a/src/gui/painting/qcolor.h b/src/gui/painting/qcolor.h
index 06c218365b..b0192662cc 100644
--- a/src/gui/painting/qcolor.h
+++ b/src/gui/painting/qcolor.h
@@ -37,6 +37,7 @@
#include <QtGui/qrgb.h>
#include <QtCore/qnamespace.h>
#include <QtCore/qstringlist.h>
+#include <QtGui/qrgba64.h>
QT_BEGIN_NAMESPACE
@@ -63,11 +64,23 @@ public:
QColor(Qt::GlobalColor color);
QColor(int r, int g, int b, int a = 255);
QColor(QRgb rgb);
+ QColor(QRgba64 rgba64);
QColor(const QString& name);
QColor(const char *name);
- QColor(const QColor &color); // ### Qt 6: remove, the trivial one is fine.
QColor(Spec spec);
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+ QColor(const QColor &color); // ### Qt 6: remove all of these, the trivial ones are fine.
+# ifdef Q_COMPILER_RVALUE_REFS
+ QColor(QColor &&other) Q_DECL_NOTHROW : cspec(other.cspec), ct(other.ct) {}
+ QColor &operator=(QColor &&other) Q_DECL_NOTHROW
+ { cspec = other.cspec; ct = other.ct; return *this; }
+# endif
+ QColor &operator=(const QColor &);
+#endif // Qt < 6
+
+ QColor &operator=(Qt::GlobalColor color);
+
bool isValid() const;
// ### Qt 6: merge overloads
@@ -100,15 +113,18 @@ public:
void setGreenF(qreal green);
void setBlueF(qreal blue);
- void getRgb(int *r, int *g, int *b, int *a = 0) const;
+ void getRgb(int *r, int *g, int *b, int *a = Q_NULLPTR) const;
void setRgb(int r, int g, int b, int a = 255);
- void getRgbF(qreal *r, qreal *g, qreal *b, qreal *a = 0) const;
+ void getRgbF(qreal *r, qreal *g, qreal *b, qreal *a = Q_NULLPTR) const;
void setRgbF(qreal r, qreal g, qreal b, qreal a = 1.0);
QRgb rgba() const;
void setRgba(QRgb rgba);
+ QRgba64 rgba64() const;
+ void setRgba64(QRgba64 rgba);
+
QRgb rgb() const;
void setRgb(QRgb rgb);
@@ -124,10 +140,10 @@ public:
qreal hsvSaturationF() const;
qreal valueF() const;
- void getHsv(int *h, int *s, int *v, int *a = 0) const;
+ void getHsv(int *h, int *s, int *v, int *a = Q_NULLPTR) const;
void setHsv(int h, int s, int v, int a = 255);
- void getHsvF(qreal *h, qreal *s, qreal *v, qreal *a = 0) const;
+ void getHsvF(qreal *h, qreal *s, qreal *v, qreal *a = Q_NULLPTR) const;
void setHsvF(qreal h, qreal s, qreal v, qreal a = 1.0);
int cyan() const;
@@ -140,10 +156,10 @@ public:
qreal yellowF() const;
qreal blackF() const;
- void getCmyk(int *c, int *m, int *y, int *k, int *a = 0);
+ void getCmyk(int *c, int *m, int *y, int *k, int *a = Q_NULLPTR);
void setCmyk(int c, int m, int y, int k, int a = 255);
- void getCmykF(qreal *c, qreal *m, qreal *y, qreal *k, qreal *a = 0);
+ void getCmykF(qreal *c, qreal *m, qreal *y, qreal *k, qreal *a = Q_NULLPTR);
void setCmykF(qreal c, qreal m, qreal y, qreal k, qreal a = 1.0);
int hslHue() const; // 0 <= hue < 360
@@ -154,10 +170,10 @@ public:
qreal hslSaturationF() const;
qreal lightnessF() const;
- void getHsl(int *h, int *s, int *l, int *a = 0) const;
+ void getHsl(int *h, int *s, int *l, int *a = Q_NULLPTR) const;
void setHsl(int h, int s, int l, int a = 255);
- void getHslF(qreal *h, qreal *s, qreal *l, qreal *a = 0) const;
+ void getHslF(qreal *h, qreal *s, qreal *l, qreal *a = Q_NULLPTR) const;
void setHslF(qreal h, qreal s, qreal l, qreal a = 1.0);
QColor toRgb() const;
@@ -173,6 +189,9 @@ public:
static QColor fromRgb(int r, int g, int b, int a = 255);
static QColor fromRgbF(qreal r, qreal g, qreal b, qreal a = 1.0);
+ static QColor fromRgba64(ushort r, ushort g, ushort b, ushort a = USHRT_MAX);
+ static QColor fromRgba64(QRgba64 rgba);
+
static QColor fromHsv(int h, int s, int v, int a = 255);
static QColor fromHsvF(qreal h, qreal s, qreal v, qreal a = 1.0);
@@ -187,9 +206,6 @@ public:
QColor dark(int f = 200) const Q_REQUIRED_RESULT;
QColor darker(int f = 200) const Q_REQUIRED_RESULT;
- QColor &operator=(const QColor &);
- QColor &operator=(Qt::GlobalColor color);
-
bool operator==(const QColor &c) const;
bool operator!=(const QColor &c) const;
@@ -254,9 +270,11 @@ inline QColor::QColor(const char *aname)
inline QColor::QColor(const QString& aname)
{ setNamedColor(aname); }
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
inline QColor::QColor(const QColor &acolor)
: cspec(acolor.cspec)
{ ct.argb = acolor.ct.argb; }
+#endif
inline bool QColor::isValid() const
{ return cspec != Invalid; }
diff --git a/src/gui/painting/qcompositionfunctions.cpp b/src/gui/painting/qcompositionfunctions.cpp
new file mode 100644
index 0000000000..ba428a7938
--- /dev/null
+++ b/src/gui/painting/qcompositionfunctions.cpp
@@ -0,0 +1,2197 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <qglobal.h>
+#include <private/qdrawhelper_p.h>
+#include <private/qrgba64_p.h>
+
+QT_BEGIN_NAMESPACE
+
+# define PRELOAD_INIT(x)
+# define PRELOAD_INIT2(x,y)
+# define PRELOAD_COND(x)
+# define PRELOAD_COND2(x,y)
+
+/* The constant alpha factor describes an alpha factor that gets applied
+ to the result of the composition operation combining it with the destination.
+
+ The intent is that if const_alpha == 0. we get back dest, and if const_alpha == 1.
+ we get the unmodified operation
+
+ result = src op dest
+ dest = result * const_alpha + dest * (1. - const_alpha)
+
+ This means that in the comments below, the first line is the const_alpha==255 case, the
+ second line the general one.
+
+ In the lines below:
+ s == src, sa == alpha(src), sia = 1 - alpha(src)
+ d == dest, da == alpha(dest), dia = 1 - alpha(dest)
+ ca = const_alpha, cia = 1 - const_alpha
+
+ The methods exist in two variants. One where we have a constant source, the other
+ where the source is an array of pixels.
+*/
+
+/*
+ result = 0
+ d = d * cia
+*/
+#define comp_func_Clear_impl(dest, length, const_alpha)\
+{\
+ if (const_alpha == 255) {\
+ QT_MEMFILL_UINT(dest, length, 0);\
+ } else {\
+ int ialpha = 255 - const_alpha;\
+ PRELOAD_INIT(dest)\
+ for (int i = 0; i < length; ++i) {\
+ PRELOAD_COND(dest)\
+ dest[i] = BYTE_MUL(dest[i], ialpha);\
+ }\
+ }\
+}
+
+void QT_FASTCALL comp_func_solid_Clear(uint *dest, int length, uint, uint const_alpha)
+{
+ comp_func_Clear_impl(dest, length, const_alpha);
+}
+
+void QT_FASTCALL comp_func_solid_Clear_rgb64(QRgba64 *dest, int length, QRgba64, uint const_alpha)
+{
+ if (const_alpha == 255)
+ qt_memfill64((quint64*)dest, 0, length);
+ else {
+ int ialpha = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha255(dest[i], ialpha);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_Clear(uint *dest, const uint *, int length, uint const_alpha)
+{
+ comp_func_Clear_impl(dest, length, const_alpha);
+}
+
+void QT_FASTCALL comp_func_Clear_rgb64(QRgba64 *dest, const QRgba64 *, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ qt_memfill64((quint64*)dest, 0, length);
+ else {
+ int ialpha = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha255(dest[i], ialpha);
+ }
+ }
+}
+
+/*
+ result = s
+ dest = s * ca + d * cia
+*/
+void QT_FASTCALL comp_func_solid_Source(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ QT_MEMFILL_UINT(dest, length, color);
+ } else {
+ int ialpha = 255 - const_alpha;
+ color = BYTE_MUL(color, const_alpha);
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = color + BYTE_MUL(dest[i], ialpha);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Source_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ qt_memfill64((quint64*)dest, color, length);
+ else {
+ int ialpha = 255 - const_alpha;
+ color = multiplyAlpha255(color, const_alpha);
+ for (int i = 0; i < length; ++i) {
+ dest[i] = color + multiplyAlpha255(dest[i], ialpha);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_Source(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ ::memcpy(dest, src, length * sizeof(uint));
+ } else {
+ int ialpha = 255 - const_alpha;
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ dest[i] = INTERPOLATE_PIXEL_255(src[i], const_alpha, dest[i], ialpha);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_Source_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ ::memcpy(dest, src, length * sizeof(quint64));
+ else {
+ int ialpha = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = interpolate255(src[i], const_alpha, dest[i], ialpha);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Destination(uint *, int, uint, uint)
+{
+}
+
+void QT_FASTCALL comp_func_solid_Destination_rgb64(QRgba64 *, int, QRgba64, uint)
+{
+}
+
+void QT_FASTCALL comp_func_Destination(uint *, const uint *, int, uint)
+{
+}
+
+void QT_FASTCALL comp_func_Destination_rgb64(QRgba64 *, const QRgba64 *, int, uint)
+{
+}
+
+/*
+ result = s + d * sia
+ dest = (s + d * sia) * ca + d * cia
+ = s * ca + d * (sia * ca + cia)
+ = s * ca + d * (1 - sa*ca)
+*/
+void QT_FASTCALL comp_func_solid_SourceOver(uint *dest, int length, uint color, uint const_alpha)
+{
+ if ((const_alpha & qAlpha(color)) == 255) {
+ QT_MEMFILL_UINT(dest, length, color);
+ } else {
+ if (const_alpha != 255)
+ color = BYTE_MUL(color, const_alpha);
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = color + BYTE_MUL(dest[i], qAlpha(~color));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_solid_SourceOver_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha == 255 && color.isOpaque()) {
+ qt_memfill64((quint64*)dest, color, length);
+ } else {
+ if (const_alpha != 255)
+ color = multiplyAlpha255(color, const_alpha);
+ for (int i = 0; i < length; ++i) {
+ dest[i] = color + multiplyAlpha65535(dest[i], 65535 - color.alpha());
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceOver(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = src[i];
+ if (s >= 0xff000000)
+ dest[i] = s;
+ else if (s != 0)
+ dest[i] = s + BYTE_MUL(dest[i], qAlpha(~s));
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = BYTE_MUL(src[i], const_alpha);
+ dest[i] = s + BYTE_MUL(dest[i], qAlpha(~s));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceOver_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = src[i];
+ if (s.isOpaque())
+ dest[i] = s;
+ else if (!s.isTransparent())
+ dest[i] = s + multiplyAlpha65535(dest[i], 65535 - s.alpha());
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = multiplyAlpha255(src[i], const_alpha);
+ dest[i] = s + multiplyAlpha65535(dest[i], 65535 - s.alpha());
+ }
+ }
+}
+
+/*
+ result = d + s * dia
+ dest = (d + s * dia) * ca + d * cia
+ = d + s * dia * ca
+*/
+void QT_FASTCALL comp_func_solid_DestinationOver(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha != 255)
+ color = BYTE_MUL(color, const_alpha);
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ dest[i] = d + BYTE_MUL(color, qAlpha(~d));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_DestinationOver_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha != 255)
+ color = multiplyAlpha255(color, const_alpha);
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = d + multiplyAlpha65535(color, 65535 - d.alpha());
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationOver(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ dest[i] = d + BYTE_MUL(src[i], qAlpha(~d));
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = BYTE_MUL(src[i], const_alpha);
+ dest[i] = d + BYTE_MUL(s, qAlpha(~d));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationOver_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = d + multiplyAlpha65535(src[i], 65535 - d.alpha());
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ QRgba64 s = multiplyAlpha255(src[i], const_alpha);
+ dest[i] = d + multiplyAlpha65535(s, 65535 - d.alpha());
+ }
+ }
+}
+
+/*
+ result = s * da
+ dest = s * da * ca + d * cia
+*/
+void QT_FASTCALL comp_func_solid_SourceIn(uint *dest, int length, uint color, uint const_alpha)
+{
+ PRELOAD_INIT(dest)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = BYTE_MUL(color, qAlpha(dest[i]));
+ }
+ } else {
+ color = BYTE_MUL(color, const_alpha);
+ uint cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(d), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_solid_SourceIn_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(color, dest[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ color = multiplyAlpha65535(color, ca);
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(color, d.alpha(), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceIn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ dest[i] = BYTE_MUL(src[i], qAlpha(dest[i]));
+ }
+ } else {
+ uint cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = BYTE_MUL(src[i], const_alpha);
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceIn_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(src[i], dest[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ QRgba64 s = multiplyAlpha65535(src[i], ca);
+ dest[i] = interpolate65535(s, d.alpha(), d, cia);
+ }
+ }
+}
+
+/*
+ result = d * sa
+ dest = d * sa * ca + d * cia
+ = d * (sa * ca + cia)
+*/
+void QT_FASTCALL comp_func_solid_DestinationIn(uint *dest, int length, uint color, uint const_alpha)
+{
+ uint a = qAlpha(color);
+ if (const_alpha != 255) {
+ a = BYTE_MUL(a, const_alpha) + 255 - const_alpha;
+ }
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = BYTE_MUL(dest[i], a);
+ }
+}
+
+void QT_FASTCALL comp_func_solid_DestinationIn_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ uint a = color.alpha();
+ uint ca64k = const_alpha * 257;
+ if (const_alpha != 255)
+ a = qt_div_65535(a * ca64k) + 65535 - ca64k;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(dest[i], a);
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationIn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ dest[i] = BYTE_MUL(dest[i], qAlpha(src[i]));
+ }
+ } else {
+ int cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint a = BYTE_MUL(qAlpha(src[i]), const_alpha) + cia;
+ dest[i] = BYTE_MUL(dest[i], a);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationIn_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(dest[i], src[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ for (int i = 0; i < length; ++i) {
+ uint a = qt_div_65535(src[i].alpha() * ca) + cia;
+ dest[i] = multiplyAlpha65535(dest[i], a);
+ }
+ }
+}
+
+/*
+ result = s * dia
+ dest = s * dia * ca + d * cia
+*/
+
+void QT_FASTCALL comp_func_solid_SourceOut(uint *dest, int length, uint color, uint const_alpha)
+{
+ PRELOAD_INIT(dest)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = BYTE_MUL(color, qAlpha(~dest[i]));
+ }
+ } else {
+ color = BYTE_MUL(color, const_alpha);
+ int cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(~d), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_solid_SourceOut_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(color, 65535 - dest[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ color = multiplyAlpha65535(color, ca);
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(color, 65535 - d.alpha(), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceOut(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ dest[i] = BYTE_MUL(src[i], qAlpha(~dest[i]));
+ }
+ } else {
+ int cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = BYTE_MUL(src[i], const_alpha);
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, cia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceOut_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(src[i], 65535 - dest[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ QRgba64 s = multiplyAlpha65535(src[i], ca);
+ dest[i] = interpolate65535(s, 65535 - d.alpha(), d, cia);
+ }
+ }
+}
+
+/*
+ result = d * sia
+ dest = d * sia * ca + d * cia
+ = d * (sia * ca + cia)
+*/
+void QT_FASTCALL comp_func_solid_DestinationOut(uint *dest, int length, uint color, uint const_alpha)
+{
+ uint a = qAlpha(~color);
+ if (const_alpha != 255)
+ a = BYTE_MUL(a, const_alpha) + 255 - const_alpha;
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = BYTE_MUL(dest[i], a);
+ }
+}
+
+void QT_FASTCALL comp_func_solid_DestinationOut_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ uint a = 65535 - color.alpha();
+ uint ca64k = const_alpha * 257;
+ if (const_alpha != 255)
+ a = qt_div_65535(a * ca64k) + 65535 - ca64k;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(dest[i], a);
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationOut(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ dest[i] = BYTE_MUL(dest[i], qAlpha(~src[i]));
+ }
+ } else {
+ int cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint sia = BYTE_MUL(qAlpha(~src[i]), const_alpha) + cia;
+ dest[i] = BYTE_MUL(dest[i], sia);
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationOut_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = multiplyAlpha65535(dest[i], 65535 - src[i].alpha());
+ }
+ } else {
+ uint ca = const_alpha * 257;
+ uint cia = 65535 - ca;
+ for (int i = 0; i < length; ++i) {
+ uint a = qt_div_65535((65535 - src[i].alpha()) * ca) + cia;
+ dest[i] = multiplyAlpha65535(dest[i], a);
+ }
+ }
+}
+
+/*
+ result = s*da + d*sia
+ dest = s*da*ca + d*sia*ca + d *cia
+ = s*ca * da + d * (sia*ca + cia)
+ = s*ca * da + d * (1 - sa*ca)
+*/
+void QT_FASTCALL comp_func_solid_SourceAtop(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha != 255) {
+ color = BYTE_MUL(color, const_alpha);
+ }
+ uint sia = qAlpha(~color);
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(dest[i]), dest[i], sia);
+ }
+}
+
+void QT_FASTCALL comp_func_solid_SourceAtop_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha != 255)
+ color = multiplyAlpha255(color, const_alpha);
+ uint sia = 65535 - color.alpha();
+ for (int i = 0; i < length; ++i) {
+ dest[i] = interpolate65535(color, dest[i].alpha(), dest[i], sia);
+ }
+}
+
+void QT_FASTCALL comp_func_SourceAtop(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = src[i];
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, qAlpha(~s));
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = BYTE_MUL(src[i], const_alpha);
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, qAlpha(~s));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_SourceAtop_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = src[i];
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(s, d.alpha(), d, 65535 - s.alpha());
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = multiplyAlpha255(src[i], const_alpha);
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(s, d.alpha(), d, 65535 - s.alpha());
+ }
+ }
+}
+
+/*
+ result = d*sa + s*dia
+ dest = d*sa*ca + s*dia*ca + d *cia
+ = s*ca * dia + d * (sa*ca + cia)
+*/
+void QT_FASTCALL comp_func_solid_DestinationAtop(uint *dest, int length, uint color, uint const_alpha)
+{
+ uint a = qAlpha(color);
+ if (const_alpha != 255) {
+ color = BYTE_MUL(color, const_alpha);
+ a = qAlpha(color) + 255 - const_alpha;
+ }
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(d, a, color, qAlpha(~d));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_DestinationAtop_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ uint a = color.alpha();
+ if (const_alpha != 255) {
+ color = multiplyAlpha255(color, const_alpha);
+ a = color.alpha() + 65535 - (const_alpha * 257);
+ }
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(d, a, color, 65535 - d.alpha());
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationAtop(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = src[i];
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(d, qAlpha(s), s, qAlpha(~d));
+ }
+ } else {
+ int cia = 255 - const_alpha;
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint s = BYTE_MUL(src[i], const_alpha);
+ uint d = dest[i];
+ uint a = qAlpha(s) + cia;
+ dest[i] = INTERPOLATE_PIXEL_255(d, a, s, qAlpha(~d));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_DestinationAtop_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = src[i];
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(d, s.alpha(), s, 65535 - d.alpha());
+ }
+ } else {
+ int ca = const_alpha * 257;
+ int cia = 65535 - ca;
+ for (int i = 0; i < length; ++i) {
+ QRgba64 s = multiplyAlpha65535(src[i], ca);
+ QRgba64 d = dest[i];
+ uint a = s.alpha() + cia;
+ dest[i] = interpolate65535(d, a, s, 65535 - d.alpha());
+ }
+ }
+}
+
+/*
+ result = d*sia + s*dia
+ dest = d*sia*ca + s*dia*ca + d *cia
+ = s*ca * dia + d * (sia*ca + cia)
+ = s*ca * dia + d * (1 - sa*ca)
+*/
+void QT_FASTCALL comp_func_solid_XOR(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha != 255)
+ color = BYTE_MUL(color, const_alpha);
+ uint sia = qAlpha(~color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(~d), d, sia);
+ }
+}
+
+void QT_FASTCALL comp_func_solid_XOR_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha != 255)
+ color = multiplyAlpha255(color, const_alpha);
+ uint sia = 65535 - color.alpha();
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ dest[i] = interpolate65535(color, 65535 - d.alpha(), d, sia);
+ }
+}
+
+void QT_FASTCALL comp_func_XOR(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ PRELOAD_INIT2(dest, src)
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, qAlpha(~s));
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = BYTE_MUL(src[i], const_alpha);
+ dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, qAlpha(~s));
+ }
+ }
+}
+
+void QT_FASTCALL comp_func_XOR_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ QRgba64 s = src[i];
+ dest[i] = interpolate65535(s, 65535 - d.alpha(), d, 65535 - s.alpha());
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ QRgba64 s = multiplyAlpha255(src[i], const_alpha);
+ dest[i] = interpolate65535(s, 65535 - d.alpha(), d, 65535 - s.alpha());
+ }
+ }
+}
+
+struct QFullCoverage {
+ inline void store(uint *dest, const uint src) const
+ {
+ *dest = src;
+ }
+};
+
+struct QPartialCoverage {
+ inline QPartialCoverage(uint const_alpha)
+ : ca(const_alpha)
+ , ica(255 - const_alpha)
+ {
+ }
+
+ inline void store(uint *dest, const uint src) const
+ {
+ *dest = INTERPOLATE_PIXEL_255(src, ca, *dest, ica);
+ }
+
+private:
+ const uint ca;
+ const uint ica;
+};
+
+static inline int mix_alpha(int da, int sa)
+{
+ return 255 - ((255 - sa) * (255 - da) >> 8);
+}
+
+/*
+ Dca' = Sca.Da + Dca.Sa + Sca.(1 - Da) + Dca.(1 - Sa)
+ = Sca + Dca
+*/
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Plus_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ uint s = color;
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ d = comp_func_Plus_one_pixel(d, s);
+ coverage.store(&dest[i], d);
+ }
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Plus_impl_rgb64(QRgba64 *dest, int length, QRgba64 color, const T &coverage)
+{
+ QRgba64 s = color;
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = dest[i];
+ d = comp_func_Plus_one_pixel(d, s);
+ coverage.store(&dest[i], d);
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Plus(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Plus_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Plus_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+void QT_FASTCALL comp_func_solid_Plus_rgb64(QRgba64 *dest, int length, QRgba64 color, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = addWithSaturation(dest[i], color);
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = addWithSaturation(dest[i], color);
+ dest[i] = interpolate255(d, const_alpha, dest[i], 255 - const_alpha);
+ }
+ }
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Plus_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ d = comp_func_Plus_one_pixel(d, s);
+
+ coverage.store(&dest[i], d);
+ }
+}
+
+void QT_FASTCALL comp_func_Plus(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Plus_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Plus_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+void QT_FASTCALL comp_func_Plus_rgb64(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255) {
+ for (int i = 0; i < length; ++i) {
+ dest[i] = addWithSaturation(dest[i], src[i]);
+ }
+ } else {
+ for (int i = 0; i < length; ++i) {
+ QRgba64 d = addWithSaturation(dest[i], src[i]);
+ dest[i] = interpolate255(d, const_alpha, dest[i], 255 - const_alpha);
+ }
+ }
+}
+
+/*
+ Dca' = Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline int multiply_op(int dst, int src, int da, int sa)
+{
+ return qt_div_255(src * dst + src * (255 - da) + dst * (255 - sa));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Multiply_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) multiply_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Multiply(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Multiply_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Multiply_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Multiply_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) multiply_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Multiply(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Multiply_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Multiply_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ Dca' = (Sca.Da + Dca.Sa - Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa)
+ = Sca + Dca - Sca.Dca
+*/
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Screen_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) 255 - qt_div_255((255-a) * (255-b))
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Screen(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Screen_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Screen_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Screen_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) 255 - (((255-a) * (255-b)) >> 8)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Screen(uint *dest, const uint *src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Screen_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Screen_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ if 2.Dca < Da
+ Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise
+ Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline int overlay_op(int dst, int src, int da, int sa)
+{
+ const int temp = src * (255 - da) + dst * (255 - sa);
+ if (2 * dst < da)
+ return qt_div_255(2 * src * dst + temp);
+ else
+ return qt_div_255(sa * da - 2 * (da - dst) * (sa - src) + temp);
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Overlay_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) overlay_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Overlay(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Overlay_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Overlay_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Overlay_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) overlay_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Overlay(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Overlay_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Overlay_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ Dca' = min(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
+ Da' = Sa + Da - Sa.Da
+*/
+static inline int darken_op(int dst, int src, int da, int sa)
+{
+ return qt_div_255(qMin(src * da, dst * sa) + src * (255 - da) + dst * (255 - sa));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Darken_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) darken_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Darken(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Darken_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Darken_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Darken_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) darken_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Darken(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Darken_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Darken_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ Dca' = max(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
+ Da' = Sa + Da - Sa.Da
+*/
+static inline int lighten_op(int dst, int src, int da, int sa)
+{
+ return qt_div_255(qMax(src * da, dst * sa) + src * (255 - da) + dst * (255 - sa));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Lighten_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) lighten_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Lighten(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Lighten_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Lighten_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Lighten_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) lighten_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Lighten(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Lighten_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Lighten_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ if Sca.Da + Dca.Sa >= Sa.Da
+ Dca' = Sa.Da + Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise
+ Dca' = Dca.Sa/(1-Sca/Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline int color_dodge_op(int dst, int src, int da, int sa)
+{
+ const int sa_da = sa * da;
+ const int dst_sa = dst * sa;
+ const int src_da = src * da;
+
+ const int temp = src * (255 - da) + dst * (255 - sa);
+ if (src_da + dst_sa >= sa_da)
+ return qt_div_255(sa_da + temp);
+ else
+ return qt_div_255(255 * dst_sa / (255 - 255 * src / sa) + temp);
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_ColorDodge_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a,b) color_dodge_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_ColorDodge(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_ColorDodge_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_ColorDodge_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_ColorDodge_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) color_dodge_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_ColorDodge(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_ColorDodge_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_ColorDodge_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ if Sca.Da + Dca.Sa <= Sa.Da
+ Dca' = Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise
+ Dca' = Sa.(Sca.Da + Dca.Sa - Sa.Da)/Sca + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline int color_burn_op(int dst, int src, int da, int sa)
+{
+ const int src_da = src * da;
+ const int dst_sa = dst * sa;
+ const int sa_da = sa * da;
+
+ const int temp = src * (255 - da) + dst * (255 - sa);
+
+ if (src == 0 || src_da + dst_sa <= sa_da)
+ return qt_div_255(temp);
+ return qt_div_255(sa * (src_da + dst_sa - sa_da) / src + temp);
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_ColorBurn_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) color_burn_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_ColorBurn(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_ColorBurn_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_ColorBurn_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_ColorBurn_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) color_burn_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_ColorBurn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_ColorBurn_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_ColorBurn_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ if 2.Sca < Sa
+ Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise
+ Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline uint hardlight_op(int dst, int src, int da, int sa)
+{
+ const uint temp = src * (255 - da) + dst * (255 - sa);
+
+ if (2 * src < sa)
+ return qt_div_255(2 * src * dst + temp);
+ else
+ return qt_div_255(sa * da - 2 * (da - dst) * (sa - src) + temp);
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_HardLight_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) hardlight_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_HardLight(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_HardLight_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_HardLight_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_HardLight_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) hardlight_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_HardLight(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_HardLight_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_HardLight_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ if 2.Sca <= Sa
+ Dca' = Dca.(Sa + (2.Sca - Sa).(1 - Dca/Da)) + Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise if 2.Sca > Sa and 4.Dca <= Da
+ Dca' = Dca.Sa + Da.(2.Sca - Sa).(4.Dca/Da.(4.Dca/Da + 1).(Dca/Da - 1) + 7.Dca/Da) + Sca.(1 - Da) + Dca.(1 - Sa)
+ otherwise if 2.Sca > Sa and 4.Dca > Da
+ Dca' = Dca.Sa + Da.(2.Sca - Sa).((Dca/Da)^0.5 - Dca/Da) + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+static inline int soft_light_op(int dst, int src, int da, int sa)
+{
+ const int src2 = src << 1;
+ const int dst_np = da != 0 ? (255 * dst) / da : 0;
+ const int temp = (src * (255 - da) + dst * (255 - sa)) * 255;
+
+ if (src2 < sa)
+ return (dst * (sa * 255 + (src2 - sa) * (255 - dst_np)) + temp) / 65025;
+ else if (4 * dst <= da)
+ return (dst * sa * 255 + da * (src2 - sa) * ((((16 * dst_np - 12 * 255) * dst_np + 3 * 65025) * dst_np) / 65025) + temp) / 65025;
+ else {
+ return (dst * sa * 255 + da * (src2 - sa) * (int(qSqrt(qreal(dst_np * 255))) - dst_np) + temp) / 65025;
+ }
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_SoftLight_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) soft_light_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_SoftLight(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_SoftLight_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_SoftLight_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_SoftLight_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) soft_light_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_SoftLight(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_SoftLight_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_SoftLight_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ Dca' = abs(Dca.Sa - Sca.Da) + Sca.(1 - Da) + Dca.(1 - Sa)
+ = Sca + Dca - 2.min(Sca.Da, Dca.Sa)
+*/
+static inline int difference_op(int dst, int src, int da, int sa)
+{
+ return src + dst - qt_div_255(2 * qMin(src * da, dst * sa));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Difference_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) difference_op(a, b, da, sa)
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Difference(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Difference_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Difference_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Difference_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) difference_op(a, b, da, sa)
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Difference(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Difference_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Difference_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+/*
+ Dca' = (Sca.Da + Dca.Sa - 2.Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa)
+*/
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void QT_FASTCALL comp_func_solid_Exclusion_impl(uint *dest, int length, uint color, const T &coverage)
+{
+ int sa = qAlpha(color);
+ int sr = qRed(color);
+ int sg = qGreen(color);
+ int sb = qBlue(color);
+
+ PRELOAD_INIT(dest)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND(dest)
+ uint d = dest[i];
+ int da = qAlpha(d);
+
+#define OP(a, b) (a + b - qt_div_255(2*(a*b)))
+ int r = OP( qRed(d), sr);
+ int b = OP( qBlue(d), sb);
+ int g = OP(qGreen(d), sg);
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_solid_Exclusion(uint *dest, int length, uint color, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_solid_Exclusion_impl(dest, length, color, QFullCoverage());
+ else
+ comp_func_solid_Exclusion_impl(dest, length, color, QPartialCoverage(const_alpha));
+}
+
+template <typename T>
+Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Exclusion_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
+{
+ PRELOAD_INIT2(dest, src)
+ for (int i = 0; i < length; ++i) {
+ PRELOAD_COND2(dest, src)
+ uint d = dest[i];
+ uint s = src[i];
+
+ int da = qAlpha(d);
+ int sa = qAlpha(s);
+
+#define OP(a, b) (a + b - ((a*b) >> 7))
+ int r = OP( qRed(d), qRed(s));
+ int b = OP( qBlue(d), qBlue(s));
+ int g = OP(qGreen(d), qGreen(s));
+ int a = mix_alpha(da, sa);
+#undef OP
+
+ coverage.store(&dest[i], qRgba(r, g, b, a));
+ }
+}
+
+void QT_FASTCALL comp_func_Exclusion(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
+{
+ if (const_alpha == 255)
+ comp_func_Exclusion_impl(dest, src, length, QFullCoverage());
+ else
+ comp_func_Exclusion_impl(dest, src, length, QPartialCoverage(const_alpha));
+}
+
+void QT_FASTCALL rasterop_solid_SourceOrDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--)
+ *dest++ |= color;
+}
+
+void QT_FASTCALL rasterop_SourceOrDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--)
+ *dest++ |= *src++;
+}
+
+void QT_FASTCALL rasterop_solid_SourceAndDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color |= 0xff000000;
+ while (length--)
+ *dest++ &= color;
+}
+
+void QT_FASTCALL rasterop_SourceAndDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (*src & *dest) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_SourceXorDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color &= 0x00ffffff;
+ while (length--)
+ *dest++ ^= color;
+}
+
+void QT_FASTCALL rasterop_SourceXorDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (*src ^ *dest) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_NotSourceAndNotDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color = ~color;
+ while (length--) {
+ *dest = (color & ~(*dest)) | 0xff000000;
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_NotSourceAndNotDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (~(*src) & ~(*dest)) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_NotSourceOrNotDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color = ~color | 0xff000000;
+ while (length--) {
+ *dest = color | ~(*dest);
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_NotSourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = ~(*src) | ~(*dest) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_NotSourceXorDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color = ~color & 0x00ffffff;
+ while (length--) {
+ *dest = color ^ (*dest);
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_NotSourceXorDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = ((~(*src)) ^ (*dest)) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_NotSource(uint *dest, int length,
+ uint color, uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ qt_memfill(dest, ~color | 0xff000000, length);
+}
+
+void QT_FASTCALL rasterop_NotSource(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src,
+ int length, uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--)
+ *dest++ = ~(*src++) | 0xff000000;
+}
+
+void QT_FASTCALL rasterop_solid_NotSourceAndDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color = ~color | 0xff000000;
+ while (length--) {
+ *dest = color & *dest;
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_NotSourceAndDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (~(*src) & *dest) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_SourceAndNotDestination(uint *dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (color & ~(*dest)) | 0xff000000;
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_SourceAndNotDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (*src & ~(*dest)) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_NotSourceOrDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (~(*src) | *dest) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_NotSourceOrDestination(uint *Q_DECL_RESTRICT dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ color = ~color | 0xff000000;
+ while (length--)
+ *dest++ |= color;
+}
+
+void QT_FASTCALL rasterop_SourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (*src | ~(*dest)) | 0xff000000;
+ ++dest; ++src;
+ }
+}
+
+void QT_FASTCALL rasterop_solid_SourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(const_alpha);
+ while (length--) {
+ *dest = (color | ~(*dest)) | 0xff000000;
+ ++dest;
+ }
+}
+
+void QT_FASTCALL rasterop_ClearDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(src);
+ comp_func_solid_SourceOver (dest, length, 0xff000000, const_alpha);
+}
+
+void QT_FASTCALL rasterop_solid_ClearDestination(uint *Q_DECL_RESTRICT dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(color);
+ comp_func_solid_SourceOver (dest, length, 0xff000000, const_alpha);
+}
+
+void QT_FASTCALL rasterop_SetDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(src);
+ comp_func_solid_SourceOver (dest, length, 0xffffffff, const_alpha);
+}
+
+void QT_FASTCALL rasterop_solid_SetDestination(uint *Q_DECL_RESTRICT dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(color);
+ comp_func_solid_SourceOver (dest, length, 0xffffffff, const_alpha);
+}
+
+void QT_FASTCALL rasterop_NotDestination(uint *Q_DECL_RESTRICT dest,
+ const uint *Q_DECL_RESTRICT src,
+ int length,
+ uint const_alpha)
+{
+ Q_UNUSED(src);
+ rasterop_solid_SourceXorDestination (dest, length, 0x00ffffff, const_alpha);
+}
+
+void QT_FASTCALL rasterop_solid_NotDestination(uint *Q_DECL_RESTRICT dest,
+ int length,
+ uint color,
+ uint const_alpha)
+{
+ Q_UNUSED(color);
+ rasterop_solid_SourceXorDestination (dest, length, 0x00ffffff, const_alpha);
+}
+
+CompositionFunctionSolid qt_functionForModeSolid_C[] = {
+ comp_func_solid_SourceOver,
+ comp_func_solid_DestinationOver,
+ comp_func_solid_Clear,
+ comp_func_solid_Source,
+ comp_func_solid_Destination,
+ comp_func_solid_SourceIn,
+ comp_func_solid_DestinationIn,
+ comp_func_solid_SourceOut,
+ comp_func_solid_DestinationOut,
+ comp_func_solid_SourceAtop,
+ comp_func_solid_DestinationAtop,
+ comp_func_solid_XOR,
+ comp_func_solid_Plus,
+ comp_func_solid_Multiply,
+ comp_func_solid_Screen,
+ comp_func_solid_Overlay,
+ comp_func_solid_Darken,
+ comp_func_solid_Lighten,
+ comp_func_solid_ColorDodge,
+ comp_func_solid_ColorBurn,
+ comp_func_solid_HardLight,
+ comp_func_solid_SoftLight,
+ comp_func_solid_Difference,
+ comp_func_solid_Exclusion,
+ rasterop_solid_SourceOrDestination,
+ rasterop_solid_SourceAndDestination,
+ rasterop_solid_SourceXorDestination,
+ rasterop_solid_NotSourceAndNotDestination,
+ rasterop_solid_NotSourceOrNotDestination,
+ rasterop_solid_NotSourceXorDestination,
+ rasterop_solid_NotSource,
+ rasterop_solid_NotSourceAndDestination,
+ rasterop_solid_SourceAndNotDestination,
+ rasterop_solid_NotSourceOrDestination,
+ rasterop_solid_SourceOrNotDestination,
+ rasterop_solid_ClearDestination,
+ rasterop_solid_SetDestination,
+ rasterop_solid_NotDestination
+};
+
+CompositionFunctionSolid64 qt_functionForModeSolid64_C[] = {
+ comp_func_solid_SourceOver_rgb64,
+ comp_func_solid_DestinationOver_rgb64,
+ comp_func_solid_Clear_rgb64,
+ comp_func_solid_Source_rgb64,
+ comp_func_solid_Destination_rgb64,
+ comp_func_solid_SourceIn_rgb64,
+ comp_func_solid_DestinationIn_rgb64,
+ comp_func_solid_SourceOut_rgb64,
+ comp_func_solid_DestinationOut_rgb64,
+ comp_func_solid_SourceAtop_rgb64,
+ comp_func_solid_DestinationAtop_rgb64,
+ comp_func_solid_XOR_rgb64,
+ comp_func_solid_Plus_rgb64,
+ 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
+};
+
+CompositionFunction qt_functionForMode_C[] = {
+ comp_func_SourceOver,
+ comp_func_DestinationOver,
+ comp_func_Clear,
+ comp_func_Source,
+ comp_func_Destination,
+ comp_func_SourceIn,
+ comp_func_DestinationIn,
+ comp_func_SourceOut,
+ comp_func_DestinationOut,
+ comp_func_SourceAtop,
+ comp_func_DestinationAtop,
+ comp_func_XOR,
+ comp_func_Plus,
+ comp_func_Multiply,
+ comp_func_Screen,
+ comp_func_Overlay,
+ comp_func_Darken,
+ comp_func_Lighten,
+ comp_func_ColorDodge,
+ comp_func_ColorBurn,
+ comp_func_HardLight,
+ comp_func_SoftLight,
+ comp_func_Difference,
+ comp_func_Exclusion,
+ rasterop_SourceOrDestination,
+ rasterop_SourceAndDestination,
+ rasterop_SourceXorDestination,
+ rasterop_NotSourceAndNotDestination,
+ rasterop_NotSourceOrNotDestination,
+ rasterop_NotSourceXorDestination,
+ rasterop_NotSource,
+ rasterop_NotSourceAndDestination,
+ rasterop_SourceAndNotDestination,
+ rasterop_NotSourceOrDestination,
+ rasterop_SourceOrNotDestination,
+ rasterop_ClearDestination,
+ rasterop_SetDestination,
+ rasterop_NotDestination
+};
+
+CompositionFunction64 qt_functionForMode64_C[] = {
+ comp_func_SourceOver_rgb64,
+ comp_func_DestinationOver_rgb64,
+ comp_func_Clear_rgb64,
+ comp_func_Source_rgb64,
+ comp_func_Destination_rgb64,
+ comp_func_SourceIn_rgb64,
+ comp_func_DestinationIn_rgb64,
+ comp_func_SourceOut_rgb64,
+ comp_func_DestinationOut_rgb64,
+ comp_func_SourceAtop_rgb64,
+ comp_func_DestinationAtop_rgb64,
+ comp_func_XOR_rgb64,
+ comp_func_Plus_rgb64,
+ 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
+};
+
+QT_END_NAMESPACE
diff --git a/src/gui/painting/qcosmeticstroker.cpp b/src/gui/painting/qcosmeticstroker.cpp
index 8fb5f4fd3f..61d57ca3f8 100644
--- a/src/gui/painting/qcosmeticstroker.cpp
+++ b/src/gui/painting/qcosmeticstroker.cpp
@@ -33,6 +33,7 @@
#include "qcosmeticstroker_p.h"
#include "private/qpainterpath_p.h"
+#include "private/qrgba64_p.h"
#include <qdebug.h>
QT_BEGIN_NAMESPACE
@@ -280,7 +281,7 @@ void QCosmeticStroker::setup()
drawCaps = state->lastPen.capStyle() != Qt::FlatCap;
if (strokeSelection & FastDraw) {
- color = INTERPOLATE_PIXEL_256(state->penData.solid.color, opacity, 0, 0);
+ color = multiplyAlpha256(state->penData.solid.color, opacity).toArgb32();
QRasterBuffer *buffer = state->penData.rasterBuffer;
pixels = (uint *)buffer->buffer();
ppl = buffer->bytesPerLine()>>2;
diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp
index d74b48a3ca..0cf7e20605 100644
--- a/src/gui/painting/qdrawhelper.cpp
+++ b/src/gui/painting/qdrawhelper.cpp
@@ -51,6 +51,7 @@
#include <private/qdrawhelper_mips_dsp_p.h>
#endif
#include <private/qguiapplication_p.h>
+#include <private/qrgba64_p.h>
#include <qmath.h>
QT_BEGIN_NAMESPACE
@@ -184,6 +185,36 @@ static const uint *QT_FASTCALL convertToRGB32(uint *buffer, const uint *src, int
}
template<QImage::Format Format>
+static const QRgba64 *QT_FASTCALL convertToRGB64(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+ Q_CONSTEXPR uint redMask = ((1 << redWidth<Format>()) - 1);
+ Q_CONSTEXPR uint greenMask = ((1 << greenWidth<Format>()) - 1);
+ Q_CONSTEXPR uint blueMask = ((1 << blueWidth<Format>()) - 1);
+
+ Q_CONSTEXPR uchar redLeftShift = 8 - redWidth<Format>();
+ Q_CONSTEXPR uchar greenLeftShift = 8 - greenWidth<Format>();
+ Q_CONSTEXPR uchar blueLeftShift = 8 - blueWidth<Format>();
+
+ Q_CONSTEXPR uchar redRightShift = 2 * redWidth<Format>() - 8;
+ Q_CONSTEXPR uchar greenRightShift = 2 * greenWidth<Format>() - 8;
+ Q_CONSTEXPR uchar blueRightShift = 2 * blueWidth<Format>() - 8;
+
+ for (int i = 0; i < count; ++i) {
+ uint red = (src[i] >> redShift<Format>()) & redMask;
+ uint green = (src[i] >> greenShift<Format>()) & greenMask;
+ uint blue = (src[i] >> blueShift<Format>()) & blueMask;
+
+ red = ((red << redLeftShift) | (red >> redRightShift)) << 16;
+ green = ((green << greenLeftShift) | (green >> greenRightShift)) << 8;
+ blue = (blue << blueLeftShift) | (blue >> blueRightShift);
+ buffer[i] = QRgba64::fromRgba(red, green, blue, 255);
+ }
+
+ return buffer;
+}
+
+template<QImage::Format Format>
static const uint *QT_FASTCALL convertARGBPMToARGB32PM(uint *buffer, const uint *src, int count,
const QPixelLayout *, const QRgb *)
{
@@ -219,6 +250,41 @@ static const uint *QT_FASTCALL convertARGBPMToARGB32PM(uint *buffer, const uint
}
template<QImage::Format Format>
+static const QRgba64 *QT_FASTCALL convertARGBPMToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+ Q_CONSTEXPR uint alphaMask = ((1 << alphaWidth<Format>()) - 1);
+ Q_CONSTEXPR uint redMask = ((1 << redWidth<Format>()) - 1);
+ Q_CONSTEXPR uint greenMask = ((1 << greenWidth<Format>()) - 1);
+ Q_CONSTEXPR uint blueMask = ((1 << blueWidth<Format>()) - 1);
+
+ Q_CONSTEXPR uchar alphaLeftShift = 8 - alphaWidth<Format>();
+ Q_CONSTEXPR uchar redLeftShift = 8 - redWidth<Format>();
+ Q_CONSTEXPR uchar greenLeftShift = 8 - greenWidth<Format>();
+ Q_CONSTEXPR uchar blueLeftShift = 8 - blueWidth<Format>();
+
+ Q_CONSTEXPR uchar alphaRightShift = 2 * alphaWidth<Format>() - 8;
+ Q_CONSTEXPR uchar redRightShift = 2 * redWidth<Format>() - 8;
+ Q_CONSTEXPR uchar greenRightShift = 2 * greenWidth<Format>() - 8;
+ Q_CONSTEXPR uchar blueRightShift = 2 * blueWidth<Format>() - 8;
+
+ for (int i = 0; i < count; ++i) {
+ uint alpha = (src[i] >> alphaShift<Format>()) & alphaMask;
+ uint red = (src[i] >> redShift<Format>()) & redMask;
+ uint green = (src[i] >> greenShift<Format>()) & greenMask;
+ uint blue = (src[i] >> blueShift<Format>()) & blueMask;
+
+ alpha = (alpha << alphaLeftShift) | (alpha >> alphaRightShift);
+ red = qMin(alpha, (red << redLeftShift) | (red >> redRightShift));
+ green = qMin(alpha, (green << greenLeftShift) | (green >> greenRightShift));
+ blue = qMin(alpha, (blue << blueLeftShift) | (blue >> blueRightShift));
+ buffer[i] = QRgba64::fromRgba(red, green, blue, alpha);
+ }
+
+ return buffer;
+}
+
+template<QImage::Format Format>
static const uint *QT_FASTCALL convertRGBFromARGB32PM(uint *buffer, const uint *src, int count,
const QPixelLayout *, const QRgb *)
{
@@ -320,7 +386,8 @@ template<QImage::Format Format> Q_DECL_CONSTEXPR static inline QPixelLayout pixe
false, bitsPerPixel<Format>(),
convertToRGB32<Format>,
convertRGBFromARGB32PM<Format>,
- convertRGBFromRGB32<Format>
+ convertRGBFromRGB32<Format>,
+ convertToRGB64<Format>
};
}
@@ -334,7 +401,8 @@ template<QImage::Format Format> Q_DECL_CONSTEXPR static inline QPixelLayout pixe
true, bitsPerPixel<Format>(),
convertARGBPMToARGB32PM<Format>,
convertARGBPMFromARGB32PM<Format>,
- convertARGBPMFromRGB32<Format>
+ convertARGBPMFromRGB32<Format>,
+ convertARGBPMToARGB64PM<Format>
};
}
@@ -349,6 +417,14 @@ static const uint *QT_FASTCALL convertIndexedToARGB32PM(uint *buffer, const uint
return buffer;
}
+static const QRgba64 *QT_FASTCALL convertIndexedToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *clut)
+{
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(clut[src[i]]).premultiplied();
+ return buffer;
+}
+
static const uint *QT_FASTCALL convertPassThrough(uint *, const uint *src, int,
const QPixelLayout *, const QRgb *)
{
@@ -391,6 +467,22 @@ static const uint *QT_FASTCALL convertGrayscale8ToRGB32(uint *buffer, const uint
return buffer;
}
+static const QRgba64 *QT_FASTCALL convertAlpha8ToRGB64(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromRgba(0, 0, 0, src[i]);
+ return buffer;
+}
+
+static const QRgba64 *QT_FASTCALL convertGrayscale8ToRGB64(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromRgba(src[i], src[i], src[i], 255);
+ return buffer;
+}
+
static const uint *QT_FASTCALL convertARGB32FromARGB32PM(uint *buffer, const uint *src, int count,
const QPixelLayout *, const QRgb *)
{
@@ -407,6 +499,111 @@ static const uint *QT_FASTCALL convertRGBA8888PMFromARGB32PM(uint *buffer, const
return buffer;
}
+#ifdef __SSE2__
+template<bool RGBA, bool maskAlpha>
+static inline void qConvertARGB32PMToARGB64PM_sse2(QRgba64 *buffer, const uint *src, int count)
+{
+ const __m128i amask = _mm_set1_epi32(0xff000000);
+ int i = 0;
+ if (((uintptr_t)buffer & 0xf) && count > 0) {
+ uint s = *src++;
+ if (RGBA)
+ s = RGBA2ARGB(s);
+ *buffer++ = QRgba64::fromArgb32(s);
+ i++;
+ }
+ for (; i < count-3; i += 4) {
+ __m128i vs = _mm_loadu_si128((const __m128i*)src);
+ if (maskAlpha)
+ vs = _mm_or_si128(vs, amask);
+ src += 4;
+ __m128i v1 = _mm_unpacklo_epi8(vs, vs);
+ __m128i v2 = _mm_unpackhi_epi8(vs, vs);
+ if (!RGBA) {
+ v1 = _mm_shufflelo_epi16(v1, _MM_SHUFFLE(3, 0, 1, 2));
+ v2 = _mm_shufflelo_epi16(v2, _MM_SHUFFLE(3, 0, 1, 2));
+ v1 = _mm_shufflehi_epi16(v1, _MM_SHUFFLE(3, 0, 1, 2));
+ v2 = _mm_shufflehi_epi16(v2, _MM_SHUFFLE(3, 0, 1, 2));
+ }
+ _mm_store_si128((__m128i*)(buffer), v1);
+ buffer += 2;
+ _mm_store_si128((__m128i*)(buffer), v2);
+ buffer += 2;
+ }
+
+ for (; i < count; ++i) {
+ uint s = *src++;
+ if (RGBA)
+ s = RGBA2ARGB(s);
+ *buffer++ = QRgba64::fromArgb32(s);
+ }
+}
+#endif
+
+static const QRgba64 *QT_FASTCALL convertRGB32ToRGB64(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertARGB32PMToARGB64PM_sse2<false, true>(buffer, src, count);
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(0xff000000 | src[i]);
+#endif
+ return buffer;
+}
+
+static const QRgba64 *QT_FASTCALL convertARGB32ToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertARGB32PMToARGB64PM_sse2<false, false>(buffer, src, count);
+ for (int i = 0; i < count; ++i)
+ buffer[i] = buffer[i].premultiplied();
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(src[i]).premultiplied();
+#endif
+ return buffer;
+}
+
+static const QRgba64 *QT_FASTCALL convertARGB32PMToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertARGB32PMToARGB64PM_sse2<false, false>(buffer, src, count);
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(src[i]);
+#endif
+ return buffer;
+}
+
+static const QRgba64 *QT_FASTCALL convertRGBA8888ToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertARGB32PMToARGB64PM_sse2<true, false>(buffer, src, count);
+ for (int i = 0; i < count; ++i)
+ buffer[i] = buffer[i].premultiplied();
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(RGBA2ARGB(src[i])).premultiplied();
+#endif
+ return buffer;
+}
+
+static const QRgba64 *QT_FASTCALL convertRGBA8888PMToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertARGB32PMToARGB64PM_sse2<true, false>(buffer, src, count);
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = QRgba64::fromArgb32(RGBA2ARGB(src[i]));
+#endif
+ return buffer;
+}
+
static const uint *QT_FASTCALL convertRGBA8888FromARGB32PM(uint *buffer, const uint *src, int count,
const QPixelLayout *, const QRgb *)
{
@@ -440,6 +637,60 @@ static const uint *QT_FASTCALL convertA2RGB30PMToARGB32PM(uint *buffer, const ui
return buffer;
}
+#ifdef __SSE2__
+template<QtPixelOrder PixelOrder>
+static inline void qConvertA2RGB30PMToARGB64PM_sse2(QRgba64 *buffer, const uint *src, int count)
+{
+ const __m128i rmask = _mm_set1_epi32(0x3ff00000);
+ const __m128i gmask = _mm_set1_epi32(0x000ffc00);
+ const __m128i bmask = _mm_set1_epi32(0x000003ff);
+ const __m128i afactor = _mm_set1_epi16(0x5555);
+ int i = 0;
+ if (((uintptr_t)buffer & 0xf) && count > 0) {
+ *buffer++ = qConvertA2rgb30ToRgb64<PixelOrder>(*src++);
+ i++;
+ }
+ for (; i < count-3; i += 4) {
+ __m128i vs = _mm_loadu_si128((const __m128i*)src);
+ src += 4;
+ __m128i va = _mm_srli_epi32(vs, 30);
+ __m128i vr = _mm_and_si128(vs, rmask);
+ __m128i vb = _mm_and_si128(vs, bmask);
+ __m128i vg = _mm_and_si128(vs, gmask);
+ va = _mm_mullo_epi16(va, afactor);
+ vr = _mm_or_si128(_mm_srli_epi32(vr, 14), _mm_srli_epi32(vr, 24));
+ vg = _mm_or_si128(_mm_srli_epi32(vg, 4), _mm_srli_epi32(vg, 14));
+ vb = _mm_or_si128(_mm_slli_epi32(vb, 6), _mm_srli_epi32(vb, 4));
+ __m128i vrb;
+ if (PixelOrder == PixelOrderRGB)
+ vrb = _mm_or_si128(vr, _mm_slli_si128(vb, 2));
+ else
+ vrb = _mm_or_si128(vb, _mm_slli_si128(vr, 2));
+ __m128i vga = _mm_or_si128(vg, _mm_slli_si128(va, 2));
+ _mm_store_si128((__m128i*)(buffer), _mm_unpacklo_epi16(vrb, vga));
+ buffer += 2;
+ _mm_store_si128((__m128i*)(buffer), _mm_unpackhi_epi16(vrb, vga));
+ buffer += 2;
+ }
+
+ for (; i < count; ++i)
+ *buffer++ = qConvertA2rgb30ToRgb64<PixelOrder>(*src++);
+}
+#endif
+
+template<QtPixelOrder PixelOrder>
+static const QRgba64 *QT_FASTCALL convertA2RGB30PMToARGB64PM(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *, const QRgb *)
+{
+#ifdef __SSE2__
+ qConvertA2RGB30PMToARGB64PM_sse2<PixelOrder>(buffer, src, count);
+#else
+ for (int i = 0; i < count; ++i)
+ buffer[i] = qConvertA2rgb30ToRgb64<PixelOrder>(src[i]);
+#endif
+ return buffer;
+}
+
template<QtPixelOrder PixelOrder>
static const uint *QT_FASTCALL convertA2RGB30PMFromARGB32PM(uint *buffer, const uint *src, int count,
const QPixelLayout *, const QRgb *)
@@ -601,15 +852,15 @@ inline void QT_FASTCALL storePixels<QPixelLayout::BPP32>(uchar *dest, const uint
// convertFromArgb32() assumes that no color channel is more than 8 bits.
// QImage::rgbSwapped() assumes that the red and blue color channels have the same number of bits.
QPixelLayout qPixelLayouts[QImage::NImageFormats] = {
- { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPPNone, 0, 0, 0 }, // Format_Invalid
- { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP1MSB, convertIndexedToARGB32PM, 0, 0 }, // Format_Mono
- { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP1LSB, convertIndexedToARGB32PM, 0, 0 }, // Format_MonoLSB
- { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP8, convertIndexedToARGB32PM, 0, 0 }, // Format_Indexed8
+ { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPPNone, 0, 0, 0, 0 }, // Format_Invalid
+ { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP1MSB, convertIndexedToARGB32PM, 0, 0, convertIndexedToARGB64PM }, // Format_Mono
+ { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP1LSB, convertIndexedToARGB32PM, 0, 0, convertIndexedToARGB64PM }, // Format_MonoLSB
+ { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP8, convertIndexedToARGB32PM, 0, 0, convertIndexedToARGB64PM }, // Format_Indexed8
// Technically using convertPassThrough to convert from ARGB32PM to RGB32 is wrong,
// but everywhere this generic conversion would be wrong is currently overloaded.
- { 8, 16, 8, 8, 8, 0, 0, 0, false, QPixelLayout::BPP32, convertPassThrough, convertPassThrough, convertPassThrough }, // Format_RGB32
- { 8, 16, 8, 8, 8, 0, 8, 24, false, QPixelLayout::BPP32, convertARGB32ToARGB32PM, convertARGB32FromARGB32PM, convertPassThrough }, // Format_ARGB32
- { 8, 16, 8, 8, 8, 0, 8, 24, true, QPixelLayout::BPP32, convertPassThrough, convertPassThrough, convertPassThrough }, // Format_ARGB32_Premultiplied
+ { 8, 16, 8, 8, 8, 0, 0, 0, false, QPixelLayout::BPP32, convertPassThrough, convertPassThrough, convertPassThrough, convertRGB32ToRGB64 }, // Format_RGB32
+ { 8, 16, 8, 8, 8, 0, 8, 24, false, QPixelLayout::BPP32, convertARGB32ToARGB32PM, convertARGB32FromARGB32PM, convertPassThrough, convertARGB32ToARGB64PM }, // Format_ARGB32
+ { 8, 16, 8, 8, 8, 0, 8, 24, true, QPixelLayout::BPP32, convertPassThrough, convertPassThrough, convertPassThrough, convertARGB32PMToARGB64PM }, // Format_ARGB32_Premultiplied
#ifdef Q_COMPILER_CONSTEXPR
pixelLayoutRGB<QImage::Format_RGB16>(),
pixelLayoutARGBPM<QImage::Format_ARGB8565_Premultiplied>(),
@@ -624,55 +875,73 @@ QPixelLayout qPixelLayouts[QImage::NImageFormats] = {
{ 5, 11, 6, 5, 5, 0, 0, 0, false, QPixelLayout::BPP16,
convertToRGB32<QImage::Format_RGB16>,
convertRGBFromARGB32PM<QImage::Format_RGB16>,
- convertRGBFromRGB32<QImage::Format_RGB16>},
+ convertRGBFromRGB32<QImage::Format_RGB16>,
+ convertToRGB64<QImage::Format_RGB16>,
+ },
{ 5, 19, 6, 13, 5, 8, 8, 0, true, QPixelLayout::BPP24,
convertARGBPMToARGB32PM<QImage::Format_ARGB8565_Premultiplied>,
convertARGBPMFromARGB32PM<QImage::Format_ARGB8565_Premultiplied>,
- convertARGBPMFromRGB32<QImage::Format_ARGB8565_Premultiplied>},
+ convertARGBPMFromRGB32<QImage::Format_ARGB8565_Premultiplied>,
+ convertARGBPMToARGB64PM<QImage::Format_ARGB8565_Premultiplied>,
+ },
{ 6, 12, 6, 6, 6, 0, 0, 0, false, QPixelLayout::BPP24,
convertToRGB32<QImage::Format_RGB666>,
convertRGBFromARGB32PM<QImage::Format_RGB666>,
- convertRGBFromRGB32<QImage::Format_RGB666>},
+ convertRGBFromRGB32<QImage::Format_RGB666>,
+ convertToRGB64<QImage::Format_RGB666>,
+ },
{ 6, 12, 6, 6, 6, 0, 6, 18, true, QPixelLayout::BPP24,
convertARGBPMToARGB32PM<QImage::Format_ARGB6666_Premultiplied>,
convertARGBPMFromARGB32PM<QImage::Format_ARGB6666_Premultiplied>,
- convertARGBPMFromRGB32<QImage::Format_ARGB6666_Premultiplied>},
+ convertARGBPMFromRGB32<QImage::Format_ARGB6666_Premultiplied>,
+ convertARGBPMToARGB64PM<QImage::Format_ARGB6666_Premultiplied>,
+ },
{ 5, 10, 5, 5, 5, 0, 0, 0, false, QPixelLayout::BPP16,
convertToRGB32<QImage::Format_RGB555>,
convertRGBFromARGB32PM<QImage::Format_RGB555>,
- convertRGBFromRGB32<QImage::Format_RGB555> },
+ convertRGBFromRGB32<QImage::Format_RGB555>,
+ convertToRGB64<QImage::Format_RGB555>,
+ },
{ 5, 18, 5, 13, 5, 8, 8, 0, true, QPixelLayout::BPP24,
convertARGBPMToARGB32PM<QImage::Format_ARGB8555_Premultiplied>,
convertARGBPMFromARGB32PM<QImage::Format_ARGB8555_Premultiplied>,
- convertARGBPMFromRGB32<QImage::Format_ARGB8555_Premultiplied>},
+ convertARGBPMFromRGB32<QImage::Format_ARGB8555_Premultiplied>,
+ convertARGBPMToARGB64PM<QImage::Format_ARGB8555_Premultiplied>,
+ },
{ 8, 16, 8, 8, 8, 0, 0, 0, false, QPixelLayout::BPP24,
convertToRGB32<QImage::Format_RGB888>,
convertRGBFromARGB32PM<QImage::Format_RGB888>,
- convertRGBFromRGB32<QImage::Format_RGB888>},
+ convertRGBFromRGB32<QImage::Format_RGB888>,
+ convertToRGB64<QImage::Format_RGB888>,
+ },
{ 4, 8, 4, 4, 4, 0, 0, 0, false, QPixelLayout::BPP16,
convertToRGB32<QImage::Format_RGB444>,
convertRGBFromARGB32PM<QImage::Format_RGB444>,
- convertRGBFromRGB32<QImage::Format_RGB444>},
+ convertRGBFromRGB32<QImage::Format_RGB444>,
+ convertToRGB64<QImage::Format_RGB444>,
+ },
{ 4, 8, 4, 4, 4, 0, 4, 12, true, QPixelLayout::BPP16,
convertARGBPMToARGB32PM<QImage::Format_ARGB4444_Premultiplied>,
convertARGBPMFromARGB32PM<QImage::Format_ARGB4444_Premultiplied>,
- convertARGBPMFromRGB32<QImage::Format_ARGB4444_Premultiplied>},
+ convertARGBPMFromRGB32<QImage::Format_ARGB4444_Premultiplied>,
+ convertARGBPMToARGB64PM<QImage::Format_ARGB4444_Premultiplied>,
+ },
#endif
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
- { 8, 24, 8, 16, 8, 8, 0, 0, false, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBXFromARGB32PM, convertRGBXFromRGB32 }, // Format_RGBX8888
- { 8, 24, 8, 16, 8, 8, 8, 0, false, QPixelLayout::BPP32, convertRGBA8888ToARGB32PM, convertRGBA8888FromARGB32PM, convertRGBXFromRGB32 }, // Format_RGBA8888
- { 8, 24, 8, 16, 8, 8, 8, 0, true, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBA8888PMFromARGB32PM, convertRGBXFromRGB32}, // Format_RGBA8888_Premultiplied
+ { 8, 24, 8, 16, 8, 8, 0, 0, false, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBXFromARGB32PM, convertRGBXFromRGB32, convertRGBA8888PMToARGB64PM }, // Format_RGBX8888
+ { 8, 24, 8, 16, 8, 8, 8, 0, false, QPixelLayout::BPP32, convertRGBA8888ToARGB32PM, convertRGBA8888FromARGB32PM, convertRGBXFromRGB32, convertRGBA8888ToARGB64PM }, // Format_RGBA8888
+ { 8, 24, 8, 16, 8, 8, 8, 0, true, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBA8888PMFromARGB32PM, convertRGBXFromRGB32, convertRGBA8888PMToARGB64PM}, // Format_RGBA8888_Premultiplied
#else
- { 8, 0, 8, 8, 8, 16, 0, 24, false, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBXFromARGB32PM, convertRGBXFromRGB32 }, // Format_RGBX8888
- { 8, 0, 8, 8, 8, 16, 8, 24, false, QPixelLayout::BPP32, convertRGBA8888ToARGB32PM, convertRGBA8888FromARGB32PM, convertRGBXFromRGB32 }, // Format_RGBA8888 (ABGR32)
- { 8, 0, 8, 8, 8, 16, 8, 24, true, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBA8888PMFromARGB32PM, convertRGBXFromRGB32 }, // Format_RGBA8888_Premultiplied
+ { 8, 0, 8, 8, 8, 16, 0, 24, false, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBXFromARGB32PM, convertRGBXFromRGB32, convertRGBA8888PMToARGB64PM }, // Format_RGBX8888
+ { 8, 0, 8, 8, 8, 16, 8, 24, false, QPixelLayout::BPP32, convertRGBA8888ToARGB32PM, convertRGBA8888FromARGB32PM, convertRGBXFromRGB32, convertRGBA8888ToARGB64PM }, // Format_RGBA8888 (ABGR32)
+ { 8, 0, 8, 8, 8, 16, 8, 24, true, QPixelLayout::BPP32, convertRGBA8888PMToARGB32PM, convertRGBA8888PMFromARGB32PM, convertRGBXFromRGB32, convertRGBA8888PMToARGB64PM }, // Format_RGBA8888_Premultiplied
#endif
- { 10, 20, 10, 10, 10, 0, 0, 30, false, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderBGR>, convertRGB30FromARGB32PM<PixelOrderBGR>, convertRGB30FromRGB32<PixelOrderBGR> }, // Format_BGR30
- { 10, 20, 10, 10, 10, 0, 2, 30, true, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderBGR>, convertA2RGB30PMFromARGB32PM<PixelOrderBGR>, convertRGB30FromRGB32<PixelOrderBGR> }, // Format_A2BGR30_Premultiplied
- { 10, 0, 10, 10, 10, 20, 0, 30, false, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderRGB>, convertRGB30FromARGB32PM<PixelOrderRGB>, convertRGB30FromRGB32<PixelOrderRGB> }, // Format_RGB30
- { 10, 0, 10, 10, 10, 20, 2, 30, true, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderRGB>, convertA2RGB30PMFromARGB32PM<PixelOrderRGB>, convertRGB30FromRGB32<PixelOrderRGB> }, // Format_A2RGB30_Premultiplied
- { 0, 0, 0, 0, 0, 0, 8, 0, false, QPixelLayout::BPP8, convertAlpha8ToRGB32, convertAlpha8FromARGB32PM, 0 }, // Format_Alpha8
- { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP8, convertGrayscale8ToRGB32, convertGrayscale8FromARGB32PM, convertGrayscale8FromRGB32 } // Format_Grayscale8
+ { 10, 20, 10, 10, 10, 0, 0, 30, false, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderBGR>, convertRGB30FromARGB32PM<PixelOrderBGR>, convertRGB30FromRGB32<PixelOrderBGR>, convertA2RGB30PMToARGB64PM<PixelOrderBGR> }, // Format_BGR30
+ { 10, 20, 10, 10, 10, 0, 2, 30, true, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderBGR>, convertA2RGB30PMFromARGB32PM<PixelOrderBGR>, convertRGB30FromRGB32<PixelOrderBGR>, convertA2RGB30PMToARGB64PM<PixelOrderBGR> }, // Format_A2BGR30_Premultiplied
+ { 10, 0, 10, 10, 10, 20, 0, 30, false, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderRGB>, convertRGB30FromARGB32PM<PixelOrderRGB>, convertRGB30FromRGB32<PixelOrderRGB>, convertA2RGB30PMToARGB64PM<PixelOrderRGB> }, // Format_RGB30
+ { 10, 0, 10, 10, 10, 20, 2, 30, true, QPixelLayout::BPP32, convertA2RGB30PMToARGB32PM<PixelOrderRGB>, convertA2RGB30PMFromARGB32PM<PixelOrderRGB>, convertRGB30FromRGB32<PixelOrderRGB>, convertA2RGB30PMToARGB64PM<PixelOrderRGB> }, // Format_A2RGB30_Premultiplied
+ { 0, 0, 0, 0, 0, 0, 8, 0, false, QPixelLayout::BPP8, convertAlpha8ToRGB32, convertAlpha8FromARGB32PM, 0, convertAlpha8ToRGB64 }, // Format_Alpha8
+ { 0, 0, 0, 0, 0, 0, 0, 0, false, QPixelLayout::BPP8, convertGrayscale8ToRGB32, convertGrayscale8FromARGB32PM, convertGrayscale8FromRGB32, convertGrayscale8ToRGB64 } // Format_Grayscale8
};
const FetchPixelsFunc qFetchPixels[QPixelLayout::BPPCount] = {
@@ -758,6 +1027,20 @@ static uint *QT_FASTCALL destFetch(uint *buffer, QRasterBuffer *rasterBuffer, in
return const_cast<uint *>(layout->convertToARGB32PM(buffer, ptr, length, layout, 0));
}
+static QRgba64 *QT_FASTCALL destFetch64(QRgba64 *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length)
+{
+ const QPixelLayout *layout = &qPixelLayouts[rasterBuffer->format];
+ uint buffer32[buffer_size];
+ const uint *ptr = qFetchPixels[layout->bpp](buffer32, rasterBuffer->scanLine(y), x, length);
+ return const_cast<QRgba64 *>(layout->convertToARGB64PM(buffer, ptr, length, layout, 0));
+}
+
+static QRgba64 *QT_FASTCALL destFetch64uint32(QRgba64 *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length)
+{
+ const QPixelLayout *layout = &qPixelLayouts[rasterBuffer->format];
+ const uint *src = ((const uint *)rasterBuffer->scanLine(y)) + x;
+ return const_cast<QRgba64 *>(layout->convertToARGB64PM(buffer, src, length, layout, 0));
+}
static DestFetchProc destFetchProc[QImage::NImageFormats] =
{
@@ -788,6 +1071,35 @@ static DestFetchProc destFetchProc[QImage::NImageFormats] =
destFetch, // Format_Grayscale8
};
+static DestFetchProc64 destFetchProc64[QImage::NImageFormats] =
+{
+ 0, // Format_Invalid
+ destFetch64, // Format_Mono,
+ destFetch64, // Format_MonoLSB
+ 0, // Format_Indexed8
+ destFetch64uint32, // Format_RGB32
+ destFetch64uint32, // Format_ARGB32,
+ destFetch64uint32, // Format_ARGB32_Premultiplied
+ destFetch64, // Format_RGB16
+ destFetch64, // Format_ARGB8565_Premultiplied
+ destFetch64, // Format_RGB666
+ destFetch64, // Format_ARGB6666_Premultiplied
+ destFetch64, // Format_RGB555
+ destFetch64, // Format_ARGB8555_Premultiplied
+ destFetch64, // Format_RGB888
+ destFetch64, // Format_RGB444
+ destFetch64, // Format_ARGB4444_Premultiplied
+ destFetch64uint32, // Format_RGBX8888
+ destFetch64uint32, // Format_RGBA8888
+ destFetch64uint32, // Format_RGBA8888_Premultiplied
+ destFetch64uint32, // Format_BGR30
+ destFetch64uint32, // Format_A2BGR30_Premultiplied
+ destFetch64uint32, // Format_RGB30
+ destFetch64uint32, // Format_A2RGB30_Premultiplied
+ destFetch64, // Format_Alpha8
+ destFetch64, // Format_Grayscale8
+};
+
/*
Returns the color in the mono destination color table
that is the "nearest" to /color/.
@@ -904,6 +1216,126 @@ static void QT_FASTCALL destStore(QRasterBuffer *rasterBuffer, int x, int y, con
}
}
+static void QT_FASTCALL convertFromRgb64(uint *dest, const QRgba64 *src, int length)
+{
+ for (int i = 0; i < length; ++i) {
+ dest[i] = src[i].toArgb32();
+ }
+}
+
+static void QT_FASTCALL destStore64(QRasterBuffer *rasterBuffer, int x, int y, const QRgba64 *buffer, int length)
+{
+ uint buf[buffer_size];
+ const QPixelLayout *layout = &qPixelLayouts[rasterBuffer->format];
+ StorePixelsFunc store = qStorePixels[layout->bpp];
+ uchar *dest = rasterBuffer->scanLine(y);
+ while (length) {
+ int l = qMin(length, buffer_size);
+ const uint *ptr = 0;
+ convertFromRgb64(buf, buffer, l);
+ if (!layout->premultiplied && !layout->alphaWidth)
+ ptr = layout->convertFromRGB32(buf, buf, l, layout, 0);
+ else
+ ptr = layout->convertFromARGB32PM(buf, buf, l, layout, 0);
+ store(dest, ptr, x, l);
+ length -= l;
+ buffer += l;
+ x += l;
+ }
+}
+
+#ifdef __SSE2__
+template<QtPixelOrder PixelOrder>
+static inline void qConvertARGB64PMToA2RGB30PM_sse2(uint *dest, const QRgba64 *buffer, int count)
+{
+ const __m128i gmask = _mm_set1_epi32(0x000ffc00);
+ const __m128i cmask = _mm_set1_epi32(0x000003ff);
+ int i = 0;
+ __m128i vr, vg, vb, va;
+ if (i < count && (const uintptr_t)buffer & 0x8) {
+ *dest++ = qConvertRgb64ToRgb30<PixelOrder>(*buffer++);
+ ++i;
+ }
+
+ for (; i < count-15; i += 16) {
+ // Repremultiplying is really expensive and hard to do in SIMD without AVX2,
+ // so we try to avoid it by checking if it is needed 16 samples at a time.
+ __m128i vOr = _mm_set1_epi32(0);
+ __m128i vAnd = _mm_set1_epi32(0xffffffff);
+ for (int j = 0; j < 16; j += 2) {
+ __m128i vs = _mm_load_si128((const __m128i*)(buffer + j));
+ vOr = _mm_or_si128(vOr, vs);
+ vAnd = _mm_and_si128(vAnd, vs);
+ }
+ const quint16 orAlpha = ((uint)_mm_extract_epi16(vOr, 3)) | ((uint)_mm_extract_epi16(vOr, 7));
+ const quint16 andAlpha = ((uint)_mm_extract_epi16(vAnd, 3)) & ((uint)_mm_extract_epi16(vAnd, 7));
+
+ if (andAlpha == 0xffff) {
+ for (int j = 0; j < 16; j += 2) {
+ __m128i vs = _mm_load_si128((const __m128i*)buffer);
+ buffer += 2;
+ vr = _mm_srli_epi64(vs, 6);
+ vg = _mm_srli_epi64(vs, 16 + 6 - 10);
+ vb = _mm_srli_epi64(vs, 32 + 6);
+ vr = _mm_and_si128(vr, cmask);
+ vg = _mm_and_si128(vg, gmask);
+ vb = _mm_and_si128(vb, cmask);
+ va = _mm_srli_epi64(vs, 48 + 14);
+ if (PixelOrder == PixelOrderRGB)
+ vr = _mm_slli_epi32(vr, 20);
+ else
+ vb = _mm_slli_epi32(vb, 20);
+ va = _mm_slli_epi32(va, 30);
+ __m128i vd = _mm_or_si128(_mm_or_si128(vr, vg), _mm_or_si128(vb, va));
+ vd = _mm_shuffle_epi32(vd, _MM_SHUFFLE(3, 1, 2, 0));
+ _mm_storel_epi64((__m128i*)dest, vd);
+ dest += 2;
+ }
+ } else if (orAlpha == 0) {
+ for (int j = 0; j < 16; ++j) {
+ *dest++ = 0;
+ buffer++;
+ }
+ } else {
+ for (int j = 0; j < 16; ++j)
+ *dest++ = qConvertRgb64ToRgb30<PixelOrder>(*buffer++);
+ }
+ }
+
+ for (; i < count; ++i)
+ *dest++ = qConvertRgb64ToRgb30<PixelOrder>(*buffer++);
+}
+#endif
+
+static void QT_FASTCALL destStore64ARGB32(QRasterBuffer *rasterBuffer, int x, int y, const QRgba64 *buffer, int length)
+{
+ uint *dest = (uint*)rasterBuffer->scanLine(y) + x;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = buffer[i].unpremultiplied().toArgb32();
+ }
+}
+
+static void QT_FASTCALL destStore64RGBA8888(QRasterBuffer *rasterBuffer, int x, int y, const QRgba64 *buffer, int length)
+{
+ uint *dest = (uint*)rasterBuffer->scanLine(y) + x;
+ for (int i = 0; i < length; ++i) {
+ dest[i] = ARGB2RGBA(buffer[i].unpremultiplied().toArgb32());
+ }
+}
+
+template<QtPixelOrder PixelOrder>
+static void QT_FASTCALL destStore64RGB30(QRasterBuffer *rasterBuffer, int x, int y, const QRgba64 *buffer, int length)
+{
+ uint *dest = (uint*)rasterBuffer->scanLine(y) + x;
+#ifdef __SSE2__
+ qConvertARGB64PMToA2RGB30PM_sse2<PixelOrder>(dest, buffer, length);
+#else
+ for (int i = 0; i < length; ++i) {
+ dest[i] = qConvertRgb64ToRgb30<PixelOrder>(buffer[i]);
+ }
+#endif
+}
+
static DestStoreProc destStoreProc[QImage::NImageFormats] =
{
0, // Format_Invalid
@@ -933,6 +1365,35 @@ static DestStoreProc destStoreProc[QImage::NImageFormats] =
destStore, // Format_Grayscale8
};
+static DestStoreProc64 destStoreProc64[QImage::NImageFormats] =
+{
+ 0, // Format_Invalid
+ destStore64, // Format_Mono,
+ destStore64, // Format_MonoLSB
+ 0, // Format_Indexed8
+ destStore64, // Format_RGB32
+ destStore64ARGB32, // Format_ARGB32,
+ destStore64, // Format_ARGB32_Premultiplied
+ destStore64, // Format_RGB16
+ destStore64, // Format_ARGB8565_Premultiplied
+ destStore64, // Format_RGB666
+ destStore64, // Format_ARGB6666_Premultiplied
+ destStore64, // Format_RGB555
+ destStore64, // Format_ARGB8555_Premultiplied
+ destStore64, // Format_RGB888
+ destStore64, // Format_RGB444
+ destStore64, // Format_ARGB4444_Premultiplied
+ destStore64, // Format_RGBX8888
+ destStore64RGBA8888, // Format_RGBA8888
+ destStore64, // Format_RGBA8888_Premultiplied
+ destStore64RGB30<PixelOrderBGR>, // Format_BGR30
+ destStore64RGB30<PixelOrderBGR>, // Format_A2BGR30_Premultiplied
+ destStore64RGB30<PixelOrderRGB>, // Format_RGB30
+ destStore64RGB30<PixelOrderRGB>, // Format_A2RGB30_Premultiplied
+ destStore64, // Format_Alpha8
+ destStore64, // Format_Grayscale8
+};
+
/*
Source fetches
@@ -988,6 +1449,21 @@ static const uint *QT_FASTCALL fetchUntransformedRGB16(uint *buffer, const Opera
return buffer;
}
+static const QRgba64 *QT_FASTCALL fetchUntransformed64(QRgba64 *buffer, const Operator *,
+ const QSpanData *data, int y, int x, int length)
+{
+ const QPixelLayout *layout = &qPixelLayouts[data->texture.format];
+ const QRgb *clut = data->texture.colorTable ? data->texture.colorTable->constData() : 0;
+ if (layout->bpp != QPixelLayout::BPP32) {
+ uint buffer32[buffer_size];
+ const uint *ptr = qFetchPixels[layout->bpp](buffer32, data->texture.scanLine(y), x, length);
+ return layout->convertToARGB64PM(buffer, ptr, length, layout, clut);
+ } else {
+ const uint *src = (const uint *)data->texture.scanLine(y) + x;
+ return layout->convertToARGB64PM(buffer, src, length, layout, clut);
+ }
+}
+
// blendType is either BlendTransformed or BlendTransformedTiled
template<TextureBlendType blendType>
static const uint *QT_FASTCALL fetchTransformedARGB32PM(uint *buffer, const Operator *, const QSpanData *data,
@@ -1155,6 +1631,111 @@ static const uint *QT_FASTCALL fetchTransformed(uint *buffer, const Operator *,
return layout->convertToARGB32PM(buffer, buffer, length, layout, clut);
}
+template<TextureBlendType blendType> /* either BlendTransformed or BlendTransformedTiled */
+static const QRgba64 *QT_FASTCALL fetchTransformed64(QRgba64 *buffer, const Operator *, const QSpanData *data,
+ int y, int x, int length)
+{
+ int image_width = data->texture.width;
+ int image_height = data->texture.height;
+
+ const qreal cx = x + qreal(0.5);
+ const qreal cy = y + qreal(0.5);
+
+ const QPixelLayout *layout = &qPixelLayouts[data->texture.format];
+ FetchPixelFunc fetch = qFetchPixel[layout->bpp];
+ const QRgb *clut = data->texture.colorTable ? data->texture.colorTable->constData() : 0;
+
+ uint buffer32[buffer_size];
+ QRgba64 *b = buffer;
+ if (data->fast_matrix) {
+ // The increment pr x in the scanline
+ int fdx = (int)(data->m11 * fixed_scale);
+ int fdy = (int)(data->m12 * fixed_scale);
+
+ int fx = int((data->m21 * cy
+ + data->m11 * cx + data->dx) * fixed_scale);
+ int fy = int((data->m22 * cy
+ + data->m12 * cx + data->dy) * fixed_scale);
+
+ int i = 0, j = 0;
+ while (i < length) {
+ if (j == buffer_size) {
+ layout->convertToARGB64PM(b, buffer32, buffer_size, layout, clut);
+ b += buffer_size;
+ j = 0;
+ }
+ int px = fx >> 16;
+ int py = fy >> 16;
+
+ if (blendType == BlendTransformedTiled) {
+ px %= image_width;
+ py %= image_height;
+ if (px < 0) px += image_width;
+ if (py < 0) py += image_height;
+ } else {
+ px = qBound(0, px, image_width - 1);
+ py = qBound(0, py, image_height - 1);
+ }
+ buffer32[j] = fetch(data->texture.scanLine(py), px);
+
+ fx += fdx;
+ fy += fdy;
+ ++i; ++j;
+ }
+ if (j > 0) {
+ layout->convertToARGB64PM(b, buffer32, j, layout, clut);
+ b += j;
+ }
+ } else {
+ const qreal fdx = data->m11;
+ const qreal fdy = data->m12;
+ const qreal fdw = data->m13;
+
+ qreal fx = data->m21 * cy + data->m11 * cx + data->dx;
+ qreal fy = data->m22 * cy + data->m12 * cx + data->dy;
+ qreal fw = data->m23 * cy + data->m13 * cx + data->m33;
+
+ int i = 0, j = 0;
+ while (i < length) {
+ if (j == buffer_size) {
+ layout->convertToARGB64PM(b, buffer32, buffer_size, layout, clut);
+ b += buffer_size;
+ j = 0;
+ }
+ const qreal iw = fw == 0 ? 1 : 1 / fw;
+ const qreal tx = fx * iw;
+ const qreal ty = fy * iw;
+ int px = int(tx) - (tx < 0);
+ int py = int(ty) - (ty < 0);
+
+ if (blendType == BlendTransformedTiled) {
+ px %= image_width;
+ py %= image_height;
+ if (px < 0) px += image_width;
+ if (py < 0) py += image_height;
+ } else {
+ px = qBound(0, px, image_width - 1);
+ py = qBound(0, py, image_height - 1);
+ }
+ buffer32[j] = fetch(data->texture.scanLine(py), px);
+
+ fx += fdx;
+ fy += fdy;
+ fw += fdw;
+ //force increment to avoid /0
+ if (!fw) {
+ fw += fdw;
+ }
+ ++i; ++j;
+ }
+ if (j > 0) {
+ layout->convertToARGB64PM(b, buffer32, j, layout, clut);
+ b += j;
+ }
+ }
+ return buffer;
+}
+
/** \internal
interpolate 4 argb pixels with the distx and disty factor.
distx and disty bust be between 0 and 16
@@ -1245,6 +1826,42 @@ static inline uint interpolate_4_pixels_16(uint tl, uint tr, uint bl, uint br, i
}
#endif
+#if defined(__SSE2__)
+static inline QRgba64 interpolate_4_pixels_rgb64(QRgba64 t[], QRgba64 b[], uint distx, uint disty)
+{
+ const __m128i vdistx = _mm_shufflelo_epi16(_mm_cvtsi32_si128(distx), _MM_SHUFFLE(0, 0, 0, 0));
+ const __m128i vidistx = _mm_shufflelo_epi16(_mm_cvtsi32_si128(0x10000 - distx), _MM_SHUFFLE(0, 0, 0, 0));
+
+ __m128i vt = _mm_loadu_si128((const __m128i*)t);
+ if (disty) {
+ __m128i vb = _mm_loadu_si128((const __m128i*)b);
+ vt = _mm_mulhi_epu16(vt, _mm_set1_epi16(0x10000 - disty));
+ vb = _mm_mulhi_epu16(vb, _mm_set1_epi16(disty));
+ vt = _mm_add_epi16(vt, vb);
+ }
+ vt = _mm_mulhi_epu16(vt, _mm_unpacklo_epi64(vidistx, vdistx));
+ vt = _mm_add_epi16(vt, _mm_srli_si128(vt, 8));
+#ifdef Q_PROCESSOR_X86_64
+ return QRgba64::fromRgba64(_mm_cvtsi128_si64(vt));
+#else
+ QRgba64 out;
+ _mm_storel_epi64((__m128i*)&out, vt);
+ return out;
+#endif
+}
+#else
+static inline QRgba64 interpolate_4_pixels_rgb64(QRgba64 t[], QRgba64 b[], uint distx, uint disty)
+{
+ const uint dx = distx>>8;
+ const uint dy = disty>>8;
+ const uint idx = 256 - dx;
+ const uint idy = 256 - dy;
+ QRgba64 xtop = interpolate256(t[0], idx, t[1], dx);
+ QRgba64 xbot = interpolate256(b[0], idx, b[1], dx);
+ return interpolate256(xtop, idy, xbot, dy);
+}
+#endif
+
template<TextureBlendType blendType>
void fetchTransformedBilinear_pixelBounds(int max, int l1, int l2, int &v1, int &v2);
@@ -2130,6 +2747,349 @@ static const uint *QT_FASTCALL fetchTransformedBilinear(uint *buffer, const Oper
return buffer;
}
+template<TextureBlendType blendType>
+static const QRgba64 *QT_FASTCALL fetchTransformedBilinear64(QRgba64 *buffer, const Operator *,
+ const QSpanData *data, int y, int x, int length)
+{
+ const QPixelLayout *layout = &qPixelLayouts[data->texture.format];
+ const QRgb *clut = data->texture.colorTable ? data->texture.colorTable->constData() : 0;
+
+ int image_width = data->texture.width;
+ int image_height = data->texture.height;
+
+ int image_x1 = data->texture.x1;
+ int image_y1 = data->texture.y1;
+ int image_x2 = data->texture.x2 - 1;
+ int image_y2 = data->texture.y2 - 1;
+
+ const qreal cx = x + qreal(0.5);
+ const qreal cy = y + qreal(0.5);
+
+ const qreal fdx = data->m11;
+ const qreal fdy = data->m12;
+ const qreal fdw = data->m13;
+
+ if (data->fast_matrix) {
+ // The increment pr x in the scanline
+ int fdx = (int)(data->m11 * fixed_scale);
+ int fdy = (int)(data->m12 * fixed_scale);
+
+ int fx = int((data->m21 * cy + data->m11 * cx + data->dx) * fixed_scale);
+ int fy = int((data->m22 * cy + data->m12 * cx + data->dy) * fixed_scale);
+
+ fx -= half_point;
+ fy -= half_point;
+
+ if (fdy == 0) { //simple scale, no rotation
+ int y1 = (fy >> 16);
+ int y2;
+ fetchTransformedBilinear_pixelBounds<blendType>(image_height, image_y1, image_y2, y1, y2);
+ const uchar *s1 = data->texture.scanLine(y1);
+ const uchar *s2 = data->texture.scanLine(y2);
+
+ FetchPixelFunc fetch = qFetchPixel[layout->bpp];
+ uint sbuf1[buffer_size];
+ uint sbuf2[buffer_size];
+ QRgba64 buf1[buffer_size];
+ QRgba64 buf2[buffer_size];
+ QRgba64 *b = buffer;
+ while (length) {
+ int len = qMin(length, buffer_size / 2);
+ int fracX = fx;
+ int i = 0;
+ int disty = (fy & 0x0000ffff);
+#if defined(__SSE2__)
+ const __m128i vdy = _mm_set1_epi16(disty);
+ const __m128i vidy = _mm_set1_epi16(0x10000 - disty);
+ if (blendType != BlendTransformedBilinearTiled && layout->bpp == QPixelLayout::BPP32) {
+ for (; i < len; ++i) {
+ int x1 = (fx >> 16);
+ int x2;
+ fetchTransformedBilinear_pixelBounds<blendType>(image_width, image_x1, image_x2, x1, x2);
+ if (x1 != x2)
+ break;
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[x1];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[x2];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[x1];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[x2];
+ fx += fdx;
+ }
+
+ const __m128i v_fdx = _mm_set1_epi32(fdx*4);
+ __m128i v_fx = _mm_setr_epi32(fx, fx + fdx, fx + fdx + fdx, fx + fdx + fdx + fdx);
+ for (; i < len-3; i+=4) {
+ int offset = _mm_extract_epi16(v_fx, 1);
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[offset + 1];
+ offset = _mm_extract_epi16(v_fx, 3);
+ sbuf1[i * 2 + 2] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 3] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 2] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 3] = ((const uint*)s2)[offset + 1];
+ offset = _mm_extract_epi16(v_fx, 5);
+ sbuf1[i * 2 + 4] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 5] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 4] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 5] = ((const uint*)s2)[offset + 1];
+ offset = _mm_extract_epi16(v_fx, 7);
+ sbuf1[i * 2 + 6] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 7] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 6] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 7] = ((const uint*)s2)[offset + 1];
+ v_fx = _mm_add_epi32(v_fx, v_fdx);
+ }
+ fx = _mm_cvtsi128_si32(v_fx);
+ }
+#endif
+ for (; i < len; ++i) {
+ int x1 = (fx >> 16);
+ int x2;
+ fetchTransformedBilinear_pixelBounds<blendType>(image_width, image_x1, image_x2, x1, x2);
+
+ if (layout->bpp == QPixelLayout::BPP32) {
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[x1];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[x2];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[x1];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[x2];
+
+ } else {
+ sbuf1[i * 2 + 0] = fetch(s1, x1);
+ sbuf1[i * 2 + 1] = fetch(s1, x2);
+ sbuf2[i * 2 + 0] = fetch(s2, x1);
+ sbuf2[i * 2 + 1] = fetch(s2, x2);
+ }
+
+ fx += fdx;
+ }
+ layout->convertToARGB64PM(buf1, sbuf1, len * 2, layout, clut);
+ if (disty)
+ layout->convertToARGB64PM(buf2, sbuf2, len * 2, layout, clut);
+
+ for (int i = 0; i < len; ++i) {
+ int distx = (fracX & 0x0000ffff);
+#if defined(__SSE2__)
+ const __m128i vdistx = _mm_shufflelo_epi16(_mm_cvtsi32_si128(distx), _MM_SHUFFLE(0, 0, 0, 0));
+ const __m128i vidistx = _mm_shufflelo_epi16(_mm_cvtsi32_si128(0x10000 - distx), _MM_SHUFFLE(0, 0, 0, 0));
+ __m128i vt = _mm_loadu_si128((const __m128i*)(buf1 + i*2));
+ if (disty) {
+ __m128i vb = _mm_loadu_si128((const __m128i*)(buf2 + i*2));
+ vt = _mm_mulhi_epu16(vt, vidy);
+ vb = _mm_mulhi_epu16(vb, vdy);
+ vt = _mm_add_epi16(vt, vb);
+ }
+ vt = _mm_mulhi_epu16(vt, _mm_unpacklo_epi64(vidistx, vdistx));
+ vt = _mm_add_epi16(vt, _mm_srli_si128(vt, 8));
+ _mm_storel_epi64((__m128i*)(b+i), vt);
+#else
+ b[i] = interpolate_4_pixels_rgb64(buf1 + i*2, buf2 + i*2, distx, disty);
+#endif
+ fracX += fdx;
+ }
+ length -= len;
+ b += len;
+ }
+ } else { //rotation
+ FetchPixelFunc fetch = qFetchPixel[layout->bpp];
+ uint sbuf1[buffer_size];
+ uint sbuf2[buffer_size];
+ QRgba64 buf1[buffer_size];
+ QRgba64 buf2[buffer_size];
+ QRgba64 *end = buffer + length;
+ QRgba64 *b = buffer;
+
+ while (b < end) {
+ int len = qMin(length, buffer_size / 2);
+ int fracX = fx;
+ int fracY = fy;
+ int i = 0;
+#if defined(__SSE2__)
+ if (blendType != BlendTransformedBilinearTiled && layout->bpp == QPixelLayout::BPP32) {
+ for (; i < len; ++i) {
+ int x1 = (fx >> 16);
+ int x2;
+ int y1 = (fy >> 16);
+ int y2;
+ fetchTransformedBilinear_pixelBounds<blendType>(image_width, image_x1, image_x2, x1, x2);
+ fetchTransformedBilinear_pixelBounds<blendType>(image_height, image_y1, image_y2, y1, y2);
+ if (x1 != x2 && y1 != y2)
+ break;
+ const uchar *s1 = data->texture.scanLine(y1);
+ const uchar *s2 = data->texture.scanLine(y2);
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[x1];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[x2];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[x1];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[x2];
+ fx += fdx;
+ fy += fdy;
+ }
+
+ const __m128i v_fdx = _mm_set1_epi32(fdx*4);
+ const __m128i v_fdy = _mm_set1_epi32(fdy*4);
+ __m128i v_fx = _mm_setr_epi32(fx, fx + fdx, fx + fdx + fdx, fx + fdx + fdx + fdx);
+ __m128i v_fy = _mm_setr_epi32(fy, fy + fdy, fy + fdy + fdy, fy + fdy + fdy + fdy);
+ const int bytesPerLine = data->texture.bytesPerLine;
+ const uchar *s1 = data->texture.imageData;
+ const uchar *s2 = s1 + bytesPerLine;
+ const __m128i vbpl = _mm_shufflelo_epi16(_mm_cvtsi32_si128(bytesPerLine/4), _MM_SHUFFLE(0, 0, 0, 0));
+ for (; i < len-3; i+=4) {
+ if (fdx > 0 && (short)_mm_extract_epi16(v_fx, 7) >= image_x2)
+ break;
+ if (fdx < 0 && (short)_mm_extract_epi16(v_fx, 7) < image_x1)
+ break;
+ if (fdy > 0 && (short)_mm_extract_epi16(v_fy, 7) >= image_y2)
+ break;
+ if (fdy < 0 && (short)_mm_extract_epi16(v_fy, 7) < image_y1)
+ break;
+ const __m128i vy = _mm_packs_epi32(_mm_srai_epi32(v_fy, 16), _mm_setzero_si128());
+ __m128i voffset = _mm_unpacklo_epi16(_mm_mullo_epi16(vy, vbpl), _mm_mulhi_epu16(vy, vbpl));
+ voffset = _mm_add_epi32(voffset, _mm_srli_epi32(v_fx, 16));
+
+ int offset = _mm_cvtsi128_si32(voffset); voffset = _mm_srli_si128(voffset, 4);
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[offset + 1];
+ offset = _mm_cvtsi128_si32(voffset); voffset = _mm_srli_si128(voffset, 4);
+ sbuf1[i * 2 + 2] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 3] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 2] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 3] = ((const uint*)s2)[offset + 1];
+ offset = _mm_cvtsi128_si32(voffset); voffset = _mm_srli_si128(voffset, 4);
+ sbuf1[i * 2 + 4] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 5] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 4] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 5] = ((const uint*)s2)[offset + 1];
+ offset = _mm_cvtsi128_si32(voffset);
+ sbuf1[i * 2 + 6] = ((const uint*)s1)[offset];
+ sbuf1[i * 2 + 7] = ((const uint*)s1)[offset + 1];
+ sbuf2[i * 2 + 6] = ((const uint*)s2)[offset];
+ sbuf2[i * 2 + 7] = ((const uint*)s2)[offset + 1];
+
+ v_fx = _mm_add_epi32(v_fx, v_fdx);
+ v_fy = _mm_add_epi32(v_fy, v_fdy);
+ }
+ fx = _mm_cvtsi128_si32(v_fx);
+ fy = _mm_cvtsi128_si32(v_fy);
+ }
+#endif
+ for (; i < len; ++i) {
+ int x1 = (fx >> 16);
+ int x2;
+ int y1 = (fy >> 16);
+ int y2;
+ fetchTransformedBilinear_pixelBounds<blendType>(image_width, image_x1, image_x2, x1, x2);
+ fetchTransformedBilinear_pixelBounds<blendType>(image_height, image_y1, image_y2, y1, y2);
+
+ const uchar *s1 = data->texture.scanLine(y1);
+ const uchar *s2 = data->texture.scanLine(y2);
+
+ if (layout->bpp == QPixelLayout::BPP32) {
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[x1];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[x2];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[x1];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[x2];
+
+ } else {
+ sbuf1[i * 2 + 0] = fetch(s1, x1);
+ sbuf1[i * 2 + 1] = fetch(s1, x2);
+ sbuf2[i * 2 + 0] = fetch(s2, x1);
+ sbuf2[i * 2 + 1] = fetch(s2, x2);
+ }
+
+ fx += fdx;
+ fy += fdy;
+ }
+ layout->convertToARGB64PM(buf1, sbuf1, len * 2, layout, clut);
+ layout->convertToARGB64PM(buf2, sbuf2, len * 2, layout, clut);
+
+ for (int i = 0; i < len; ++i) {
+ int distx = (fracX & 0x0000ffff);
+ int disty = (fracY & 0x0000ffff);
+ b[i] = interpolate_4_pixels_rgb64(buf1 + i*2, buf2 + i*2, distx, disty);
+ fracX += fdx;
+ fracY += fdy;
+ }
+
+ length -= len;
+ b += len;
+ }
+ }
+ } else {
+ qreal fx = data->m21 * cy + data->m11 * cx + data->dx;
+ qreal fy = data->m22 * cy + data->m12 * cx + data->dy;
+ qreal fw = data->m23 * cy + data->m13 * cx + data->m33;
+
+ FetchPixelFunc fetch = qFetchPixel[layout->bpp];
+ uint sbuf1[buffer_size];
+ uint sbuf2[buffer_size];
+ QRgba64 buf1[buffer_size];
+ QRgba64 buf2[buffer_size];
+ QRgba64 *b = buffer;
+
+ int distxs[buffer_size / 2];
+ int distys[buffer_size / 2];
+
+ while (length) {
+ int len = qMin(length, buffer_size / 2);
+ for (int i = 0; i < len; ++i) {
+ const qreal iw = fw == 0 ? 1 : 1 / fw;
+ const qreal px = fx * iw - qreal(0.5);
+ const qreal py = fy * iw - qreal(0.5);
+
+ int x1 = int(px) - (px < 0);
+ int x2;
+ int y1 = int(py) - (py < 0);
+ int y2;
+
+ distxs[i] = int((px - x1) * (1<<16));
+ distys[i] = int((py - y1) * (1<<16));
+
+ fetchTransformedBilinear_pixelBounds<blendType>(image_width, image_x1, image_x2, x1, x2);
+ fetchTransformedBilinear_pixelBounds<blendType>(image_height, image_y1, image_y2, y1, y2);
+
+ const uchar *s1 = data->texture.scanLine(y1);
+ const uchar *s2 = data->texture.scanLine(y2);
+
+ if (layout->bpp == QPixelLayout::BPP32) {
+ sbuf1[i * 2 + 0] = ((const uint*)s1)[x1];
+ sbuf1[i * 2 + 1] = ((const uint*)s1)[x2];
+ sbuf2[i * 2 + 0] = ((const uint*)s2)[x1];
+ sbuf2[i * 2 + 1] = ((const uint*)s2)[x2];
+
+ } else {
+ sbuf1[i * 2 + 0] = fetch(s1, x1);
+ sbuf1[i * 2 + 1] = fetch(s1, x2);
+ sbuf2[i * 2 + 0] = fetch(s2, x1);
+ sbuf2[i * 2 + 1] = fetch(s2, x2);
+ }
+
+ fx += fdx;
+ fy += fdy;
+ fw += fdw;
+ //force increment to avoid /0
+ if (!fw)
+ fw += fdw;
+ }
+
+ layout->convertToARGB64PM(buf1, sbuf1, len * 2, layout, clut);
+ layout->convertToARGB64PM(buf2, sbuf2, len * 2, layout, clut);
+
+ for (int i = 0; i < len; ++i) {
+ int distx = distxs[i];
+ int disty = distys[i];
+ b[i] = interpolate_4_pixels_rgb64(buf1 + i*2, buf2 + i*2, distx, disty);
+ }
+
+ length -= len;
+ b += len;
+ }
+ }
+
+ return buffer;
+}
+
static SourceFetchProc sourceFetch[NBlendTypes][QImage::NImageFormats] = {
// Untransformed
{
@@ -2298,12 +3258,186 @@ static SourceFetchProc sourceFetch[NBlendTypes][QImage::NImageFormats] = {
},
};
+static SourceFetchProc64 sourceFetch64[NBlendTypes][QImage::NImageFormats] = {
+ // Untransformed
+ {
+ 0, // Invalid
+ fetchUntransformed64, // Mono
+ fetchUntransformed64, // MonoLsb
+ fetchUntransformed64, // Indexed8
+ fetchUntransformed64, // RGB32
+ fetchUntransformed64, // ARGB32
+ fetchUntransformed64, // ARGB32_Premultiplied
+ fetchUntransformed64, // RGB16
+ fetchUntransformed64, // ARGB8565_Premultiplied
+ fetchUntransformed64, // RGB666
+ fetchUntransformed64, // ARGB6666_Premultiplied
+ fetchUntransformed64, // RGB555
+ fetchUntransformed64, // ARGB8555_Premultiplied
+ fetchUntransformed64, // RGB888
+ fetchUntransformed64, // RGB444
+ fetchUntransformed64, // ARGB4444_Premultiplied
+ fetchUntransformed64, // RGBX8888
+ fetchUntransformed64, // RGBA8888
+ fetchUntransformed64, // RGBA8888_Premultiplied
+ fetchUntransformed64, // Format_BGR30
+ fetchUntransformed64, // Format_A2BGR30_Premultiplied
+ fetchUntransformed64, // Format_RGB30
+ fetchUntransformed64, // Format_A2RGB30_Premultiplied
+ fetchUntransformed64, // Alpha8
+ fetchUntransformed64, // Grayscale8
+ },
+ // Tiled
+ {
+ 0, // Invalid
+ fetchUntransformed64, // Mono
+ fetchUntransformed64, // MonoLsb
+ fetchUntransformed64, // Indexed8
+ fetchUntransformed64, // RGB32
+ fetchUntransformed64, // ARGB32
+ fetchUntransformed64, // ARGB32_Premultiplied
+ fetchUntransformed64, // RGB16
+ fetchUntransformed64, // ARGB8565_Premultiplied
+ fetchUntransformed64, // RGB666
+ fetchUntransformed64, // ARGB6666_Premultiplied
+ fetchUntransformed64, // RGB555
+ fetchUntransformed64, // ARGB8555_Premultiplied
+ fetchUntransformed64, // RGB888
+ fetchUntransformed64, // RGB444
+ fetchUntransformed64, // ARGB4444_Premultiplied
+ fetchUntransformed64, // RGBX8888
+ fetchUntransformed64, // RGBA8888
+ fetchUntransformed64, // RGBA8888_Premultiplied
+ fetchUntransformed64, // BGR30
+ fetchUntransformed64, // A2BGR30_Premultiplied
+ fetchUntransformed64, // RGB30
+ fetchUntransformed64, // A2RGB30_Premultiplied
+ fetchUntransformed64, // Alpha8
+ fetchUntransformed64, // Grayscale8
+ },
+ // Transformed
+ {
+ 0, // Invalid
+ fetchTransformed64<BlendTransformed>, // Mono
+ fetchTransformed64<BlendTransformed>, // MonoLsb
+ fetchTransformed64<BlendTransformed>, // Indexed8
+ fetchTransformed64<BlendTransformed>, // RGB32
+ fetchTransformed64<BlendTransformed>, // ARGB32
+ fetchTransformed64<BlendTransformed>, // ARGB32_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGB16
+ fetchTransformed64<BlendTransformed>, // ARGB8565_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGB666
+ fetchTransformed64<BlendTransformed>, // ARGB6666_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGB555
+ fetchTransformed64<BlendTransformed>, // ARGB8555_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGB888
+ fetchTransformed64<BlendTransformed>, // RGB444
+ fetchTransformed64<BlendTransformed>, // ARGB4444_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGBX8888
+ fetchTransformed64<BlendTransformed>, // RGBA8888
+ fetchTransformed64<BlendTransformed>, // RGBA8888_Premultiplied
+ fetchTransformed64<BlendTransformed>, // BGR30
+ fetchTransformed64<BlendTransformed>, // A2BGR30_Premultiplied
+ fetchTransformed64<BlendTransformed>, // RGB30
+ fetchTransformed64<BlendTransformed>, // A2RGB30_Premultiplied
+ fetchTransformed64<BlendTransformed>, // Alpah8
+ fetchTransformed64<BlendTransformed>, // Grayscale8
+ },
+ {
+ 0, // TransformedTiled
+ fetchTransformed64<BlendTransformedTiled>, // Mono
+ fetchTransformed64<BlendTransformedTiled>, // MonoLsb
+ fetchTransformed64<BlendTransformedTiled>, // Indexed8
+ fetchTransformed64<BlendTransformedTiled>, // RGB32
+ fetchTransformed64<BlendTransformedTiled>, // ARGB32
+ fetchTransformed64<BlendTransformedTiled>, // ARGB32_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGB16
+ fetchTransformed64<BlendTransformedTiled>, // ARGB8565_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGB666
+ fetchTransformed64<BlendTransformedTiled>, // ARGB6666_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGB555
+ fetchTransformed64<BlendTransformedTiled>, // ARGB8555_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGB888
+ fetchTransformed64<BlendTransformedTiled>, // RGB444
+ fetchTransformed64<BlendTransformedTiled>, // ARGB4444_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGBX8888
+ fetchTransformed64<BlendTransformedTiled>, // RGBA8888
+ fetchTransformed64<BlendTransformedTiled>, // RGBA8888_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // BGR30
+ fetchTransformed64<BlendTransformedTiled>, // A2BGR30_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // RGB30
+ fetchTransformed64<BlendTransformedTiled>, // A2RGB30_Premultiplied
+ fetchTransformed64<BlendTransformedTiled>, // Alpha8
+ fetchTransformed64<BlendTransformedTiled>, // Grayscale8
+ },
+ {
+ 0, // Bilinear
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // Mono
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // MonoLsb
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // Indexed8
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB32
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB32
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB32_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB16
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB8565_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB666
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB6666_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB555
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB8555_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB888
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB444
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // ARGB4444_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGBX8888
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGBA8888
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGBA8888_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // BGR30
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // A2BGR30_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // RGB30
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // A2RGB30_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // Alpha8
+ fetchTransformedBilinear64<BlendTransformedBilinear>, // Grayscale8
+ },
+ {
+ 0, // BilinearTiled
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // Mono
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // MonoLsb
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // Indexed8
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB32
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB32
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB32_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB16
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB8565_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB666
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB6666_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB555
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB8555_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB888
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB444
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // ARGB4444_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGBX8888
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGBA8888
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGBA8888_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // BGR30
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // A2BGR30_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // RGB30
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // A2RGB30_Premultiplied
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // Alpha8
+ fetchTransformedBilinear64<BlendTransformedBilinearTiled>, // Grayscale8
+ },
+};
+
#define FIXPT_BITS 8
#define FIXPT_SIZE (1<<FIXPT_BITS)
static uint qt_gradient_pixel_fixed(const QGradientData *data, int fixed_pos)
{
int ipos = (fixed_pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS;
+ return data->colorTable[qt_gradient_clamp(data, ipos)].toArgb32();
+}
+
+static const QRgba64& qt_gradient_pixel64_fixed(const QGradientData *data, int fixed_pos)
+{
+ int ipos = (fixed_pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS;
return data->colorTable[qt_gradient_clamp(data, ipos)];
}
@@ -2320,10 +3454,50 @@ static void QT_FASTCALL getLinearGradientValues(LinearGradientValues *v, const Q
}
}
-static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Operator *op, const QSpanData *data,
- int y, int x, int length)
+class GradientBase32
{
- const uint *b = buffer;
+public:
+ typedef uint Type;
+ static Type null() { return 0; }
+ static Type fetchSingle(const QGradientData& gradient, qreal v)
+ {
+ return qt_gradient_pixel(&gradient, v);
+ }
+ static Type fetchSingle(const QGradientData& gradient, int v)
+ {
+ return qt_gradient_pixel_fixed(&gradient, v);
+ }
+ static void memfill(Type *buffer, Type fill, int length)
+ {
+ qt_memfill32(buffer, fill, length);
+ }
+};
+
+class GradientBase64
+{
+public:
+ typedef QRgba64 Type;
+ static Type null() { return QRgba64::fromRgba64(0); }
+ static Type fetchSingle(const QGradientData& gradient, qreal v)
+ {
+ return qt_gradient_pixel64(&gradient, v);
+ }
+ static Type fetchSingle(const QGradientData& gradient, int v)
+ {
+ return qt_gradient_pixel64_fixed(&gradient, v);
+ }
+ static void memfill(Type *buffer, Type fill, int length)
+ {
+ qt_memfill64((quint64*)buffer, fill, length);
+ }
+};
+
+template<class GradientBase, typename BlendType>
+static inline const BlendType * QT_FASTCALL qt_fetch_linear_gradient_template(
+ BlendType *buffer, const Operator *op, const QSpanData *data,
+ int y, int x, int length)
+{
+ const BlendType *b = buffer;
qreal t, inc;
bool affine = true;
@@ -2343,10 +3517,10 @@ static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Ope
}
}
- const uint *end = buffer + length;
+ const BlendType *end = buffer + length;
if (affine) {
if (inc > qreal(-1e-5) && inc < qreal(1e-5)) {
- QT_MEMFILL_UINT(buffer, length, qt_gradient_pixel_fixed(&data->gradient, int(t * FIXPT_SIZE)));
+ GradientBase::memfill(buffer, GradientBase::fetchSingle(data->gradient, int(t * FIXPT_SIZE)), length);
} else {
if (t+inc*length < qreal(INT_MAX >> (FIXPT_BITS + 1)) &&
t+inc*length > qreal(INT_MIN >> (FIXPT_BITS + 1))) {
@@ -2354,14 +3528,14 @@ static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Ope
int t_fixed = int(t * FIXPT_SIZE);
int inc_fixed = int(inc * FIXPT_SIZE);
while (buffer < end) {
- *buffer = qt_gradient_pixel_fixed(&data->gradient, t_fixed);
+ *buffer = GradientBase::fetchSingle(data->gradient, t_fixed);
t_fixed += inc_fixed;
++buffer;
}
} else {
// we have to fall back to float math
while (buffer < end) {
- *buffer = qt_gradient_pixel(&data->gradient, t/GRADIENT_STOPTABLE_SIZE);
+ *buffer = GradientBase::fetchSingle(data->gradient, t/GRADIENT_STOPTABLE_SIZE);
t += inc;
++buffer;
}
@@ -2374,7 +3548,7 @@ static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Ope
qreal y = ry/rw;
t = (op->linear.dx*x + op->linear.dy *y) + op->linear.off;
- *buffer = qt_gradient_pixel(&data->gradient, t);
+ *buffer = GradientBase::fetchSingle(data->gradient, t);
rx += data->m11;
ry += data->m12;
rw += data->m13;
@@ -2388,6 +3562,18 @@ static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Ope
return b;
}
+static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Operator *op, const QSpanData *data,
+ int y, int x, int length)
+{
+ return qt_fetch_linear_gradient_template<GradientBase32, uint>(buffer, op, data, y, x, length);
+}
+
+static const QRgba64 * QT_FASTCALL qt_fetch_linear_gradient_rgb64(QRgba64 *buffer, const Operator *op, const QSpanData *data,
+ int y, int x, int length)
+{
+ return qt_fetch_linear_gradient_template<GradientBase64, QRgba64>(buffer, op, data, y, x, length);
+}
+
static void QT_FASTCALL getRadialGradientValues(RadialGradientValues *v, const QSpanData *data)
{
v->dx = data->gradient.radial.center.x - data->gradient.radial.focal.x;
@@ -2402,19 +3588,22 @@ static void QT_FASTCALL getRadialGradientValues(RadialGradientValues *v, const Q
v->extended = !qFuzzyIsNull(data->gradient.radial.focal.radius) || v->a <= 0;
}
-class RadialFetchPlain
+template <class GradientBase>
+class RadialFetchPlain : public GradientBase
{
public:
- static inline void fetch(uint *buffer, uint *end, const Operator *op, const QSpanData *data, qreal det,
- qreal delta_det, qreal delta_delta_det, qreal b, qreal delta_b)
+ typedef typename GradientBase::Type BlendType;
+ static void fetch(BlendType *buffer, BlendType *end,
+ const Operator *op, const QSpanData *data, qreal det,
+ qreal delta_det, qreal delta_delta_det, qreal b, qreal delta_b)
{
if (op->radial.extended) {
while (buffer < end) {
- quint32 result = 0;
+ BlendType result = GradientBase::null();
if (det >= 0) {
qreal w = qSqrt(det) - b;
if (data->gradient.radial.focal.radius + op->radial.dr * w >= 0)
- result = qt_gradient_pixel(&data->gradient, w);
+ result = GradientBase::fetchSingle(data->gradient, w);
}
*buffer = result;
@@ -2427,7 +3616,7 @@ public:
}
} else {
while (buffer < end) {
- *buffer++ = qt_gradient_pixel(&data->gradient, qSqrt(det) - b);
+ *buffer++ = GradientBase::fetchSingle(data->gradient, qSqrt(det) - b);
det += delta_det;
delta_det += delta_delta_det;
@@ -2440,15 +3629,23 @@ public:
const uint * QT_FASTCALL qt_fetch_radial_gradient_plain(uint *buffer, const Operator *op, const QSpanData *data,
int y, int x, int length)
{
- return qt_fetch_radial_gradient_template<RadialFetchPlain>(buffer, op, data, y, x, length);
+ return qt_fetch_radial_gradient_template<RadialFetchPlain<GradientBase32>, uint>(buffer, op, data, y, x, length);
}
static SourceFetchProc qt_fetch_radial_gradient = qt_fetch_radial_gradient_plain;
-static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Operator *, const QSpanData *data,
- int y, int x, int length)
+const QRgba64 * QT_FASTCALL qt_fetch_radial_gradient_rgb64(QRgba64 *buffer, const Operator *op, const QSpanData *data,
+ int y, int x, int length)
{
- const uint *b = buffer;
+ return qt_fetch_radial_gradient_template<RadialFetchPlain<GradientBase64>, QRgba64>(buffer, op, data, y, x, length);
+}
+
+template <class GradientBase, typename BlendType>
+static inline const BlendType * QT_FASTCALL qt_fetch_conical_gradient_template(
+ BlendType *buffer, const QSpanData *data,
+ int y, int x, int length)
+{
+ const BlendType *b = buffer;
qreal rx = data->m21 * (y + qreal(0.5))
+ data->dx + data->m11 * (x + qreal(0.5));
qreal ry = data->m22 * (y + qreal(0.5))
@@ -2457,14 +3654,14 @@ static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Op
const qreal inv2pi = M_1_PI / 2.0;
- const uint *end = buffer + length;
+ const BlendType *end = buffer + length;
if (affine) {
rx -= data->gradient.conical.center.x;
ry -= data->gradient.conical.center.y;
while (buffer < end) {
qreal angle = qAtan2(ry, rx) + data->gradient.conical.angle;
- *buffer = qt_gradient_pixel(&data->gradient, 1 - angle * inv2pi);
+ *buffer = GradientBase::fetchSingle(data->gradient, 1 - angle * inv2pi);
rx += data->m11;
ry += data->m12;
@@ -2480,7 +3677,7 @@ static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Op
rx/rw - data->gradient.conical.center.y)
+ data->gradient.conical.angle;
- *buffer = qt_gradient_pixel(&data->gradient, 1 - angle * inv2pi);
+ *buffer = GradientBase::fetchSingle(data->gradient, 1 - angle * inv2pi);
rx += data->m11;
ry += data->m12;
@@ -2494,1763 +3691,29 @@ static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Op
return b;
}
-# define PRELOAD_INIT(x)
-# define PRELOAD_INIT2(x,y)
-# define PRELOAD_COND(x)
-# define PRELOAD_COND2(x,y)
-
-/* The constant alpha factor describes an alpha factor that gets applied
- to the result of the composition operation combining it with the destination.
-
- The intent is that if const_alpha == 0. we get back dest, and if const_alpha == 1.
- we get the unmodified operation
-
- result = src op dest
- dest = result * const_alpha + dest * (1. - const_alpha)
-
- This means that in the comments below, the first line is the const_alpha==255 case, the
- second line the general one.
-
- In the lines below:
- s == src, sa == alpha(src), sia = 1 - alpha(src)
- d == dest, da == alpha(dest), dia = 1 - alpha(dest)
- ca = const_alpha, cia = 1 - const_alpha
-
- The methods exist in two variants. One where we have a constant source, the other
- where the source is an array of pixels.
-*/
-
-/*
- result = 0
- d = d * cia
-*/
-#define comp_func_Clear_impl(dest, length, const_alpha)\
-{\
- if (const_alpha == 255) {\
- QT_MEMFILL_UINT(dest, length, 0);\
- } else {\
- int ialpha = 255 - const_alpha;\
- PRELOAD_INIT(dest)\
- for (int i = 0; i < length; ++i) {\
- PRELOAD_COND(dest)\
- dest[i] = BYTE_MUL(dest[i], ialpha);\
- }\
- }\
-}
-
-void QT_FASTCALL comp_func_solid_Clear(uint *dest, int length, uint, uint const_alpha)
-{
- comp_func_Clear_impl(dest, length, const_alpha);
-}
-
-void QT_FASTCALL comp_func_Clear(uint *dest, const uint *, int length, uint const_alpha)
-{
- comp_func_Clear_impl(dest, length, const_alpha);
-}
-
-/*
- result = s
- dest = s * ca + d * cia
-*/
-void QT_FASTCALL comp_func_solid_Source(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255) {
- QT_MEMFILL_UINT(dest, length, color);
- } else {
- int ialpha = 255 - const_alpha;
- color = BYTE_MUL(color, const_alpha);
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = color + BYTE_MUL(dest[i], ialpha);
- }
- }
-}
-
-void QT_FASTCALL comp_func_Source(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255) {
- ::memcpy(dest, src, length * sizeof(uint));
- } else {
- int ialpha = 255 - const_alpha;
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- dest[i] = INTERPOLATE_PIXEL_255(src[i], const_alpha, dest[i], ialpha);
- }
- }
-}
-
-void QT_FASTCALL comp_func_solid_Destination(uint *, int, uint, uint)
-{
-}
-
-void QT_FASTCALL comp_func_Destination(uint *, const uint *, int, uint)
-{
-}
-
-/*
- result = s + d * sia
- dest = (s + d * sia) * ca + d * cia
- = s * ca + d * (sia * ca + cia)
- = s * ca + d * (1 - sa*ca)
-*/
-void QT_FASTCALL comp_func_solid_SourceOver(uint *dest, int length, uint color, uint const_alpha)
-{
- if ((const_alpha & qAlpha(color)) == 255) {
- QT_MEMFILL_UINT(dest, length, color);
- } else {
- if (const_alpha != 255)
- color = BYTE_MUL(color, const_alpha);
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = color + BYTE_MUL(dest[i], qAlpha(~color));
- }
- }
-}
-
-void QT_FASTCALL comp_func_SourceOver(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = src[i];
- if (s >= 0xff000000)
- dest[i] = s;
- else if (s != 0)
- dest[i] = s + BYTE_MUL(dest[i], qAlpha(~s));
- }
- } else {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = BYTE_MUL(src[i], const_alpha);
- dest[i] = s + BYTE_MUL(dest[i], qAlpha(~s));
- }
- }
-}
-
-/*
- result = d + s * dia
- dest = (d + s * dia) * ca + d * cia
- = d + s * dia * ca
-*/
-void QT_FASTCALL comp_func_solid_DestinationOver(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha != 255)
- color = BYTE_MUL(color, const_alpha);
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- dest[i] = d + BYTE_MUL(color, qAlpha(~d));
- }
-}
-
-void QT_FASTCALL comp_func_DestinationOver(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- dest[i] = d + BYTE_MUL(src[i], qAlpha(~d));
- }
- } else {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = BYTE_MUL(src[i], const_alpha);
- dest[i] = d + BYTE_MUL(s, qAlpha(~d));
- }
- }
-}
-
-/*
- result = s * da
- dest = s * da * ca + d * cia
-*/
-void QT_FASTCALL comp_func_solid_SourceIn(uint *dest, int length, uint color, uint const_alpha)
-{
- PRELOAD_INIT(dest)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = BYTE_MUL(color, qAlpha(dest[i]));
- }
- } else {
- color = BYTE_MUL(color, const_alpha);
- uint cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(d), d, cia);
- }
- }
-}
-
-void QT_FASTCALL comp_func_SourceIn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- dest[i] = BYTE_MUL(src[i], qAlpha(dest[i]));
- }
- } else {
- uint cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = BYTE_MUL(src[i], const_alpha);
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, cia);
- }
- }
-}
-
-/*
- result = d * sa
- dest = d * sa * ca + d * cia
- = d * (sa * ca + cia)
-*/
-void QT_FASTCALL comp_func_solid_DestinationIn(uint *dest, int length, uint color, uint const_alpha)
-{
- uint a = qAlpha(color);
- if (const_alpha != 255) {
- a = BYTE_MUL(a, const_alpha) + 255 - const_alpha;
- }
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = BYTE_MUL(dest[i], a);
- }
-}
-
-void QT_FASTCALL comp_func_DestinationIn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- dest[i] = BYTE_MUL(dest[i], qAlpha(src[i]));
- }
- } else {
- int cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint a = BYTE_MUL(qAlpha(src[i]), const_alpha) + cia;
- dest[i] = BYTE_MUL(dest[i], a);
- }
- }
-}
-
-/*
- result = s * dia
- dest = s * dia * ca + d * cia
-*/
-
-void QT_FASTCALL comp_func_solid_SourceOut(uint *dest, int length, uint color, uint const_alpha)
-{
- PRELOAD_INIT(dest)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = BYTE_MUL(color, qAlpha(~dest[i]));
- }
- } else {
- color = BYTE_MUL(color, const_alpha);
- int cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(~d), d, cia);
- }
- }
-}
-
-void QT_FASTCALL comp_func_SourceOut(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- dest[i] = BYTE_MUL(src[i], qAlpha(~dest[i]));
- }
- } else {
- int cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = BYTE_MUL(src[i], const_alpha);
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, cia);
- }
- }
-}
-
-/*
- result = d * sia
- dest = d * sia * ca + d * cia
- = d * (sia * ca + cia)
-*/
-void QT_FASTCALL comp_func_solid_DestinationOut(uint *dest, int length, uint color, uint const_alpha)
-{
- uint a = qAlpha(~color);
- if (const_alpha != 255)
- a = BYTE_MUL(a, const_alpha) + 255 - const_alpha;
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = BYTE_MUL(dest[i], a);
- }
-}
-
-void QT_FASTCALL comp_func_DestinationOut(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- dest[i] = BYTE_MUL(dest[i], qAlpha(~src[i]));
- }
- } else {
- int cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint sia = BYTE_MUL(qAlpha(~src[i]), const_alpha) + cia;
- dest[i] = BYTE_MUL(dest[i], sia);
- }
- }
-}
-
-/*
- result = s*da + d*sia
- dest = s*da*ca + d*sia*ca + d *cia
- = s*ca * da + d * (sia*ca + cia)
- = s*ca * da + d * (1 - sa*ca)
-*/
-void QT_FASTCALL comp_func_solid_SourceAtop(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha != 255) {
- color = BYTE_MUL(color, const_alpha);
- }
- uint sia = qAlpha(~color);
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(dest[i]), dest[i], sia);
- }
-}
-
-void QT_FASTCALL comp_func_SourceAtop(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = src[i];
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, qAlpha(~s));
- }
- } else {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = BYTE_MUL(src[i], const_alpha);
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(d), d, qAlpha(~s));
- }
- }
-}
-
-/*
- result = d*sa + s*dia
- dest = d*sa*ca + s*dia*ca + d *cia
- = s*ca * dia + d * (sa*ca + cia)
-*/
-void QT_FASTCALL comp_func_solid_DestinationAtop(uint *dest, int length, uint color, uint const_alpha)
-{
- uint a = qAlpha(color);
- if (const_alpha != 255) {
- color = BYTE_MUL(color, const_alpha);
- a = qAlpha(color) + 255 - const_alpha;
- }
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(d, a, color, qAlpha(~d));
- }
-}
-
-void QT_FASTCALL comp_func_DestinationAtop(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = src[i];
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(d, qAlpha(s), s, qAlpha(~d));
- }
- } else {
- int cia = 255 - const_alpha;
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint s = BYTE_MUL(src[i], const_alpha);
- uint d = dest[i];
- uint a = qAlpha(s) + cia;
- dest[i] = INTERPOLATE_PIXEL_255(d, a, s, qAlpha(~d));
- }
- }
-}
-
-/*
- result = d*sia + s*dia
- dest = d*sia*ca + s*dia*ca + d *cia
- = s*ca * dia + d * (sia*ca + cia)
- = s*ca * dia + d * (1 - sa*ca)
-*/
-void QT_FASTCALL comp_func_solid_XOR(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha != 255)
- color = BYTE_MUL(color, const_alpha);
- uint sia = qAlpha(~color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- dest[i] = INTERPOLATE_PIXEL_255(color, qAlpha(~d), d, sia);
- }
-}
-
-void QT_FASTCALL comp_func_XOR(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- PRELOAD_INIT2(dest, src)
- if (const_alpha == 255) {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, qAlpha(~s));
- }
- } else {
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = BYTE_MUL(src[i], const_alpha);
- dest[i] = INTERPOLATE_PIXEL_255(s, qAlpha(~d), d, qAlpha(~s));
- }
- }
-}
-
-struct QFullCoverage {
- inline void store(uint *dest, const uint src) const
- {
- *dest = src;
- }
-};
-
-struct QPartialCoverage {
- inline QPartialCoverage(uint const_alpha)
- : ca(const_alpha)
- , ica(255 - const_alpha)
- {
- }
-
- inline void store(uint *dest, const uint src) const
- {
- *dest = INTERPOLATE_PIXEL_255(src, ca, *dest, ica);
- }
-
-private:
- const uint ca;
- const uint ica;
-};
-
-static inline int mix_alpha(int da, int sa)
-{
- return 255 - ((255 - sa) * (255 - da) >> 8);
-}
-
-/*
- Dca' = Sca.Da + Dca.Sa + Sca.(1 - Da) + Dca.(1 - Sa)
- = Sca + Dca
-*/
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Plus_impl(uint *dest, int length, uint color, const T &coverage)
-{
- uint s = color;
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- d = comp_func_Plus_one_pixel(d, s);
- coverage.store(&dest[i], d);
- }
-}
-
-void QT_FASTCALL comp_func_solid_Plus(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Plus_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Plus_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Plus_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- d = comp_func_Plus_one_pixel(d, s);
-
- coverage.store(&dest[i], d);
- }
-}
-
-void QT_FASTCALL comp_func_Plus(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Plus_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Plus_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline int multiply_op(int dst, int src, int da, int sa)
-{
- return qt_div_255(src * dst + src * (255 - da) + dst * (255 - sa));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Multiply_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) multiply_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Multiply(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Multiply_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Multiply_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Multiply_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) multiply_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Multiply(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Multiply_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Multiply_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = (Sca.Da + Dca.Sa - Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa)
- = Sca + Dca - Sca.Dca
-*/
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Screen_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) 255 - qt_div_255((255-a) * (255-b))
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Screen(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Screen_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Screen_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Screen_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) 255 - (((255-a) * (255-b)) >> 8)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Screen(uint *dest, const uint *src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Screen_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Screen_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- if 2.Dca < Da
- Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise
- Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline int overlay_op(int dst, int src, int da, int sa)
-{
- const int temp = src * (255 - da) + dst * (255 - sa);
- if (2 * dst < da)
- return qt_div_255(2 * src * dst + temp);
- else
- return qt_div_255(sa * da - 2 * (da - dst) * (sa - src) + temp);
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Overlay_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) overlay_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Overlay(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Overlay_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Overlay_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Overlay_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) overlay_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Overlay(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Overlay_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Overlay_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = min(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
- Da' = Sa + Da - Sa.Da
-*/
-static inline int darken_op(int dst, int src, int da, int sa)
-{
- return qt_div_255(qMin(src * da, dst * sa) + src * (255 - da) + dst * (255 - sa));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Darken_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) darken_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Darken(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Darken_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Darken_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Darken_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) darken_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Darken(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Darken_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Darken_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = max(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
- Da' = Sa + Da - Sa.Da
-*/
-static inline int lighten_op(int dst, int src, int da, int sa)
-{
- return qt_div_255(qMax(src * da, dst * sa) + src * (255 - da) + dst * (255 - sa));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Lighten_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) lighten_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Lighten(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Lighten_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Lighten_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Lighten_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) lighten_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Lighten(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Lighten_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Lighten_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- if Sca.Da + Dca.Sa >= Sa.Da
- Dca' = Sa.Da + Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise
- Dca' = Dca.Sa/(1-Sca/Sa) + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline int color_dodge_op(int dst, int src, int da, int sa)
-{
- const int sa_da = sa * da;
- const int dst_sa = dst * sa;
- const int src_da = src * da;
-
- const int temp = src * (255 - da) + dst * (255 - sa);
- if (src_da + dst_sa >= sa_da)
- return qt_div_255(sa_da + temp);
- else
- return qt_div_255(255 * dst_sa / (255 - 255 * src / sa) + temp);
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_ColorDodge_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a,b) color_dodge_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_ColorDodge(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_ColorDodge_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_ColorDodge_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_ColorDodge_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) color_dodge_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_ColorDodge(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_ColorDodge_impl(dest, src, length, QFullCoverage());
- else
- comp_func_ColorDodge_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- if Sca.Da + Dca.Sa <= Sa.Da
- Dca' = Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise
- Dca' = Sa.(Sca.Da + Dca.Sa - Sa.Da)/Sca + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline int color_burn_op(int dst, int src, int da, int sa)
-{
- const int src_da = src * da;
- const int dst_sa = dst * sa;
- const int sa_da = sa * da;
-
- const int temp = src * (255 - da) + dst * (255 - sa);
-
- if (src == 0 || src_da + dst_sa <= sa_da)
- return qt_div_255(temp);
- return qt_div_255(sa * (src_da + dst_sa - sa_da) / src + temp);
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_ColorBurn_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) color_burn_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_ColorBurn(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_ColorBurn_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_ColorBurn_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_ColorBurn_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) color_burn_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_ColorBurn(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_ColorBurn_impl(dest, src, length, QFullCoverage());
- else
- comp_func_ColorBurn_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- if 2.Sca < Sa
- Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise
- Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline uint hardlight_op(int dst, int src, int da, int sa)
-{
- const uint temp = src * (255 - da) + dst * (255 - sa);
-
- if (2 * src < sa)
- return qt_div_255(2 * src * dst + temp);
- else
- return qt_div_255(sa * da - 2 * (da - dst) * (sa - src) + temp);
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_HardLight_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) hardlight_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_HardLight(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_HardLight_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_HardLight_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_HardLight_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) hardlight_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_HardLight(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_HardLight_impl(dest, src, length, QFullCoverage());
- else
- comp_func_HardLight_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- if 2.Sca <= Sa
- Dca' = Dca.(Sa + (2.Sca - Sa).(1 - Dca/Da)) + Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise if 2.Sca > Sa and 4.Dca <= Da
- Dca' = Dca.Sa + Da.(2.Sca - Sa).(4.Dca/Da.(4.Dca/Da + 1).(Dca/Da - 1) + 7.Dca/Da) + Sca.(1 - Da) + Dca.(1 - Sa)
- otherwise if 2.Sca > Sa and 4.Dca > Da
- Dca' = Dca.Sa + Da.(2.Sca - Sa).((Dca/Da)^0.5 - Dca/Da) + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-static inline int soft_light_op(int dst, int src, int da, int sa)
-{
- const int src2 = src << 1;
- const int dst_np = da != 0 ? (255 * dst) / da : 0;
- const int temp = (src * (255 - da) + dst * (255 - sa)) * 255;
-
- if (src2 < sa)
- return (dst * (sa * 255 + (src2 - sa) * (255 - dst_np)) + temp) / 65025;
- else if (4 * dst <= da)
- return (dst * sa * 255 + da * (src2 - sa) * ((((16 * dst_np - 12 * 255) * dst_np + 3 * 65025) * dst_np) / 65025) + temp) / 65025;
- else {
- return (dst * sa * 255 + da * (src2 - sa) * (int(qSqrt(qreal(dst_np * 255))) - dst_np) + temp) / 65025;
- }
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_SoftLight_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) soft_light_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_SoftLight(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_SoftLight_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_SoftLight_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_SoftLight_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) soft_light_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_SoftLight(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_SoftLight_impl(dest, src, length, QFullCoverage());
- else
- comp_func_SoftLight_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = abs(Dca.Sa - Sca.Da) + Sca.(1 - Da) + Dca.(1 - Sa)
- = Sca + Dca - 2.min(Sca.Da, Dca.Sa)
-*/
-static inline int difference_op(int dst, int src, int da, int sa)
-{
- return src + dst - qt_div_255(2 * qMin(src * da, dst * sa));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_solid_Difference_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) difference_op(a, b, da, sa)
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Difference(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Difference_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Difference_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Difference_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) difference_op(a, b, da, sa)
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Difference(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Difference_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Difference_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-/*
- Dca' = (Sca.Da + Dca.Sa - 2.Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa)
-*/
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void QT_FASTCALL comp_func_solid_Exclusion_impl(uint *dest, int length, uint color, const T &coverage)
-{
- int sa = qAlpha(color);
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
-
- PRELOAD_INIT(dest)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND(dest)
- uint d = dest[i];
- int da = qAlpha(d);
-
-#define OP(a, b) (a + b - qt_div_255(2*(a*b)))
- int r = OP( qRed(d), sr);
- int b = OP( qBlue(d), sb);
- int g = OP(qGreen(d), sg);
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_solid_Exclusion(uint *dest, int length, uint color, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_solid_Exclusion_impl(dest, length, color, QFullCoverage());
- else
- comp_func_solid_Exclusion_impl(dest, length, color, QPartialCoverage(const_alpha));
-}
-
-template <typename T>
-Q_STATIC_TEMPLATE_FUNCTION inline void comp_func_Exclusion_impl(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, const T &coverage)
-{
- PRELOAD_INIT2(dest, src)
- for (int i = 0; i < length; ++i) {
- PRELOAD_COND2(dest, src)
- uint d = dest[i];
- uint s = src[i];
-
- int da = qAlpha(d);
- int sa = qAlpha(s);
-
-#define OP(a, b) (a + b - ((a*b) >> 7))
- int r = OP( qRed(d), qRed(s));
- int b = OP( qBlue(d), qBlue(s));
- int g = OP(qGreen(d), qGreen(s));
- int a = mix_alpha(da, sa);
-#undef OP
-
- coverage.store(&dest[i], qRgba(r, g, b, a));
- }
-}
-
-void QT_FASTCALL comp_func_Exclusion(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha)
-{
- if (const_alpha == 255)
- comp_func_Exclusion_impl(dest, src, length, QFullCoverage());
- else
- comp_func_Exclusion_impl(dest, src, length, QPartialCoverage(const_alpha));
-}
-
-void QT_FASTCALL rasterop_solid_SourceOrDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--)
- *dest++ |= color;
-}
-
-void QT_FASTCALL rasterop_SourceOrDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--)
- *dest++ |= *src++;
-}
-
-void QT_FASTCALL rasterop_solid_SourceAndDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color |= 0xff000000;
- while (length--)
- *dest++ &= color;
-}
-
-void QT_FASTCALL rasterop_SourceAndDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (*src & *dest) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_SourceXorDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color &= 0x00ffffff;
- while (length--)
- *dest++ ^= color;
-}
-
-void QT_FASTCALL rasterop_SourceXorDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (*src ^ *dest) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_NotSourceAndNotDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color = ~color;
- while (length--) {
- *dest = (color & ~(*dest)) | 0xff000000;
- ++dest;
- }
-}
-
-void QT_FASTCALL rasterop_NotSourceAndNotDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (~(*src) & ~(*dest)) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_NotSourceOrNotDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color = ~color | 0xff000000;
- while (length--) {
- *dest = color | ~(*dest);
- ++dest;
- }
-}
-
-void QT_FASTCALL rasterop_NotSourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = ~(*src) | ~(*dest) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_NotSourceXorDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color = ~color & 0x00ffffff;
- while (length--) {
- *dest = color ^ (*dest);
- ++dest;
- }
-}
-
-void QT_FASTCALL rasterop_NotSourceXorDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = ((~(*src)) ^ (*dest)) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_NotSource(uint *dest, int length,
- uint color, uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- qt_memfill(dest, ~color | 0xff000000, length);
-}
-
-void QT_FASTCALL rasterop_NotSource(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src,
- int length, uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--)
- *dest++ = ~(*src++) | 0xff000000;
-}
-
-void QT_FASTCALL rasterop_solid_NotSourceAndDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- color = ~color | 0xff000000;
- while (length--) {
- *dest = color & *dest;
- ++dest;
- }
-}
-
-void QT_FASTCALL rasterop_NotSourceAndDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (~(*src) & *dest) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_SourceAndNotDestination(uint *dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (color & ~(*dest)) | 0xff000000;
- ++dest;
- }
-}
-
-void QT_FASTCALL rasterop_SourceAndNotDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (*src & ~(*dest)) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_NotSourceOrDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (~(*src) | *dest) | 0xff000000;
- ++dest; ++src;
- }
-}
-
-void QT_FASTCALL rasterop_solid_NotSourceOrDestination(uint *Q_DECL_RESTRICT dest,
- int length,
- uint color,
- uint const_alpha)
+static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Operator *, const QSpanData *data,
+ int y, int x, int length)
{
- Q_UNUSED(const_alpha);
- color = ~color | 0xff000000;
- while (length--)
- *dest++ |= color;
+ return qt_fetch_conical_gradient_template<GradientBase32, uint>(buffer, data, y, x, length);
}
-void QT_FASTCALL rasterop_SourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
+static const QRgba64 * QT_FASTCALL qt_fetch_conical_gradient_rgb64(QRgba64 *buffer, const Operator *, const QSpanData *data,
+ int y, int x, int length)
{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (*src | ~(*dest)) | 0xff000000;
- ++dest; ++src;
- }
+ return qt_fetch_conical_gradient_template<GradientBase64, QRgba64>(buffer, data, y, x, length);
}
-void QT_FASTCALL rasterop_solid_SourceOrNotDestination(uint *Q_DECL_RESTRICT dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(const_alpha);
- while (length--) {
- *dest = (color | ~(*dest)) | 0xff000000;
- ++dest;
- }
-}
+extern CompositionFunctionSolid qt_functionForModeSolid_C[];
+extern CompositionFunctionSolid64 qt_functionForModeSolid64_C[];
-void QT_FASTCALL rasterop_ClearDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(src);
- comp_func_solid_SourceOver (dest, length, 0xff000000, const_alpha);
-}
-
-void QT_FASTCALL rasterop_solid_ClearDestination(uint *Q_DECL_RESTRICT dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(color);
- comp_func_solid_SourceOver (dest, length, 0xff000000, const_alpha);
-}
-
-void QT_FASTCALL rasterop_SetDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(src);
- comp_func_solid_SourceOver (dest, length, 0xffffffff, const_alpha);
-}
-
-void QT_FASTCALL rasterop_solid_SetDestination(uint *Q_DECL_RESTRICT dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(color);
- comp_func_solid_SourceOver (dest, length, 0xffffffff, const_alpha);
-}
-
-void QT_FASTCALL rasterop_NotDestination(uint *Q_DECL_RESTRICT dest,
- const uint *Q_DECL_RESTRICT src,
- int length,
- uint const_alpha)
-{
- Q_UNUSED(src);
- rasterop_solid_SourceXorDestination (dest, length, 0x00ffffff, const_alpha);
-}
-
-void QT_FASTCALL rasterop_solid_NotDestination(uint *Q_DECL_RESTRICT dest,
- int length,
- uint color,
- uint const_alpha)
-{
- Q_UNUSED(color);
- rasterop_solid_SourceXorDestination (dest, length, 0x00ffffff, const_alpha);
-}
-
-static CompositionFunctionSolid functionForModeSolid_C[] = {
- comp_func_solid_SourceOver,
- comp_func_solid_DestinationOver,
- comp_func_solid_Clear,
- comp_func_solid_Source,
- comp_func_solid_Destination,
- comp_func_solid_SourceIn,
- comp_func_solid_DestinationIn,
- comp_func_solid_SourceOut,
- comp_func_solid_DestinationOut,
- comp_func_solid_SourceAtop,
- comp_func_solid_DestinationAtop,
- comp_func_solid_XOR,
- comp_func_solid_Plus,
- comp_func_solid_Multiply,
- comp_func_solid_Screen,
- comp_func_solid_Overlay,
- comp_func_solid_Darken,
- comp_func_solid_Lighten,
- comp_func_solid_ColorDodge,
- comp_func_solid_ColorBurn,
- comp_func_solid_HardLight,
- comp_func_solid_SoftLight,
- comp_func_solid_Difference,
- comp_func_solid_Exclusion,
- rasterop_solid_SourceOrDestination,
- rasterop_solid_SourceAndDestination,
- rasterop_solid_SourceXorDestination,
- rasterop_solid_NotSourceAndNotDestination,
- rasterop_solid_NotSourceOrNotDestination,
- rasterop_solid_NotSourceXorDestination,
- rasterop_solid_NotSource,
- rasterop_solid_NotSourceAndDestination,
- rasterop_solid_SourceAndNotDestination,
- rasterop_solid_NotSourceOrDestination,
- rasterop_solid_SourceOrNotDestination,
- rasterop_solid_ClearDestination,
- rasterop_solid_SetDestination,
- rasterop_solid_NotDestination
-};
+static const CompositionFunctionSolid *functionForModeSolid = qt_functionForModeSolid_C;
+static const CompositionFunctionSolid64 *functionForModeSolid64 = qt_functionForModeSolid64_C;
-static const CompositionFunctionSolid *functionForModeSolid = functionForModeSolid_C;
-
-static CompositionFunction functionForMode_C[] = {
- comp_func_SourceOver,
- comp_func_DestinationOver,
- comp_func_Clear,
- comp_func_Source,
- comp_func_Destination,
- comp_func_SourceIn,
- comp_func_DestinationIn,
- comp_func_SourceOut,
- comp_func_DestinationOut,
- comp_func_SourceAtop,
- comp_func_DestinationAtop,
- comp_func_XOR,
- comp_func_Plus,
- comp_func_Multiply,
- comp_func_Screen,
- comp_func_Overlay,
- comp_func_Darken,
- comp_func_Lighten,
- comp_func_ColorDodge,
- comp_func_ColorBurn,
- comp_func_HardLight,
- comp_func_SoftLight,
- comp_func_Difference,
- comp_func_Exclusion,
- rasterop_SourceOrDestination,
- rasterop_SourceAndDestination,
- rasterop_SourceXorDestination,
- rasterop_NotSourceAndNotDestination,
- rasterop_NotSourceOrNotDestination,
- rasterop_NotSourceXorDestination,
- rasterop_NotSource,
- rasterop_NotSourceAndDestination,
- rasterop_SourceAndNotDestination,
- rasterop_NotSourceOrDestination,
- rasterop_SourceOrNotDestination,
- rasterop_ClearDestination,
- rasterop_SetDestination,
- rasterop_NotDestination
-};
+extern CompositionFunction qt_functionForMode_C[];
+extern CompositionFunction64 qt_functionForMode64_C[];
-static const CompositionFunction *functionForMode = functionForMode_C;
+static const CompositionFunction *functionForMode = qt_functionForMode_C;
+static const CompositionFunction64 *functionForMode64 = qt_functionForMode64_C;
static TextureBlendType getBlendType(const QSpanData *data)
{
@@ -4280,26 +3743,34 @@ static inline Operator getOperator(const QSpanData *data, const QSpan *spans, in
switch(data->type) {
case QSpanData::Solid:
- solidSource = (qAlpha(data->solid.color) == 255);
+ solidSource = data->solid.color.isOpaque();
+ op.srcFetch = 0;
+ op.srcFetch64 = 0;
break;
case QSpanData::LinearGradient:
solidSource = !data->gradient.alphaColor;
getLinearGradientValues(&op.linear, data);
- op.src_fetch = qt_fetch_linear_gradient;
+ op.srcFetch = qt_fetch_linear_gradient;
+ op.srcFetch64 = qt_fetch_linear_gradient_rgb64;
break;
case QSpanData::RadialGradient:
solidSource = !data->gradient.alphaColor;
getRadialGradientValues(&op.radial, data);
- op.src_fetch = qt_fetch_radial_gradient;
+ op.srcFetch = qt_fetch_radial_gradient;
+ op.srcFetch64 = qt_fetch_radial_gradient_rgb64;
break;
case QSpanData::ConicalGradient:
solidSource = !data->gradient.alphaColor;
- op.src_fetch = qt_fetch_conical_gradient;
+ op.srcFetch = qt_fetch_conical_gradient;
+ op.srcFetch64 = qt_fetch_conical_gradient_rgb64;
break;
case QSpanData::Texture:
- op.src_fetch = sourceFetch[getBlendType(data)][data->texture.format];
solidSource = !data->texture.hasAlpha;
+ op.srcFetch = sourceFetch[getBlendType(data)][data->texture.format];
+ op.srcFetch64 = sourceFetch64[getBlendType(data)][data->texture.format];
+ break;
default:
+ Q_UNREACHABLE();
break;
}
@@ -4307,12 +3778,13 @@ static inline Operator getOperator(const QSpanData *data, const QSpan *spans, in
if (op.mode == QPainter::CompositionMode_SourceOver && solidSource)
op.mode = QPainter::CompositionMode_Source;
- op.dest_fetch = destFetchProc[data->rasterBuffer->format];
+ op.destFetch = destFetchProc[data->rasterBuffer->format];
+ op.destFetch64 = destFetchProc64[data->rasterBuffer->format];
if (op.mode == QPainter::CompositionMode_Source) {
switch (data->rasterBuffer->format) {
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
- // don't clear dest_fetch as it sets up the pointer correctly to save one copy
+ // don't clear destFetch as it sets up the pointer correctly to save one copy
break;
default: {
if (data->type == QSpanData::Texture && data->texture.const_alpha != 256)
@@ -4327,15 +3799,18 @@ static inline Operator getOperator(const QSpanData *data, const QSpan *spans, in
++spans;
}
if (!alphaSpans)
- op.dest_fetch = 0;
+ op.destFetch = 0;
}
}
}
- op.dest_store = destStoreProc[data->rasterBuffer->format];
+ op.destStore = destStoreProc[data->rasterBuffer->format];
+ op.destStore64 = destStoreProc64[data->rasterBuffer->format];
op.funcSolid = functionForModeSolid[op.mode];
+ op.funcSolid64 = functionForModeSolid64[op.mode];
op.func = functionForMode[op.mode];
+ op.func64 = functionForMode64[op.mode];
return op;
}
@@ -4352,16 +3827,17 @@ void blend_color_generic(int count, const QSpan *spans, void *userData)
QSpanData *data = reinterpret_cast<QSpanData *>(userData);
uint buffer[buffer_size];
Operator op = getOperator(data, spans, count);
+ const uint color = data->solid.color.toArgb32();
while (count--) {
int x = spans->x;
int length = spans->len;
while (length) {
int l = qMin(buffer_size, length);
- uint *dest = op.dest_fetch ? op.dest_fetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
- op.funcSolid(dest, l, data->solid.color, spans->coverage);
- if (op.dest_store)
- op.dest_store(data->rasterBuffer, x, spans->y, dest, l);
+ uint *dest = op.destFetch ? op.destFetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
+ op.funcSolid(dest, l, color, spans->coverage);
+ if (op.destStore)
+ op.destStore(data->rasterBuffer, x, spans->y, dest, l);
length -= l;
x += l;
}
@@ -4374,15 +3850,16 @@ static void blend_color_argb(int count, const QSpan *spans, void *userData)
QSpanData *data = reinterpret_cast<QSpanData *>(userData);
Operator op = getOperator(data, spans, count);
+ const uint color = data->solid.color.toArgb32();
if (op.mode == QPainter::CompositionMode_Source) {
// inline for performance
while (count--) {
uint *target = ((uint *)data->rasterBuffer->scanLine(spans->y)) + spans->x;
if (spans->coverage == 255) {
- QT_MEMFILL_UINT(target, spans->len, data->solid.color);
+ QT_MEMFILL_UINT(target, spans->len, color);
} else {
- uint c = BYTE_MUL(data->solid.color, spans->coverage);
+ uint c = BYTE_MUL(color, spans->coverage);
int ialpha = 255 - spans->coverage;
for (int i = 0; i < spans->len; ++i)
target[i] = c + BYTE_MUL(target[i], ialpha);
@@ -4394,7 +3871,34 @@ static void blend_color_argb(int count, const QSpan *spans, void *userData)
while (count--) {
uint *target = ((uint *)data->rasterBuffer->scanLine(spans->y)) + spans->x;
- op.funcSolid(target, spans->len, data->solid.color, spans->coverage);
+ op.funcSolid(target, spans->len, color, spans->coverage);
+ ++spans;
+ }
+}
+
+void blend_color_generic_rgb64(int count, const QSpan *spans, void *userData)
+{
+ QSpanData *data = reinterpret_cast<QSpanData *>(userData);
+ Operator op = getOperator(data, spans, count);
+ if (!op.funcSolid64) {
+ qDebug() << Q_FUNC_INFO << "unsupported 64bit blend attempted";
+ return blend_color_generic(count, spans, userData);
+ }
+
+ QRgba64 buffer[buffer_size];
+ const QRgba64 color = data->solid.color;
+
+ while (count--) {
+ int x = spans->x;
+ int length = spans->len;
+ while (length) {
+ int l = qMin(buffer_size, length);
+ QRgba64 *dest = op.destFetch64(buffer, data->rasterBuffer, x, spans->y, l);
+ op.funcSolid64(dest, l, color, spans->coverage);
+ op.destStore64(data->rasterBuffer, x, spans->y, dest, l);
+ length -= l;
+ x += l;
+ }
++spans;
}
}
@@ -4409,13 +3913,12 @@ static void blend_color_rgb16(int count, const QSpan *spans, void *userData)
from qt_gradient_quint16 with minimal overhead.
*/
QPainter::CompositionMode mode = data->rasterBuffer->compositionMode;
- if (mode == QPainter::CompositionMode_SourceOver &&
- qAlpha(data->solid.color) == 255)
+ if (mode == QPainter::CompositionMode_SourceOver && data->solid.color.isOpaque())
mode = QPainter::CompositionMode_Source;
if (mode == QPainter::CompositionMode_Source) {
// inline for performance
- ushort c = qConvertRgb32To16(data->solid.color);
+ ushort c = data->solid.color.toRgb16();
while (count--) {
ushort *target = ((ushort *)data->rasterBuffer->scanLine(spans->y)) + spans->x;
if (spans->coverage == 255) {
@@ -4436,7 +3939,7 @@ static void blend_color_rgb16(int count, const QSpan *spans, void *userData)
if (mode == QPainter::CompositionMode_SourceOver) {
while (count--) {
- uint color = BYTE_MUL(data->solid.color, spans->coverage);
+ uint color = BYTE_MUL(data->solid.color.toArgb32(), spans->coverage);
int ialpha = qAlpha(~color);
ushort c = qConvertRgb32To16(color);
ushort *target = ((ushort *)data->rasterBuffer->scanLine(spans->y)) + spans->x;
@@ -4500,7 +4003,7 @@ void handleSpans(int count, const QSpan *spans, const QSpanData *data, T &handle
int process_length = l;
int process_x = x;
- const uint *src = handler.fetch(process_x, y, process_length);
+ const typename T::BlendType *src = handler.fetch(process_x, y, process_length);
int offset = 0;
while (l > 0) {
if (x == spans->x) // new span?
@@ -4525,8 +4028,10 @@ void handleSpans(int count, const QSpan *spans, const QSpanData *data, T &handle
}
}
+template<typename T>
struct QBlendBase
{
+ typedef T BlendType;
QBlendBase(QSpanData *d, Operator o)
: data(d)
, op(o)
@@ -4537,24 +4042,24 @@ struct QBlendBase
QSpanData *data;
Operator op;
- uint *dest;
+ BlendType *dest;
- uint buffer[buffer_size];
- uint src_buffer[buffer_size];
+ BlendType buffer[buffer_size];
+ BlendType src_buffer[buffer_size];
};
-class BlendSrcGeneric : public QBlendBase
+class BlendSrcGeneric : public QBlendBase<uint>
{
public:
BlendSrcGeneric(QSpanData *d, Operator o)
- : QBlendBase(d, o)
+ : QBlendBase<uint>(d, o)
{
}
const uint *fetch(int x, int y, int len)
{
- dest = op.dest_fetch ? op.dest_fetch(buffer, data->rasterBuffer, x, y, len) : buffer;
- return op.src_fetch(src_buffer, &op, data, y, x, len);
+ dest = op.destFetch ? op.destFetch(buffer, data->rasterBuffer, x, y, len) : buffer;
+ return op.srcFetch(src_buffer, &op, data, y, x, len);
}
void process(int, int, int len, int coverage, const uint *src, int offset)
@@ -4564,8 +4069,38 @@ public:
void store(int x, int y, int len)
{
- if (op.dest_store)
- op.dest_store(data->rasterBuffer, x, y, dest, len);
+ if (op.destStore)
+ op.destStore(data->rasterBuffer, x, y, dest, len);
+ }
+};
+
+class BlendSrcGenericRGB64 : public QBlendBase<QRgba64>
+{
+public:
+ BlendSrcGenericRGB64(QSpanData *d, Operator o)
+ : QBlendBase<QRgba64>(d, o)
+ {
+ }
+
+ bool isSupported() const
+ {
+ return op.func64 && op.destFetch64 && op.destStore64;
+ }
+
+ const QRgba64 *fetch(int x, int y, int len)
+ {
+ dest = op.destFetch64(buffer, data->rasterBuffer, x, y, len);
+ return op.srcFetch64(src_buffer, &op, data, y, x, len);
+ }
+
+ void process(int, int, int len, int coverage, const QRgba64 *src, int offset)
+ {
+ op.func64(dest + offset, src + offset, len, coverage);
+ }
+
+ void store(int x, int y, int len)
+ {
+ op.destStore64(data->rasterBuffer, x, y, dest, len);
}
};
@@ -4576,6 +4111,20 @@ static void blend_src_generic(int count, const QSpan *spans, void *userData)
handleSpans(count, spans, data, blend);
}
+static void blend_src_generic_rgb64(int count, const QSpan *spans, void *userData)
+{
+ QSpanData *data = reinterpret_cast<QSpanData *>(userData);
+ Operator op = getOperator(data, spans, count);
+ BlendSrcGenericRGB64 blend64(data, op);
+ if (blend64.isSupported())
+ handleSpans(count, spans, data, blend64);
+ else {
+ qDebug("blend_src_generic_rgb64: unsupported 64-bit blend attempted");
+ BlendSrcGeneric blend32(data, op);
+ handleSpans(count, spans, data, blend32);
+ }
+}
+
static void blend_untransformed_generic(int count, const QSpan *spans, void *userData)
{
QSpanData *data = reinterpret_cast<QSpanData *>(userData);
@@ -4606,11 +4155,59 @@ static void blend_untransformed_generic(int count, const QSpan *spans, void *use
const int coverage = (spans->coverage * data->texture.const_alpha) >> 8;
while (length) {
int l = qMin(buffer_size, length);
- const uint *src = op.src_fetch(src_buffer, &op, data, sy, sx, l);
- uint *dest = op.dest_fetch ? op.dest_fetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
+ const uint *src = op.srcFetch(src_buffer, &op, data, sy, sx, l);
+ uint *dest = op.destFetch ? op.destFetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
op.func(dest, src, l, coverage);
- if (op.dest_store)
- op.dest_store(data->rasterBuffer, x, spans->y, dest, l);
+ if (op.destStore)
+ op.destStore(data->rasterBuffer, x, spans->y, dest, l);
+ x += l;
+ sx += l;
+ length -= l;
+ }
+ }
+ }
+ ++spans;
+ }
+}
+
+static void blend_untransformed_generic_rgb64(int count, const QSpan *spans, void *userData)
+{
+ QSpanData *data = reinterpret_cast<QSpanData *>(userData);
+
+ Operator op = getOperator(data, spans, count);
+ if (!op.func64) {
+ qWarning() << Q_FUNC_INFO << "Unsupported blend";
+ return blend_untransformed_generic(count, spans, userData);
+ }
+ QRgba64 buffer[buffer_size];
+ QRgba64 src_buffer[buffer_size];
+
+ const int image_width = data->texture.width;
+ const int image_height = data->texture.height;
+ int xoff = -qRound(-data->dx);
+ int yoff = -qRound(-data->dy);
+
+ while (count--) {
+ int x = spans->x;
+ int length = spans->len;
+ int sx = xoff + x;
+ int sy = yoff + spans->y;
+ if (sy >= 0 && sy < image_height && sx < image_width) {
+ if (sx < 0) {
+ x -= sx;
+ length += sx;
+ sx = 0;
+ }
+ if (sx + length > image_width)
+ length = image_width - sx;
+ if (length > 0) {
+ const int coverage = (spans->coverage * data->texture.const_alpha) >> 8;
+ while (length) {
+ int l = qMin(buffer_size, length);
+ const QRgba64 *src = op.srcFetch64(src_buffer, &op, data, sy, sx, l);
+ QRgba64 *dest = op.destFetch64(buffer, data->rasterBuffer, x, spans->y, l);
+ op.func64(dest, src, l, coverage);
+ op.destStore64(data->rasterBuffer, x, spans->y, dest, l);
x += l;
sx += l;
length -= l;
@@ -4799,11 +4396,62 @@ static void blend_tiled_generic(int count, const QSpan *spans, void *userData)
int l = qMin(image_width - sx, length);
if (buffer_size < l)
l = buffer_size;
- const uint *src = op.src_fetch(src_buffer, &op, data, sy, sx, l);
- uint *dest = op.dest_fetch ? op.dest_fetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
+ const uint *src = op.srcFetch(src_buffer, &op, data, sy, sx, l);
+ uint *dest = op.destFetch ? op.destFetch(buffer, data->rasterBuffer, x, spans->y, l) : buffer;
op.func(dest, src, l, coverage);
- if (op.dest_store)
- op.dest_store(data->rasterBuffer, x, spans->y, dest, l);
+ if (op.destStore)
+ op.destStore(data->rasterBuffer, x, spans->y, dest, l);
+ x += l;
+ sx += l;
+ length -= l;
+ if (sx >= image_width)
+ sx = 0;
+ }
+ ++spans;
+ }
+}
+
+static void blend_tiled_generic_rgb64(int count, const QSpan *spans, void *userData)
+{
+ QSpanData *data = reinterpret_cast<QSpanData *>(userData);
+
+ Operator op = getOperator(data, spans, count);
+ if (!op.func64) {
+ qDebug("unsupported rgb64 blend");
+ return blend_tiled_generic(count, spans, userData);
+ }
+ QRgba64 buffer[buffer_size];
+ QRgba64 src_buffer[buffer_size];
+
+ const int image_width = data->texture.width;
+ const int image_height = data->texture.height;
+ int xoff = -qRound(-data->dx) % image_width;
+ int yoff = -qRound(-data->dy) % image_height;
+
+ if (xoff < 0)
+ xoff += image_width;
+ if (yoff < 0)
+ yoff += image_height;
+
+ while (count--) {
+ int x = spans->x;
+ int length = spans->len;
+ int sx = (xoff + spans->x) % image_width;
+ int sy = (spans->y + yoff) % image_height;
+ if (sx < 0)
+ sx += image_width;
+ if (sy < 0)
+ sy += image_height;
+
+ const int coverage = (spans->coverage * data->texture.const_alpha) >> 8;
+ while (length) {
+ int l = qMin(image_width - sx, length);
+ if (buffer_size < l)
+ l = buffer_size;
+ const QRgba64 *src = op.srcFetch64(src_buffer, &op, data, sy, sx, l);
+ QRgba64 *dest = op.destFetch64(buffer, data->rasterBuffer, x, spans->y, l);
+ op.func64(dest, src, l, coverage);
+ op.destStore64(data->rasterBuffer, x, spans->y, dest, l);
x += l;
sx += l;
length -= l;
@@ -5684,10 +5332,10 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_untransformed_generic,
blend_untransformed_generic,
blend_untransformed_generic,
- blend_untransformed_generic,
- blend_untransformed_generic,
- blend_untransformed_generic,
- blend_untransformed_generic,
+ blend_untransformed_generic_rgb64,
+ blend_untransformed_generic_rgb64,
+ blend_untransformed_generic_rgb64,
+ blend_untransformed_generic_rgb64,
blend_untransformed_generic,
blend_untransformed_generic,
},
@@ -5712,10 +5360,10 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_tiled_generic,
blend_tiled_generic,
blend_tiled_generic,
- blend_tiled_generic,
- blend_tiled_generic,
- blend_tiled_generic,
- blend_tiled_generic,
+ blend_tiled_generic_rgb64,
+ blend_tiled_generic_rgb64,
+ blend_tiled_generic_rgb64,
+ blend_tiled_generic_rgb64,
blend_tiled_generic,
blend_tiled_generic,
},
@@ -5740,10 +5388,10 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_src_generic,
blend_src_generic,
blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
blend_src_generic,
blend_src_generic,
},
@@ -5767,12 +5415,12 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_src_generic,
blend_src_generic,
blend_src_generic,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
blend_src_generic,
blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic
},
// Bilinear
{
@@ -5795,10 +5443,10 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_src_generic,
blend_src_generic,
blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic,
- blend_src_generic,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
+ blend_src_generic_rgb64,
blend_src_generic,
blend_src_generic,
},
@@ -5823,10 +5471,10 @@ static const ProcessSpans processTextureSpans[NBlendTypes][QImage::NImageFormats
blend_src_generic, // RGBX8888
blend_src_generic, // RGBA8888
blend_src_generic, // RGBA8888_Premultiplied
- blend_src_generic, // BGR30
- blend_src_generic, // A2BGR30_Premultiplied
- blend_src_generic, // RGB30
- blend_src_generic, // A2RGB30_Premultiplied
+ blend_src_generic_rgb64, // BGR30
+ blend_src_generic_rgb64, // A2BGR30_Premultiplied
+ blend_src_generic_rgb64, // RGB30
+ blend_src_generic_rgb64, // A2RGB30_Premultiplied
blend_src_generic, // Alpha8
blend_src_generic, // Grayscale8
}
@@ -5982,13 +5630,11 @@ static void qt_gradient_quint16(int count, const QSpan *spans, void *userData)
int yinc = int((linear.dy * data->m22 * gss) * FIXPT_SIZE);
int off = int((((linear.dy * (data->m22 * qreal(0.5) + data->dy) + linear.off) * gss) * FIXPT_SIZE));
- uint oldColor = data->solid.color;
+ QRgba64 oldColor = data->solid.color;
while (count--) {
int y = spans->y;
- quint32 color = qt_gradient_pixel_fixed(&data->gradient, yinc * y + off);
-
- data->solid.color = color;
+ data->solid.color = QRgba64::fromArgb32(qt_gradient_pixel_fixed(&data->gradient, yinc * y + off));
blend_color_rgb16(1, spans, userData);
++spans;
}
@@ -6000,39 +5646,49 @@ static void qt_gradient_quint16(int count, const QSpan *spans, void *userData)
}
inline static void qt_bitmapblit_argb32(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride)
{
- qt_bitmapblit_template<quint32>(rasterBuffer, x, y, color,
+ qt_bitmapblit_template<quint32>(rasterBuffer, x, y, color.toArgb32(),
map, mapWidth, mapHeight, mapStride);
}
inline static void qt_bitmapblit_rgba8888(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride)
{
- qt_bitmapblit_template<quint32>(rasterBuffer, x, y, ARGB2RGBA(color),
+ qt_bitmapblit_template<quint32>(rasterBuffer, x, y, ARGB2RGBA(color.toArgb32()),
+ map, mapWidth, mapHeight, mapStride);
+}
+
+template<QtPixelOrder PixelOrder>
+inline static void qt_bitmapblit_rgb30(QRasterBuffer *rasterBuffer,
+ int x, int y, const QRgba64 &color,
+ const uchar *map,
+ int mapWidth, int mapHeight, int mapStride)
+{
+ qt_bitmapblit_template<quint32>(rasterBuffer, x, y, qConvertRgb64ToRgb30<PixelOrder>(color),
map, mapWidth, mapHeight, mapStride);
}
inline static void qt_bitmapblit_quint16(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride)
{
- qt_bitmapblit_template<quint16>(rasterBuffer, x, y, qConvertRgb32To16(color),
+ qt_bitmapblit_template<quint16>(rasterBuffer, x, y, color.toRgb16(),
map, mapWidth, mapHeight, mapStride);
}
static void qt_alphamapblit_quint16(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride,
const QClipData *)
{
- const quint16 c = qConvertRgb32To16(color);
+ const quint16 c = color.toRgb16();
quint16 *dest = reinterpret_cast<quint16*>(rasterBuffer->scanLine(y)) + x;
const int destStride = rasterBuffer->bytesPerLine() / sizeof(quint16);
@@ -6130,7 +5786,7 @@ static inline void grayBlendPixel(quint32 *dst, int coverage, int sr, int sg, in
}
#endif
-static void qt_alphamapblit_argb32(QRasterBuffer *rasterBuffer,
+static void qt_alphamapblit_uint32(QRasterBuffer *rasterBuffer,
int x, int y, quint32 color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride,
@@ -6226,28 +5882,38 @@ static void qt_alphamapblit_argb32(QRasterBuffer *rasterBuffer,
}
}
+
+static void qt_alphamapblit_argb32(QRasterBuffer *rasterBuffer,
+ int x, int y, const QRgba64 &color,
+ const uchar *map,
+ int mapWidth, int mapHeight, int mapStride,
+ const QClipData *clip)
+{
+ qt_alphamapblit_uint32(rasterBuffer, x, y, color.toArgb32(), map, mapWidth, mapHeight, mapStride, clip);
+}
+
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
static void qt_alphamapblit_rgba8888(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *map,
int mapWidth, int mapHeight, int mapStride,
const QClipData *clip)
{
- qt_alphamapblit_argb32(rasterBuffer, x, y, ARGB2RGBA(color), map, mapWidth, mapHeight, mapStride, clip);
+ qt_alphamapblit_uint32(rasterBuffer, x, y, ARGB2RGBA(color.toArgb32()), map, mapWidth, mapHeight, mapStride, clip);
}
#endif
static void qt_alphargbblit_argb32(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uint *src, int mapWidth, int mapHeight, int srcStride,
const QClipData *clip)
{
- const quint32 c = color;
+ const quint32 c = color.toArgb32();
- int sr = qRed(color);
- int sg = qGreen(color);
- int sb = qBlue(color);
- int sa = qAlpha(color);
+ int sr = qRed(c);
+ int sg = qGreen(c);
+ int sb = qBlue(c);
+ int sa = qAlpha(c);
const QDrawHelperGammaTables *tables = QGuiApplicationPrivate::instance()->gammaTables();
if (!tables)
@@ -6314,58 +5980,67 @@ static void qt_alphargbblit_argb32(QRasterBuffer *rasterBuffer,
static void qt_rectfill_argb32(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint32>(reinterpret_cast<quint32 *>(rasterBuffer->buffer()),
- color, x, y, width, height, rasterBuffer->bytesPerLine());
+ color.toArgb32(), x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_quint16(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint16>(reinterpret_cast<quint16 *>(rasterBuffer->buffer()),
- qConvertRgb32To16(color), x, y, width, height, rasterBuffer->bytesPerLine());
+ color.toRgb16(), x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_nonpremul_argb32(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint32>(reinterpret_cast<quint32 *>(rasterBuffer->buffer()),
- qUnpremultiply(color), x, y, width, height, rasterBuffer->bytesPerLine());
+ color.unpremultiplied().toArgb32(), x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_rgba(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint32>(reinterpret_cast<quint32 *>(rasterBuffer->buffer()),
- ARGB2RGBA(color), x, y, width, height, rasterBuffer->bytesPerLine());
+ ARGB2RGBA(color.toArgb32()), x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_nonpremul_rgba(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
+{
+ qt_rectfill<quint32>(reinterpret_cast<quint32 *>(rasterBuffer->buffer()),
+ ARGB2RGBA(color.unpremultiplied().toArgb32()), x, y, width, height, rasterBuffer->bytesPerLine());
+}
+
+template<QtPixelOrder PixelOrder>
+static void qt_rectfill_rgb30(QRasterBuffer *rasterBuffer,
+ int x, int y, int width, int height,
+ const QRgba64 &color)
{
qt_rectfill<quint32>(reinterpret_cast<quint32 *>(rasterBuffer->buffer()),
- ARGB2RGBA(qUnpremultiply(color)), x, y, width, height, rasterBuffer->bytesPerLine());
+ qConvertRgb64ToRgb30<PixelOrder>(color), x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_alpha(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint8>(reinterpret_cast<quint8 *>(rasterBuffer->buffer()),
- qAlpha(color), x, y, width, height, rasterBuffer->bytesPerLine());
+ color.alpha() >> 8, x, y, width, height, rasterBuffer->bytesPerLine());
}
static void qt_rectfill_gray(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color)
+ const QRgba64 &color)
{
qt_rectfill<quint8>(reinterpret_cast<quint8 *>(rasterBuffer->buffer()),
- qGray(color), x, y, width, height, rasterBuffer->bytesPerLine());
+ qGray(color.toArgb32()), x, y, width, height, rasterBuffer->bytesPerLine());
}
// Map table for destination image format. Contains function pointers
@@ -6518,39 +6193,39 @@ DrawHelper qDrawHelper[QImage::NImageFormats] =
},
// Format_BGR30
{
- blend_color_generic,
- blend_src_generic,
- 0,
+ blend_color_generic_rgb64,
+ blend_src_generic_rgb64,
+ qt_bitmapblit_rgb30<PixelOrderBGR>,
0,
0,
- 0
+ qt_rectfill_rgb30<PixelOrderBGR>
},
// Format_A2BGR30_Premultiplied
{
- blend_color_generic,
- blend_src_generic,
- 0,
+ blend_color_generic_rgb64,
+ blend_src_generic_rgb64,
+ qt_bitmapblit_rgb30<PixelOrderBGR>,
0,
0,
- 0
+ qt_rectfill_rgb30<PixelOrderBGR>
},
// Format_RGB30
{
- blend_color_generic,
- blend_src_generic,
- 0,
+ blend_color_generic_rgb64,
+ blend_src_generic_rgb64,
+ qt_bitmapblit_rgb30<PixelOrderRGB>,
0,
0,
- 0
+ qt_rectfill_rgb30<PixelOrderRGB>
},
// Format_A2RGB30_Premultiplied
{
- blend_color_generic,
- blend_src_generic,
- 0,
+ blend_color_generic_rgb64,
+ blend_src_generic_rgb64,
+ qt_bitmapblit_rgb30<PixelOrderRGB>,
0,
0,
- 0
+ qt_rectfill_rgb30<PixelOrderRGB>
},
// Format_Alpha8
{
@@ -6619,6 +6294,11 @@ inline void qt_memfill_template(quint16 *dest, quint16 value, int count)
}
#endif
+void qt_memfill64(quint64 *dest, quint64 color, int count)
+{
+ qt_memfill_template<quint64>(dest, color, count);
+}
+
#if !defined(__SSE2__)
void qt_memfill16(quint16 *dest, quint16 color, int count)
{
@@ -6646,9 +6326,6 @@ template<QtPixelOrder> const uint *QT_FASTCALL convertA2RGB30PMFromARGB32PM_sse4
void qInitDrawhelperAsm()
{
- CompositionFunction *functionForModeAsm = 0;
- CompositionFunctionSolid *functionForModeSolidAsm = 0;
-
const uint features = qCpuFeatures();
Q_UNUSED(features);
#ifdef __SSE2__
@@ -6735,9 +6412,15 @@ void qInitDrawhelperAsm()
qPixelLayouts[QImage::Format_RGBA8888].convertToARGB32PM = convertRGBA8888ToARGB32PM_avx2;
}
#endif
+ extern void QT_FASTCALL comp_func_SourceOver_sse2(uint *destPixels, const uint *srcPixels, int length, uint const_alpha);
+ extern void QT_FASTCALL comp_func_solid_SourceOver_sse2(uint *destPixels, int length, uint color, uint const_alpha);
+ extern void QT_FASTCALL comp_func_Source_sse2(uint *destPixels, const uint *srcPixels, int length, uint const_alpha);
+ extern void QT_FASTCALL comp_func_Plus_sse2(uint *destPixels, const uint *srcPixels, int length, uint const_alpha);
+ qt_functionForMode_C[QPainter::CompositionMode_SourceOver] = comp_func_SourceOver_sse2;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceOver] = comp_func_solid_SourceOver_sse2;
+ qt_functionForMode_C[QPainter::CompositionMode_Source] = comp_func_Source_sse2;
+ qt_functionForMode_C[QPainter::CompositionMode_Plus] = comp_func_Plus_sse2;
- functionForModeAsm = qt_functionForMode_SSE2;
- functionForModeSolidAsm = qt_functionForModeSolid_SSE2;
#endif // SSE2
#if defined(__ARM_NEON__) && !defined(Q_OS_IOS)
@@ -6763,9 +6446,9 @@ void qInitDrawhelperAsm()
qDrawHelper[QImage::Format_RGB16].alphamapBlit = qt_alphamapblit_quint16_neon;
- functionForMode_C[QPainter::CompositionMode_SourceOver] = qt_blend_argb32_on_argb32_scanline_neon;
- functionForModeSolid_C[QPainter::CompositionMode_SourceOver] = comp_func_solid_SourceOver_neon;
- functionForMode_C[QPainter::CompositionMode_Plus] = comp_func_Plus_neon;
+ qt_functionForMode_C[QPainter::CompositionMode_SourceOver] = qt_blend_argb32_on_argb32_scanline_neon;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceOver] = comp_func_solid_SourceOver_neon;
+ qt_functionForMode_C[QPainter::CompositionMode_Plus] = comp_func_Plus_neon;
destFetchProc[QImage::Format_RGB16] = qt_destFetchRGB16_neon;
destStoreProc[QImage::Format_RGB16] = qt_destStoreRGB16_neon;
@@ -6785,25 +6468,25 @@ void qInitDrawhelperAsm()
#if defined(QT_COMPILER_SUPPORTS_MIPS_DSP) || defined(QT_COMPILER_SUPPORTS_MIPS_DSPR2)
if (features & (DSP | DSPR2)) {
// Composition functions are all DSP r1
- functionForMode_C[QPainter::CompositionMode_SourceOver] = comp_func_SourceOver_asm_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_Source] = comp_func_Source_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_DestinationOver] = comp_func_DestinationOver_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_SourceIn] = comp_func_SourceIn_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_DestinationIn] = comp_func_DestinationIn_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_DestinationOut] = comp_func_DestinationOut_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_SourceAtop] = comp_func_SourceAtop_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_DestinationAtop] = comp_func_DestinationAtop_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_Xor] = comp_func_XOR_mips_dsp;
- functionForMode_C[QPainter::CompositionMode_SourceOut] = comp_func_SourceOut_mips_dsp;
-
- functionForModeSolid_C[QPainter::CompositionMode_SourceOver] = comp_func_solid_SourceOver_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_DestinationOver] = comp_func_solid_DestinationOver_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_SourceIn] = comp_func_solid_SourceIn_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_DestinationIn] = comp_func_solid_DestinationIn_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_SourceAtop] = comp_func_solid_SourceAtop_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_DestinationAtop] = comp_func_solid_DestinationAtop_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_Xor] = comp_func_solid_XOR_mips_dsp;
- functionForModeSolid_C[QPainter::CompositionMode_SourceOut] = comp_func_solid_SourceOut_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_SourceOver] = comp_func_SourceOver_asm_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_Source] = comp_func_Source_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_DestinationOver] = comp_func_DestinationOver_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_SourceIn] = comp_func_SourceIn_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_DestinationIn] = comp_func_DestinationIn_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_DestinationOut] = comp_func_DestinationOut_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_SourceAtop] = comp_func_SourceAtop_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_DestinationAtop] = comp_func_DestinationAtop_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_Xor] = comp_func_XOR_mips_dsp;
+ qt_functionForMode_C[QPainter::CompositionMode_SourceOut] = comp_func_SourceOut_mips_dsp;
+
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceOver] = comp_func_solid_SourceOver_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_DestinationOver] = comp_func_solid_DestinationOver_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceIn] = comp_func_solid_SourceIn_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_DestinationIn] = comp_func_solid_DestinationIn_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceAtop] = comp_func_solid_SourceAtop_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_DestinationAtop] = comp_func_solid_DestinationAtop_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_Xor] = comp_func_solid_XOR_mips_dsp;
+ qt_functionForModeSolid_C[QPainter::CompositionMode_SourceOut] = comp_func_solid_SourceOut_mips_dsp;
qBlendFunctions[QImage::Format_RGB32][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb32_mips_dsp;
qBlendFunctions[QImage::Format_ARGB32_Premultiplied][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb32_mips_dsp;
@@ -6830,20 +6513,6 @@ void qInitDrawhelperAsm()
#endif // QT_COMPILER_SUPPORTS_MIPS_DSPR2
}
#endif // QT_COMPILER_SUPPORTS_MIPS_DSP || QT_COMPILER_SUPPORTS_MIPS_DSPR2
-
- if (functionForModeSolidAsm) {
- const int destinationMode = QPainter::CompositionMode_Destination;
- functionForModeSolidAsm[destinationMode] = functionForModeSolid_C[destinationMode];
-
- // use the default qdrawhelper implementation for the
- // extended composition modes
- for (int mode = 12; mode < 24; ++mode)
- functionForModeSolidAsm[mode] = functionForModeSolid_C[mode];
-
- functionForModeSolid = functionForModeSolidAsm;
- }
- if (functionForModeAsm)
- functionForMode = functionForModeAsm;
}
QT_END_NAMESPACE
diff --git a/src/gui/painting/qdrawhelper_neon.cpp b/src/gui/painting/qdrawhelper_neon.cpp
index 7e12e62151..08e564f017 100644
--- a/src/gui/painting/qdrawhelper_neon.cpp
+++ b/src/gui/painting/qdrawhelper_neon.cpp
@@ -466,7 +466,7 @@ void qt_blend_rgb32_on_rgb32_neon(uchar *destPixels, int dbpl,
}
void qt_alphamapblit_quint16_neon(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *bitmap,
int mapWidth, int mapHeight, int mapStride,
const QClipData *)
@@ -475,8 +475,9 @@ void qt_alphamapblit_quint16_neon(QRasterBuffer *rasterBuffer,
const int destStride = rasterBuffer->bytesPerLine() / sizeof(quint16);
uchar *mask = const_cast<uchar *>(bitmap);
+ const uint c = color.toArgb32();
- pixman_composite_over_n_8_0565_asm_neon(mapWidth, mapHeight, dest, destStride, color, 0, mask, mapStride);
+ pixman_composite_over_n_8_0565_asm_neon(mapWidth, mapHeight, dest, destStride, c, 0, mask, mapStride);
}
extern "C" void blend_8_pixels_rgb16_on_rgb16_neon(quint16 *dst, const quint16 *src, int const_alpha);
@@ -985,7 +986,7 @@ public:
const uint * QT_FASTCALL qt_fetch_radial_gradient_neon(uint *buffer, const Operator *op, const QSpanData *data,
int y, int x, int length)
{
- return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdNeon> >(buffer, op, data, y, x, length);
+ return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdNeon>,uint>(buffer, op, data, y, x, length);
}
QT_END_NAMESPACE
diff --git a/src/gui/painting/qdrawhelper_neon_p.h b/src/gui/painting/qdrawhelper_neon_p.h
index bd030a8bf3..37e060f147 100644
--- a/src/gui/painting/qdrawhelper_neon_p.h
+++ b/src/gui/painting/qdrawhelper_neon_p.h
@@ -82,7 +82,7 @@ void qt_blend_rgb16_on_rgb16_neon(uchar *destPixels, int dbpl,
int const_alpha);
void qt_alphamapblit_quint16_neon(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *bitmap,
int mapWidth, int mapHeight, int mapStride,
const QClipData *clip);
diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h
index 73ff21812a..2fb9e7760c 100644
--- a/src/gui/painting/qdrawhelper_p.h
+++ b/src/gui/painting/qdrawhelper_p.h
@@ -50,6 +50,7 @@
#include "QtGui/qcolor.h"
#include "QtGui/qpainter.h"
#include "QtGui/qimage.h"
+#include "QtGui/qrgba64.h"
#ifndef QT_FT_BEGIN_HEADER
#define QT_FT_BEGIN_HEADER
#define QT_FT_END_HEADER
@@ -61,15 +62,12 @@ QT_BEGIN_NAMESPACE
#if defined(Q_CC_GNU)
# define Q_STATIC_TEMPLATE_FUNCTION static
-# define Q_ALWAYS_INLINE inline __attribute__((always_inline))
# define Q_DECL_RESTRICT __restrict__
#elif defined(Q_CC_MSVC)
# define Q_STATIC_TEMPLATE_FUNCTION static
-# define Q_ALWAYS_INLINE __forceinline
# define Q_DECL_RESTRICT __restrict
#else
# define Q_STATIC_TEMPLATE_FUNCTION static
-# define Q_ALWAYS_INLINE inline
# define Q_DECL_RESTRICT
#endif
@@ -99,25 +97,25 @@ class QRasterPaintEngineState;
typedef QT_FT_SpanFunc ProcessSpans;
typedef void (*BitmapBlitFunc)(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *bitmap,
int mapWidth, int mapHeight, int mapStride);
typedef void (*AlphamapBlitFunc)(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uchar *bitmap,
int mapWidth, int mapHeight, int mapStride,
const QClipData *clip);
typedef void (*AlphaRGBBlitFunc)(QRasterBuffer *rasterBuffer,
- int x, int y, quint32 color,
+ int x, int y, const QRgba64 &color,
const uint *rgbmask,
int mapWidth, int mapHeight, int mapStride,
const QClipData *clip);
typedef void (*RectFillFunc)(QRasterBuffer *rasterBuffer,
int x, int y, int width, int height,
- quint32 color);
+ const QRgba64 &color);
typedef void (*SrcOverBlendFunc)(uchar *destPixels, int dbpl,
const uchar *src, int spbl,
@@ -158,11 +156,14 @@ extern MemRotateFunc qMemRotateFunctions[QImage::NImageFormats][3];
extern DrawHelper qDrawHelper[QImage::NImageFormats];
void qBlendTexture(int count, const QSpan *spans, void *userData);
+extern void qt_memfill64(quint64 *dest, quint64 value, int count);
extern void qt_memfill32(quint32 *dest, quint32 value, int count);
extern void qt_memfill16(quint16 *dest, quint16 value, int count);
typedef void (QT_FASTCALL *CompositionFunction)(uint *Q_DECL_RESTRICT dest, const uint *Q_DECL_RESTRICT src, int length, uint const_alpha);
+typedef void (QT_FASTCALL *CompositionFunction64)(QRgba64 *Q_DECL_RESTRICT dest, const QRgba64 *Q_DECL_RESTRICT src, int length, uint const_alpha);
typedef void (QT_FASTCALL *CompositionFunctionSolid)(uint *dest, int length, uint color, uint const_alpha);
+typedef void (QT_FASTCALL *CompositionFunctionSolid64)(QRgba64 *dest, int length, QRgba64 color, uint const_alpha);
struct LinearGradientValues
{
@@ -185,17 +186,27 @@ struct RadialGradientValues
struct Operator;
typedef uint* (QT_FASTCALL *DestFetchProc)(uint *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length);
+typedef QRgba64* (QT_FASTCALL *DestFetchProc64)(QRgba64 *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length);
typedef void (QT_FASTCALL *DestStoreProc)(QRasterBuffer *rasterBuffer, int x, int y, const uint *buffer, int length);
+typedef void (QT_FASTCALL *DestStoreProc64)(QRasterBuffer *rasterBuffer, int x, int y, const QRgba64 *buffer, int length);
typedef const uint* (QT_FASTCALL *SourceFetchProc)(uint *buffer, const Operator *o, const QSpanData *data, int y, int x, int length);
+typedef const QRgba64* (QT_FASTCALL *SourceFetchProc64)(QRgba64 *buffer, const Operator *o, const QSpanData *data, int y, int x, int length);
struct Operator
{
QPainter::CompositionMode mode;
- DestFetchProc dest_fetch;
- DestStoreProc dest_store;
- SourceFetchProc src_fetch;
+ DestFetchProc destFetch;
+ DestStoreProc destStore;
+ SourceFetchProc srcFetch;
CompositionFunctionSolid funcSolid;
CompositionFunction func;
+
+ DestFetchProc64 destFetch64;
+ DestStoreProc64 destStore64;
+ SourceFetchProc64 srcFetch64;
+ CompositionFunctionSolid64 funcSolid64;
+ CompositionFunction64 func64;
+
union {
LinearGradientValues linear;
RadialGradientValues radial;
@@ -208,7 +219,7 @@ class QRasterPaintEngine;
struct QSolidData
{
- uint color;
+ QRgba64 color;
};
struct QLinearGradientData
@@ -259,7 +270,7 @@ struct QGradientData
#define GRADIENT_STOPTABLE_SIZE 1024
#define GRADIENT_STOPTABLE_SIZE_SHIFT 10
- uint* colorTable; //[GRADIENT_STOPTABLE_SIZE];
+ QRgba64* colorTable; //[GRADIENT_STOPTABLE_SIZE];
uint alphaColor : 1;
};
@@ -367,6 +378,12 @@ static inline uint qt_gradient_clamp(const QGradientData *data, int ipos)
static inline uint qt_gradient_pixel(const QGradientData *data, qreal pos)
{
int ipos = int(pos * (GRADIENT_STOPTABLE_SIZE - 1) + qreal(0.5));
+ return data->colorTable[qt_gradient_clamp(data, ipos)].toArgb32();
+}
+
+static inline const QRgba64& qt_gradient_pixel64(const QGradientData *data, qreal pos)
+{
+ int ipos = int(pos * (GRADIENT_STOPTABLE_SIZE - 1) + qreal(0.5));
return data->colorTable[qt_gradient_clamp(data, ipos)];
}
@@ -375,24 +392,24 @@ static inline qreal qRadialDeterminant(qreal a, qreal b, qreal c)
return (b * b) - (4 * a * c);
}
-template <class RadialFetchFunc> Q_STATIC_TEMPLATE_FUNCTION
-const uint * QT_FASTCALL qt_fetch_radial_gradient_template(uint *buffer, const Operator *op, const QSpanData *data,
- int y, int x, int length)
+template <class RadialFetchFunc, typename BlendType> static
+const BlendType * QT_FASTCALL qt_fetch_radial_gradient_template(BlendType *buffer, const Operator *op,
+ const QSpanData *data, int y, int x, int length)
{
// avoid division by zero
if (qFuzzyIsNull(op->radial.a)) {
- qt_memfill32(buffer, 0, length);
+ RadialFetchFunc::memfill(buffer, RadialFetchFunc::null(), length);
return buffer;
}
- const uint *b = buffer;
+ const BlendType *b = buffer;
qreal rx = data->m21 * (y + qreal(0.5))
+ data->dx + data->m11 * (x + qreal(0.5));
qreal ry = data->m22 * (y + qreal(0.5))
+ data->dy + data->m12 * (x + qreal(0.5));
bool affine = !data->m13 && !data->m23;
- uint *end = buffer + length;
+ BlendType *end = buffer + length;
if (affine) {
rx -= data->gradient.radial.focal.x;
ry -= data->gradient.radial.focal.y;
@@ -439,7 +456,7 @@ const uint * QT_FASTCALL qt_fetch_radial_gradient_template(uint *buffer, const O
qreal b = 2*(op->radial.dr*data->gradient.radial.focal.radius + gx*op->radial.dx + gy*op->radial.dy);
qreal det = qRadialDeterminant(op->radial.a, b, op->radial.sqrfr - (gx*gx + gy*gy));
- quint32 result = 0;
+ BlendType result = RadialFetchFunc::null();
if (det >= 0) {
qreal detSqrt = qSqrt(det);
@@ -449,7 +466,7 @@ const uint * QT_FASTCALL qt_fetch_radial_gradient_template(uint *buffer, const O
qreal s = qMax(s0, s1);
if (data->gradient.radial.focal.radius + op->radial.dr * s >= 0)
- result = qt_gradient_pixel(&data->gradient, s);
+ result = RadialFetchFunc::fetchSingle(data->gradient, s);
}
*buffer = result;
@@ -470,6 +487,15 @@ template <class Simd>
class QRadialFetchSimd
{
public:
+ static uint null() { return 0; }
+ static uint fetchSingle(const QGradientData& gradient, qreal v)
+ {
+ return qt_gradient_pixel(&gradient, v);
+ }
+ static void memfill(uint *buffer, uint fill, int length)
+ {
+ qt_memfill32(buffer, fill, length);
+ }
static void fetch(uint *buffer, uint *end, const Operator *op, const QSpanData *data, qreal det,
qreal delta_det, qreal delta_delta_det, qreal b, qreal delta_b)
{
@@ -526,7 +552,7 @@ public:
delta_det4_vec.v = Simd::v_add(delta_det4_vec.v, v_delta_delta_det16); \
b_vec.v = Simd::v_add(b_vec.v, v_delta_b4); \
for (int i = 0; i < 4; ++i) \
- *buffer++ = (extended_mask | v_buffer_mask.i[i]) & data->gradient.colorTable[index_vec.i[i]]; \
+ *buffer++ = (extended_mask | v_buffer_mask.i[i]) & data->gradient.colorTable[index_vec.i[i]].toArgb32(); \
}
#define FETCH_RADIAL_LOOP(FETCH_RADIAL_LOOP_CLAMP) \
@@ -680,19 +706,8 @@ static Q_ALWAYS_INLINE uint BYTE_MUL_RGB16_32(uint x, uint a) {
return t;
}
-static Q_ALWAYS_INLINE int qt_div_255(int x) { return (x + (x>>8) + 0x80) >> 8; }
-
-static Q_ALWAYS_INLINE uint BYTE_MUL_RGB30(uint x, uint a) {
- uint xa = x >> 30;
- uint xr = (x >> 20) & 0x3ff;
- uint xg = (x >> 10) & 0x3ff;
- uint xb = x & 0x3ff;
- xa = qt_div_255(xa * a);
- xr = qt_div_255(xr * a);
- xg = qt_div_255(xg * a);
- xb = qt_div_255(xb * a);
- return (xa << 30) | (xr << 20) | (xg << 10) | xb;
-}
+static Q_DECL_CONSTEXPR Q_ALWAYS_INLINE int qt_div_255(int x) { return (x + (x>>8) + 0x80) >> 8; }
+static Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_div_65535(uint x) { return (x + (x>>16) + 0x8000U) >> 16; }
static Q_ALWAYS_INLINE uint qAlphaRgb30(uint c)
{
@@ -723,6 +738,11 @@ inline quint24::operator uint() const
template <class T> Q_STATIC_TEMPLATE_FUNCTION
void qt_memfill(T *dest, T value, int count);
+template<> inline void qt_memfill(quint64 *dest, quint64 color, int count)
+{
+ qt_memfill64(dest, color, count);
+}
+
template<> inline void qt_memfill(quint32 *dest, quint32 color, int count)
{
qt_memfill32(dest, color, count);
@@ -862,6 +882,18 @@ inline QRgb qRepremultiply(QRgb p)
return qPremultiply(p);
}
+template<unsigned int Shift>
+inline QRgba64 qRepremultiply(QRgba64 p)
+{
+ const uint alpha = p.alpha();
+ if (alpha == 65535 || alpha == 0)
+ return p;
+ p = p.unpremultiplied();
+ Q_CONSTEXPR uint mult = 65535 / (65535 >> Shift);
+ p.setAlpha(mult * (alpha >> Shift));
+ return p.premultiplied();
+}
+
template<>
inline uint qConvertArgb32ToA2rgb30<PixelOrderBGR>(QRgb c)
{
@@ -924,6 +956,66 @@ inline QRgb qConvertA2rgb30ToArgb32<PixelOrderRGB>(uint c)
| ((c >> 2) & 0x000000ff);
}
+template<enum QtPixelOrder> inline QRgba64 qConvertA2rgb30ToRgb64(uint rgb);
+
+template<>
+inline QRgba64 qConvertA2rgb30ToRgb64<PixelOrderBGR>(uint rgb)
+{
+ quint16 alpha = rgb >> 30;
+ quint16 blue = (rgb >> 20) & 0x3ff;
+ quint16 green = (rgb >> 10) & 0x3ff;
+ quint16 red = rgb & 0x3ff;
+ // Expand the range.
+ alpha |= (alpha << 2);
+ alpha |= (alpha << 4);
+ alpha |= (alpha << 8);
+ red = (red << 6) | (red >> 4);
+ green = (green << 6) | (green >> 4);
+ blue = (blue << 6) | (blue >> 4);
+ return qRgba64(red, green, blue, alpha);
+}
+
+template<>
+inline QRgba64 qConvertA2rgb30ToRgb64<PixelOrderRGB>(uint rgb)
+{
+ quint16 alpha = rgb >> 30;
+ quint16 red = (rgb >> 20) & 0x3ff;
+ quint16 green = (rgb >> 10) & 0x3ff;
+ quint16 blue = rgb & 0x3ff;
+ // Expand the range.
+ alpha |= (alpha << 2);
+ alpha |= (alpha << 4);
+ alpha |= (alpha << 8);
+ red = (red << 6) | (red >> 4);
+ green = (green << 6) | (green >> 4);
+ blue = (blue << 6) | (blue >> 4);
+ return qRgba64(red, green, blue, alpha);
+}
+
+template<enum QtPixelOrder> inline unsigned int qConvertRgb64ToRgb30(QRgba64);
+
+template<>
+inline unsigned int qConvertRgb64ToRgb30<PixelOrderBGR>(QRgba64 c)
+{
+ c = qRepremultiply<14>(c);
+ const uint a = c.alpha() >> 14;
+ const uint r = c.red() >> 6;
+ const uint g = c.green() >> 6;
+ const uint b = c.blue() >> 6;
+ return (a << 30) | (b << 20) | (g << 10) | r;
+}
+
+template<>
+inline unsigned int qConvertRgb64ToRgb30<PixelOrderRGB>(QRgba64 c)
+{
+ c = qRepremultiply<14>(c);
+ const uint a = c.alpha() >> 14;
+ const uint r = c.red() >> 6;
+ const uint g = c.green() >> 6;
+ const uint b = c.blue() >> 6;
+ return (a << 30) | (r << 20) | (g << 10) | b;
+}
+
inline uint qRgbSwapRgb30(uint c)
{
const uint ag = c & 0xc00ffc00;
@@ -1025,89 +1117,11 @@ inline int comp_func_Plus_one_pixel(uint d, const uint s)
#undef MIX
#undef AMIX
-// prototypes of all the composition functions
-void QT_FASTCALL comp_func_SourceOver(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_DestinationOver(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Clear(uint *dest, const uint *, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Source(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Destination(uint *, const uint *, int, uint);
-void QT_FASTCALL comp_func_SourceIn(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_DestinationIn(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_SourceOut(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_DestinationOut(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_SourceAtop(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_DestinationAtop(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_XOR(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Plus(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Multiply(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Screen(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Overlay(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Darken(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Lighten(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_ColorDodge(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_ColorBurn(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_HardLight(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_SoftLight(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Difference(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL comp_func_Exclusion(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SourceOrDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SourceAndDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SourceXorDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSourceAndNotDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSourceOrNotDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSourceXorDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSource(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSourceAndDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SourceAndNotDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotSourceOrDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SourceOrNotDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_ClearDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_SetDestination(uint *dest, const uint *src, int length, uint const_alpha);
-void QT_FASTCALL rasterop_NotDestination(uint *dest, const uint *src, int length, uint const_alpha);
-// prototypes of all the solid composition functions
-void QT_FASTCALL comp_func_solid_SourceOver(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_DestinationOver(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Clear(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Source(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Destination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_SourceIn(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_DestinationIn(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_SourceOut(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_DestinationOut(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_SourceAtop(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_DestinationAtop(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_XOR(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Plus(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Multiply(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Screen(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Overlay(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Darken(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Lighten(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_ColorDodge(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_ColorBurn(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_HardLight(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_SoftLight(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Difference(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL comp_func_solid_Exclusion(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SourceOrDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SourceAndDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SourceXorDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSourceAndNotDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSourceOrNotDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSourceXorDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSource(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSourceAndDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SourceAndNotDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotSourceOrDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SourceOrNotDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_ClearDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_SetDestination(uint *dest, int length, uint color, uint const_alpha);
-void QT_FASTCALL rasterop_solid_NotDestination(uint *dest, int length, uint color, uint const_alpha);
-
-
struct QPixelLayout;
typedef const uint *(QT_FASTCALL *ConvertFunc)(uint *buffer, const uint *src, int count,
const QPixelLayout *layout, const QRgb *clut);
+typedef const QRgba64 *(QT_FASTCALL *ConvertFunc64)(QRgba64 *buffer, const uint *src, int count,
+ const QPixelLayout *layout, const QRgb *clut);
struct QPixelLayout
{
@@ -1137,6 +1151,7 @@ struct QPixelLayout
ConvertFunc convertToARGB32PM;
ConvertFunc convertFromARGB32PM;
ConvertFunc convertFromRGB32;
+ ConvertFunc64 convertToARGB64PM;
};
typedef const uint *(QT_FASTCALL *FetchPixelsFunc)(uint *buffer, const uchar *src, int index, int count);
diff --git a/src/gui/painting/qdrawhelper_sse2.cpp b/src/gui/painting/qdrawhelper_sse2.cpp
index 84eb3b7909..d7f3686e54 100644
--- a/src/gui/painting/qdrawhelper_sse2.cpp
+++ b/src/gui/painting/qdrawhelper_sse2.cpp
@@ -311,90 +311,6 @@ void QT_FASTCALL comp_func_solid_SourceOver_sse2(uint *destPixels, int length, u
}
}
-#ifndef QDRAWHELPER_AVX
-CompositionFunctionSolid qt_functionForModeSolid_SSE2[numCompositionFunctions] = {
- comp_func_solid_SourceOver_sse2,
- comp_func_solid_DestinationOver,
- comp_func_solid_Clear,
- comp_func_solid_Source,
- comp_func_solid_Destination,
- comp_func_solid_SourceIn,
- comp_func_solid_DestinationIn,
- comp_func_solid_SourceOut,
- comp_func_solid_DestinationOut,
- comp_func_solid_SourceAtop,
- comp_func_solid_DestinationAtop,
- comp_func_solid_XOR,
- comp_func_solid_Plus,
- comp_func_solid_Multiply,
- comp_func_solid_Screen,
- comp_func_solid_Overlay,
- comp_func_solid_Darken,
- comp_func_solid_Lighten,
- comp_func_solid_ColorDodge,
- comp_func_solid_ColorBurn,
- comp_func_solid_HardLight,
- comp_func_solid_SoftLight,
- comp_func_solid_Difference,
- comp_func_solid_Exclusion,
- rasterop_solid_SourceOrDestination,
- rasterop_solid_SourceAndDestination,
- rasterop_solid_SourceXorDestination,
- rasterop_solid_NotSourceAndNotDestination,
- rasterop_solid_NotSourceOrNotDestination,
- rasterop_solid_NotSourceXorDestination,
- rasterop_solid_NotSource,
- rasterop_solid_NotSourceAndDestination,
- rasterop_solid_SourceAndNotDestination,
- rasterop_solid_NotSourceOrDestination,
- rasterop_solid_SourceOrNotDestination,
- rasterop_solid_ClearDestination,
- rasterop_solid_SetDestination,
- rasterop_solid_NotDestination
-};
-
-CompositionFunction qt_functionForMode_SSE2[numCompositionFunctions] = {
- comp_func_SourceOver_sse2,
- comp_func_DestinationOver,
- comp_func_Clear,
- comp_func_Source_sse2,
- comp_func_Destination,
- comp_func_SourceIn,
- comp_func_DestinationIn,
- comp_func_SourceOut,
- comp_func_DestinationOut,
- comp_func_SourceAtop,
- comp_func_DestinationAtop,
- comp_func_XOR,
- comp_func_Plus_sse2,
- comp_func_Multiply,
- comp_func_Screen,
- comp_func_Overlay,
- comp_func_Darken,
- comp_func_Lighten,
- comp_func_ColorDodge,
- comp_func_ColorBurn,
- comp_func_HardLight,
- comp_func_SoftLight,
- comp_func_Difference,
- comp_func_Exclusion,
- rasterop_SourceOrDestination,
- rasterop_SourceAndDestination,
- rasterop_SourceXorDestination,
- rasterop_NotSourceAndNotDestination,
- rasterop_NotSourceOrNotDestination,
- rasterop_NotSourceXorDestination,
- rasterop_NotSource,
- rasterop_NotSourceAndDestination,
- rasterop_SourceAndNotDestination,
- rasterop_NotSourceOrDestination,
- rasterop_SourceOrNotDestination,
- rasterop_ClearDestination,
- rasterop_SetDestination,
- rasterop_NotDestination
-};
-#endif
-
void qt_memfill16(quint16 *dest, quint16 value, int count)
{
if (count < 3) {
@@ -417,7 +333,7 @@ void qt_memfill16(quint16 *dest, quint16 value, int count)
dest[count - 1] = value;
}
-void qt_bitmapblit32_sse2(QRasterBuffer *rasterBuffer, int x, int y,
+void qt_bitmapblit32_sse2_base(QRasterBuffer *rasterBuffer, int x, int y,
quint32 color,
const uchar *src, int width, int height, int stride)
{
@@ -468,18 +384,25 @@ void qt_bitmapblit32_sse2(QRasterBuffer *rasterBuffer, int x, int y,
}
}
+void qt_bitmapblit32_sse2(QRasterBuffer *rasterBuffer, int x, int y,
+ const QRgba64 &color,
+ const uchar *src, int width, int height, int stride)
+{
+ qt_bitmapblit32_sse2_base(rasterBuffer, x, y, color.toArgb32(), src, width, height, stride);
+}
+
void qt_bitmapblit8888_sse2(QRasterBuffer *rasterBuffer, int x, int y,
- quint32 color,
+ const QRgba64 &color,
const uchar *src, int width, int height, int stride)
{
- qt_bitmapblit32_sse2(rasterBuffer, x, y, ARGB2RGBA(color), src, width, height, stride);
+ qt_bitmapblit32_sse2_base(rasterBuffer, x, y, ARGB2RGBA(color.toArgb32()), src, width, height, stride);
}
void qt_bitmapblit16_sse2(QRasterBuffer *rasterBuffer, int x, int y,
- quint32 color,
+ const QRgba64 &color,
const uchar *src, int width, int height, int stride)
{
- const quint16 c = qConvertRgb32To16(color);
+ const quint16 c = qConvertRgb32To16(color.toArgb32());
quint16 *dest = reinterpret_cast<quint16*>(rasterBuffer->scanLine(y)) + x;
const int destStride = rasterBuffer->bytesPerLine() / sizeof(quint16);
@@ -543,7 +466,7 @@ public:
const uint * QT_FASTCALL qt_fetch_radial_gradient_sse2(uint *buffer, const Operator *op, const QSpanData *data,
int y, int x, int length)
{
- return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdSse2> >(buffer, op, data, y, x, length);
+ return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdSse2>,uint>(buffer, op, data, y, x, length);
}
void qt_scale_image_argb32_on_argb32_sse2(uchar *destPixels, int dbpl,
diff --git a/src/gui/painting/qdrawhelper_x86_p.h b/src/gui/painting/qdrawhelper_x86_p.h
index 4d203c4f9d..50ee83aa2c 100644
--- a/src/gui/painting/qdrawhelper_x86_p.h
+++ b/src/gui/painting/qdrawhelper_x86_p.h
@@ -53,13 +53,13 @@ QT_BEGIN_NAMESPACE
void qt_memfill32(quint32 *dest, quint32 value, int count);
void qt_memfill16(quint16 *dest, quint16 value, int count);
void qt_bitmapblit32_sse2(QRasterBuffer *rasterBuffer, int x, int y,
- quint32 color,
+ const QRgba64 &color,
const uchar *src, int width, int height, int stride);
void qt_bitmapblit8888_sse2(QRasterBuffer *rasterBuffer, int x, int y,
- quint32 color,
+ const QRgba64 &color,
const uchar *src, int width, int height, int stride);
void qt_bitmapblit16_sse2(QRasterBuffer *rasterBuffer, int x, int y,
- quint32 color,
+ const QRgba64 &color,
const uchar *src, int width, int height, int stride);
void qt_blend_argb32_on_argb32_sse2(uchar *destPixels, int dbpl,
const uchar *srcPixels, int sbpl,
diff --git a/src/gui/painting/qimagescale.cpp b/src/gui/painting/qimagescale.cpp
index 2f85e90c49..33dccc5374 100644
--- a/src/gui/painting/qimagescale.cpp
+++ b/src/gui/painting/qimagescale.cpp
@@ -77,8 +77,9 @@ QT_BEGIN_NAMESPACE
*
* Changes include formatting, namespaces and other C++'ings, removal of old
* #ifdef'ed code, and removal of unneeded border calculation code.
- * Later the code has been refactored and an SSE4.1 optimizated path have been
- * added instead of the removed MMX assembler.
+ * Later the code has been refactored, an SSE4.1 optimizated path have been
+ * added instead of the removed MMX assembler, and scaling of clipped area
+ * removed.
*
* Imlib2 is (C) Carsten Haitzler and various contributors. The MMX code
* is by Willem Monsuwe <willem@stack.nl>. All other modifications are
@@ -256,34 +257,27 @@ QImageScaleInfo* QImageScale::qimageCalcScaleInfo(const QImage &img,
static void qt_qimageScaleAARGBA_up_x_down_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
static void qt_qimageScaleAARGBA_down_x_up_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
static void qt_qimageScaleAARGBA_down_xy(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow);
+ int dw, int dh, int dow, int sow);
#if defined(QT_COMPILER_SUPPORTS_SSE4_1)
template<bool RGB>
void qt_qimageScaleAARGBA_up_x_down_y_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template<bool RGB>
void qt_qimageScaleAARGBA_down_x_up_y_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template<bool RGB>
void qt_qimageScaleAARGBA_down_xy_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
#endif
static void qt_qimageScaleAARGBA_up_xy(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -291,15 +285,14 @@ static void qt_qimageScaleAARGBA_up_xy(QImageScaleInfo *isi, unsigned int *dest,
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
/* calculate the source line we'll scan from */
- const unsigned int *sptr = ypoints[dyy + y];
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- const int yap = yapoints[dyy + y];
+ const unsigned int *sptr = ypoints[y];
+ unsigned int *dptr = dest + (y * dow);
+ const int yap = yapoints[y];
if (yap > 0) {
- for (int x = dxx; x < end; x++) {
+ for (int x = 0; x < dw; x++) {
const unsigned int *pix = sptr + xpoints[x];
const int xap = xapoints[x];
if (xap > 0)
@@ -309,7 +302,7 @@ static void qt_qimageScaleAARGBA_up_xy(QImageScaleInfo *isi, unsigned int *dest,
dptr++;
}
} else {
- for (int x = dxx; x < end; x++) {
+ for (int x = 0; x < dw; x++) {
const unsigned int *pix = sptr + xpoints[x];
const int xap = xapoints[x];
if (xap > 0)
@@ -324,39 +317,38 @@ static void qt_qimageScaleAARGBA_up_xy(QImageScaleInfo *isi, unsigned int *dest,
/* scale by area sampling */
static void qt_qimageScaleAARGBA(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow)
+ int dw, int dh, int dow, int sow)
{
/* scaling up both ways */
if (isi->xup_yup == 3) {
- qt_qimageScaleAARGBA_up_xy(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_up_xy(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down vertically */
else if (isi->xup_yup == 1) {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_up_x_down_y_sse4<false>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_up_x_down_y_sse4<false>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGBA_up_x_down_y(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_up_x_down_y(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down horizontally */
else if (isi->xup_yup == 2) {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_down_x_up_y_sse4<false>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_x_up_y_sse4<false>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGBA_down_x_up_y(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_x_up_y(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down horizontally & vertically */
else {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_down_xy_sse4<false>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_xy_sse4<false>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGBA_down_xy(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_xy(isi, dest, dw, dh, dow, sow);
}
}
@@ -382,7 +374,6 @@ inline static void qt_qimageScaleAARGBA_helper(const unsigned int *pix, int xyap
}
static void qt_qimageScaleAARGBA_up_x_down_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -390,16 +381,14 @@ static void qt_qimageScaleAARGBA_up_x_down_y(QImageScaleInfo *isi, unsigned int
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = yapoints[y] >> 16;
+ int yap = yapoints[y] & 0xffff;
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int r, g, b, a;
qt_qimageScaleAARGBA_helper(sptr, yap, Cy, sow, r, g, b, a);
@@ -423,7 +412,6 @@ static void qt_qimageScaleAARGBA_up_x_down_y(QImageScaleInfo *isi, unsigned int
}
static void qt_qimageScaleAARGBA_down_x_up_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -431,20 +419,18 @@ static void qt_qimageScaleAARGBA_down_x_up_y(QImageScaleInfo *isi, unsigned int
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
int Cx = xapoints[x] >> 16;
int xap = xapoints[x] & 0xffff;
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int r, g, b, a;
qt_qimageScaleAARGBA_helper(sptr, xap, Cx, 1, r, g, b, a);
- int yap = yapoints[dyy + y];
+ int yap = yapoints[y];
if (yap > 0) {
int rr, gg, bb, aa;
qt_qimageScaleAARGBA_helper(sptr + sow, xap, Cx, 1, rr, gg, bb, aa);
@@ -465,26 +451,23 @@ static void qt_qimageScaleAARGBA_down_x_up_y(QImageScaleInfo *isi, unsigned int
}
static void qt_qimageScaleAARGBA_down_xy(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow)
+ int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = (yapoints[y]) >> 16;
+ int yap = (yapoints[y]) & 0xffff;
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
int Cx = xapoints[x] >> 16;
int xap = xapoints[x] & 0xffff;
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int rx, gx, bx, ax;
qt_qimageScaleAARGBA_helper(sptr, xap, Cx, 1, rx, gx, bx, ax);
@@ -517,52 +500,48 @@ static void qt_qimageScaleAARGBA_down_xy(QImageScaleInfo *isi, unsigned int *des
}
static void qt_qimageScaleAARGB_up_x_down_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow);
+ int dw, int dh, int dow, int sow);
static void qt_qimageScaleAARGB_down_x_up_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow);
+ int dw, int dh, int dow, int sow);
static void qt_qimageScaleAARGB_down_xy(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow);
+ int dw, int dh, int dow, int sow);
/* scale by area sampling - IGNORE the ALPHA byte*/
static void qt_qimageScaleAARGB(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
/* scaling up both ways */
if (isi->xup_yup == 3) {
- qt_qimageScaleAARGBA_up_xy(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_up_xy(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down vertically */
else if (isi->xup_yup == 1) {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_up_x_down_y_sse4<true>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_up_x_down_y_sse4<true>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGB_up_x_down_y(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGB_up_x_down_y(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down horizontally */
else if (isi->xup_yup == 2) {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_down_x_up_y_sse4<true>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_x_up_y_sse4<true>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGB_down_x_up_y(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGB_down_x_up_y(isi, dest, dw, dh, dow, sow);
}
/* if we're scaling down horizontally & vertically */
else {
#ifdef QT_COMPILER_SUPPORTS_SSE4_1
if (qCpuHasFeature(SSE4_1))
- qt_qimageScaleAARGBA_down_xy_sse4<true>(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGBA_down_xy_sse4<true>(isi, dest, dw, dh, dow, sow);
else
#endif
- qt_qimageScaleAARGB_down_xy(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
+ qt_qimageScaleAARGB_down_xy(isi, dest, dw, dh, dow, sow);
}
}
@@ -586,24 +565,21 @@ inline static void qt_qimageScaleAARGB_helper(const unsigned int *pix, int xyap,
}
static void qt_qimageScaleAARGB_up_x_down_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow)
+ int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = yapoints[y] >> 16;
+ int yap = yapoints[y] & 0xffff;
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int r, g, b;
qt_qimageScaleAARGB_helper(sptr, yap, Cy, sow, r, g, b);
@@ -625,28 +601,25 @@ static void qt_qimageScaleAARGB_up_x_down_y(QImageScaleInfo *isi, unsigned int *
}
static void qt_qimageScaleAARGB_down_x_up_y(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow)
+ int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
int Cx = xapoints[x] >> 16;
int xap = xapoints[x] & 0xffff;
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int r, g, b;
qt_qimageScaleAARGB_helper(sptr, xap, Cx, 1, r, g, b);
- int yap = yapoints[dyy + y];
+ int yap = yapoints[y];
if (yap > 0) {
int rr, bb, gg;
qt_qimageScaleAARGB_helper(sptr + sow, xap, Cx, 1, rr, gg, bb);
@@ -664,26 +637,23 @@ static void qt_qimageScaleAARGB_down_x_up_y(QImageScaleInfo *isi, unsigned int *
}
static void qt_qimageScaleAARGB_down_xy(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy, int dw,
- int dh, int dow, int sow)
+ int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = yapoints[y] >> 16;
+ int yap = yapoints[y] & 0xffff;
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
int Cx = xapoints[x] >> 16;
int xap = xapoints[x] & 0xffff;
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
int rx, gx, bx;
qt_qimageScaleAARGB_helper(sptr, xap, Cx, 1, rx, gx, bx);
@@ -735,10 +705,10 @@ QImage qSmoothScaleImage(const QImage &src, int dw, int dh)
if (src.hasAlphaChannel())
qt_qimageScaleAARGBA(scaleinfo, (unsigned int *)buffer.scanLine(0),
- 0, 0, 0, 0, dw, dh, dw, src.bytesPerLine() / 4);
+ dw, dh, dw, src.bytesPerLine() / 4);
else
qt_qimageScaleAARGB(scaleinfo, (unsigned int *)buffer.scanLine(0),
- 0, 0, 0, 0, dw, dh, dw, src.bytesPerLine() / 4);
+ dw, dh, dw, src.bytesPerLine() / 4);
qimageFreeScaleInfo(scaleinfo);
return buffer;
diff --git a/src/gui/painting/qimagescale_sse4.cpp b/src/gui/painting/qimagescale_sse4.cpp
index 303e0fd980..8712b5d324 100644
--- a/src/gui/painting/qimagescale_sse4.cpp
+++ b/src/gui/painting/qimagescale_sse4.cpp
@@ -59,7 +59,6 @@ inline static __m128i qt_qimageScaleAARGBA_helper(const unsigned int *pix, int x
template<bool RGB>
void qt_qimageScaleAARGBA_up_x_down_y_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -67,20 +66,18 @@ void qt_qimageScaleAARGBA_up_x_down_y_sse4(QImageScaleInfo *isi, unsigned int *d
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
const __m128i v256 = _mm_set1_epi32(256);
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = yapoints[y] >> 16;
+ int yap = yapoints[y] & 0xffff;
const __m128i vCy = _mm_set1_epi32(Cy);
const __m128i vyap = _mm_set1_epi32(yap);
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
__m128i vx = qt_qimageScaleAARGBA_helper(sptr, yap, Cy, sow, vyap, vCy);
int xap = xapoints[x];
@@ -107,7 +104,6 @@ void qt_qimageScaleAARGBA_up_x_down_y_sse4(QImageScaleInfo *isi, unsigned int *d
template<bool RGB>
void qt_qimageScaleAARGBA_down_x_up_y_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -115,23 +111,21 @@ void qt_qimageScaleAARGBA_down_x_up_y_sse4(QImageScaleInfo *isi, unsigned int *d
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
- int end = dxx + dw;
-
const __m128i v256 = _mm_set1_epi32(256);
/* go through every scanline in the output buffer */
for (int y = 0; y < dh; y++) {
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
int Cx = xapoints[x] >> 16;
int xap = xapoints[x] & 0xffff;
const __m128i vCx = _mm_set1_epi32(Cx);
const __m128i vxap = _mm_set1_epi32(xap);
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
__m128i vx = qt_qimageScaleAARGBA_helper(sptr, xap, Cx, 1, vxap, vCx);
- int yap = yapoints[dyy + y];
+ int yap = yapoints[y];
if (yap > 0) {
const __m128i vyap = _mm_set1_epi32(yap);
const __m128i vinvyap = _mm_sub_epi32(v256, vyap);
@@ -155,7 +149,6 @@ void qt_qimageScaleAARGBA_down_x_up_y_sse4(QImageScaleInfo *isi, unsigned int *d
template<bool RGB>
void qt_qimageScaleAARGBA_down_xy_sse4(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow)
{
const unsigned int **ypoints = isi->ypoints;
@@ -164,20 +157,19 @@ void qt_qimageScaleAARGBA_down_xy_sse4(QImageScaleInfo *isi, unsigned int *dest,
int *yapoints = isi->yapoints;
for (int y = 0; y < dh; y++) {
- int Cy = (yapoints[dyy + y]) >> 16;
- int yap = (yapoints[dyy + y]) & 0xffff;
+ int Cy = yapoints[y] >> 16;
+ int yap = yapoints[y] & 0xffff;
const __m128i vCy = _mm_set1_epi32(Cy);
const __m128i vyap = _mm_set1_epi32(yap);
- unsigned int *dptr = dest + dx + ((y + dy) * dow);
- int end = dxx + dw;
- for (int x = dxx; x < end; x++) {
+ unsigned int *dptr = dest + (y * dow);
+ for (int x = 0; x < dw; x++) {
const int Cx = xapoints[x] >> 16;
const int xap = xapoints[x] & 0xffff;
const __m128i vCx = _mm_set1_epi32(Cx);
const __m128i vxap = _mm_set1_epi32(xap);
- const unsigned int *sptr = ypoints[dyy + y] + xpoints[x];
+ const unsigned int *sptr = ypoints[y] + xpoints[x];
__m128i vx = qt_qimageScaleAARGBA_helper(sptr, xap, Cx, 1, vxap, vCx);
__m128i vr = _mm_mullo_epi32(_mm_srli_epi32(vx, 4), vyap);
@@ -203,27 +195,21 @@ void qt_qimageScaleAARGBA_down_xy_sse4(QImageScaleInfo *isi, unsigned int *dest,
}
template void qt_qimageScaleAARGBA_up_x_down_y_sse4<false>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template void qt_qimageScaleAARGBA_up_x_down_y_sse4<true>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template void qt_qimageScaleAARGBA_down_x_up_y_sse4<false>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template void qt_qimageScaleAARGBA_down_x_up_y_sse4<true>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template void qt_qimageScaleAARGBA_down_xy_sse4<false>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
template void qt_qimageScaleAARGBA_down_xy_sse4<true>(QImageScaleInfo *isi, unsigned int *dest,
- int dxx, int dyy, int dx, int dy,
int dw, int dh, int dow, int sow);
QT_END_NAMESPACE
diff --git a/src/gui/painting/qmatrix.cpp b/src/gui/painting/qmatrix.cpp
index acedc6a7ba..e4d756c18d 100644
--- a/src/gui/painting/qmatrix.cpp
+++ b/src/gui/painting/qmatrix.cpp
@@ -31,9 +31,11 @@
**
****************************************************************************/
+#include "qmatrix.h"
+
#include "qdatastream.h"
#include "qdebug.h"
-#include "qmatrix.h"
+#include "qhashfunctions.h"
#include "qregion.h"
#include "qpainterpath.h"
#include "qpainterpath_p.h"
@@ -972,6 +974,26 @@ bool QMatrix::operator==(const QMatrix &m) const
_dy == m._dy;
}
+
+/*!
+ \since 5.6
+ \relates QMatrix
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QMatrix &key, uint seed) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(key.m11(), seed);
+ seed = hash(key.m12(), seed);
+ seed = hash(key.m21(), seed);
+ seed = hash(key.m22(), seed);
+ seed = hash(key.dx(), seed);
+ seed = hash(key.dy(), seed);
+ return seed;
+}
+
/*!
\fn bool QMatrix::operator!=(const QMatrix &matrix) const
diff --git a/src/gui/painting/qmatrix.h b/src/gui/painting/qmatrix.h
index ddffa8a8b9..809a19a0b8 100644
--- a/src/gui/painting/qmatrix.h
+++ b/src/gui/painting/qmatrix.h
@@ -92,7 +92,7 @@ public:
bool isInvertible() const { return !qFuzzyIsNull(_m11*_m22 - _m12*_m21); }
qreal determinant() const { return _m11*_m22 - _m12*_m21; }
- QMatrix inverted(bool *invertible = 0) const Q_REQUIRED_RESULT;
+ QMatrix inverted(bool *invertible = Q_NULLPTR) const Q_REQUIRED_RESULT;
bool operator==(const QMatrix &) const;
bool operator!=(const QMatrix &) const;
@@ -126,6 +126,8 @@ private:
};
Q_DECLARE_TYPEINFO(QMatrix, Q_MOVABLE_TYPE);
+Q_GUI_EXPORT Q_DECL_CONST_FUNCTION uint qHash(const QMatrix &key, uint seed = 0) Q_DECL_NOTHROW;
+
// mathematical semantics
inline QPoint operator*(const QPoint &p, const QMatrix &m)
{ return m.map(p); }
diff --git a/src/gui/painting/qpagedpaintdevice.cpp b/src/gui/painting/qpagedpaintdevice.cpp
index 3adc5e9411..547cedf51f 100644
--- a/src/gui/painting/qpagedpaintdevice.cpp
+++ b/src/gui/painting/qpagedpaintdevice.cpp
@@ -36,6 +36,10 @@
QT_BEGIN_NAMESPACE
+QPagedPaintDevicePrivate::~QPagedPaintDevicePrivate()
+{
+}
+
/*!
\class QPagedPaintDevice
\inmodule QtGui
diff --git a/src/gui/painting/qpagedpaintdevice_p.h b/src/gui/painting/qpagedpaintdevice_p.h
index 62f69747db..30b1c0a1e6 100644
--- a/src/gui/painting/qpagedpaintdevice_p.h
+++ b/src/gui/painting/qpagedpaintdevice_p.h
@@ -61,9 +61,7 @@ public:
{
}
- virtual ~QPagedPaintDevicePrivate()
- {
- }
+ virtual ~QPagedPaintDevicePrivate();
// ### Qt6 Remove these and make public class methods virtual
virtual bool setPageLayout(const QPageLayout &newPageLayout)
diff --git a/src/gui/painting/qpagelayout.h b/src/gui/painting/qpagelayout.h
index 17e5eeece2..7eac348c43 100644
--- a/src/gui/painting/qpagelayout.h
+++ b/src/gui/painting/qpagelayout.h
@@ -75,14 +75,13 @@ public:
const QMarginsF &margins, Unit units = Point,
const QMarginsF &minMargins = QMarginsF(0, 0, 0, 0));
QPageLayout(const QPageLayout &other);
- ~QPageLayout();
-
- QPageLayout &operator=(const QPageLayout &other);
- #ifdef Q_COMPILER_RVALUE_REFS
- QPageLayout &operator=(QPageLayout &&other) { swap(other); return *this; }
+#ifdef Q_COMPILER_RVALUE_REFS
+ QPageLayout &operator=(QPageLayout &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
+ QPageLayout &operator=(const QPageLayout &other);
+ ~QPageLayout();
- void swap(QPageLayout &other) { d.swap(other.d); }
+ void swap(QPageLayout &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
friend Q_GUI_EXPORT bool operator==(const QPageLayout &lhs, const QPageLayout &rhs);
bool isEquivalentTo(const QPageLayout &other) const;
diff --git a/src/gui/painting/qpagesize.h b/src/gui/painting/qpagesize.h
index 00e22a243f..9119a582ac 100644
--- a/src/gui/painting/qpagesize.h
+++ b/src/gui/painting/qpagesize.h
@@ -229,14 +229,14 @@ public:
const QString &name = QString(),
SizeMatchPolicy matchPolicy = FuzzyMatch);
QPageSize(const QPageSize &other);
- ~QPageSize();
-
- QPageSize &operator=(const QPageSize &other);
#ifdef Q_COMPILER_RVALUE_REFS
- QPageSize &operator=(QPageSize &&other) { swap(other); return *this; }
+ QPageSize &operator=(QPageSize &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
+ QPageSize &operator=(const QPageSize &other);
+ ~QPageSize();
+
- void swap(QPageSize &other) { d.swap(other.d); }
+ void swap(QPageSize &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
friend Q_GUI_EXPORT bool operator==(const QPageSize &lhs, const QPageSize &rhs);
bool isEquivalentTo(const QPageSize &other) const;
diff --git a/src/gui/painting/qpaintdevice.cpp b/src/gui/painting/qpaintdevice.cpp
index bbf8e8f170..2332d11a03 100644
--- a/src/gui/painting/qpaintdevice.cpp
+++ b/src/gui/painting/qpaintdevice.cpp
@@ -79,7 +79,13 @@ Q_GUI_EXPORT int qt_paint_device_metric(const QPaintDevice *device, QPaintDevice
int QPaintDevice::metric(PaintDeviceMetric m) const
{
+ // Fallback: A subclass has not implemented PdmDevicePixelRatioScaled but might
+ // have implemented PdmDevicePixelRatio.
+ if (m == PdmDevicePixelRatioScaled)
+ return this->metric(PdmDevicePixelRatio) * devicePixelRatioFScale();
+
qWarning("QPaintDevice::metrics: Device has no metric information");
+
if (m == PdmDpiX) {
return 72;
} else if (m == PdmDpiY) {
diff --git a/src/gui/painting/qpaintdevice.h b/src/gui/painting/qpaintdevice.h
index 4eb972786b..c360573e78 100644
--- a/src/gui/painting/qpaintdevice.h
+++ b/src/gui/painting/qpaintdevice.h
@@ -58,7 +58,8 @@ public:
PdmDpiY,
PdmPhysicalDpiX,
PdmPhysicalDpiY,
- PdmDevicePixelRatio
+ PdmDevicePixelRatio,
+ PdmDevicePixelRatioScaled
};
virtual ~QPaintDevice();
@@ -76,9 +77,11 @@ public:
int physicalDpiX() const { return metric(PdmPhysicalDpiX); }
int physicalDpiY() const { return metric(PdmPhysicalDpiY); }
int devicePixelRatio() const { return metric(PdmDevicePixelRatio); }
+ qreal devicePixelRatioF() const { return metric(PdmDevicePixelRatioScaled) / devicePixelRatioFScale(); }
int colorCount() const { return metric(PdmNumColors); }
int depth() const { return metric(PdmDepth); }
+ static inline qreal devicePixelRatioFScale() {return 10000000.0; }
protected:
QPaintDevice() Q_DECL_NOEXCEPT;
virtual int metric(PaintDeviceMetric metric) const;
@@ -87,7 +90,6 @@ protected:
virtual QPainter *sharedPainter() const;
ushort painters; // refcount
-
private:
Q_DISABLE_COPY(QPaintDevice)
diff --git a/src/gui/painting/qpaintdevice.qdoc b/src/gui/painting/qpaintdevice.qdoc
index 8db65af18e..a83acdd21a 100644
--- a/src/gui/painting/qpaintdevice.qdoc
+++ b/src/gui/painting/qpaintdevice.qdoc
@@ -286,3 +286,24 @@
Common values are 1 for normal-dpi displays and 2 for high-dpi
"retina" displays.
*/
+
+/*!
+ \fn qreal QPaintDevice::devicePixelRatioF() const
+
+ Returns the device pixel ratio for the device as a floating point number.
+
+ \since 5.6
+*/
+
+/*!
+ \fn qreal QPaintDevice::devicePixelRatioFScale()
+
+ \internal
+
+ Returns the scaling factor used for \c PdmDevicePixelRatioScaled. Classes
+ that are not QPaintDevice subclasses are implementing metric(), and need to
+ access this constant. Since it's a qreal, it cannot be an enum, and an inline
+ function is more efficient than a static member variable.
+
+ \since 5.6
+*/
diff --git a/src/gui/painting/qpaintengine.cpp b/src/gui/painting/qpaintengine.cpp
index 6ba26df3b4..ef93094387 100644
--- a/src/gui/painting/qpaintengine.cpp
+++ b/src/gui/painting/qpaintengine.cpp
@@ -968,6 +968,10 @@ QRect QPaintEngine::systemRect() const
return d_func()->systemRect;
}
+QPaintEnginePrivate::~QPaintEnginePrivate()
+{
+}
+
void QPaintEnginePrivate::drawBoxTextItem(const QPointF &p, const QTextItemInt &ti)
{
if (!ti.glyphs.numGlyphs)
diff --git a/src/gui/painting/qpaintengine.h b/src/gui/painting/qpaintengine.h
index eeca87ce16..fa3fad1caa 100644
--- a/src/gui/painting/qpaintengine.h
+++ b/src/gui/painting/qpaintengine.h
@@ -137,7 +137,7 @@ public:
PolylineMode
};
- explicit QPaintEngine(PaintEngineFeatures features=0);
+ explicit QPaintEngine(PaintEngineFeatures features=PaintEngineFeatures());
virtual ~QPaintEngine();
bool isActive() const { return active; }
@@ -220,7 +220,7 @@ public:
inline bool isExtended() const { return extended; }
protected:
- QPaintEngine(QPaintEnginePrivate &data, PaintEngineFeatures devcaps=0);
+ QPaintEngine(QPaintEnginePrivate &data, PaintEngineFeatures devcaps=PaintEngineFeatures());
QPaintEngineState *state;
PaintEngineFeatures gccaps;
diff --git a/src/gui/painting/qpaintengine_p.h b/src/gui/painting/qpaintengine_p.h
index c58662ede4..918c98997b 100644
--- a/src/gui/painting/qpaintengine_p.h
+++ b/src/gui/painting/qpaintengine_p.h
@@ -60,7 +60,8 @@ class Q_GUI_EXPORT QPaintEnginePrivate
public:
QPaintEnginePrivate() : pdev(0), q_ptr(0), currentClipDevice(0), hasSystemTransform(0),
hasSystemViewport(0) {}
- virtual ~QPaintEnginePrivate() { }
+ virtual ~QPaintEnginePrivate();
+
QPaintDevice *pdev;
QPaintEngine *q_ptr;
QRegion systemClip;
diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp
index a5957ca86e..6b8136c52d 100644
--- a/src/gui/painting/qpaintengine_raster.cpp
+++ b/src/gui/painting/qpaintengine_raster.cpp
@@ -42,7 +42,6 @@
#include <qpainterpath.h>
#include <qdebug.h>
-#include <qhash.h>
#include <qbitmap.h>
#include <qmath.h>
@@ -57,6 +56,7 @@
#include <private/qstatictext_p.h>
#include <private/qcosmeticstroker_p.h>
#include "qmemrotate_p.h"
+#include "qrgba64_p.h"
#include "qpaintengine_raster_p.h"
// #include "qbezier_p.h"
@@ -830,7 +830,7 @@ void QRasterPaintEngine::updateRasterState()
&& s->intOpacity == 256
&& (mode == QPainter::CompositionMode_Source
|| (mode == QPainter::CompositionMode_SourceOver
- && qAlpha(s->penData.solid.color) == 255));
+ && s->penData.solid.color.isOpaque()));
}
s->dirty = 0;
@@ -1412,10 +1412,9 @@ static void fillRect_normalized(const QRect &r, QSpanData *data,
if (data->fillRect && (mode == QPainter::CompositionMode_Source
|| (mode == QPainter::CompositionMode_SourceOver
- && qAlpha(data->solid.color) == 255)))
+ && data->solid.color.isOpaque())))
{
- data->fillRect(data->rasterBuffer, x1, y1, width, height,
- data->solid.color);
+ data->fillRect(data->rasterBuffer, x1, y1, width, height, data->solid.color);
return;
}
}
@@ -1773,8 +1772,9 @@ void QRasterPaintEngine::fillRect(const QRectF &r, const QColor &color)
Q_D(QRasterPaintEngine);
QRasterPaintEngineState *s = state();
- d->solid_color_filler.solid.color = qPremultiply(ARGB_COMBINE_ALPHA(color.rgba(), s->intOpacity));
- if ((d->solid_color_filler.solid.color & 0xff000000) == 0
+ d->solid_color_filler.solid.color = qPremultiply(combineAlpha256(color.rgba64(), s->intOpacity));
+
+ if (d->solid_color_filler.solid.color.isTransparent()
&& s->composition_mode == QPainter::CompositionMode_SourceOver) {
return;
}
@@ -2219,19 +2219,15 @@ void QRasterPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRe
case QImage::Format_A2BGR30_Premultiplied:
case QImage::Format_A2RGB30_Premultiplied:
// Combine premultiplied color with the opacity set on the painter.
- d->solid_color_filler.solid.color =
- ((((color & 0x00ff00ff) * s->intOpacity) >> 8) & 0x00ff00ff)
- | ((((color & 0xff00ff00) >> 8) * s->intOpacity) & 0xff00ff00);
+ d->solid_color_filler.solid.color = multiplyAlpha256(QRgba64::fromArgb32(color), s->intOpacity);
break;
default:
- d->solid_color_filler.solid.color = qPremultiply(ARGB_COMBINE_ALPHA(color, s->intOpacity));
+ d->solid_color_filler.solid.color = qPremultiply(combineAlpha256(QRgba64::fromArgb32(color), s->intOpacity));
break;
}
- if ((d->solid_color_filler.solid.color & 0xff000000) == 0
- && s->composition_mode == QPainter::CompositionMode_SourceOver) {
+ if (d->solid_color_filler.solid.color.isTransparent() && s->composition_mode == QPainter::CompositionMode_SourceOver)
return;
- }
d->solid_color_filler.clip = d->clip();
d->solid_color_filler.adjustSpanMethods();
@@ -4140,8 +4136,8 @@ class QGradientCache
struct CacheInfo
{
inline CacheInfo(QGradientStops s, int op, QGradient::InterpolationMode mode) :
- stops(s), opacity(op), interpolationMode(mode) {}
- uint buffer[GRADIENT_STOPTABLE_SIZE];
+ stops(qMove(s)), opacity(op), interpolationMode(mode) {}
+ QRgba64 buffer[GRADIENT_STOPTABLE_SIZE];
QGradientStops stops;
int opacity;
QGradient::InterpolationMode interpolationMode;
@@ -4150,12 +4146,12 @@ class QGradientCache
typedef QMultiHash<quint64, CacheInfo> QGradientColorTableHash;
public:
- inline const uint *getBuffer(const QGradient &gradient, int opacity) {
+ inline const QRgba64 *getBuffer(const QGradient &gradient, int opacity) {
quint64 hash_val = 0;
QGradientStops stops = gradient.stops();
for (int i = 0; i < stops.size() && i <= 2; i++)
- hash_val += stops[i].second.rgba();
+ hash_val += stops[i].second.rgba64();
QMutexLocker lock(&mutex);
QGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
@@ -4178,9 +4174,9 @@ public:
protected:
inline int maxCacheSize() const { return 60; }
inline void generateGradientColorTable(const QGradient& g,
- uint *colorTable,
+ QRgba64 *colorTable,
int size, int opacity) const;
- uint *addCacheElement(quint64 hash_val, const QGradient &gradient, int opacity) {
+ QRgba64 *addCacheElement(quint64 hash_val, const QGradient &gradient, int opacity) {
if (cache.size() == maxCacheSize()) {
// may remove more than 1, but OK
cache.erase(cache.begin() + (qrand() % maxCacheSize()));
@@ -4194,7 +4190,7 @@ protected:
QMutex mutex;
};
-void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, int opacity) const
+void QGradientCache::generateGradientColorTable(const QGradient& gradient, QRgba64 *colorTable, int size, int opacity) const
{
QGradientStops stops = gradient.stops();
int stopCount = stops.count();
@@ -4203,14 +4199,16 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
if (stopCount == 2) {
- uint first_color = ARGB_COMBINE_ALPHA(stops[0].second.rgba(), opacity);
- uint second_color = ARGB_COMBINE_ALPHA(stops[1].second.rgba(), opacity);
+ QRgba64 first_color = combineAlpha256(stops[0].second.rgba64(), opacity);
+ QRgba64 second_color = combineAlpha256(stops[1].second.rgba64(), opacity);
qreal first_stop = stops[0].first;
qreal second_stop = stops[1].first;
if (second_stop < first_stop) {
- qSwap(first_color, second_color);
+ quint64 tmp = first_color;
+ first_color = second_color;
+ second_color = tmp;
qSwap(first_stop, second_stop);
}
@@ -4222,15 +4220,15 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
int first_index = qRound(first_stop * (GRADIENT_STOPTABLE_SIZE-1));
int second_index = qRound(second_stop * (GRADIENT_STOPTABLE_SIZE-1));
- uint red_first = qRed(first_color) << 16;
- uint green_first = qGreen(first_color) << 16;
- uint blue_first = qBlue(first_color) << 16;
- uint alpha_first = qAlpha(first_color) << 16;
+ uint red_first = uint(first_color.red()) << 16;
+ uint green_first = uint(first_color.green()) << 16;
+ uint blue_first = uint(first_color.blue()) << 16;
+ uint alpha_first = uint(first_color.alpha()) << 16;
- uint red_second = qRed(second_color) << 16;
- uint green_second = qGreen(second_color) << 16;
- uint blue_second = qBlue(second_color) << 16;
- uint alpha_second = qAlpha(second_color) << 16;
+ uint red_second = uint(second_color.red()) << 16;
+ uint green_second = uint(second_color.green()) << 16;
+ uint blue_second = uint(second_color.blue()) << 16;
+ uint alpha_second = uint(second_color.alpha()) << 16;
int i = 0;
for (; i <= qMin(GRADIENT_STOPTABLE_SIZE, first_index); ++i) {
@@ -4243,10 +4241,10 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
if (i < second_index) {
qreal reciprocal = qreal(1) / (second_index - first_index);
- int red_delta = qRound(int(red_second - red_first) * reciprocal);
- int green_delta = qRound(int(green_second - green_first) * reciprocal);
- int blue_delta = qRound(int(blue_second - blue_first) * reciprocal);
- int alpha_delta = qRound(int(alpha_second - alpha_first) * reciprocal);
+ int red_delta = qRound((qreal(red_second) - red_first) * reciprocal);
+ int green_delta = qRound((qreal(green_second) - green_first) * reciprocal);
+ int blue_delta = qRound((qreal(blue_second) - blue_first) * reciprocal);
+ int alpha_delta = qRound((qreal(alpha_second) - alpha_first) * reciprocal);
// rounding
red_first += 1 << 15;
@@ -4260,8 +4258,7 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
blue_first += blue_delta;
alpha_first += alpha_delta;
- const uint color = ((alpha_first << 8) & 0xff000000) | (red_first & 0xff0000)
- | ((green_first >> 8) & 0xff00) | (blue_first >> 16);
+ const QRgba64 color = qRgba64(red_first >> 16, green_first >> 16, blue_first >> 16, alpha_first >> 16);
if (colorInterpolation)
colorTable[i] = color;
@@ -4280,7 +4277,7 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
return;
}
- uint current_color = ARGB_COMBINE_ALPHA(stops[0].second.rgba(), opacity);
+ QRgba64 current_color = combineAlpha256(stops[0].second.rgba64(), opacity);
if (stopCount == 1) {
current_color = qPremultiply(current_color);
for (int i = 0; i < size; ++i)
@@ -4293,7 +4290,7 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
qreal end_pos = stops[stopCount-1].first;
int pos = 0; // The position in the color table.
- uint next_color;
+ QRgba64 next_color;
qreal incr = 1 / qreal(size); // the double increment.
qreal dpos = 1.5 * incr; // current position in gradient stop list (0 to 1)
@@ -4317,8 +4314,8 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
++current_stop;
if (current_stop != 0)
- current_color = ARGB_COMBINE_ALPHA(stops[current_stop].second.rgba(), opacity);
- next_color = ARGB_COMBINE_ALPHA(stops[current_stop+1].second.rgba(), opacity);
+ current_color = combineAlpha256(stops[current_stop].second.rgba64(), opacity);
+ next_color = combineAlpha256(stops[current_stop+1].second.rgba64(), opacity);
if (colorInterpolation) {
current_color = qPremultiply(current_color);
@@ -4337,9 +4334,9 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
int idist = 256 - dist;
if (colorInterpolation)
- colorTable[pos] = INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist);
+ colorTable[pos] = interpolate256(current_color, idist, next_color, dist);
else
- colorTable[pos] = qPremultiply(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
+ colorTable[pos] = qPremultiply(interpolate256(current_color, idist, next_color, dist));
++pos;
dpos += incr;
@@ -4358,8 +4355,8 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
if (skip == 1)
current_color = next_color;
else
- current_color = ARGB_COMBINE_ALPHA(stops[current_stop].second.rgba(), opacity);
- next_color = ARGB_COMBINE_ALPHA(stops[current_stop+1].second.rgba(), opacity);
+ current_color = combineAlpha256(stops[current_stop].second.rgba64(), opacity);
+ next_color = combineAlpha256(stops[current_stop+1].second.rgba64(), opacity);
if (colorInterpolation) {
if (skip != 1)
@@ -4376,7 +4373,7 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint
}
// After last point
- current_color = qPremultiply(ARGB_COMBINE_ALPHA(stops[stopCount - 1].second.rgba(), opacity));
+ current_color = qPremultiply(combineAlpha256(stops[stopCount - 1].second.rgba64(), opacity));
while (pos < size - 1) {
colorTable[pos] = current_color;
++pos;
@@ -4409,12 +4406,9 @@ void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode
case Qt::SolidPattern: {
type = Solid;
QColor c = qbrush_color(brush);
- QRgb rgba = c.rgba();
- solid.color = qPremultiply(ARGB_COMBINE_ALPHA(rgba, alpha));
- if ((solid.color & 0xff000000) == 0
- && compositionMode == QPainter::CompositionMode_SourceOver) {
+ solid.color = qPremultiply(combineAlpha256(c.rgba64(), alpha));
+ if (solid.color.isTransparent() && compositionMode == QPainter::CompositionMode_SourceOver)
type = None;
- }
break;
}
@@ -4423,7 +4417,7 @@ void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode
type = LinearGradient;
const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
gradient.alphaColor = !brush.isOpaque() || alpha != 256;
- gradient.colorTable = const_cast<uint*>(qt_gradient_cache()->getBuffer(*g, alpha));
+ gradient.colorTable = const_cast<QRgba64*>(qt_gradient_cache()->getBuffer(*g, alpha));
gradient.spread = g->spread();
QLinearGradientData &linearData = gradient.linear;
@@ -4440,7 +4434,7 @@ void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode
type = RadialGradient;
const QRadialGradient *g = static_cast<const QRadialGradient *>(brush.gradient());
gradient.alphaColor = !brush.isOpaque() || alpha != 256;
- gradient.colorTable = const_cast<uint*>(qt_gradient_cache()->getBuffer(*g, alpha));
+ gradient.colorTable = const_cast<QRgba64*>(qt_gradient_cache()->getBuffer(*g, alpha));
gradient.spread = g->spread();
QRadialGradientData &radialData = gradient.radial;
@@ -4461,7 +4455,7 @@ void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode
type = ConicalGradient;
const QConicalGradient *g = static_cast<const QConicalGradient *>(brush.gradient());
gradient.alphaColor = !brush.isOpaque() || alpha != 256;
- gradient.colorTable = const_cast<uint*>(qt_gradient_cache()->getBuffer(*g, alpha));
+ gradient.colorTable = const_cast<QRgba64*>(qt_gradient_cache()->getBuffer(*g, alpha));
gradient.spread = QGradient::RepeatSpread;
QConicalGradientData &conicalData = gradient.conical;
diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp
index 20608e5aee..e80c0130c3 100644
--- a/src/gui/painting/qpainter.cpp
+++ b/src/gui/painting/qpainter.cpp
@@ -219,18 +219,18 @@ QTransform QPainterPrivate::viewTransform() const
return QTransform();
}
-int QPainterPrivate::effectiveDevicePixelRatio() const
+qreal QPainterPrivate::effectiveDevicePixelRatio() const
{
// Special cases for devices that does not support PdmDevicePixelRatio go here:
if (device->devType() == QInternal::Printer)
- return 1;
+ return qreal(1);
- return qMax(1, device->metric(QPaintDevice::PdmDevicePixelRatio));
+ return qMax(qreal(1), device->devicePixelRatioF());
}
QTransform QPainterPrivate::hidpiScaleTransform() const
{
- int devicePixelRatio = effectiveDevicePixelRatio();
+ const qreal devicePixelRatio = effectiveDevicePixelRatio();
return QTransform::fromScale(devicePixelRatio, devicePixelRatio);
}
@@ -5110,7 +5110,7 @@ void QPainter::drawPixmap(const QPointF &p, const QPixmap &pm)
x += d->state->matrix.dx();
y += d->state->matrix.dy();
}
- int scale = pm.devicePixelRatio();
+ qreal scale = pm.devicePixelRatio();
d->engine->drawPixmap(QRectF(x, y, w / scale, h / scale), pm, QRectF(0, 0, w, h));
}
}
@@ -7470,7 +7470,7 @@ start_lengthVariant:
}
}
- QList<QTextLayout::FormatRange> underlineFormats;
+ QVector<QTextLayout::FormatRange> underlineFormats;
int length = offset - old_offset;
if ((hidemnmemonic || showmnemonic) && maxUnderlines > 0) {
QChar *cout = text.data() + old_offset;
@@ -7526,6 +7526,7 @@ start_lengthVariant:
if (engine.option.tabs().isEmpty() && ta) {
QList<qreal> tabs;
+ tabs.reserve(tabarraylen);
for (int i = 0; i < tabarraylen; i++)
tabs.append(qreal(ta[i]));
engine.option.setTabArray(tabs);
@@ -7544,7 +7545,7 @@ start_lengthVariant:
engine.forceJustification = true;
QTextLayout textLayout(&engine);
textLayout.setCacheEnabled(true);
- textLayout.setAdditionalFormats(underlineFormats);
+ textLayout.setFormats(underlineFormats);
if (finalText.isEmpty()) {
height = fm.height();
diff --git a/src/gui/painting/qpainter.h b/src/gui/painting/qpainter.h
index 51776a9642..8e2d17d3a5 100644
--- a/src/gui/painting/qpainter.h
+++ b/src/gui/painting/qpainter.h
@@ -374,7 +374,7 @@ public:
inline void drawPixmap(int x, int y, int w, int h, const QPixmap &pm);
void drawPixmapFragments(const PixmapFragment *fragments, int fragmentCount,
- const QPixmap &pixmap, PixmapFragmentHints hints = 0);
+ const QPixmap &pixmap, PixmapFragmentHints hints = PixmapFragmentHints());
void drawImage(const QRectF &targetRect, const QImage &image, const QRectF &sourceRect,
Qt::ImageConversionFlags flags = Qt::AutoColor);
@@ -408,9 +408,9 @@ public:
void drawText(const QPointF &p, const QString &str, int tf, int justificationPadding);
- void drawText(const QRectF &r, int flags, const QString &text, QRectF *br=0);
- void drawText(const QRect &r, int flags, const QString &text, QRect *br=0);
- inline void drawText(int x, int y, int w, int h, int flags, const QString &text, QRect *br=0);
+ void drawText(const QRectF &r, int flags, const QString &text, QRectF *br = Q_NULLPTR);
+ void drawText(const QRect &r, int flags, const QString &text, QRect *br = Q_NULLPTR);
+ inline void drawText(int x, int y, int w, int h, int flags, const QString &text, QRect *br = Q_NULLPTR);
void drawText(const QRectF &r, const QString &text, const QTextOption &o = QTextOption());
@@ -453,7 +453,7 @@ public:
static void setRedirected(const QPaintDevice *device, QPaintDevice *replacement,
const QPoint& offset = QPoint());
- static QPaintDevice *redirected(const QPaintDevice *device, QPoint *offset = 0);
+ static QPaintDevice *redirected(const QPaintDevice *device, QPoint *offset = Q_NULLPTR);
static void restoreRedirected(const QPaintDevice *device);
void beginNativePainting();
diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h
index 7c32dc1694..e8b675365f 100644
--- a/src/gui/painting/qpainter_p.h
+++ b/src/gui/painting/qpainter_p.h
@@ -53,7 +53,6 @@
#include "QtGui/qpainter.h"
#include "QtGui/qpainterpath.h"
#include "QtGui/qpaintengine.h"
-#include <QtCore/qhash.h>
#include <private/qpen_p.h>
@@ -241,7 +240,7 @@ public:
}
QTransform viewTransform() const;
- int effectiveDevicePixelRatio() const;
+ qreal effectiveDevicePixelRatio() const;
QTransform hidpiScaleTransform() const;
static bool attachPainterPrivate(QPainter *q, QPaintDevice *pdev);
void detachPainterPrivate(QPainter *q);
diff --git a/src/gui/painting/qpathclipper.cpp b/src/gui/painting/qpathclipper.cpp
index 0798418c17..513fdfa2b6 100644
--- a/src/gui/painting/qpathclipper.cpp
+++ b/src/gui/painting/qpathclipper.cpp
@@ -1889,10 +1889,10 @@ bool QPathClipper::handleCrossingEdges(QWingedEdge &list, qreal y, ClipperMode m
namespace {
-QList<QPainterPath> toSubpaths(const QPainterPath &path)
+QVector<QPainterPath> toSubpaths(const QPainterPath &path)
{
- QList<QPainterPath> subpaths;
+ QVector<QPainterPath> subpaths;
if (path.isEmpty())
return subpaths;
@@ -2092,7 +2092,7 @@ QPainterPath clip(const QPainterPath &path, qreal t)
QPainterPath intersectPath(const QPainterPath &path, const QRectF &rect)
{
- QList<QPainterPath> subpaths = toSubpaths(path);
+ QVector<QPainterPath> subpaths = toSubpaths(path);
QPainterPath result;
result.setFillRule(path.fillRule());
diff --git a/src/gui/painting/qpdf.cpp b/src/gui/painting/qpdf.cpp
index 54e656e339..0814e0494d 100644
--- a/src/gui/painting/qpdf.cpp
+++ b/src/gui/painting/qpdf.cpp
@@ -996,6 +996,34 @@ void QPdfEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
*d->currentPage << "Q\n";
}
+void QPdfEngine::drawHyperlink(const QRectF &r, const QUrl &url)
+{
+ Q_D(QPdfEngine);
+
+ const uint annot = d->addXrefEntry(-1);
+ const QByteArray urlascii = url.toEncoded();
+ int len = urlascii.size();
+ QVarLengthArray<char> url_esc(0);
+ for (int j = 0; j < len; j++) {
+ if (urlascii[j] == '(' || urlascii[j] == ')' || urlascii[j] == '\\')
+ url_esc.append('\\');
+ url_esc.append(urlascii[j]);
+ }
+ url_esc.append('\0');
+
+ char buf[256];
+ const QRectF rr = d->pageMatrix().mapRect(r);
+ d->xprintf("<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
+ d->xprintf("%s ", qt_real_to_string(rr.left(), buf));
+ d->xprintf("%s ", qt_real_to_string(rr.top(), buf));
+ d->xprintf("%s ", qt_real_to_string(rr.right(), buf));
+ d->xprintf("%s", qt_real_to_string(rr.bottom(), buf));
+ d->xprintf("]\n/Border [0 0 0]\n/A <<\n");
+ d->xprintf("/Type /Action\n/S /URI\n/URI (%s)\n", url_esc.constData());
+ d->xprintf(">>\n>>\n");
+ d->xprintf("endobj\n");
+ d->currentPage->annotations.append(annot);
+}
void QPdfEngine::updateState(const QPaintEngineState &state)
{
@@ -1318,6 +1346,9 @@ int QPdfEngine::metric(QPaintDevice::PaintDeviceMetric metricType) const
case QPaintDevice::PdmDevicePixelRatio:
val = 1;
break;
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ val = 1 * QPaintDevice::devicePixelRatioFScale();
+ break;
default:
qWarning("QPdfWriter::metric: Invalid metric command");
return 0;
@@ -1952,7 +1983,9 @@ int QPdfEnginePrivate::createShadingFunction(const QGradient *gradient, int from
stops.append(QGradientStop(1, stops.at(stops.size() - 1).second));
QVector<int> functions;
- for (int i = 0; i < stops.size() - 1; ++i) {
+ const int numStops = stops.size();
+ functions.reserve(numStops - 1);
+ for (int i = 0; i < numStops - 1; ++i) {
int f = addXrefEntry(-1);
QByteArray data;
QPdf::ByteStream s(&data);
@@ -2098,9 +2131,9 @@ int QPdfEnginePrivate::generateLinearGradientShader(const QLinearGradient *gradi
int QPdfEnginePrivate::generateRadialGradientShader(const QRadialGradient *gradient, const QTransform &matrix, bool alpha)
{
QPointF p1 = gradient->center();
- double r1 = gradient->centerRadius();
+ qreal r1 = gradient->centerRadius();
QPointF p0 = gradient->focalPoint();
- double r0 = gradient->focalRadius();
+ qreal r0 = gradient->focalRadius();
Q_ASSERT(gradient->coordinateMode() == QGradient::LogicalMode);
diff --git a/src/gui/painting/qpdf_p.h b/src/gui/painting/qpdf_p.h
index 94e74f30b9..de30744ca2 100644
--- a/src/gui/painting/qpdf_p.h
+++ b/src/gui/painting/qpdf_p.h
@@ -188,6 +188,8 @@ public:
Qt::ImageConversionFlags flags = Qt::AutoColor) Q_DECL_OVERRIDE;
void drawTiledPixmap (const QRectF & rectangle, const QPixmap & pixmap, const QPointF & point) Q_DECL_OVERRIDE;
+ void drawHyperlink(const QRectF &r, const QUrl &url);
+
void updateState(const QPaintEngineState &state) Q_DECL_OVERRIDE;
int metric(QPaintDevice::PaintDeviceMetric metricType) const;
@@ -243,7 +245,7 @@ public:
QPointF brushOrigin;
QBrush brush;
QPen pen;
- QList<QPainterPath> clips;
+ QVector<QPainterPath> clips;
bool clipEnabled;
bool allClipped;
bool hasPen;
diff --git a/src/gui/painting/qpen.cpp b/src/gui/painting/qpen.cpp
index 6263d18b01..073d254b49 100644
--- a/src/gui/painting/qpen.cpp
+++ b/src/gui/painting/qpen.cpp
@@ -980,6 +980,7 @@ QDataStream &operator>>(QDataStream &s, QPen &p)
quint32 numDashes;
s >> numDashes;
double dash;
+ dashPattern.reserve(numDashes);
for (quint32 i = 0; i < numDashes; ++i) {
s >> dash;
dashPattern << dash;
diff --git a/src/gui/painting/qplatformbackingstore.cpp b/src/gui/painting/qplatformbackingstore.cpp
index 62492980de..e765a9e402 100644
--- a/src/gui/painting/qplatformbackingstore.cpp
+++ b/src/gui/painting/qplatformbackingstore.cpp
@@ -100,7 +100,7 @@ public:
{
}
- QList<QBackingstoreTextureInfo> textures;
+ QVector<QBackingstoreTextureInfo> textures;
bool locked;
};
@@ -220,7 +220,9 @@ static QRegion deviceRegion(const QRegion &region, QWindow *window)
return region;
QVector<QRect> rects;
- foreach (QRect rect, region.rects())
+ const QVector<QRect> regionRects = region.rects();
+ rects.reserve(regionRects.count());
+ foreach (const QRect &rect, regionRects)
rects.append(deviceRect(rect, window));
QRegion deviceRegion;
diff --git a/src/gui/painting/qpolygon.h b/src/gui/painting/qpolygon.h
index 1549ebe2b5..1e503c03b7 100644
--- a/src/gui/painting/qpolygon.h
+++ b/src/gui/painting/qpolygon.h
@@ -52,11 +52,19 @@ public:
inline QPolygon() {}
inline ~QPolygon() {}
inline explicit QPolygon(int size);
- inline QPolygon(const QPolygon &a) : QVector<QPoint>(a) {}
inline /*implicit*/ QPolygon(const QVector<QPoint> &v) : QVector<QPoint>(v) {}
+#ifdef Q_COMPILER_RVALUE_REFS
+ /*implicit*/ QPolygon(QVector<QPoint> &&v) Q_DECL_NOTHROW : QVector<QPoint>(std::move(v)) {}
+#endif
QPolygon(const QRect &r, bool closed=false);
QPolygon(int nPoints, const int *points);
- inline void swap(QPolygon &other) { QVector<QPoint>::swap(other); } // prevent QVector<QPoint><->QPolygon swaps
+ QPolygon(const QPolygon &other) : QVector<QPoint>(other) {}
+#ifdef Q_COMPILER_RVALUE_REFS
+ QPolygon(QPolygon &&other) Q_DECL_NOTHROW : QVector<QPoint>(std::move(other)) {}
+ QPolygon &operator=(QPolygon &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QPolygon &operator=(const QPolygon &other) { QVector<QPoint>::operator=(other); return *this; }
+ void swap(QPolygon &other) Q_DECL_NOTHROW { QVector<QPoint>::swap(other); } // prevent QVector<QPoint><->QPolygon swaps
operator QVariant() const;
@@ -126,10 +134,18 @@ public:
inline QPolygonF() {}
inline ~QPolygonF() {}
inline explicit QPolygonF(int size);
- inline QPolygonF(const QPolygonF &a) : QVector<QPointF>(a) {}
inline /*implicit*/ QPolygonF(const QVector<QPointF> &v) : QVector<QPointF>(v) {}
+#ifdef Q_COMPILER_RVALUE_REFS
+ /* implicit */ QPolygonF(QVector<QPointF> &&v) Q_DECL_NOTHROW : QVector<QPointF>(std::move(v)) {}
+#endif
QPolygonF(const QRectF &r);
/*implicit*/ QPolygonF(const QPolygon &a);
+ inline QPolygonF(const QPolygonF &a) : QVector<QPointF>(a) {}
+#ifdef Q_COMPILER_RVALUE_REFS
+ QPolygonF(QPolygonF &&other) Q_DECL_NOTHROW : QVector<QPointF>(std::move(other)) {}
+ QPolygonF &operator=(QPolygonF &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QPolygonF &operator=(const QPolygonF &other) { QVector<QPointF>::operator=(other); return *this; }
inline void swap(QPolygonF &other) { QVector<QPointF>::swap(other); } // prevent QVector<QPointF><->QPolygonF swaps
operator QVariant() const;
diff --git a/src/gui/painting/qrgba64.h b/src/gui/painting/qrgba64.h
new file mode 100644
index 0000000000..cca9019959
--- /dev/null
+++ b/src/gui/painting/qrgba64.h
@@ -0,0 +1,228 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QRGBA64_H
+#define QRGBA64_H
+
+#include <QtCore/qglobal.h>
+#include <QtCore/qprocessordetection.h>
+
+QT_BEGIN_NAMESPACE
+
+class QRgba64 {
+ quint64 rgba;
+
+ // Make sure that the representation always has the order: red green blue alpha, independent
+ // of byte order. This way, vector operations that assume 4 16-bit values see the correct ones.
+ enum {
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ RedShift = 48,
+ GreenShift = 32,
+ BlueShift = 16,
+ AlphaShift = 0
+#else // little endian:
+ RedShift = 0,
+ GreenShift = 16,
+ BlueShift = 32,
+ AlphaShift = 48
+#endif
+ };
+
+ // No constructors are allowed in C++98, since this needs to be usable in a union.
+ // We however require one for constexprs in C++11/C++14
+#ifdef Q_COMPILER_CONSTEXPR
+ explicit Q_ALWAYS_INLINE Q_DECL_CONSTEXPR QRgba64(quint64 c) : rgba(c) { }
+#endif
+public:
+#ifdef Q_COMPILER_CONSTEXPR
+ Q_ALWAYS_INLINE Q_DECL_CONSTEXPR QRgba64() : rgba(0) { }
+#endif
+
+ Q_DECL_CONSTEXPR static
+ QRgba64 fromRgba64(quint64 c)
+ {
+#ifdef Q_COMPILER_CONSTEXPR
+ return QRgba64(c);
+#else
+ QRgba64 rgba64;
+ rgba64.rgba = c;
+ return rgba64;
+#endif
+ }
+ Q_DECL_CONSTEXPR static
+ QRgba64 fromRgba64(quint16 red, quint16 green, quint16 blue, quint16 alpha)
+ {
+ return fromRgba64(quint64(red) << RedShift
+ | quint64(green) << GreenShift
+ | quint64(blue) << BlueShift
+ | quint64(alpha) << AlphaShift);
+ }
+ Q_DECL_RELAXED_CONSTEXPR static QRgba64 fromRgba(quint8 red, quint8 green, quint8 blue, quint8 alpha)
+ {
+ QRgba64 rgb64 = fromRgba64(red, green, blue, alpha);
+ // Expand the range so that 0x00 maps to 0x0000 and 0xff maps to 0xffff.
+ rgb64.rgba |= rgb64.rgba << 8;
+ return rgb64;
+ }
+ Q_DECL_RELAXED_CONSTEXPR static
+ QRgba64 fromArgb32(uint rgb)
+ {
+ return fromRgba(rgb >> 16, rgb >> 8, rgb, rgb >> 24);
+ }
+
+ Q_DECL_CONSTEXPR bool isOpaque() const
+ {
+ return (rgba & alphaMask()) == alphaMask();
+ }
+ Q_DECL_CONSTEXPR bool isTransparent() const
+ {
+ return (rgba & alphaMask()) == 0;
+ }
+
+ Q_DECL_CONSTEXPR quint16 red() const { return rgba >> RedShift; }
+ Q_DECL_CONSTEXPR quint16 green() const { return rgba >> GreenShift; }
+ Q_DECL_CONSTEXPR quint16 blue() const { return rgba >> BlueShift; }
+ Q_DECL_CONSTEXPR quint16 alpha() const { return rgba >> AlphaShift; }
+ void setRed(quint16 _red) { *this = fromRgba64(_red, green(), blue(), alpha()); }
+ void setGreen(quint16 _green) { *this = fromRgba64(red(), _green, blue(), alpha()); }
+ void setBlue(quint16 _blue) { *this = fromRgba64(red(), green(), _blue, alpha()); }
+ void setAlpha(quint16 _alpha) { *this = fromRgba64(red(), green(), blue(), _alpha); }
+
+ Q_DECL_CONSTEXPR quint8 red8() const { return div_257(red()); }
+ Q_DECL_CONSTEXPR quint8 green8() const { return div_257(green()); }
+ Q_DECL_CONSTEXPR quint8 blue8() const { return div_257(blue()); }
+ Q_DECL_CONSTEXPR quint8 alpha8() const { return div_257(alpha()); }
+ Q_DECL_CONSTEXPR uint toArgb32() const
+ {
+ return (alpha8() << 24) | (red8() << 16) | (green8() << 8) | blue8();
+ }
+ Q_DECL_CONSTEXPR ushort toRgb16() const
+ {
+ return (red() & 0xf800) | ((green() >> 10) << 5) | (blue() >> 11);
+ }
+
+ Q_DECL_RELAXED_CONSTEXPR QRgba64 premultiplied() const
+ {
+ const quint32 a = alpha();
+ const quint16 r = div_65535(red() * a);
+ const quint16 g = div_65535(green() * a);
+ const quint16 b = div_65535(blue() * a);
+ return fromRgba64(r, g, b, a);
+ }
+
+ Q_DECL_RELAXED_CONSTEXPR QRgba64 unpremultiplied() const
+ {
+#if Q_PROCESSOR_WORDSIZE < 8
+ return unpremultiplied_32bit();
+#else
+ return unpremultiplied_64bit();
+#endif
+ }
+
+ Q_DECL_CONSTEXPR operator quint64() const
+ {
+ return rgba;
+ }
+
+ QRgba64 operator=(quint64 _rgba)
+ {
+ rgba = _rgba;
+ return *this;
+ }
+
+private:
+ static Q_DECL_CONSTEXPR quint64 alphaMask() { return quint64(0xffff) << AlphaShift; }
+
+ static Q_DECL_CONSTEXPR uint div_257_floor(uint x) { return (x - (x >> 8)) >> 8; }
+ static Q_DECL_CONSTEXPR uint div_257(uint x) { return div_257_floor(x + 128); }
+ static Q_DECL_CONSTEXPR uint div_65535(uint x) { return (x + (x>>16) + 0x8000U) >> 16; }
+ Q_DECL_RELAXED_CONSTEXPR QRgba64 unpremultiplied_32bit() const
+ {
+ const quint16 a = alpha();
+ if (a == 0xffff || a == 0)
+ return *this;
+ const quint16 r = (quint32(red()) * 0xffff + a/2) / a;
+ const quint16 g = (quint32(green()) * 0xffff + a/2) / a;
+ const quint16 b = (quint32(blue()) * 0xffff + a/2) / a;
+ return fromRgba64(r, g, b, a);
+ }
+ Q_DECL_RELAXED_CONSTEXPR QRgba64 unpremultiplied_64bit() const
+ {
+ const quint16 a = alpha();
+ if (a == 0xffff || a == 0)
+ return *this;
+ const quint64 fa = (Q_UINT64_C(0xffff00008000) + a/2) / a;
+ const quint16 r = (red() * fa + 0x80000000) >> 32;
+ const quint16 g = (green() * fa + 0x80000000) >> 32;
+ const quint16 b = (blue() * fa + 0x80000000) >> 32;
+ return fromRgba64(r, g, b, a);
+ }
+};
+
+Q_DECLARE_TYPEINFO(QRgba64, Q_PRIMITIVE_TYPE);
+
+Q_DECL_CONSTEXPR inline QRgba64 qRgba64(quint16 r, quint16 g, quint16 b, quint16 a)
+{
+ return QRgba64::fromRgba64(r, g, b, a);
+}
+
+Q_DECL_CONSTEXPR inline QRgba64 qRgba64(quint64 c)
+{
+ return QRgba64::fromRgba64(c);
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline QRgba64 qPremultiply(QRgba64 c)
+{
+ return c.premultiplied();
+}
+
+Q_DECL_RELAXED_CONSTEXPR inline QRgba64 qUnpremultiply(QRgba64 c)
+{
+ return c.unpremultiplied();
+}
+
+inline Q_DECL_CONSTEXPR uint qRed(QRgba64 rgb)
+{ return rgb.red8(); }
+
+inline Q_DECL_CONSTEXPR uint qGreen(QRgba64 rgb)
+{ return rgb.green8(); }
+
+inline Q_DECL_CONSTEXPR uint qBlue(QRgba64 rgb)
+{ return rgb.blue8(); }
+
+inline Q_DECL_CONSTEXPR uint qAlpha(QRgba64 rgb)
+{ return rgb.alpha8(); }
+
+QT_END_NAMESPACE
+
+#endif // QRGBA64_H
diff --git a/src/gui/painting/qrgba64.qdoc b/src/gui/painting/qrgba64.qdoc
new file mode 100644
index 0000000000..29da0aa390
--- /dev/null
+++ b/src/gui/painting/qrgba64.qdoc
@@ -0,0 +1,241 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:FDL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Free Documentation License Usage
+** 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. Please review the following information to ensure
+** the GNU Free Documentation License version 1.3 requirements
+** will be met: http://www.gnu.org/copyleft/fdl.html.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+/*!
+ \class QRgba64
+ \brief The QRgba64 struct contains a 64-bit RGB color.
+ \since 5.6
+
+ \ingroup painting
+ \inmodule QtGui
+
+ QRgba64 is a 64-bit data-structure containing four 16-bit color channels: Red, green, blue and alpha.
+
+ QRgba64 can be used a replacement for QRgb when higher precision is needed. In particular a
+ premultiplied QRgba64 can operate on unpremultipled QRgb without loss of precision except
+ for alpha 0.
+
+ \sa QRgb, QColor
+*/
+
+/*!
+ \fn static QRgba64 QRgba64::fromRgba64(quint16 r, quint16 g, quint16 b, quint16 a)
+
+ Returns the QRgba64 quadruplet (\a{r}, \a{g}, \a{b}, \a{a}).
+
+ \sa fromRgba()
+*/
+
+/*!
+ \fn static QRgba64 QRgba64::fromRgba64(quint64 c)
+
+ Returns \a c as a QRgba64 struct.
+
+ \sa fromArgb32()
+*/
+
+/*!
+ \fn static QRgba64 QRgba64::fromRgba(quint8 red, quint8 green, quint8 blue, quint8 alpha)
+
+ Constructs a QRgba64 value from the four 8-bit color channels \a red, \a green, \a blue and \a alpha.
+
+ \sa fromArgb32()
+*/
+
+/*!
+ \fn static QRgba64 QRgba64::fromArgb32(uint rgb)
+
+ Constructs a QRgba64 value from the 32bit ARGB value \a rgb.
+
+ \sa fromRgba()
+*/
+
+/*!
+ \fn quint16 QRgba64::red() const
+
+ Returns the 16-bit red color component.
+*/
+
+/*!
+ \fn quint16 QRgba64::green() const
+
+ Returns the 16-bit green color component.
+*/
+
+/*!
+ \fn quint16 QRgba64::blue() const
+
+ Returns the 16-bit blue color component.
+*/
+
+/*!
+ \fn quint16 QRgba64::alpha() const
+
+ Returns the 16-bit alpha channel.
+*/
+
+/*!
+ \fn quint8 QRgba64::red8() const
+
+ Returns the red color component as an 8-bit.
+*/
+
+/*!
+ \fn quint8 QRgba64::green8() const
+
+ Returns the green color component as an 8-bit.
+*/
+
+/*!
+ \fn quint8 QRgba64::blue8() const
+
+ Returns the blue color component as an 8-bit.
+*/
+
+/*!
+ \fn quint8 QRgba64::alpha8() const
+
+ Returns the alpha channel as an 8-bit.
+*/
+
+/*!
+ \fn uint QRgba64::toArgb32() const
+
+ Returns the color as a 32-bit ARGB value.
+
+ \sa fromArgb32()
+*/
+
+/*!
+ \fn ushort QRgba64::toRgb16() const
+
+ Returns the color as a 16-bit RGB value.
+
+ \sa toArgb32()
+*/
+
+/*!
+ \fn QRgba64 QRgba64::premultiplied() const
+
+ Returns the color with the alpha premultiplied.
+
+ \sa unpremultiplied()
+*/
+
+/*!
+ \fn QRgba64 QRgba64::unpremultiplied() const
+
+ Returns the color with the alpha unpremultiplied.
+
+ \sa premultiplied()
+*/
+
+/*!
+ \fn QRgba64::operator quint64() const
+
+ Returns the color as a 64bit unsigned integer
+*/
+
+/*!
+ \fn QRgba64 qRgba64(quint16 r, quint16 g, quint16 b, quint16 a)
+ \relates QColor
+ \since 5.6
+
+ Returns the QRgba64 quadruplet (\a{r}, \a{g}, \a{b}, \a{a}).
+
+ \sa qRgba()
+*/
+
+/*!
+ \fn QRgba64 qRgba64(quint64 c)
+ \relates QColor
+ \since 5.6
+
+ Returns \a c as a QRgba64 struct.
+
+ \sa qRgba()
+*/
+
+/*!
+ \fn QRgba64 qPremultiply(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Converts an unpremultiplied QRgba64 quadruplet \a rgba64 into a premultiplied QRgba64 quadruplet.
+
+ \sa QRgba64::premultiplied(), qUnpremultiply()
+*/
+
+/*!
+ \fn QRgba64 qUnpremultiply(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Converts a premultiplied QRgba64 quadruplet \a rgba64 into an unpremultiplied QRgba64 quadruplet.
+
+ \sa QRgba64::unpremultiplied(), qPremultiply()
+*/
+
+/*!
+ \fn uint qRed(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Returns the red component of \a rgba64 as an 8-bit value.
+
+ \sa QRgba64::red8(), QColor::red()
+*/
+
+/*!
+ \fn uint qGreen(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Returns the green component of \a rgba64 as an 8-bit value.
+
+ \sa QRgba64::green8(), QColor::green()
+*/
+
+/*!
+ \fn uint qBlue(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Returns the blue component of \a rgba64 as an 8-bit value.
+
+ \sa QRgba64::blue8(), QColor::blue()
+*/
+
+/*!
+ \fn uint qAlpha(QRgba64 rgba64)
+ \since 5.6
+ \relates QColor
+
+ Returns the alpha component of \a rgba64 as an 8-bit value.
+
+ \sa QRgba64::alpha8(), QColor::alpha()
+*/
diff --git a/src/gui/painting/qrgba64_p.h b/src/gui/painting/qrgba64_p.h
new file mode 100644
index 0000000000..c6cbe666ac
--- /dev/null
+++ b/src/gui/painting/qrgba64_p.h
@@ -0,0 +1,120 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QRGBA64_P_H
+#define QRGBA64_P_H
+
+#include <QtGui/qrgba64.h>
+#include <QtGui/private/qdrawhelper_p.h>
+#include <private/qsimd_p.h>
+
+QT_BEGIN_NAMESPACE
+
+inline QRgba64 combineAlpha256(QRgba64 rgba64, uint alpha256)
+{
+ return QRgba64::fromRgba64(rgba64.red(), rgba64.green(), rgba64.blue(), (rgba64.alpha() * alpha256) >> 8);
+}
+
+inline QRgba64 multiplyAlpha256(QRgba64 rgba64, uint alpha256)
+{
+ return QRgba64::fromRgba64((rgba64.red() * alpha256) >> 8,
+ (rgba64.green() * alpha256) >> 8,
+ (rgba64.blue() * alpha256) >> 8,
+ (rgba64.alpha() * alpha256) >> 8);
+}
+
+inline QRgba64 multiplyAlpha65535(QRgba64 rgba64, uint alpha65535)
+{
+#ifdef __SSE2__
+ const __m128i va = _mm_shufflelo_epi16(_mm_cvtsi32_si128(alpha65535), _MM_SHUFFLE(0, 0, 0, 0));
+ __m128i vs = _mm_loadl_epi64((__m128i*)&rgba64);
+ vs = _mm_unpacklo_epi16(_mm_mullo_epi16(vs, va), _mm_mulhi_epu16(vs, va));
+ vs = _mm_add_epi32(vs, _mm_srli_epi32(vs, 16));
+ vs = _mm_add_epi32(vs, _mm_set1_epi32(0x8000));
+ vs = _mm_srai_epi32(vs, 16);
+ vs = _mm_packs_epi32(vs, _mm_setzero_si128());
+ _mm_storel_epi64((__m128i*)&rgba64, vs);
+ return rgba64;
+#else
+ return QRgba64::fromRgba64(qt_div_65535(rgba64.red() * alpha65535),
+ qt_div_65535(rgba64.green() * alpha65535),
+ qt_div_65535(rgba64.blue() * alpha65535),
+ qt_div_65535(rgba64.alpha() * alpha65535));
+#endif
+}
+
+inline QRgba64 multiplyAlpha255(QRgba64 rgba64, uint alpha255)
+{
+#ifdef __SSE2__
+ return multiplyAlpha65535(rgba64, alpha255 * 257);
+#else
+ return QRgba64::fromRgba64(qt_div_255(rgba64.red() * alpha255),
+ qt_div_255(rgba64.green() * alpha255),
+ qt_div_255(rgba64.blue() * alpha255),
+ qt_div_255(rgba64.alpha() * alpha255));
+#endif
+}
+
+inline QRgba64 interpolate256(QRgba64 x, uint alpha1, QRgba64 y, uint alpha2)
+{
+ return QRgba64::fromRgba64(multiplyAlpha256(x, alpha1) + multiplyAlpha256(y, alpha2));
+}
+
+inline QRgba64 interpolate255(QRgba64 x, uint alpha1, QRgba64 y, uint alpha2)
+{
+ return QRgba64::fromRgba64(multiplyAlpha255(x, alpha1) + multiplyAlpha255(y, alpha2));
+}
+
+inline QRgba64 interpolate65535(QRgba64 x, uint alpha1, QRgba64 y, uint alpha2)
+{
+ return QRgba64::fromRgba64(multiplyAlpha65535(x, alpha1) + multiplyAlpha65535(y, alpha2));
+}
+
+inline QRgba64 addWithSaturation(QRgba64 a, QRgba64 b)
+{
+#if defined(__SSE2__) && defined(Q_PROCESSOR_X86_64)
+ __m128i va = _mm_cvtsi64_si128((quint64)a);
+ __m128i vb = _mm_cvtsi64_si128((quint64)b);
+ va = _mm_adds_epu16(va, vb);
+ return QRgba64::fromRgba64(_mm_cvtsi128_si64(va));
+#else
+ return QRgba64::fromRgba64(qMin(a.red() + b.red(), 65535),
+ qMin(a.green() + b.green(), 65535),
+ qMin(a.blue() + b.blue(), 65535),
+ qMin(a.alpha() + b.alpha(), 65535));
+#endif
+}
+
+QT_END_NAMESPACE
+
+#endif // QRGBA64_P_H
diff --git a/src/gui/painting/qtextureglyphcache.cpp b/src/gui/painting/qtextureglyphcache.cpp
index 4c879cf05d..44e14f656d 100644
--- a/src/gui/painting/qtextureglyphcache.cpp
+++ b/src/gui/painting/qtextureglyphcache.cpp
@@ -42,16 +42,24 @@ QT_BEGIN_NAMESPACE
// #define CACHE_DEBUG
+// out-of-line to avoid vtable duplication, breaking e.g. RTTI
+QTextureGlyphCache::~QTextureGlyphCache()
+{
+}
+
int QTextureGlyphCache::calculateSubPixelPositionCount(glyph_t glyph) const
{
// Test 12 different subpixel positions since it factors into 3*4 so it gives
// the coverage we need.
- QList<QImage> images;
- for (int i=0; i<12; ++i) {
+ const int NumSubpixelPositions = 12;
+
+ QImage images[NumSubpixelPositions];
+ int numImages = 0;
+ for (int i = 0; i < NumSubpixelPositions; ++i) {
QImage img = textureMapForGlyph(glyph, QFixed::fromReal(i / 12.0));
- if (images.isEmpty()) {
+ if (numImages == 0) {
QPainterPath path;
QFixedPoint point;
m_current_fontengine->addGlyphsToPath(&glyph, &point, 1, &path, QTextItem::RenderFlags());
@@ -60,21 +68,21 @@ int QTextureGlyphCache::calculateSubPixelPositionCount(glyph_t glyph) const
if (path.isEmpty())
break;
- images.append(img);
+ images[numImages++] = qMove(img);
} else {
bool found = false;
- for (int j=0; j<images.size(); ++j) {
- if (images.at(j) == img) {
+ for (int j = 0; j < numImages; ++j) {
+ if (images[j] == img) {
found = true;
break;
}
}
if (!found)
- images.append(img);
+ images[numImages++] = qMove(img);
}
}
- return images.size();
+ return numImages;
}
bool QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,
@@ -262,6 +270,11 @@ QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g, QFixed subPixelPosition
* QImageTextureGlyphCache
*/
+// out-of-line to avoid vtable duplication, breaking e.g. RTTI
+QImageTextureGlyphCache::~QImageTextureGlyphCache()
+{
+}
+
void QImageTextureGlyphCache::resizeTextureData(int width, int height)
{
m_image = m_image.copy(0, 0, width, height);
diff --git a/src/gui/painting/qtextureglyphcache_p.h b/src/gui/painting/qtextureglyphcache_p.h
index c9e7060b0d..7dd8277a45 100644
--- a/src/gui/painting/qtextureglyphcache_p.h
+++ b/src/gui/painting/qtextureglyphcache_p.h
@@ -72,7 +72,7 @@ public:
m_w(0), m_h(0), m_cx(0), m_cy(0), m_currentRowHeight(0)
{ }
- virtual ~QTextureGlyphCache() { }
+ ~QTextureGlyphCache();
struct GlyphAndSubPixelPosition
{
@@ -158,6 +158,8 @@ class Q_GUI_EXPORT QImageTextureGlyphCache : public QTextureGlyphCache
public:
QImageTextureGlyphCache(QFontEngine::GlyphFormat format, const QTransform &matrix)
: QTextureGlyphCache(format, matrix) { }
+ ~QImageTextureGlyphCache();
+
virtual void createTextureData(int width, int height) Q_DECL_OVERRIDE;
virtual void resizeTextureData(int width, int height) Q_DECL_OVERRIDE;
virtual void fillTexture(const Coord &c, glyph_t glyph, QFixed subPixelPosition) Q_DECL_OVERRIDE;
diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp
index a3e9db2057..a23aabe559 100644
--- a/src/gui/painting/qtransform.cpp
+++ b/src/gui/painting/qtransform.cpp
@@ -34,6 +34,7 @@
#include "qdatastream.h"
#include "qdebug.h"
+#include "qhashfunctions.h"
#include "qmatrix.h"
#include "qregion.h"
#include "qpainterpath.h"
@@ -776,6 +777,29 @@ bool QTransform::operator==(const QTransform &o) const
}
/*!
+ \since 5.6
+ \relates QTransform
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+uint qHash(const QTransform &key, uint seed) Q_DECL_NOTHROW
+{
+ QtPrivate::QHashCombine hash;
+ seed = hash(key.m11(), seed);
+ seed = hash(key.m12(), seed);
+ seed = hash(key.m21(), seed);
+ seed = hash(key.m22(), seed);
+ seed = hash(key.dx(), seed);
+ seed = hash(key.dy(), seed);
+ seed = hash(key.m13(), seed);
+ seed = hash(key.m23(), seed);
+ seed = hash(key.m33(), seed);
+ return seed;
+}
+
+
+/*!
\fn bool QTransform::operator!=(const QTransform &matrix) const
Returns \c true if this matrix is not equal to the given \a matrix,
otherwise returns \c false.
@@ -1357,7 +1381,9 @@ static QPolygonF mapProjective(const QTransform &transform, const QPolygonF &pol
path = transform.map(path);
QPolygonF result;
- for (int i = 0; i < path.elementCount(); ++i)
+ const int elementCount = path.elementCount();
+ result.reserve(elementCount);
+ for (int i = 0; i < elementCount; ++i)
result << path.elementAt(i);
return result;
}
diff --git a/src/gui/painting/qtransform.h b/src/gui/painting/qtransform.h
index cf8d4d1970..8874996e19 100644
--- a/src/gui/painting/qtransform.h
+++ b/src/gui/painting/qtransform.h
@@ -96,7 +96,7 @@ public:
qreal m21, qreal m22, qreal m23,
qreal m31, qreal m32, qreal m33);
- QTransform inverted(bool *invertible = 0) const Q_REQUIRED_RESULT;
+ QTransform inverted(bool *invertible = Q_NULLPTR) const Q_REQUIRED_RESULT;
QTransform adjoint() const Q_REQUIRED_RESULT;
QTransform transposed() const Q_REQUIRED_RESULT;
@@ -180,6 +180,8 @@ private:
};
Q_DECLARE_TYPEINFO(QTransform, Q_MOVABLE_TYPE);
+Q_GUI_EXPORT Q_DECL_CONST_FUNCTION uint qHash(const QTransform &key, uint seed = 0) Q_DECL_NOTHROW;
+
/******* inlines *****/
inline QTransform::TransformationType QTransform::inline_type() const
{
diff --git a/src/gui/text/qabstracttextdocumentlayout.cpp b/src/gui/text/qabstracttextdocumentlayout.cpp
index 70be92535d..7735fd6b46 100644
--- a/src/gui/text/qabstracttextdocumentlayout.cpp
+++ b/src/gui/text/qabstracttextdocumentlayout.cpp
@@ -40,6 +40,15 @@
QT_BEGIN_NAMESPACE
+QAbstractTextDocumentLayoutPrivate::~QAbstractTextDocumentLayoutPrivate()
+{
+}
+
+QTextObjectInterface::~QTextObjectInterface()
+{
+ // must be empty until ### Qt 6
+}
+
/*!
\class QAbstractTextDocumentLayout
\reentrant
diff --git a/src/gui/text/qabstracttextdocumentlayout.h b/src/gui/text/qabstracttextdocumentlayout.h
index 27135b0476..cdcfed7535 100644
--- a/src/gui/text/qabstracttextdocumentlayout.h
+++ b/src/gui/text/qabstracttextdocumentlayout.h
@@ -90,7 +90,7 @@ public:
QTextDocument *document() const;
void registerHandler(int objectType, QObject *component);
- void unregisterHandler(int objectType, QObject *component = 0);
+ void unregisterHandler(int objectType, QObject *component = Q_NULLPTR);
QTextObjectInterface *handlerForObject(int objectType) const;
Q_SIGNALS:
@@ -126,7 +126,7 @@ private:
class Q_GUI_EXPORT QTextObjectInterface
{
public:
- virtual ~QTextObjectInterface() {}
+ virtual ~QTextObjectInterface();
virtual QSizeF intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format) = 0;
virtual void drawObject(QPainter *painter, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format) = 0;
};
diff --git a/src/gui/text/qabstracttextdocumentlayout_p.h b/src/gui/text/qabstracttextdocumentlayout_p.h
index 505135fa4b..a7f28ebf96 100644
--- a/src/gui/text/qabstracttextdocumentlayout_p.h
+++ b/src/gui/text/qabstracttextdocumentlayout_p.h
@@ -58,13 +58,14 @@ struct QTextObjectHandler
};
typedef QHash<int, QTextObjectHandler> HandlerHash;
-class QAbstractTextDocumentLayoutPrivate : public QObjectPrivate
+class Q_GUI_EXPORT QAbstractTextDocumentLayoutPrivate : public QObjectPrivate
{
public:
Q_DECLARE_PUBLIC(QAbstractTextDocumentLayout)
inline QAbstractTextDocumentLayoutPrivate()
: paintDevice(0) {}
+ ~QAbstractTextDocumentLayoutPrivate();
inline void setDocument(QTextDocument *doc) {
document = doc;
diff --git a/src/gui/text/qcssparser.cpp b/src/gui/text/qcssparser.cpp
index 3c98cb568d..adbb3df3bf 100644
--- a/src/gui/text/qcssparser.cpp
+++ b/src/gui/text/qcssparser.cpp
@@ -461,6 +461,7 @@ void ValueExtractor::lengthValues(const Declaration &decl, int *m)
}
QList<QVariant> v;
+ v.reserve(4);
for (i = 0; i < 4; i++) {
v += QVariant::fromValue<LengthData>(datas[i]);
m[i] = lengthValueFromData(datas[i], f);
diff --git a/src/gui/text/qfont.cpp b/src/gui/text/qfont.cpp
index 3c6709e685..796f223797 100644
--- a/src/gui/text/qfont.cpp
+++ b/src/gui/text/qfont.cpp
@@ -1860,14 +1860,9 @@ void QFont::removeSubstitutions(const QString &familyName)
*/
QStringList QFont::substitutions()
{
- typedef QFontSubst::const_iterator QFontSubstConstIterator;
-
QFontSubst *fontSubst = globalFontSubst();
Q_ASSERT(fontSubst != 0);
- QStringList ret;
- const QFontSubstConstIterator cend = fontSubst->constEnd();
- for (QFontSubstConstIterator it = fontSubst->constBegin(); it != cend; ++it)
- ret.append(it.key());
+ QStringList ret = fontSubst->keys();
ret.sort();
return ret;
diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp
index 85a804acfe..80908122a8 100644
--- a/src/gui/text/qfontdatabase.cpp
+++ b/src/gui/text/qfontdatabase.cpp
@@ -1413,22 +1413,30 @@ QList<QFontDatabase::WritingSystem> QFontDatabase::writingSystems() const
QT_PREPEND_NAMESPACE(load)();
- QList<WritingSystem> list;
+ quint64 writingSystemsFound = 0;
+ Q_STATIC_ASSERT(WritingSystemsCount < 64);
+
for (int i = 0; i < d->count; ++i) {
QtFontFamily *family = d->families[i];
family->ensurePopulated();
if (family->count == 0)
continue;
- for (int x = Latin; x < WritingSystemsCount; ++x) {
- const WritingSystem writingSystem = WritingSystem(x);
- if (!(family->writingSystems[writingSystem] & QtFontFamily::Supported))
- continue;
- if (!list.contains(writingSystem))
- list.append(writingSystem);
+ for (uint x = Latin; x < uint(WritingSystemsCount); ++x) {
+ if (family->writingSystems[x] & QtFontFamily::Supported)
+ writingSystemsFound |= quint64(1) << x;
}
}
- std::sort(list.begin(), list.end());
+
+ // mutex protection no longer needed - just working on local data now:
+ locker.unlock();
+
+ QList<WritingSystem> list;
+ list.reserve(qPopulationCount(writingSystemsFound));
+ for (uint x = Latin ; x < uint(WritingSystemsCount); ++x) {
+ if (writingSystemsFound & (quint64(1) << x))
+ list.push_back(WritingSystem(x));
+ }
return list;
}
diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp
index 37be0afccf..246df127ad 100644
--- a/src/gui/text/qfontengine_ft.cpp
+++ b/src/gui/text/qfontengine_ft.cpp
@@ -99,6 +99,13 @@ static bool ft_getSfntTable(void *user_data, uint tag, uchar *buffer, uint *leng
static QFontEngineFT::Glyph emptyGlyph = {0, 0, 0, 0, 0, 0, 0, 0};
+static const QFontEngine::HintStyle ftInitialDefaultHintStyle =
+#ifdef Q_OS_WIN
+ QFontEngineFT::HintFull;
+#else
+ QFontEngineFT::HintNone;
+#endif
+
// -------------------------- Freetype support ------------------------------
class QtFreetypeData
@@ -629,11 +636,7 @@ QFontEngineFT::QFontEngineFT(const QFontDef &fd)
antialias = true;
freetype = 0;
default_load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
-#ifndef Q_OS_WIN
- default_hint_style = HintNone;
-#else
- default_hint_style = HintFull;
-#endif
+ default_hint_style = ftInitialDefaultHintStyle;
subpixelType = Subpixel_None;
lcdFilterType = 0;
#if defined(FT_LCD_FILTER_H)
@@ -760,6 +763,24 @@ bool QFontEngineFT::init(FaceId faceId, bool antialias, GlyphFormat format,
return true;
}
+void QFontEngineFT::setQtDefaultHintStyle(QFont::HintingPreference hintingPreference)
+{
+ switch (hintingPreference) {
+ case QFont::PreferNoHinting:
+ setDefaultHintStyle(HintNone);
+ break;
+ case QFont::PreferFullHinting:
+ setDefaultHintStyle(HintFull);
+ break;
+ case QFont::PreferVerticalHinting:
+ setDefaultHintStyle(HintLight);
+ break;
+ case QFont::PreferDefaultHinting:
+ setDefaultHintStyle(ftInitialDefaultHintStyle);
+ break;
+ }
+}
+
void QFontEngineFT::setDefaultHintStyle(HintStyle style)
{
default_hint_style = style;
diff --git a/src/gui/text/qfontengine_ft_p.h b/src/gui/text/qfontengine_ft_p.h
index 7b28a4064f..b81e51bf2e 100644
--- a/src/gui/text/qfontengine_ft_p.h
+++ b/src/gui/text/qfontengine_ft_p.h
@@ -281,7 +281,7 @@ private:
virtual int getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) Q_DECL_OVERRIDE;
-
+ void setQtDefaultHintStyle(QFont::HintingPreference hintingPreference);
virtual void setDefaultHintStyle(HintStyle style) Q_DECL_OVERRIDE;
virtual QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
@@ -307,6 +307,7 @@ private:
friend class QFontEngineFTRawFont;
friend class QFontconfigDatabase;
friend class QBasicFontDatabase;
+ friend class QCoreTextFontDatabase;
friend class QFontEngineMultiFontConfig;
int loadFlags(QGlyphSet *set, GlyphFormat format, int flags, bool &hsubpixel, int &vfactor) const;
diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h
index bb34155d31..780104bc37 100644
--- a/src/gui/text/qfontengine_p.h
+++ b/src/gui/text/qfontengine_p.h
@@ -49,6 +49,7 @@
#include "QtCore/qatomic.h"
#include <QtCore/qvarlengtharray.h>
#include <QtCore/QLinkedList>
+#include <QtCore/qhashfunctions.h>
#include "private/qtextengine_p.h"
#include "private/qfont_p.h"
@@ -328,12 +329,18 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QFontEngine::ShaperFlags)
inline bool operator ==(const QFontEngine::FaceId &f1, const QFontEngine::FaceId &f2)
{
- return (f1.index == f2.index) && (f1.encoding == f2.encoding) && (f1.filename == f2.filename);
+ return f1.index == f2.index && f1.encoding == f2.encoding && f1.filename == f2.filename && f1.uuid == f2.uuid;
}
-inline uint qHash(const QFontEngine::FaceId &f)
+inline uint qHash(const QFontEngine::FaceId &f, uint seed = 0)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(f.filename)))
{
- return qHash((f.index << 16) + f.encoding) + qHash(f.filename + f.uuid);
+ QtPrivate::QHashCombine hash;
+ seed = hash(seed, f.filename);
+ seed = hash(seed, f.uuid);
+ seed = hash(seed, f.index);
+ seed = hash(seed, f.encoding);
+ return seed;
}
diff --git a/src/plugins/platforms/cocoa/qcocoaautoreleasepool.h b/src/gui/text/qfontengineglyphcache.cpp
index 8b2a9f3788..f6fdfa3ce3 100644
--- a/src/plugins/platforms/cocoa/qcocoaautoreleasepool.h
+++ b/src/gui/text/qfontengineglyphcache.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@@ -31,23 +31,13 @@
**
****************************************************************************/
-#ifndef QCOCOAAUTORELEASEPOOL_H
-#define QCOCOAAUTORELEASEPOOL_H
-
-#undef slots
-#include <qglobal.h>
-#include <Cocoa/Cocoa.h>
+#include <private/qfontengineglyphcache_p.h>
QT_BEGIN_NAMESPACE
-class QCocoaAutoReleasePool
+
+// out-of-line to avoid vtable duplication, breaking e.g. RTTI
+QFontEngineGlyphCache::~QFontEngineGlyphCache()
{
-public:
- QCocoaAutoReleasePool();
- ~QCocoaAutoReleasePool();
+}
-private:
- NSAutoreleasePool *pool;
-};
QT_END_NAMESPACE
-
-#endif // QCOCOAAUTORELEASEPOOL_H
diff --git a/src/gui/text/qfontengineglyphcache_p.h b/src/gui/text/qfontengineglyphcache_p.h
index 6cf4d2f1ba..def42c22a3 100644
--- a/src/gui/text/qfontengineglyphcache_p.h
+++ b/src/gui/text/qfontengineglyphcache_p.h
@@ -56,7 +56,7 @@
QT_BEGIN_NAMESPACE
-class QFontEngineGlyphCache: public QSharedData
+class Q_GUI_EXPORT QFontEngineGlyphCache: public QSharedData
{
public:
QFontEngineGlyphCache(QFontEngine::GlyphFormat format, const QTransform &matrix) : m_format(format), m_transform(matrix)
@@ -64,7 +64,7 @@ public:
Q_ASSERT(m_format != QFontEngine::Format_None);
}
- virtual ~QFontEngineGlyphCache() { }
+ virtual ~QFontEngineGlyphCache();
QFontEngine::GlyphFormat glyphFormat() const { return m_format; }
const QTransform &transform() const { return m_transform; }
diff --git a/src/gui/text/qfontmetrics.h b/src/gui/text/qfontmetrics.h
index 2031f022d4..4c2c6317ba 100644
--- a/src/gui/text/qfontmetrics.h
+++ b/src/gui/text/qfontmetrics.h
@@ -93,11 +93,11 @@ public:
QRect boundingRect(QChar) const;
QRect boundingRect(const QString &text) const;
- QRect boundingRect(const QRect &r, int flags, const QString &text, int tabstops=0, int *tabarray=0) const;
+ QRect boundingRect(const QRect &r, int flags, const QString &text, int tabstops = 0, int *tabarray = Q_NULLPTR) const;
inline QRect boundingRect(int x, int y, int w, int h, int flags, const QString &text,
- int tabstops=0, int *tabarray=0) const
+ int tabstops = 0, int *tabarray = Q_NULLPTR) const
{ return boundingRect(QRect(x, y, w, h), flags, text, tabstops, tabarray); }
- QSize size(int flags, const QString& str, int tabstops=0, int *tabarray=0) const;
+ QSize size(int flags, const QString& str, int tabstops = 0, int *tabarray = Q_NULLPTR) const;
QRect tightBoundingRect(const QString &text) const;
@@ -161,8 +161,8 @@ public:
QRectF boundingRect(const QString &string) const;
QRectF boundingRect(QChar) const;
- QRectF boundingRect(const QRectF &r, int flags, const QString& string, int tabstops=0, int *tabarray=0) const;
- QSizeF size(int flags, const QString& str, int tabstops=0, int *tabarray=0) const;
+ QRectF boundingRect(const QRectF &r, int flags, const QString& string, int tabstops = 0, int *tabarray = Q_NULLPTR) const;
+ QSizeF size(int flags, const QString& str, int tabstops = 0, int *tabarray = Q_NULLPTR) const;
QRectF tightBoundingRect(const QString &text) const;
diff --git a/src/gui/text/qfontsubset.cpp b/src/gui/text/qfontsubset.cpp
index 9f652084be..dc32405f36 100644
--- a/src/gui/text/qfontsubset.cpp
+++ b/src/gui/text/qfontsubset.cpp
@@ -350,6 +350,7 @@ struct qttf_head_table {
quint16 macStyle;
qint16 indexToLocFormat;
};
+Q_DECLARE_TYPEINFO(qttf_head_table, Q_PRIMITIVE_TYPE);
struct qttf_hhea_table {
@@ -362,6 +363,7 @@ struct qttf_hhea_table {
qint16 xMaxExtent;
quint16 numberOfHMetrics;
};
+Q_DECLARE_TYPEINFO(qttf_hhea_table, Q_PRIMITIVE_TYPE);
struct qttf_maxp_table {
@@ -373,6 +375,7 @@ struct qttf_maxp_table {
quint16 maxComponentElements;
quint16 maxComponentDepth;
};
+Q_DECLARE_TYPEINFO(qttf_maxp_table, Q_PRIMITIVE_TYPE);
struct qttf_name_table {
QString copyright;
@@ -380,6 +383,7 @@ struct qttf_name_table {
QString subfamily;
QString postscript_name;
};
+Q_DECLARE_TYPEINFO(qttf_name_table, Q_MOVABLE_TYPE);
static QTtfTable generateHead(const qttf_head_table &head);
@@ -411,9 +415,9 @@ Q_DECLARE_TYPEINFO(QTtfGlyph, Q_MOVABLE_TYPE);
static QTtfGlyph generateGlyph(int index, const QPainterPath &path, qreal advance, qreal lsb, qreal ppem);
// generates glyf, loca and hmtx
-static QList<QTtfTable> generateGlyphTables(qttf_font_tables &tables, const QList<QTtfGlyph> &_glyphs);
+static QVector<QTtfTable> generateGlyphTables(qttf_font_tables &tables, const QVector<QTtfGlyph> &_glyphs);
-static QByteArray bindFont(const QList<QTtfTable>& _tables);
+static QByteArray bindFont(const QVector<QTtfTable>& _tables);
static quint32 checksum(const QByteArray &table)
@@ -607,12 +611,13 @@ struct QTtfNameRecord {
quint16 nameId;
QString value;
};
+Q_DECLARE_TYPEINFO(QTtfNameRecord, Q_MOVABLE_TYPE);
-static QTtfTable generateName(const QList<QTtfNameRecord> &name);
+static QTtfTable generateName(const QVector<QTtfNameRecord> &name);
static QTtfTable generateName(const qttf_name_table &name)
{
- QList<QTtfNameRecord> list;
+ QVector<QTtfNameRecord> list;
QTtfNameRecord rec;
rec.nameId = 0;
rec.value = name.copyright;
@@ -636,7 +641,7 @@ static QTtfTable generateName(const qttf_name_table &name)
}
// ####### should probably generate Macintosh/Roman name entries as well
-static QTtfTable generateName(const QList<QTtfNameRecord> &name)
+static QTtfTable generateName(const QVector<QTtfNameRecord> &name)
{
const int char_size = 2;
@@ -707,7 +712,7 @@ struct TTF_POINT {
};
Q_DECLARE_TYPEINFO(TTF_POINT, Q_PRIMITIVE_TYPE);
-static void convertPath(const QPainterPath &path, QList<TTF_POINT> *points, QList<int> *endPoints, qreal ppem)
+static void convertPath(const QPainterPath &path, QVector<TTF_POINT> *points, QVector<int> *endPoints, qreal ppem)
{
int numElements = path.elementCount();
for (int i = 0; i < numElements - 1; ++i) {
@@ -829,7 +834,7 @@ static void convertPath(const QPainterPath &path, QList<TTF_POINT> *points, QLis
endPoints->append(points->size() - 1);
}
-static void getBounds(const QList<TTF_POINT> &points, qint16 *xmin, qint16 *xmax, qint16 *ymin, qint16 *ymax)
+static void getBounds(const QVector<TTF_POINT> &points, qint16 *xmin, qint16 *xmax, qint16 *ymin, qint16 *ymax)
{
*xmin = points.at(0).x;
*xmax = *xmin;
@@ -844,7 +849,7 @@ static void getBounds(const QList<TTF_POINT> &points, qint16 *xmin, qint16 *xmax
}
}
-static int convertToRelative(QList<TTF_POINT> *points)
+static int convertToRelative(QVector<TTF_POINT> *points)
{
// convert points to relative and setup flags
// qDebug() << "relative points:";
@@ -897,7 +902,7 @@ static int convertToRelative(QList<TTF_POINT> *points)
return point_array_size;
}
-static void getGlyphData(QTtfGlyph *glyph, const QList<TTF_POINT> &points, const QList<int> &endPoints, int point_array_size)
+static void getGlyphData(QTtfGlyph *glyph, const QVector<TTF_POINT> &points, const QVector<int> &endPoints, int point_array_size)
{
const int max_size = 5*sizeof(qint16) // header
+ endPoints.size()*sizeof(quint16) // end points of contours
@@ -947,8 +952,8 @@ static void getGlyphData(QTtfGlyph *glyph, const QList<TTF_POINT> &points, const
static QTtfGlyph generateGlyph(int index, const QPainterPath &path, qreal advance, qreal lsb, qreal ppem)
{
- QList<TTF_POINT> points;
- QList<int> endPoints;
+ QVector<TTF_POINT> points;
+ QVector<int> endPoints;
QTtfGlyph glyph;
glyph.index = index;
glyph.advanceWidth = qRound(advance * 2048. / ppem);
@@ -983,10 +988,10 @@ static bool operator <(const QTtfGlyph &g1, const QTtfGlyph &g2)
return g1.index < g2.index;
}
-static QList<QTtfTable> generateGlyphTables(qttf_font_tables &tables, const QList<QTtfGlyph> &_glyphs)
+static QVector<QTtfTable> generateGlyphTables(qttf_font_tables &tables, const QVector<QTtfGlyph> &_glyphs)
{
const int max_size_small = 65536*2;
- QList<QTtfGlyph> glyphs = _glyphs;
+ QVector<QTtfGlyph> glyphs = _glyphs;
std::sort(glyphs.begin(), glyphs.end());
Q_ASSERT(tables.maxp.numGlyphs == glyphs.at(glyphs.size()-1).index + 1);
@@ -1049,7 +1054,7 @@ static QList<QTtfTable> generateGlyphTables(qttf_font_tables &tables, const QLis
Q_ASSERT(loca.data.size() == ls.offset());
Q_ASSERT(hmtx.data.size() == hs.offset());
- QList<QTtfTable> list;
+ QVector<QTtfTable> list;
list.append(glyf);
list.append(loca);
list.append(hmtx);
@@ -1061,9 +1066,9 @@ static bool operator <(const QTtfTable &t1, const QTtfTable &t2)
return t1.tag < t2.tag;
}
-static QByteArray bindFont(const QList<QTtfTable>& _tables)
+static QByteArray bindFont(const QVector<QTtfTable>& _tables)
{
- QList<QTtfTable> tables = _tables;
+ QVector<QTtfTable> tables = _tables;
std::sort(tables.begin(), tables.end());
@@ -1154,7 +1159,7 @@ QByteArray QFontSubset::toTruetype() const
qreal ppem = fontEngine->fontDef.pixelSize;
#define TO_TTF(x) qRound(x * 2048. / ppem)
- QList<QTtfGlyph> glyphs;
+ QVector<QTtfGlyph> glyphs;
QFontEngine::Properties properties = fontEngine->properties();
// initialize some stuff needed in createWidthArray
@@ -1225,7 +1230,7 @@ QByteArray QFontSubset::toTruetype() const
}
- QList<QTtfTable> tables = generateGlyphTables(font, glyphs);
+ QVector<QTtfTable> tables = generateGlyphTables(font, glyphs);
tables.append(generateHead(font.head));
tables.append(generateHhea(font.hhea));
tables.append(generateMaxp(font.maxp));
diff --git a/src/gui/text/qfontsubset_p.h b/src/gui/text/qfontsubset_p.h
index da8589de3f..4abdb48c0d 100644
--- a/src/gui/text/qfontsubset_p.h
+++ b/src/gui/text/qfontsubset_p.h
@@ -79,7 +79,7 @@ public:
const int object_id;
bool noEmbed;
QFontEngine *fontEngine;
- QList<int> glyph_indices;
+ QVector<int> glyph_indices;
mutable int downloaded_glyphs;
mutable bool standard_font;
int nGlyphs() const { return glyph_indices.size(); }
diff --git a/src/gui/text/qglyphrun.cpp b/src/gui/text/qglyphrun.cpp
index e6d6863134..642313d340 100644
--- a/src/gui/text/qglyphrun.cpp
+++ b/src/gui/text/qglyphrun.cpp
@@ -49,7 +49,6 @@ QT_BEGIN_NAMESPACE
\ingroup text
\ingroup shared
- \mainclass
When Qt displays a string of text encoded in Unicode, it will first convert the Unicode points
into a list of glyph indexes and a list of positions based on one or more fonts. The Unicode
diff --git a/src/gui/text/qglyphrun.h b/src/gui/text/qglyphrun.h
index d3034b7546..9f51a49a6d 100644
--- a/src/gui/text/qglyphrun.h
+++ b/src/gui/text/qglyphrun.h
@@ -59,9 +59,13 @@ public:
QGlyphRun();
QGlyphRun(const QGlyphRun &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QGlyphRun &operator=(QGlyphRun &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QGlyphRun &operator=(const QGlyphRun &other);
~QGlyphRun();
- void swap(QGlyphRun &other) { qSwap(d, other.d); }
+ void swap(QGlyphRun &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QRawFont rawFont() const;
void setRawFont(const QRawFont &rawFont);
@@ -78,8 +82,6 @@ public:
void clear();
- QGlyphRun &operator=(const QGlyphRun &other);
-
bool operator==(const QGlyphRun &other) const;
inline bool operator!=(const QGlyphRun &other) const
{ return !operator==(other); }
diff --git a/src/gui/text/qplatformfontdatabase.cpp b/src/gui/text/qplatformfontdatabase.cpp
index 8764c8cebf..0695c2eff4 100644
--- a/src/gui/text/qplatformfontdatabase.cpp
+++ b/src/gui/text/qplatformfontdatabase.cpp
@@ -40,6 +40,9 @@
#include <QtCore/QLibraryInfo>
#include <QtCore/QDir>
+#include <algorithm>
+#include <iterator>
+
QT_BEGIN_NAMESPACE
void qt_registerFont(const QString &familyname, const QString &stylename,
@@ -450,11 +453,11 @@ bool QPlatformFontDatabase::fontsAlwaysScalable() const
QList<int> QPlatformFontDatabase::standardSizes() const
{
QList<int> ret;
- static const unsigned short standard[] =
- { 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 0 };
- ret.reserve(int(sizeof(standard) / sizeof(standard[0])));
- const unsigned short *sizes = standard;
- while (*sizes) ret << *sizes++;
+ static const quint8 standard[] =
+ { 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 };
+ static const int num_standards = int(sizeof standard / sizeof *standard);
+ ret.reserve(num_standards);
+ std::copy(standard, standard + num_standards, std::back_inserter(ret));
return ret;
}
@@ -471,7 +474,7 @@ QFontEngine::SubpixelAntialiasingType QPlatformFontDatabase::subpixelAntialiasin
// ### copied to tools/makeqpf/qpf2.cpp
// see the Unicode subset bitfields in the MSDN docs
-static const ushort requiredUnicodeBits[QFontDatabase::WritingSystemsCount][2] = {
+static const quint8 requiredUnicodeBits[QFontDatabase::WritingSystemsCount][2] = {
{ 127, 127 }, // Any
{ 0, 127 }, // Latin
{ 7, 127 }, // Greek
diff --git a/src/gui/text/qplatformfontdatabase.h b/src/gui/text/qplatformfontdatabase.h
index 0615df65d6..3331d96f8b 100644
--- a/src/gui/text/qplatformfontdatabase.h
+++ b/src/gui/text/qplatformfontdatabase.h
@@ -47,7 +47,9 @@
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QList>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/QHash>
+#endif
#include <QtGui/QFontDatabase>
#include <QtGui/private/qfontengine_p.h>
#include <QtGui/private/qfont_p.h>
diff --git a/src/gui/text/qrawfont.cpp b/src/gui/text/qrawfont.cpp
index fedf58872b..0fd5f510c7 100644
--- a/src/gui/text/qrawfont.cpp
+++ b/src/gui/text/qrawfont.cpp
@@ -55,7 +55,6 @@ QT_BEGIN_NAMESPACE
\ingroup text
\ingroup shared
- \mainclass
\note QRawFont is a low level class. For most purposes QFont is a more appropriate class.
diff --git a/src/gui/text/qrawfont.h b/src/gui/text/qrawfont.h
index 3798555de5..d710658a9b 100644
--- a/src/gui/text/qrawfont.h
+++ b/src/gui/text/qrawfont.h
@@ -72,13 +72,15 @@ public:
qreal pixelSize,
QFont::HintingPreference hintingPreference = QFont::PreferDefaultHinting);
QRawFont(const QRawFont &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QRawFont &operator=(QRawFont &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QRawFont &operator=(const QRawFont &other);
~QRawFont();
- bool isValid() const;
+ void swap(QRawFont &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
- QRawFont &operator=(const QRawFont &other);
-
- void swap(QRawFont &other) { qSwap(d, other.d); }
+ bool isValid() const;
bool operator==(const QRawFont &other) const;
inline bool operator!=(const QRawFont &other) const
diff --git a/src/gui/text/qstatictext.cpp b/src/gui/text/qstatictext.cpp
index fc95a859e7..74f4b10305 100644
--- a/src/gui/text/qstatictext.cpp
+++ b/src/gui/text/qstatictext.cpp
@@ -39,6 +39,10 @@
QT_BEGIN_NAMESPACE
+QStaticTextUserData::~QStaticTextUserData()
+{
+}
+
/*!
\class QStaticText
\brief The QStaticText class enables optimized drawing of text when the text and its layout
@@ -49,7 +53,6 @@ QT_BEGIN_NAMESPACE
\ingroup multimedia
\ingroup text
\ingroup shared
- \mainclass
QStaticText provides a way to cache layout data for a block of text so that it can be drawn
more efficiently than by using QPainter::drawText() in which the layout information is
@@ -555,6 +558,9 @@ namespace {
case PdmDevicePixelRatio:
val = 1;
break;
+ case PdmDevicePixelRatioScaled:
+ val = devicePixelRatioFScale();
+ break;
default:
val = 0;
qWarning("DrawTextItemDevice::metric: Invalid metric command");
diff --git a/src/gui/text/qstatictext.h b/src/gui/text/qstatictext.h
index d2825e73ac..0a1d9429b4 100644
--- a/src/gui/text/qstatictext.h
+++ b/src/gui/text/qstatictext.h
@@ -57,9 +57,13 @@ public:
QStaticText();
QStaticText(const QString &text);
QStaticText(const QStaticText &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QStaticText &operator=(QStaticText &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QStaticText &operator=(const QStaticText &);
~QStaticText();
- void swap(QStaticText &other) { qSwap(data, other.data); }
+ void swap(QStaticText &other) Q_DECL_NOTHROW { qSwap(data, other.data); }
void setText(const QString &text);
QString text() const;
@@ -80,7 +84,6 @@ public:
void setPerformanceHint(PerformanceHint performanceHint);
PerformanceHint performanceHint() const;
- QStaticText &operator=(const QStaticText &);
bool operator==(const QStaticText &) const;
bool operator!=(const QStaticText &) const;
diff --git a/src/gui/text/qstatictext_p.h b/src/gui/text/qstatictext_p.h
index 088e49e2fc..49ca24d51c 100644
--- a/src/gui/text/qstatictext_p.h
+++ b/src/gui/text/qstatictext_p.h
@@ -52,7 +52,8 @@
QT_BEGIN_NAMESPACE
-class QStaticTextUserData
+// ### Qt 6: Unexport again, if QOpenGLStaticTextUserData (the one from QtOpenGL) is gone by then
+class Q_GUI_EXPORT QStaticTextUserData
{
public:
enum Type {
@@ -61,7 +62,7 @@ public:
};
QStaticTextUserData(Type t) : ref(0), type(t) {}
- virtual ~QStaticTextUserData() {}
+ virtual ~QStaticTextUserData();
QAtomicInt ref;
Type type;
diff --git a/src/gui/text/qsyntaxhighlighter.cpp b/src/gui/text/qsyntaxhighlighter.cpp
index 162c646a98..f180a839b7 100644
--- a/src/gui/text/qsyntaxhighlighter.cpp
+++ b/src/gui/text/qsyntaxhighlighter.cpp
@@ -90,13 +90,13 @@ void QSyntaxHighlighterPrivate::applyFormatChanges()
QTextLayout *layout = currentBlock.layout();
- QList<QTextLayout::FormatRange> ranges = layout->additionalFormats();
+ QVector<QTextLayout::FormatRange> ranges = layout->formats();
const int preeditAreaStart = layout->preeditAreaPosition();
const int preeditAreaLength = layout->preeditAreaText().length();
if (preeditAreaLength != 0) {
- QList<QTextLayout::FormatRange>::Iterator it = ranges.begin();
+ QVector<QTextLayout::FormatRange>::Iterator it = ranges.begin();
while (it != ranges.end()) {
if (it->start >= preeditAreaStart
&& it->start + it->length <= preeditAreaStart + preeditAreaLength) {
@@ -142,7 +142,7 @@ void QSyntaxHighlighterPrivate::applyFormatChanges()
}
if (formatsChanged) {
- layout->setAdditionalFormats(ranges);
+ layout->setFormats(ranges);
doc->markContentsDirty(currentBlock.position(), currentBlock.length());
}
}
@@ -329,7 +329,7 @@ void QSyntaxHighlighter::setDocument(QTextDocument *doc)
QTextCursor cursor(d->doc);
cursor.beginEditBlock();
for (QTextBlock blk = d->doc->begin(); blk.isValid(); blk = blk.next())
- blk.layout()->clearAdditionalFormats();
+ blk.layout()->clearFormats();
cursor.endEditBlock();
}
d->doc = doc;
diff --git a/src/gui/text/qtextcursor.h b/src/gui/text/qtextcursor.h
index f04055603c..350f38cd02 100644
--- a/src/gui/text/qtextcursor.h
+++ b/src/gui/text/qtextcursor.h
@@ -66,10 +66,13 @@ public:
explicit QTextCursor(const QTextBlock &block);
explicit QTextCursor(QTextCursorPrivate *d);
QTextCursor(const QTextCursor &cursor);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QTextCursor &operator=(QTextCursor &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QTextCursor &operator=(const QTextCursor &other);
~QTextCursor();
- void swap(QTextCursor &other) { qSwap(d, other.d); }
+ void swap(QTextCursor &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isNull() const;
diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp
index 29e00d481e..0affd3239d 100644
--- a/src/gui/text/qtextdocument.cpp
+++ b/src/gui/text/qtextdocument.cpp
@@ -532,7 +532,7 @@ QTextOption QTextDocument::defaultTextOption() const
/*!
\since 4.3
- Sets the default text option.
+ Sets the default text option to \a option.
*/
void QTextDocument::setDefaultTextOption(const QTextOption &option)
{
@@ -1401,7 +1401,9 @@ static bool findInBlock(const QTextBlock &block, const QRegExp &expression, int
/*!
\overload
- Finds the next occurrence, matching the regular expression, \a expr, in the document.
+ Finds the next occurrence that matches the given regular expression,
+ \a expr, within the same paragraph in the document.
+
The search starts at the given \a from position, and proceeds forwards
through the document unless specified otherwise in the search options.
The \a options control the type of search performed. The FindCaseSensitively
@@ -1454,7 +1456,9 @@ QTextCursor QTextDocument::find(const QRegExp & expr, int from, FindFlags option
/*!
\overload
- Finds the next occurrence, matching the regular expression, \a expr, in the document.
+ Finds the next occurrence that matches the given regular expression,
+ \a expr, within the same paragraph in the document.
+
The search starts at the position of the given from \a cursor, and proceeds
forwards through the document unless specified otherwise in the search
options. The \a options control the type of search performed. The FindCaseSensitively
@@ -1463,7 +1467,7 @@ QTextCursor QTextDocument::find(const QRegExp & expr, int from, FindFlags option
Returns a cursor with the match selected if a match was found; otherwise
returns a null cursor.
- If the given \a from cursor has a selection, the search begins after the
+ If the given \a cursor has a selection, the search begins after the
selection; otherwise it begins at the cursor's position.
By default the search is case-sensitive, and can match text anywhere in the
@@ -1525,7 +1529,9 @@ static bool findInBlock(const QTextBlock &block, const QRegularExpression &expre
/*!
\since 5.5
- Finds the next occurrence, matching the regular expression, \a expr, in the document.
+ Finds the next occurrence that matches the given regular expression,
+ \a expr, within the same paragraph in the document.
+
The search starts at the given \a from position, and proceeds forwards
through the document unless specified otherwise in the search options.
The \a options control the type of search performed.
@@ -1578,7 +1584,9 @@ QTextCursor QTextDocument::find(const QRegularExpression &expr, int from, FindFl
/*!
\since 5.5
- Finds the next occurrence, matching the regular expression, \a expr, in the document.
+ Finds the next occurrence that matches the given regular expression,
+ \a expr, within the same paragraph in the document.
+
The search starts at the position of the given \a cursor, and proceeds
forwards through the document unless specified otherwise in the search
options. The \a options control the type of search performed.
@@ -1948,7 +1956,7 @@ void QTextDocument::print(QPagedPaintDevice *printer) const
for (QTextBlock srcBlock = firstBlock(), dstBlock = clonedDoc->firstBlock();
srcBlock.isValid() && dstBlock.isValid();
srcBlock = srcBlock.next(), dstBlock = dstBlock.next()) {
- dstBlock.layout()->setAdditionalFormats(srcBlock.layout()->additionalFormats());
+ dstBlock.layout()->setFormats(srcBlock.layout()->formats());
}
QAbstractTextDocumentLayout *layout = doc->documentLayout();
diff --git a/src/gui/text/qtextdocument.h b/src/gui/text/qtextdocument.h
index ca80a88033..f05b624704 100644
--- a/src/gui/text/qtextdocument.h
+++ b/src/gui/text/qtextdocument.h
@@ -109,11 +109,11 @@ class Q_GUI_EXPORT QTextDocument : public QObject
Q_PROPERTY(QUrl baseUrl READ baseUrl WRITE setBaseUrl NOTIFY baseUrlChanged)
public:
- explicit QTextDocument(QObject *parent = 0);
- explicit QTextDocument(const QString &text, QObject *parent = 0);
+ explicit QTextDocument(QObject *parent = Q_NULLPTR);
+ explicit QTextDocument(const QString &text, QObject *parent = Q_NULLPTR);
~QTextDocument();
- QTextDocument *clone(QObject *parent = 0) const;
+ QTextDocument *clone(QObject *parent = Q_NULLPTR) const;
bool isEmpty() const;
virtual void clear();
@@ -157,17 +157,17 @@ public:
};
Q_DECLARE_FLAGS(FindFlags, FindFlag)
- QTextCursor find(const QString &subString, int from = 0, FindFlags options = 0) const;
- QTextCursor find(const QString &subString, const QTextCursor &cursor, FindFlags options = 0) const;
+ QTextCursor find(const QString &subString, int from = 0, FindFlags options = FindFlags()) const;
+ QTextCursor find(const QString &subString, const QTextCursor &cursor, FindFlags options = FindFlags()) const;
#ifndef QT_NO_REGEXP
- QTextCursor find(const QRegExp &expr, int from = 0, FindFlags options = 0) const;
- QTextCursor find(const QRegExp &expr, const QTextCursor &cursor, FindFlags options = 0) const;
+ QTextCursor find(const QRegExp &expr, int from = 0, FindFlags options = FindFlags()) const;
+ QTextCursor find(const QRegExp &expr, const QTextCursor &cursor, FindFlags options = FindFlags()) const;
#endif
#ifndef QT_NO_REGULAREXPRESSION
- QTextCursor find(const QRegularExpression &expr, int from = 0, FindFlags options = 0) const;
- QTextCursor find(const QRegularExpression &expr, const QTextCursor &cursor, FindFlags options = 0) const;
+ QTextCursor find(const QRegularExpression &expr, int from = 0, FindFlags options = FindFlags()) const;
+ QTextCursor find(const QRegularExpression &expr, const QTextCursor &cursor, FindFlags options = FindFlags()) const;
#endif
QTextFrame *frameAt(int pos) const;
diff --git a/src/gui/text/qtextdocumentlayout.cpp b/src/gui/text/qtextdocumentlayout.cpp
index 5864ca0b1a..c7bbcea4f4 100644
--- a/src/gui/text/qtextdocumentlayout.cpp
+++ b/src/gui/text/qtextdocumentlayout.cpp
@@ -106,7 +106,7 @@ public:
bool sizeDirty;
bool layoutDirty;
- QList<QPointer<QTextFrame> > floats;
+ QVector<QPointer<QTextFrame> > floats;
};
QTextFrameData::QTextFrameData()
@@ -467,9 +467,9 @@ public:
void drawFlow(const QPointF &offset, QPainter *painter, const QAbstractTextDocumentLayout::PaintContext &context,
QTextFrame::Iterator it, const QList<QTextFrame *> &floats, QTextBlock *cursorBlockNeedingRepaint) const;
void drawBlock(const QPointF &offset, QPainter *painter, const QAbstractTextDocumentLayout::PaintContext &context,
- QTextBlock bl, bool inRootFrame) const;
+ const QTextBlock &bl, bool inRootFrame) const;
void drawListItem(const QPointF &offset, QPainter *painter, const QAbstractTextDocumentLayout::PaintContext &context,
- QTextBlock bl, const QTextCharFormat *selectionFormat) const;
+ const QTextBlock &bl, const QTextCharFormat *selectionFormat) const;
void drawTableCell(const QRectF &cellRect, QPainter *painter, const QAbstractTextDocumentLayout::PaintContext &cell_context,
QTextTable *table, QTextTableData *td, int r, int c,
QTextBlock *cursorBlockNeedingRepaint, QPointF *cursorBlockOffset) const;
@@ -487,7 +487,7 @@ public:
HitPoint hitTest(QTextFrame::Iterator it, HitPoint hit, const QFixedPoint &p,
int *position, QTextLayout **l, Qt::HitTestAccuracy accuracy) const;
HitPoint hitTest(QTextTable *table, const QFixedPoint &point, int *position, QTextLayout **l, Qt::HitTestAccuracy accuracy) const;
- HitPoint hitTest(QTextBlock bl, const QFixedPoint &point, int *position, QTextLayout **l, Qt::HitTestAccuracy accuracy) const;
+ HitPoint hitTest(const QTextBlock &bl, const QFixedPoint &point, int *position, QTextLayout **l, Qt::HitTestAccuracy accuracy) const;
QTextLayoutStruct layoutCell(QTextTable *t, const QTextTableCell &cell, QFixed width,
int layoutFrom, int layoutTo, QTextTableData *tableData, QFixed absoluteTableY,
@@ -749,7 +749,7 @@ QTextDocumentLayoutPrivate::hitTest(QTextTable *table, const QFixedPoint &point,
}
QTextDocumentLayoutPrivate::HitPoint
-QTextDocumentLayoutPrivate::hitTest(QTextBlock bl, const QFixedPoint &point, int *position, QTextLayout **l,
+QTextDocumentLayoutPrivate::hitTest(const QTextBlock &bl, const QFixedPoint &point, int *position, QTextLayout **l,
Qt::HitTestAccuracy accuracy) const
{
QTextLayout *tl = bl.layout();
@@ -1071,7 +1071,9 @@ void QTextDocumentLayoutPrivate::drawFrame(const QPointF &offset, QPainter *pain
it = frameIteratorForYPosition(QFixed::fromReal(context.clip.top()));
QList<QTextFrame *> floats;
- for (int i = 0; i < fd->floats.count(); ++i)
+ const int numFloats = fd->floats.count();
+ floats.reserve(numFloats);
+ for (int i = 0; i < numFloats; ++i)
floats.append(fd->floats.at(i));
drawFlow(off, painter, context, it, floats, &cursorBlockNeedingRepaint);
@@ -1283,7 +1285,7 @@ void QTextDocumentLayoutPrivate::drawFlow(const QPointF &offset, QPainter *paint
void QTextDocumentLayoutPrivate::drawBlock(const QPointF &offset, QPainter *painter,
const QAbstractTextDocumentLayout::PaintContext &context,
- QTextBlock bl, bool inRootFrame) const
+ const QTextBlock &bl, bool inRootFrame) const
{
const QTextLayout *tl = bl.layout();
QRectF r = tl->boundingRect();
@@ -1377,7 +1379,7 @@ void QTextDocumentLayoutPrivate::drawBlock(const QPointF &offset, QPainter *pain
void QTextDocumentLayoutPrivate::drawListItem(const QPointF &offset, QPainter *painter,
const QAbstractTextDocumentLayout::PaintContext &context,
- QTextBlock bl, const QTextCharFormat *selectionFormat) const
+ const QTextBlock &bl, const QTextCharFormat *selectionFormat) const
{
Q_Q(const QTextDocumentLayout);
const QTextBlockFormat blockFormat = bl.blockFormat();
diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp
index 29a633f350..6b98c14205 100644
--- a/src/gui/text/qtextengine.cpp
+++ b/src/gui/text/qtextengine.cpp
@@ -1120,6 +1120,15 @@ QT_BEGIN_INCLUDE_NAMESPACE
QT_END_INCLUDE_NAMESPACE
+#if defined(Q_OS_OSX) && !defined(QT_NO_FREETYPE)
+static const char *s_shapersForOsxFreeType[] =
+{
+ "ot",
+ "fallback",
+ Q_NULLPTR
+};
+#endif
+
int QTextEngine::shapeTextWithHarfbuzzNG(const QScriptItem &si, const ushort *string, int itemLength, QFontEngine *fontEngine, const QVector<uint> &itemBoundaries, bool kerningEnabled) const
{
uint glyphs_shaped = 0;
@@ -1172,7 +1181,15 @@ int QTextEngine::shapeTextWithHarfbuzzNG(const QScriptItem &si, const ushort *st
};
const int num_features = 1;
- bool shapedOk = hb_shape_full(hb_font, buffer, features, num_features, 0);
+ const char *const *shaper_list = Q_NULLPTR;
+#if defined(Q_OS_OSX) && !defined(QT_NO_FREETYPE)
+ // What's behind QFontEngine::FaceData::user_data isn't compatible between CoreText and
+ // FreeType font engines - specifically functions in hb-coretext.cc would run into undefined
+ // behavior with data from the FreeType engine. The OpenType shaper works with that engine.
+ if (actualFontEngine->type() == QFontEngine::Freetype)
+ shaper_list = s_shapersForOsxFreeType;
+#endif
+ bool shapedOk = hb_shape_full(hb_font, buffer, features, num_features, shaper_list);
if (Q_UNLIKELY(!shapedOk)) {
hb_buffer_destroy(buffer);
return 0;
@@ -2571,7 +2588,7 @@ void QTextEngine::setPreeditArea(int position, const QString &preeditText)
clearLineData();
}
-void QTextEngine::setFormats(const QList<QTextLayout::FormatRange> &formats)
+void QTextEngine::setFormats(const QVector<QTextLayout::FormatRange> &formats)
{
if (formats.isEmpty()) {
if (!specialData)
@@ -2863,6 +2880,7 @@ QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
if (!tabArray.isEmpty()) {
if (isRightToLeft()) { // rebase the tabArray positions.
QList<QTextOption::Tab> newTabs;
+ newTabs.reserve(tabArray.count());
QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
while(iter != tabArray.end()) {
QTextOption::Tab tab = *iter;
@@ -2946,17 +2964,17 @@ QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
namespace {
class FormatRangeComparatorByStart {
- const QList<QTextLayout::FormatRange> &list;
+ const QVector<QTextLayout::FormatRange> &list;
public:
- FormatRangeComparatorByStart(const QList<QTextLayout::FormatRange> &list) : list(list) { }
+ FormatRangeComparatorByStart(const QVector<QTextLayout::FormatRange> &list) : list(list) { }
bool operator()(int a, int b) {
return list.at(a).start < list.at(b).start;
}
};
class FormatRangeComparatorByEnd {
- const QList<QTextLayout::FormatRange> &list;
+ const QVector<QTextLayout::FormatRange> &list;
public:
- FormatRangeComparatorByEnd(const QList<QTextLayout::FormatRange> &list) : list(list) { }
+ FormatRangeComparatorByEnd(const QVector<QTextLayout::FormatRange> &list) : list(list) { }
bool operator()(int a, int b) {
return list.at(a).start + list.at(a).length < list.at(b).start + list.at(b).length;
}
diff --git a/src/gui/text/qtextengine_p.h b/src/gui/text/qtextengine_p.h
index 39b9e0cb5a..d2b39f274c 100644
--- a/src/gui/text/qtextengine_p.h
+++ b/src/gui/text/qtextengine_p.h
@@ -400,6 +400,7 @@ public:
};
struct ItemDecoration {
+ ItemDecoration() {} // for QVector, don't use
ItemDecoration(qreal x1, qreal x2, qreal y, const QPen &pen):
x1(x1), x2(x2), y(y), pen(pen) {}
@@ -409,7 +410,7 @@ public:
QPen pen;
};
- typedef QList<ItemDecoration> ItemDecorationList;
+ typedef QVector<ItemDecoration> ItemDecorationList;
QTextEngine();
QTextEngine(const QString &str, const QFont &f);
@@ -570,9 +571,9 @@ public:
inline bool hasFormats() const
{ return block.docHandle() || (specialData && !specialData->formats.isEmpty()); }
- inline QList<QTextLayout::FormatRange> formats() const
- { return specialData ? specialData->formats : QList<QTextLayout::FormatRange>(); }
- void setFormats(const QList<QTextLayout::FormatRange> &formats);
+ inline QVector<QTextLayout::FormatRange> formats() const
+ { return specialData ? specialData->formats : QVector<QTextLayout::FormatRange>(); }
+ void setFormats(const QVector<QTextLayout::FormatRange> &formats);
private:
static void init(QTextEngine *e);
@@ -580,7 +581,7 @@ private:
struct SpecialData {
int preeditPosition;
QString preeditText;
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
QVector<QTextCharFormat> resolvedFormats;
// only used when no docHandle is available
QScopedPointer<QTextFormatCollection> formatCollection;
@@ -643,6 +644,7 @@ public:
LayoutData _layoutData;
void *_memory[MemSize];
};
+Q_DECLARE_TYPEINFO(QTextEngine::ItemDecoration, Q_MOVABLE_TYPE);
struct QTextLineItemIterator
{
diff --git a/src/gui/text/qtextformat.cpp b/src/gui/text/qtextformat.cpp
index ba4bdcc5ad..7dcd060ba1 100644
--- a/src/gui/text/qtextformat.cpp
+++ b/src/gui/text/qtextformat.cpp
@@ -38,7 +38,7 @@
#include <qdatastream.h>
#include <qdebug.h>
#include <qmap.h>
-#include <qhash.h>
+#include <qhashfunctions.h>
QT_BEGIN_NAMESPACE
@@ -1115,7 +1115,9 @@ void QTextFormat::setProperty(int propertyId, const QVector<QTextLength> &value)
if (!d)
d = new QTextFormatPrivate;
QVariantList list;
- for (int i=0; i<value.size(); ++i)
+ const int numValues = value.size();
+ list.reserve(numValues);
+ for (int i = 0; i < numValues; ++i)
list << value.at(i);
d->insertProperty(propertyId, list);
}
@@ -2041,6 +2043,7 @@ QTextBlockFormat::QTextBlockFormat(const QTextFormat &fmt)
void QTextBlockFormat::setTabPositions(const QList<QTextOption::Tab> &tabs)
{
QList<QVariant> list;
+ list.reserve(tabs.count());
QList<QTextOption::Tab>::ConstIterator iter = tabs.constBegin();
while (iter != tabs.constEnd()) {
QVariant v;
@@ -2065,6 +2068,7 @@ QList<QTextOption::Tab> QTextBlockFormat::tabPositions() const
QList<QTextOption::Tab> answer;
QList<QVariant> variantsList = qvariant_cast<QList<QVariant> >(variant);
QList<QVariant>::Iterator iter = variantsList.begin();
+ answer.reserve(variantsList.count());
while(iter != variantsList.end()) {
answer.append( qvariant_cast<QTextOption::Tab>(*iter));
++iter;
diff --git a/src/gui/text/qtextformat_p.h b/src/gui/text/qtextformat_p.h
index 29656bbafe..928cef6488 100644
--- a/src/gui/text/qtextformat_p.h
+++ b/src/gui/text/qtextformat_p.h
@@ -47,7 +47,6 @@
#include "QtGui/qtextformat.h"
#include "QtCore/qvector.h"
-#include "QtCore/qhash.h"
QT_BEGIN_NAMESPACE
diff --git a/src/gui/text/qtextimagehandler.cpp b/src/gui/text/qtextimagehandler.cpp
index e85890baf2..1ba2cb31ca 100644
--- a/src/gui/text/qtextimagehandler.cpp
+++ b/src/gui/text/qtextimagehandler.cpp
@@ -256,10 +256,10 @@ void QTextImageHandler::drawObject(QPainter *p, const QRectF &rect, QTextDocumen
const QTextImageFormat imageFormat = format.toImageFormat();
if (QCoreApplication::instance()->thread() != QThread::currentThread()) {
- const QImage image = getImage(doc, imageFormat, p->device()->devicePixelRatio());
+ const QImage image = getImage(doc, imageFormat, p->device()->devicePixelRatioF());
p->drawImage(rect, image, image.rect());
} else {
- const QPixmap pixmap = getPixmap(doc, imageFormat, p->device()->devicePixelRatio());
+ const QPixmap pixmap = getPixmap(doc, imageFormat, p->device()->devicePixelRatioF());
p->drawPixmap(rect, pixmap, pixmap.rect());
}
}
diff --git a/src/gui/text/qtextlayout.cpp b/src/gui/text/qtextlayout.cpp
index 013cd8ae0f..0c729c74d1 100644
--- a/src/gui/text/qtextlayout.cpp
+++ b/src/gui/text/qtextlayout.cpp
@@ -69,7 +69,7 @@ QT_BEGIN_NAMESPACE
for a specified area in the text layout's content.
\inmodule QtGui
- \sa QTextLayout::setAdditionalFormats(), QTextLayout::draw()
+ \sa QTextLayout::setFormats(), QTextLayout::draw()
*/
/*!
@@ -87,6 +87,20 @@ QT_BEGIN_NAMESPACE
Specifies the format to apply.
*/
+/*! \fn bool operator==(const FormatRange &lhs, const FormatRange &rhs)
+ \relates QTextLayout::FormatRange
+
+ Returns true if the \c {start}, \c {length}, and \c {format} fields
+ in \a lhs and \a rhs contain the same values respectively.
+ */
+
+/*! \fn bool operator!=(const FormatRange &lhs, const FormatRange &rhs)
+ \relates QTextLayout::FormatRange
+
+ Returns true if any of the \c {start}, \c {length}, or \c {format} fields
+ in \a lhs and \a rhs contain different values respectively.
+ */
+
/*!
\class QTextInlineObject
\reentrant
@@ -485,39 +499,76 @@ QString QTextLayout::preeditAreaText() const
return d->preeditAreaText();
}
+#if QT_DEPRECATED_SINCE(5, 6)
+/*!
+ \obsolete Use setFormats() instead.
+*/
+void QTextLayout::setAdditionalFormats(const QList<FormatRange> &formatList)
+{
+ setFormats(formatList.toVector());
+}
+#endif // deprecated since 5.6
/*!
- Sets the additional formats supported by the text layout to \a formatList.
+ \since 5.6
+
+ Sets the additional formats supported by the text layout to \a formats.
The formats are applied with preedit area text in place.
- \sa additionalFormats(), clearAdditionalFormats()
+ \sa formats(), clearFormats()
*/
-void QTextLayout::setAdditionalFormats(const QList<FormatRange> &formatList)
+void QTextLayout::setFormats(const QVector<FormatRange> &formats)
{
- d->setFormats(formatList);
+ d->setFormats(formats);
if (d->block.docHandle())
d->block.docHandle()->documentChange(d->block.position(), d->block.length());
}
+#if QT_DEPRECATED_SINCE(5, 6)
/*!
- Returns the list of additional formats supported by the text layout.
+ \obsolete Use formats() instead.
\sa setAdditionalFormats(), clearAdditionalFormats()
*/
QList<QTextLayout::FormatRange> QTextLayout::additionalFormats() const
{
+ return formats().toList();
+}
+#endif // deprecated since 5.6
+
+/*!
+ \since 5.6
+
+ Returns the list of additional formats supported by the text layout.
+
+ \sa setFormats(), clearFormats()
+*/
+QVector<QTextLayout::FormatRange> QTextLayout::formats() const
+{
return d->formats();
}
+#if QT_DEPRECATED_SINCE(5, 6)
+/*!
+ \obsolete Use clearFormats() instead.
+*/
+void QTextLayout::clearAdditionalFormats()
+{
+ clearFormats();
+}
+#endif // deprecated since 5.6
+
/*!
+ \since 5.6
+
Clears the list of additional formats supported by the text layout.
- \sa additionalFormats(), setAdditionalFormats()
+ \sa formats(), setFormats()
*/
-void QTextLayout::clearAdditionalFormats()
+void QTextLayout::clearFormats()
{
- setAdditionalFormats(QList<FormatRange>());
+ setFormats(QVector<FormatRange>());
}
/*!
diff --git a/src/gui/text/qtextlayout.h b/src/gui/text/qtextlayout.h
index 47dcd388e2..f74d4d4229 100644
--- a/src/gui/text/qtextlayout.h
+++ b/src/gui/text/qtextlayout.h
@@ -62,7 +62,7 @@ class Q_GUI_EXPORT QTextInlineObject
{
public:
QTextInlineObject(int i, QTextEngine *e) : itm(i), eng(e) {}
- inline QTextInlineObject() : itm(0), eng(0) {}
+ inline QTextInlineObject() : itm(0), eng(Q_NULLPTR) {}
inline bool isValid() const { return eng; }
QRectF rect() const;
@@ -100,7 +100,7 @@ public:
// does itemization
QTextLayout();
QTextLayout(const QString& text);
- QTextLayout(const QString& text, const QFont &font, QPaintDevice *paintdevice = 0);
+ QTextLayout(const QString& text, const QFont &font, QPaintDevice *paintdevice = Q_NULLPTR);
QTextLayout(const QTextBlock &b);
~QTextLayout();
@@ -125,10 +125,20 @@ public:
int start;
int length;
QTextCharFormat format;
+
+ friend bool operator==(const FormatRange &lhs, const FormatRange &rhs)
+ { return lhs.start == rhs.start && lhs.length == rhs.length && lhs.format == rhs.format; }
+ friend bool operator!=(const FormatRange &lhs, const FormatRange &rhs)
+ { return !operator==(lhs, rhs); }
};
- void setAdditionalFormats(const QList<FormatRange> &overrides);
- QList<FormatRange> additionalFormats() const;
- void clearAdditionalFormats();
+#if QT_DEPRECATED_SINCE(5, 6)
+ QT_DEPRECATED_X("Use setFormats()") void setAdditionalFormats(const QList<FormatRange> &overrides);
+ QT_DEPRECATED_X("Use formats()") QList<FormatRange> additionalFormats() const;
+ QT_DEPRECATED_X("Use clearFormats()") void clearAdditionalFormats();
+#endif
+ void setFormats(const QVector<FormatRange> &overrides);
+ QVector<FormatRange> formats() const;
+ void clearFormats();
void setCacheEnabled(bool enable);
bool cacheEnabled() const;
@@ -192,7 +202,7 @@ private:
class Q_GUI_EXPORT QTextLine
{
public:
- inline QTextLine() : index(0), eng(0) {}
+ inline QTextLine() : index(0), eng(Q_NULLPTR) {}
inline bool isValid() const { return eng; }
QRectF rect() const;
@@ -237,7 +247,7 @@ public:
int lineNumber() const { return index; }
- void draw(QPainter *p, const QPointF &point, const QTextLayout::FormatRange *selection = 0) const;
+ void draw(QPainter *p, const QPointF &point, const QTextLayout::FormatRange *selection = Q_NULLPTR) const;
#if !defined(QT_NO_RAWFONT)
QList<QGlyphRun> glyphRuns(int from = -1, int length = -1) const;
diff --git a/src/gui/text/qtextobject.h b/src/gui/text/qtextobject.h
index 9ad912d992..fbb90e42b0 100644
--- a/src/gui/text/qtextobject.h
+++ b/src/gui/text/qtextobject.h
@@ -190,7 +190,7 @@ class Q_GUI_EXPORT QTextBlock
friend class QSyntaxHighlighter;
public:
inline QTextBlock(QTextDocumentPrivate *priv, int b) : p(priv), n(b) {}
- inline QTextBlock() : p(0), n(0) {}
+ inline QTextBlock() : p(Q_NULLPTR), n(0) {}
inline QTextBlock(const QTextBlock &o) : p(o.p), n(o.n) {}
inline QTextBlock &operator=(const QTextBlock &o) { p = o.p; n = o.n; return *this; }
@@ -247,7 +247,7 @@ public:
friend class QTextBlock;
iterator(const QTextDocumentPrivate *priv, int begin, int end, int f) : p(priv), b(begin), e(end), n(f) {}
public:
- iterator() : p(0), b(0), e(0), n(0) {}
+ iterator() : p(Q_NULLPTR), b(0), e(0), n(0) {}
iterator(const iterator &o) : p(o.p), b(o.b), e(o.e), n(o.n) {}
QTextFragment fragment() const;
@@ -289,7 +289,7 @@ class Q_GUI_EXPORT QTextFragment
{
public:
inline QTextFragment(const QTextDocumentPrivate *priv, int f, int fe) : p(priv), n(f), ne(fe) {}
- inline QTextFragment() : p(0), n(0), ne(0) {}
+ inline QTextFragment() : p(Q_NULLPTR), n(0), ne(0) {}
inline QTextFragment(const QTextFragment &o) : p(o.p), n(o.n), ne(o.ne) {}
inline QTextFragment &operator=(const QTextFragment &o) { p = o.p; n = o.n; ne = o.ne; return *this; }
diff --git a/src/gui/text/qtextodfwriter.cpp b/src/gui/text/qtextodfwriter.cpp
index 6b17a264b1..429e910f18 100644
--- a/src/gui/text/qtextodfwriter.cpp
+++ b/src/gui/text/qtextodfwriter.cpp
@@ -396,7 +396,7 @@ void QTextOdfWriter::writeInlineCharacter(QXmlStreamWriter &writer, const QTextF
writer.writeEndElement(); // frame
}
-void QTextOdfWriter::writeFormats(QXmlStreamWriter &writer, QSet<int> formats) const
+void QTextOdfWriter::writeFormats(QXmlStreamWriter &writer, const QSet<int> &formats) const
{
writer.writeStartElement(officeNS, QString::fromLatin1("automatic-styles"));
QVector<QTextFormat> allStyles = m_document->allFormats();
diff --git a/src/gui/text/qtextodfwriter_p.h b/src/gui/text/qtextodfwriter_p.h
index 20805a8d27..15a4b40796 100644
--- a/src/gui/text/qtextodfwriter_p.h
+++ b/src/gui/text/qtextodfwriter_p.h
@@ -83,7 +83,7 @@ public:
bool createArchive() const { return m_createArchive; }
void writeBlock(QXmlStreamWriter &writer, const QTextBlock &block);
- void writeFormats(QXmlStreamWriter &writer, QSet<int> formatIds) const;
+ void writeFormats(QXmlStreamWriter &writer, const QSet<int> &formatIds) const;
void writeBlockFormat(QXmlStreamWriter &writer, QTextBlockFormat format, int formatIndex) const;
void writeCharacterFormat(QXmlStreamWriter &writer, QTextCharFormat format, int formatIndex) const;
void writeListFormat(QXmlStreamWriter &writer, QTextListFormat format, int formatIndex) const;
diff --git a/src/gui/text/qtextoption.cpp b/src/gui/text/qtextoption.cpp
index dbafcfd58e..5a4f6b7954 100644
--- a/src/gui/text/qtextoption.cpp
+++ b/src/gui/text/qtextoption.cpp
@@ -146,6 +146,7 @@ void QTextOption::setTabArray(const QList<qreal> &tabStops)
d = new QTextOptionPrivate;
QList<QTextOption::Tab> tabs;
QTextOption::Tab tab;
+ tabs.reserve(tabStops.count());
foreach (qreal pos, tabStops) {
tab.position = pos;
tabs.append(tab);
@@ -174,10 +175,11 @@ void QTextOption::setTabs(const QList<QTextOption::Tab> &tabStops)
*/
QList<qreal> QTextOption::tabArray() const
{
+ QList<qreal> answer;
if (!d)
- return QList<qreal>();
+ return answer;
- QList<qreal> answer;
+ answer.reserve(d->tabStops.count());
QList<QTextOption::Tab>::ConstIterator iter = d->tabStops.constBegin();
while(iter != d->tabStops.constEnd()) {
answer.append( (*iter).position);
diff --git a/src/gui/text/qtexttable.h b/src/gui/text/qtexttable.h
index 6ceb1fdd0f..4ff7d19e85 100644
--- a/src/gui/text/qtexttable.h
+++ b/src/gui/text/qtexttable.h
@@ -48,7 +48,7 @@ class QTextTablePrivate;
class Q_GUI_EXPORT QTextTableCell
{
public:
- QTextTableCell() : table(0) {}
+ QTextTableCell() : table(Q_NULLPTR) {}
~QTextTableCell() {}
QTextTableCell(const QTextTableCell &o) : table(o.table), fragment(o.fragment) {}
QTextTableCell &operator=(const QTextTableCell &o)
@@ -63,7 +63,7 @@ public:
int rowSpan() const;
int columnSpan() const;
- inline bool isValid() const { return table != 0; }
+ inline bool isValid() const { return table != Q_NULLPTR; }
QTextCursor firstCursorPosition() const;
QTextCursor lastCursorPosition() const;
diff --git a/src/gui/text/qzip.cpp b/src/gui/text/qzip.cpp
index 1d621db0e6..6053466148 100644
--- a/src/gui/text/qzip.cpp
+++ b/src/gui/text/qzip.cpp
@@ -303,6 +303,7 @@ enum HostOS {
HostOS400 = 18,
HostOSX = 19
};
+Q_DECLARE_TYPEINFO(HostOS, Q_PRIMITIVE_TYPE);
enum GeneralPurposeFlag {
Encrypted = 0x01,
@@ -314,6 +315,7 @@ enum GeneralPurposeFlag {
Utf8Names = 0x0800,
CentralDirectoryEncrypted = 0x2000
};
+Q_DECLARE_TYPEINFO(GeneralPurposeFlag, Q_PRIMITIVE_TYPE);
enum CompressionMethod {
CompressionMethodStored = 0,
@@ -340,6 +342,7 @@ enum CompressionMethod {
CompressionMethodPPMd = 98,
CompressionMethodWzAES = 99
};
+Q_DECLARE_TYPEINFO(CompressionMethod, Q_PRIMITIVE_TYPE);
struct LocalFileHeader
{
@@ -354,6 +357,7 @@ struct LocalFileHeader
uchar file_name_length[2];
uchar extra_field_length[2];
};
+Q_DECLARE_TYPEINFO(LocalFileHeader, Q_PRIMITIVE_TYPE);
struct DataDescriptor
{
@@ -361,6 +365,7 @@ struct DataDescriptor
uchar compressed_size[4];
uchar uncompressed_size[4];
};
+Q_DECLARE_TYPEINFO(DataDescriptor, Q_PRIMITIVE_TYPE);
struct CentralFileHeader
{
@@ -382,6 +387,7 @@ struct CentralFileHeader
uchar offset_local_header[4];
LocalFileHeader toLocalHeader() const;
};
+Q_DECLARE_TYPEINFO(CentralFileHeader, Q_PRIMITIVE_TYPE);
struct EndOfDirectory
{
@@ -394,6 +400,7 @@ struct EndOfDirectory
uchar dir_start_offset[4];
uchar comment_length[2];
};
+Q_DECLARE_TYPEINFO(EndOfDirectory, Q_PRIMITIVE_TYPE);
struct FileHeader
{
@@ -402,38 +409,7 @@ struct FileHeader
QByteArray extra_field;
QByteArray file_comment;
};
-
-QZipReader::FileInfo::FileInfo()
- : isDir(false), isFile(false), isSymLink(false), crc(0), size(0)
-{
-}
-
-QZipReader::FileInfo::~FileInfo()
-{
-}
-
-QZipReader::FileInfo::FileInfo(const FileInfo &other)
-{
- operator=(other);
-}
-
-QZipReader::FileInfo& QZipReader::FileInfo::operator=(const FileInfo &other)
-{
- filePath = other.filePath;
- isDir = other.isDir;
- isFile = other.isFile;
- isSymLink = other.isSymLink;
- permissions = other.permissions;
- crc = other.crc;
- size = other.size;
- lastModified = other.lastModified;
- return *this;
-}
-
-bool QZipReader::FileInfo::isValid() const
-{
- return isDir || isFile || isSymLink;
-}
+Q_DECLARE_TYPEINFO(FileHeader, Q_MOVABLE_TYPE);
class QZipPrivate
{
@@ -449,18 +425,19 @@ public:
delete device;
}
- void fillFileInfo(int index, QZipReader::FileInfo &fileInfo) const;
+ QZipReader::FileInfo fillFileInfo(int index) const;
QIODevice *device;
bool ownDevice;
bool dirtyFileTree;
- QList<FileHeader> fileHeaders;
+ QVector<FileHeader> fileHeaders;
QByteArray comment;
uint start_of_directory;
};
-void QZipPrivate::fillFileInfo(int index, QZipReader::FileInfo &fileInfo) const
+QZipReader::FileInfo QZipPrivate::fillFileInfo(int index) const
{
+ QZipReader::FileInfo fileInfo;
FileHeader header = fileHeaders.at(index);
quint32 mode = readUInt(header.h.external_file_attributes);
const HostOS hostOS = HostOS(readUShort(header.h.version_made) >> 8);
@@ -502,7 +479,7 @@ void QZipPrivate::fillFileInfo(int index, QZipReader::FileInfo &fileInfo) const
break;
default:
qWarning("QZip: Zip entry format at %d is not supported.", index);
- return; // we don't support anything else
+ return fileInfo; // we don't support anything else
}
ushort general_purpose_bits = readUShort(header.h.general_purpose_bits);
@@ -519,6 +496,8 @@ void QZipPrivate::fillFileInfo(int index, QZipReader::FileInfo &fileInfo) const
fileInfo.filePath = fileInfo.filePath.mid(1);
while (!fileInfo.filePath.isEmpty() && fileInfo.filePath.at(fileInfo.filePath.size() - 1) == QLatin1Char('/'))
fileInfo.filePath.chop(1);
+
+ return fileInfo;
}
class QZipReaderPrivate : public QZipPrivate
@@ -913,15 +892,14 @@ bool QZipReader::exists() const
/*!
Returns the list of files the archive contains.
*/
-QList<QZipReader::FileInfo> QZipReader::fileInfoList() const
+QVector<QZipReader::FileInfo> QZipReader::fileInfoList() const
{
d->scanFiles();
- QList<QZipReader::FileInfo> files;
- for (int i = 0; i < d->fileHeaders.size(); ++i) {
- QZipReader::FileInfo fi;
- d->fillFileInfo(i, fi);
- files.append(fi);
- }
+ QVector<FileInfo> files;
+ const int numFileHeaders = d->fileHeaders.size();
+ files.reserve(numFileHeaders);
+ for (int i = 0; i < numFileHeaders; ++i)
+ files.append(d->fillFileInfo(i));
return files;
}
@@ -945,10 +923,9 @@ int QZipReader::count() const
QZipReader::FileInfo QZipReader::entryInfoAt(int index) const
{
d->scanFiles();
- QZipReader::FileInfo fi;
if (index >= 0 && index < d->fileHeaders.count())
- d->fillFileInfo(index, fi);
- return fi;
+ return d->fillFileInfo(index);
+ return QZipReader::FileInfo();
}
/*!
@@ -1044,7 +1021,7 @@ bool QZipReader::extractAll(const QString &destinationDir) const
QDir baseDir(destinationDir);
// create directories first
- QList<FileInfo> allFiles = fileInfoList();
+ const QVector<FileInfo> allFiles = fileInfoList();
foreach (const FileInfo &fi, allFiles) {
const QString absPath = destinationDir + QDir::separator() + fi.filePath;
if (fi.isDir) {
diff --git a/src/gui/text/qzipreader_p.h b/src/gui/text/qzipreader_p.h
index df7e2d26e9..7f26bfb184 100644
--- a/src/gui/text/qzipreader_p.h
+++ b/src/gui/text/qzipreader_p.h
@@ -70,13 +70,14 @@ public:
bool isReadable() const;
bool exists() const;
- struct Q_GUI_EXPORT FileInfo
+ struct FileInfo
{
- FileInfo();
- FileInfo(const FileInfo &other);
- ~FileInfo();
- FileInfo &operator=(const FileInfo &other);
- bool isValid() const;
+ FileInfo() Q_DECL_NOTHROW
+ : isDir(false), isFile(false), isSymLink(false), crc(0), size(0)
+ {}
+
+ bool isValid() const Q_DECL_NOTHROW { return isDir || isFile || isSymLink; }
+
QString filePath;
uint isDir : 1;
uint isFile : 1;
@@ -85,10 +86,9 @@ public:
uint crc;
qint64 size;
QDateTime lastModified;
- void *d;
};
- QList<FileInfo> fileInfoList() const;
+ QVector<FileInfo> fileInfoList() const;
int count() const;
FileInfo entryInfoAt(int index) const;
@@ -111,6 +111,8 @@ private:
QZipReaderPrivate *d;
Q_DISABLE_COPY(QZipReader)
};
+Q_DECLARE_TYPEINFO(QZipReader::FileInfo, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QZipReader::Status, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE
diff --git a/src/gui/text/text.pri b/src/gui/text/text.pri
index 61e239f678..be60ba72cc 100644
--- a/src/gui/text/text.pri
+++ b/src/gui/text/text.pri
@@ -21,6 +21,7 @@ HEADERS += \
text/qtextdocument_p.h \
text/qtexthtmlparser_p.h \
text/qabstracttextdocumentlayout.h \
+ text/qabstracttextdocumentlayout_p.h \
text/qtextdocumentlayout_p.h \
text/qtextcursor.h \
text/qtextcursor_p.h \
@@ -47,6 +48,7 @@ HEADERS += \
SOURCES += \
text/qfont.cpp \
text/qfontengine.cpp \
+ text/qfontengineglyphcache.cpp \
text/qfontsubset.cpp \
text/qfontmetrics.cpp \
text/qfontdatabase.cpp \
diff --git a/src/gui/util/qvalidator.h b/src/gui/util/qvalidator.h
index 0435e4e9ff..a979a268aa 100644
--- a/src/gui/util/qvalidator.h
+++ b/src/gui/util/qvalidator.h
@@ -52,7 +52,7 @@ class Q_GUI_EXPORT QValidator : public QObject
{
Q_OBJECT
public:
- explicit QValidator(QObject * parent = 0);
+ explicit QValidator(QObject * parent = Q_NULLPTR);
~QValidator();
enum State {
@@ -86,8 +86,8 @@ class Q_GUI_EXPORT QIntValidator : public QValidator
Q_PROPERTY(int top READ top WRITE setTop NOTIFY topChanged)
public:
- explicit QIntValidator(QObject * parent = 0);
- QIntValidator(int bottom, int top, QObject *parent = 0);
+ explicit QIntValidator(QObject * parent = Q_NULLPTR);
+ QIntValidator(int bottom, int top, QObject *parent = Q_NULLPTR);
~QIntValidator();
QValidator::State validate(QString &, int &) const Q_DECL_OVERRIDE;
@@ -123,8 +123,8 @@ class Q_GUI_EXPORT QDoubleValidator : public QValidator
Q_PROPERTY(Notation notation READ notation WRITE setNotation NOTIFY notationChanged)
public:
- explicit QDoubleValidator(QObject * parent = 0);
- QDoubleValidator(double bottom, double top, int decimals, QObject *parent = 0);
+ explicit QDoubleValidator(QObject * parent = Q_NULLPTR);
+ QDoubleValidator(double bottom, double top, int decimals, QObject *parent = Q_NULLPTR);
~QDoubleValidator();
enum Notation {
@@ -167,8 +167,8 @@ class Q_GUI_EXPORT QRegExpValidator : public QValidator
Q_PROPERTY(QRegExp regExp READ regExp WRITE setRegExp NOTIFY regExpChanged)
public:
- explicit QRegExpValidator(QObject *parent = 0);
- explicit QRegExpValidator(const QRegExp& rx, QObject *parent = 0);
+ explicit QRegExpValidator(QObject *parent = Q_NULLPTR);
+ explicit QRegExpValidator(const QRegExp& rx, QObject *parent = Q_NULLPTR);
~QRegExpValidator();
virtual QValidator::State validate(QString& input, int& pos) const Q_DECL_OVERRIDE;
@@ -197,8 +197,8 @@ class Q_GUI_EXPORT QRegularExpressionValidator : public QValidator
Q_PROPERTY(QRegularExpression regularExpression READ regularExpression WRITE setRegularExpression NOTIFY regularExpressionChanged)
public:
- explicit QRegularExpressionValidator(QObject *parent = 0);
- explicit QRegularExpressionValidator(const QRegularExpression &re, QObject *parent = 0);
+ explicit QRegularExpressionValidator(QObject *parent = Q_NULLPTR);
+ explicit QRegularExpressionValidator(const QRegularExpression &re, QObject *parent = Q_NULLPTR);
~QRegularExpressionValidator();
virtual QValidator::State validate(QString &input, int &pos) const Q_DECL_OVERRIDE;
diff --git a/src/network/access/qabstractnetworkcache.h b/src/network/access/qabstractnetworkcache.h
index 352daa9700..326891b3dc 100644
--- a/src/network/access/qabstractnetworkcache.h
+++ b/src/network/access/qabstractnetworkcache.h
@@ -60,9 +60,12 @@ public:
QNetworkCacheMetaData(const QNetworkCacheMetaData &other);
~QNetworkCacheMetaData();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkCacheMetaData &operator=(QNetworkCacheMetaData &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkCacheMetaData &operator=(const QNetworkCacheMetaData &other);
- void swap(QNetworkCacheMetaData &other)
+ void swap(QNetworkCacheMetaData &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QNetworkCacheMetaData &other) const;
@@ -121,7 +124,7 @@ public Q_SLOTS:
virtual void clear() = 0;
protected:
- explicit QAbstractNetworkCache(QObject *parent = 0);
+ explicit QAbstractNetworkCache(QObject *parent = Q_NULLPTR);
QAbstractNetworkCache(QAbstractNetworkCachePrivate &dd, QObject *parent);
private:
diff --git a/src/network/access/qftp.cpp b/src/network/access/qftp.cpp
index a83d56f31f..74c95ecd5e 100644
--- a/src/network/access/qftp.cpp
+++ b/src/network/access/qftp.cpp
@@ -46,7 +46,6 @@
#include "qregexp.h"
#include "qtimer.h"
#include "qfileinfo.h"
-#include "qhash.h"
#include "qtcpserver.h"
#include "qlocale.h"
diff --git a/src/network/access/qhttpmultipart.h b/src/network/access/qhttpmultipart.h
index 2e08a3d6f8..5f865c059b 100644
--- a/src/network/access/qhttpmultipart.h
+++ b/src/network/access/qhttpmultipart.h
@@ -51,9 +51,12 @@ public:
QHttpPart();
QHttpPart(const QHttpPart &other);
~QHttpPart();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QHttpPart &operator=(QHttpPart &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QHttpPart &operator=(const QHttpPart &other);
- void swap(QHttpPart &other) { qSwap(d, other.d); }
+ void swap(QHttpPart &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QHttpPart &other) const;
inline bool operator!=(const QHttpPart &other) const
@@ -88,8 +91,8 @@ public:
AlternativeType
};
- explicit QHttpMultiPart(QObject *parent = 0);
- explicit QHttpMultiPart(ContentType contentType, QObject *parent = 0);
+ explicit QHttpMultiPart(QObject *parent = Q_NULLPTR);
+ explicit QHttpMultiPart(ContentType contentType, QObject *parent = Q_NULLPTR);
~QHttpMultiPart();
void append(const QHttpPart &httpPart);
diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp
index b7d17be955..c2d986ef3d 100644
--- a/src/network/access/qhttpnetworkconnection.cpp
+++ b/src/network/access/qhttpnetworkconnection.cpp
@@ -506,6 +506,53 @@ bool QHttpNetworkConnectionPrivate::handleAuthenticateChallenge(QAbstractSocket
return false;
}
+QUrl QHttpNetworkConnectionPrivate::parseRedirectResponse(QAbstractSocket *socket, QHttpNetworkReply *reply)
+{
+ if (!reply->request().isFollowRedirects())
+ return QUrl();
+
+ QUrl rUrl;
+ QList<QPair<QByteArray, QByteArray> > fields = reply->header();
+ foreach (const QNetworkReply::RawHeaderPair &header, fields) {
+ if (header.first.toLower() == "location") {
+ rUrl = QUrl::fromEncoded(header.second);
+ break;
+ }
+ }
+
+ // If the location url is invalid/empty, we emit ProtocolUnknownError
+ if (!rUrl.isValid()) {
+ emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
+ return QUrl();
+ }
+
+ // Check if we have exceeded max redirects allowed
+ if (reply->request().redirectCount() <= 0) {
+ emitReplyError(socket, reply, QNetworkReply::TooManyRedirectsError);
+ return QUrl();
+ }
+
+ // Resolve the URL if it's relative
+ if (rUrl.isRelative())
+ rUrl = reply->request().url().resolved(rUrl);
+
+ // Check redirect url protocol
+ QString scheme = rUrl.scheme();
+ if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) {
+ QString previousUrlScheme = reply->request().url().scheme();
+ // Check if we're doing an unsecure redirect (https -> http)
+ if (previousUrlScheme == QLatin1String("https")
+ && scheme == QLatin1String("http")) {
+ emitReplyError(socket, reply, QNetworkReply::InsecureRedirectError);
+ return QUrl();
+ }
+ } else {
+ emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
+ return QUrl();
+ }
+ return rUrl;
+}
+
void QHttpNetworkConnectionPrivate::createAuthorization(QAbstractSocket *socket, QHttpNetworkRequest &request)
{
Q_ASSERT(socket);
@@ -802,6 +849,12 @@ QString QHttpNetworkConnectionPrivate::errorDetail(QNetworkReply::NetworkError e
case QNetworkReply::SslHandshakeFailedError:
errorString = QCoreApplication::translate("QHttp", "SSL handshake failed");
break;
+ case QNetworkReply::TooManyRedirectsError:
+ errorString = QCoreApplication::translate("QHttp", "Too many redirects");
+ break;
+ case QNetworkReply::InsecureRedirectError:
+ errorString = QCoreApplication::translate("QHttp", "Insecure redirect");
+ break;
default:
// all other errors are treated as QNetworkReply::UnknownNetworkError
errorString = extraDetail;
@@ -1389,7 +1442,7 @@ void QHttpNetworkConnectionPrivate::emitProxyAuthenticationRequired(const QHttpN
// but that does not matter because the signal will ultimately be emitted
// by the QNetworkAccessManager.
Q_ASSERT(chan->spdyRequestsToSend.count() > 0);
- reply = chan->spdyRequestsToSend.values().first().second;
+ reply = chan->spdyRequestsToSend.cbegin().value().second;
} else { // HTTP
#endif // QT_NO_SSL
reply = chan->reply;
diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h
index 115eef581e..9af39d416a 100644
--- a/src/network/access/qhttpnetworkconnection_p.h
+++ b/src/network/access/qhttpnetworkconnection_p.h
@@ -250,6 +250,7 @@ public:
void emitReplyError(QAbstractSocket *socket, QHttpNetworkReply *reply, QNetworkReply::NetworkError errorCode);
bool handleAuthenticateChallenge(QAbstractSocket *socket, QHttpNetworkReply *reply, bool isProxy, bool &resend);
+ QUrl parseRedirectResponse(QAbstractSocket *socket, QHttpNetworkReply *reply);
#ifndef QT_NO_NETWORKPROXY
QNetworkProxy networkProxy;
diff --git a/src/network/access/qhttpnetworkconnectionchannel.cpp b/src/network/access/qhttpnetworkconnectionchannel.cpp
index 257aa13718..8980ed7a41 100644
--- a/src/network/access/qhttpnetworkconnectionchannel.cpp
+++ b/src/network/access/qhttpnetworkconnectionchannel.cpp
@@ -511,6 +511,20 @@ void QHttpNetworkConnectionChannel::handleStatus()
bool resend = false;
switch (statusCode) {
+ case 301:
+ case 302:
+ case 303:
+ case 305:
+ case 307: {
+ // Parse the response headers and get the "location" url
+ QUrl redirectUrl = connection->d_func()->parseRedirectResponse(socket, reply);
+ if (redirectUrl.isValid())
+ reply->setRedirectUrl(redirectUrl);
+
+ if (qobject_cast<QHttpNetworkConnection *>(connection))
+ QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
+ break;
+ }
case 401: // auth required
case 407: // proxy auth required
if (connection->d_func()->handleAuthenticateChallenge(socket, reply, (statusCode == 407), resend)) {
diff --git a/src/network/access/qhttpnetworkheader.cpp b/src/network/access/qhttpnetworkheader.cpp
index af9f38cdec..cf8259294d 100644
--- a/src/network/access/qhttpnetworkheader.cpp
+++ b/src/network/access/qhttpnetworkheader.cpp
@@ -79,16 +79,8 @@ QByteArray QHttpNetworkHeaderPrivate::headerField(const QByteArray &name, const
QList<QByteArray> allValues = headerFieldValues(name);
if (allValues.isEmpty())
return defaultValue;
-
- QByteArray result;
- bool first = true;
- foreach (const QByteArray &value, allValues) {
- if (!first)
- result += ", ";
- first = false;
- result += value;
- }
- return result;
+ else
+ return allValues.join(", ");
}
QList<QByteArray> QHttpNetworkHeaderPrivate::headerFieldValues(const QByteArray &name) const
diff --git a/src/network/access/qhttpnetworkreply.cpp b/src/network/access/qhttpnetworkreply.cpp
index 80f3670660..dd108ad5c7 100644
--- a/src/network/access/qhttpnetworkreply.cpp
+++ b/src/network/access/qhttpnetworkreply.cpp
@@ -78,6 +78,23 @@ void QHttpNetworkReply::setUrl(const QUrl &url)
d->url = url;
}
+QUrl QHttpNetworkReply::redirectUrl() const
+{
+ return d_func()->redirectUrl;
+}
+
+void QHttpNetworkReply::setRedirectUrl(const QUrl &url)
+{
+ Q_D(QHttpNetworkReply);
+ d->redirectUrl = url;
+}
+
+bool QHttpNetworkReply::isHttpRedirect(int statusCode)
+{
+ return (statusCode == 301 || statusCode == 302 || statusCode == 303
+ || statusCode == 305 || statusCode == 307);
+}
+
qint64 QHttpNetworkReply::contentLength() const
{
return d_func()->contentLength();
@@ -267,6 +284,11 @@ void QHttpNetworkReply::setSpdyWasUsed(bool spdy)
d_func()->spdyUsed = spdy;
}
+bool QHttpNetworkReply::isRedirecting() const
+{
+ return d_func()->isRedirecting();
+}
+
QHttpNetworkConnection* QHttpNetworkReply::connection()
{
return d_func()->connection;
@@ -910,6 +932,14 @@ qint64 QHttpNetworkReplyPrivate::getChunkSize(QAbstractSocket *socket, qint64 *c
return bytes;
}
+bool QHttpNetworkReplyPrivate::isRedirecting() const
+{
+ // We're in the process of redirecting - if the HTTP status code says so and
+ // followRedirect is switched on
+ return (QHttpNetworkReply::isHttpRedirect(statusCode)
+ && request.isFollowRedirects());
+}
+
bool QHttpNetworkReplyPrivate::shouldEmitSignals()
{
// for 401 & 407 don't emit the data signals. Content along with these
diff --git a/src/network/access/qhttpnetworkreply_p.h b/src/network/access/qhttpnetworkreply_p.h
index 0fe298da27..6e81663500 100644
--- a/src/network/access/qhttpnetworkreply_p.h
+++ b/src/network/access/qhttpnetworkreply_p.h
@@ -127,8 +127,15 @@ public:
bool isSpdyUsed() const;
void setSpdyWasUsed(bool spdy);
+ bool isRedirecting() const;
+
QHttpNetworkConnection* connection();
+ QUrl redirectUrl() const;
+ void setRedirectUrl(const QUrl &url);
+
+ static bool isHttpRedirect(int statusCode);
+
#ifndef QT_NO_SSL
QSslConfiguration sslConfiguration() const;
void setSslConfiguration(const QSslConfiguration &config);
@@ -153,6 +160,7 @@ Q_SIGNALS:
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator);
#endif
void authenticationRequired(const QHttpNetworkRequest &request, QAuthenticator *authenticator);
+ void redirected(const QUrl &url, int httpStatus, int maxRedirectsRemaining);
private:
Q_DECLARE_PRIVATE(QHttpNetworkReply)
friend class QHttpSocketEngine;
@@ -185,6 +193,7 @@ public:
qint64 readReplyBodyChunked(QAbstractSocket *in, QByteDataBuffer *out);
qint64 getChunkSize(QAbstractSocket *in, qint64 *chunkSize);
+ bool isRedirecting() const;
bool shouldEmitSignals();
bool expectContent();
void eraseData();
@@ -245,6 +254,7 @@ public:
bool downstreamLimited;
char* userProvidedDownloadBuffer;
+ QUrl redirectUrl;
#ifndef QT_NO_COMPRESS
z_stream_s *inflateStrm;
diff --git a/src/network/access/qhttpnetworkrequest.cpp b/src/network/access/qhttpnetworkrequest.cpp
index ea1cd3d591..64172fc4fd 100644
--- a/src/network/access/qhttpnetworkrequest.cpp
+++ b/src/network/access/qhttpnetworkrequest.cpp
@@ -42,7 +42,7 @@ QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(QHttpNetworkRequest::Oper
QHttpNetworkRequest::Priority pri, const QUrl &newUrl)
: QHttpNetworkHeaderPrivate(newUrl), operation(op), priority(pri), uploadByteDevice(0),
autoDecompress(false), pipeliningAllowed(false), spdyAllowed(false),
- withCredentials(true), preConnect(false)
+ withCredentials(true), preConnect(false), followRedirect(false), redirectCount(0)
{
}
@@ -59,6 +59,8 @@ QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(const QHttpNetworkRequest
withCredentials = other.withCredentials;
ssl = other.ssl;
preConnect = other.preConnect;
+ followRedirect = other.followRedirect;
+ redirectCount = other.redirectCount;
}
QHttpNetworkRequestPrivate::~QHttpNetworkRequestPrivate()
@@ -217,6 +219,26 @@ void QHttpNetworkRequest::setPreConnect(bool preConnect)
d->preConnect = preConnect;
}
+bool QHttpNetworkRequest::isFollowRedirects() const
+{
+ return d->followRedirect;
+}
+
+void QHttpNetworkRequest::setFollowRedirects(bool followRedirect)
+{
+ d->followRedirect = followRedirect;
+}
+
+int QHttpNetworkRequest::redirectCount() const
+{
+ return d->redirectCount;
+}
+
+void QHttpNetworkRequest::setRedirectCount(int count)
+{
+ d->redirectCount = count;
+}
+
qint64 QHttpNetworkRequest::contentLength() const
{
return d->contentLength();
diff --git a/src/network/access/qhttpnetworkrequest_p.h b/src/network/access/qhttpnetworkrequest_p.h
index d136f22b7d..1add3c6150 100644
--- a/src/network/access/qhttpnetworkrequest_p.h
+++ b/src/network/access/qhttpnetworkrequest_p.h
@@ -118,6 +118,12 @@ public:
bool isPreConnect() const;
void setPreConnect(bool preConnect);
+ bool isFollowRedirects() const;
+ void setFollowRedirects(bool followRedirect);
+
+ int redirectCount() const;
+ void setRedirectCount(int count);
+
void setUploadByteDevice(QNonContiguousByteDevice *bd);
QNonContiguousByteDevice* uploadByteDevice() const;
@@ -154,6 +160,8 @@ public:
bool withCredentials;
bool ssl;
bool preConnect;
+ bool followRedirect;
+ int redirectCount;
};
diff --git a/src/network/access/qhttpthreaddelegate.cpp b/src/network/access/qhttpthreaddelegate.cpp
index be6fa01098..3fc4fa9dee 100644
--- a/src/network/access/qhttpthreaddelegate.cpp
+++ b/src/network/access/qhttpthreaddelegate.cpp
@@ -496,6 +496,9 @@ void QHttpThreadDelegate::finishedSlot()
emit error(statusCodeFromHttp(httpReply->statusCode(), httpRequest.url()), msg);
}
+ if (httpRequest.isFollowRedirects() && httpReply->isRedirecting())
+ emit redirected(httpReply->redirectUrl(), httpReply->statusCode(), httpReply->request().redirectCount() - 1);
+
emit downloadFinished();
QMetaObject::invokeMethod(httpReply, "deleteLater", Qt::QueuedConnection);
diff --git a/src/network/access/qhttpthreaddelegate_p.h b/src/network/access/qhttpthreaddelegate_p.h
index 9573d500ea..784e9c14b8 100644
--- a/src/network/access/qhttpthreaddelegate_p.h
+++ b/src/network/access/qhttpthreaddelegate_p.h
@@ -139,6 +139,8 @@ signals:
void downloadData(QByteArray);
void error(QNetworkReply::NetworkError, const QString);
void downloadFinished();
+ void redirected(const QUrl &url, int httpStatus, int maxRedirectsRemainig);
+
public slots:
// This are called via QueuedConnection from user thread
void startRequest();
diff --git a/src/network/access/qnetworkaccessauthenticationmanager_p.h b/src/network/access/qnetworkaccessauthenticationmanager_p.h
index 8f06ecb6b7..462827d7fc 100644
--- a/src/network/access/qnetworkaccessauthenticationmanager_p.h
+++ b/src/network/access/qnetworkaccessauthenticationmanager_p.h
@@ -64,7 +64,7 @@ public:
QString domain;
QString user;
QString password;
- bool isNull() {
+ bool isNull() const {
return domain.isNull() && user.isNull() && password.isNull();
}
};
diff --git a/src/network/access/qnetworkaccessbackend.cpp b/src/network/access/qnetworkaccessbackend.cpp
index 692af1b2fc..321352e045 100644
--- a/src/network/access/qnetworkaccessbackend.cpp
+++ b/src/network/access/qnetworkaccessbackend.cpp
@@ -37,7 +37,6 @@
#include "qnetworkrequest.h"
#include "qnetworkreply.h"
#include "qnetworkreply_p.h"
-#include "QtCore/qhash.h"
#include "QtCore/qmutex.h"
#include "QtCore/qstringlist.h"
#include "QtNetwork/private/qnetworksession_p.h"
diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp
index 84931cbb40..e6fb1a09a0 100644
--- a/src/network/access/qnetworkaccessmanager.cpp
+++ b/src/network/access/qnetworkaccessmanager.cpp
@@ -447,7 +447,6 @@ static void ensureInitialized()
QNetworkAccessManager::QNetworkAccessManager(QObject *parent)
: QObject(*new QNetworkAccessManagerPrivate, parent)
{
- Q_D(QNetworkAccessManager);
ensureInitialized();
qRegisterMetaType<QNetworkReply::NetworkError>();
@@ -467,6 +466,7 @@ QNetworkAccessManager::QNetworkAccessManager(QObject *parent)
qRegisterMetaType<QSharedPointer<char> >();
#ifndef QT_NO_BEARERMANAGEMENT
+ Q_D(QNetworkAccessManager);
if (!d->networkSessionRequired) {
// if a session is required, we track online state through
// the QNetworkSession's signals
diff --git a/src/network/access/qnetworkaccessmanager.h b/src/network/access/qnetworkaccessmanager.h
index 988eafa18b..c8df213ead 100644
--- a/src/network/access/qnetworkaccessmanager.h
+++ b/src/network/access/qnetworkaccessmanager.h
@@ -90,7 +90,7 @@ public:
};
#endif
- explicit QNetworkAccessManager(QObject *parent = 0);
+ explicit QNetworkAccessManager(QObject *parent = Q_NULLPTR);
~QNetworkAccessManager();
// ### Qt 6: turn into virtual
@@ -120,7 +120,7 @@ public:
QNetworkReply *put(const QNetworkRequest &request, const QByteArray &data);
QNetworkReply *put(const QNetworkRequest &request, QHttpMultiPart *multiPart);
QNetworkReply *deleteResource(const QNetworkRequest &request);
- QNetworkReply *sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = 0);
+ QNetworkReply *sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = Q_NULLPTR);
#ifndef QT_NO_BEARERMANAGEMENT
void setConfiguration(const QNetworkConfiguration &config);
@@ -157,7 +157,7 @@ Q_SIGNALS:
protected:
virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
- QIODevice *outgoingData = 0);
+ QIODevice *outgoingData = Q_NULLPTR);
protected Q_SLOTS:
QStringList supportedSchemesImplementation() const;
diff --git a/src/network/access/qnetworkcookie.h b/src/network/access/qnetworkcookie.h
index 2da86d3f81..27925c8201 100644
--- a/src/network/access/qnetworkcookie.h
+++ b/src/network/access/qnetworkcookie.h
@@ -59,9 +59,12 @@ public:
explicit QNetworkCookie(const QByteArray &name = QByteArray(), const QByteArray &value = QByteArray());
QNetworkCookie(const QNetworkCookie &other);
~QNetworkCookie();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkCookie &operator=(QNetworkCookie &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkCookie &operator=(const QNetworkCookie &other);
- void swap(QNetworkCookie &other) { qSwap(d, other.d); }
+ void swap(QNetworkCookie &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkCookie &other) const;
inline bool operator!=(const QNetworkCookie &other) const
diff --git a/src/network/access/qnetworkcookiejar.h b/src/network/access/qnetworkcookiejar.h
index 59ba7f8738..3ac78ea1c3 100644
--- a/src/network/access/qnetworkcookiejar.h
+++ b/src/network/access/qnetworkcookiejar.h
@@ -47,7 +47,7 @@ class Q_NETWORK_EXPORT QNetworkCookieJar: public QObject
{
Q_OBJECT
public:
- explicit QNetworkCookieJar(QObject *parent = 0);
+ explicit QNetworkCookieJar(QObject *parent = Q_NULLPTR);
virtual ~QNetworkCookieJar();
virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const;
diff --git a/src/network/access/qnetworkdiskcache.h b/src/network/access/qnetworkdiskcache.h
index 568d34dc0f..533eabce9b 100644
--- a/src/network/access/qnetworkdiskcache.h
+++ b/src/network/access/qnetworkdiskcache.h
@@ -47,7 +47,7 @@ class Q_NETWORK_EXPORT QNetworkDiskCache : public QAbstractNetworkCache
Q_OBJECT
public:
- explicit QNetworkDiskCache(QObject *parent = 0);
+ explicit QNetworkDiskCache(QObject *parent = Q_NULLPTR);
~QNetworkDiskCache();
QString cacheDirectory() const;
diff --git a/src/network/access/qnetworkreply.cpp b/src/network/access/qnetworkreply.cpp
index 3e77e1b874..26f7034c09 100644
--- a/src/network/access/qnetworkreply.cpp
+++ b/src/network/access/qnetworkreply.cpp
@@ -132,6 +132,14 @@ QNetworkReplyPrivate::QNetworkReplyPrivate()
\value BackgroundRequestNotAllowedError the background request
is not currently allowed due to platform policy.
+ \value TooManyRedirectsError while following redirects, the maximum
+ limit was reached. The limit is by default set to 50 or as set by
+ QNetworkRequest::setMaxRedirectsAllowed().
+
+ \value InsecureRedirectError while following redirects, the network
+ access API detected a redirect from a encrypted protocol (https) to an
+ unencrypted one (http).
+
\value ProxyConnectionRefusedError the connection to the proxy
server was refused (the proxy server is not accepting requests)
@@ -276,6 +284,19 @@ QNetworkReplyPrivate::QNetworkReplyPrivate()
*/
/*!
+ \fn void QNetworkReply::redirected(const QUrl &url)
+ \since 5.6
+
+ This signal is emitted if the QNetworkRequest::FollowRedirectsAttribute was
+ set in the request and the server responded with a 3xx status (specifically
+ 301, 302, 303, 305 or 307 status code) with a valid url in the location
+ header, indicating a HTTP redirect. The \a url parameter contains the new
+ redirect url as returned by the server in the location header.
+
+ \sa QNetworkRequest::FollowRedirectsAttribute
+*/
+
+/*!
\fn void QNetworkReply::metaDataChanged()
\omit FIXME: Update name? \endomit
@@ -498,7 +519,7 @@ QNetworkAccessManager *QNetworkReply::manager() const
*/
QNetworkRequest QNetworkReply::request() const
{
- return d_func()->request;
+ return d_func()->originalRequest;
}
/*!
@@ -549,9 +570,12 @@ bool QNetworkReply::isRunning() const
/*!
Returns the URL of the content downloaded or uploaded. Note that
- the URL may be different from that of the original request.
+ the URL may be different from that of the original request. If the
+ QNetworkRequest::FollowRedirectsAttribute was set in the request, then this
+ function returns the current url that the network API is accessing, i.e the
+ url emitted in the QNetworkReply::redirected signal.
- \sa request(), setUrl(), QNetworkRequest::url()
+ \sa request(), setUrl(), QNetworkRequest::url(), redirected()
*/
QUrl QNetworkReply::url() const
{
@@ -794,7 +818,7 @@ void QNetworkReply::setOperation(QNetworkAccessManager::Operation operation)
void QNetworkReply::setRequest(const QNetworkRequest &request)
{
Q_D(QNetworkReply);
- d->request = request;
+ d->originalRequest = request;
}
/*!
diff --git a/src/network/access/qnetworkreply.h b/src/network/access/qnetworkreply.h
index 91c9e77d8d..254dd3ff12 100644
--- a/src/network/access/qnetworkreply.h
+++ b/src/network/access/qnetworkreply.h
@@ -69,6 +69,8 @@ public:
TemporaryNetworkFailureError,
NetworkSessionFailedError,
BackgroundRequestNotAllowedError,
+ TooManyRedirectsError,
+ InsecureRedirectError,
UnknownNetworkError = 99,
// proxy errors (101-199):
@@ -153,12 +155,13 @@ Q_SIGNALS:
void sslErrors(const QList<QSslError> &errors);
void preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator);
#endif
+ void redirected(const QUrl &url);
void uploadProgress(qint64 bytesSent, qint64 bytesTotal);
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
protected:
- explicit QNetworkReply(QObject *parent = 0);
+ explicit QNetworkReply(QObject *parent = Q_NULLPTR);
QNetworkReply(QNetworkReplyPrivate &dd, QObject *parent);
virtual qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE;
diff --git a/src/network/access/qnetworkreply_p.h b/src/network/access/qnetworkreply_p.h
index f5fe7bd844..2a3a2e4297 100644
--- a/src/network/access/qnetworkreply_p.h
+++ b/src/network/access/qnetworkreply_p.h
@@ -69,6 +69,7 @@ public:
QNetworkReplyPrivate();
QNetworkRequest request;
+ QNetworkRequest originalRequest;
QUrl url;
QPointer<QNetworkAccessManager> manager;
qint64 readBufferMaxSize;
diff --git a/src/network/access/qnetworkreplyfileimpl.cpp b/src/network/access/qnetworkreplyfileimpl.cpp
index 8f51b2ca3b..1e5608bc90 100644
--- a/src/network/access/qnetworkreplyfileimpl.cpp
+++ b/src/network/access/qnetworkreplyfileimpl.cpp
@@ -36,7 +36,6 @@
#include "QtCore/qdatetime.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
-#include <QDebug>
QT_BEGIN_NAMESPACE
@@ -136,6 +135,7 @@ QNetworkReplyFileImpl::QNetworkReplyFileImpl(QObject *parent, const QNetworkRequ
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
}
+
void QNetworkReplyFileImpl::close()
{
Q_D(QNetworkReplyFileImpl);
@@ -182,8 +182,11 @@ qint64 QNetworkReplyFileImpl::readData(char *data, qint64 maxlen)
d->realFile.close();
if (ret == 0 && bytesAvailable() == 0)
return -1;
- else
+ else {
+ setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200);
+ setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, QLatin1String("OK"));
return ret;
+ }
}
diff --git a/src/network/access/qnetworkreplyhttpimpl.cpp b/src/network/access/qnetworkreplyhttpimpl.cpp
index c445677792..8c0c098147 100644
--- a/src/network/access/qnetworkreplyhttpimpl.cpp
+++ b/src/network/access/qnetworkreplyhttpimpl.cpp
@@ -49,6 +49,8 @@
#include "qthread.h"
#include "QtCore/qcoreapplication.h"
+#include <QtCore/private/qthread_p.h>
+
#include "qnetworkcookiejar.h"
#ifndef QT_NO_HTTP
@@ -166,6 +168,7 @@ QNetworkReplyHttpImpl::QNetworkReplyHttpImpl(QNetworkAccessManager* const manage
d->manager = manager;
d->managerPrivate = manager->d_func();
d->request = request;
+ d->originalRequest = request;
d->operation = operation;
d->outgoingData = outgoingData;
d->url = request.url();
@@ -483,7 +486,7 @@ bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &h
if (!nc)
return false; // no local cache
- QNetworkCacheMetaData metaData = nc->metaData(request.url());
+ QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
if (!metaData.isValid())
return false; // not in cache
@@ -597,7 +600,7 @@ QHttpNetworkRequest::Priority QNetworkReplyHttpImplPrivate::convert(const QNetwo
}
}
-void QNetworkReplyHttpImplPrivate::postRequest()
+void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpRequest)
{
Q_Q(QNetworkReplyHttpImpl);
@@ -621,8 +624,9 @@ void QNetworkReplyHttpImplPrivate::postRequest()
thread = managerPrivate->httpThread;
}
- QUrl url = request.url();
+ QUrl url = newHttpRequest.url();
httpRequest.setUrl(url);
+ httpRequest.setRedirectCount(newHttpRequest.maximumRedirectsAllowed());
QString scheme = url.scheme().toLower();
bool ssl = (scheme == QLatin1String("https")
@@ -638,7 +642,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
QNetworkProxy transparentProxy, cacheProxy;
// FIXME the proxy stuff should be done in the HTTP thread
- foreach (const QNetworkProxy &p, managerPrivate->queryProxy(QNetworkProxyQuery(request.url()))) {
+ foreach (const QNetworkProxy &p, managerPrivate->queryProxy(QNetworkProxyQuery(newHttpRequest.url()))) {
// use the first proxy that works
// for non-encrypted connections, any transparent or HTTP proxy
// for encrypted, only transparent proxies
@@ -669,9 +673,11 @@ void QNetworkReplyHttpImplPrivate::postRequest()
}
#endif
+ if (newHttpRequest.attribute(QNetworkRequest::FollowRedirectsAttribute).toBool())
+ httpRequest.setFollowRedirects(true);
bool loadedFromCache = false;
- httpRequest.setPriority(convert(request.priority()));
+ httpRequest.setPriority(convert(newHttpRequest.priority()));
switch (operation) {
case QNetworkAccessManager::GetOperation:
@@ -705,7 +711,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
invalidateCache(); // for safety reasons, we don't know what the operation does
httpRequest.setOperation(QHttpNetworkRequest::Custom);
createUploadByteDevice();
- httpRequest.setCustomVerb(request.attribute(
+ httpRequest.setCustomVerb(newHttpRequest.attribute(
QNetworkRequest::CustomVerbAttribute).toByteArray());
break;
@@ -717,7 +723,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
return; // no need to send the request! :)
}
- QList<QByteArray> headers = request.rawHeaderList();
+ QList<QByteArray> headers = newHttpRequest.rawHeaderList();
if (resumeOffset != 0) {
if (headers.contains("Range")) {
// Need to adjust resume offset for user specified range
@@ -725,7 +731,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
headers.removeOne("Range");
// We've already verified that requestRange starts with "bytes=", see canResume.
- QByteArray requestRange = request.rawHeader("Range").mid(6);
+ QByteArray requestRange = newHttpRequest.rawHeader("Range").mid(6);
int index = requestRange.indexOf('-');
@@ -742,16 +748,16 @@ void QNetworkReplyHttpImplPrivate::postRequest()
}
foreach (const QByteArray &header, headers)
- httpRequest.setHeaderField(header, request.rawHeader(header));
+ httpRequest.setHeaderField(header, newHttpRequest.rawHeader(header));
- if (request.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool() == true)
+ if (newHttpRequest.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool() == true)
httpRequest.setPipeliningAllowed(true);
if (request.attribute(QNetworkRequest::SpdyAllowedAttribute).toBool() == true)
httpRequest.setSPDYAllowed(true);
if (static_cast<QNetworkRequest::LoadControl>
- (request.attribute(QNetworkRequest::AuthenticationReuseAttribute,
+ (newHttpRequest.attribute(QNetworkRequest::AuthenticationReuseAttribute,
QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Manual)
httpRequest.setWithCredentials(false);
@@ -778,7 +784,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
delegate->ssl = ssl;
#ifndef QT_NO_SSL
if (ssl)
- delegate->incomingSslConfiguration = request.sslConfiguration();
+ delegate->incomingSslConfiguration = newHttpRequest.sslConfiguration();
#endif
// Do we use synchronous HTTP?
@@ -790,7 +796,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
if (!synchronous) {
// Tell our zerocopy policy to the delegate
- QVariant downloadBufferMaximumSizeAttribute = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
+ QVariant downloadBufferMaximumSizeAttribute = newHttpRequest.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
if (downloadBufferMaximumSizeAttribute.isValid()) {
delegate->downloadBufferMaximumSize = downloadBufferMaximumSizeAttribute.toLongLong();
} else {
@@ -825,6 +831,9 @@ void QNetworkReplyHttpImplPrivate::postRequest()
QObject::connect(delegate, SIGNAL(error(QNetworkReply::NetworkError,QString)),
q, SLOT(httpError(QNetworkReply::NetworkError,QString)),
Qt::QueuedConnection);
+ QObject::connect(delegate, SIGNAL(redirected(QUrl,int,int)),
+ q, SLOT(onRedirected(QUrl,int,int)),
+ Qt::QueuedConnection);
#ifndef QT_NO_SSL
QObject::connect(delegate, SIGNAL(sslConfigurationChanged(QSslConfiguration)),
q, SLOT(replySslConfigurationChanged(QSslConfiguration)),
@@ -951,7 +960,7 @@ void QNetworkReplyHttpImplPrivate::invalidateCache()
{
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc)
- nc->remove(request.url());
+ nc->remove(httpRequest.url());
}
void QNetworkReplyHttpImplPrivate::initCacheSaveDevice()
@@ -1031,21 +1040,30 @@ void QNetworkReplyHttpImplPrivate::replyDownloadData(QByteArray d)
for (int i = 0; i < pendingDownloadDataCopy.bufferCount(); i++) {
QByteArray const &item = pendingDownloadDataCopy[i];
+ // This is going to look a little strange. When downloading data while a
+ // HTTP redirect is happening (and enabled), we write the redirect
+ // response to the cache. However, we do not append it to our internal
+ // buffer as that will contain the response data only for the final
+ // response
if (cacheSaveDevice)
cacheSaveDevice->write(item.constData(), item.size());
- downloadMultiBuffer.append(item);
+
+ if (!isHttpRedirectResponse())
+ downloadMultiBuffer.append(item);
bytesWritten += item.size();
}
pendingDownloadDataCopy.clear();
- bytesDownloaded += bytesWritten;
-
-
QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
if (preMigrationDownloaded != Q_INT64_C(-1))
totalSize = totalSize.toLongLong() + preMigrationDownloaded;
+ if (isHttpRedirectResponse())
+ return;
+
+ bytesDownloaded += bytesWritten;
+
emit q->readyRead();
// emit readyRead before downloadProgress incase this will cause events to be
// processed and we get into a recursive call (as in QProgressDialog).
@@ -1067,6 +1085,64 @@ void QNetworkReplyHttpImplPrivate::replyFinished()
finished();
}
+QNetworkAccessManager::Operation QNetworkReplyHttpImplPrivate::getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus)
+{
+ // HTTP status code can be used to decide if we can redirect with a GET
+ // operation or not. See http://www.ietf.org/rfc/rfc2616.txt [Sec 10.3] for
+ // more details
+ Q_UNUSED(httpStatus);
+
+ switch (currentOp) {
+ case QNetworkAccessManager::HeadOperation:
+ return QNetworkAccessManager::HeadOperation;
+ default:
+ break;
+ }
+ // For now, we're always returning GET for anything other than HEAD
+ return QNetworkAccessManager::GetOperation;
+}
+
+bool QNetworkReplyHttpImplPrivate::isHttpRedirectResponse() const
+{
+ return httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(statusCode);
+}
+
+QNetworkRequest QNetworkReplyHttpImplPrivate::createRedirectRequest(const QNetworkRequest &originalRequest,
+ const QUrl &url,
+ int maxRedirectsRemaining)
+{
+ QNetworkRequest newRequest(originalRequest);
+ newRequest.setUrl(url);
+ newRequest.setMaximumRedirectsAllowed(maxRedirectsRemaining);
+
+ return newRequest;
+}
+
+void QNetworkReplyHttpImplPrivate::onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemaining)
+{
+ Q_Q(QNetworkReplyHttpImpl);
+
+ if (isFinished)
+ return;
+
+ if (httpRequest.isFollowRedirects()) // update the reply's url as it could've changed
+ url = redirectUrl;
+
+ QNetworkRequest redirectRequest = createRedirectRequest(originalRequest, redirectUrl, maxRedirectsRemaining);
+ operation = getRedirectOperation(operation, httpStatus);
+
+ cookedHeaders.clear();
+
+ if (managerPrivate->httpThread)
+ managerPrivate->httpThread->disconnect();
+
+ // Recurse
+ QMetaObject::invokeMethod(q, "start", Qt::QueuedConnection,
+ Q_ARG(QNetworkRequest, redirectRequest));
+
+ emit q->redirected(redirectUrl);
+}
+
void QNetworkReplyHttpImplPrivate::checkForRedirect(const int statusCode)
{
Q_Q(QNetworkReplyHttpImpl);
@@ -1115,7 +1191,16 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
end = headerMap.constEnd();
for (; it != end; ++it) {
QByteArray value = q->rawHeader(it->first);
+
+ // Reset any previous "location" header set in the reply. In case of
+ // redirects, we don't want to 'append' multiple location header values,
+ // rather we keep only the latest one
+ if (it->first.toLower() == "location")
+ value.clear();
+
if (!value.isEmpty()) {
+ // Why are we appending values for headers which are already
+ // present?
if (qstricmp(it->first.constData(), "set-cookie") == 0)
value += '\n';
else
@@ -1129,12 +1214,13 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, reasonPhrase);
// is it a redirection?
- checkForRedirect(statusCode);
+ if (!isHttpRedirectResponse())
+ checkForRedirect(statusCode);
if (statusCode >= 500 && statusCode < 600) {
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc) {
- QNetworkCacheMetaData metaData = nc->metaData(request.url());
+ QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
QNetworkHeadersPrivate cacheHeaders;
cacheHeaders.setAllRawHeaders(metaData.rawHeaders());
QNetworkHeadersPrivate::RawHeadersList::ConstIterator it;
@@ -1156,7 +1242,7 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
#endif
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc) {
- QNetworkCacheMetaData oldMetaData = nc->metaData(request.url());
+ QNetworkCacheMetaData oldMetaData = nc->metaData(httpRequest.url());
QNetworkCacheMetaData metaData = fetchCacheMetaData(oldMetaData);
if (oldMetaData != metaData)
nc->updateMetaData(metaData);
@@ -1203,6 +1289,9 @@ void QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(qint64 bytesReceive
// FIXME where is it closed?
}
+ if (isHttpRedirectResponse())
+ return;
+
bytesDownloaded = bytesReceived;
downloadBufferCurrentSize = bytesReceived;
@@ -1361,6 +1450,8 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
if (status < 100)
status = 200; // fake it
+ statusCode = status;
+
q->setAttribute(QNetworkRequest::HttpStatusCodeAttribute, status);
q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));
q->setAttribute(QNetworkRequest::SourceIsFromCacheAttribute, true);
@@ -1368,10 +1459,16 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
QNetworkCacheMetaData::RawHeaderList rawHeaders = metaData.rawHeaders();
QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
end = rawHeaders.constEnd();
- for ( ; it != end; ++it)
+ QUrl redirectUrl;
+ for ( ; it != end; ++it) {
+ if (httpRequest.isFollowRedirects() &&
+ !qstricmp(it->first.toLower().constData(), "location"))
+ redirectUrl = QUrl::fromEncoded(it->second);
setRawHeader(it->first, it->second);
+ }
- checkForRedirect(status);
+ if (!isHttpRedirectResponse())
+ checkForRedirect(status);
cacheLoadDevice = contents;
q->connect(cacheLoadDevice, SIGNAL(readyRead()), SLOT(_q_cacheLoadReadyRead()));
@@ -1388,6 +1485,14 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
qDebug() << "Successfully sent cache:" << url << contents->size() << "bytes";
#endif
+ // Do redirect processing
+ if (httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(status)) {
+ QMetaObject::invokeMethod(q, "onRedirected", Qt::QueuedConnection,
+ Q_ARG(QUrl, redirectUrl),
+ Q_ARG(int, status),
+ Q_ARG(int, httpRequest.redirectCount() - 1));
+ }
+
// Set the following flag so we can ignore some signals from HTTP thread
// that would still come
loadingFromCache = true;
@@ -1583,13 +1688,13 @@ void QNetworkReplyHttpImplPrivate::setResumeOffset(quint64 offset)
could not be started due to an unopened or roaming session. The caller should recall this
function once the session has been opened or the roaming process has finished.
*/
-bool QNetworkReplyHttpImplPrivate::start()
+bool QNetworkReplyHttpImplPrivate::start(const QNetworkRequest &newHttpRequest)
{
#ifndef QT_NO_BEARERMANAGEMENT
QSharedPointer<QNetworkSession> networkSession(managerPrivate->getNetworkSession());
if (!networkSession) {
#endif
- postRequest();
+ postRequest(newHttpRequest);
return true;
#ifndef QT_NO_BEARERMANAGEMENT
}
@@ -1599,7 +1704,7 @@ bool QNetworkReplyHttpImplPrivate::start()
if (host == QLatin1String("localhost") ||
QHostAddress(host).isLoopback()) {
// Don't need an open session for localhost access.
- postRequest();
+ postRequest(newHttpRequest);
return true;
}
@@ -1608,13 +1713,13 @@ bool QNetworkReplyHttpImplPrivate::start()
Q_Q(QNetworkReplyHttpImpl);
QObject::connect(networkSession.data(), SIGNAL(usagePoliciesChanged(QNetworkSession::UsagePolicies)),
q, SLOT(_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies)));
- postRequest();
+ postRequest(newHttpRequest);
return true;
} else if (synchronous) {
// Command line applications using the synchronous path such as xmlpatterns may need an extra push.
networkSession->open();
if (networkSession->waitForOpened()) {
- postRequest();
+ postRequest(newHttpRequest);
return true;
}
}
@@ -1646,7 +1751,7 @@ void QNetworkReplyHttpImplPrivate::_q_startOperation()
}
#endif
- if (!start()) {
+ if (!start(request)) {
#ifndef QT_NO_BEARERMANAGEMENT
// backend failed to start because the session state is not Connected.
// QNetworkAccessManager will call reply->backend->start() again for us when the session
@@ -1708,18 +1813,20 @@ void QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead()
// emit readyRead before downloadProgress incase this will cause events to be
// processed and we get into a recursive call (as in QProgressDialog).
- // This readyRead() goes to the user. The user then may or may not read() anything.
- emit q->readyRead();
- if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
- downloadProgressSignalChoke.restart();
- emit q->downloadProgress(bytesDownloaded,
- totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
- }
+ if (!(isHttpRedirectResponse())) {
+ // This readyRead() goes to the user. The user then may or may not read() anything.
+ emit q->readyRead();
+ if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
+ downloadProgressSignalChoke.restart();
+ emit q->downloadProgress(bytesDownloaded,
+ totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
+ }
+ }
// If there are still bytes available in the cacheLoadDevice then the user did not read
// in response to the readyRead() signal. This means we have to load from the cacheLoadDevice
// and buffer that stuff. This is needed to be able to properly emit finished() later.
- while (cacheLoadDevice->bytesAvailable()) {
+ while (cacheLoadDevice->bytesAvailable() && !isHttpRedirectResponse()) {
downloadMultiBuffer.append(cacheLoadDevice->readAll());
}
@@ -1742,7 +1849,6 @@ void QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead()
cacheLoadDevice = 0;
QMetaObject::invokeMethod(q, "_q_finished", Qt::QueuedConnection);
}
-
}
@@ -1962,6 +2068,15 @@ void QNetworkReplyHttpImplPrivate::finished()
#endif
}
+ // if we don't know the total size of or we received everything save the cache
+ if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
+ completeCacheSave();
+
+ // We check for errorCode too as in case of SSL handshake failure, we still
+ // get the HTTP redirect status code (301, 303 etc)
+ if (isHttpRedirectResponse() && errorCode == QNetworkReply::NoError)
+ return;
+
state = Finished;
q->setFinished(true);
@@ -1974,10 +2089,6 @@ void QNetworkReplyHttpImplPrivate::finished()
if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
emit q->uploadProgress(0, 0);
- // if we don't know the total size of or we received everything save the cache
- if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
- completeCacheSave();
-
emit q->readChannelFinished();
emit q->finished();
}
diff --git a/src/network/access/qnetworkreplyhttpimpl_p.h b/src/network/access/qnetworkreplyhttpimpl_p.h
index b009092196..fff88f8f2d 100644
--- a/src/network/access/qnetworkreplyhttpimpl_p.h
+++ b/src/network/access/qnetworkreplyhttpimpl_p.h
@@ -89,6 +89,7 @@ public:
Q_DECLARE_PRIVATE(QNetworkReplyHttpImpl)
Q_PRIVATE_SLOT(d_func(), void _q_startOperation())
+ Q_PRIVATE_SLOT(d_func(), bool start(const QNetworkRequest &))
Q_PRIVATE_SLOT(d_func(), void _q_cacheLoadReadyRead())
Q_PRIVATE_SLOT(d_func(), void _q_bufferOutgoingData())
Q_PRIVATE_SLOT(d_func(), void _q_bufferOutgoingDataFinished())
@@ -126,7 +127,7 @@ public:
Q_PRIVATE_SLOT(d_func(), void emitReplyUploadProgress(qint64, qint64))
Q_PRIVATE_SLOT(d_func(), void _q_cacheSaveDeviceAboutToClose())
Q_PRIVATE_SLOT(d_func(), void _q_metaDataChanged())
-
+ Q_PRIVATE_SLOT(d_func(), void onRedirected(const QUrl &, int, int))
#ifndef QT_NO_SSL
protected:
@@ -157,7 +158,7 @@ public:
QNetworkReplyHttpImplPrivate();
~QNetworkReplyHttpImplPrivate();
- bool start();
+ bool start(const QNetworkRequest &newHttpRequest);
void _q_startOperation();
void _q_cacheLoadReadyRead();
@@ -201,6 +202,7 @@ public:
QIODevice *outgoingData;
QSharedPointer<QRingBuffer> outgoingDataBuffer;
void emitReplyUploadProgress(qint64 bytesSent, qint64 bytesTotal); // dup?
+ void onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemainig);
qint64 bytesUploaded;
@@ -260,9 +262,10 @@ public:
QNetworkCacheMetaData fetchCacheMetaData(const QNetworkCacheMetaData &metaData) const;
- void postRequest();
-
-
+ void postRequest(const QNetworkRequest& newHttpRequest);
+ QNetworkAccessManager::Operation getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus);
+ QNetworkRequest createRedirectRequest(const QNetworkRequest &originalRequests, const QUrl &url, int maxRedirectsRemainig);
+ bool isHttpRedirectResponse() const;
public:
// From HTTP thread:
diff --git a/src/network/access/qnetworkreplyimpl.cpp b/src/network/access/qnetworkreplyimpl.cpp
index f235adaee8..a73e0ea75e 100644
--- a/src/network/access/qnetworkreplyimpl.cpp
+++ b/src/network/access/qnetworkreplyimpl.cpp
@@ -65,8 +65,6 @@ inline QNetworkReplyImplPrivate::QNetworkReplyImplPrivate()
void QNetworkReplyImplPrivate::_q_startOperation()
{
- Q_Q(QNetworkReplyImpl);
-
// ensure this function is only being called once
if (state == Working || state == Finished) {
qDebug("QNetworkReplyImpl::_q_startOperation was called more than once");
@@ -85,6 +83,7 @@ void QNetworkReplyImplPrivate::_q_startOperation()
}
#ifndef QT_NO_BEARERMANAGEMENT
+ Q_Q(QNetworkReplyImpl);
// Do not start background requests if they are not allowed by session policy
QSharedPointer<QNetworkSession> session(manager->d_func()->getNetworkSession());
QVariant isBackground = backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(false));
@@ -915,13 +914,11 @@ void QNetworkReplyImpl::abort()
QNetworkReply::close();
- if (d->state != QNetworkReplyPrivate::Finished) {
- // call finished which will emit signals
- d->error(OperationCanceledError, tr("Operation canceled"));
- if (d->state == QNetworkReplyPrivate::WaitingForSession)
- d->state = QNetworkReplyPrivate::Working;
- d->finished();
- }
+ // call finished which will emit signals
+ d->error(OperationCanceledError, tr("Operation canceled"));
+ if (d->state == QNetworkReplyPrivate::WaitingForSession)
+ d->state = QNetworkReplyPrivate::Working;
+ d->finished();
d->state = QNetworkReplyPrivate::Aborted;
// finished may access the backend
diff --git a/src/network/access/qnetworkreplyimpl_p.h b/src/network/access/qnetworkreplyimpl_p.h
index d2e7d02408..3e720ef597 100644
--- a/src/network/access/qnetworkreplyimpl_p.h
+++ b/src/network/access/qnetworkreplyimpl_p.h
@@ -115,8 +115,6 @@ public:
QNetworkReplyImplPrivate();
void _q_startOperation();
- void _q_sourceReadyRead();
- void _q_sourceReadChannelFinished();
void _q_copyReadyRead();
void _q_copyReadChannelFinished();
void _q_bufferOutgoingData();
@@ -203,6 +201,7 @@ public:
Q_DECLARE_PUBLIC(QNetworkReplyImpl)
};
+Q_DECLARE_TYPEINFO(QNetworkReplyImplPrivate::InternalNotifications, Q_PRIMITIVE_TYPE);
#ifndef QT_NO_BEARERMANAGEMENT
class QDisabledNetworkReply : public QNetworkReply
diff --git a/src/network/access/qnetworkrequest.cpp b/src/network/access/qnetworkrequest.cpp
index c7cb16c71c..558e015ae4 100644
--- a/src/network/access/qnetworkrequest.cpp
+++ b/src/network/access/qnetworkrequest.cpp
@@ -140,7 +140,9 @@ QT_BEGIN_NAMESPACE
request to a different URL. The Network Access API does not by
default follow redirections: it's up to the application to
determine if the requested redirection should be allowed,
- according to its security policies.
+ according to its security policies. However, if
+ QNetworkRequest::FollowRedirectsAttribute is set, then this attribute
+ will not be present in the reply.
The returned URL might be relative. Use QUrl::resolved()
to create an absolute URL out of it.
@@ -256,6 +258,12 @@ QT_BEGIN_NAMESPACE
in 100 millisecond intervals.
(This value was introduced in 5.5.)
+ \value FollowRedirectsAttribute
+ Requests only, type: QMetaType::Bool (default: false)
+ Indicates whether the Network Access API should automatically follow a
+ HTTP redirect response or not. Currently redirects that are insecure,
+ that is redirecting from "https" to "http" protocol, are not allowed.
+
\value User
Special type. Additional information can be passed in
QVariants with types ranging from User to UserMax. The default
@@ -306,11 +314,13 @@ QT_BEGIN_NAMESPACE
class QNetworkRequestPrivate: public QSharedData, public QNetworkHeadersPrivate
{
public:
+ static const int maxRedirectCount = 50;
inline QNetworkRequestPrivate()
: priority(QNetworkRequest::NormalPriority)
#ifndef QT_NO_SSL
, sslConfiguration(0)
#endif
+ , maxRedirectsAllowed(maxRedirectCount)
{ qRegisterMetaType<QNetworkRequest>(); }
~QNetworkRequestPrivate()
{
@@ -325,7 +335,7 @@ public:
{
url = other.url;
priority = other.priority;
-
+ maxRedirectsAllowed = other.maxRedirectsAllowed;
#ifndef QT_NO_SSL
sslConfiguration = 0;
if (other.sslConfiguration)
@@ -338,7 +348,8 @@ public:
return url == other.url &&
priority == other.priority &&
rawHeaders == other.rawHeaders &&
- attributes == other.attributes;
+ attributes == other.attributes &&
+ maxRedirectsAllowed == other.maxRedirectsAllowed;
// don't compare cookedHeaders
}
@@ -347,6 +358,7 @@ public:
#ifndef QT_NO_SSL
mutable QSslConfiguration *sslConfiguration;
#endif
+ int maxRedirectsAllowed;
};
/*!
@@ -657,6 +669,32 @@ void QNetworkRequest::setPriority(Priority priority)
d->priority = priority;
}
+/*!
+ \since 5.6
+
+ Returns the maximum number of redirects allowed to be followed for this
+ request.
+
+ \sa setMaximumRedirectsAllowed()
+*/
+int QNetworkRequest::maximumRedirectsAllowed() const
+{
+ return d->maxRedirectsAllowed;
+}
+
+/*!
+ \since 5.6
+
+ Sets the maximum number of redirects allowed to be followed for this
+ request to \a maxRedirectsAllowed.
+
+ \sa maximumRedirectsAllowed()
+*/
+void QNetworkRequest::setMaximumRedirectsAllowed(int maxRedirectsAllowed)
+{
+ d->maxRedirectsAllowed = maxRedirectsAllowed;
+}
+
static QByteArray headerName(QNetworkRequest::KnownHeaders header)
{
switch (header) {
@@ -881,6 +919,7 @@ QNetworkHeadersPrivate::RawHeadersList QNetworkHeadersPrivate::allRawHeaders() c
QList<QByteArray> QNetworkHeadersPrivate::rawHeadersKeys() const
{
QList<QByteArray> result;
+ result.reserve(rawHeaders.size());
RawHeadersList::ConstIterator it = rawHeaders.constBegin(),
end = rawHeaders.constEnd();
for ( ; it != end; ++it)
diff --git a/src/network/access/qnetworkrequest.h b/src/network/access/qnetworkrequest.h
index d6d907bdc4..eb343c97df 100644
--- a/src/network/access/qnetworkrequest.h
+++ b/src/network/access/qnetworkrequest.h
@@ -81,6 +81,7 @@ public:
SpdyAllowedAttribute,
SpdyWasUsedAttribute,
EmitAllUploadProgressSignalsAttribute,
+ FollowRedirectsAttribute,
User = 1000,
UserMax = 32767
@@ -105,9 +106,12 @@ public:
explicit QNetworkRequest(const QUrl &url = QUrl());
QNetworkRequest(const QNetworkRequest &other);
~QNetworkRequest();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkRequest &operator=(QNetworkRequest &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkRequest &operator=(const QNetworkRequest &other);
- inline void swap(QNetworkRequest &other) { qSwap(d, other.d); }
+ void swap(QNetworkRequest &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkRequest &other) const;
inline bool operator!=(const QNetworkRequest &other) const
@@ -141,6 +145,10 @@ public:
Priority priority() const;
void setPriority(Priority priority);
+ // HTTP redirect related
+ int maximumRedirectsAllowed() const;
+ void setMaximumRedirectsAllowed(int maximumRedirectsAllowed);
+
private:
QSharedDataPointer<QNetworkRequestPrivate> d;
friend class QNetworkRequestPrivate;
diff --git a/src/network/access/qspdyprotocolhandler.cpp b/src/network/access/qspdyprotocolhandler.cpp
index 7430ca029d..7d2c0dfef2 100644
--- a/src/network/access/qspdyprotocolhandler.cpp
+++ b/src/network/access/qspdyprotocolhandler.cpp
@@ -288,16 +288,14 @@ bool QSpdyProtocolHandler::sendRequest()
m_channel->state = QHttpNetworkConnectionChannel::WritingState;
- // requests will be ordered by priority (see QMultiMap doc)
- QList<HttpMessagePair> requests = m_channel->spdyRequestsToSend.values();
- QList<int> priorities = m_channel->spdyRequestsToSend.keys();
-
- int requestsToSend = qMin(requests.count(), maxPossibleRequests);
+ int requestsToSend = qMin(m_channel->spdyRequestsToSend.size(), maxPossibleRequests);
+ QMultiMap<int, HttpMessagePair>::iterator it = m_channel->spdyRequestsToSend.begin();
+ // requests will be ordered by priority (see QMultiMap doc)
for (int a = 0; a < requestsToSend; ++a) {
- HttpMessagePair currentPair = requests.at(a);
- QHttpNetworkRequest currentRequest = requests.at(a).first;
- QHttpNetworkReply *currentReply = requests.at(a).second;
+ HttpMessagePair currentPair = *it;
+ QHttpNetworkRequest currentRequest = currentPair.first;
+ QHttpNetworkReply *currentReply = currentPair.second;
currentReply->setSpdyWasUsed(true);
qint32 streamID = generateNextStreamID();
@@ -310,10 +308,7 @@ bool QSpdyProtocolHandler::sendRequest()
connect(currentReply, SIGNAL(destroyed(QObject*)), this, SLOT(_q_replyDestroyed(QObject*)));
sendSYN_STREAM(currentPair, streamID, /* associatedToStreamID = */ 0);
- int requestsRemoved = m_channel->spdyRequestsToSend.remove(
- priorities.at(a), currentPair);
- Q_ASSERT(requestsRemoved == 1);
- Q_UNUSED(requestsRemoved); // silence -Wunused-variable
+ m_channel->spdyRequestsToSend.erase(it++);
}
m_channel->state = QHttpNetworkConnectionChannel::IdleState;
return true;
diff --git a/src/network/bearer/qnetworkconfigmanager.h b/src/network/bearer/qnetworkconfigmanager.h
index b62a44c422..84080ba83e 100644
--- a/src/network/bearer/qnetworkconfigmanager.h
+++ b/src/network/bearer/qnetworkconfigmanager.h
@@ -59,13 +59,13 @@ public:
Q_DECLARE_FLAGS(Capabilities, Capability)
- explicit QNetworkConfigurationManager(QObject *parent = 0);
+ explicit QNetworkConfigurationManager(QObject *parent = Q_NULLPTR);
virtual ~QNetworkConfigurationManager();
QNetworkConfigurationManager::Capabilities capabilities() const;
QNetworkConfiguration defaultConfiguration() const;
- QList<QNetworkConfiguration> allConfigurations(QNetworkConfiguration::StateFlags flags = 0) const;
+ QList<QNetworkConfiguration> allConfigurations(QNetworkConfiguration::StateFlags flags = QNetworkConfiguration::StateFlags()) const;
QNetworkConfiguration configurationFromIdentifier(const QString &identifier) const;
bool isOnline() const;
diff --git a/src/network/bearer/qnetworkconfigmanager_p.cpp b/src/network/bearer/qnetworkconfigmanager_p.cpp
index 8ff6ee828d..49daa22ec8 100644
--- a/src/network/bearer/qnetworkconfigmanager_p.cpp
+++ b/src/network/bearer/qnetworkconfigmanager_p.cpp
@@ -41,6 +41,7 @@
#include <QtCore/qstringlist.h>
#include <QtCore/qthread.h>
#include <QtCore/private/qcoreapplication_p.h>
+#include <QtCore/private/qthread_p.h>
#ifndef QT_NO_BEARERMANAGEMENT
@@ -61,7 +62,7 @@ QNetworkConfigurationManagerPrivate::QNetworkConfigurationManagerPrivate()
void QNetworkConfigurationManagerPrivate::initialize()
{
//Two stage construction, because we only want to do this heavyweight work for the winner of the Q_GLOBAL_STATIC race.
- bearerThread = new QThread();
+ bearerThread = new QDaemonThread();
bearerThread->setObjectName(QStringLiteral("Qt bearer thread"));
bearerThread->moveToThread(QCoreApplicationPrivate::mainThread()); // because cleanup() is called in main thread context.
diff --git a/src/network/bearer/qnetworkconfiguration.h b/src/network/bearer/qnetworkconfiguration.h
index dbef344e69..317c232bea 100644
--- a/src/network/bearer/qnetworkconfiguration.h
+++ b/src/network/bearer/qnetworkconfiguration.h
@@ -49,10 +49,13 @@ class Q_NETWORK_EXPORT QNetworkConfiguration
public:
QNetworkConfiguration();
QNetworkConfiguration(const QNetworkConfiguration& other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkConfiguration &operator=(QNetworkConfiguration &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkConfiguration &operator=(const QNetworkConfiguration &other);
~QNetworkConfiguration();
- void swap(QNetworkConfiguration &other) { qSwap(d, other.d); }
+ void swap(QNetworkConfiguration &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkConfiguration &other) const;
inline bool operator!=(const QNetworkConfiguration &other) const
diff --git a/src/network/bearer/qnetworksession.h b/src/network/bearer/qnetworksession.h
index 34d721f484..bee4be7eb6 100644
--- a/src/network/bearer/qnetworksession.h
+++ b/src/network/bearer/qnetworksession.h
@@ -80,7 +80,7 @@ public:
Q_DECLARE_FLAGS(UsagePolicies, UsagePolicy)
- explicit QNetworkSession(const QNetworkConfiguration &connConfig, QObject *parent = 0);
+ explicit QNetworkSession(const QNetworkConfiguration &connConfig, QObject *parent = Q_NULLPTR);
virtual ~QNetworkSession();
bool isOpen() const;
diff --git a/src/network/kernel/qdnslookup.h b/src/network/kernel/qdnslookup.h
index 01ebbb6535..ae015a22b8 100644
--- a/src/network/kernel/qdnslookup.h
+++ b/src/network/kernel/qdnslookup.h
@@ -55,16 +55,18 @@ class Q_NETWORK_EXPORT QDnsDomainNameRecord
public:
QDnsDomainNameRecord();
QDnsDomainNameRecord(const QDnsDomainNameRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsDomainNameRecord &operator=(QDnsDomainNameRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsDomainNameRecord &operator=(const QDnsDomainNameRecord &other);
~QDnsDomainNameRecord();
- void swap(QDnsDomainNameRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsDomainNameRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QString value() const;
- QDnsDomainNameRecord &operator=(const QDnsDomainNameRecord &other);
-
private:
QSharedDataPointer<QDnsDomainNameRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -77,16 +79,18 @@ class Q_NETWORK_EXPORT QDnsHostAddressRecord
public:
QDnsHostAddressRecord();
QDnsHostAddressRecord(const QDnsHostAddressRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsHostAddressRecord &operator=(QDnsHostAddressRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsHostAddressRecord &operator=(const QDnsHostAddressRecord &other);
~QDnsHostAddressRecord();
- void swap(QDnsHostAddressRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsHostAddressRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QHostAddress value() const;
- QDnsHostAddressRecord &operator=(const QDnsHostAddressRecord &other);
-
private:
QSharedDataPointer<QDnsHostAddressRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -99,17 +103,19 @@ class Q_NETWORK_EXPORT QDnsMailExchangeRecord
public:
QDnsMailExchangeRecord();
QDnsMailExchangeRecord(const QDnsMailExchangeRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsMailExchangeRecord &operator=(QDnsMailExchangeRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsMailExchangeRecord &operator=(const QDnsMailExchangeRecord &other);
~QDnsMailExchangeRecord();
- void swap(QDnsMailExchangeRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsMailExchangeRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString exchange() const;
QString name() const;
quint16 preference() const;
quint32 timeToLive() const;
- QDnsMailExchangeRecord &operator=(const QDnsMailExchangeRecord &other);
-
private:
QSharedDataPointer<QDnsMailExchangeRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -122,9 +128,13 @@ class Q_NETWORK_EXPORT QDnsServiceRecord
public:
QDnsServiceRecord();
QDnsServiceRecord(const QDnsServiceRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsServiceRecord &operator=(QDnsServiceRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsServiceRecord &operator=(const QDnsServiceRecord &other);
~QDnsServiceRecord();
- void swap(QDnsServiceRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsServiceRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint16 port() const;
@@ -133,8 +143,6 @@ public:
quint32 timeToLive() const;
quint16 weight() const;
- QDnsServiceRecord &operator=(const QDnsServiceRecord &other);
-
private:
QSharedDataPointer<QDnsServiceRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -147,16 +155,18 @@ class Q_NETWORK_EXPORT QDnsTextRecord
public:
QDnsTextRecord();
QDnsTextRecord(const QDnsTextRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsTextRecord &operator=(QDnsTextRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsTextRecord &operator=(const QDnsTextRecord &other);
~QDnsTextRecord();
- void swap(QDnsTextRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsTextRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QList<QByteArray> values() const;
- QDnsTextRecord &operator=(const QDnsTextRecord &other);
-
private:
QSharedDataPointer<QDnsTextRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -201,9 +211,9 @@ public:
};
Q_ENUM(Type)
- explicit QDnsLookup(QObject *parent = 0);
- QDnsLookup(Type type, const QString &name, QObject *parent = 0);
- QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent = 0);
+ explicit QDnsLookup(QObject *parent = Q_NULLPTR);
+ QDnsLookup(Type type, const QString &name, QObject *parent = Q_NULLPTR);
+ QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent = Q_NULLPTR);
~QDnsLookup();
Error error() const;
diff --git a/src/network/kernel/qhostaddress.cpp b/src/network/kernel/qhostaddress.cpp
index 58c0de1f3b..935af04e31 100644
--- a/src/network/kernel/qhostaddress.cpp
+++ b/src/network/kernel/qhostaddress.cpp
@@ -46,6 +46,9 @@
#ifndef QT_NO_DATASTREAM
#include <qdatastream.h>
#endif
+#ifdef __SSE2__
+# include <private/qsimd_p.h>
+#endif
#ifdef QT_LINUXBASE
# include <arpa/inet.h>
@@ -106,7 +109,11 @@ public:
QString scopeId;
quint32 a; // IPv4 address
- Q_IPV6ADDR a6; // IPv6 address
+ union {
+ Q_IPV6ADDR a6; // IPv6 address
+ struct { quint64 c[2]; } a6_64;
+ struct { quint32 c[4]; } a6_32;
+ };
QAbstractSocket::NetworkLayerProtocol protocol;
bool isParsed;
@@ -123,24 +130,17 @@ QHostAddressPrivate::QHostAddressPrivate()
void QHostAddressPrivate::setAddress(quint32 a_)
{
a = a_;
+ protocol = QAbstractSocket::IPv4Protocol;
+ isParsed = true;
+
//create mapped address, except for a_ == 0 (any)
- memset(&a6, 0, sizeof(a6));
+ a6_64.c[0] = 0;
if (a) {
- a6[11] = 0xFF;
- a6[10] = 0xFF;
+ a6_32.c[2] = qToBigEndian(0xffff);
+ a6_32.c[3] = qToBigEndian(a);
} else {
- a6[11] = 0;
- a6[10] = 0;
+ a6_64.c[1] = 0;
}
-
- int i;
- for (i=15; a_ != 0; i--) {
- a6[i] = a_ & 0xFF;
- a_ >>=8;
- }
- Q_ASSERT(i >= 11);
- protocol = QAbstractSocket::IPv4Protocol;
- isParsed = true;
}
/// parses v4-mapped addresses or the AnyIPv6 address and stores in \a a;
@@ -163,21 +163,16 @@ static bool convertToIpv4(quint32& a, const Q_IPV6ADDR &a6)
void QHostAddressPrivate::setAddress(const quint8 *a_)
{
- for (int i = 0; i < 16; i++)
- a6[i] = a_[i];
- a = 0;
- convertToIpv4(a, a6);
protocol = QAbstractSocket::IPv6Protocol;
isParsed = true;
+ memcpy(a6.c, a_, sizeof(a6));
+ a = 0;
+ convertToIpv4(a, a6);
}
void QHostAddressPrivate::setAddress(const Q_IPV6ADDR &a_)
{
- a6 = a_;
- a = 0;
- convertToIpv4(a, a6);
- protocol = QAbstractSocket::IPv6Protocol;
- isParsed = true;
+ setAddress(a_.c);
}
static bool parseIp6(const QString &address, QIPAddressUtils::IPv6Address &addr, QString *scopeId)
@@ -193,7 +188,7 @@ static bool parseIp6(const QString &address, QIPAddressUtils::IPv6Address &addr,
return QIPAddressUtils::parseIp6(addr, tmp.constBegin(), tmp.constEnd()) == 0;
}
-bool QHostAddressPrivate::parse()
+Q_NEVER_INLINE bool QHostAddressPrivate::parse()
{
isParsed = true;
protocol = QAbstractSocket::UnknownNetworkLayerProtocol;
@@ -486,31 +481,35 @@ QHostAddress::QHostAddress(SpecialAddress address)
{
Q_IPV6ADDR ip6;
memset(&ip6, 0, sizeof ip6);
+ quint32 ip4 = INADDR_ANY;
switch (address) {
case Null:
- break;
+ return;
+
case Broadcast:
- d->setAddress(quint32(-1));
+ ip4 = INADDR_BROADCAST;
break;
case LocalHost:
- d->setAddress(0x7f000001);
- break;
- case LocalHostIPv6:
- ip6[15] = 1;
- d->setAddress(ip6);
+ ip4 = INADDR_LOOPBACK;
break;
case AnyIPv4:
- setAddress(0u);
break;
+
+ case LocalHostIPv6:
+ ip6[15] = 1;
+ // fall through
case AnyIPv6:
d->setAddress(ip6);
- break;
+ return;
+
case Any:
- d->clear();
d->protocol = QAbstractSocket::AnyIPProtocol;
- break;
+ return;
}
+
+ // common IPv4 part
+ d->setAddress(ip4);
}
/*!
@@ -775,11 +774,6 @@ QString QHostAddress::toString() const
on your host. Link-local addresses ("fe80...") are generated from the MAC
address of the local network adaptor, and are not guaranteed to be unique.
- \li Site-local: Addresses that are local to the site / private network
- (e.g., the company intranet). Site-local addresses ("fec0...") are
- usually distributed by the site router, and are not guaranteed to be
- unique outside of the local site.
-
\li Global: For globally routable addresses, such as public servers on the
Internet.
@@ -790,7 +784,7 @@ QString QHostAddress::toString() const
usually the same as the interface name (e.g., "eth0", "en1") or number
(e.g., "1", "2").
- \sa setScopeId()
+ \sa setScopeId(), QNetworkInterface, QNetworkInterface::interfaceFromName
*/
QString QHostAddress::scopeId() const
{
@@ -801,8 +795,14 @@ QString QHostAddress::scopeId() const
/*!
\since 4.1
- Sets the IPv6 scope ID of the address to \a id. If the address
- protocol is not IPv6, this function does nothing.
+ Sets the IPv6 scope ID of the address to \a id. If the address protocol is
+ not IPv6, this function does nothing. The scope ID may be set as an
+ interface name (such as "eth0" or "en1") or as an integer representing the
+ interface index. If \a id is an interface name, QtNetwork will convert to
+ an interface index using QNetworkInterface::interfaceIndexFromName() before
+ calling the operating system networking functions.
+
+ \sa scopeId(), QNetworkInterface, QNetworkInterface::interfaceFromName
*/
void QHostAddress::setScopeId(const QString &id)
{
@@ -836,34 +836,36 @@ bool QHostAddress::operator==(const QHostAddress &other) const
bool QHostAddress::operator ==(SpecialAddress other) const
{
QT_ENSURE_PARSED(this);
+ quint32 ip4 = INADDR_ANY;
switch (other) {
case Null:
return d->protocol == QAbstractSocket::UnknownNetworkLayerProtocol;
case Broadcast:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_BROADCAST;
+ ip4 = INADDR_BROADCAST;
+ break;
case LocalHost:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_LOOPBACK;
+ ip4 = INADDR_LOOPBACK;
+ break;
case Any:
return d->protocol == QAbstractSocket::AnyIPProtocol;
case AnyIPv4:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_ANY;
+ break;
case LocalHostIPv6:
case AnyIPv6:
if (d->protocol == QAbstractSocket::IPv6Protocol) {
- Q_IPV6ADDR ip6 = { { 0 } };
- ip6[15] = quint8(other == LocalHostIPv6); // 1 for localhost, 0 for any
- return memcmp(&d->a6, &ip6, sizeof ip6) == 0;
+ quint64 second = quint8(other == LocalHostIPv6); // 1 for localhost, 0 for any
+ return d->a6_64.c[0] == 0 && d->a6_64.c[1] == qToBigEndian(second);
}
return false;
}
- Q_UNREACHABLE();
- return false;
+ // common IPv4 part
+ return d->protocol == QAbstractSocket::IPv4Protocol && d->a == ip4;
}
/*!
@@ -1085,16 +1087,36 @@ bool QHostAddress::isLoopback() const
if ((d->a & 0xFF000000) == 0x7F000000)
return true; // v4 range (including IPv6 wrapped IPv4 addresses)
if (d->protocol == QAbstractSocket::IPv6Protocol) {
- if (d->a6.c[15] != 1)
+#ifdef __SSE2__
+ const __m128i loopback = _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
+ __m128i ipv6 = _mm_loadu_si128((const __m128i *)d->a6.c);
+ __m128i cmp = _mm_cmpeq_epi8(ipv6, loopback);
+ return _mm_movemask_epi8(cmp) == 0xffff;
+#else
+ if (d->a6_64.c[0] != 0 || qFromBigEndian(d->a6_64.c[1]) != 1)
return false;
- for (int i = 0; i < 15; i++)
- if (d->a6[i] != 0)
- return false;
+#endif
return true;
}
return false;
}
+/*!
+ \since 5.6
+
+ Returns \c true if the address is an IPv4 or IPv6 multicast address, \c
+ false otherwise.
+*/
+bool QHostAddress::isMulticast() const
+{
+ QT_ENSURE_PARSED(this);
+ if ((d->a & 0xF0000000) == 0xE0000000)
+ return true; // 224.0.0.0-239.255.255.255 (including v4-mapped IPv6 addresses)
+ if (d->protocol == QAbstractSocket::IPv6Protocol)
+ return d->a6.c[0] == 0xff;
+ return false;
+}
+
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const QHostAddress &address)
{
@@ -1112,7 +1134,7 @@ uint qHash(const QHostAddress &key, uint seed)
{
// both lines might throw
QT_ENSURE_PARSED(&key);
- return qHash(QByteArray::fromRawData(reinterpret_cast<const char *>(key.d->a6.c), 16), seed);
+ return qHashBits(key.d->a6.c, 16, seed);
}
#ifndef QT_NO_DATASTREAM
diff --git a/src/network/kernel/qhostaddress.h b/src/network/kernel/qhostaddress.h
index 0c2229c334..cea54a2984 100644
--- a/src/network/kernel/qhostaddress.h
+++ b/src/network/kernel/qhostaddress.h
@@ -84,9 +84,16 @@ public:
QHostAddress(SpecialAddress address);
~QHostAddress();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QHostAddress &operator=(QHostAddress &&other) Q_DECL_NOTHROW
+ { swap(other); return *this; }
+#endif
+
QHostAddress &operator=(const QHostAddress &other);
QHostAddress &operator=(const QString &address);
+ void swap(QHostAddress &other) Q_DECL_NOTHROW { d.swap(other.d); }
+
void setAddress(quint32 ip4Addr);
void setAddress(quint8 *ip6Addr); // ### Qt 6: remove me
void setAddress(const quint8 *ip6Addr);
@@ -117,6 +124,7 @@ public:
bool isInSubnet(const QPair<QHostAddress, int> &subnet) const;
bool isLoopback() const;
+ bool isMulticast() const;
static QPair<QHostAddress, int> parseSubnet(const QString &subnet);
diff --git a/src/network/kernel/qhostinfo.cpp b/src/network/kernel/qhostinfo.cpp
index a2ac9065fd..c6c09542e7 100644
--- a/src/network/kernel/qhostinfo.cpp
+++ b/src/network/kernel/qhostinfo.cpp
@@ -415,10 +415,22 @@ void QHostInfo::setErrorString(const QString &str)
/*!
\fn QString QHostInfo::localHostName()
- Returns the host name of this machine.
+ Returns this machine's host name, if one is configured. Note that hostnames
+ are not guaranteed to be globally unique, especially if they were
+ configured automatically.
- \sa hostName()
+ This function does not guarantee the returned host name is a Fully
+ Qualified Domain Name (FQDN). For that, use fromName() to resolve the
+ returned name to an FQDN.
+
+ This function returns the same as QSysInfo::machineHostName().
+
+ \sa hostName(), localDomainName()
*/
+QString QHostInfo::localHostName()
+{
+ return QSysInfo::machineHostName();
+}
/*!
\fn QString QHostInfo::localDomainName()
diff --git a/src/network/kernel/qhostinfo_unix.cpp b/src/network/kernel/qhostinfo_unix.cpp
index 90a6f763f7..266a67771c 100644
--- a/src/network/kernel/qhostinfo_unix.cpp
+++ b/src/network/kernel/qhostinfo_unix.cpp
@@ -315,15 +315,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
-QString QHostInfo::localHostName()
-{
- char hostName[512];
- if (gethostname(hostName, sizeof(hostName)) == -1)
- return QString();
- hostName[sizeof(hostName) - 1] = '\0';
- return QString::fromLocal8Bit(hostName);
-}
-
QString QHostInfo::localDomainName()
{
#if !defined(Q_OS_VXWORKS) && !defined(Q_OS_ANDROID)
diff --git a/src/network/kernel/qhostinfo_win.cpp b/src/network/kernel/qhostinfo_win.cpp
index e044728198..da28cd48c1 100644
--- a/src/network/kernel/qhostinfo_win.cpp
+++ b/src/network/kernel/qhostinfo_win.cpp
@@ -111,7 +111,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
QMutexLocker locker(&qPrivCEMutex);
#endif
- QWindowsSockInit winSock;
+ QSysInfo::machineHostName(); // this initializes ws2_32.dll
// Load res_init on demand.
static QBasicAtomicInt triedResolve = Q_BASIC_ATOMIC_INITIALIZER(false);
@@ -136,7 +136,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
// Reverse lookup
if (local_getnameinfo) {
sockaddr_in sa4;
- qt_sockaddr_in6 sa6;
+ sockaddr_in6 sa6;
sockaddr *sa;
QT_SOCKLEN_T saSize;
if (address.protocol() == QAbstractSocket::IPv4Protocol) {
@@ -150,7 +150,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
saSize = sizeof(sa6);
memset(&sa6, 0, sizeof(sa6));
sa6.sin6_family = AF_INET6;
- memcpy(sa6.sin6_addr.qt_s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.qt_s6_addr));
+ memcpy(&sa6.sin6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr));
}
char hbuf[NI_MAXHOST];
@@ -197,7 +197,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
break;
case AF_INET6: {
QHostAddress addr;
- addr.setAddress(((qt_sockaddr_in6 *) p->ai_addr)->sin6_addr.qt_s6_addr);
+ addr.setAddress(((sockaddr_in6 *) p->ai_addr)->sin6_addr.s6_addr);
if (!addresses.contains(addr))
addresses.append(addr);
}
@@ -256,17 +256,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
-QString QHostInfo::localHostName()
-{
- QWindowsSockInit winSock;
-
- char hostName[512];
- if (gethostname(hostName, sizeof(hostName)) == -1)
- return QString();
- hostName[sizeof(hostName) - 1] = '\0';
- return QString::fromLocal8Bit(hostName);
-}
-
// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
QT_END_NAMESPACE
diff --git a/src/network/kernel/qhostinfo_winrt.cpp b/src/network/kernel/qhostinfo_winrt.cpp
index 1a97fe0e40..3d2344726b 100644
--- a/src/network/kernel/qhostinfo_winrt.cpp
+++ b/src/network/kernel/qhostinfo_winrt.cpp
@@ -130,45 +130,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
-QString QHostInfo::localHostName()
-{
- ComPtr<INetworkInformationStatics> statics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);
-
- ComPtr<IVectorView<HostName *>> hostNames;
- statics->GetHostNames(&hostNames);
- if (!hostNames)
- return QString();
-
- unsigned int size;
- hostNames->get_Size(&size);
- if (size == 0)
- return QString();
-
- for (unsigned int i = 0; i < size; ++i) {
- ComPtr<IHostName> hostName;
- hostNames->GetAt(i, &hostName);
- HostNameType type;
- hostName->get_Type(&type);
- if (type != HostNameType_DomainName)
- continue;
-
- HString name;
- hostName->get_CanonicalName(name.GetAddressOf());
- UINT32 length;
- PCWSTR rawString = name.GetRawBuffer(&length);
- return QString::fromWCharArray(rawString, length);
- }
- ComPtr<IHostName> firstHost;
- hostNames->GetAt(0, &firstHost);
-
- HString name;
- firstHost->get_CanonicalName(name.GetAddressOf());
- UINT32 length;
- PCWSTR rawString = name.GetRawBuffer(&length);
- return QString::fromWCharArray(rawString, length);
-}
-
// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
QT_END_NAMESPACE
diff --git a/src/network/kernel/qnetworkinterface.cpp b/src/network/kernel/qnetworkinterface.cpp
index 8d891733ac..4a527052d1 100644
--- a/src/network/kernel/qnetworkinterface.cpp
+++ b/src/network/kernel/qnetworkinterface.cpp
@@ -86,9 +86,16 @@ QSharedDataPointer<QNetworkInterfacePrivate> QNetworkInterfaceManager::interface
{
QList<QSharedDataPointer<QNetworkInterfacePrivate> > interfaceList = allInterfaces();
QList<QSharedDataPointer<QNetworkInterfacePrivate> >::ConstIterator it = interfaceList.constBegin();
- for ( ; it != interfaceList.constEnd(); ++it)
- if ((*it)->name == name)
+
+ bool ok;
+ uint index = name.toUInt(&ok);
+
+ for ( ; it != interfaceList.constEnd(); ++it) {
+ if (ok && (*it)->index == int(index))
return *it;
+ else if ((*it)->name == name)
+ return *it;
+ }
return empty;
}
@@ -108,6 +115,7 @@ QList<QSharedDataPointer<QNetworkInterfacePrivate> > QNetworkInterfaceManager::a
{
QList<QNetworkInterfacePrivate *> list = postProcess(scan());
QList<QSharedDataPointer<QNetworkInterfacePrivate> > result;
+ result.reserve(list.size());
foreach (QNetworkInterfacePrivate *ptr, list)
result << QSharedDataPointer<QNetworkInterfacePrivate>(ptr);
@@ -515,6 +523,9 @@ QList<QNetworkAddressEntry> QNetworkInterface::addressEntries() const
name. If no such interface exists, this function returns an
invalid QNetworkInterface object.
+ The string \a name may be either an actual interface name (such as "eth0"
+ or "en1") or an interface index in string form ("1", "2", etc.).
+
\sa name(), isValid()
*/
QNetworkInterface QNetworkInterface::interfaceFromName(const QString &name)
@@ -549,6 +560,7 @@ QList<QNetworkInterface> QNetworkInterface::allInterfaces()
{
QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
QList<QNetworkInterface> result;
+ result.reserve(privs.size());
foreach (const QSharedDataPointer<QNetworkInterfacePrivate> &p, privs) {
QNetworkInterface item;
item.d = p;
diff --git a/src/network/kernel/qnetworkinterface.h b/src/network/kernel/qnetworkinterface.h
index a4d93156fb..31d3b7b128 100644
--- a/src/network/kernel/qnetworkinterface.h
+++ b/src/network/kernel/qnetworkinterface.h
@@ -51,10 +51,13 @@ class Q_NETWORK_EXPORT QNetworkAddressEntry
public:
QNetworkAddressEntry();
QNetworkAddressEntry(const QNetworkAddressEntry &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkAddressEntry &operator=(QNetworkAddressEntry &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkAddressEntry &operator=(const QNetworkAddressEntry &other);
~QNetworkAddressEntry();
- void swap(QNetworkAddressEntry &other) { qSwap(d, other.d); }
+ void swap(QNetworkAddressEntry &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkAddressEntry &other) const;
inline bool operator!=(const QNetworkAddressEntry &other) const
@@ -93,10 +96,13 @@ public:
QNetworkInterface();
QNetworkInterface(const QNetworkInterface &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkInterface &operator=(QNetworkInterface &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkInterface &operator=(const QNetworkInterface &other);
~QNetworkInterface();
- void swap(QNetworkInterface &other) { qSwap(d, other.d); }
+ void swap(QNetworkInterface &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isValid() const;
diff --git a/src/network/kernel/qnetworkinterface_unix.cpp b/src/network/kernel/qnetworkinterface_unix.cpp
index 9c5ba4e799..cc53087024 100644
--- a/src/network/kernel/qnetworkinterface_unix.cpp
+++ b/src/network/kernel/qnetworkinterface_unix.cpp
@@ -127,14 +127,13 @@ static QNetworkInterface::InterfaceFlags convertFlags(uint rawFlags)
#ifdef QT_NO_GETIFADDRS
// getifaddrs not available
-static const int STORAGEBUFFER_GROWTH = 256;
-
static QSet<QByteArray> interfaceNames(int socket)
{
QSet<QByteArray> result;
#ifdef QT_NO_IPV6IFNAME
QByteArray storageBuffer;
struct ifconf interfaceList;
+ static const int STORAGEBUFFER_GROWTH = 256;
forever {
// grow the storage buffer
@@ -186,9 +185,14 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
QNetworkInterfacePrivate *iface = 0;
int ifindex = 0;
-#ifndef QT_NO_IPV6IFNAME
+#if !defined(QT_NO_IPV6IFNAME) || defined(SIOCGIFINDEX)
// Get the interface index
+# ifdef SIOCGIFINDEX
+ if (qt_safe_ioctl(socket, SIOCGIFINDEX, &req) >= 0)
+ ifindex = req.ifr_ifindex;
+# else
ifindex = if_nametoindex(req.ifr_name);
+# endif
// find the interface data
QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
@@ -214,6 +218,27 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
iface = new QNetworkInterfacePrivate;
iface->index = ifindex;
interfaces << iface;
+ }
+
+ return iface;
+}
+
+static QList<QNetworkInterfacePrivate *> interfaceListing()
+{
+ QList<QNetworkInterfacePrivate *> interfaces;
+
+ int socket;
+ if ((socket = qt_safe_socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == -1)
+ return interfaces; // error
+
+ QSet<QByteArray> names = interfaceNames(socket);
+ QSet<QByteArray>::ConstIterator it = names.constBegin();
+ for ( ; it != names.constEnd(); ++it) {
+ ifreq req;
+ memset(&req, 0, sizeof(ifreq));
+ memcpy(req.ifr_name, *it, qMin<int>(it->length() + 1, sizeof(req.ifr_name) - 1));
+
+ QNetworkInterfacePrivate *iface = findInterface(socket, interfaces, req);
#ifdef SIOCGIFNAME
// Get the canonical name
@@ -242,27 +267,6 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
iface->hardwareAddress = iface->makeHwAddress(6, addr);
}
#endif
- }
-
- return iface;
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListing()
-{
- QList<QNetworkInterfacePrivate *> interfaces;
-
- int socket;
- if ((socket = qt_safe_socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == -1)
- return interfaces; // error
-
- QSet<QByteArray> names = interfaceNames(socket);
- QSet<QByteArray>::ConstIterator it = names.constBegin();
- for ( ; it != names.constEnd(); ++it) {
- ifreq req;
- memset(&req, 0, sizeof(ifreq));
- memcpy(req.ifr_name, *it, qMin<int>(it->length() + 1, sizeof(req.ifr_name) - 1));
-
- QNetworkInterfacePrivate *iface = findInterface(socket, interfaces, req);
// Get the interface broadcast address
QNetworkAddressEntry entry;
diff --git a/src/network/kernel/qnetworkinterface_win.cpp b/src/network/kernel/qnetworkinterface_win.cpp
index ddeb6c111f..dfcfdcc91f 100644
--- a/src/network/kernel/qnetworkinterface_win.cpp
+++ b/src/network/kernel/qnetworkinterface_win.cpp
@@ -43,6 +43,8 @@
#include <qurl.h>
#include <private/qsystemlibrary_p.h>
+#include <WS2tcpip.h>
+
QT_BEGIN_NAMESPACE
typedef DWORD (WINAPI *PtrGetAdaptersInfo)(PIP_ADAPTER_INFO, PULONG);
@@ -58,11 +60,11 @@ static void resolveLibs()
static bool done = false;
if (!done) {
- done = true;
-
HINSTANCE iphlpapiHnd = QSystemLibrary::load(L"iphlpapi");
- if (iphlpapiHnd == NULL)
+ if (iphlpapiHnd == NULL) {
+ done = true;
return;
+ }
#if defined(Q_OS_WINCE)
ptrGetAdaptersInfo = (PtrGetAdaptersInfo)GetProcAddress(iphlpapiHnd, L"GetAdaptersInfo");
@@ -73,6 +75,7 @@ static void resolveLibs()
ptrGetAdaptersAddresses = (PtrGetAdaptersAddresses)GetProcAddress(iphlpapiHnd, "GetAdaptersAddresses");
ptrGetNetworkParams = (PtrGetNetworkParams)GetProcAddress(iphlpapiHnd, "GetNetworkParams");
#endif
+ done = true;
}
}
@@ -85,8 +88,8 @@ static QHostAddress addressFromSockaddr(sockaddr *sa)
if (sa->sa_family == AF_INET)
address.setAddress(htonl(((sockaddr_in *)sa)->sin_addr.s_addr));
else if (sa->sa_family == AF_INET6) {
- address.setAddress(((qt_sockaddr_in6 *)sa)->sin6_addr.qt_s6_addr);
- int scope = ((qt_sockaddr_in6 *)sa)->sin6_scope_id;
+ address.setAddress(((sockaddr_in6 *)sa)->sin6_addr.s6_addr);
+ int scope = ((sockaddr_in6 *)sa)->sin6_scope_id;
if (scope)
address.setScopeId(QString::number(scope));
} else
@@ -221,67 +224,11 @@ static QList<QNetworkInterfacePrivate *> interfaceListingWinXP()
return interfaces;
}
-static QList<QNetworkInterfacePrivate *> interfaceListingWin2k()
-{
- QList<QNetworkInterfacePrivate *> interfaces;
- IP_ADAPTER_INFO staticBuf[2]; // 2 is arbitrary
- PIP_ADAPTER_INFO pAdapter = staticBuf;
- ULONG bufSize = sizeof staticBuf;
-
- DWORD retval = ptrGetAdaptersInfo(pAdapter, &bufSize);
- if (retval == ERROR_BUFFER_OVERFLOW) {
- // need more memory
- pAdapter = (IP_ADAPTER_INFO *)malloc(bufSize);
- if (!pAdapter)
- return interfaces;
- // try again
- if (ptrGetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
- free(pAdapter);
- return interfaces;
- }
- } else if (retval != ERROR_SUCCESS) {
- // error
- return interfaces;
- }
-
- // iterate over the list and add the entries to our listing
- for (PIP_ADAPTER_INFO ptr = pAdapter; ptr; ptr = ptr->Next) {
- QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
- interfaces << iface;
-
- iface->index = ptr->Index;
- iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
- if (ptr->Type == MIB_IF_TYPE_PPP)
- iface->flags |= QNetworkInterface::IsPointToPoint;
- else
- iface->flags |= QNetworkInterface::CanBroadcast;
- iface->name = QString::fromLocal8Bit(ptr->AdapterName);
- iface->hardwareAddress = QNetworkInterfacePrivate::makeHwAddress(ptr->AddressLength,
- ptr->Address);
-
- for (PIP_ADDR_STRING addr = &ptr->IpAddressList; addr; addr = addr->Next) {
- QNetworkAddressEntry entry;
- entry.setIp(QHostAddress(QLatin1String(addr->IpAddress.String)));
- entry.setNetmask(QHostAddress(QLatin1String(addr->IpMask.String)));
- // broadcast address is set on postProcess()
-
- iface->addressEntries << entry;
- }
- }
-
- if (pAdapter != staticBuf)
- free(pAdapter);
-
- return interfaces;
-}
-
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
resolveLibs();
if (ptrGetAdaptersAddresses != NULL)
return interfaceListingWinXP();
- else if (ptrGetAdaptersInfo != NULL)
- return interfaceListingWin2k();
// failed
return QList<QNetworkInterfacePrivate *>();
diff --git a/src/network/kernel/qnetworkinterface_win_p.h b/src/network/kernel/qnetworkinterface_win_p.h
index 88c1945fe6..55d98d2407 100644
--- a/src/network/kernel/qnetworkinterface_win_p.h
+++ b/src/network/kernel/qnetworkinterface_win_p.h
@@ -91,17 +91,6 @@ QT_BEGIN_NAMESPACE
#define IF_TYPE_PPP 23
#endif
-// copied from qnativesocketengine_win.cpp
-struct qt_in6_addr {
- u_char qt_s6_addr[16];
-};
-typedef struct {
- short sin6_family; /* AF_INET6 */
- u_short sin6_port; /* Transport level port number */
- u_long sin6_flowinfo; /* IPv6 flow information */
- struct qt_in6_addr sin6_addr; /* IPv6 address */
- u_long sin6_scope_id; /* set of interfaces for a scope */
-} qt_sockaddr_in6;
// copied from MSDN online help
typedef enum {
diff --git a/src/network/kernel/qnetworkproxy.cpp b/src/network/kernel/qnetworkproxy.cpp
index 53c4410fab..d219d72136 100644
--- a/src/network/kernel/qnetworkproxy.cpp
+++ b/src/network/kernel/qnetworkproxy.cpp
@@ -218,7 +218,6 @@
#include "private/qhttpsocketengine_p.h"
#include "qauthenticator.h"
#include "qdebug.h"
-#include "qhash.h"
#include "qmutex.h"
#include "qstringlist.h"
#include "qurl.h"
diff --git a/src/network/kernel/qnetworkproxy.h b/src/network/kernel/qnetworkproxy.h
index 6b0f4a3937..717c141d60 100644
--- a/src/network/kernel/qnetworkproxy.h
+++ b/src/network/kernel/qnetworkproxy.h
@@ -63,7 +63,6 @@ public:
QueryType queryType = TcpSocket);
explicit QNetworkProxyQuery(quint16 bindPort, const QString &protocolTag = QString(),
QueryType queryType = TcpServer);
- QNetworkProxyQuery(const QNetworkProxyQuery &other);
#ifndef QT_NO_BEARERMANAGEMENT
QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
const QUrl &requestUrl, QueryType queryType = UrlRequest);
@@ -74,10 +73,14 @@ public:
quint16 bindPort, const QString &protocolTag = QString(),
QueryType queryType = TcpServer);
#endif
- ~QNetworkProxyQuery();
+ QNetworkProxyQuery(const QNetworkProxyQuery &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkProxyQuery &operator=(QNetworkProxyQuery &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkProxyQuery &operator=(const QNetworkProxyQuery &other);
+ ~QNetworkProxyQuery();
- void swap(QNetworkProxyQuery &other) { qSwap(d, other.d); }
+ void swap(QNetworkProxyQuery &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkProxyQuery &other) const;
inline bool operator!=(const QNetworkProxyQuery &other) const
@@ -139,10 +142,13 @@ public:
QNetworkProxy(ProxyType type, const QString &hostName = QString(), quint16 port = 0,
const QString &user = QString(), const QString &password = QString());
QNetworkProxy(const QNetworkProxy &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkProxy &operator=(QNetworkProxy &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkProxy &operator=(const QNetworkProxy &other);
~QNetworkProxy();
- void swap(QNetworkProxy &other) { qSwap(d, other.d); }
+ void swap(QNetworkProxy &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkProxy &other) const;
inline bool operator!=(const QNetworkProxy &other) const
diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp
index c42b4f520c..009bc90bf5 100644
--- a/src/network/socket/qabstractsocket.cpp
+++ b/src/network/socket/qabstractsocket.cpp
@@ -559,7 +559,6 @@ QAbstractSocketPrivate::QAbstractSocketPrivate()
readBufferMaxSize(0),
writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
isBuffered(false),
- blockingTimeout(30000),
connectTimer(0),
disconnectTimer(0),
connectTimeElapsed(0),
@@ -650,6 +649,8 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
return false;
}
+ configureCreatedSocket();
+
if (threadData->hasEventDispatcher())
socketEngine->setReceiver(this);
@@ -661,6 +662,12 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
}
/*! \internal
+*/
+void QAbstractSocketPrivate::configureCreatedSocket()
+{
+}
+
+/*! \internal
Slot connected to the read socket notifier. This slot is called
when new data is available for reading, or when the socket has
@@ -817,7 +824,7 @@ bool QAbstractSocketPrivate::canWriteNotification()
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
#endif
- int tmp = writeBuffer.size();
+ qint64 tmp = writeBuffer.size();
flush();
if (socketEngine) {
@@ -877,7 +884,7 @@ bool QAbstractSocketPrivate::flush()
return false;
}
- int nextSize = writeBuffer.nextDataBlockSize();
+ qint64 nextSize = writeBuffer.nextDataBlockSize();
const char *ptr = writeBuffer.readPointer();
// Attempt to write it all in one chunk.
@@ -1712,9 +1719,9 @@ qint64 QAbstractSocket::bytesToWrite() const
{
Q_D(const QAbstractSocket);
#if defined(QABSTRACTSOCKET_DEBUG)
- qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
+ qDebug("QAbstractSocket::bytesToWrite() == %lld", d->writeBuffer.size());
#endif
- return (qint64)d->writeBuffer.size();
+ return d->writeBuffer.size();
}
/*!
@@ -1808,12 +1815,12 @@ QString QAbstractSocket::peerName() const
*/
bool QAbstractSocket::canReadLine() const
{
- bool hasLine = d_func()->buffer.canReadLine();
+ bool hasLine = QIODevice::canReadLine();
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %lld, size = %lld",
hasLine ? "true" : "false", d_func()->buffer.size(), d_func()->buffer.size());
#endif
- return hasLine || QIODevice::canReadLine();
+ return hasLine;
}
/*!
diff --git a/src/network/socket/qabstractsocket.h b/src/network/socket/qabstractsocket.h
index f3d7f13f48..23f0d26cbd 100644
--- a/src/network/socket/qabstractsocket.h
+++ b/src/network/socket/qabstractsocket.h
@@ -149,7 +149,7 @@ public:
qint64 bytesAvailable() const Q_DECL_OVERRIDE;
qint64 bytesToWrite() const Q_DECL_OVERRIDE;
- bool canReadLine() const Q_DECL_OVERRIDE;
+ bool canReadLine() const Q_DECL_OVERRIDE; // ### Qt6: remove me
quint16 localPort() const;
QHostAddress localAddress() const;
@@ -213,7 +213,7 @@ protected:
void setPeerAddress(const QHostAddress &address);
void setPeerName(const QString &name);
- QAbstractSocket(SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent = 0);
+ QAbstractSocket(SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QAbstractSocket)
diff --git a/src/network/socket/qabstractsocket_p.h b/src/network/socket/qabstractsocket_p.h
index 63440b6416..85e82aef47 100644
--- a/src/network/socket/qabstractsocket_p.h
+++ b/src/network/socket/qabstractsocket_p.h
@@ -130,6 +130,7 @@ public:
bool flush();
bool initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol);
+ virtual void configureCreatedSocket();
void startConnectingByName(const QString &host);
void fetchConnectionParameters();
void setupSocketNotifiers();
@@ -139,7 +140,6 @@ public:
QRingBuffer writeBuffer;
bool isBuffered;
- int blockingTimeout;
QTimer *connectTimer;
QTimer *disconnectTimer;
diff --git a/src/network/socket/qabstractsocketengine_p.h b/src/network/socket/qabstractsocketengine_p.h
index f2a3149678..d2b5882d18 100644
--- a/src/network/socket/qabstractsocketengine_p.h
+++ b/src/network/socket/qabstractsocketengine_p.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -58,6 +59,30 @@ class QNetworkInterface;
#endif
class QNetworkProxy;
+class QIpPacketHeader
+{
+public:
+ QIpPacketHeader(const QHostAddress &dstAddr = QHostAddress(), quint16 port = 0)
+ : destinationAddress(dstAddr), ifindex(0), hopLimit(-1), destinationPort(port)
+ {}
+
+ void clear()
+ {
+ senderAddress.clear();
+ destinationAddress.clear();
+ ifindex = 0;
+ hopLimit = -1;
+ }
+
+ QHostAddress senderAddress;
+ QHostAddress destinationAddress;
+
+ uint ifindex;
+ qint16 hopLimit;
+ quint16 senderPort;
+ quint16 destinationPort;
+};
+
class QAbstractSocketEngineReceiver {
public:
virtual ~QAbstractSocketEngineReceiver(){}
@@ -93,9 +118,21 @@ public:
KeepAliveOption,
MulticastTtlOption,
MulticastLoopbackOption,
- TypeOfServiceOption
+ TypeOfServiceOption,
+ ReceivePacketInformation,
+ ReceiveHopLimit
};
+ enum PacketHeaderOption {
+ WantNone = 0,
+ WantDatagramSender,
+ WantDatagramDestination,
+ WantDatagramHopLimit,
+
+ WantAll = 0xff
+ };
+ Q_DECLARE_FLAGS(PacketHeaderOptions, PacketHeaderOption)
+
virtual bool initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol = QAbstractSocket::IPv4Protocol) = 0;
virtual bool initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState = QAbstractSocket::ConnectedState) = 0;
@@ -126,10 +163,9 @@ public:
virtual bool setMulticastInterface(const QNetworkInterface &iface) = 0;
#endif // QT_NO_NETWORKINTERFACE
- virtual qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) = 0;
- virtual qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) = 0;
+ virtual qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header = 0,
+ PacketHeaderOptions = WantNone) = 0;
+ virtual qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header) = 0;
virtual bool hasPendingDatagrams() const = 0;
virtual qint64 pendingDatagramSize() const = 0;
#endif // QT_NO_UDPSOCKET
@@ -225,6 +261,8 @@ private:
friend class QAbstractSocketEngine;
};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QAbstractSocketEngine::PacketHeaderOptions)
+
QT_END_NAMESPACE
#endif // QABSTRACTSOCKETENGINE_P_H
diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp
index 23347ce08b..1a90abd22c 100644
--- a/src/network/socket/qhttpsocketengine.cpp
+++ b/src/network/socket/qhttpsocketengine.cpp
@@ -271,14 +271,12 @@ bool QHttpSocketEngine::setMulticastInterface(const QNetworkInterface &)
}
#endif // QT_NO_NETWORKINTERFACE
-qint64 QHttpSocketEngine::readDatagram(char *, qint64, QHostAddress *,
- quint16 *)
+qint64 QHttpSocketEngine::readDatagram(char *, qint64, QIpPacketHeader *, PacketHeaderOptions)
{
return 0;
}
-qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QHostAddress &,
- quint16)
+qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QIpPacketHeader &)
{
return 0;
}
diff --git a/src/network/socket/qhttpsocketengine_p.h b/src/network/socket/qhttpsocketengine_p.h
index 4d90487679..41c63fe11e 100644
--- a/src/network/socket/qhttpsocketengine_p.h
+++ b/src/network/socket/qhttpsocketengine_p.h
@@ -105,10 +105,9 @@ public:
bool setMulticastInterface(const QNetworkInterface &iface) Q_DECL_OVERRIDE;
#endif // QT_NO_NETWORKINTERFACE
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader *,
+ PacketHeaderOptions) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qlocalserver.h b/src/network/socket/qlocalserver.h
index a03cdb726d..24908db4aa 100644
--- a/src/network/socket/qlocalserver.h
+++ b/src/network/socket/qlocalserver.h
@@ -64,7 +64,7 @@ public:
};
Q_DECLARE_FLAGS(SocketOptions, SocketOption)
- explicit QLocalServer(QObject *parent = 0);
+ explicit QLocalServer(QObject *parent = Q_NULLPTR);
~QLocalServer();
void close();
@@ -80,7 +80,7 @@ public:
static bool removeServer(const QString &name);
QAbstractSocket::SocketError serverError() const;
void setMaxPendingConnections(int numConnections);
- bool waitForNewConnection(int msec = 0, bool *timedOut = 0);
+ bool waitForNewConnection(int msec = 0, bool *timedOut = Q_NULLPTR);
void setSocketOptions(SocketOptions options);
SocketOptions socketOptions() const;
diff --git a/src/network/socket/qlocalsocket.h b/src/network/socket/qlocalsocket.h
index a4d8405912..4b39a7c562 100644
--- a/src/network/socket/qlocalsocket.h
+++ b/src/network/socket/qlocalsocket.h
@@ -73,7 +73,7 @@ public:
ClosingState = QAbstractSocket::ClosingState
};
- QLocalSocket(QObject *parent = 0);
+ QLocalSocket(QObject *parent = Q_NULLPTR);
~QLocalSocket();
void connectToServer(OpenMode openMode = ReadWrite);
diff --git a/src/network/socket/qnativesocketengine.cpp b/src/network/socket/qnativesocketengine.cpp
index 52e6922b5f..c11b889220 100644
--- a/src/network/socket/qnativesocketengine.cpp
+++ b/src/network/socket/qnativesocketengine.cpp
@@ -88,6 +88,25 @@
errorString() can be called to determine the cause of the error.
*/
+/*!
+ \enum QAbstractSocketEngine::PacketHeaderOption
+
+ Specifies which fields in the IP packet header are desired in the call to
+ readDatagram().
+
+ \value WantNone caller isn't interested in the packet metadata
+ \value WantDatagramSender caller wants the sender address and port number
+ \value WantDatagramDestination caller wants the packet's destination address and port number
+ (this option is useful to distinguish multicast packets from unicast)
+ \value WantDatagramHopLimit caller wants the packet's remaining hop limit or time to live
+ (this option is useful in IPv4 multicasting, where the TTL is used
+ to indicate the realm)
+ \value WantAll this is a catch-all value to indicate the caller is
+ interested in all the available information
+
+ \sa readDatagram(), QUdpDatagram
+*/
+
#include "qnativesocketengine_p.h"
#include <qabstracteventdispatcher.h>
@@ -152,10 +171,6 @@ QT_BEGIN_NAMESPACE
/*! \internal
Constructs the private class and initializes all data members.
-
- On Windows, WSAStartup is called "recursively" for every
- concurrent QNativeSocketEngine. This is safe, because WSAStartup and
- WSACleanup are reference counted.
*/
QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
socketDescriptor(-1),
@@ -163,6 +178,9 @@ QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
writeNotifier(0),
exceptNotifier(0)
{
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+ QSysInfo::machineHostName(); // this initializes ws2_32.dll
+#endif
}
/*! \internal
@@ -395,13 +413,18 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
return false;
}
- // Set the broadcasting flag if it's a UDP socket.
- if (socketType == QAbstractSocket::UdpSocket
- && !setOption(BroadcastSocketOption, 1)) {
- d->setError(QAbstractSocket::UnsupportedSocketOperationError,
- QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
- close();
- return false;
+ if (socketType == QAbstractSocket::UdpSocket) {
+ // Set the broadcasting flag if it's a UDP socket.
+ if (!setOption(BroadcastSocketOption, 1)) {
+ d->setError(QAbstractSocket::UnsupportedSocketOperationError,
+ QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
+ close();
+ return false;
+ }
+
+ // Set some extra flags that are interesting to us, but accept failure
+ setOption(ReceivePacketInformation, 1);
+ setOption(ReceiveHopLimit, 1);
}
@@ -425,8 +448,6 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
// setReceiveBufferSize(49152);
// setSendBufferSize(49152);
- d->socketType = socketType;
- d->socketProtocol = protocol;
return true;
}
@@ -762,9 +783,8 @@ qint64 QNativeSocketEngine::pendingDatagramSize() const
/*!
Reads up to \a maxSize bytes of a datagram from the socket,
stores it in \a data and returns the number of bytes read. The
- address and port of the sender are stored in \a address and \a
- port. If either of these pointers is 0, the corresponding value is
- discarded.
+ address, port, and other IP header fields are stored in \a header
+ according to the request in \a options.
To avoid unnecessarily loss of data, call pendingDatagramSize() to
determine the size of the pending message before reading it. If \a
@@ -774,20 +794,23 @@ qint64 QNativeSocketEngine::pendingDatagramSize() const
\sa hasPendingDatagrams()
*/
-qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
- quint16 *port)
+qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QIpPacketHeader *header,
+ PacketHeaderOptions options)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::readDatagram(), -1);
Q_CHECK_TYPE(QNativeSocketEngine::readDatagram(), QAbstractSocket::UdpSocket, -1);
- return d->nativeReceiveDatagram(data, maxSize, address, port);
+ return d->nativeReceiveDatagram(data, maxSize, header, options);
}
/*!
Writes a UDP datagram of size \a size bytes to the socket from
- \a data to the address \a host on port \a port, and returns the
- number of bytes written, or -1 if an error occurred.
+ \a data to the destination contained in \a header, and returns the
+ number of bytes written, or -1 if an error occurred. If \a header
+ contains other settings like hop limit or source address, this function
+ will try to pass them to the operating system too, but will not
+ indicate an error if it could not pass them.
Only one datagram is sent, and if there is too much data to fit
into a single datagram, the operation will fail and error()
@@ -797,18 +820,19 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddres
disadvised, as even if they are sent successfully, they are likely
to be fragmented before arriving at their destination.
- Experience has shown that it is in general safe to send datagrams
- no larger than 512 bytes.
+ Experience has shown that it is in general safe to send IPv4 datagrams
+ no larger than 512 bytes or IPv6 datagrams no larger than 1280 (the
+ minimum MTU).
\sa readDatagram()
*/
-qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size,
- const QHostAddress &host, quint16 port)
+qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size, const QIpPacketHeader &header)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::writeDatagram(), -1);
Q_CHECK_TYPE(QNativeSocketEngine::writeDatagram(), QAbstractSocket::UdpSocket, -1);
- return d->nativeSendDatagram(data, size, d->adjustAddressProtocol(host), port);
+
+ return d->nativeSendDatagram(data, size, header);
}
/*!
diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h
index 24909bf310..0fa1d8f96e 100644
--- a/src/network/socket/qnativesocketengine_p.h
+++ b/src/network/socket/qnativesocketengine_p.h
@@ -51,46 +51,51 @@
# include <netinet/in.h>
#else
# include <winsock2.h>
+# include <ws2tcpip.h>
+# include <mswsock.h>
#endif
QT_BEGIN_NAMESPACE
-// Use our own defines and structs which we know are correct
-# define QT_SS_MAXSIZE 128
-# define QT_SS_ALIGNSIZE (sizeof(qint64))
-# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short))
-# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE))
-struct qt_sockaddr_storage {
- short ss_family;
- char __ss_pad1[QT_SS_PAD1SIZE];
- qint64 __ss_align;
- char __ss_pad2[QT_SS_PAD2SIZE];
-};
-
#ifdef Q_OS_WIN
#define QT_SOCKLEN_T int
#define QT_SOCKOPTLEN_T int
-#endif
-// sockaddr_in6 size changed between old and new SDK
-// Only the new version is the correct one, so always
-// use this structure.
-struct qt_in6_addr {
- quint8 qt_s6_addr[16];
-};
-struct qt_sockaddr_in6 {
- short sin6_family; /* AF_INET6 */
- quint16 sin6_port; /* Transport level port number */
- quint32 sin6_flowinfo; /* IPv6 flow information */
- struct qt_in6_addr sin6_addr; /* IPv6 address */
- quint32 sin6_scope_id; /* set of interfaces for a scope */
-};
+// The following definitions are copied from the MinGW header mswsock.h which
+// was placed in the public domain. The WSASendMsg and WSARecvMsg functions
+// were introduced with Windows Vista, so some Win32 headers are lacking them.
+// There are no known versions of Windows CE or Embedded that contain them.
+#ifndef Q_OS_WINCE
+# ifndef WSAID_WSARECVMSG
+typedef INT (WINAPI *LPFN_WSARECVMSG)(SOCKET s, LPWSAMSG lpMsg,
+ LPDWORD lpdwNumberOfBytesRecvd,
+ LPWSAOVERLAPPED lpOverlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
+# define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
+# endif
+# ifndef WSAID_WSASENDMSG
+typedef struct {
+ LPWSAMSG lpMsg;
+ DWORD dwFlags;
+ LPDWORD lpNumberOfBytesSent;
+ LPWSAOVERLAPPED lpOverlapped;
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine;
+} WSASENDMSG, *LPWSASENDMSG;
+
+typedef INT (WSAAPI *LPFN_WSASENDMSG)(SOCKET s, LPWSAMSG lpMsg, DWORD dwFlags,
+ LPDWORD lpNumberOfBytesSent,
+ LPWSAOVERLAPPED lpOverlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
+
+# define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
+# endif
+#endif
+#endif
union qt_sockaddr {
sockaddr a;
sockaddr_in a4;
- qt_sockaddr_in6 a6;
- qt_sockaddr_storage storage;
+ sockaddr_in6 a6;
};
class QNativeSocketEnginePrivate;
@@ -133,10 +138,9 @@ public:
qint64 read(char *data, qint64 maxlen) Q_DECL_OVERRIDE;
qint64 write(const char *data, qint64 len) Q_DECL_OVERRIDE;
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader * = 0,
+ PacketHeaderOptions = WantNone) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
@@ -173,16 +177,6 @@ private:
Q_DISABLE_COPY(QNativeSocketEngine)
};
-#ifdef Q_OS_WIN
-class QWindowsSockInit
-{
-public:
- QWindowsSockInit();
- ~QWindowsSockInit();
- int version;
-};
-#endif
-
class QSocketNotifier;
class QNativeSocketEnginePrivate : public QAbstractSocketEnginePrivate
@@ -196,10 +190,10 @@ public:
QSocketNotifier *readNotifier, *writeNotifier, *exceptNotifier;
-#ifdef Q_OS_WIN
- QWindowsSockInit winSock;
-#endif
-
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+ LPFN_WSASENDMSG sendmsg;
+ LPFN_WSARECVMSG recvmsg;
+# endif
enum ErrorString {
NonBlockingInitFailedErrorString,
BroadcastingInitFailedErrorString,
@@ -256,24 +250,48 @@ public:
bool nativeHasPendingDatagrams() const;
qint64 nativePendingDatagramSize() const;
- qint64 nativeReceiveDatagram(char *data, qint64 maxLength,
- QHostAddress *address, quint16 *port);
- qint64 nativeSendDatagram(const char *data, qint64 length,
- const QHostAddress &host, quint16 port);
+ qint64 nativeReceiveDatagram(char *data, qint64 maxLength, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options);
+ qint64 nativeSendDatagram(const char *data, qint64 length, const QIpPacketHeader &header);
qint64 nativeRead(char *data, qint64 maxLength);
qint64 nativeWrite(const char *data, qint64 length);
int nativeSelect(int timeout, bool selectForRead) const;
int nativeSelect(int timeout, bool checkRead, bool checkWrite,
bool *selectForRead, bool *selectForWrite) const;
-#ifdef Q_OS_WIN
- void setPortAndAddress(sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
- quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize);
-#endif
void nativeClose();
bool checkProxy(const QHostAddress &address);
bool fetchConnectionParameters();
+
+ static uint scopeIdFromString(const QString &scopeid);
+
+ /*! \internal
+ Sets \a address and \a port in the \a aa sockaddr structure and the size in \a sockAddrSize.
+ The address \a is converted to IPv6 if the current socket protocol is also IPv6.
+ */
+ void setPortAndAddress(quint16 port, const QHostAddress &address, qt_sockaddr *aa, QT_SOCKLEN_T *sockAddrSize)
+ {
+ if (address.protocol() == QAbstractSocket::IPv6Protocol
+ || address.protocol() == QAbstractSocket::AnyIPProtocol
+ || socketProtocol == QAbstractSocket::IPv6Protocol
+ || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ memset(&aa->a6, 0, sizeof(sockaddr_in6));
+ aa->a6.sin6_family = AF_INET6;
+ aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());
+ aa->a6.sin6_port = htons(port);
+ Q_IPV6ADDR tmp = address.toIPv6Address();
+ memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));
+ *sockAddrSize = sizeof(sockaddr_in6);
+ } else {
+ memset(&aa->a, 0, sizeof(sockaddr_in));
+ aa->a4.sin_family = AF_INET;
+ aa->a4.sin_port = htons(port);
+ aa->a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ *sockAddrSize = sizeof(sockaddr_in);
+ }
+ }
+
};
QT_END_NAMESPACE
diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp
index 4648a3cb5a..0e14c175c5 100644
--- a/src/network/socket/qnativesocketengine_unix.cpp
+++ b/src/network/socket/qnativesocketengine_unix.cpp
@@ -49,6 +49,9 @@
#ifdef QT_LINUXBASE
#include <arpa/inet.h>
#endif
+#ifdef Q_OS_BSD4
+#include <net/if_dl.h>
+#endif
#if defined QNATIVESOCKETENGINE_DEBUG
#include <qstring.h>
@@ -128,9 +131,9 @@ static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *po
}
}
-static inline uint makeScopeId(const QHostAddress &addr)
+// inline on purpose
+inline uint QNativeSocketEnginePrivate::scopeIdFromString(const QString &scopeid)
{
- QString scopeid = addr.scopeId();
if (scopeid.isEmpty())
return 0;
@@ -202,6 +205,32 @@ static void convertToLevelAndOption(QNativeSocketEngine::SocketOption opt,
n = IP_TOS;
}
break;
+ case QNativeSocketEngine::ReceivePacketInformation:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_RECVPKTINFO;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+#ifdef IP_PKTINFO
+ n = IP_PKTINFO;
+#elif defined(IP_RECVDSTADDR)
+ // variant found in QNX and FreeBSD; it will get us only the
+ // destination address, not the interface; we need IP_RECVIF for that.
+ n = IP_RECVDSTADDR;
+#endif
+ }
+ break;
+ case QNativeSocketEngine::ReceiveHopLimit:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_RECVHOPLIMIT;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+#ifdef IP_RECVTTL // IP_RECVTTL is a non-standard extension supported on some OS
+ level = IPPROTO_IP;
+ n = IP_RECVTTL;
+#endif
+ }
+ break;
}
}
@@ -259,6 +288,10 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
#endif
socketDescriptor = socket;
+ if (socket != -1) {
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
+ }
return true;
}
@@ -281,7 +314,7 @@ int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) co
QT_SOCKOPTLEN_T len = sizeof(v);
convertToLevelAndOption(opt, socketProtocol, level, n);
- if (::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
+ if (n != -1 && ::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
return v;
return -1;
@@ -356,37 +389,11 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
qDebug() << "QNativeSocketEnginePrivate::nativeConnect() " << socketDescriptor;
#endif
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- struct sockaddr_in6 sockAddrIPv6;
-
- if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(addr);
-
- Q_IPV6ADDR ip6 = addr.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6));
-
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
- } else
- if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(addr.toIPv4Address());
-
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- } else {
- // unreachable
- }
+ qt_sockaddr aa;
+ QT_SOCKLEN_T sockAddrSize;
+ setPortAndAddress(port, addr, &aa, &sockAddrSize);
- int connectResult = qt_safe_connect(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int connectResult = qt_safe_connect(socketDescriptor, &aa.a, sockAddrSize);
#if defined (QNATIVESOCKETENGINE_DEBUG)
int ecopy = errno;
#endif
@@ -458,51 +465,28 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16 port)
{
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
-
- struct sockaddr_in6 sockAddrIPv6;
+ qt_sockaddr aa;
+ QT_SOCKLEN_T sockAddrSize;
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
- if (address.protocol() == QAbstractSocket::IPv6Protocol || address.protocol() == QAbstractSocket::AnyIPProtocol) {
#ifdef IPV6_V6ONLY
+ if (aa.a.sa_family == AF_INET6) {
int ipv6only = 0;
if (address.protocol() == QAbstractSocket::IPv6Protocol)
ipv6only = 1;
//default value of this socket option varies depending on unix variant (or system configuration on BSD), so always set it explicitly
::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
+ }
#endif
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(address);
-
- Q_IPV6ADDR tmp = address.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
- } else
- if (address.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- } else {
- // unreachable
- }
- int bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);
if (bindResult < 0 && errno == EAFNOSUPPORT && address.protocol() == QAbstractSocket::AnyIPProtocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
+ // retry with v4
+ aa.a4.sin_family = AF_INET;
+ aa.a4.sin_port = htons(port);
+ aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ sockAddrSize = sizeof(aa.a4);
+ bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);
}
if (bindResult < 0) {
@@ -840,68 +824,183 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
return qint64(recvResult);
}
-qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize,
- QHostAddress *address, quint16 *port)
+qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options)
{
+ // we use quintptr to force the alignment
+ quintptr cbuf[(CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(int)) + sizeof(quintptr) - 1) / sizeof(quintptr)];
+
+ struct msghdr msg;
+ struct iovec vec;
qt_sockaddr aa;
+ char c;
+ memset(&msg, 0, sizeof(msg));
memset(&aa, 0, sizeof(aa));
- QT_SOCKLEN_T sz;
- sz = sizeof(aa);
- ssize_t recvFromResult = 0;
+ // we need to receive at least one byte, even if our user isn't interested in it
+ vec.iov_base = maxSize ? data : &c;
+ vec.iov_len = maxSize ? maxSize : 1;
+ msg.msg_iov = &vec;
+ msg.msg_iovlen = 1;
+ if (options & QAbstractSocketEngine::WantDatagramSender) {
+ msg.msg_name = &aa;
+ msg.msg_namelen = sizeof(aa);
+ }
+ if (options & (QAbstractSocketEngine::WantDatagramHopLimit | QAbstractSocketEngine::WantDatagramDestination)) {
+ msg.msg_control = cbuf;
+ msg.msg_controllen = sizeof(cbuf);
+ }
+
+ ssize_t recvResult = 0;
do {
- char c;
- recvFromResult = ::recvfrom(socketDescriptor, maxSize ? data : &c, maxSize ? maxSize : 1,
- 0, &aa.a, &sz);
- } while (recvFromResult == -1 && errno == EINTR);
+ recvResult = ::recvmsg(socketDescriptor, &msg, 0);
+ } while (recvResult == -1 && errno == EINTR);
- if (recvFromResult == -1) {
+ if (recvResult == -1) {
setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
- } else if (port || address) {
- qt_socket_getPortAndAddress(&aa, port, address);
+ if (header)
+ header->clear();
+ } else if (options != QAbstractSocketEngine::WantNone) {
+ Q_ASSERT(header);
+ qt_socket_getPortAndAddress(&aa, &header->senderPort, &header->senderAddress);
+ header->destinationPort = localPort;
+
+ // parse the ancillary data
+ struct cmsghdr *cmsgptr;
+ for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
+ cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) {
+ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in6_pktinfo))) {
+ in6_pktinfo *info = reinterpret_cast<in6_pktinfo *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(reinterpret_cast<quint8 *>(&info->ipi6_addr));
+ header->ifindex = info->ipi6_ifindex;
+ if (header->ifindex)
+ header->destinationAddress.setScopeId(QString::number(info->ipi6_ifindex));
+ }
+
+#ifdef IP_PKTINFO
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_PKTINFO
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in_pktinfo))) {
+ in_pktinfo *info = reinterpret_cast<in_pktinfo *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(ntohl(info->ipi_addr.s_addr));
+ header->ifindex = info->ipi_ifindex;
+ }
+#else
+# ifdef IP_RECVDSTADDR
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_RECVDSTADDR
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in_addr))) {
+ in_addr *addr = reinterpret_cast<in_addr *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(ntohl(addr->s_addr));
+ }
+# endif
+# if defined(IP_RECVIF) && defined(Q_OS_BSD4)
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_RECVIF
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(sockaddr_dl))) {
+ sockaddr_dl *sdl = reinterpret_cast<sockaddr_dl *>(CMSG_DATA(cmsgptr));
+
+ header->ifindex = LLINDEX(sdl);
+ }
+# endif
+#endif
+
+ if (cmsgptr->cmsg_len == CMSG_LEN(sizeof(int))
+ && ((cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT)
+ || (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_TTL))) {
+ header->hopLimit = *reinterpret_cast<int *>(CMSG_DATA(cmsgptr));
+ }
+ }
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
- data, qt_prettyDebug(data, qMin(recvFromResult, ssize_t(16)), recvFromResult).data(), maxSize,
+ data, qt_prettyDebug(data, qMin(recvResult, ssize_t(16)), recvResult).data(), maxSize,
address ? address->toString().toLatin1().constData() : "(nil)",
- port ? *port : 0, (qint64) recvFromResult);
+ port ? *port : 0, (qint64) recvResult);
#endif
- return qint64(maxSize ? recvFromResult : recvFromResult == -1 ? -1 : 0);
+ return qint64(maxSize ? recvResult : recvResult == -1 ? -1 : 0);
}
-qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
- const QHostAddress &host, quint16 port)
+qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- struct sockaddr_in6 sockAddrIPv6;
- if (host.protocol() == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::AnyIPProtocol) {
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(host);
-
- Q_IPV6ADDR tmp = host.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *)&sockAddrIPv6;
- } else if (host.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(host.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *)&sockAddrIPv4;
+ // we use quintptr to force the alignment
+ quintptr cbuf[(CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(int)) + sizeof(quintptr) - 1) / sizeof(quintptr)];
+
+ struct cmsghdr *cmsgptr = reinterpret_cast<struct cmsghdr *>(cbuf);
+ struct msghdr msg;
+ struct iovec vec;
+ qt_sockaddr aa;
+
+ memset(&msg, 0, sizeof(msg));
+ memset(&aa, 0, sizeof(aa));
+ vec.iov_base = const_cast<char *>(data);
+ vec.iov_len = len;
+ msg.msg_iov = &vec;
+ msg.msg_iovlen = 1;
+ msg.msg_name = &aa.a;
+ msg.msg_control = &cbuf;
+
+ setPortAndAddress(header.destinationPort, header.destinationAddress, &aa, &msg.msg_namelen);
+
+ if (msg.msg_namelen == sizeof(aa.a6)) {
+ if (header.hopLimit != -1) {
+ msg.msg_controllen += CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_HOPLIMIT;
+ memcpy(CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in6_pktinfo *data = reinterpret_cast<in6_pktinfo *>(CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.msg_controllen += CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_PKTINFO;
+ data->ipi6_ifindex = header.ifindex;
+
+ QIPv6Address tmp = header.senderAddress.toIPv6Address();
+ memcpy(&data->ipi6_addr, &tmp, sizeof(tmp));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(*data)));
+ }
+ } else {
+ if (header.hopLimit != -1) {
+ msg.msg_controllen += CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_TTL;
+ memcpy(CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(int)));
+ }
+
+#if defined(IP_PKTINFO) || defined(IP_SENDSRCADDR)
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+# ifdef IP_PKTINFO
+ struct in_pktinfo *data = reinterpret_cast<in_pktinfo *>(CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ cmsgptr->cmsg_type = IP_PKTINFO;
+ data->ipi_ifindex = header.ifindex;
+ data->ipi_addr.s_addr = htonl(header.senderAddress.toIPv4Address());
+# elif defined(IP_SENDSRCADDR)
+ struct in_addr *data = reinterpret_cast<in_addr *>(CMSG_DATA(cmsgptr));
+ cmsgptr->cmsg_type = IP_SENDSRCADDR;
+ addr->s_addr = htonl(header.senderAddress.toIPv4Address());
+# endif
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ msg.msg_controllen += CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(*data));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(*data)));
+ }
+#endif
}
- ssize_t sentBytes = qt_safe_sendto(socketDescriptor, data, len,
- 0, sockAddrPtr, sockAddrSize);
+ if (msg.msg_controllen == 0)
+ msg.msg_control = 0;
+ ssize_t sentBytes = qt_safe_sendmsg(socketDescriptor, &msg, 0);
if (sentBytes < 0) {
switch (errno) {
diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp
index 72f85c831f..2e905ad610 100644
--- a/src/network/socket/qnativesocketengine_win.cpp
+++ b/src/network/socket/qnativesocketengine_win.cpp
@@ -59,6 +59,9 @@ QT_BEGIN_NAMESPACE
#ifndef IPV6_V6ONLY
#define IPV6_V6ONLY 27
#endif
+#ifndef IP_HOPLIMIT
+#define IP_HOPLIMIT 21 // Receive packet hop limit.
+#endif
#if defined(QNATIVESOCKETENGINE_DEBUG)
@@ -168,10 +171,10 @@ static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
static inline void qt_socket_getPortAndAddress(SOCKET socketDescriptor, const qt_sockaddr *sa, quint16 *port, QHostAddress *address)
{
if (sa->a.sa_family == AF_INET6) {
- const qt_sockaddr_in6 *sa6 = &sa->a6;
+ const sockaddr_in6 *sa6 = &sa->a6;
Q_IPV6ADDR tmp;
for (int i = 0; i < 16; ++i)
- tmp.c[i] = sa6->sin6_addr.qt_s6_addr[i];
+ tmp.c[i] = sa6->sin6_addr.s6_addr[i];
if (address) {
QHostAddress a;
a.setAddress(tmp);
@@ -252,40 +255,24 @@ static void convertToLevelAndOption(QNativeSocketEngine::SocketOption opt,
n = IP_MULTICAST_LOOP;
}
break;
- }
-}
-
-/*! \internal
-
- Sets the port and address to a sockaddr. Requires that sa point to the IPv6 struct if the address is IPv6.
-*/
-void QNativeSocketEnginePrivate::setPortAndAddress(sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
- quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize)
-{
- if (address.protocol() == QAbstractSocket::IPv6Protocol
- || address.protocol() == QAbstractSocket::AnyIPProtocol
- || socketProtocol == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::AnyIPProtocol) {
- memset(sockAddrIPv6, 0, sizeof(qt_sockaddr_in6));
- sockAddrIPv6->sin6_family = AF_INET6;
- sockAddrIPv6->sin6_scope_id = address.scopeId().toUInt();
- WSAHtons(socketDescriptor, port, &(sockAddrIPv6->sin6_port));
- Q_IPV6ADDR tmp = address.toIPv6Address();
- memcpy(&(sockAddrIPv6->sin6_addr.qt_s6_addr), &tmp, sizeof(tmp));
- *sockAddrSize = sizeof(qt_sockaddr_in6);
- *sockAddrPtr = (struct sockaddr *) sockAddrIPv6;
- } else
-
- if (address.protocol() == QAbstractSocket::IPv4Protocol
- || address.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
- memset(sockAddrIPv4, 0, sizeof(sockaddr_in));
- sockAddrIPv4->sin_family = AF_INET;
- WSAHtons(socketDescriptor, port, &(sockAddrIPv4->sin_port));
- WSAHtonl(socketDescriptor, address.toIPv4Address(), &(sockAddrIPv4->sin_addr.s_addr));
- *sockAddrSize = sizeof(sockaddr_in);
- *sockAddrPtr = (struct sockaddr *) sockAddrIPv4;
- } else {
- // unreachable
+ case QNativeSocketEngine::ReceivePacketInformation:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_PKTINFO;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+ n = IP_PKTINFO;
+ }
+ break;
+ case QNativeSocketEngine::ReceiveHopLimit:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_HOPLIMIT;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+ n = IP_HOPLIMIT;
+ }
+ break;
}
}
@@ -320,25 +307,6 @@ static inline int qt_socket_getMaxMsgSize(qintptr socketDescriptor)
return value;
}
-QWindowsSockInit::QWindowsSockInit()
-: version(0)
-{
- //### should we try for 2.2 on all platforms ??
- WSAData wsadata;
-
- // IPv6 requires Winsock v2.0 or better.
- if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
- qWarning("QTcpSocketAPI: WinSock v2.0 initialization failed.");
- } else {
- version = 0x20;
- }
-}
-
-QWindowsSockInit::~QWindowsSockInit()
-{
- WSACleanup();
-}
-
// MS Transport Provider IOCTL to control
// reporting PORT_UNREACHABLE messages
// on UDP sockets via recv/WSARecv/etc.
@@ -354,6 +322,12 @@ QWindowsSockInit::~QWindowsSockInit()
# define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
#endif
+// inline on purpose
+inline uint QNativeSocketEnginePrivate::scopeIdFromString(const QString &scopeid)
+{
+ return scopeid.toUInt();
+}
+
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
@@ -439,9 +413,27 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
WS_ERROR_DEBUG(err);
}
}
+
+ // get the pointer to sendmsg and recvmsg
+ DWORD bytesReturned;
+ GUID recvmsgguid = WSAID_WSARECVMSG;
+ if (WSAIoctl(socketDescriptor, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &recvmsgguid, sizeof(recvmsgguid),
+ &recvmsg, sizeof(recvmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
+ recvmsg = 0;
+
+ GUID sendmsgguid = WSAID_WSASENDMSG;
+ if (WSAIoctl(socketDescriptor, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &sendmsgguid, sizeof(sendmsgguid),
+ &sendmsg, sizeof(sendmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
+ sendmsg = 0;
#endif
socketDescriptor = socket;
+ if (socket != INVALID_SOCKET) {
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
+ }
// Make the socket nonblocking.
if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
@@ -626,12 +618,10 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
#endif
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
+ qt_sockaddr aa;
QT_SOCKLEN_T sockAddrSize = 0;
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
if ((socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) && address.toIPv4Address()) {
//IPV6_V6ONLY option must be cleared to connect to a V4 mapped address
@@ -642,7 +632,7 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
}
forever {
- int connectResult = ::WSAConnect(socketDescriptor, sockAddrPtr, sockAddrSize, 0,0,0,0);
+ int connectResult = ::WSAConnect(socketDescriptor, &aa.a, sockAddrSize, 0,0,0,0);
if (connectResult == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
@@ -765,46 +755,36 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &a, quint16 port)
{
QHostAddress address = a;
- DWORD ipv6only = 0;
- switch (address.protocol()) {
- case QAbstractSocket::IPv6Protocol:
- if (address.toIPv6Address()[0] == 0xff) {
- // binding to a multicast address
- address = QHostAddress(QHostAddress::AnyIPv6);
- }
- //This is default in current windows versions, it may change in future so set it explicitly
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_6_0) {
- ipv6only = 1;
- ipv6only = ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
- }
- break;
- case QAbstractSocket::IPv4Protocol:
+ if (address.protocol() == QAbstractSocket::IPv4Protocol) {
if ((address.toIPv4Address() & 0xffff0000) == 0xefff0000) {
// binding to a multicast address
address = QHostAddress(QHostAddress::AnyIPv4);
}
- break;
- case QAbstractSocket::AnyIPProtocol:
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_6_0) {
- ipv6only = ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
- } else {
- address = QHostAddress(QHostAddress::AnyIPv4); //xp/WS2003 and earlier don't support dual stack, so bind to IPv4
- socketProtocol = QAbstractSocket::IPv4Protocol;
- }
- break;
- default:
- break;
}
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
+ qt_sockaddr aa;
QT_SOCKLEN_T sockAddrSize = 0;
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
+ if (aa.a.sa_family == AF_INET6) {
+ // The default may change in future, so set it explicitly
+ int ipv6only = 0;
+ if (address.protocol() == QAbstractSocket::IPv6Protocol)
+ ipv6only = 1;
+ ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
+ }
- int bindResult = ::bind(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
+ if (bindResult == SOCKET_ERROR && WSAGetLastError() == WSAEAFNOSUPPORT
+ && address.protocol() == QAbstractSocket::AnyIPProtocol) {
+ // retry with v4
+ aa.a4.sin_family = AF_INET;
+ aa.a4.sin_port = htons(port);
+ aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ sockAddrSize = sizeof(aa.a4);
+ bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
+ }
if (bindResult == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
@@ -1211,33 +1191,47 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
return ret;
}
+#ifdef Q_OS_WINCE
+// Windows CE has no support for sendmsg or recvmsg. We set it to null here to simplify the code below.
+static int (*const recvmsg)(...) = 0;
+static int (*const sendmsg)(...) = 0;
+#endif
-qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength,
- QHostAddress *address, quint16 *port)
+qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options)
{
- qint64 ret = 0;
-
+ union {
+ char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
+ WSACMSGHDR align; // only to ensure alignment
+ };
+ WSAMSG msg;
+ WSABUF buf;
qt_sockaddr aa;
+ char c;
+ memset(&msg, 0, sizeof(msg));
memset(&aa, 0, sizeof(aa));
- QT_SOCKLEN_T sz;
- sz = sizeof(aa);
- WSABUF buf;
- buf.buf = data;
- buf.len = maxLength;
-#if !defined(Q_OS_WINCE)
- buf.buf = data;
- buf.len = maxLength;
-#else
- char tmpChar;
- buf.buf = data ? data : &tmpChar;
- buf.len = maxLength;
-#endif
+ // we need to receive at least one byte, even if our user isn't interested in it
+ buf.buf = maxLength ? data : &c;
+ buf.len = maxLength ? maxLength : 1;
+ msg.lpBuffers = &buf;
+ msg.dwBufferCount = 1;
+ msg.name = reinterpret_cast<LPSOCKADDR>(&aa);
+ msg.namelen = sizeof(aa);
+ if (options & (QAbstractSocketEngine::WantDatagramHopLimit | QAbstractSocketEngine::WantDatagramDestination)) {
+ msg.Control.buf = cbuf;
+ msg.Control.len = sizeof(cbuf);
+ }
DWORD flags = 0;
DWORD bytesRead = 0;
- int wsaRet = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, &aa.a, &sz,0,0);
- if (wsaRet == SOCKET_ERROR) {
+ qint64 ret;
+
+ if (recvmsg)
+ ret = recvmsg(socketDescriptor, &msg, &bytesRead, 0,0);
+ else
+ ret = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, msg.name, &msg.namelen,0,0);
+ if (ret == SOCKET_ERROR) {
int err = WSAGetLastError();
if (err == WSAEMSGSIZE) {
// it is ok the buffer was to small if bytesRead is larger than
@@ -1247,12 +1241,44 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
WS_ERROR_DEBUG(err);
setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
ret = -1;
+ if (header)
+ header->clear();
}
} else {
ret = qint64(bytesRead);
+ if (options & QNativeSocketEngine::WantDatagramSender)
+ qt_socket_getPortAndAddress(socketDescriptor, &aa, &header->senderPort, &header->senderAddress);
}
- qt_socket_getPortAndAddress(socketDescriptor, &aa, port, address);
+ if (ret != -1 && recvmsg) {
+ // get the ancillary data
+ WSACMSGHDR *cmsgptr;
+ for (cmsgptr = WSA_CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
+ cmsgptr = WSA_CMSG_NXTHDR(&msg, cmsgptr)) {
+ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO
+ && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in6_pktinfo))) {
+ in6_pktinfo *info = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ QHostAddress target(reinterpret_cast<quint8 *>(&info->ipi6_addr));
+ if (info->ipi6_ifindex)
+ target.setScopeId(QString::number(info->ipi6_ifindex));
+ }
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_PKTINFO
+ && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in_pktinfo))) {
+ in_pktinfo *info = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ u_long addr;
+ WSANtohl(socketDescriptor, info->ipi_addr.s_addr, &addr);
+ QHostAddress target(addr);
+ if (info->ipi_ifindex)
+ target.setScopeId(QString::number(info->ipi_ifindex));
+ }
+
+ if (cmsgptr->cmsg_len == WSA_CMSG_LEN(sizeof(int))
+ && ((cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT)
+ || (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_TTL))) {
+ header->hopLimit = *reinterpret_cast<int *>(WSA_CMSG_DATA(cmsgptr));
+ }
+ }
+ }
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %li, %s, %i) == %li",
@@ -1266,27 +1292,94 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
- const QHostAddress &address, quint16 port)
+ const QIpPacketHeader &header)
{
- qint64 ret = -1;
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
-
+ union {
+ char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
+ WSACMSGHDR align; // ensures alignment
+ };
+ WSACMSGHDR *cmsgptr = &align;
+ WSAMSG msg;
WSABUF buf;
+ qt_sockaddr aa;
+
+ memset(&msg, 0, sizeof(msg));
+ memset(&aa, 0, sizeof(aa));
#if !defined(Q_OS_WINCE)
buf.buf = len ? (char*)data : 0;
#else
char tmp;
buf.buf = len ? (char*)data : &tmp;
#endif
+ msg.lpBuffers = &buf;
+ msg.dwBufferCount = 1;
+ msg.name = &aa.a;
buf.len = len;
+
+ setPortAndAddress(header.destinationPort, header.destinationAddress, &aa, &msg.namelen);
+
+ if (msg.namelen == sizeof(aa.a6)) {
+ // sending IPv6
+ if (header.hopLimit != -1) {
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_HOPLIMIT;
+ memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in6_pktinfo *data = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_PKTINFO;
+ data->ipi6_ifindex = header.ifindex;
+
+ Q_IPV6ADDR tmp = header.senderAddress.toIPv6Address();
+ memcpy(&data->ipi6_addr, &tmp, sizeof(tmp));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(*data)));
+ }
+ } else {
+ // sending IPv4
+ if (header.hopLimit != -1) {
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_TTL;
+ memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in_pktinfo *data = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_PKTINFO;
+ data->ipi_ifindex = header.ifindex;
+ WSAHtonl(socketDescriptor, header.senderAddress.toIPv4Address(), &data->ipi_addr.s_addr);
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(*data)));
+ }
+ }
+
+ if (msg.Control.len != 0)
+ msg.Control.buf = cbuf;
+
DWORD flags = 0;
DWORD bytesSent = 0;
- if (::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, sockAddrPtr, sockAddrSize, 0,0) == SOCKET_ERROR) {
+ qint64 ret = -1;
+ if (sendmsg) {
+ ret = sendmsg(socketDescriptor, &msg, flags, &bytesSent, 0,0);
+ } else {
+ ret = ::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, msg.name, msg.namelen, 0,0);
+ }
+ if (ret == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
switch (err) {
diff --git a/src/network/socket/qnativesocketengine_winrt.cpp b/src/network/socket/qnativesocketengine_winrt.cpp
index 5e58ee3895..025e3e5017 100644
--- a/src/network/socket/qnativesocketengine_winrt.cpp
+++ b/src/network/socket/qnativesocketengine_winrt.cpp
@@ -538,18 +538,19 @@ qint64 QNativeSocketEngine::write(const char *data, qint64 len)
return bytesWritten;
}
-qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr, quint16 *port)
+qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header,
+ PacketHeaderOptions)
{
Q_D(QNativeSocketEngine);
- if (d->socketType != QAbstractSocket::UdpSocket || d->pendingDatagrams.isEmpty())
+ if (d->socketType != QAbstractSocket::UdpSocket || d->pendingDatagrams.isEmpty()) {
+ if (header)
+ header->clear();
return -1;
+ }
WinRtDatagram datagram = d->pendingDatagrams.takeFirst();
- if (addr)
- *addr = datagram.address;
-
- if (port)
- *port = datagram.port;
+ if (header)
+ *header = datagram.header;
QByteArray readOrigin;
// Do not read the whole datagram. Put the rest of it back into the "queue"
@@ -564,7 +565,7 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress
return readOrigin.length();
}
-qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &addr, quint16 port)
+qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
Q_D(QNativeSocketEngine);
if (d->socketType != QAbstractSocket::UdpSocket)
@@ -576,13 +577,13 @@ qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QH
HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory);
RETURN_IF_FAILED("Could not obtain hostname factory", return -1);
- const QString addressString = addr.toString();
+ const QString addressString = header.destinationAddress.toString();
HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(addressString.utf16()));
hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost);
ComPtr<IAsyncOperation<IOutputStream *>> streamOperation;
ComPtr<IOutputStream> stream;
- const QString portString = QString::number(port);
+ const QString portString = QString::number(header.destinationPort);
HStringReference portRef(reinterpret_cast<LPCWSTR>(portString.utf16()));
hr = d->udpSocket()->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation);
RETURN_IF_FAILED("Failed to get output stream to socket", return -1);
@@ -794,6 +795,8 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
return false;
}
+ this->socketType = socketType;
+
// Make the socket nonblocking.
if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
setError(QAbstractSocket::UnsupportedSocketOperationError, NonBlockingInitFailedErrorString);
@@ -1228,11 +1231,11 @@ HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, I
remoteHost->get_CanonicalName(remoteHostString.GetAddressOf());
RETURN_OK_IF_FAILED("Could not obtain remote host's canonical name");
returnAddress.setAddress(qt_QStringFromHString(remoteHostString));
- datagram.address = returnAddress;
+ datagram.header.senderAddress = returnAddress;
HString remotePort;
hr = args->get_RemotePort(remotePort.GetAddressOf());
RETURN_OK_IF_FAILED("Could not obtain remote port");
- datagram.port = qt_QStringFromHString(remotePort).toInt();
+ datagram.header.senderPort = qt_QStringFromHString(remotePort).toInt();
ComPtr<IDataReader> reader;
hr = args->GetDataReader(&reader);
diff --git a/src/network/socket/qnativesocketengine_winrt_p.h b/src/network/socket/qnativesocketengine_winrt_p.h
index eb032bc977..4286ff6373 100644
--- a/src/network/socket/qnativesocketengine_winrt_p.h
+++ b/src/network/socket/qnativesocketengine_winrt_p.h
@@ -58,8 +58,7 @@ class QNativeSocketEnginePrivate;
struct WinRtDatagram {
QByteArray data;
- int port;
- QHostAddress address;
+ QIpPacketHeader header;
};
class Q_AUTOTEST_EXPORT QNativeSocketEngine : public QAbstractSocketEngine
@@ -97,10 +96,8 @@ public:
qint64 read(char *data, qint64 maxlen);
qint64 write(const char *data, qint64 len);
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0);
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port);
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader *, PacketHeaderOptions);
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header);
bool hasPendingDatagrams() const;
qint64 pendingDatagramSize() const;
diff --git a/src/network/socket/qnet_unix_p.h b/src/network/socket/qnet_unix_p.h
index 979afb82ba..9626c53711 100644
--- a/src/network/socket/qnet_unix_p.h
+++ b/src/network/socket/qnet_unix_p.h
@@ -77,15 +77,13 @@ static inline int qt_safe_socket(int domain, int type, int protocol, int flags =
Q_ASSERT((flags & ~O_NONBLOCK) == 0);
int fd;
-#if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+#ifdef QT_THREADSAFE_CLOEXEC
int newtype = type | SOCK_CLOEXEC;
if (flags & O_NONBLOCK)
newtype |= SOCK_NONBLOCK;
fd = ::socket(domain, newtype, protocol);
- if (fd != -1 || errno != EINVAL)
- return fd;
-#endif
-
+ return fd;
+#else
fd = ::socket(domain, type, protocol);
if (fd == -1)
return -1;
@@ -97,6 +95,7 @@ static inline int qt_safe_socket(int domain, int type, int protocol, int flags =
::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);
return fd;
+#endif
}
// Tru64 redefines accept -> _accept with _XOPEN_SOURCE_EXTENDED
@@ -105,16 +104,14 @@ static inline int qt_safe_accept(int s, struct sockaddr *addr, QT_SOCKLEN_T *add
Q_ASSERT((flags & ~O_NONBLOCK) == 0);
int fd;
-#if QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+#ifdef QT_THREADSAFE_CLOEXEC
// use accept4
int sockflags = SOCK_CLOEXEC;
if (flags & O_NONBLOCK)
sockflags |= SOCK_NONBLOCK;
fd = ::accept4(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen), sockflags);
- if (fd != -1 || !(errno == ENOSYS || errno == EINVAL))
- return fd;
-#endif
-
+ return fd;
+#else
fd = ::accept(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen));
if (fd == -1)
return -1;
@@ -126,6 +123,7 @@ static inline int qt_safe_accept(int s, struct sockaddr *addr, QT_SOCKLEN_T *add
::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);
return fd;
+#endif
}
// UnixWare 7 redefines listen -> _listen
@@ -175,8 +173,7 @@ static inline in_addr_t qt_safe_inet_addr(const char *cp)
#endif
}
-// VxWorks' headers do not specify any const modifiers
-static inline int qt_safe_sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *to, QT_SOCKLEN_T tolen)
+static inline int qt_safe_sendmsg(int sockfd, const struct msghdr *msg, int flags)
{
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
@@ -185,11 +182,15 @@ static inline int qt_safe_sendto(int sockfd, const void *buf, size_t len, int fl
#endif
int ret;
-#ifdef Q_OS_VXWORKS
- EINTR_LOOP(ret, ::sendto(sockfd, (char *) buf, len, flags, (struct sockaddr *) to, tolen));
-#else
- EINTR_LOOP(ret, ::sendto(sockfd, buf, len, flags, to, tolen));
-#endif
+ EINTR_LOOP(ret, ::sendmsg(sockfd, msg, flags));
+ return ret;
+}
+
+static inline int qt_safe_recvmsg(int sockfd, struct msghdr *msg, int flags)
+{
+ int ret;
+
+ EINTR_LOOP(ret, ::recvmsg(sockfd, msg, flags));
return ret;
}
diff --git a/src/network/socket/qsocks5socketengine.cpp b/src/network/socket/qsocks5socketengine.cpp
index a6eafd2601..26543883cc 100644
--- a/src/network/socket/qsocks5socketengine.cpp
+++ b/src/network/socket/qsocks5socketengine.cpp
@@ -1383,7 +1383,7 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
#endif
dummy.setProxy(QNetworkProxy::NoProxy);
if (!dummy.bind()
- || writeDatagram(0,0, d->data->controlSocket->localAddress(), dummy.localPort()) != 0
+ || writeDatagram(0,0, QIpPacketHeader(d->data->controlSocket->localAddress(), dummy.localPort())) != 0
|| !dummy.waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))
|| dummy.readDatagram(0,0, &d->localAddress, &d->localPort) != 0) {
QSOCKS5_DEBUG << "udp actual address and port lookup failed";
@@ -1555,7 +1555,7 @@ qint64 QSocks5SocketEngine::write(const char *data, qint64 len)
#ifndef QT_NO_UDPSOCKET
} else if (d->mode == QSocks5SocketEnginePrivate::UdpAssociateMode) {
// send to connected address
- return writeDatagram(data, len, d->peerAddress, d->peerPort);
+ return writeDatagram(data, len, QIpPacketHeader(d->peerAddress, d->peerPort));
#endif
}
//### set an error ???
@@ -1594,8 +1594,7 @@ bool QSocks5SocketEngine::setMulticastInterface(const QNetworkInterface &)
}
#endif // QT_NO_NETWORKINTERFACE
-qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr,
- quint16 *port)
+qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header, PacketHeaderOptions)
{
Q_D(QSocks5SocketEngine);
@@ -1607,15 +1606,12 @@ qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress
QSocks5RevivedDatagram datagram = d->udpData->pendingDatagrams.dequeue();
int copyLen = qMin<int>(maxlen, datagram.data.size());
memcpy(data, datagram.data.constData(), copyLen);
- if (addr)
- *addr = datagram.address;
- if (port)
- *port = datagram.port;
+ header->senderAddress = datagram.address;
+ header->senderPort = datagram.port;
return copyLen;
}
-qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &address,
- quint16 port)
+qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
Q_D(QSocks5SocketEngine);
@@ -1634,7 +1630,7 @@ qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QH
outBuf[0] = 0x00;
outBuf[1] = 0x00;
outBuf[2] = 0x00;
- if (!qt_socks5_set_host_address_and_port(address, port, &outBuf)) {
+ if (!qt_socks5_set_host_address_and_port(header.destinationAddress, header.destinationPort, &outBuf)) {
}
outBuf += QByteArray(data, len);
QSOCKS5_DEBUG << "sending" << dump(outBuf);
diff --git a/src/network/socket/qsocks5socketengine_p.h b/src/network/socket/qsocks5socketengine_p.h
index c97b0e89ce..de20e0ef0e 100644
--- a/src/network/socket/qsocks5socketengine_p.h
+++ b/src/network/socket/qsocks5socketengine_p.h
@@ -93,10 +93,9 @@ public:
bool setMulticastInterface(const QNetworkInterface &iface) Q_DECL_OVERRIDE;
#endif // QT_NO_NETWORKINTERFACE
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader * = 0,
+ PacketHeaderOptions = WantNone) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qtcpserver.cpp b/src/network/socket/qtcpserver.cpp
index b41d207947..914c14877e 100644
--- a/src/network/socket/qtcpserver.cpp
+++ b/src/network/socket/qtcpserver.cpp
@@ -160,6 +160,23 @@ QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint
/*! \internal
*/
+void QTcpServerPrivate::configureCreatedSocket()
+{
+#if defined(Q_OS_UNIX)
+ // Under Unix, we want to be able to bind to the port, even if a socket on
+ // the same address-port is in TIME_WAIT. Under Windows this is possible
+ // anyway -- furthermore, the meaning of reusable on Windows is different:
+ // it means that you can use the same address-port for multiple listening
+ // sockets.
+ // Don't abort though if we can't set that option. For example the socks
+ // engine doesn't support that option, but that shouldn't prevent us from
+ // trying to bind/listen.
+ socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
+#endif
+}
+
+/*! \internal
+*/
void QTcpServerPrivate::readNotification()
{
Q_Q(QTcpServer);
@@ -205,6 +222,9 @@ void QTcpServerPrivate::readNotification()
QTcpServer::QTcpServer(QObject *parent)
: QObject(*new QTcpServerPrivate, parent)
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::QTcpServer(%p)", parent);
+#endif
}
/*!
@@ -218,6 +238,9 @@ QTcpServer::QTcpServer(QObject *parent)
*/
QTcpServer::~QTcpServer()
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::~QTcpServer()");
+#endif
close();
}
@@ -226,6 +249,9 @@ QTcpServer::~QTcpServer()
QTcpServer::QTcpServer(QTcpServerPrivate &dd, QObject *parent)
: QObject(dd, parent)
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::QTcpServer(QTcpServerPrivate == %p, parent == %p)", &dd, parent);
+#endif
}
/*!
@@ -275,17 +301,7 @@ bool QTcpServer::listen(const QHostAddress &address, quint16 port)
if (addr.protocol() == QAbstractSocket::AnyIPProtocol && proto == QAbstractSocket::IPv4Protocol)
addr = QHostAddress::AnyIPv4;
-#if defined(Q_OS_UNIX)
- // Under Unix, we want to be able to bind to the port, even if a socket on
- // the same address-port is in TIME_WAIT. Under Windows this is possible
- // anyway -- furthermore, the meaning of reusable on Windows is different:
- // it means that you can use the same address-port for multiple listening
- // sockets.
- // Don't abort though if we can't set that option. For example the socks
- // engine doesn't support that option, but that shouldn't prevent us from
- // trying to bind/listen.
- d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
-#endif
+ d->configureCreatedSocket();
if (!d->socketEngine->bind(addr, port)) {
d->serverSocketError = d->socketEngine->error();
diff --git a/src/network/socket/qtcpserver.h b/src/network/socket/qtcpserver.h
index 8c7537a9b1..dd7b12c96a 100644
--- a/src/network/socket/qtcpserver.h
+++ b/src/network/socket/qtcpserver.h
@@ -51,7 +51,7 @@ class Q_NETWORK_EXPORT QTcpServer : public QObject
{
Q_OBJECT
public:
- explicit QTcpServer(QObject *parent = 0);
+ explicit QTcpServer(QObject *parent = Q_NULLPTR);
virtual ~QTcpServer();
bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
@@ -68,7 +68,7 @@ public:
qintptr socketDescriptor() const;
bool setSocketDescriptor(qintptr socketDescriptor);
- bool waitForNewConnection(int msec = 0, bool *timedOut = 0);
+ bool waitForNewConnection(int msec = 0, bool *timedOut = Q_NULLPTR);
virtual bool hasPendingConnections() const;
virtual QTcpSocket *nextPendingConnection();
@@ -87,7 +87,7 @@ protected:
virtual void incomingConnection(qintptr handle);
void addPendingConnection(QTcpSocket* socket);
- QTcpServer(QTcpServerPrivate &dd, QObject *parent = 0);
+ QTcpServer(QTcpServerPrivate &dd, QObject *parent = Q_NULLPTR);
Q_SIGNALS:
void newConnection();
diff --git a/src/network/socket/qtcpserver_p.h b/src/network/socket/qtcpserver_p.h
index 415a0e190a..47505e7e91 100644
--- a/src/network/socket/qtcpserver_p.h
+++ b/src/network/socket/qtcpserver_p.h
@@ -80,6 +80,8 @@ public:
QNetworkProxy resolveProxy(const QHostAddress &address, quint16 port);
#endif
+ virtual void configureCreatedSocket();
+
// from QAbstractSocketEngineReceiver
void readNotification() Q_DECL_OVERRIDE;
void closeNotification() Q_DECL_OVERRIDE { readNotification(); }
diff --git a/src/network/socket/qtcpsocket.cpp b/src/network/socket/qtcpsocket.cpp
index b6072b2909..13865fbc9c 100644
--- a/src/network/socket/qtcpsocket.cpp
+++ b/src/network/socket/qtcpsocket.cpp
@@ -103,4 +103,13 @@ QTcpSocket::QTcpSocket(QTcpSocketPrivate &dd, QObject *parent)
d_func()->isBuffered = true;
}
+/*!
+ \internal
+*/
+QTcpSocket::QTcpSocket(QAbstractSocket::SocketType socketType,
+ QTcpSocketPrivate &dd, QObject *parent)
+ : QAbstractSocket(socketType, dd, parent)
+{
+}
+
QT_END_NAMESPACE
diff --git a/src/network/socket/qtcpsocket.h b/src/network/socket/qtcpsocket.h
index 3449beeceb..8e3cb5946f 100644
--- a/src/network/socket/qtcpsocket.h
+++ b/src/network/socket/qtcpsocket.h
@@ -46,11 +46,13 @@ class Q_NETWORK_EXPORT QTcpSocket : public QAbstractSocket
{
Q_OBJECT
public:
- explicit QTcpSocket(QObject *parent = 0);
+ explicit QTcpSocket(QObject *parent = Q_NULLPTR);
virtual ~QTcpSocket();
protected:
- QTcpSocket(QTcpSocketPrivate &dd, QObject *parent = 0);
+ QTcpSocket(QTcpSocketPrivate &dd, QObject *parent = Q_NULLPTR);
+ QTcpSocket(QAbstractSocket::SocketType socketType, QTcpSocketPrivate &dd,
+ QObject *parent = Q_NULLPTR);
private:
Q_DISABLE_COPY(QTcpSocket)
diff --git a/src/network/socket/qudpsocket.cpp b/src/network/socket/qudpsocket.cpp
index 87686f94e1..f4e7d20b03 100644
--- a/src/network/socket/qudpsocket.cpp
+++ b/src/network/socket/qudpsocket.cpp
@@ -333,7 +333,7 @@ qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddre
if (state() == UnconnectedState)
bind();
- qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
+ qint64 sent = d->socketEngine->writeDatagram(data, size, QIpPacketHeader(address, port));
d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
if (sent >= 0) {
@@ -379,7 +379,20 @@ qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *addres
qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
#endif
QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
- qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
+
+ qint64 readBytes;
+ if (address || port) {
+ QIpPacketHeader header;
+ readBytes = d->socketEngine->readDatagram(data, maxSize, &header,
+ QAbstractSocketEngine::WantDatagramSender);
+ if (address)
+ *address = header.senderAddress;
+ if (port)
+ *port = header.senderPort;
+ } else {
+ readBytes = d->socketEngine->readDatagram(data, maxSize);
+ }
+
d_func()->socketEngine->setReadNotificationEnabled(true);
if (readBytes < 0) {
d->socketError = d->socketEngine->error();
diff --git a/src/network/socket/qudpsocket.h b/src/network/socket/qudpsocket.h
index fcf16fb345..e902984b4f 100644
--- a/src/network/socket/qudpsocket.h
+++ b/src/network/socket/qudpsocket.h
@@ -49,7 +49,7 @@ class Q_NETWORK_EXPORT QUdpSocket : public QAbstractSocket
{
Q_OBJECT
public:
- explicit QUdpSocket(QObject *parent = 0);
+ explicit QUdpSocket(QObject *parent = Q_NULLPTR);
virtual ~QUdpSocket();
#ifndef QT_NO_NETWORKINTERFACE
@@ -66,7 +66,7 @@ public:
bool hasPendingDatagrams() const;
qint64 pendingDatagramSize() const;
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host = 0, quint16 *port = 0);
+ qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host = Q_NULLPTR, quint16 *port = Q_NULLPTR);
qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port);
inline qint64 writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{ return writeDatagram(datagram.constData(), datagram.size(), host, port); }
diff --git a/src/network/ssl/qssl.cpp b/src/network/ssl/qssl.cpp
index 26381fcb8e..84aa9d7dca 100644
--- a/src/network/ssl/qssl.cpp
+++ b/src/network/ssl/qssl.cpp
@@ -166,6 +166,10 @@ Q_LOGGING_CATEGORY(lcSsl, "qt.network.ssl");
in ASN.1 format as returned by QSslConfiguration::sessionTicket(). Enabling
this feature adds memory overhead of approximately 1K per used session
ticket.
+ \value SslOptionDisableServerCipherPreference Disables selecting the cipher
+ chosen based on the servers preferences rather than the order ciphers were
+ sent by the client. This option is only relevant to server sockets, and is
+ only honored by the OpenSSL backend.
By default, SslOptionDisableEmptyFragments is turned on since this causes
problems with a large number of servers. SslOptionDisableLegacyRenegotiation
diff --git a/src/network/ssl/qssl.h b/src/network/ssl/qssl.h
index f56c36b219..03497ecf76 100644
--- a/src/network/ssl/qssl.h
+++ b/src/network/ssl/qssl.h
@@ -95,7 +95,8 @@ namespace QSsl {
SslOptionDisableServerNameIndication = 0x08,
SslOptionDisableLegacyRenegotiation = 0x10,
SslOptionDisableSessionSharing = 0x20,
- SslOptionDisableSessionPersistence = 0x40
+ SslOptionDisableSessionPersistence = 0x40,
+ SslOptionDisableServerCipherPreference = 0x80
};
Q_DECLARE_FLAGS(SslOptions, SslOption)
}
diff --git a/src/network/ssl/qsslcertificate.h b/src/network/ssl/qsslcertificate.h
index ef0767ae8f..af605b0629 100644
--- a/src/network/ssl/qsslcertificate.h
+++ b/src/network/ssl/qsslcertificate.h
@@ -83,9 +83,12 @@ public:
explicit QSslCertificate(const QByteArray &data = QByteArray(), QSsl::EncodingFormat format = QSsl::Pem);
QSslCertificate(const QSslCertificate &other);
~QSslCertificate();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCertificate &operator=(QSslCertificate &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCertificate &operator=(const QSslCertificate &other);
- inline void swap(QSslCertificate &other)
+ void swap(QSslCertificate &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslCertificate &other) const;
@@ -144,7 +147,7 @@ public:
static bool importPkcs12(QIODevice *device,
QSslKey *key, QSslCertificate *cert,
- QList<QSslCertificate> *caCertificates=0,
+ QList<QSslCertificate> *caCertificates = Q_NULLPTR,
const QByteArray &passPhrase=QByteArray());
Qt::HANDLE handle() const;
diff --git a/src/network/ssl/qsslcertificate_openssl.cpp b/src/network/ssl/qsslcertificate_openssl.cpp
index ad88ea5d56..3324587821 100644
--- a/src/network/ssl/qsslcertificate_openssl.cpp
+++ b/src/network/ssl/qsslcertificate_openssl.cpp
@@ -464,8 +464,9 @@ QList<QSslCertificateExtension> QSslCertificate::extensions() const
return result;
int count = q_X509_get_ext_count(d->x509);
+ result.reserve(count);
- for (int i=0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
X509_EXTENSION *ext = q_X509_get_ext(d->x509, i);
result << QSslCertificatePrivate::convertExtension(ext);
}
diff --git a/src/network/ssl/qsslcertificateextension.h b/src/network/ssl/qsslcertificateextension.h
index 7c958eff30..8dd0e8eb4b 100644
--- a/src/network/ssl/qsslcertificateextension.h
+++ b/src/network/ssl/qsslcertificateextension.h
@@ -51,11 +51,13 @@ class Q_NETWORK_EXPORT QSslCertificateExtension
public:
QSslCertificateExtension();
QSslCertificateExtension(const QSslCertificateExtension &other);
- ~QSslCertificateExtension();
-
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCertificateExtension &operator=(QSslCertificateExtension &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCertificateExtension &operator=(const QSslCertificateExtension &other);
+ ~QSslCertificateExtension();
- void swap(QSslCertificateExtension &other) { qSwap(d, other.d); }
+ void swap(QSslCertificateExtension &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString oid() const;
QString name() const;
diff --git a/src/network/ssl/qsslcipher.h b/src/network/ssl/qsslcipher.h
index dc65e32111..64122cdd53 100644
--- a/src/network/ssl/qsslcipher.h
+++ b/src/network/ssl/qsslcipher.h
@@ -52,10 +52,13 @@ public:
explicit QSslCipher(const QString &name);
QSslCipher(const QString &name, QSsl::SslProtocol protocol);
QSslCipher(const QSslCipher &other);
- ~QSslCipher();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCipher &operator=(QSslCipher &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCipher &operator=(const QSslCipher &other);
+ ~QSslCipher();
- inline void swap(QSslCipher &other)
+ void swap(QSslCipher &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslCipher &other) const;
diff --git a/src/network/ssl/qsslconfiguration.h b/src/network/ssl/qsslconfiguration.h
index 960aec60ce..2cbc31b032 100644
--- a/src/network/ssl/qsslconfiguration.h
+++ b/src/network/ssl/qsslconfiguration.h
@@ -71,9 +71,12 @@ public:
QSslConfiguration();
QSslConfiguration(const QSslConfiguration &other);
~QSslConfiguration();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslConfiguration &operator=(QSslConfiguration &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslConfiguration &operator=(const QSslConfiguration &other);
- inline void swap(QSslConfiguration &other)
+ void swap(QSslConfiguration &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslConfiguration &other) const;
diff --git a/src/network/ssl/qsslellipticcurve.h b/src/network/ssl/qsslellipticcurve.h
index a991881b93..5716e3447d 100644
--- a/src/network/ssl/qsslellipticcurve.h
+++ b/src/network/ssl/qsslellipticcurve.h
@@ -37,7 +37,10 @@
#include <QtCore/QtGlobal>
#include <QtCore/QString>
#include <QtCore/QMetaType>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/QHash>
+#endif
+#include <QtCore/qhashfunctions.h>
QT_BEGIN_NAMESPACE
diff --git a/src/network/ssl/qsslerror.h b/src/network/ssl/qsslerror.h
index b149f86d9e..bc2a2d5220 100644
--- a/src/network/ssl/qsslerror.h
+++ b/src/network/ssl/qsslerror.h
@@ -84,10 +84,13 @@ public:
QSslError(const QSslError &other);
- inline void swap(QSslError &other)
+ void swap(QSslError &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
~QSslError();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslError &operator=(QSslError &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslError &operator=(const QSslError &other);
bool operator==(const QSslError &other) const;
inline bool operator!=(const QSslError &other) const
diff --git a/src/network/ssl/qsslkey.h b/src/network/ssl/qsslkey.h
index b89069e4cb..d02c031015 100644
--- a/src/network/ssl/qsslkey.h
+++ b/src/network/ssl/qsslkey.h
@@ -64,10 +64,13 @@ public:
const QByteArray &passPhrase = QByteArray());
explicit QSslKey(Qt::HANDLE handle, QSsl::KeyType type = QSsl::PrivateKey);
QSslKey(const QSslKey &other);
- ~QSslKey();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslKey &operator=(QSslKey &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslKey &operator=(const QSslKey &other);
+ ~QSslKey();
- inline void swap(QSslKey &other) { qSwap(d, other.d); }
+ void swap(QSslKey &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isNull() const;
void clear();
diff --git a/src/network/ssl/qsslkey_openssl.cpp b/src/network/ssl/qsslkey_openssl.cpp
index 33cb81ce71..a90c9411b7 100644
--- a/src/network/ssl/qsslkey_openssl.cpp
+++ b/src/network/ssl/qsslkey_openssl.cpp
@@ -265,4 +265,53 @@ Qt::HANDLE QSslKeyPrivate::handle() const
}
}
+static QByteArray doCrypt(QSslKeyPrivate::Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv, int enc)
+{
+ EVP_CIPHER_CTX ctx;
+ const EVP_CIPHER* type = 0;
+ int i = 0, len = 0;
+
+ switch (cipher) {
+ case QSslKeyPrivate::DesCbc:
+ type = q_EVP_des_cbc();
+ break;
+ case QSslKeyPrivate::DesEde3Cbc:
+ type = q_EVP_des_ede3_cbc();
+ break;
+ case QSslKeyPrivate::Rc2Cbc:
+ type = q_EVP_rc2_cbc();
+ break;
+ }
+
+ QByteArray output;
+ output.resize(data.size() + EVP_MAX_BLOCK_LENGTH);
+ q_EVP_CIPHER_CTX_init(&ctx);
+ q_EVP_CipherInit(&ctx, type, NULL, NULL, enc);
+ q_EVP_CIPHER_CTX_set_key_length(&ctx, key.size());
+ if (cipher == QSslKeyPrivate::Rc2Cbc)
+ q_EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_SET_RC2_KEY_BITS, 8 * key.size(), NULL);
+ q_EVP_CipherInit(&ctx, NULL,
+ reinterpret_cast<const unsigned char *>(key.constData()),
+ reinterpret_cast<const unsigned char *>(iv.constData()), enc);
+ q_EVP_CipherUpdate(&ctx,
+ reinterpret_cast<unsigned char *>(output.data()), &len,
+ reinterpret_cast<const unsigned char *>(data.constData()), data.size());
+ q_EVP_CipherFinal(&ctx,
+ reinterpret_cast<unsigned char *>(output.data()) + len, &i);
+ len += i;
+ q_EVP_CIPHER_CTX_cleanup(&ctx);
+
+ return output.left(len);
+}
+
+QByteArray QSslKeyPrivate::decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, 0);
+}
+
+QByteArray QSslKeyPrivate::encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, 1);
+}
+
QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslkey_p.h b/src/network/ssl/qsslkey_p.h
index be981bb484..fea0e30bbc 100644
--- a/src/network/ssl/qsslkey_p.h
+++ b/src/network/ssl/qsslkey_p.h
@@ -90,6 +90,16 @@ public:
bool isNull;
QSsl::KeyType type;
QSsl::KeyAlgorithm algorithm;
+
+ enum Cipher {
+ DesCbc,
+ DesEde3Cbc,
+ Rc2Cbc
+ };
+
+ Q_AUTOTEST_EXPORT static QByteArray decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+ Q_AUTOTEST_EXPORT static QByteArray encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+
#ifndef QT_NO_OPENSSL
union {
EVP_PKEY *opaque;
@@ -100,15 +110,6 @@ public:
#endif
};
#else
- enum Cipher {
- DesCbc,
- DesEde3Cbc,
- Rc2Cbc
- };
-
- Q_AUTOTEST_EXPORT static QByteArray decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
- Q_AUTOTEST_EXPORT static QByteArray encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
-
Qt::HANDLE opaque;
QByteArray derData;
int keyLength;
diff --git a/src/network/ssl/qsslpresharedkeyauthenticator.h b/src/network/ssl/qsslpresharedkeyauthenticator.h
index 159b16d563..34e5d6fd50 100644
--- a/src/network/ssl/qsslpresharedkeyauthenticator.h
+++ b/src/network/ssl/qsslpresharedkeyauthenticator.h
@@ -52,14 +52,10 @@ public:
Q_NETWORK_EXPORT QSslPreSharedKeyAuthenticator &operator=(const QSslPreSharedKeyAuthenticator &authenticator);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QSslPreSharedKeyAuthenticator &operator=(QSslPreSharedKeyAuthenticator &&authenticator)
- { d.swap(authenticator.d); return *this; }
+ QSslPreSharedKeyAuthenticator &operator=(QSslPreSharedKeyAuthenticator &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- void swap(QSslPreSharedKeyAuthenticator &authenticator)
- {
- d.swap(authenticator.d);
- }
+ void swap(QSslPreSharedKeyAuthenticator &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
Q_NETWORK_EXPORT QByteArray identityHint() const;
diff --git a/src/network/ssl/qsslsocket.h b/src/network/ssl/qsslsocket.h
index 4124f5b7e5..22856c6ea9 100644
--- a/src/network/ssl/qsslsocket.h
+++ b/src/network/ssl/qsslsocket.h
@@ -72,7 +72,7 @@ public:
AutoVerifyPeer
};
- explicit QSslSocket(QObject *parent = 0);
+ explicit QSslSocket(QObject *parent = Q_NULLPTR);
~QSslSocket();
void resume() Q_DECL_OVERRIDE; // to continue after proxy authentication required, SSL errors etc.
diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp
index a21317d0f2..8e1d0c13b1 100644
--- a/src/network/ssl/qsslsocket_openssl.cpp
+++ b/src/network/ssl/qsslsocket_openssl.cpp
@@ -344,6 +344,9 @@ long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, Q
options |= SSL_OP_NO_COMPRESSION;
#endif
+ if (!(sslOptions & QSsl::SslOptionDisableServerCipherPreference))
+ options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
+
return options;
}
@@ -488,30 +491,8 @@ bool QSslSocketPrivate::ensureLibraryLoaded()
// Initialize OpenSSL's random seed.
if (!q_RAND_status()) {
- struct {
- int msec;
- int sec;
- void *stack;
- } randomish;
-
- int attempts = 500;
- do {
- if (attempts < 500) {
-#ifdef Q_OS_UNIX
- struct timespec ts = {0, 33333333};
- nanosleep(&ts, 0);
-#else
- Sleep(3);
-#endif
- randomish.msec = attempts;
- }
- randomish.stack = (void *)&randomish;
- randomish.msec = QTime::currentTime().msec();
- randomish.sec = QTime::currentTime().second();
- q_RAND_seed((const char *)&randomish, sizeof(randomish));
- } while (!q_RAND_status() && --attempts);
- if (!attempts)
- return false;
+ qWarning("Random number generator not seeded, disabling SSL support");
+ return false;
}
}
return true;
@@ -659,8 +640,10 @@ void QSslSocketPrivate::resetDefaultCiphers()
if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
if (!ciph.isNull()) {
- // Unconditionally exclude ADH ciphers since they offer no MITM protection
- if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
+ // Unconditionally exclude ADH and AECDH ciphers since they offer no MITM protection
+ if (!ciph.name().toLower().startsWith(QLatin1String("adh")) &&
+ !ciph.name().toLower().startsWith(QLatin1String("exp-adh")) &&
+ !ciph.name().toLower().startsWith(QLatin1String("aecdh")))
ciphers << ciph;
if (ciph.usedBits() >= 128)
defaultCiphers << ciph;
@@ -685,6 +668,7 @@ void QSslSocketPrivate::resetDefaultEllipticCurves()
QVarLengthArray<EC_builtin_curve> builtinCurves(static_cast<int>(curveCount));
if (q_EC_get_builtin_curves(builtinCurves.data(), curveCount) == curveCount) {
+ curves.reserve(int(curveCount));
for (size_t i = 0; i < curveCount; ++i) {
QSslEllipticCurve curve;
curve.id = builtinCurves[int(i)].nid;
@@ -1213,7 +1197,9 @@ bool QSslSocketBackendPrivate::startHandshake()
}
// Translate errors from the error list into QSslErrors.
- for (int i = 0; i < errorList.size(); ++i) {
+ const int numErrors = errorList.size();
+ errors.reserve(errors.size() + numErrors);
+ for (int i = 0; i < numErrors; ++i) {
const QPair<int, int> &errorAndDepth = errorList.at(i);
int err = errorAndDepth.first;
int depth = errorAndDepth.second;
@@ -1782,7 +1768,9 @@ QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &
}
// Translate errors from the error list into QSslErrors.
- for (int i = 0; i < errorList.size(); ++i) {
+ const int numErrors = errorList.size();
+ errors.reserve(errors.size() + numErrors);
+ for (int i = 0; i < numErrors; ++i) {
const QPair<int, int> &errorAndDepth = errorList.at(i);
int err = errorAndDepth.first;
int depth = errorAndDepth.second;
diff --git a/src/network/ssl/qsslsocket_openssl_symbols.cpp b/src/network/ssl/qsslsocket_openssl_symbols.cpp
index e2700df3cc..e7829bac90 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols.cpp
+++ b/src/network/ssl/qsslsocket_openssl_symbols.cpp
@@ -119,10 +119,13 @@ void qsslSocketUnresolvedSymbolWarning(const char *functionName)
qCWarning(lcSsl, "QSslSocket: cannot call unresolved function %s", functionName);
}
+#ifndef QT_NO_LIBRARY
void qsslSocketCannotResolveSymbolWarning(const char *functionName)
{
qCWarning(lcSsl, "QSslSocket: cannot resolve %s", functionName);
}
+#endif
+
}
#endif // QT_LINKED_OPENSSL
@@ -156,7 +159,16 @@ DEFINEFUNC3(X509 *, d2i_X509, X509 **a, a, const unsigned char **b, b, long c, c
DEFINEFUNC2(char *, ERR_error_string, unsigned long a, a, char *b, b, return 0, return)
DEFINEFUNC(unsigned long, ERR_get_error, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(void, ERR_free_strings, void, DUMMYARG, return, DUMMYARG)
+DEFINEFUNC(void, EVP_CIPHER_CTX_cleanup, EVP_CIPHER_CTX *a, a, return, DUMMYARG)
+DEFINEFUNC(void, EVP_CIPHER_CTX_init, EVP_CIPHER_CTX *a, a, return, DUMMYARG)
+DEFINEFUNC4(int, EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX *ctx, ctx, int type, type, int arg, arg, void *ptr, ptr, return 0, return);
+DEFINEFUNC2(int, EVP_CIPHER_CTX_set_key_length, EVP_CIPHER_CTX *ctx, ctx, int keylen, keylen, return 0, return)
+DEFINEFUNC5(int, EVP_CipherInit, EVP_CIPHER_CTX *ctx, ctx, const EVP_CIPHER *type, type, const unsigned char *key, key, const unsigned char *iv, iv, int enc, enc, return 0, return);
+DEFINEFUNC5(int, EVP_CipherUpdate, EVP_CIPHER_CTX *ctx, ctx, unsigned char *out, out, int *outl, outl, const unsigned char *in, in, int inl, inl, return 0, return);
+DEFINEFUNC3(int, EVP_CipherFinal, EVP_CIPHER_CTX *ctx, ctx, unsigned char *out, out, int *outl, outl, return 0, return);
+DEFINEFUNC(const EVP_CIPHER *, EVP_des_cbc, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(const EVP_CIPHER *, EVP_des_ede3_cbc, DUMMYARG, DUMMYARG, return 0, return)
+DEFINEFUNC(const EVP_CIPHER *, EVP_rc2_cbc, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC3(int, EVP_PKEY_assign, EVP_PKEY *a, a, int b, b, char *c, c, return -1, return)
DEFINEFUNC2(int, EVP_PKEY_set1_RSA, EVP_PKEY *a, a, RSA *b, b, return -1, return)
DEFINEFUNC2(int, EVP_PKEY_set1_DSA, EVP_PKEY *a, a, DSA *b, b, return -1, return)
@@ -309,13 +321,17 @@ DEFINEFUNC(const SSL_METHOD *, TLSv1_1_server_method, DUMMYARG, DUMMYARG, return
DEFINEFUNC(const SSL_METHOD *, TLSv1_2_server_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
#else
+#ifndef OPENSSL_NO_SSL2
DEFINEFUNC(SSL_METHOD *, SSLv2_client_method, DUMMYARG, DUMMYARG, return 0, return)
+#endif
#ifndef OPENSSL_NO_SSL3_METHOD
DEFINEFUNC(SSL_METHOD *, SSLv3_client_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
DEFINEFUNC(SSL_METHOD *, SSLv23_client_method, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(SSL_METHOD *, TLSv1_client_method, DUMMYARG, DUMMYARG, return 0, return)
+#ifndef OPENSSL_NO_SSL2
DEFINEFUNC(SSL_METHOD *, SSLv2_server_method, DUMMYARG, DUMMYARG, return 0, return)
+#endif
#ifndef OPENSSL_NO_SSL3_METHOD
DEFINEFUNC(SSL_METHOD *, SSLv3_server_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
@@ -436,39 +452,41 @@ bool q_resolveOpenSslSymbols()
#else
# ifdef Q_OS_UNIX
-static bool libGreaterThan(const QString &lhs, const QString &rhs)
+struct NumericallyLess
{
- QStringList lhsparts = lhs.split(QLatin1Char('.'));
- QStringList rhsparts = rhs.split(QLatin1Char('.'));
- Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);
-
- for (int i = 1; i < rhsparts.count(); ++i) {
- if (lhsparts.count() <= i)
- // left hand side is shorter, so it's less than rhs
- return false;
-
+ typedef bool result_type;
+ result_type operator()(const QStringRef &lhs, const QStringRef &rhs) const
+ {
bool ok = false;
int b = 0;
- int a = lhsparts.at(i).toInt(&ok);
+ int a = lhs.toInt(&ok);
if (ok)
- b = rhsparts.at(i).toInt(&ok);
+ b = rhs.toInt(&ok);
if (ok) {
// both toInt succeeded
- if (a == b)
- continue;
- return a > b;
+ return a < b;
} else {
// compare as strings;
- if (lhsparts.at(i) == rhsparts.at(i))
- continue;
- return lhsparts.at(i) > rhsparts.at(i);
+ return lhs < rhs;
}
}
+};
- // they compared strictly equally so far
- // lhs cannot be less than rhs
- return true;
-}
+struct LibGreaterThan
+{
+ typedef bool result_type;
+ result_type operator()(const QString &lhs, const QString &rhs) const
+ {
+ const QVector<QStringRef> lhsparts = lhs.splitRef(QLatin1Char('.'));
+ const QVector<QStringRef> rhsparts = rhs.splitRef(QLatin1Char('.'));
+ Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);
+
+ // note: checking rhs < lhs, the same as lhs > rhs
+ return std::lexicographical_compare(rhsparts.begin() + 1, rhsparts.end(),
+ lhsparts.begin() + 1, lhsparts.end(),
+ NumericallyLess());
+ }
+};
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
static int dlIterateCallback(struct dl_phdr_info *info, size_t size, void *data)
@@ -522,39 +540,33 @@ static QStringList libraryPathList()
return paths;
}
-
-static QStringList findAllLibSsl()
+Q_NEVER_INLINE
+static QStringList findAllLibs(QLatin1String filter)
{
QStringList paths = libraryPathList();
- QStringList foundSsls;
+ QStringList found;
+ const QStringList filters((QString(filter)));
foreach (const QString &path, paths) {
QDir dir(path);
- QStringList entryList = dir.entryList(QStringList() << QLatin1String("libssl.*"), QDir::Files);
+ QStringList entryList = dir.entryList(filters, QDir::Files);
- std::sort(entryList.begin(), entryList.end(), libGreaterThan);
+ std::sort(entryList.begin(), entryList.end(), LibGreaterThan());
foreach (const QString &entry, entryList)
- foundSsls << path + QLatin1Char('/') + entry;
+ found << path + QLatin1Char('/') + entry;
}
- return foundSsls;
+ return found;
}
-static QStringList findAllLibCrypto()
+static QStringList findAllLibSsl()
{
- QStringList paths = libraryPathList();
-
- QStringList foundCryptos;
- foreach (const QString &path, paths) {
- QDir dir(path);
- QStringList entryList = dir.entryList(QStringList() << QLatin1String("libcrypto.*"), QDir::Files);
-
- std::sort(entryList.begin(), entryList.end(), libGreaterThan);
- foreach (const QString &entry, entryList)
- foundCryptos << path + QLatin1Char('/') + entry;
- }
+ return findAllLibs(QLatin1String("libssl.*"));
+}
- return foundCryptos;
+static QStringList findAllLibCrypto()
+{
+ return findAllLibs(QLatin1String("libcrypto.*"));
}
# endif
@@ -759,7 +771,16 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(ERR_error_string)
RESOLVEFUNC(ERR_get_error)
RESOLVEFUNC(ERR_free_strings)
+ RESOLVEFUNC(EVP_CIPHER_CTX_cleanup)
+ RESOLVEFUNC(EVP_CIPHER_CTX_init)
+ RESOLVEFUNC(EVP_CIPHER_CTX_ctrl)
+ RESOLVEFUNC(EVP_CIPHER_CTX_set_key_length)
+ RESOLVEFUNC(EVP_CipherInit)
+ RESOLVEFUNC(EVP_CipherUpdate)
+ RESOLVEFUNC(EVP_CipherFinal)
+ RESOLVEFUNC(EVP_des_cbc)
RESOLVEFUNC(EVP_des_ede3_cbc)
+ RESOLVEFUNC(EVP_rc2_cbc)
RESOLVEFUNC(EVP_PKEY_assign)
RESOLVEFUNC(EVP_PKEY_set1_RSA)
RESOLVEFUNC(EVP_PKEY_set1_DSA)
diff --git a/src/network/ssl/qsslsocket_openssl_symbols_p.h b/src/network/ssl/qsslsocket_openssl_symbols_p.h
index 626c049629..7f87f11b7c 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols_p.h
+++ b/src/network/ssl/qsslsocket_openssl_symbols_p.h
@@ -235,7 +235,16 @@ X509 *q_d2i_X509(X509 **a, const unsigned char **b, long c);
char *q_ERR_error_string(unsigned long a, char *b);
unsigned long q_ERR_get_error();
void q_ERR_free_strings();
+void q_EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a);
+void q_EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a);
+int q_EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
+int q_EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
+int q_EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, const unsigned char *key, const unsigned char *iv, int enc);
+int q_EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl);
+int q_EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
+const EVP_CIPHER *q_EVP_des_cbc();
const EVP_CIPHER *q_EVP_des_ede3_cbc();
+const EVP_CIPHER *q_EVP_rc2_cbc();
int q_EVP_PKEY_assign(EVP_PKEY *a, int b, char *c);
Q_AUTOTEST_EXPORT int q_EVP_PKEY_set1_RSA(EVP_PKEY *a, RSA *b);
int q_EVP_PKEY_set1_DSA(EVP_PKEY *a, DSA *b);
@@ -363,27 +372,43 @@ typedef unsigned int (*q_psk_client_callback_t)(SSL *ssl, const char *hint, char
void q_SSL_set_psk_client_callback(SSL *ssl, q_psk_client_callback_t callback);
#endif // OPENSSL_NO_PSK
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+#ifndef OPENSSL_NO_SSL2
const SSL_METHOD *q_SSLv2_client_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *q_SSLv3_client_method();
+#endif
const SSL_METHOD *q_SSLv23_client_method();
const SSL_METHOD *q_TLSv1_client_method();
const SSL_METHOD *q_TLSv1_1_client_method();
const SSL_METHOD *q_TLSv1_2_client_method();
+#ifndef OPENSSL_NO_SSL2
const SSL_METHOD *q_SSLv2_server_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *q_SSLv3_server_method();
+#endif
const SSL_METHOD *q_SSLv23_server_method();
const SSL_METHOD *q_TLSv1_server_method();
const SSL_METHOD *q_TLSv1_1_server_method();
const SSL_METHOD *q_TLSv1_2_server_method();
#else
+#ifndef OPENSSL_NO_SSL2
SSL_METHOD *q_SSLv2_client_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
SSL_METHOD *q_SSLv3_client_method();
+#endif
SSL_METHOD *q_SSLv23_client_method();
SSL_METHOD *q_TLSv1_client_method();
SSL_METHOD *q_TLSv1_1_client_method();
SSL_METHOD *q_TLSv1_2_client_method();
+#ifndef OPENSSL_NO_SSL2
SSL_METHOD *q_SSLv2_server_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
SSL_METHOD *q_SSLv3_server_method();
+#endif
SSL_METHOD *q_SSLv23_server_method();
SSL_METHOD *q_TLSv1_server_method();
SSL_METHOD *q_TLSv1_1_server_method();
diff --git a/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp b/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp
index 1551d1c7cb..6bf152b83d 100644
--- a/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp
+++ b/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp
@@ -63,6 +63,7 @@ QGLCustomShaderStage::~QGLCustomShaderStage()
d->m_manager->removeCustomStage();
d->m_manager->sharedShaders->cleanupCustomStage(this);
}
+ delete d_ptr;
}
void QGLCustomShaderStage::setUniformsDirty()
diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp
index eae9a4c228..d84b59efff 100644
--- a/src/opengl/qgl.cpp
+++ b/src/opengl/qgl.cpp
@@ -4357,8 +4357,7 @@ void QGLWidget::resizeOverlayGL(int, int)
{
}
-/*!
- Handles the event \a e passed as a parameter.
+/*!\reimp
*/
bool QGLWidget::event(QEvent *e)
{
@@ -4500,7 +4499,7 @@ QImage QGLWidget::grabFrameBuffer(bool withAlpha)
{
makeCurrent();
QImage res;
- qreal pixelRatio = devicePixelRatio();
+ qreal pixelRatio = devicePixelRatioF();
int w = pixelRatio * width();
int h = pixelRatio * height();
if (format().rgba())
@@ -4913,7 +4912,7 @@ void QGLWidget::renderText(double x, double y, double z, const QString &str, con
GLdouble win_x = 0, win_y = 0, win_z = 0;
qgluProject(x, y, z, &model[0], &proj[0], &view[0],
&win_x, &win_y, &win_z);
- const int dpr = d->glcx->device()->devicePixelRatio();
+ const int dpr = d->glcx->device()->devicePixelRatioF();
win_x /= dpr;
win_y /= dpr;
win_y = height - win_y; // y is inverted
diff --git a/src/opengl/qgl.h b/src/opengl/qgl.h
index 8c55cffbb3..99abdd2ad6 100644
--- a/src/opengl/qgl.h
+++ b/src/opengl/qgl.h
@@ -235,7 +235,7 @@ public:
QGLContext(const QGLFormat& format);
virtual ~QGLContext();
- virtual bool create(const QGLContext* shareContext = 0);
+ virtual bool create(const QGLContext* shareContext = Q_NULLPTR);
bool isValid() const;
bool isSharing() const;
void reset();
@@ -303,7 +303,7 @@ public:
QOpenGLContext *contextHandle() const;
protected:
- virtual bool chooseContext(const QGLContext* shareContext = 0);
+ virtual bool chooseContext(const QGLContext* shareContext = Q_NULLPTR);
bool deviceIsPixmap() const;
bool windowCreated() const;
@@ -356,12 +356,12 @@ class Q_OPENGL_EXPORT QGLWidget : public QWidget
Q_OBJECT
Q_DECLARE_PRIVATE(QGLWidget)
public:
- explicit QGLWidget(QWidget* parent=0,
- const QGLWidget* shareWidget = 0, Qt::WindowFlags f=0);
- explicit QGLWidget(QGLContext *context, QWidget* parent=0,
- const QGLWidget* shareWidget = 0, Qt::WindowFlags f=0);
- explicit QGLWidget(const QGLFormat& format, QWidget* parent=0,
- const QGLWidget* shareWidget = 0, Qt::WindowFlags f=0);
+ explicit QGLWidget(QWidget* parent=Q_NULLPTR,
+ const QGLWidget* shareWidget = Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags());
+ explicit QGLWidget(QGLContext *context, QWidget* parent=Q_NULLPTR,
+ const QGLWidget* shareWidget = Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags());
+ explicit QGLWidget(const QGLFormat& format, QWidget* parent=Q_NULLPTR,
+ const QGLWidget* shareWidget = Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags());
~QGLWidget();
void qglColor(const QColor& c) const;
@@ -380,7 +380,7 @@ public:
void setFormat(const QGLFormat& format);
QGLContext* context() const;
- void setContext(QGLContext* context, const QGLContext* shareContext = 0,
+ void setContext(QGLContext* context, const QGLContext* shareContext = Q_NULLPTR,
bool deleteOldContext = true);
QPixmap renderPixmap(int w = 0, int h = 0, bool useContext = false);
@@ -442,9 +442,9 @@ protected:
QGLWidget(QGLWidgetPrivate &dd,
const QGLFormat &format = QGLFormat(),
- QWidget *parent = 0,
- const QGLWidget* shareWidget = 0,
- Qt::WindowFlags f = 0);
+ QWidget *parent = Q_NULLPTR,
+ const QGLWidget* shareWidget = Q_NULLPTR,
+ Qt::WindowFlags f = Qt::WindowFlags());
private:
Q_DISABLE_COPY(QGLWidget)
diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h
index fd7f2b328c..ad5386d8bc 100644
--- a/src/opengl/qgl_p.h
+++ b/src/opengl/qgl_p.h
@@ -50,7 +50,7 @@
#include "QtCore/qmap.h"
#include "QtCore/qthread.h"
#include "QtCore/qthreadstorage.h"
-#include "QtCore/qhash.h"
+#include "QtCore/qhashfunctions.h"
#include "QtCore/qatomic.h"
#include "QtWidgets/private/qwidget_p.h"
#include "QtGui/private/qopenglcontext_p.h"
diff --git a/src/opengl/qglbuffer.h b/src/opengl/qglbuffer.h
index e424ff2b5c..67b1a68072 100644
--- a/src/opengl/qglbuffer.h
+++ b/src/opengl/qglbuffer.h
@@ -103,7 +103,7 @@ public:
void write(int offset, const void *data, int count);
void allocate(const void *data, int count);
- inline void allocate(int count) { allocate(0, count); }
+ inline void allocate(int count) { allocate(Q_NULLPTR, count); }
void *map(QGLBuffer::Access access);
bool unmap();
diff --git a/src/opengl/qglcolormap.h b/src/opengl/qglcolormap.h
index f16f94c7f5..53031fd98f 100644
--- a/src/opengl/qglcolormap.h
+++ b/src/opengl/qglcolormap.h
@@ -63,7 +63,7 @@ public:
int findNearest(QRgb color) const;
protected:
- Qt::HANDLE handle() { return d ? d->cmapHandle : 0; }
+ Qt::HANDLE handle() { return d ? d->cmapHandle : Q_NULLPTR; }
void setHandle(Qt::HANDLE ahandle) { d->cmapHandle = ahandle; }
private:
diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp
index 3479fccf58..b636f90918 100644
--- a/src/opengl/qglframebufferobject.cpp
+++ b/src/opengl/qglframebufferobject.cpp
@@ -1285,6 +1285,9 @@ int QGLFramebufferObject::metric(PaintDeviceMetric metric) const
case QPaintDevice::PdmDevicePixelRatio:
return 1;
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ return 1 * QPaintDevice::devicePixelRatioFScale();
+
default:
qWarning("QGLFramebufferObject::metric(), Unhandled metric type: %d.\n", metric);
break;
diff --git a/src/opengl/qglfunctions.h b/src/opengl/qglfunctions.h
index 80b8596a20..ddb7b89d98 100644
--- a/src/opengl/qglfunctions.h
+++ b/src/opengl/qglfunctions.h
@@ -70,7 +70,7 @@ public:
QGLFunctions::OpenGLFeatures openGLFeatures() const;
bool hasOpenGLFeature(QGLFunctions::OpenGLFeature feature) const;
- void initializeGLFunctions(const QGLContext *context = 0);
+ void initializeGLFunctions(const QGLContext *context = Q_NULLPTR);
void glActiveTexture(GLenum texture);
void glAttachShader(GLuint program, GLuint shader);
@@ -172,14 +172,14 @@ public:
private:
QGLFunctionsPrivate *d_ptr;
- static bool isInitialized(const QGLFunctionsPrivate *d) { return d != 0; }
+ static bool isInitialized(const QGLFunctionsPrivate *d) { return d != Q_NULLPTR; }
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QGLFunctions::OpenGLFeatures)
struct QGLFunctionsPrivate
{
- QGLFunctionsPrivate(const QGLContext *context = 0);
+ QGLFunctionsPrivate(const QGLContext *context = Q_NULLPTR);
QOpenGLFunctions *funcs;
};
diff --git a/src/opengl/qglpaintdevice.cpp b/src/opengl/qglpaintdevice.cpp
index 89cf01d8ec..b5df45bcc8 100644
--- a/src/opengl/qglpaintdevice.cpp
+++ b/src/opengl/qglpaintdevice.cpp
@@ -62,6 +62,8 @@ int QGLPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const
}
case PdmDevicePixelRatio:
return 1;
+ case PdmDevicePixelRatioScaled:
+ return 1 * QPaintDevice::devicePixelRatioFScale();
default:
qWarning("QGLPaintDevice::metric() - metric %d not known", metric);
return 0;
diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp
index 42fa3415ef..943ec7ad30 100644
--- a/src/opengl/qglpixelbuffer.cpp
+++ b/src/opengl/qglpixelbuffer.cpp
@@ -458,6 +458,9 @@ int QGLPixelBuffer::metric(PaintDeviceMetric metric) const
case QPaintDevice::PdmDevicePixelRatio:
return 1;
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ return QPaintDevice::devicePixelRatioFScale();
+
default:
qWarning("QGLPixelBuffer::metric(), Unhandled metric type: %d\n", metric);
break;
diff --git a/src/opengl/qglpixelbuffer.h b/src/opengl/qglpixelbuffer.h
index 0f0110da96..2aad76b002 100644
--- a/src/opengl/qglpixelbuffer.h
+++ b/src/opengl/qglpixelbuffer.h
@@ -47,9 +47,9 @@ class Q_OPENGL_EXPORT QGLPixelBuffer : public QPaintDevice
Q_DECLARE_PRIVATE(QGLPixelBuffer)
public:
QGLPixelBuffer(const QSize &size, const QGLFormat &format = QGLFormat::defaultFormat(),
- QGLWidget *shareWidget = 0);
+ QGLWidget *shareWidget = Q_NULLPTR);
QGLPixelBuffer(int width, int height, const QGLFormat &format = QGLFormat::defaultFormat(),
- QGLWidget *shareWidget = 0);
+ QGLWidget *shareWidget = Q_NULLPTR);
virtual ~QGLPixelBuffer();
bool isValid() const;
diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp
index c0122eb59f..abd4a59fb8 100644
--- a/src/opengl/qglshaderprogram.cpp
+++ b/src/opengl/qglshaderprogram.cpp
@@ -1706,7 +1706,7 @@ void QGLShaderProgram::setAttributeBuffer
Q_UNUSED(d);
if (location != -1) {
d->glfuncs->glVertexAttribPointer(location, tupleSize, type, GL_TRUE, stride,
- reinterpret_cast<const void *>(offset));
+ reinterpret_cast<const void *>(qintptr(offset)));
}
}
diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h
index 5d9fe22b0b..8f2c74fae7 100644
--- a/src/opengl/qglshaderprogram.h
+++ b/src/opengl/qglshaderprogram.h
@@ -58,8 +58,8 @@ public:
};
Q_DECLARE_FLAGS(ShaderType, ShaderTypeBit)
- explicit QGLShader(QGLShader::ShaderType type, QObject *parent = 0);
- QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent = 0);
+ explicit QGLShader(QGLShader::ShaderType type, QObject *parent = Q_NULLPTR);
+ QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent = Q_NULLPTR);
virtual ~QGLShader();
QGLShader::ShaderType shaderType() const;
@@ -76,7 +76,7 @@ public:
GLuint shaderId() const;
- static bool hasOpenGLShaders(ShaderType type, const QGLContext *context = 0);
+ static bool hasOpenGLShaders(ShaderType type, const QGLContext *context = Q_NULLPTR);
private:
friend class QGLShaderProgram;
@@ -94,8 +94,8 @@ class Q_OPENGL_EXPORT QGLShaderProgram : public QObject
{
Q_OBJECT
public:
- explicit QGLShaderProgram(QObject *parent = 0);
- explicit QGLShaderProgram(const QGLContext *context, QObject *parent = 0);
+ explicit QGLShaderProgram(QObject *parent = Q_NULLPTR);
+ explicit QGLShaderProgram(const QGLContext *context, QObject *parent = Q_NULLPTR);
virtual ~QGLShaderProgram();
bool addShader(QGLShader *shader);
@@ -280,7 +280,7 @@ public:
void setUniformValueArray(const char *name, const QMatrix4x3 *values, int count);
void setUniformValueArray(const char *name, const QMatrix4x4 *values, int count);
- static bool hasOpenGLShaderPrograms(const QGLContext *context = 0);
+ static bool hasOpenGLShaderPrograms(const QGLContext *context = Q_NULLPTR);
private Q_SLOTS:
void shaderDestroyed();
diff --git a/src/platformheaders/cocoafunctions/cocoafunctions.pri b/src/platformheaders/cocoafunctions/cocoafunctions.pri
new file mode 100644
index 0000000000..3987523f9a
--- /dev/null
+++ b/src/platformheaders/cocoafunctions/cocoafunctions.pri
@@ -0,0 +1 @@
+HEADERS += $$PWD/qcocoawindowfunctions.h
diff --git a/src/plugins/platforms/kms/qkmscursor.h b/src/platformheaders/cocoafunctions/qcocoawindowfunctions.h
index 9aadf407c0..997f440e65 100644
--- a/src/plugins/platforms/kms/qkmscursor.h
+++ b/src/platformheaders/cocoafunctions/qcocoawindowfunctions.h
@@ -31,36 +31,27 @@
**
****************************************************************************/
-#ifndef QKMSCURSOR_H
-#define QKMSCURSOR_H
+#ifndef QXCBWINDOWFUNCTIONS_H
+#define QXCBWINDOWFUNCTIONS_H
-#include <qpa/qplatformcursor.h>
-
-struct gbm_device;
-struct gbm_bo;
+#include <QtPlatformHeaders/QPlatformHeaderHelper>
QT_BEGIN_NAMESPACE
-class QKmsScreen;
+class QWindow;
-class QKmsCursor : public QPlatformCursor
-{
+class QCocoaWindowFunctions {
public:
- QKmsCursor(QKmsScreen *screen);
- ~QKmsCursor();
-
- void pointerEvent(const QMouseEvent &event) Q_DECL_OVERRIDE;
- void changeCursor(QCursor *windowCursor, QWindow *window) Q_DECL_OVERRIDE;
+ typedef QPoint (*BottomLeftClippedByNSWindowOffset)(QWindow *window);
+ static const QByteArray bottomLeftClippedByNSWindowOffsetIdentifier() { return QByteArrayLiteral("CocoaBottomLeftClippedByNSWindowOffset"); }
-private:
- QKmsScreen *m_screen;
- gbm_device *m_graphicsBufferManager;
- gbm_bo *m_cursorBufferObject;
- QPlatformCursorImage *m_cursorImage;
- bool m_moved;
- QSize m_cursorSize;
+ static QPoint bottomLeftClippedByNSWindowOffset(QWindow *window)
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<QPoint, BottomLeftClippedByNSWindowOffset>(bottomLeftClippedByNSWindowOffsetIdentifier(),window);
+ }
};
+
QT_END_NAMESPACE
-#endif // QKMSCURSOR_H
+#endif // QXCBWINDOWFUNCTIONS_H
diff --git a/src/platformheaders/cocoafunctions/qcocoawindowfunctions.qdoc b/src/platformheaders/cocoafunctions/qcocoawindowfunctions.qdoc
new file mode 100644
index 0000000000..e95f92edb5
--- /dev/null
+++ b/src/platformheaders/cocoafunctions/qcocoawindowfunctions.qdoc
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:FDL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Free Documentation License Usage
+** 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. Please review the following information to ensure
+** the GNU Free Documentation License version 1.3 requirements
+** will be met: http://www.gnu.org/copyleft/fdl.html.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+/*!
+ \class QCocoaWindowFunctions
+ \inmodule QtPlatformHeaders
+
+ \brief The QCocoaWindowFunctions class is an inline class containing
+ miscellaneous functionality for NSWindow and NSView window specific functionality.
+
+ \note There is no binary compatibility guarantee for this class,
+ meaning that an application using it is only guaranteed to work with the Qt
+ version it was developed against.
+*/
+
+/*!
+ \typedef QCocoaWindowFunctions::BottomLeftClippedByNSWindowOffset
+
+ This is the typedef for the function returned by QGuiApplication::platformFunction when passed clippedByNSWindowIdentifier.
+*/
+
+/*!
+ \fn QByteArray QCocoaWindowFunctions::bottomLeftClippedByNSWindowOffsetIdentifier()
+
+ This function returnes the bytearray that can be used to query
+ QGuiApplication::platformFunction to retrieve the BottomLeftClippedByNSWindowOffset function.
+*/
+
+/*!
+ \fn QPoint QCocoaWindowFunctions::bottomLeftClippedByNSWindowOffset(QWindow *window)
+
+ This is a convenience function that can be used directly instead of resolving the function pointer.
+ \a window will be relayed to the function retrieved by QGuiApplication
+*/
diff --git a/src/platformheaders/helper/helper.pri b/src/platformheaders/helper/helper.pri
new file mode 100644
index 0000000000..2f6e766214
--- /dev/null
+++ b/src/platformheaders/helper/helper.pri
@@ -0,0 +1,2 @@
+HEADERS += \
+ $$PWD/qplatformheaderhelper.h
diff --git a/src/platformheaders/helper/qplatformheaderhelper.h b/src/platformheaders/helper/qplatformheaderhelper.h
new file mode 100644
index 0000000000..52302dbfba
--- /dev/null
+++ b/src/platformheaders/helper/qplatformheaderhelper.h
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QPLATFORMHEADERHELPER_H
+#define QPLATFORMHEADERHELPER_H
+
+#include <QtCore/QByteArray>
+#include <QtGui/QGuiApplication>
+
+#if 0
+#pragma qt_class(QPlatformHeaderHelper)
+#endif
+
+QT_BEGIN_NAMESPACE
+
+namespace QPlatformHeaderHelper {
+
+template<typename ReturnT, typename FunctionT>
+ReturnT callPlatformFunction(const QByteArray &functionName)
+{
+ FunctionT func = reinterpret_cast<FunctionT>(QGuiApplication::platformFunction(functionName));
+ return func ? func() : ReturnT();
+}
+
+template<typename ReturnT, typename FunctionT, typename Arg1>
+ReturnT callPlatformFunction(const QByteArray &functionName, Arg1 a1)
+{
+ FunctionT func = reinterpret_cast<FunctionT>(QGuiApplication::platformFunction(functionName));
+ return func ? func(a1) : ReturnT();
+}
+
+template<typename ReturnT, typename FunctionT, typename Arg1, typename Arg2>
+ReturnT callPlatformFunction(const QByteArray &functionName, Arg1 a1, Arg2 a2)
+{
+ FunctionT func = reinterpret_cast<FunctionT>(QGuiApplication::platformFunction(functionName));
+ return func ? func(a1, a2) : ReturnT();
+}
+
+template<typename ReturnT, typename FunctionT, typename Arg1, typename Arg2, typename Arg3>
+ReturnT callPlatformFunction(const QByteArray &functionName, Arg1 a1, Arg2 a2, Arg3 a3)
+{
+ FunctionT func = reinterpret_cast<FunctionT>(QGuiApplication::platformFunction(functionName));
+ return func ? func(a1, a2, a3) : ReturnT();
+}
+
+template<typename ReturnT, typename FunctionT, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
+ReturnT callPlatformFunction(const QByteArray &functionName, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4)
+{
+ FunctionT func = reinterpret_cast<FunctionT>(QGuiApplication::platformFunction(functionName));
+ return func ? func(a1, a2, a3, a4) : ReturnT();
+}
+
+}
+
+QT_END_NAMESPACE
+
+#endif /*QPLATFORMHEADERHELPER_H*/
diff --git a/src/platformheaders/platformheaders.pro b/src/platformheaders/platformheaders.pro
index 5e875f7d2d..1ced4f1c95 100644
--- a/src/platformheaders/platformheaders.pro
+++ b/src/platformheaders/platformheaders.pro
@@ -7,6 +7,8 @@ include(nativecontexts/nativecontexts.pri)
include(xcbfunctions/xcbfunctions.pri)
include(eglfsfunctions/eglfsfunctions.pri)
include(windowsfunctions/windowsfunctions.pri)
+include(helper/helper.pri)
+include(cocoafunctions/cocoafunctions.pri)
QMAKE_DOCS = $$PWD/doc/qtplatformheaders.qdocconf
diff --git a/src/plugins/platforms/kms/qkmswindow.h b/src/platformheaders/xcbfunctions/qxcbintegrationfunctions.h
index aec6d55b5d..66bfb72307 100644
--- a/src/plugins/platforms/kms/qkmswindow.h
+++ b/src/platformheaders/xcbfunctions/qxcbintegrationfunctions.h
@@ -31,27 +31,24 @@
**
****************************************************************************/
-#ifndef QKMSWINDOW_H
-#define QKMSWINDOW_H
+#ifndef QXCBINTEGRATIONFUNCTIONS_H
+#define QXCBINTEGRATIONFUNCTIONS_H
-#include <qpa/qplatformwindow.h>
+#include <QtPlatformHeaders/QPlatformHeaderHelper>
QT_BEGIN_NAMESPACE
-class QKmsWindow : public QPlatformWindow
+class QXcbIntegrationFunctions
{
- Q_DECLARE_PRIVATE(QPlatformWindow)
-
public:
- QKmsWindow(QWindow *window);
-
- void setGeometry(const QRect &rect) Q_DECL_OVERRIDE;
- QSurfaceFormat format() const Q_DECL_OVERRIDE;
-
-private:
- QPlatformScreen *m_screen;
+ typedef bool (*XEmbedSystemTrayVisualHasAlphaChannel)();
+ static const QByteArray xEmbedSystemTrayVisualHasAlphaChannelIdentifier() { return QByteArrayLiteral("XcbXEmbedSystemTrayVisualHasAlphaChannel"); }
+ static bool xEmbedSystemTrayVisualHasAlphaChannel()
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<bool, XEmbedSystemTrayVisualHasAlphaChannel>(xEmbedSystemTrayVisualHasAlphaChannelIdentifier());
+ }
};
QT_END_NAMESPACE
-#endif // QKMSWINDOW_H
+#endif /*QXCBINTEGRATIONFUNCTIONS_H*/
diff --git a/src/platformheaders/xcbfunctions/qxcbwindowfunctions.h b/src/platformheaders/xcbfunctions/qxcbwindowfunctions.h
index ae05cf52a9..0db2e2a09d 100644
--- a/src/platformheaders/xcbfunctions/qxcbwindowfunctions.h
+++ b/src/platformheaders/xcbfunctions/qxcbwindowfunctions.h
@@ -34,8 +34,7 @@
#ifndef QXCBWINDOWFUNCTIONS_H
#define QXCBWINDOWFUNCTIONS_H
-#include <QtCore/QByteArray>
-#include <QtGui/QGuiApplication>
+#include <QtPlatformHeaders/QPlatformHeaderHelper>
QT_BEGIN_NAMESPACE
@@ -65,12 +64,37 @@ public:
typedef void (*SetWmWindowType)(QWindow *window, QXcbWindowFunctions::WmWindowTypes windowType);
static const QByteArray setWmWindowTypeIdentifier() { return QByteArrayLiteral("XcbSetWmWindowType"); }
-
static void setWmWindowType(QWindow *window, WmWindowType type)
{
- SetWmWindowType func = reinterpret_cast<SetWmWindowType>(QGuiApplication::platformFunction(setWmWindowTypeIdentifier()));
- if (func)
- func(window, type);
+ return QPlatformHeaderHelper::callPlatformFunction<void, SetWmWindowType, QWindow *, WmWindowType>(setWmWindowTypeIdentifier(), window, type);
+ }
+
+ typedef void (*SetWmWindowIconText)(QWindow *window, const QString &text);
+ static const QByteArray setWmWindowIconTextIdentifier() { return QByteArrayLiteral("XcbSetWmWindowIconText"); }
+ static void setWmWindowIconText(QWindow *window, const QString &text)
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<void, SetWmWindowIconText, QWindow *, const QString &>(setWmWindowIconTextIdentifier(), window, text);
+ }
+
+ typedef void (*SetParentRelativeBackPixmap)(const QWindow *window);
+ static const QByteArray setParentRelativeBackPixmapIdentifier() { return QByteArrayLiteral("XcbSetParentRelativeBackPixmap"); }
+ static void setParentRelativeBackPixmap(const QWindow *window)
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<void, SetParentRelativeBackPixmap, const QWindow *>(setParentRelativeBackPixmapIdentifier(), window);
+ }
+
+ typedef bool (*RequestSystemTrayWindowDock)(const QWindow *window);
+ static const QByteArray requestSystemTrayWindowDockIdentifier() { return QByteArrayLiteral("XcbRequestSystemTrayWindowDockIdentifier"); }
+ static bool requestSystemTrayWindowDock(const QWindow *window)
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<bool, RequestSystemTrayWindowDock, const QWindow *>(requestSystemTrayWindowDockIdentifier(), window);
+ }
+
+ typedef QRect (*SystemTrayWindowGlobalGeometry)(const QWindow *window);
+ static const QByteArray systemTrayWindowGlobalGeometryIdentifier() { return QByteArrayLiteral("XcbSystemTrayWindowGlobalGeometryIdentifier"); }
+ static QRect systemTrayWindowGlobalGeometry(const QWindow *window)
+ {
+ return QPlatformHeaderHelper::callPlatformFunction<QRect, SystemTrayWindowGlobalGeometry, const QWindow *>(systemTrayWindowGlobalGeometryIdentifier(), window);
}
typedef uint (*VisualId)(QWindow *window);
diff --git a/src/platformheaders/xcbfunctions/qxcbwindowfunctions.qdoc b/src/platformheaders/xcbfunctions/qxcbwindowfunctions.qdoc
index ab6ef9089f..b26255553f 100644
--- a/src/platformheaders/xcbfunctions/qxcbwindowfunctions.qdoc
+++ b/src/platformheaders/xcbfunctions/qxcbwindowfunctions.qdoc
@@ -65,7 +65,9 @@
/*!
\typedef QXcbWindowFunctions::SetWmWindowType
- This is the typedef for the function returned by QGuiApplication::platformFunction when passed setWmWindowTypeIdentifier.
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by setWmWindowTypeIdentifier().
*/
/*!
@@ -78,7 +80,132 @@
/*!
\fn void QXcbWindowFunctions::setWmWindowType(QWindow *window, WmWindowType type)
- This is a convenience function that can be used directly instead of resolving the function pointer.
- \a window and \a type will be relayed to the function retrieved by QGuiApplication
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window and \a type will be
+ relayed to the function retrieved by QGuiApplication.
+*/
+
+/*!
+ \typedef QXcbWindowFunctions::SetWmWindowIconText
+
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by setWmWindowIconTextIdentifier().
+*/
+
+/*!
+ \fn const QByteArray QXcbWindowFunctions::setWmWindowIconTextIdentifier()
+
+ This function returns the byte array that can be used to query
+ QGuiApplication::platformFunction to retrieve the SetWmWindowIconText function.
+*/
+
+/*!
+ \fn void QXcbWindowFunctions::setWmWindowIconText(QWindow *window, const QString& text)
+
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window and \a text will be
+ relayed to the function retrieved by QGuiApplication.
+*/
+
+/*!
+ \typedef QXcbWindowFunctions::SetParentRelativeBackPixmap
+
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by setParentRelativeBackPixmapIdentifier().
+*/
+
+/*!
+ \fn const QByteArray QXcbWindowFunctions::setParentRelativeBackPixmapIdentifier()
+
+ This function returns the byte array that can be used to query
+ QGuiApplication::platformFunction to retrieve the SetParentRelativeBackPixmap function.
+*/
+
+/*!
+ \fn void QXcbWindowFunctions::setParentRelativeBackPixmap(const QWindow *window)
+
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window will be
+ relayed to the function retrieved by QGuiApplication.
+*/
+
+/*!
+ \typedef QXcbWindowFunctions::RequestSystemTrayWindowDock
+
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by requestSystemTrayWindowDockIdentifier().
+*/
+
+/*!
+ \fn const QByteArray QXcbWindowFunctions::requestSystemTrayWindowDockIdentifier()
+
+ This function returns the byte array that can be used to query
+ QGuiApplication::platformFunction to retrieve the RequestSystemTrayWindowDock function.
+*/
+
+/*!
+ \fn bool QXcbWindowFunctions::requestSystemTrayWindowDock(const QWindow *window)
+
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window will be
+ relayed to the function retrieved by QGuiApplication.
+
+ Returns the boolean result of calling the function or false if the
+ function was not found.
+*/
+
+/*!
+ \typedef QXcbWindowFunctions::SystemTrayWindowGlobalGeometry
+
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by systemTrayWindowGlobalGeometryIdentifier().
+*/
+
+/*!
+ \fn const QByteArray QXcbWindowFunctions::systemTrayWindowGlobalGeometryIdentifier()
+
+ This function returns the byte array that can be used to query
+ QGuiApplication::platformFunction to retrieve the SystemTrayWindowGlobalGeometry function.
+*/
+
+/*!
+ \fn QRect QXcbWindowFunctions::systemTrayWindowGlobalGeometry(const QWindow *window)
+
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window will be
+ relayed to the function retrieved by QGuiApplication.
+
+ Returns the QRect result of calling the function or an empty
+ QRect if the function was not found.
+*/
+
+/*!
+ \typedef QXcbWindowFunctions::VisualId
+
+ This is the typedef for the function returned by
+ QGuiApplication::platformFunction when passed the
+ value returned by visualIdIdentifier().
+*/
+
+/*!
+ \fn const QByteArray QXcbWindowFunctions::visualIdIdentifier()
+
+ This function returns the byte array that can be used to query
+ QGuiApplication::platformFunction to retrieve the VisualId function.
+*/
+
+/*!
+ \fn uint QXcbWindowFunctions::visualId(QWindow *window)
+
+ This is a convenience function that can be used directly instead
+ of resolving the function pointer. \a window will be
+ relayed to the function retrieved by QGuiApplication.
+
+ Returns the unsigned integer result of calling the function or
+ UINT_MAX if the function was not found.
*/
diff --git a/src/platformheaders/xcbfunctions/xcbfunctions.pri b/src/platformheaders/xcbfunctions/xcbfunctions.pri
index 8844913cd1..7f611d80bd 100644
--- a/src/platformheaders/xcbfunctions/xcbfunctions.pri
+++ b/src/platformheaders/xcbfunctions/xcbfunctions.pri
@@ -1 +1,3 @@
-HEADERS += $$PWD/qxcbwindowfunctions.h
+HEADERS += \
+ $$PWD/qxcbwindowfunctions.h \
+ $$PWD/qxcbintegrationfunctions.h
diff --git a/src/platformsupport/dbusmenu/qdbusmenutypes.cpp b/src/platformsupport/dbusmenu/qdbusmenutypes.cpp
index 73957eacfe..94df0f53dd 100644
--- a/src/platformsupport/dbusmenu/qdbusmenutypes.cpp
+++ b/src/platformsupport/dbusmenu/qdbusmenutypes.cpp
@@ -208,6 +208,7 @@ QDBusMenuItemList QDBusMenuItem::items(const QList<int> &ids, const QStringList
Q_UNUSED(propertyNames)
QDBusMenuItemList ret;
QList<const QDBusPlatformMenuItem *> items = QDBusPlatformMenuItem::byIds(ids);
+ ret.reserve(items.size());
Q_FOREACH (const QDBusPlatformMenuItem *item, items)
ret << QDBusMenuItem(item);
return ret;
diff --git a/src/platformsupport/dbusmenu/qdbusmenutypes_p.h b/src/platformsupport/dbusmenu/qdbusmenutypes_p.h
index 28d16b32d5..8dae75281c 100644
--- a/src/platformsupport/dbusmenu/qdbusmenutypes_p.h
+++ b/src/platformsupport/dbusmenu/qdbusmenutypes_p.h
@@ -46,7 +46,7 @@ QT_BEGIN_NAMESPACE
class QDBusPlatformMenu;
class QDBusPlatformMenuItem;
class QDBusMenuItem;
-typedef QList<QDBusMenuItem> QDBusMenuItemList;
+typedef QVector<QDBusMenuItem> QDBusMenuItemList;
class QDBusMenuItem
{
@@ -61,6 +61,7 @@ public:
int m_id;
QVariantMap m_properties;
};
+Q_DECLARE_TYPEINFO(QDBusMenuItem, Q_MOVABLE_TYPE);
const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItem &item);
const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItem &item);
@@ -72,11 +73,12 @@ public:
int id;
QStringList properties;
};
+Q_DECLARE_TYPEINFO(QDBusMenuItemKeys, Q_MOVABLE_TYPE);
const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItemKeys &keys);
const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItemKeys &keys);
-typedef QList<QDBusMenuItemKeys> QDBusMenuItemKeysList;
+typedef QVector<QDBusMenuItemKeys> QDBusMenuItemKeysList;
class QDBusMenuLayoutItem
{
@@ -87,13 +89,14 @@ public:
int m_id;
QVariantMap m_properties;
- QList<QDBusMenuLayoutItem> m_children;
+ QVector<QDBusMenuLayoutItem> m_children;
};
+Q_DECLARE_TYPEINFO(QDBusMenuLayoutItem, Q_MOVABLE_TYPE);
const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuLayoutItem &);
const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuLayoutItem &item);
-typedef QList<QDBusMenuLayoutItem> QDBusMenuLayoutItemList;
+typedef QVector<QDBusMenuLayoutItem> QDBusMenuLayoutItemList;
class QDBusMenuEvent
{
@@ -103,11 +106,13 @@ public:
QDBusVariant m_data;
uint m_timestamp;
};
+Q_DECLARE_TYPEINFO(QDBusMenuEvent, Q_MOVABLE_TYPE); // QDBusVariant is movable, even though it cannot
+ // be marked as such until Qt 6.
const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuEvent &ev);
const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuEvent &ev);
-typedef QList<QDBusMenuEvent> QDBusMenuEventList;
+typedef QVector<QDBusMenuEvent> QDBusMenuEventList;
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const QDBusMenuItem &item);
diff --git a/src/platformsupport/dbustray/qdbustraytypes.cpp b/src/platformsupport/dbustray/qdbustraytypes.cpp
index 7b7d31b7c3..83b5d5da3f 100644
--- a/src/platformsupport/dbustray/qdbustraytypes.cpp
+++ b/src/platformsupport/dbustray/qdbustraytypes.cpp
@@ -82,6 +82,8 @@ QXdgDBusImageVector iconToQXdgDBusImageVector(const QIcon &icon)
sizes.append(QSize(IconNormalSmallSize * dpr, IconNormalSmallSize * dpr));
if (!hasMediumIcon)
sizes.append(QSize(IconNormalMediumSize * dpr, IconNormalMediumSize * dpr));
+
+ ret.reserve(sizes.size());
foreach (QSize size, sizes) {
// Protocol specifies ARGB32 format in network byte order
QImage im = icon.pixmap(size).toImage().convertToFormat(QImage::Format_ARGB32);
diff --git a/src/platformsupport/dbustray/qdbustraytypes_p.h b/src/platformsupport/dbustray/qdbustraytypes_p.h
index 4e7ae70a96..e6f200362f 100644
--- a/src/platformsupport/dbustray/qdbustraytypes_p.h
+++ b/src/platformsupport/dbustray/qdbustraytypes_p.h
@@ -56,6 +56,7 @@ struct QXdgDBusImageStruct
int height;
QByteArray data;
};
+Q_DECLARE_TYPEINFO(QXdgDBusImageStruct, Q_MOVABLE_TYPE);
typedef QVector<QXdgDBusImageStruct> QXdgDBusImageVector;
@@ -69,6 +70,7 @@ struct QXdgDBusToolTipStruct
QString title;
QString subTitle;
};
+Q_DECLARE_TYPEINFO(QXdgDBusToolTipStruct, Q_MOVABLE_TYPE);
const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusImageStruct &icon);
const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusImageStruct &icon);
diff --git a/src/platformsupport/eglconvenience/eglconvenience.pri b/src/platformsupport/eglconvenience/eglconvenience.pri
index d102203d5e..457efd68fb 100644
--- a/src/platformsupport/eglconvenience/eglconvenience.pri
+++ b/src/platformsupport/eglconvenience/eglconvenience.pri
@@ -1,29 +1,16 @@
contains(QT_CONFIG,egl) {
HEADERS += \
- $$PWD/qeglconvenience_p.h \
- $$PWD/qeglpbuffer_p.h
+ $$PWD/qeglconvenience_p.h
SOURCES += \
- $$PWD/qeglconvenience.cpp \
- $$PWD/qeglpbuffer.cpp
+ $$PWD/qeglconvenience.cpp
contains(QT_CONFIG,opengl) {
- HEADERS += $$PWD/qeglplatformcontext_p.h
- SOURCES += $$PWD/qeglplatformcontext.cpp
+ HEADERS += $$PWD/qeglplatformcontext_p.h \
+ $$PWD/qeglpbuffer_p.h
- unix {
- HEADERS += \
- $$PWD/qeglplatformcursor_p.h \
- $$PWD/qeglplatformwindow_p.h \
- $$PWD/qeglplatformscreen_p.h \
- $$PWD/qeglplatformintegration_p.h
-
- SOURCES += \
- $$PWD/qeglplatformcursor.cpp \
- $$PWD/qeglplatformwindow.cpp \
- $$PWD/qeglplatformscreen.cpp \
- $$PWD/qeglplatformintegration.cpp
- }
+ SOURCES += $$PWD/qeglplatformcontext.cpp \
+ $$PWD/qeglpbuffer.cpp
}
# Avoid X11 header collision
diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp b/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
index 5bee29afef..905f7695bb 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
+++ b/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
@@ -154,6 +154,7 @@ void QEGLPlatformContext::init(const QSurfaceFormat &format, QPlatformOpenGLCont
}
}
contextAttrs.append(EGL_NONE);
+ m_contextAttrs = contextAttrs;
switch (m_format.renderableType()) {
case QSurfaceFormat::OpenVG:
@@ -244,6 +245,8 @@ void QEGLPlatformContext::initialize()
updateFormatFromGL();
}
+// Base implementation for pbuffers. Subclasses will handle the specialized cases for
+// platforms without pbuffers.
EGLSurface QEGLPlatformContext::createTemporaryOffscreenSurface()
{
// Make the context current to ensure the GL version query works. This needs a surface too.
@@ -283,10 +286,18 @@ void QEGLPlatformContext::updateFormatFromGL()
// avoid creating an extra pbuffer surface which is apparently troublesome with some
// drivers (Mesa) when certain attributes are present (multisampling).
EGLSurface tempSurface = EGL_NO_SURFACE;
+ EGLContext tempContext = EGL_NO_CONTEXT;
if (!q_hasEglExtension(m_eglDisplay, "EGL_KHR_surfaceless_context"))
tempSurface = createTemporaryOffscreenSurface();
- if (eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, m_eglContext)) {
+ EGLBoolean ok = eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, m_eglContext);
+ if (!ok) {
+ EGLConfig config = q_configFromGLFormat(m_eglDisplay, m_format, false, EGL_PBUFFER_BIT);
+ tempContext = eglCreateContext(m_eglDisplay, config, 0, m_contextAttrs.constData());
+ if (tempContext != EGL_NO_CONTEXT)
+ ok = eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, tempContext);
+ }
+ if (ok) {
if (m_format.renderableType() == QSurfaceFormat::OpenGL
|| m_format.renderableType() == QSurfaceFormat::OpenGLES) {
const GLubyte *s = glGetString(GL_VERSION);
@@ -324,10 +335,12 @@ void QEGLPlatformContext::updateFormatFromGL()
}
eglMakeCurrent(prevDisplay, prevSurfaceDraw, prevSurfaceRead, prevContext);
} else {
- qWarning("QEGLPlatformContext: Failed to make temporary surface current, format not updated");
+ qWarning("QEGLPlatformContext: Failed to make temporary surface current, format not updated (%x)", eglGetError());
}
if (tempSurface != EGL_NO_SURFACE)
destroyTemporaryOffscreenSurface(tempSurface);
+ if (tempContext != EGL_NO_CONTEXT)
+ eglDestroyContext(m_eglDisplay, tempContext);
#endif // QT_NO_OPENGL
}
diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h b/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
index 50c264e1dc..2ab7ad28d0 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
+++ b/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
@@ -94,6 +94,7 @@ private:
bool m_swapIntervalEnvChecked;
int m_swapIntervalFromEnv;
bool m_ownsContext;
+ QVector<EGLint> m_contextAttrs;
};
QT_END_NAMESPACE
diff --git a/src/platformsupport/eglconvenience/qeglplatformintegration.cpp b/src/platformsupport/eglconvenience/qeglplatformintegration.cpp
deleted file mode 100644
index 1868ff1665..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformintegration.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui/QWindow>
-#include <QtGui/QOpenGLContext>
-#include <QtGui/QOffscreenSurface>
-#include <QtGui/QGuiApplication>
-#include <QtGui/private/qguiapplication_p.h>
-#include <qpa/qwindowsysteminterface.h>
-#include <qpa/qplatforminputcontextfactory_p.h>
-
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
-#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
-
-#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
-#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
-#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
-#include <QtPlatformSupport/private/qevdevtouchmanager_p.h>
-#endif
-
-#if !defined(QT_NO_TSLIB) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
-#include <QtPlatformSupport/private/qtslib_p.h>
-#endif
-
-#include <QtPlatformHeaders/qeglfsfunctions.h>
-
-#include "qeglplatformintegration_p.h"
-#include "qeglplatformcontext_p.h"
-#include "qeglplatformwindow_p.h"
-#include "qeglplatformscreen_p.h"
-#include "qeglplatformcursor_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QEGLPlatformIntegration
- \brief Base class for EGL-based QPlatformIntegration implementations.
- \since 5.2
- \internal
- \ingroup qpa
-
- This class provides most of the necessary platform integration for
- an EGL-based Unix system. Platform plugins must subclass this and
- reimplement the virtuals for creating platform screens and windows
- since they will most likely wish to use a subclass for these.
-
- The backing store, native interface accessors, font database,
- basic capability flags, etc. are provided out of the box, no
- further customization is needed.
-
- \note It is critical that this class' implementation of
- initialize() is called. Therefore subclasses should either avoid
- to reimplement this function or call the base class
- implementation.
- */
-
-QEGLPlatformIntegration::QEGLPlatformIntegration()
- : m_display(EGL_NO_DISPLAY),
- m_inputContext(0),
- m_fontDb(new QGenericUnixFontDatabase),
- m_services(new QGenericUnixServices),
- m_kbdMgr(0)
-{
-}
-
-QEGLPlatformIntegration::~QEGLPlatformIntegration()
-{
-}
-
-void QEGLPlatformIntegration::initialize()
-{
- m_display = eglGetDisplay(nativeDisplay());
- if (m_display == EGL_NO_DISPLAY)
- qFatal("Could not open egl display");
-
- EGLint major, minor;
- if (!eglInitialize(m_display, &major, &minor))
- qFatal("Could not initialize egl display");
-
- m_inputContext = QPlatformInputContextFactory::create();
-
- m_vtHandler.reset(new QFbVtHandler);
-}
-
-void QEGLPlatformIntegration::destroy()
-{
- foreach (QWindow *w, qGuiApp->topLevelWindows())
- w->destroy();
-
- if (m_display != EGL_NO_DISPLAY)
- eglTerminate(m_display);
-}
-
-QAbstractEventDispatcher *QEGLPlatformIntegration::createEventDispatcher() const
-{
- return createUnixEventDispatcher();
-}
-
-QPlatformServices *QEGLPlatformIntegration::services() const
-{
- return m_services.data();
-}
-
-QPlatformFontDatabase *QEGLPlatformIntegration::fontDatabase() const
-{
- return m_fontDb.data();
-}
-
-QPlatformBackingStore *QEGLPlatformIntegration::createPlatformBackingStore(QWindow *window) const
-{
- QOpenGLCompositorBackingStore *bs = new QOpenGLCompositorBackingStore(window);
- if (!window->handle())
- window->create();
- static_cast<QEGLPlatformWindow *>(window->handle())->setBackingStore(bs);
- return bs;
-}
-
-QPlatformWindow *QEGLPlatformIntegration::createPlatformWindow(QWindow *window) const
-{
- QWindowSystemInterface::flushWindowSystemEvents();
- QEGLPlatformWindow *w = createWindow(window);
- w->create();
- if (window->type() != Qt::ToolTip)
- w->requestActivateWindow();
- return w;
-}
-
-QPlatformOpenGLContext *QEGLPlatformIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
-{
- // If there is a "root" window into which raster and QOpenGLWidget content is
- // composited, all other contexts must share with its context.
- QOpenGLContext *compositingContext = QOpenGLCompositor::instance()->context();
- QPlatformOpenGLContext *share = compositingContext ? compositingContext->handle() : context->shareHandle();
- QVariant nativeHandle = context->nativeHandle();
- QPlatformOpenGLContext *platformContext = createContext(context->format(),
- share,
- display(),
- &nativeHandle);
- context->setNativeHandle(nativeHandle);
- return platformContext;
-}
-
-QPlatformOffscreenSurface *QEGLPlatformIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const
-{
- QEGLPlatformScreen *screen = static_cast<QEGLPlatformScreen *>(surface->screen()->handle());
- return createOffscreenSurface(screen->display(), surface->requestedFormat(), surface);
-}
-
-bool QEGLPlatformIntegration::hasCapability(QPlatformIntegration::Capability cap) const
-{
- switch (cap) {
- case ThreadedPixmaps: return true;
- case OpenGL: return true;
- case ThreadedOpenGL: return true;
- case WindowManagement: return false;
- case RasterGLSurface: return true;
- default: return QPlatformIntegration::hasCapability(cap);
- }
-}
-
-QPlatformNativeInterface *QEGLPlatformIntegration::nativeInterface() const
-{
- return const_cast<QEGLPlatformIntegration *>(this);
-}
-
-enum ResourceType {
- EglDisplay,
- EglWindow,
- EglContext,
- EglConfig,
- NativeDisplay,
- XlibDisplay
-};
-
-static int resourceType(const QByteArray &key)
-{
- static const QByteArray names[] = { // match ResourceType
- QByteArrayLiteral("egldisplay"),
- QByteArrayLiteral("eglwindow"),
- QByteArrayLiteral("eglcontext"),
- QByteArrayLiteral("eglconfig"),
- QByteArrayLiteral("nativedisplay"),
- QByteArrayLiteral("display")
- };
- const QByteArray *end = names + sizeof(names) / sizeof(names[0]);
- const QByteArray *result = std::find(names, end, key);
- if (result == end)
- result = std::find(names, end, key.toLower());
- return int(result - names);
-}
-
-void *QEGLPlatformIntegration::nativeResourceForIntegration(const QByteArray &resource)
-{
- void *result = 0;
-
- switch (resourceType(resource)) {
- case EglDisplay:
- result = display();
- break;
- case NativeDisplay:
- result = reinterpret_cast<void*>(nativeDisplay());
- break;
- default:
- break;
- }
-
- return result;
-}
-
-void *QEGLPlatformIntegration::nativeResourceForScreen(const QByteArray &resource, QScreen *)
-{
- void *result = 0;
-
- switch (resourceType(resource)) {
- case XlibDisplay:
- // Play nice when using the x11 hooks: Be compatible with xcb that allows querying
- // the X Display pointer, which is nothing but our native display.
- result = reinterpret_cast<void*>(nativeDisplay());
- break;
- default:
- break;
- }
-
- return result;
-}
-
-void *QEGLPlatformIntegration::nativeResourceForWindow(const QByteArray &resource, QWindow *window)
-{
- void *result = 0;
-
- switch (resourceType(resource)) {
- case EglDisplay:
- if (window && window->handle())
- result = static_cast<QEGLPlatformScreen *>(window->handle()->screen())->display();
- else
- result = display();
- break;
- case EglWindow:
- if (window && window->handle())
- result = reinterpret_cast<void*>(static_cast<QEGLPlatformWindow *>(window->handle())->eglWindow());
- break;
- default:
- break;
- }
-
- return result;
-}
-
-void *QEGLPlatformIntegration::nativeResourceForContext(const QByteArray &resource, QOpenGLContext *context)
-{
- void *result = 0;
-
- switch (resourceType(resource)) {
- case EglContext:
- if (context->handle())
- result = static_cast<QEGLPlatformContext *>(context->handle())->eglContext();
- break;
- case EglConfig:
- if (context->handle())
- result = static_cast<QEGLPlatformContext *>(context->handle())->eglConfig();
- break;
- case EglDisplay:
- if (context->handle())
- result = static_cast<QEGLPlatformContext *>(context->handle())->eglDisplay();
- break;
- default:
- break;
- }
-
- return result;
-}
-
-static void *eglContextForContext(QOpenGLContext *context)
-{
- Q_ASSERT(context);
-
- QEGLPlatformContext *handle = static_cast<QEGLPlatformContext *>(context->handle());
- if (!handle)
- return 0;
-
- return handle->eglContext();
-}
-
-QPlatformNativeInterface::NativeResourceForContextFunction QEGLPlatformIntegration::nativeResourceFunctionForContext(const QByteArray &resource)
-{
- QByteArray lowerCaseResource = resource.toLower();
- if (lowerCaseResource == "get_egl_context")
- return NativeResourceForContextFunction(eglContextForContext);
-
- return 0;
-}
-
-QFunctionPointer QEGLPlatformIntegration::platformFunction(const QByteArray &function) const
-{
-#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
- if (function == QEglFSFunctions::loadKeymapTypeIdentifier())
- return QFunctionPointer(loadKeymapStatic);
-#else
- Q_UNUSED(function)
-#endif
-
- return 0;
-}
-
-void QEGLPlatformIntegration::loadKeymapStatic(const QString &filename)
-{
-#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
- QEGLPlatformIntegration *self = static_cast<QEGLPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
- if (self->m_kbdMgr)
- self->m_kbdMgr->loadKeymap(filename);
- else
- qWarning("QEGLPlatformIntegration: Cannot load keymap, no keyboard handler found");
-#else
- Q_UNUSED(filename);
-#endif
-}
-
-void QEGLPlatformIntegration::createInputHandlers()
-{
-#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
- m_kbdMgr = new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString() /* spec */, this);
- new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString() /* spec */, this);
-#ifndef QT_NO_TSLIB
- const bool useTslib = qEnvironmentVariableIntValue("QT_QPA_EGLFS_TSLIB");
- if (useTslib)
- new QTsLibMouseHandler(QLatin1String("TsLib"), QString() /* spec */);
- else
-#endif // QT_NO_TSLIB
- new QEvdevTouchManager(QLatin1String("EvdevTouch"), QString() /* spec */, this);
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/platformsupport/eglconvenience/qeglplatformintegration_p.h b/src/platformsupport/eglconvenience/qeglplatformintegration_p.h
deleted file mode 100644
index 42fbf8c8a1..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformintegration_p.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QEGLPLATFORMINTEGRATION_H
-#define QEGLPLATFORMINTEGRATION_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/QVariant>
-#include <qpa/qplatformintegration.h>
-#include <qpa/qplatformnativeinterface.h>
-#include <EGL/egl.h>
-
-QT_BEGIN_NAMESPACE
-
-class QEGLPlatformWindow;
-class QEGLPlatformContext;
-class QFbVtHandler;
-class QEvdevKeyboardManager;
-
-class QEGLPlatformIntegration : public QPlatformIntegration, public QPlatformNativeInterface
-{
-public:
- QEGLPlatformIntegration();
- ~QEGLPlatformIntegration();
-
- void initialize() Q_DECL_OVERRIDE;
- void destroy() Q_DECL_OVERRIDE;
-
- EGLDisplay display() const { return m_display; }
-
- QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
- QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
- QPlatformServices *services() const Q_DECL_OVERRIDE;
- QPlatformInputContext *inputContext() const Q_DECL_OVERRIDE { return m_inputContext; }
-
- QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
- QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const Q_DECL_OVERRIDE;
- QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const Q_DECL_OVERRIDE;
- QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
-
- bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
-
- QPlatformNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
- // QPlatformNativeInterface
- void *nativeResourceForIntegration(const QByteArray &resource) Q_DECL_OVERRIDE;
- void *nativeResourceForScreen(const QByteArray &resource, QScreen *screen) Q_DECL_OVERRIDE;
- void *nativeResourceForWindow(const QByteArray &resource, QWindow *window) Q_DECL_OVERRIDE;
- void *nativeResourceForContext(const QByteArray &resource, QOpenGLContext *context) Q_DECL_OVERRIDE;
- NativeResourceForContextFunction nativeResourceFunctionForContext(const QByteArray &resource) Q_DECL_OVERRIDE;
-
- QFunctionPointer platformFunction(const QByteArray &function) const Q_DECL_OVERRIDE;
-
- QFbVtHandler *vtHandler() { return m_vtHandler.data(); }
-
-protected:
- virtual QEGLPlatformWindow *createWindow(QWindow *window) const = 0;
- virtual QEGLPlatformContext *createContext(const QSurfaceFormat &format,
- QPlatformOpenGLContext *shareContext,
- EGLDisplay display,
- QVariant *nativeHandle) const = 0;
- virtual QPlatformOffscreenSurface *createOffscreenSurface(EGLDisplay display,
- const QSurfaceFormat &format,
- QOffscreenSurface *surface) const = 0;
-
- virtual EGLNativeDisplayType nativeDisplay() const { return EGL_DEFAULT_DISPLAY; }
-
- void createInputHandlers();
-
-private:
- static void loadKeymapStatic(const QString &filename);
-
- EGLDisplay m_display;
- QPlatformInputContext *m_inputContext;
- QScopedPointer<QPlatformFontDatabase> m_fontDb;
- QScopedPointer<QPlatformServices> m_services;
- QScopedPointer<QFbVtHandler> m_vtHandler;
- QEvdevKeyboardManager *m_kbdMgr;
-};
-
-QT_END_NAMESPACE
-
-#endif // QEGLPLATFORMINTEGRATION_H
diff --git a/src/platformsupport/eglconvenience/qeglplatformscreen.cpp b/src/platformsupport/eglconvenience/qeglplatformscreen.cpp
deleted file mode 100644
index 61f8cdd9b4..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformscreen.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qeglplatformscreen_p.h"
-#include "qeglplatformwindow_p.h"
-#include <QtGui/qwindow.h>
-#include <qpa/qwindowsysteminterface.h>
-#include <QtPlatformSupport/private/qopenglcompositor_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QEGLPlatformScreen
- \brief Base class for EGL-based platform screen implementations.
- \since 5.2
- \internal
- \ingroup qpa
- */
-
-QEGLPlatformScreen::QEGLPlatformScreen(EGLDisplay dpy)
- : m_dpy(dpy),
- m_pointerWindow(0)
-{
-}
-
-QEGLPlatformScreen::~QEGLPlatformScreen()
-{
- QOpenGLCompositor::destroy();
-}
-
-void QEGLPlatformScreen::handleCursorMove(const QPoint &pos)
-{
- const QOpenGLCompositor *compositor = QOpenGLCompositor::instance();
- const QList<QOpenGLCompositorWindow *> windows = compositor->windows();
-
- // Generate enter and leave events like a real windowing system would do.
- if (windows.isEmpty())
- return;
-
- // First window is always fullscreen.
- if (windows.count() == 1) {
- QWindow *window = windows[0]->sourceWindow();
- if (m_pointerWindow != window) {
- m_pointerWindow = window;
- QWindowSystemInterface::handleEnterEvent(window, window->mapFromGlobal(pos), pos);
- }
- return;
- }
-
- QWindow *enter = 0, *leave = 0;
- for (int i = windows.count() - 1; i >= 0; --i) {
- QWindow *window = windows[i]->sourceWindow();
- const QRect geom = window->geometry();
- if (geom.contains(pos)) {
- if (m_pointerWindow != window) {
- leave = m_pointerWindow;
- m_pointerWindow = window;
- enter = window;
- }
- break;
- }
- }
-
- if (enter && leave)
- QWindowSystemInterface::handleEnterLeaveEvent(enter, leave, enter->mapFromGlobal(pos), pos);
-}
-
-QPixmap QEGLPlatformScreen::grabWindow(WId wid, int x, int y, int width, int height) const
-{
- QOpenGLCompositor *compositor = QOpenGLCompositor::instance();
- const QList<QOpenGLCompositorWindow *> windows = compositor->windows();
- Q_ASSERT(!windows.isEmpty());
-
- QImage img;
-
- if (static_cast<QEGLPlatformWindow *>(windows.first()->sourceWindow()->handle())->isRaster()) {
- // Request the compositor to render everything into an FBO and read it back. This
- // is of course slow, but it's safe and reliable. It will not include the mouse
- // cursor, which is a plus.
- img = compositor->grab();
- } else {
- // Just a single OpenGL window without compositing. Do not support this case for now. Doing
- // glReadPixels is not an option since it would read from the back buffer which may have
- // undefined content when calling right after a swapBuffers (unless preserved swap is
- // available and enabled, but we have no support for that).
- qWarning("grabWindow: Not supported for non-composited OpenGL content. Use QQuickWindow::grabWindow() instead.");
- return QPixmap();
- }
-
- if (!wid) {
- const QSize screenSize = geometry().size();
- if (width < 0)
- width = screenSize.width() - x;
- if (height < 0)
- height = screenSize.height() - y;
- return QPixmap::fromImage(img).copy(x, y, width, height);
- }
-
- foreach (QOpenGLCompositorWindow *w, windows) {
- const QWindow *window = w->sourceWindow();
- if (window->winId() == wid) {
- const QRect geom = window->geometry();
- if (width < 0)
- width = geom.width() - x;
- if (height < 0)
- height = geom.height() - y;
- QRect rect(geom.topLeft() + QPoint(x, y), QSize(width, height));
- rect &= window->geometry();
- return QPixmap::fromImage(img).copy(rect);
- }
- }
-
- return QPixmap();
-}
-
-QT_END_NAMESPACE
diff --git a/src/platformsupport/eglconvenience/qeglplatformscreen_p.h b/src/platformsupport/eglconvenience/qeglplatformscreen_p.h
deleted file mode 100644
index 4a987f6860..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformscreen_p.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QEGLPLATFORMSCREEN_H
-#define QEGLPLATFORMSCREEN_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/QPoint>
-#include <QtCore/qtextstream.h>
-#include <qpa/qplatformscreen.h>
-#include <EGL/egl.h>
-
-QT_BEGIN_NAMESPACE
-
-class QOpenGLContext;
-class QWindow;
-class QEGLPlatformWindow;
-
-class QEGLPlatformScreen : public QPlatformScreen
-{
-public:
- QEGLPlatformScreen(EGLDisplay dpy);
- ~QEGLPlatformScreen();
-
- EGLDisplay display() const { return m_dpy; }
-
- void handleCursorMove(const QPoint &pos);
-
- QPixmap grabWindow(WId wid, int x, int y, int width, int height) const Q_DECL_OVERRIDE;
-
-private:
- EGLDisplay m_dpy;
- QWindow *m_pointerWindow;
-};
-
-QT_END_NAMESPACE
-
-#endif // QEGLPLATFORMSCREEN_H
diff --git a/src/platformsupport/eglconvenience/qeglplatformwindow.cpp b/src/platformsupport/eglconvenience/qeglplatformwindow.cpp
deleted file mode 100644
index 35f38ac29a..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformwindow.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qpa/qwindowsysteminterface.h>
-#include <QtPlatformSupport/private/qopenglcompositor_p.h>
-#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
-
-#include "qeglplatformwindow_p.h"
-#include "qeglplatformscreen_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QEGLPlatformWindow
- \brief Base class for EGL-based platform window implementations.
- \since 5.2
- \internal
- \ingroup qpa
-
- Lightweight class providing some basic platform window operations
- and interfacing with QOpenGLCompositorBackingStore.
-
- Almost no QPlatformWindow functions are implemented here. This is
- intentional because different platform plugins may use different
- strategies for their window management (some may force fullscreen
- windows, some may not, some may share the underlying native
- surface, some may not, etc.) and therefore it is not sensible to
- enforce anything for these functions.
-
- \note Subclasses are responsible for invoking this class'
- implementation of create() and are expected to utilize the window
- stack management functions (addWindow() etc.) in
- QOpenGLCompositor.
- */
-
-QEGLPlatformWindow::QEGLPlatformWindow(QWindow *w)
- : QPlatformWindow(w),
- m_backingStore(0),
- m_raster(false),
- m_winId(0)
-{
-}
-
-static WId newWId()
-{
- static WId id = 0;
-
- if (id == std::numeric_limits<WId>::max())
- qWarning("QEGLPlatformWindow: Out of window IDs");
-
- return ++id;
-}
-
-void QEGLPlatformWindow::create()
-{
- m_winId = newWId();
-
- // Save the original surface type before changing to OpenGLSurface.
- m_raster = (window()->surfaceType() == QSurface::RasterSurface);
- if (m_raster) // change to OpenGL, but not for RasterGLSurface
- window()->setSurfaceType(QSurface::OpenGLSurface);
-
- if (window()->type() == Qt::Desktop) {
- QRect fullscreenRect(QPoint(), screen()->availableGeometry().size());
- QPlatformWindow::setGeometry(fullscreenRect);
- QWindowSystemInterface::handleGeometryChange(window(), fullscreenRect);
- return;
- }
-}
-
-bool QEGLPlatformWindow::isRaster() const
-{
- return m_raster || window()->surfaceType() == QSurface::RasterGLSurface;
-}
-
-QWindow *QEGLPlatformWindow::sourceWindow() const
-{
- return window();
-}
-
-const QPlatformTextureList *QEGLPlatformWindow::textures() const
-{
- if (m_backingStore)
- return m_backingStore->textures();
-
- return 0;
-}
-
-void QEGLPlatformWindow::endCompositing()
-{
- if (m_backingStore)
- m_backingStore->notifyComposited();
-}
-
-WId QEGLPlatformWindow::winId() const
-{
- return m_winId;
-}
-
-void QEGLPlatformWindow::setOpacity(qreal)
-{
- if (!isRaster())
- qWarning("QEGLPlatformWindow: Cannot set opacity for non-raster windows");
-
- // Nothing to do here. The opacity is stored in the QWindow.
-}
-
-QT_END_NAMESPACE
diff --git a/src/platformsupport/eglconvenience/qeglplatformwindow_p.h b/src/platformsupport/eglconvenience/qeglplatformwindow_p.h
deleted file mode 100644
index 852d690c92..0000000000
--- a/src/platformsupport/eglconvenience/qeglplatformwindow_p.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QEGLPLATFORMWINDOW_H
-#define QEGLPLATFORMWINDOW_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 <qpa/qplatformwindow.h>
-#include <QtPlatformSupport/private/qopenglcompositor_p.h>
-#include <EGL/egl.h>
-
-QT_BEGIN_NAMESPACE
-
-class QOpenGLCompositorBackingStore;
-class QPlatformTextureList;
-
-class QEGLPlatformWindow : public QPlatformWindow, public QOpenGLCompositorWindow
-{
-public:
- QEGLPlatformWindow(QWindow *w);
-
- virtual void create();
-
- QOpenGLCompositorBackingStore *backingStore() { return m_backingStore; }
- void setBackingStore(QOpenGLCompositorBackingStore *backingStore) { m_backingStore = backingStore; }
- bool isRaster() const;
-
- QWindow *sourceWindow() const Q_DECL_OVERRIDE;
- const QPlatformTextureList *textures() const Q_DECL_OVERRIDE;
- void endCompositing() Q_DECL_OVERRIDE;
-
- WId winId() const Q_DECL_OVERRIDE;
- void setOpacity(qreal opacity) Q_DECL_OVERRIDE;
-
- virtual EGLNativeWindowType eglWindow() const = 0;
-
-private:
- QOpenGLCompositorBackingStore *m_backingStore;
- bool m_raster;
- WId m_winId;
-};
-
-QT_END_NAMESPACE
-
-#endif // QEGLPLATFORMWINDOW_H
diff --git a/src/platformsupport/fbconvenience/qfbscreen.cpp b/src/platformsupport/fbconvenience/qfbscreen.cpp
index 566f84c9ea..d00954375d 100644
--- a/src/platformsupport/fbconvenience/qfbscreen.cpp
+++ b/src/platformsupport/fbconvenience/qfbscreen.cpp
@@ -206,10 +206,11 @@ void QFbScreen::generateRects()
}
#endif
}
- foreach (const QRect &rect, remainingScreen.rects())
+ const QVector<QRect> remainingScreenRects = remainingScreen.rects();
+ mCachedRects.reserve(mCachedRects.count() + remainingScreenRects.count());
+ foreach (const QRect &rect, remainingScreenRects)
mCachedRects += QPair<QRect, int>(rect, -1);
mIsUpToDate = true;
- return;
}
QRegion QFbScreen::doRedraw()
diff --git a/src/platformsupport/fontdatabases/basic/qbasicfontdatabase.cpp b/src/platformsupport/fontdatabases/basic/qbasicfontdatabase.cpp
index c41061a9fd..b04ae8ee52 100644
--- a/src/platformsupport/fontdatabases/basic/qbasicfontdatabase.cpp
+++ b/src/platformsupport/fontdatabases/basic/qbasicfontdatabase.cpp
@@ -76,24 +76,6 @@ void QBasicFontDatabase::populateFontDatabase()
}
}
-inline static void setHintingPreference(QFontEngine *engine, QFont::HintingPreference hintingPreference)
-{
- switch (hintingPreference) {
- case QFont::PreferNoHinting:
- engine->setDefaultHintStyle(QFontEngineFT::HintNone);
- break;
- case QFont::PreferFullHinting:
- engine->setDefaultHintStyle(QFontEngineFT::HintFull);
- break;
- case QFont::PreferVerticalHinting:
- engine->setDefaultHintStyle(QFontEngineFT::HintLight);
- break;
- case QFont::PreferDefaultHinting:
- // Leave it as it is
- break;
- }
-}
-
QFontEngine *QBasicFontDatabase::fontEngine(const QFontDef &fontDef, void *usrPtr)
{
FontFile *fontfile = static_cast<FontFile *> (usrPtr);
@@ -119,7 +101,7 @@ QFontEngine *QBasicFontDatabase::fontEngine(const QFontDef &fontDef, void *usrPt
delete engine;
engine = 0;
} else {
- setHintingPreference(engine, static_cast<QFont::HintingPreference>(fontDef.hintingPreference));
+ engine->setQtDefaultHintStyle(static_cast<QFont::HintingPreference>(fontDef.hintingPreference));
}
return engine;
@@ -172,7 +154,7 @@ QFontEngine *QBasicFontDatabase::fontEngine(const QByteArray &fontData, qreal pi
}
fe->updateFamilyNameAndStyle();
- setHintingPreference(fe, hintingPreference);
+ fe->setQtDefaultHintStyle(static_cast<QFont::HintingPreference>(fontDef.hintingPreference));
return fe;
}
diff --git a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp b/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp
index 112bb8e0a6..022bc8bec2 100644
--- a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp
+++ b/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp
@@ -44,6 +44,7 @@
#include <QtGui/private/qfontengine_ft_p.h>
#include <QtGui/private/qguiapplication_p.h>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qguiapplication.h>
@@ -553,10 +554,8 @@ QFontEngine::HintStyle defaultHintStyleFromMatch(QFont::HintingPreference hintin
break;
}
- if (QGuiApplication::platformNativeInterface()->nativeResourceForScreen("nofonthinting",
- QGuiApplication::primaryScreen())) {
+ if (QHighDpiScaling::isActive())
return QFontEngine::HintNone;
- }
int hint_style = 0;
if (FcPatternGetInteger (match, FC_HINT_STYLE, 0, &hint_style) == FcResultMatch) {
diff --git a/src/platformsupport/fontdatabases/mac/coretext.pri b/src/platformsupport/fontdatabases/mac/coretext.pri
index f67f00672a..ebb64d15b4 100644
--- a/src/platformsupport/fontdatabases/mac/coretext.pri
+++ b/src/platformsupport/fontdatabases/mac/coretext.pri
@@ -1,6 +1,13 @@
HEADERS += $$PWD/qcoretextfontdatabase_p.h $$PWD/qfontengine_coretext_p.h
OBJECTIVE_SOURCES += $$PWD/qfontengine_coretext.mm $$PWD/qcoretextfontdatabase.mm
+contains(QT_CONFIG, freetype) {
+ include($$QT_SOURCE_TREE/src/3rdparty/freetype_dependency.pri)
+ HEADERS += $$QT_SOURCE_TREE/src/gui/text/qfontengine_ft_p.h
+ SOURCES += $$QT_SOURCE_TREE/src/gui/text/qfontengine_ft.cpp
+ CONFIG += opentype
+}
+
ios: \
# On iOS CoreText and CoreGraphics are stand-alone frameworks
LIBS_PRIVATE += -framework CoreText -framework CoreGraphics
diff --git a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm
index be70092010..1f000421cc 100644
--- a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm
+++ b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm
@@ -33,6 +33,8 @@
#include "qglobal.h"
+#include <sys/param.h>
+
#if defined(Q_OS_MACX)
#import <Cocoa/Cocoa.h>
#import <IOKit/graphics/IOGraphicsLib.h>
@@ -45,21 +47,12 @@
#include <QtCore/QSettings>
#include <QtGui/QGuiApplication>
#include <QtCore/QtEndian>
+#ifndef QT_NO_FREETYPE
+#include <QtGui/private/qfontengine_ft_p.h>
+#endif
QT_BEGIN_NAMESPACE
-namespace {
-class AutoReleasePool
-{
-public:
- AutoReleasePool(): pool([[NSAutoreleasePool alloc] init]) {}
- ~AutoReleasePool() { [pool release]; }
-
-private:
- NSAutoreleasePool *pool;
-};
-}
-
// 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[] = {
@@ -114,8 +107,12 @@ static NSInteger languageMapSort(id obj1, id obj2, void *context)
}
#endif
-QCoreTextFontDatabase::QCoreTextFontDatabase()
+QCoreTextFontDatabase::QCoreTextFontDatabase(bool useFreeType)
+#ifndef QT_NO_FREETYPE
+ : m_useFreeType(useFreeType)
+#endif
{
+ Q_UNUSED(useFreeType)
#ifdef Q_OS_MACX
QSettings appleSettings(QLatin1String("apple.com"));
QVariant appleValue = appleSettings.value(QLatin1String("AppleAntiAliasingThreshold"));
@@ -360,10 +357,48 @@ void QCoreTextFontDatabase::releaseHandle(void *handle)
CFRelease(CTFontDescriptorRef(handle));
}
+#ifndef QT_NO_FREETYPE
+static QByteArray filenameForCFUrl(CFURLRef url)
+{
+ // The on-stack buffer prevents that a QByteArray allocated for the worst case (MAXPATHLEN)
+ // stays around for the lifetime of the font. Additionally, it helps to move the char
+ // signedness cast to an acceptable place.
+ uchar buffer[MAXPATHLEN];
+ QByteArray filename;
+
+ if (!CFURLGetFileSystemRepresentation(url, true, buffer, sizeof(buffer))) {
+ qWarning("QCoreTextFontDatabase::filenameForCFUrl: could not resolve file for URL %s",
+ qPrintable(QString::fromCFString(CFURLGetString(url))));
+ } else {
+ QCFType<CFStringRef> scheme = CFURLCopyScheme(url);
+ if (QString::fromCFString(scheme) == QLatin1String("qrc"))
+ filename = ":";
+
+ filename += reinterpret_cast<char *>(buffer);
+ }
+
+ return filename;
+}
+#endif
+
extern CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef);
QFontEngine *QCoreTextFontDatabase::fontEngine(const QFontDef &f, void *usrPtr)
{
+ CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(usrPtr);
+
+#ifndef QT_NO_FREETYPE
+ if (m_useFreeType) {
+ QCFType<CFURLRef> url(static_cast<CFURLRef>(CTFontDescriptorCopyAttribute(descriptor, kCTFontURLAttribute)));
+
+ QByteArray filename;
+ if (url)
+ filename = filenameForCFUrl(url);
+
+ return freeTypeFontEngine(f, filename);
+ }
+#endif
+
qreal scaledPointSize = f.pixelSize;
// When 96 DPI is forced, the Mac plugin will use DPI 72 for some
@@ -375,7 +410,6 @@ QFontEngine *QCoreTextFontDatabase::fontEngine(const QFontDef &f, void *usrPtr)
if (QGuiApplication::testAttribute(Qt::AA_Use96Dpi))
scaledPointSize = f.pointSize;
- CTFontDescriptorRef descriptor = (CTFontDescriptorRef) usrPtr;
CGAffineTransform matrix = qt_transform_from_fontdef(f);
CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, scaledPointSize, &matrix);
if (font) {
@@ -397,6 +431,29 @@ static void releaseFontData(void* info, const void* data, size_t size)
QFontEngine *QCoreTextFontDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference)
{
+#ifndef QT_NO_FREETYPE
+ if (m_useFreeType) {
+ QByteArray *fontDataCopy = new QByteArray(fontData);
+ QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(fontDataCopy,
+ fontDataCopy->constData(), fontDataCopy->size(), releaseFontData);
+ QCFType<CGFontRef> cgFont(CGFontCreateWithDataProvider(dataProvider));
+
+ if (!cgFont) {
+ qWarning("QCoreTextFontDatabase::fontEngine: CGFontCreateWithDataProvider failed");
+ return Q_NULLPTR;
+ }
+
+ QFontDef fontDef;
+ fontDef.pixelSize = pixelSize;
+ fontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi();
+ fontDef.hintingPreference = hintingPreference;
+ CGAffineTransform transform = qt_transform_from_fontdef(fontDef);
+ QCFType<CTFontRef> ctFont(CTFontCreateWithGraphicsFont(cgFont, fontDef.pixelSize, &transform, Q_NULLPTR));
+ QCFType<CFURLRef> url(static_cast<CFURLRef>(CTFontCopyAttribute(ctFont, kCTFontURLAttribute)));
+ return freeTypeFontEngine(fontDef, filenameForCFUrl(url), fontData);
+ }
+#endif
+
Q_UNUSED(hintingPreference);
QByteArray* fontDataCopy = new QByteArray(fontData);
@@ -453,7 +510,7 @@ QStringList QCoreTextFontDatabase::fallbacksForFamily(const QString &family, QFo
Q_UNUSED(style);
Q_UNUSED(script);
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
static QHash<QString, QStringList> fallbackLists;
@@ -568,10 +625,36 @@ QStringList QCoreTextFontDatabase::fallbacksForFamily(const QString &family, QFo
}
#if HAVE_CORETEXT
-static CFArrayRef createDescriptorArrayForFont(CTFontRef font)
+static CFArrayRef createDescriptorArrayForFont(CTFontRef font, const QString &fileName = QString())
{
CFMutableArrayRef array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
- CFArrayAppendValue(array, QCFType<CTFontDescriptorRef>(CTFontCopyFontDescriptor(font)));
+ QCFType<CTFontDescriptorRef> descriptor = CTFontCopyFontDescriptor(font);
+
+ Q_UNUSED(fileName)
+#ifndef QT_NO_FREETYPE
+ // The physical font source URL (usually a local file or Qt resource) is only required for
+ // FreeType, when using non-system fonts, and needs some hackery to attach in a format
+ // agreeable to OSX.
+ if (!fileName.isEmpty()) {
+ QCFType<CFURLRef> fontURL;
+
+ if (fileName.startsWith(QLatin1String(":/"))) {
+ // QUrl::fromLocalFile() doesn't accept qrc pseudo-paths like ":/fonts/myfont.ttf".
+ // Therefore construct from QString with the qrc:// scheme -> "qrc:///fonts/myfont.ttf".
+ fontURL = QUrl(QStringLiteral("qrc://") + fileName.mid(1)).toCFURL();
+ } else if (!fileName.isEmpty()) {
+ // At this point we hope that filename is in a format that QUrl can handle.
+ fontURL = QUrl::fromLocalFile(fileName).toCFURL();
+ }
+
+ QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 1,
+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+ CFDictionaryAddValue(attributes, kCTFontURLAttribute, fontURL);
+ descriptor = CTFontDescriptorCreateCopyWithAttributes(descriptor, attributes);
+ }
+#endif
+
+ CFArrayAppendValue(array, descriptor);
return array;
}
#endif
@@ -592,7 +675,11 @@ QStringList QCoreTextFontDatabase::addApplicationFont(const QByteArray &fontData
if (cgFont) {
if (CTFontManagerRegisterGraphicsFont(cgFont, &error)) {
QCFType<CTFontRef> font = CTFontCreateWithGraphicsFont(cgFont, 0.0, NULL, NULL);
- fonts = createDescriptorArrayForFont(font);
+ fonts = createDescriptorArrayForFont(font
+#ifndef QT_NO_FREETYPE
+ , m_useFreeType ? fileName : QString()
+#endif
+ );
m_applicationFonts.append(QVariant::fromValue(QCFType<CGFontRef>::constructFromGet(cgFont)));
}
}
@@ -892,5 +979,36 @@ void QCoreTextFontDatabase::removeApplicationFonts()
#endif
}
+#ifndef QT_NO_FREETYPE
+QFontEngine *QCoreTextFontDatabase::freeTypeFontEngine(const QFontDef &fontDef, const QByteArray &filename,
+ const QByteArray &fontData)
+{
+ QFontEngine::FaceId faceId;
+ faceId.filename = filename;
+ const bool antialias = !(fontDef.styleStrategy & QFont::NoAntialias);
+
+ QScopedPointer<QFontEngineFT> engine(new QFontEngineFT(fontDef));
+ QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_Mono;
+ if (antialias) {
+ QFontEngine::SubpixelAntialiasingType subpixelType = subpixelAntialiasingTypeHint();
+ if (subpixelType == QFontEngine::Subpixel_None || (fontDef.styleStrategy & QFont::NoSubpixelAntialias)) {
+ format = QFontEngineFT::Format_A8;
+ engine->subpixelType = QFontEngine::Subpixel_None;
+ } else {
+ format = QFontEngineFT::Format_A32;
+ engine->subpixelType = subpixelType;
+ }
+ }
+
+ if (!engine->init(faceId, antialias, format, fontData) || engine->invalid()) {
+ qWarning() << "QCoreTextFontDatabase::freeTypefontEngine Failed to create engine";
+ return Q_NULLPTR;
+ }
+ engine->setQtDefaultHintStyle(static_cast<QFont::HintingPreference>(fontDef.hintingPreference));
+
+ return engine.take();
+}
+#endif
+
QT_END_NAMESPACE
diff --git a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h
index a423ed5ae2..95af1210b3 100644
--- a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h
+++ b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h
@@ -73,7 +73,7 @@ QT_BEGIN_NAMESPACE
class QCoreTextFontDatabase : public QPlatformFontDatabase
{
public:
- QCoreTextFontDatabase();
+ QCoreTextFontDatabase(bool useFreeType = false);
~QCoreTextFontDatabase();
void populateFontDatabase() Q_DECL_OVERRIDE;
void populateFamily(const QString &familyName) Q_DECL_OVERRIDE;
@@ -95,6 +95,11 @@ public:
private:
void populateFromDescriptor(CTFontDescriptorRef font);
+#ifndef QT_NO_FREETYPE
+ bool m_useFreeType;
+ QFontEngine *freeTypeFontEngine(const QFontDef &fontDef, const QByteArray &filename,
+ const QByteArray &fontData = QByteArray());
+#endif
mutable QString defaultFontName;
void removeApplicationFonts();
diff --git a/src/platformsupport/input/evdevtablet/qevdevtablet.cpp b/src/platformsupport/input/evdevtablet/qevdevtablet.cpp
index c59f0f390a..c6f952c64d 100644
--- a/src/platformsupport/input/evdevtablet/qevdevtablet.cpp
+++ b/src/platformsupport/input/evdevtablet/qevdevtablet.cpp
@@ -292,7 +292,7 @@ void QEvdevTabletHandler::readData()
QEvdevTabletHandlerThread::QEvdevTabletHandlerThread(const QString &spec, QObject *parent)
- : QThread(parent), m_spec(spec), m_handler(0)
+ : QDaemonThread(parent), m_spec(spec), m_handler(0)
{
start();
}
diff --git a/src/platformsupport/input/evdevtablet/qevdevtablet_p.h b/src/platformsupport/input/evdevtablet/qevdevtablet_p.h
index f9682290d9..f546f9a88a 100644
--- a/src/platformsupport/input/evdevtablet/qevdevtablet_p.h
+++ b/src/platformsupport/input/evdevtablet/qevdevtablet_p.h
@@ -48,6 +48,7 @@
#include <QObject>
#include <QString>
#include <QThread>
+#include <QtCore/private/qthread_p.h>
QT_BEGIN_NAMESPACE
@@ -68,7 +69,7 @@ private:
QEvdevTabletData *d;
};
-class QEvdevTabletHandlerThread : public QThread
+class QEvdevTabletHandlerThread : public QDaemonThread
{
public:
explicit QEvdevTabletHandlerThread(const QString &spec, QObject *parent = 0);
diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp b/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp
index 885326e512..1ca95074b9 100644
--- a/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp
+++ b/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp
@@ -418,11 +418,11 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data)
m_currentData.y = qBound(hw_range_y_min, data->value, hw_range_y_max);
if (m_singleTouch)
m_contacts[m_currentSlot].y = m_currentData.y;
- if (m_typeB) {
- m_contacts[m_currentSlot].y = m_currentData.y;
- if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
- m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
- }
+ if (m_typeB) {
+ m_contacts[m_currentSlot].y = m_currentData.y;
+ if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
+ m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
+ }
} else if (data->code == ABS_MT_TRACKING_ID) {
m_currentData.trackingId = data->value;
if (m_typeB) {
@@ -642,7 +642,7 @@ void QEvdevTouchScreenData::reportPoints()
QEvdevTouchScreenHandlerThread::QEvdevTouchScreenHandlerThread(const QString &device, const QString &spec, QObject *parent)
- : QThread(parent), m_device(device), m_spec(spec), m_handler(0)
+ : QDaemonThread(parent), m_device(device), m_spec(spec), m_handler(0)
{
start();
}
diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h b/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h
index a6d3a860f5..8e7dfe59bb 100644
--- a/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h
+++ b/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h
@@ -49,6 +49,7 @@
#include <QString>
#include <QList>
#include <QThread>
+#include <QtCore/private/qthread_p.h>
#include <qpa/qwindowsysteminterface.h>
#if !defined(QT_NO_MTDEV)
@@ -80,7 +81,7 @@ private:
#endif
};
-class QEvdevTouchScreenHandlerThread : public QThread
+class QEvdevTouchScreenHandlerThread : public QDaemonThread
{
public:
explicit QEvdevTouchScreenHandlerThread(const QString &device, const QString &spec, QObject *parent = 0);
diff --git a/src/platformsupport/input/libinput/qlibinputhandler.cpp b/src/platformsupport/input/libinput/qlibinputhandler.cpp
index 1a64ad5a30..5aa66a4eaf 100644
--- a/src/platformsupport/input/libinput/qlibinputhandler.cpp
+++ b/src/platformsupport/input/libinput/qlibinputhandler.cpp
@@ -46,7 +46,7 @@
QT_BEGIN_NAMESPACE
-Q_LOGGING_CATEGORY(qLcInput, "qt.qpa.input")
+Q_LOGGING_CATEGORY(qLcLibInput, "qt.qpa.input")
static int liOpen(const char *path, int flags, void *user_data)
{
@@ -75,7 +75,7 @@ static void liLogHandler(libinput *libinput, libinput_log_priority priority, con
if (n > 0) {
if (buf[n - 1] == '\n')
buf[n - 1] = '\0';
- qCDebug(qLcInput, "libinput: %s", buf);
+ qCDebug(qLcLibInput, "libinput: %s", buf);
}
}
@@ -93,7 +93,7 @@ QLibInputHandler::QLibInputHandler(const QString &key, const QString &spec)
qFatal("Failed to get libinput context");
libinput_log_set_handler(m_li, liLogHandler);
- if (qLcInput().isDebugEnabled())
+ if (qLcLibInput().isDebugEnabled())
libinput_log_set_priority(m_li, LIBINPUT_LOG_PRIORITY_DEBUG);
if (libinput_udev_assign_seat(m_li, "seat0"))
diff --git a/src/platformsupport/input/libinput/qlibinputkeyboard.cpp b/src/platformsupport/input/libinput/qlibinputkeyboard.cpp
index 5f1bc550b4..ec7ea7ef0d 100644
--- a/src/platformsupport/input/libinput/qlibinputkeyboard.cpp
+++ b/src/platformsupport/input/libinput/qlibinputkeyboard.cpp
@@ -33,6 +33,7 @@
#include "qlibinputkeyboard_p.h"
#include <QtCore/QTextCodec>
+#include <QtCore/QLoggingCategory>
#include <qpa/qwindowsysteminterface.h>
#include <libinput.h>
#ifndef QT_NO_XKBCOMMON_EVDEV
@@ -42,6 +43,8 @@
QT_BEGIN_NAMESPACE
+Q_DECLARE_LOGGING_CATEGORY(qLcLibInput)
+
const int REPEAT_DELAY = 500;
const int REPEAT_RATE = 100;
@@ -128,6 +131,7 @@ QLibInputKeyboard::QLibInputKeyboard()
#endif
{
#ifndef QT_NO_XKBCOMMON_EVDEV
+ qCDebug(qLcLibInput) << "Using xkbcommon for key mapping";
m_ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
if (!m_ctx) {
qWarning("Failed to create xkb context");
@@ -150,6 +154,8 @@ QLibInputKeyboard::QLibInputKeyboard()
m_repeatTimer.setSingleShot(true);
connect(&m_repeatTimer, &QTimer::timeout, this, &QLibInputKeyboard::handleRepeat);
+#else
+ qCWarning(qLcLibInput) << "X-less xkbcommon not available, not performing key mapping";
#endif
}
@@ -174,10 +180,13 @@ void QLibInputKeyboard::processKey(libinput_event_keyboard *e)
const uint32_t k = libinput_event_keyboard_get_key(e) + 8;
const bool pressed = libinput_event_keyboard_get_key_state(e) == LIBINPUT_KEY_STATE_PRESSED;
- QByteArray chars;
- chars.resize(1 + xkb_state_key_get_utf8(m_state, k, Q_NULLPTR, 0));
- xkb_state_key_get_utf8(m_state, k, chars.data(), chars.size());
- const QString text = QString::fromUtf8(chars);
+ QVarLengthArray<char, 32> chars(32);
+ const int size = xkb_state_key_get_utf8(m_state, k, chars.data(), chars.size());
+ if (Q_UNLIKELY(size + 1 > chars.size())) { // +1 for NUL
+ chars.resize(size + 1);
+ xkb_state_key_get_utf8(m_state, k, chars.data(), chars.size());
+ }
+ const QString text = QString::fromUtf8(chars.constData(), size);
const xkb_keysym_t sym = xkb_state_key_get_one_sym(m_state, k);
diff --git a/src/platformsupport/linuxaccessibility/atspiadaptor.cpp b/src/platformsupport/linuxaccessibility/atspiadaptor.cpp
index c040dab5e1..d155cecd89 100644
--- a/src/platformsupport/linuxaccessibility/atspiadaptor.cpp
+++ b/src/platformsupport/linuxaccessibility/atspiadaptor.cpp
@@ -1431,7 +1431,9 @@ bool AtSpiAdaptor::accessibleInterface(QAccessibleInterface *interface, const QS
QSpiObjectReference(connection, QDBusObjectPath(QSPI_OBJECT_PATH_ROOT))));
} else if (function == QLatin1String("GetChildren")) {
QSpiObjectReferenceArray children;
- for (int i = 0; i < interface->childCount(); ++i) {
+ const int numChildren = interface->childCount();
+ children.reserve(numChildren);
+ for (int i = 0; i < numChildren; ++i) {
QString childPath = pathForInterface(interface->child(i));
QSpiObjectReference ref(connection, QDBusObjectPath(childPath));
children << ref;
@@ -1507,7 +1509,7 @@ QSpiRelationArray AtSpiAdaptor::relationSet(QAccessibleInterface *interface, con
Q_FOREACH (const RelationPair &pair, relationInterfaces) {
// FIXME: this loop seems a bit strange... "related" always have one item when we check.
//And why is it a list, when it always have one item? And it seems to assume that the QAccessible::Relation enum maps directly to AtSpi
- QList<QSpiObjectReference> related;
+ QSpiObjectReferenceArray related;
QDBusObjectPath path = QDBusObjectPath(pathForInterface(pair.first));
related.append(QSpiObjectReference(connection, path));
@@ -1747,7 +1749,9 @@ QSpiActionArray AtSpiAdaptor::getActions(QAccessibleInterface *interface) const
{
QAccessibleActionInterface *actionInterface = interface->actionInterface();
QSpiActionArray actions;
- Q_FOREACH (const QString &actionName, QAccessibleBridgeUtils::effectiveActionNames(interface)) {
+ const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface);
+ actions.reserve(actionNames.size());
+ Q_FOREACH (const QString &actionName, actionNames) {
QSpiAction action;
QStringList keyBindings;
diff --git a/src/platformsupport/linuxaccessibility/cache.cpp b/src/platformsupport/linuxaccessibility/cache.cpp
index 2ece905fdf..0ccd2cba6e 100644
--- a/src/platformsupport/linuxaccessibility/cache.cpp
+++ b/src/platformsupport/linuxaccessibility/cache.cpp
@@ -78,8 +78,7 @@ void QSpiDBusCache::emitRemoveAccessible(const QSpiObjectReference& item)
QSpiAccessibleCacheArray QSpiDBusCache::GetItems()
{
- QList <QSpiAccessibleCacheItem> cacheArray;
- return cacheArray;
+ return QSpiAccessibleCacheArray();
}
QT_END_NAMESPACE
diff --git a/src/platformsupport/linuxaccessibility/dbusconnection.cpp b/src/platformsupport/linuxaccessibility/dbusconnection.cpp
index 45729fa065..637b06549a 100644
--- a/src/platformsupport/linuxaccessibility/dbusconnection.cpp
+++ b/src/platformsupport/linuxaccessibility/dbusconnection.cpp
@@ -42,6 +42,9 @@
#include <QDBusConnectionInterface>
#include "bus_interface.h"
+#include <QtGui/qguiapplication.h>
+#include <qplatformnativeinterface.h>
+
QT_BEGIN_NAMESPACE
QString A11Y_SERVICE = QStringLiteral("org.a11y.Bus");
@@ -65,6 +68,29 @@ DBusConnection::DBusConnection(QObject *parent)
// If it is registered already, setup a11y right away
if (c.interface()->isServiceRegistered(A11Y_SERVICE))
serviceRegistered();
+
+ // In addition try if there is an xatom exposing the bus address, this allows applications run as root to work
+ QString address = getAddressFromXCB();
+ if (!address.isEmpty()) {
+ m_enabled = true;
+ connectA11yBus(address);
+ }
+}
+
+QString DBusConnection::getAddressFromXCB()
+{
+ QGuiApplication *app = qobject_cast<QGuiApplication *>(QCoreApplication::instance());
+ if (!app)
+ return QString();
+ QPlatformNativeInterface *platformNativeInterface = app->platformNativeInterface();
+ QByteArray *addressByteArray = reinterpret_cast<QByteArray*>(
+ platformNativeInterface->nativeResourceForIntegration(QByteArrayLiteral("AtspiBus")));
+ if (addressByteArray) {
+ QString address = QString::fromLatin1(*addressByteArray);
+ delete addressByteArray;
+ return address;
+ }
+ return QString();
}
// We have the a11y registry on the session bus.
diff --git a/src/platformsupport/linuxaccessibility/dbusconnection_p.h b/src/platformsupport/linuxaccessibility/dbusconnection_p.h
index a0bd6450bf..30707a3f95 100644
--- a/src/platformsupport/linuxaccessibility/dbusconnection_p.h
+++ b/src/platformsupport/linuxaccessibility/dbusconnection_p.h
@@ -68,6 +68,7 @@ Q_SIGNALS:
void enabledChanged(bool enabled);
private Q_SLOTS:
+ QString getAddressFromXCB();
void serviceRegistered();
void serviceUnregistered();
void connectA11yBus(const QString &address);
diff --git a/src/platformsupport/linuxaccessibility/struct_marshallers_p.h b/src/platformsupport/linuxaccessibility/struct_marshallers_p.h
index 7788ceb7cc..61d79e6daa 100644
--- a/src/platformsupport/linuxaccessibility/struct_marshallers_p.h
+++ b/src/platformsupport/linuxaccessibility/struct_marshallers_p.h
@@ -46,7 +46,7 @@
// We mean it.
//
-#include <QtCore/qlist.h>
+#include <QtCore/qvector.h>
#include <QtCore/qpair.h>
#include <QtDBus/QDBusArgument>
#include <QtDBus/QDBusConnection>
@@ -55,8 +55,8 @@
#ifndef QT_NO_ACCESSIBILITY
QT_BEGIN_NAMESPACE
-typedef QList <int> QSpiIntList;
-typedef QList <uint> QSpiUIntList;
+typedef QVector<int> QSpiIntList;
+typedef QVector<uint> QSpiUIntList;
// FIXME: make this copy on write
struct QSpiObjectReference
@@ -68,26 +68,29 @@ struct QSpiObjectReference
QSpiObjectReference(const QDBusConnection& connection, const QDBusObjectPath& path)
: service(connection.baseService()), path(path) {}
};
+Q_DECLARE_TYPEINFO(QSpiObjectReference, Q_MOVABLE_TYPE); // QDBusObjectPath is movable, even though it
+ // cannot be marked that way until Qt 6
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiObjectReference &address);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiObjectReference &address);
-typedef QList <QSpiObjectReference> QSpiObjectReferenceArray;
+typedef QVector<QSpiObjectReference> QSpiObjectReferenceArray;
struct QSpiAccessibleCacheItem
{
QSpiObjectReference path;
QSpiObjectReference application;
QSpiObjectReference parent;
- QList <QSpiObjectReference> children;
+ QSpiObjectReferenceArray children;
QStringList supportedInterfaces;
QString name;
uint role;
QString description;
QSpiUIntList state;
};
+Q_DECLARE_TYPEINFO(QSpiAccessibleCacheItem, Q_MOVABLE_TYPE);
-typedef QList <QSpiAccessibleCacheItem> QSpiAccessibleCacheArray;
+typedef QVector<QSpiAccessibleCacheItem> QSpiAccessibleCacheArray;
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAccessibleCacheItem &item);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAccessibleCacheItem &item);
@@ -98,8 +101,9 @@ struct QSpiAction
QString description;
QString keyBinding;
};
+Q_DECLARE_TYPEINFO(QSpiAction, Q_MOVABLE_TYPE);
-typedef QList <QSpiAction> QSpiActionArray;
+typedef QVector<QSpiAction> QSpiActionArray;
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAction &action);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAction &action);
@@ -109,14 +113,15 @@ struct QSpiEventListener
QString listenerAddress;
QString eventName;
};
+Q_DECLARE_TYPEINFO(QSpiEventListener, Q_MOVABLE_TYPE);
-typedef QList <QSpiEventListener> QSpiEventListenerArray;
+typedef QVector<QSpiEventListener> QSpiEventListenerArray;
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiEventListener &action);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiEventListener &action);
-typedef QPair < unsigned int, QList < QSpiObjectReference > > QSpiRelationArrayEntry;
-typedef QList< QSpiRelationArrayEntry > QSpiRelationArray;
+typedef QPair<unsigned int, QSpiObjectReferenceArray> QSpiRelationArrayEntry;
+typedef QVector<QSpiRelationArrayEntry> QSpiRelationArray;
//a(iisv)
struct QSpiTextRange {
@@ -125,18 +130,22 @@ struct QSpiTextRange {
QString contents;
QVariant v;
};
-typedef QList <QSpiTextRange> QSpiTextRangeList;
+Q_DECLARE_TYPEINFO(QSpiTextRange, Q_MOVABLE_TYPE);
+
+typedef QVector<QSpiTextRange> QSpiTextRangeList;
typedef QMap <QString, QString> QSpiAttributeSet;
enum QSpiAppUpdateType {
QSPI_APP_UPDATE_ADDED = 0,
QSPI_APP_UPDATE_REMOVED = 1
};
+Q_DECLARE_TYPEINFO(QSpiAppUpdateType, Q_PRIMITIVE_TYPE);
struct QSpiAppUpdate {
int type; /* Is an application added or removed */
QString address; /* D-Bus address of application added or removed */
};
+Q_DECLARE_TYPEINFO(QSpiAppUpdate, Q_MOVABLE_TYPE);
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAppUpdate &update);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAppUpdate &update);
@@ -150,6 +159,7 @@ struct QSpiDeviceEvent {
QString text;
bool isText;
};
+Q_DECLARE_TYPEINFO(QSpiDeviceEvent, Q_MOVABLE_TYPE);
QDBusArgument &operator<<(QDBusArgument &argument, const QSpiDeviceEvent &event);
const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiDeviceEvent &event);
diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
index ba328bfb41..cd38498217 100644
--- a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
+++ b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
@@ -47,6 +47,7 @@
#include <QtCore/QLoggingCategory>
#include <QtCore/QSettings>
#include <QtCore/QVariant>
+#include <QtCore/QStandardPaths>
#include <QtCore/QStringList>
#include <private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
@@ -209,14 +210,16 @@ public:
, wheelScrollLines(3)
{ }
- static QString kdeGlobals(const QString &kdeDir)
+ static QString kdeGlobals(const QString &kdeDir, int kdeVersion)
{
+ if (kdeVersion > 4)
+ return kdeDir + QStringLiteral("/kdeglobals");
return kdeDir + QStringLiteral("/share/config/kdeglobals");
}
void refresh();
- static QVariant readKdeSetting(const QString &key, const QStringList &kdeDirs, QHash<QString, QSettings*> &kdeSettings);
- static void readKdeSystemPalette(const QStringList &kdeDirs, QHash<QString, QSettings*> &kdeSettings, QPalette *pal);
+ static QVariant readKdeSetting(const QString &key, const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings);
+ static void readKdeSystemPalette(const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings, QPalette *pal);
static QFont *kdeFont(const QVariant &fontValue);
static QStringList kdeIconThemeSearchPaths(const QStringList &kdeDirs);
@@ -246,30 +249,30 @@ void QKdeThemePrivate::refresh()
QHash<QString, QSettings*> kdeSettings;
QPalette systemPalette = QPalette();
- readKdeSystemPalette(kdeDirs, kdeSettings, &systemPalette);
+ readKdeSystemPalette(kdeDirs, kdeVersion, kdeSettings, &systemPalette);
resources.palettes[QPlatformTheme::SystemPalette] = new QPalette(systemPalette);
//## TODO tooltip color
- const QVariant styleValue = readKdeSetting(QStringLiteral("widgetStyle"), kdeDirs, kdeSettings);
+ const QVariant styleValue = readKdeSetting(QStringLiteral("widgetStyle"), kdeDirs, kdeVersion, kdeSettings);
if (styleValue.isValid()) {
const QString style = styleValue.toString();
if (style != styleNames.front())
styleNames.push_front(style);
}
- const QVariant singleClickValue = readKdeSetting(QStringLiteral("KDE/SingleClick"), kdeDirs, kdeSettings);
+ const QVariant singleClickValue = readKdeSetting(QStringLiteral("KDE/SingleClick"), kdeDirs, kdeVersion, kdeSettings);
if (singleClickValue.isValid())
singleClick = singleClickValue.toBool();
- const QVariant themeValue = readKdeSetting(QStringLiteral("Icons/Theme"), kdeDirs, kdeSettings);
+ const QVariant themeValue = readKdeSetting(QStringLiteral("Icons/Theme"), kdeDirs, kdeVersion, kdeSettings);
if (themeValue.isValid())
iconThemeName = themeValue.toString();
- const QVariant toolBarIconSizeValue = readKdeSetting(QStringLiteral("ToolbarIcons/Size"), kdeDirs, kdeSettings);
+ const QVariant toolBarIconSizeValue = readKdeSetting(QStringLiteral("ToolbarIcons/Size"), kdeDirs, kdeVersion, kdeSettings);
if (toolBarIconSizeValue.isValid())
toolBarIconSize = toolBarIconSizeValue.toInt();
- const QVariant toolbarStyleValue = readKdeSetting(QStringLiteral("Toolbar style/ToolButtonStyle"), kdeDirs, kdeSettings);
+ const QVariant toolbarStyleValue = readKdeSetting(QStringLiteral("Toolbar style/ToolButtonStyle"), kdeDirs, kdeVersion, kdeSettings);
if (toolbarStyleValue.isValid()) {
const QString toolBarStyle = toolbarStyleValue.toString();
if (toolBarStyle == QLatin1String("TextBesideIcon"))
@@ -280,17 +283,17 @@ void QKdeThemePrivate::refresh()
toolButtonStyle = Qt::ToolButtonTextUnderIcon;
}
- const QVariant wheelScrollLinesValue = readKdeSetting(QStringLiteral("KDE/WheelScrollLines"), kdeDirs, kdeSettings);
+ const QVariant wheelScrollLinesValue = readKdeSetting(QStringLiteral("KDE/WheelScrollLines"), kdeDirs, kdeVersion, kdeSettings);
if (wheelScrollLinesValue.isValid())
wheelScrollLines = wheelScrollLinesValue.toInt();
// Read system font, ignore 'smallestReadableFont'
- if (QFont *systemFont = kdeFont(readKdeSetting(QStringLiteral("font"), kdeDirs, kdeSettings)))
+ if (QFont *systemFont = kdeFont(readKdeSetting(QStringLiteral("font"), kdeDirs, kdeVersion, kdeSettings)))
resources.fonts[QPlatformTheme::SystemFont] = systemFont;
else
resources.fonts[QPlatformTheme::SystemFont] = new QFont(QLatin1String(defaultSystemFontNameC), defaultSystemFontSize);
- if (QFont *fixedFont = kdeFont(readKdeSetting(QStringLiteral("fixed"), kdeDirs, kdeSettings))) {
+ if (QFont *fixedFont = kdeFont(readKdeSetting(QStringLiteral("fixed"), kdeDirs, kdeVersion, kdeSettings))) {
resources.fonts[QPlatformTheme::FixedFont] = fixedFont;
} else {
fixedFont = new QFont(QLatin1String(defaultSystemFontNameC), defaultSystemFontSize);
@@ -301,12 +304,12 @@ void QKdeThemePrivate::refresh()
qDeleteAll(kdeSettings);
}
-QVariant QKdeThemePrivate::readKdeSetting(const QString &key, const QStringList &kdeDirs, QHash<QString, QSettings*> &kdeSettings)
+QVariant QKdeThemePrivate::readKdeSetting(const QString &key, const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings)
{
foreach (const QString &kdeDir, kdeDirs) {
QSettings *settings = kdeSettings.value(kdeDir);
if (!settings) {
- const QString kdeGlobalsPath = kdeGlobals(kdeDir);
+ const QString kdeGlobalsPath = kdeGlobals(kdeDir, kdeVersion);
if (QFileInfo(kdeGlobalsPath).isReadable()) {
settings = new QSettings(kdeGlobalsPath, QSettings::IniFormat);
kdeSettings.insert(kdeDir, settings);
@@ -334,9 +337,9 @@ static inline bool kdeColor(QPalette *pal, QPalette::ColorRole role, const QVari
return true;
}
-void QKdeThemePrivate::readKdeSystemPalette(const QStringList &kdeDirs, QHash<QString, QSettings*> &kdeSettings, QPalette *pal)
+void QKdeThemePrivate::readKdeSystemPalette(const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings, QPalette *pal)
{
- if (!kdeColor(pal, QPalette::Button, readKdeSetting(QStringLiteral("Colors:Button/BackgroundNormal"), kdeDirs, kdeSettings))) {
+ if (!kdeColor(pal, QPalette::Button, readKdeSetting(QStringLiteral("Colors:Button/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings))) {
// kcolorscheme.cpp: SetDefaultColors
const QColor defaultWindowBackground(214, 210, 208);
const QColor defaultButtonBackground(223, 220, 217);
@@ -344,18 +347,18 @@ void QKdeThemePrivate::readKdeSystemPalette(const QStringList &kdeDirs, QHash<QS
return;
}
- kdeColor(pal, QPalette::Window, readKdeSetting(QStringLiteral("Colors:Window/BackgroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::Text, readKdeSetting(QStringLiteral("Colors:View/ForegroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::WindowText, readKdeSetting(QStringLiteral("Colors:Window/ForegroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::Base, readKdeSetting(QStringLiteral("Colors:View/BackgroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::Highlight, readKdeSetting(QStringLiteral("Colors:Selection/BackgroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::HighlightedText, readKdeSetting(QStringLiteral("Colors:Selection/ForegroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::AlternateBase, readKdeSetting(QStringLiteral("Colors:View/BackgroundAlternate"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::ButtonText, readKdeSetting(QStringLiteral("Colors:Button/ForegroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::Link, readKdeSetting(QStringLiteral("Colors:View/ForegroundLink"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::LinkVisited, readKdeSetting(QStringLiteral("Colors:View/ForegroundVisited"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::ToolTipBase, readKdeSetting(QStringLiteral("Colors:Tooltip/BackgroundNormal"), kdeDirs, kdeSettings));
- kdeColor(pal, QPalette::ToolTipText, readKdeSetting(QStringLiteral("Colors:Tooltip/ForegroundNormal"), kdeDirs, kdeSettings));
+ kdeColor(pal, QPalette::Window, readKdeSetting(QStringLiteral("Colors:Window/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::Text, readKdeSetting(QStringLiteral("Colors:View/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::WindowText, readKdeSetting(QStringLiteral("Colors:Window/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::Base, readKdeSetting(QStringLiteral("Colors:View/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::Highlight, readKdeSetting(QStringLiteral("Colors:Selection/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::HighlightedText, readKdeSetting(QStringLiteral("Colors:Selection/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::AlternateBase, readKdeSetting(QStringLiteral("Colors:View/BackgroundAlternate"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::ButtonText, readKdeSetting(QStringLiteral("Colors:Button/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::Link, readKdeSetting(QStringLiteral("Colors:View/ForegroundLink"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::LinkVisited, readKdeSetting(QStringLiteral("Colors:View/ForegroundVisited"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::ToolTipBase, readKdeSetting(QStringLiteral("Colors:Tooltip/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings));
+ kdeColor(pal, QPalette::ToolTipText, readKdeSetting(QStringLiteral("Colors:Tooltip/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings));
// The above code sets _all_ color roles to "normal" colors. In KDE, the disabled
// color roles are calculated by applying various effects described in kdeglobals.
@@ -497,6 +500,11 @@ QPlatformTheme *QKdeTheme::createKdeTheme()
if (kdeVersion < 4)
return 0;
+ if (kdeVersion > 4)
+ // Plasma 5 follows XDG spec
+ // but uses the same config file format:
+ return new QKdeTheme(QStandardPaths::standardLocations(QStandardPaths::GenericConfigLocation), kdeVersion);
+
// Determine KDE prefixes in the following priority order:
// - KDEHOME and KDEDIRS environment variables
// - ~/.kde(<version>)
@@ -678,7 +686,7 @@ QPlatformTheme *QGenericUnixTheme::createUnixTheme(const QString &name)
#endif
if (name == QLatin1String(QGnomeTheme::name))
return new QGnomeTheme;
- return new QGenericUnixTheme;
+ return Q_NULLPTR;
}
QStringList QGenericUnixTheme::themeNames()
@@ -710,8 +718,7 @@ QStringList QGenericUnixTheme::themeNames()
if (!session.isEmpty() && session != QLatin1String("default") && !result.contains(session))
result.push_back(session);
} // desktopSettingsAware
- if (result.isEmpty())
- result.push_back(QLatin1String(QGenericUnixTheme::name));
+ result.append(QLatin1String(QGenericUnixTheme::name));
return result;
}
diff --git a/src/plugins/bearer/connman/main.cpp b/src/plugins/bearer/connman/main.cpp
index a84121e89b..f1e9d763a7 100644
--- a/src/plugins/bearer/connman/main.cpp
+++ b/src/plugins/bearer/connman/main.cpp
@@ -36,7 +36,6 @@
#include <QtCore/qdebug.h>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -78,4 +77,3 @@ QT_END_NAMESPACE
#include "main.moc"
#endif
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/connman/qconnmanengine.cpp b/src/plugins/bearer/connman/qconnmanengine.cpp
index 7911857ff5..b7cc5f949c 100644
--- a/src/plugins/bearer/connman/qconnmanengine.cpp
+++ b/src/plugins/bearer/connman/qconnmanengine.cpp
@@ -46,7 +46,6 @@
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -122,8 +121,10 @@ QList<QNetworkConfigurationPrivate *> QConnmanEngine::getConfigurations()
QMutexLocker locker(&mutex);
QList<QNetworkConfigurationPrivate *> fetchedConfigurations;
QNetworkConfigurationPrivate* cpPriv = 0;
+ const int numFoundConfigurations = foundConfigurations.count();
+ fetchedConfigurations.reserve(numFoundConfigurations);
- for (int i = 0; i < foundConfigurations.count(); ++i) {
+ for (int i = 0; i < numFoundConfigurations; ++i) {
QNetworkConfigurationPrivate *config = new QNetworkConfigurationPrivate;
cpPriv = foundConfigurations.at(i);
@@ -556,4 +557,3 @@ void QConnmanEngine::reEvaluateCellular()
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/connman/qconnmanengine.h b/src/plugins/bearer/connman/qconnmanengine.h
index 2c1f5490e3..8c79b22bf9 100644
--- a/src/plugins/bearer/connman/qconnmanengine.h
+++ b/src/plugins/bearer/connman/qconnmanengine.h
@@ -53,7 +53,6 @@
#include <QMap>
#include <QVariant>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -135,7 +134,6 @@ protected:
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
#endif
diff --git a/src/plugins/bearer/connman/qconnmanservice_linux.cpp b/src/plugins/bearer/connman/qconnmanservice_linux.cpp
index 155e6970fa..10d8285a4a 100644
--- a/src/plugins/bearer/connman/qconnmanservice_linux.cpp
+++ b/src/plugins/bearer/connman/qconnmanservice_linux.cpp
@@ -45,7 +45,6 @@
#include "qconnmanservice_linux_p.h"
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -175,11 +174,10 @@ void QConnmanManagerInterface::connectNotify(const QMetaMethod &signal)
void QConnmanManagerInterface::onServicesChanged(const ConnmanMapList &changed, const QList<QDBusObjectPath> &removed)
{
- ConnmanMap connmanobj;
servicesList.clear(); //connman list changes order
- Q_FOREACH (connmanobj, changed) {
+ Q_FOREACH (const ConnmanMap &connmanobj, changed) {
const QString svcPath(connmanobj.objectPath.path());
- servicesList << svcPath;
+ servicesList << svcPath;
}
Q_EMIT servicesChanged(changed, removed);
@@ -221,7 +219,7 @@ QStringList QConnmanManagerInterface::getTechnologies()
QDBusPendingReply<ConnmanMapList> reply = call(QLatin1String("GetTechnologies"));
reply.waitForFinished();
if (!reply.isError()) {
- Q_FOREACH (ConnmanMap map, reply.value()) {
+ Q_FOREACH (const ConnmanMap &map, reply.value()) {
if (!technologiesMap.contains(map.objectPath.path())) {
technologyAdded(map.objectPath, map.propertyMap);
}
@@ -237,7 +235,7 @@ QStringList QConnmanManagerInterface::getServices()
QDBusPendingReply<ConnmanMapList> reply = call(QLatin1String("GetServices"));
reply.waitForFinished();
if (!reply.isError()) {
- Q_FOREACH (ConnmanMap map, reply.value()) {
+ Q_FOREACH (const ConnmanMap &map, reply.value()) {
servicesList << map.objectPath.path();
}
}
@@ -504,5 +502,3 @@ void QConnmanTechnologyInterface::scanReply(QDBusPendingCallWatcher *call)
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
-
diff --git a/src/plugins/bearer/connman/qconnmanservice_linux_p.h b/src/plugins/bearer/connman/qconnmanservice_linux_p.h
index 49ca9f391c..1a10a2260a 100644
--- a/src/plugins/bearer/connman/qconnmanservice_linux_p.h
+++ b/src/plugins/bearer/connman/qconnmanservice_linux_p.h
@@ -58,7 +58,6 @@
#include <QtDBus/QDBusContext>
#include <QMap>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
#ifndef __CONNMAN_DBUS_H
@@ -219,6 +218,5 @@ private:
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
#endif //QCONNMANSERVICE_H
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm
index eb756db39e..6d16b59d35 100644
--- a/src/plugins/bearer/corewlan/qcorewlanengine.mm
+++ b/src/plugins/bearer/corewlan/qcorewlanengine.mm
@@ -77,12 +77,11 @@ extern "C" { // Otherwise it won't find CWKeychain* symbols at link time
- (id) init
{
[locker lock];
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
notificationCenter = [NSNotificationCenter defaultCenter];
currentInterface = [CWInterface interfaceWithName:nil];
[notificationCenter addObserver:self selector:@selector(notificationHandler:) name:CWPowerDidChangeNotification object:nil];
[locker unlock];
- [autoreleasepool release];
return self;
}
@@ -154,7 +153,7 @@ void QScanThread::quit()
void QScanThread::run()
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QStringList found;
mutex.lock();
CWInterface *currentInterface = [CWInterface interfaceWithName: QCFString::toNSString(interfaceName)];
@@ -236,7 +235,6 @@ void QScanThread::run()
}
}
emit networksChanged();
- [autoreleasepool release];
}
QStringList QScanThread::foundNetwork(const QString &id, const QString &name, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose)
@@ -276,7 +274,7 @@ void QScanThread::getUserConfigurations()
{
QMutexLocker locker(&mutex);
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
userProfiles.clear();
NSSet *wifiInterfaces = [CWInterface interfaceNames];
@@ -357,7 +355,6 @@ void QScanThread::getUserConfigurations()
}
}
}
- [autoreleasepool release];
}
QString QScanThread::getSsidFromNetworkName(const QString &name)
@@ -436,7 +433,7 @@ QCoreWlanEngine::~QCoreWlanEngine()
void QCoreWlanEngine::initialize()
{
QMutexLocker locker(&mutex);
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
if ([[CWInterface interfaceNames] count] > 0 && !listener) {
listener = [[QT_MANGLE_NAMESPACE(QNSListener) alloc] init];
@@ -448,7 +445,6 @@ void QCoreWlanEngine::initialize()
storeSession = NULL;
startNetworkChangeLoop();
- [autoreleasepool release];
}
@@ -469,7 +465,7 @@ bool QCoreWlanEngine::hasIdentifier(const QString &id)
void QCoreWlanEngine::connectToId(const QString &id)
{
QMutexLocker locker(&mutex);
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QString interfaceString = getInterfaceFromId(id);
CWInterface *wifiInterface =
@@ -541,7 +537,6 @@ void QCoreWlanEngine::connectToId(const QString &id)
locker.unlock();
emit connectionError(id, InterfaceLookupError);
- [autoreleasepool release];
}
void QCoreWlanEngine::disconnectFromId(const QString &id)
@@ -554,7 +549,7 @@ void QCoreWlanEngine::disconnectFromId(const QString &id)
emit connectionError(id, DisconnectionError);
return;
}
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
CWInterface *wifiInterface =
[CWInterface interfaceWithName: QCFString::toNSString(interfaceString)];
@@ -563,14 +558,13 @@ void QCoreWlanEngine::disconnectFromId(const QString &id)
[wifiInterface disassociate];
QTimer::singleShot(1000, this,SLOT(checkDisconnect()));
- [autoreleasepool release];
}
void QCoreWlanEngine::checkDisconnect()
{
QMutexLocker locker(&mutex);
if (!disconnectedInterfaceString.isEmpty()) {
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
CWInterface *wifiInterface =
[CWInterface interfaceWithName: QCFString::toNSString(disconnectedInterfaceString)];
@@ -582,7 +576,6 @@ void QCoreWlanEngine::checkDisconnect()
emit connectionError(id, DisconnectionError);
locker.relock();
}
- [autoreleasepool release];
disconnectedInterfaceString.clear();
}
}
@@ -597,7 +590,7 @@ void QCoreWlanEngine::doRequestUpdate()
{
QMutexLocker locker(&mutex);
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
NSSet *wifiInterfaces = [CWInterface interfaceNames];
for (NSString *ifName in wifiInterfaces) {
@@ -607,7 +600,6 @@ void QCoreWlanEngine::doRequestUpdate()
locker.unlock();
if ([wifiInterfaces count] == 0)
networksChanged();
- [autoreleasepool release];
}
bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName)
@@ -615,12 +607,11 @@ bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName)
QMutexLocker locker(&mutex);
bool haswifi = false;
if(hasWifi) {
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
CWInterface *defaultInterface = [CWInterface interfaceWithName: QCFString::toNSString(wifiDeviceName)];
if (defaultInterface.powerOn) {
haswifi = true;
}
- [autoreleasepool release];
}
return haswifi;
}
@@ -814,7 +805,7 @@ quint64 QCoreWlanEngine::bytesReceived(const QString &id)
quint64 QCoreWlanEngine::startTime(const QString &identifier)
{
QMutexLocker locker(&mutex);
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
quint64 timestamp = 0;
NSString *filePath = @"/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist";
@@ -861,7 +852,6 @@ quint64 QCoreWlanEngine::startTime(const QString &identifier)
}
}
}
- [autoreleasepool release];
return timestamp;
}
diff --git a/src/plugins/bearer/generic/main.cpp b/src/plugins/bearer/generic/main.cpp
index 112c7420e1..4f79807128 100644
--- a/src/plugins/bearer/generic/main.cpp
+++ b/src/plugins/bearer/generic/main.cpp
@@ -37,8 +37,6 @@
#include <QtCore/qdebug.h>
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
class QGenericEnginePlugin : public QBearerEnginePlugin
@@ -72,5 +70,3 @@ QBearerEngine *QGenericEnginePlugin::create(const QString &key) const
QT_END_NAMESPACE
#include "main.moc"
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/generic/qgenericengine.cpp b/src/plugins/bearer/generic/qgenericengine.cpp
index e1b3d79b38..93b27f16f1 100644
--- a/src/plugins/bearer/generic/qgenericengine.cpp
+++ b/src/plugins/bearer/generic/qgenericengine.cpp
@@ -50,8 +50,10 @@
#ifdef Q_OS_WINCE
typedef ULONG NDIS_OID, *PNDIS_OID;
-#include <nuiouser.h>
-#endif
+# ifndef QT_NO_WINCE_NUIOUSER
+# include <nuiouser.h>
+# endif
+#endif // Q_OS_WINCE
#ifdef Q_OS_LINUX
#include <sys/socket.h>
@@ -61,8 +63,6 @@ typedef ULONG NDIS_OID, *PNDIS_OID;
#include <unistd.h>
#endif
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
#ifndef QT_NO_NETWORKINTERFACE
@@ -73,7 +73,7 @@ static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interf
NDIS_MEDIUM medium;
NDIS_PHYSICAL_MEDIUM physicalMedium;
-#ifdef Q_OS_WINCE
+#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
NDISUIO_QUERY_OID nicGetOid;
HANDLE handle = CreateFile((PTCHAR)NDISUIO_DEVICE_NAME, 0,
FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
@@ -87,7 +87,7 @@ static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interf
bytesWritten = 0;
-#ifdef Q_OS_WINCE
+#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
ZeroMemory(&nicGetOid, sizeof(NDISUIO_QUERY_OID));
nicGetOid.Oid = OID_GEN_MEDIA_SUPPORTED;
nicGetOid.ptcDeviceName = (PTCHAR)interface.utf16();
@@ -105,7 +105,7 @@ static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interf
bytesWritten = 0;
-#ifdef Q_OS_WINCE
+#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
medium = NDIS_MEDIUM( *(LPDWORD)nicGetOid.Data );
ZeroMemory(&nicGetOid, sizeof(NDISUIO_QUERY_OID));
@@ -385,5 +385,3 @@ bool QGenericEngine::requiresPolling() const
}
QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/generic/qgenericengine.h b/src/plugins/bearer/generic/qgenericengine.h
index 9acd6c4c2e..4b99c90051 100644
--- a/src/plugins/bearer/generic/qgenericengine.h
+++ b/src/plugins/bearer/generic/qgenericengine.h
@@ -39,8 +39,6 @@
#include <QMap>
#include <QTimer>
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
class QNetworkConfigurationPrivate;
@@ -82,7 +80,5 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_BEARERMANAGEMENT
-
#endif
diff --git a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp b/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
index 6e427544fa..e9e91f9855 100644
--- a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
+++ b/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
@@ -45,7 +45,6 @@
#include "qofonoservice_linux_p.h"
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QDBusArgument &operator<<(QDBusArgument &argument, const ObjectPathProperties &item)
@@ -98,7 +97,7 @@ QStringList QOfonoManagerInterface::getModems()
QDBusPendingReply<PathPropertiesList> reply = callWithArgumentList(QDBus::Block, QLatin1String("GetModems"), argumentList);
reply.waitForFinished();
if (!reply.isError()) {
- foreach (ObjectPathProperties modem, reply.value()) {
+ foreach (const ObjectPathProperties &modem, reply.value()) {
modemList << modem.path.path();
}
}
@@ -261,7 +260,7 @@ QStringList QOfonoDataConnectionManagerInterface::contexts()
QDBusPendingReply<PathPropertiesList > reply = call(QLatin1String("GetContexts"));
reply.waitForFinished();
if (!reply.isError()) {
- foreach (ObjectPathProperties context, reply.value()) {
+ foreach (const ObjectPathProperties &context, reply.value()) {
contextList << context.path.path();
}
}
@@ -382,4 +381,3 @@ QString QOfonoConnectionContextInterface::name()
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/linux_common/qofonoservice_linux_p.h b/src/plugins/bearer/linux_common/qofonoservice_linux_p.h
index b051b8feaa..57ea089ec8 100644
--- a/src/plugins/bearer/linux_common/qofonoservice_linux_p.h
+++ b/src/plugins/bearer/linux_common/qofonoservice_linux_p.h
@@ -57,7 +57,6 @@
#include <QtDBus/QDBusContext>
#include <QMap>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
#define OFONO_SERVICE "org.ofono"
@@ -193,6 +192,5 @@ private slots:
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
#endif //QOFONOSERVICE_H
diff --git a/src/plugins/bearer/networkmanager/main.cpp b/src/plugins/bearer/networkmanager/main.cpp
index 8a872cf08f..0d22846c44 100644
--- a/src/plugins/bearer/networkmanager/main.cpp
+++ b/src/plugins/bearer/networkmanager/main.cpp
@@ -37,7 +37,6 @@
#include <QtCore/qdebug.h>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -77,4 +76,3 @@ QT_END_NAMESPACE
#include "main.moc"
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
index e662d5f2d3..7258877eb7 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
@@ -49,7 +49,6 @@
#include <QDBusReply>
#include "../linux_common/qofonoservice_linux_p.h"
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -1129,4 +1128,3 @@ void QNetworkManagerEngine::ofonoUnRegistered(const QString &)
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
index 3d90fcd0e5..1f578890dc 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
@@ -54,7 +54,6 @@
#include <QMap>
#include <QVariant>
-#ifndef QT_NO_BEARERMANAGEMENT
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
@@ -150,7 +149,6 @@ private:
QT_END_NAMESPACE
#endif // QT_NO_DBUS
-#endif // QT_NO_BEARERMANAGEMENT
#endif
diff --git a/src/plugins/bearer/qbearerengine_impl.h b/src/plugins/bearer/qbearerengine_impl.h
index 6db4d8c6b2..a343474f2c 100644
--- a/src/plugins/bearer/qbearerengine_impl.h
+++ b/src/plugins/bearer/qbearerengine_impl.h
@@ -36,8 +36,6 @@
#include <QtNetwork/private/qbearerengine_p.h>
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
class QBearerEngineImpl : public QBearerEngine
@@ -74,6 +72,4 @@ QT_END_NAMESPACE
Q_DECLARE_METATYPE(QBearerEngineImpl::ConnectionError)
-#endif // QT_NO_BEARERMANAGEMENT
-
#endif // QBEARERENGINE_IMPL_H
diff --git a/src/plugins/bearer/qnetworksession_impl.cpp b/src/plugins/bearer/qnetworksession_impl.cpp
index f3f3729504..5e9e5e7015 100644
--- a/src/plugins/bearer/qnetworksession_impl.cpp
+++ b/src/plugins/bearer/qnetworksession_impl.cpp
@@ -42,8 +42,6 @@
#include <QtCore/qmutex.h>
#include <QtCore/qstringlist.h>
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
static QBearerEngineImpl *getEngineFromId(const QString &id)
@@ -423,5 +421,3 @@ void QNetworkSessionPrivateImpl::decrementTimeout()
}
QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/qnetworksession_impl.h b/src/plugins/bearer/qnetworksession_impl.h
index 87a2b29bd4..a26b05ab3b 100644
--- a/src/plugins/bearer/qnetworksession_impl.h
+++ b/src/plugins/bearer/qnetworksession_impl.h
@@ -50,8 +50,6 @@
#include <QtNetwork/private/qnetworkconfigmanager_p.h>
#include <QtNetwork/private/qnetworksession_p.h>
-#ifndef QT_NO_BEARERMANAGEMENT
-
QT_BEGIN_NAMESPACE
class QBearerEngineImpl;
@@ -123,6 +121,4 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_BEARERMANAGEMENT
-
#endif // QNETWORKSESSION_IMPL_H
diff --git a/src/plugins/generic/tuiotouch/qtuiohandler.cpp b/src/plugins/generic/tuiotouch/qtuiohandler.cpp
index 5211ed8381..dd161570e8 100644
--- a/src/plugins/generic/tuiotouch/qtuiohandler.cpp
+++ b/src/plugins/generic/tuiotouch/qtuiohandler.cpp
@@ -317,6 +317,7 @@ void QTuioHandler::process2DCurFseq(const QOscMessage &message)
return;
QList<QWindowSystemInterface::TouchPoint> tpl;
+ tpl.reserve(m_activeCursors.size() + m_deadCursors.size());
foreach (const QTuioCursor &tc, m_activeCursors) {
QWindowSystemInterface::TouchPoint tp = cursorToTouchPoint(tc, win);
diff --git a/src/plugins/imageformats/gif/main.cpp b/src/plugins/imageformats/gif/main.cpp
index 8181900adb..62c4f4b597 100644
--- a/src/plugins/imageformats/gif/main.cpp
+++ b/src/plugins/imageformats/gif/main.cpp
@@ -34,8 +34,6 @@
#include <qimageiohandler.h>
#include <qstringlist.h>
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
#include "main.h"
#ifdef QT_NO_IMAGEFORMAT_GIF
@@ -69,6 +67,4 @@ QImageIOHandler *QGifPlugin::create(QIODevice *device, const QByteArray &format)
return handler;
}
-#endif // QT_NO_IMAGEFORMATPLUGIN
-
QT_END_NAMESPACE
diff --git a/src/plugins/imageformats/gif/main.h b/src/plugins/imageformats/gif/main.h
index 1b02d5eaf6..56e0655b1f 100644
--- a/src/plugins/imageformats/gif/main.h
+++ b/src/plugins/imageformats/gif/main.h
@@ -34,8 +34,6 @@
#include <qimageiohandler.h>
#include <qstringlist.h>
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
#ifdef QT_NO_IMAGEFORMAT_GIF
#undef QT_NO_IMAGEFORMAT_GIF
#endif
@@ -56,5 +54,3 @@ public:
};
QT_END_NAMESPACE
-
-#endif // QT_NO_IMAGEFORMATPLUGIN
diff --git a/src/plugins/imageformats/ico/main.cpp b/src/plugins/imageformats/ico/main.cpp
index 80182fb665..03448d4ae1 100644
--- a/src/plugins/imageformats/ico/main.cpp
+++ b/src/plugins/imageformats/ico/main.cpp
@@ -33,8 +33,6 @@
#include "main.h"
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
QT_BEGIN_NAMESPACE
QImageIOPlugin::Capabilities QICOPlugin::capabilities(QIODevice *device, const QByteArray &format) const
@@ -63,5 +61,3 @@ QImageIOHandler *QICOPlugin::create(QIODevice *device, const QByteArray &format)
}
QT_END_NAMESPACE
-
-#endif /* QT_NO_IMAGEFORMATPLUGIN */
diff --git a/src/plugins/imageformats/ico/main.h b/src/plugins/imageformats/ico/main.h
index a254a626d1..d17dbe824d 100644
--- a/src/plugins/imageformats/ico/main.h
+++ b/src/plugins/imageformats/ico/main.h
@@ -34,8 +34,6 @@
#include <qimageiohandler.h>
#include <qdebug.h>
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
#ifdef QT_NO_IMAGEFORMAT_ICO
#undef QT_NO_IMAGEFORMAT_ICO
#endif
@@ -53,5 +51,3 @@ public:
};
QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/imageformats/ico/qicohandler.cpp b/src/plugins/imageformats/ico/qicohandler.cpp
index 4cb5e22bf7..2ddbc4519b 100644
--- a/src/plugins/imageformats/ico/qicohandler.cpp
+++ b/src/plugins/imageformats/ico/qicohandler.cpp
@@ -96,9 +96,9 @@ public:
QImage iconAt(int index);
static bool canRead(QIODevice *iodev);
- static QList<QImage> read(QIODevice * device);
+ static QVector<QImage> read(QIODevice *device);
- static bool write(QIODevice * device, const QList<QImage> & images);
+ static bool write(QIODevice *device, const QVector<QImage> &images);
private:
bool readHeader();
@@ -612,12 +612,14 @@ QImage ICOReader::iconAt(int index)
\sa write()
*/
-QList<QImage> ICOReader::read(QIODevice * device)
+QVector<QImage> ICOReader::read(QIODevice *device)
{
- QList<QImage> images;
+ QVector<QImage> images;
ICOReader reader(device);
- for (int i = 0; i < reader.count(); i++)
+ const int N = reader.count();
+ images.reserve(N);
+ for (int i = 0; i < N; i++)
images += reader.iconAt(i);
return images;
@@ -636,7 +638,7 @@ QList<QImage> ICOReader::read(QIODevice * device)
\sa read()
*/
-bool ICOReader::write(QIODevice * device, const QList<QImage> & images)
+bool ICOReader::write(QIODevice *device, const QVector<QImage> &images)
{
bool retValue = false;
@@ -849,7 +851,7 @@ bool QtIcoHandler::read(QImage *image)
bool QtIcoHandler::write(const QImage &image)
{
QIODevice *device = QImageIOHandler::device();
- QList<QImage> imgs;
+ QVector<QImage> imgs;
imgs.append(image);
return ICOReader::write(device, imgs);
}
diff --git a/src/plugins/imageformats/jpeg/main.cpp b/src/plugins/imageformats/jpeg/main.cpp
index d009707fa0..c8a575cb43 100644
--- a/src/plugins/imageformats/jpeg/main.cpp
+++ b/src/plugins/imageformats/jpeg/main.cpp
@@ -33,8 +33,6 @@
#include "main.h"
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
#ifdef QT_NO_IMAGEFORMAT_JPEG
#undef QT_NO_IMAGEFORMAT_JPEG
#endif
@@ -68,5 +66,3 @@ QImageIOHandler *QJpegPlugin::create(QIODevice *device, const QByteArray &format
}
QT_END_NAMESPACE
-
-#endif // QT_NO_IMAGEFORMATPLUGIN
diff --git a/src/plugins/imageformats/jpeg/main.h b/src/plugins/imageformats/jpeg/main.h
index 2d79c84666..77ee33faca 100644
--- a/src/plugins/imageformats/jpeg/main.h
+++ b/src/plugins/imageformats/jpeg/main.h
@@ -34,8 +34,6 @@
#include <qimageiohandler.h>
#include <qstringlist.h>
-#ifndef QT_NO_IMAGEFORMATPLUGIN
-
#ifdef QT_NO_IMAGEFORMAT_JPEG
#undef QT_NO_IMAGEFORMAT_JPEG
#endif
@@ -52,5 +50,3 @@ public:
};
QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/platforminputcontexts/compose/compose.pro b/src/plugins/platforminputcontexts/compose/compose.pro
index a9da36c473..a4b5280e64 100644
--- a/src/plugins/platforminputcontexts/compose/compose.pro
+++ b/src/plugins/platforminputcontexts/compose/compose.pro
@@ -5,7 +5,7 @@ PLUGIN_EXTENDS = -
PLUGIN_CLASS_NAME = QComposePlatformInputContextPlugin
load(qt_plugin)
-QT += gui-private
+QT += core-private gui-private
DEFINES += X11_PREFIX='\\"$$QMAKE_X11_PREFIX\\"'
diff --git a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
index 65020eb848..ad9877eb25 100644
--- a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
+++ b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
@@ -36,8 +36,12 @@
#include <QtCore/QByteArray>
#include <QtCore/QTextCodec>
#include <QtCore/QDebug>
+#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtCore/QString>
+#include <QtCore/QSaveFile>
+#include <QtCore/QStandardPaths>
+#include <private/qcore_unix_p.h>
#include <algorithm>
@@ -48,12 +52,191 @@
#include <strings.h> // strncasecmp
#include <clocale> // LC_CTYPE
+static const quint32 SupportedCacheVersion = 1;
+
+/*
+ In short on how and why the "Compose" file is cached:
+
+ The "Compose" file is large, for en_US it's likely located at:
+ /usr/share/X11/locale/en_US.UTF-8/Compose
+ and it has about 6000 string lines.
+ Q(Gui)Applications parse this file each time they're created. On modern CPUs
+ it incurs a 4-10 ms startup penalty of each Qt gui app, on older CPUs -
+ tens of ms or more.
+ Since the "Compose" file (almost) never changes using a pre-parsed
+ cache file instead of the "Compose" file is a good idea to improve Qt5
+ application startup time by about 5+ ms (or tens of ms on older CPUs).
+
+ The cache file contains the contents of the QComposeCacheFileHeader struct at the
+ beginning followed by the pre-parsed contents of the "Compose" file.
+
+ struct QComposeCacheFileHeader stores
+ (a) The cache version - in the unlikely event that some day one might need
+ to break compatibility.
+ (b) The (cache) file size.
+ (c) The lastModified field tracks if anything changed since the last time
+ the cache file was saved.
+ If anything did change then we read the compose file and save (cache) it
+ in binary/pre-parsed format, which should happen extremely rarely if at all.
+*/
+
+struct QComposeCacheFileHeader
+{
+ quint32 cacheVersion;
+ // The compiler will add 4 padding bytes anyway.
+ // Reserve them explicitly to possibly use in the future.
+ quint32 reserved;
+ quint64 fileSize;
+ qint64 lastModified;
+};
+
+// localHostName() copied from qtbase/src/corelib/io/qlockfile_unix.cpp
+static QByteArray localHostName()
+{
+ QByteArray hostName(512, Qt::Uninitialized);
+ if (gethostname(hostName.data(), hostName.size()) == -1)
+ return QByteArray();
+ hostName.truncate(strlen(hostName.data()));
+ return hostName;
+}
+
+/*
+ Reads metadata about the Compose file. Later used to determine if the
+ compose cache should be updated. The fileSize field will be zero on failure.
+*/
+static QComposeCacheFileHeader readFileMetadata(const QString &path)
+{
+ QComposeCacheFileHeader info;
+ info.reserved = 0;
+ info.fileSize = 0;
+ const QByteArray pathBytes = QFile::encodeName(path);
+ QT_STATBUF st;
+ if (QT_STAT(pathBytes.data(), &st) != 0)
+ return info;
+ info.lastModified = st.st_mtime;
+ info.fileSize = st.st_size;
+ return info;
+}
+
+static const QString getCacheFilePath()
+{
+ QFile machineIdFile("/var/lib/dbus/machine-id");
+ QString machineId;
+ if (machineIdFile.exists()) {
+ if (machineIdFile.open(QIODevice::ReadOnly))
+ machineId = QString::fromLatin1(machineIdFile.readAll().trimmed());
+ }
+ if (machineId.isEmpty())
+ machineId = localHostName();
+ const QString dirPath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
+
+ if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
+ return dirPath + QLatin1String("/qt_compose_cache_big_endian_") + machineId;
+ return dirPath + QLatin1String("/qt_compose_cache_little_endian_") + machineId;
+}
+
+// Returns empty vector on failure
+static QVector<QComposeTableElement> loadCache(const QComposeCacheFileHeader &composeInfo)
+{
+ QVector<QComposeTableElement> vec;
+ const QString cacheFilePath = getCacheFilePath();
+ QFile inputFile(cacheFilePath);
+
+ if (!inputFile.open(QIODevice::ReadOnly))
+ return vec;
+ QComposeCacheFileHeader cacheInfo;
+ // use a "buffer" variable to make the line after this one more readable.
+ char *buffer = reinterpret_cast<char*>(&cacheInfo);
+
+ if (inputFile.read(buffer, sizeof cacheInfo) != sizeof cacheInfo)
+ return vec;
+ if (cacheInfo.fileSize == 0)
+ return vec;
+ // using "!=" just in case someone replaced with a backup that existed before
+ if (cacheInfo.lastModified != composeInfo.lastModified)
+ return vec;
+ if (cacheInfo.cacheVersion != SupportedCacheVersion)
+ return vec;
+ const QByteArray pathBytes = QFile::encodeName(cacheFilePath);
+ QT_STATBUF st;
+ if (QT_STAT(pathBytes.data(), &st) != 0)
+ return vec;
+ const off_t fileSize = st.st_size;
+ if (fileSize > 1024 * 1024 * 5) {
+ // The cache file size is usually about 150KB, so if its size is over
+ // say 5MB then somebody inflated the file, abort.
+ return vec;
+ }
+ const off_t bufferSize = fileSize - (sizeof cacheInfo);
+ const size_t elemSize = sizeof (struct QComposeTableElement);
+ const int elemCount = bufferSize / elemSize;
+ const QByteArray ba = inputFile.read(bufferSize);
+ const char *data = ba.data();
+ // Since we know the number of the (many) elements and their size in
+ // advance calling vector.reserve(..) seems reasonable.
+ vec.reserve(elemCount);
+
+ for (int i = 0; i < elemCount; i++) {
+ const QComposeTableElement *elem =
+ reinterpret_cast<const QComposeTableElement*>(data + (i * elemSize));
+ vec.push_back(*elem);
+ }
+ return vec;
+}
+
+// Returns true on success, false otherwise.
+static bool saveCache(const QComposeCacheFileHeader &info, const QVector<QComposeTableElement> &vec)
+{
+ const QString filePath = getCacheFilePath();
+ QSaveFile outputFile(filePath);
+
+ if (!outputFile.open(QIODevice::WriteOnly))
+ return false;
+ const char *data = reinterpret_cast<const char*>(&info);
+
+ if (outputFile.write(data, sizeof info) != sizeof info)
+ return false;
+ data = reinterpret_cast<const char*>(vec.constData());
+ const qint64 size = vec.size() * (sizeof (struct QComposeTableElement));
+
+ if (outputFile.write(data, size) != size)
+ return false;
+ return outputFile.commit();
+}
+
TableGenerator::TableGenerator() : m_state(NoErrors),
m_systemComposeDir(QString())
{
initPossibleLocations();
- findComposeFile();
- orderComposeTable();
+ QString composeFilePath = findComposeFile();
+#ifdef DEBUG_GENERATOR
+// don't use cache when in debug mode.
+ if (!composeFilePath.isEmpty())
+ qDebug() << "Using Compose file from: " << composeFilePath;
+#else
+ QComposeCacheFileHeader fileInfo = readFileMetadata(composeFilePath);
+ if (fileInfo.fileSize != 0)
+ m_composeTable = loadCache(fileInfo);
+#endif
+ if (m_composeTable.isEmpty() && cleanState()) {
+ if (composeFilePath.isEmpty()) {
+ m_state = MissingComposeFile;
+ } else {
+ QFile composeFile(composeFilePath);
+ composeFile.open(QIODevice::ReadOnly);
+ parseComposeFile(&composeFile);
+ orderComposeTable();
+ if (m_composeTable.isEmpty()) {
+ m_state = EmptyTable;
+#ifndef DEBUG_GENERATOR
+// don't save cache when in debug mode
+ } else {
+ fileInfo.cacheVersion = SupportedCacheVersion;
+ saveCache(fileInfo, m_composeTable);
+#endif
+ }
+ }
+ }
#ifdef DEBUG_GENERATOR
printComposeTable();
#endif
@@ -76,53 +259,39 @@ void TableGenerator::initPossibleLocations()
m_possibleLocations.append(QStringLiteral(X11_PREFIX "/lib/X11/locale"));
}
-void TableGenerator::findComposeFile()
+QString TableGenerator::findComposeFile()
{
- bool found = false;
// check if XCOMPOSEFILE points to a Compose file
if (qEnvironmentVariableIsSet("XCOMPOSEFILE")) {
- QString composeFile(qgetenv("XCOMPOSEFILE"));
- if (composeFile.endsWith(QLatin1String("Compose")))
- found = processFile(composeFile);
+ QString path(qgetenv("XCOMPOSEFILE"));
+ if (path.endsWith(QLatin1String("Compose")))
+ return path;
else
qWarning("Qt Warning: XCOMPOSEFILE doesn't point to a valid Compose file");
-#ifdef DEBUG_GENERATOR
- if (found)
- qDebug() << "Using Compose file from: " << composeFile;
-#endif
}
+
// check if user’s home directory has a file named .XCompose
- if (!found && cleanState()) {
- QString composeFile = qgetenv("HOME") + QStringLiteral("/.XCompose");
- if (QFile(composeFile).exists())
- found = processFile(composeFile);
-#ifdef DEBUG_GENERATOR
- if (found)
- qDebug() << "Using Compose file from: " << composeFile;
-#endif
+ if (cleanState()) {
+ QString path = qgetenv("HOME") + QStringLiteral("/.XCompose");
+ if (QFile(path).exists())
+ return path;
}
+
// check for the system provided compose files
- if (!found && cleanState()) {
+ if (cleanState()) {
QString table = composeTableForLocale();
if (cleanState()) {
if (table.isEmpty())
// no table mappings for the system's locale in the compose.dir
m_state = UnsupportedLocale;
- else
- found = processFile(systemComposeDir() + QLatin1Char('/') + table);
-#ifdef DEBUG_GENERATOR
- if (found)
- qDebug() << "Using Compose file from: " <<
- systemComposeDir() + QLatin1Char('/') + table;
-#endif
+ else {
+ QString path = QDir(systemComposeDir()).filePath(table);
+ if (QFile(path).exists())
+ return path;
+ }
}
}
-
- if (found && m_composeTable.isEmpty())
- m_state = EmptyTable;
-
- if (!found)
- m_state = MissingComposeFile;
+ return QString();
}
QString TableGenerator::composeTableForLocale()
diff --git a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
index 468da4cad1..8ad081bea5 100644
--- a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
+++ b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
@@ -43,6 +43,8 @@
//#define DEBUG_GENERATOR
+/* Whenever QComposeTableElement gets modified supportedCacheVersion
+ from qtablegenerator.cpp must be bumped. */
struct QComposeTableElement {
uint keys[QT_KEYSEQUENCE_MAX_LEN];
uint value;
@@ -107,7 +109,7 @@ protected:
void parseKeySequence(char *line);
void parseIncludeInstruction(QString line);
- void findComposeFile();
+ QString findComposeFile();
bool findSystemComposeDir();
QString systemComposeDir();
QString composeTableForLocale();
diff --git a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
index 673942b5d9..27fca7c6ed 100644
--- a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
+++ b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
@@ -39,6 +39,10 @@
#include <qwindow.h>
#include <qevent.h>
+#include <qpa/qplatformcursor.h>
+#include <qpa/qplatformscreen.h>
+#include <qpa/qwindowsysteminterface.h>
+
#include "qibusproxy.h"
#include "qibusinputcontextproxy.h"
#include "qibustypes.h"
@@ -48,8 +52,14 @@
#include <QtDBus>
+#ifndef IBUS_RELEASE_MASK
+#define IBUS_RELEASE_MASK (1 << 30)
+#endif
+
QT_BEGIN_NAMESPACE
+Q_LOGGING_CATEGORY(qtQpaInputMethods, "qt.qpa.input.methods")
+
enum { debug = 0 };
class QIBusPlatformInputContextPrivate
@@ -86,6 +96,13 @@ QIBusPlatformInputContext::QIBusPlatformInputContext ()
}
QInputMethod *p = qApp->inputMethod();
connect(p, SIGNAL(cursorRectangleChanged()), this, SLOT(cursorRectChanged()));
+ m_eventFilterUseSynchronousMode = false;
+ if (qEnvironmentVariableIsSet("IBUS_ENABLE_SYNC_MODE")) {
+ bool ok;
+ int enableSync = qgetenv("IBUS_ENABLE_SYNC_MODE").toInt(&ok);
+ if (ok && enableSync == 1)
+ m_eventFilterUseSynchronousMode = true;
+ }
}
QIBusPlatformInputContext::~QIBusPlatformInputContext (void)
@@ -272,8 +289,7 @@ void QIBusPlatformInputContext::deleteSurroundingText(int offset, uint n_chars)
QCoreApplication::sendEvent(input, &event);
}
-bool
-QIBusPlatformInputContext::x11FilterEvent(uint keyval, uint keycode, uint state, bool press)
+bool QIBusPlatformInputContext::filterEvent(const QEvent *event)
{
if (!d->valid)
return false;
@@ -281,15 +297,105 @@ QIBusPlatformInputContext::x11FilterEvent(uint keyval, uint keycode, uint state,
if (!inputMethodAccepted())
return false;
- if (!press)
- return false;
+ const QKeyEvent *keyEvent = static_cast<const QKeyEvent *>(event);
+ quint32 sym = keyEvent->nativeVirtualKey();
+ quint32 code = keyEvent->nativeScanCode();
+ quint32 state = keyEvent->nativeModifiers();
+ quint32 ibusState = state;
+
+ if (keyEvent->type() != QEvent::KeyPress)
+ ibusState |= IBUS_RELEASE_MASK;
+
+ QDBusPendingReply<bool> reply = d->context->ProcessKeyEvent(sym, code - 8, ibusState);
+
+ if (m_eventFilterUseSynchronousMode || reply.isFinished()) {
+ bool retval = reply.value();
+ qCDebug(qtQpaInputMethods) << "filterEvent return" << code << sym << state << retval;
+ return retval;
+ }
+
+ Qt::KeyboardModifiers modifiers = keyEvent->modifiers();
+ const int qtcode = keyEvent->key();
+
+ // From QKeyEvent::modifiers()
+ switch (qtcode) {
+ case Qt::Key_Shift:
+ modifiers ^= Qt::ShiftModifier;
+ break;
+ case Qt::Key_Control:
+ modifiers ^= Qt::ControlModifier;
+ break;
+ case Qt::Key_Alt:
+ modifiers ^= Qt::AltModifier;
+ break;
+ case Qt::Key_Meta:
+ modifiers ^= Qt::MetaModifier;
+ break;
+ case Qt::Key_AltGr:
+ modifiers ^= Qt::GroupSwitchModifier;
+ break;
+ }
+
+ QVariantList args;
+ args << QVariant::fromValue(keyEvent->timestamp());
+ args << QVariant::fromValue(static_cast<uint>(keyEvent->type()));
+ args << QVariant::fromValue(qtcode);
+ args << QVariant::fromValue(code) << QVariant::fromValue(sym) << QVariant::fromValue(state);
+ args << QVariant::fromValue(keyEvent->text());
+ args << QVariant::fromValue(keyEvent->isAutoRepeat());
- keycode -= 8; // ###
- QDBusReply<bool> reply = d->context->ProcessKeyEvent(keyval, keycode, state);
+ QIBusFilterEventWatcher *watcher = new QIBusFilterEventWatcher(reply, this, QGuiApplication::focusWindow(), modifiers, args);
+ QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &QIBusPlatformInputContext::filterEventFinished);
-// qDebug() << "x11FilterEvent return" << reply.value();
+ return true;
+}
+
+void QIBusPlatformInputContext::filterEventFinished(QDBusPendingCallWatcher *call)
+{
+ QIBusFilterEventWatcher *watcher = (QIBusFilterEventWatcher *) call;
+ QDBusPendingReply<bool> reply = *call;
+
+ if (reply.isError()) {
+ call->deleteLater();
+ return;
+ }
- return reply.value();
+ // Use watcher's window instead of the current focused window
+ // since there is a time lag until filterEventFinished() returns.
+ QWindow *window = watcher->window();
+
+ if (!window) {
+ call->deleteLater();
+ return;
+ }
+
+ Qt::KeyboardModifiers modifiers = watcher->modifiers();
+ QVariantList args = watcher->arguments();
+ const ulong time = static_cast<const ulong>(args.at(0).toUInt());
+ const QEvent::Type type = static_cast<const QEvent::Type>(args.at(1).toUInt());
+ const int qtcode = args.at(2).toInt();
+ const quint32 code = args.at(3).toUInt();
+ const quint32 sym = args.at(4).toUInt();
+ const quint32 state = args.at(5).toUInt();
+ const QString string = args.at(6).toString();
+ const bool isAutoRepeat = args.at(7).toBool();
+
+ // copied from QXcbKeyboard::handleKeyEvent()
+ bool retval = reply.value();
+ qCDebug(qtQpaInputMethods) << "filterEventFinished return" << code << sym << state << retval;
+ if (!retval) {
+ if (type == QEvent::KeyPress && qtcode == Qt::Key_Menu
+ && window != NULL) {
+ const QPoint globalPos = window->screen()->handle()->cursor()->pos();
+ const QPoint pos = window->mapFromGlobal(globalPos);
+ QWindowSystemInterface::handleContextMenuEvent(window, false, pos,
+ globalPos, modifiers);
+ }
+ QWindowSystemInterface::handleExtendedKeyEvent(window, time, type, qtcode, modifiers,
+ code, sym, state, string, isAutoRepeat);
+
+ }
+ call->deleteLater();
}
QIBusPlatformInputContextPrivate::QIBusPlatformInputContextPrivate()
@@ -340,7 +446,7 @@ QIBusPlatformInputContextPrivate::QIBusPlatformInputContextPrivate()
QDBusConnection *QIBusPlatformInputContextPrivate::createConnection()
{
- QByteArray display(getenv("DISPLAY"));
+ QByteArray display(qgetenv("DISPLAY"));
QByteArray host = "unix";
QByteArray displayNumber = "0";
diff --git a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
index 816da8d377..127db7df8b 100644
--- a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
+++ b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
@@ -35,11 +35,44 @@
#include <qpa/qplatforminputcontext.h>
+#include <QtCore/qpointer.h>
+#include <QtDBus/qdbuspendingreply.h>
+#include <QLoggingCategory>
+#include <QWindow>
+
QT_BEGIN_NAMESPACE
+Q_DECLARE_LOGGING_CATEGORY(qtQpaInputMethods)
+
class QIBusPlatformInputContextPrivate;
class QDBusVariant;
+class QIBusFilterEventWatcher: public QDBusPendingCallWatcher
+{
+public:
+ explicit QIBusFilterEventWatcher(const QDBusPendingCall &call,
+ QObject *parent = 0,
+ QWindow *window = 0,
+ const Qt::KeyboardModifiers modifiers = 0,
+ const QVariantList arguments = QVariantList())
+ : QDBusPendingCallWatcher(call, parent)
+ , m_window(window)
+ , m_modifiers(modifiers)
+ , m_arguments(arguments)
+ {}
+ ~QIBusFilterEventWatcher()
+ {}
+
+ inline QWindow *window() const { return m_window; }
+ inline const Qt::KeyboardModifiers modifiers() const { return m_modifiers; }
+ inline const QVariantList arguments() const { return m_arguments; }
+
+private:
+ QPointer<QWindow> m_window;
+ const Qt::KeyboardModifiers m_modifiers;
+ const QVariantList m_arguments;
+};
+
class QIBusPlatformInputContext : public QPlatformInputContext
{
Q_OBJECT
@@ -54,8 +87,7 @@ public:
void reset() Q_DECL_OVERRIDE;
void commit() Q_DECL_OVERRIDE;
void update(Qt::InputMethodQueries) Q_DECL_OVERRIDE;
-
- Q_INVOKABLE bool x11FilterEvent(uint keyval, uint keycode, uint state, bool press);
+ bool filterEvent(const QEvent *event) Q_DECL_OVERRIDE;
public Q_SLOTS:
void commitText(const QDBusVariant &text);
@@ -63,9 +95,11 @@ public Q_SLOTS:
void cursorRectChanged();
void deleteSurroundingText(int offset, uint n_chars);
void surroundingTextRequired();
+ void filterEventFinished(QDBusPendingCallWatcher *call);
private:
QIBusPlatformInputContextPrivate *d;
+ bool m_eventFilterUseSynchronousMode;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforminputcontexts/ibus/qibustypes.cpp b/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
index d6be6cbb31..f88e5ca5a3 100644
--- a/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
+++ b/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
@@ -225,9 +225,10 @@ const QDBusArgument &operator>>(const QDBusArgument &arg, QIBusAttributeList &at
QList<QInputMethodEvent::Attribute> QIBusAttributeList::imAttributes() const
{
QHash<QPair<int, int>, QTextCharFormat> rangeAttrs;
+ const int numAttributes = attributes.size();
// Merge text fomats for identical ranges into a single QTextFormat.
- for (int i = 0; i < attributes.size(); ++i) {
+ for (int i = 0; i < numAttributes; ++i) {
const QIBusAttribute &attr = attributes.at(i);
const QTextCharFormat &format = attr.format();
@@ -239,8 +240,9 @@ QList<QInputMethodEvent::Attribute> QIBusAttributeList::imAttributes() const
// Assemble list in original attribute order.
QList<QInputMethodEvent::Attribute> imAttrs;
+ imAttrs.reserve(numAttributes);
- for (int i = 0; i < attributes.size(); ++i) {
+ for (int i = 0; i < numAttributes; ++i) {
const QIBusAttribute &attr = attributes.at(i);
const QTextFormat &format = attr.format();
diff --git a/src/plugins/platforms/android/androidjniinput.cpp b/src/plugins/platforms/android/androidjniinput.cpp
index 8ee3ff88d1..b410e5f68e 100644
--- a/src/plugins/platforms/android/androidjniinput.cpp
+++ b/src/plugins/platforms/android/androidjniinput.cpp
@@ -70,18 +70,20 @@ namespace QtAndroidInput
candidatesEnd);
}
- void showSoftwareKeyboard(int left, int top, int width, int height, int inputHints)
+ void showSoftwareKeyboard(int left, int top, int width, int height, int inputHints, int enterKeyType)
{
QJNIObjectPrivate::callStaticMethod<void>(applicationClass(),
"showSoftwareKeyboard",
- "(IIIII)V",
+ "(IIIIII)V",
left,
top,
width,
height,
- inputHints);
+ inputHints,
+ enterKeyType
+ );
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
- qDebug() << "@@@ SHOWSOFTWAREKEYBOARD" << left << top << width << height << inputHints;
+ qDebug() << "@@@ SHOWSOFTWAREKEYBOARD" << left << top << width << height << inputHints << enterKeyType;
#endif
}
@@ -238,6 +240,52 @@ namespace QtAndroidInput
QWindowSystemInterface::handleTouchEvent(window, touchDevice, m_touchPoints);
}
+ static void tabletEvent(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint deviceId, jlong time, jint action,
+ jint pointerType, jint buttonState, jfloat x, jfloat y, jfloat pressure)
+ {
+ QPointF globalPosF(x, y);
+ QPoint globalPos((int)x, (int)y);
+ QWindow *tlw = topLevelWindowAt(globalPos);
+ QPointF localPos = tlw ? (globalPosF - tlw->position()) : globalPosF;
+
+ // Galaxy Note with plain Android:
+ // 0 1 0 stylus press
+ // 2 1 0 stylus drag
+ // 1 1 0 stylus release
+ // 0 1 2 stylus press with side-button held
+ // 2 1 2 stylus drag with side-button held
+ // 1 1 2 stylus release with side-button held
+ // Galaxy Note 4 with Samsung firmware:
+ // 0 1 0 stylus press
+ // 2 1 0 stylus drag
+ // 1 1 0 stylus release
+ // 211 1 2 stylus press with side-button held
+ // 213 1 2 stylus drag with side-button held
+ // 212 1 2 stylus release with side-button held
+ // when action == ACTION_UP (1) it's a release; otherwise we say which button is pressed
+ Qt::MouseButtons buttons = Qt::NoButton;
+ switch (action) {
+ case 1: // ACTION_UP
+ case 212: // stylus release while side-button held on Galaxy Note 4
+ buttons = Qt::NoButton;
+ break;
+ default: // action is press or drag
+ if (buttonState == 0)
+ buttons = Qt::LeftButton;
+ else // 2 means RightButton
+ buttons = Qt::MouseButtons(buttonState);
+ break;
+ }
+
+#ifdef QT_DEBUG_ANDROID_STYLUS
+ qDebug() << action << pointerType << buttonState << "@" << x << y << "pressure" << pressure << ": buttons" << buttons;
+#endif
+
+ QWindowSystemInterface::handleTabletEvent(tlw, ulong(time),
+ localPos, globalPosF, QTabletEvent::Stylus, pointerType,
+ buttons, pressure, 0, 0, 0., 0., 0, deviceId, Qt::NoModifier);
+ }
+
static int mapAndroidKey(int key)
{
// 0--9 0x00000007 -- 0x00000010
@@ -702,6 +750,7 @@ namespace QtAndroidInput
{"mouseUp", "(III)V", (void *)mouseUp},
{"mouseMove", "(III)V", (void *)mouseMove},
{"longPress", "(III)V", (void *)longPress},
+ {"tabletEvent", "(IIJIIIFFF)V", (void *)tabletEvent},
{"keyDown", "(IIIZ)V", (void *)keyDown},
{"keyUp", "(IIIZ)V", (void *)keyUp},
{"keyboardVisibilityChanged", "(Z)V", (void *)keyboardVisibilityChanged}
diff --git a/src/plugins/platforms/android/androidjniinput.h b/src/plugins/platforms/android/androidjniinput.h
index b5a2ef06e4..d737dc9c98 100644
--- a/src/plugins/platforms/android/androidjniinput.h
+++ b/src/plugins/platforms/android/androidjniinput.h
@@ -41,7 +41,7 @@ QT_BEGIN_NAMESPACE
namespace QtAndroidInput
{
// Software keyboard support
- void showSoftwareKeyboard(int top, int left, int width, int height, int inputHints);
+ void showSoftwareKeyboard(int top, int left, int width, int height, int inputHints, int enterKeyType);
void resetSoftwareKeyboard();
void hideSoftwareKeyboard();
bool isSoftwareKeyboardVisible();
diff --git a/src/plugins/platforms/android/androidjnimain.cpp b/src/plugins/platforms/android/androidjnimain.cpp
index a04bf1eccb..cd40b7eec2 100644
--- a/src/plugins/platforms/android/androidjnimain.cpp
+++ b/src/plugins/platforms/android/androidjnimain.cpp
@@ -600,6 +600,11 @@ static void updateApplicationState(JNIEnv */*env*/, jobject /*thiz*/, jint state
return;
}
+ if (state == Qt::ApplicationActive)
+ QtAndroidPrivate::handleResume();
+ else if (state == Qt::ApplicationInactive)
+ QtAndroidPrivate::handlePause();
+
if (state <= Qt::ApplicationInactive) {
// NOTE: sometimes we will receive two consecutive suspended notifications,
// In the second suspended notification, QWindowSystemInterface::flushWindowSystemEvents()
diff --git a/src/plugins/platforms/android/qandroidinputcontext.cpp b/src/plugins/platforms/android/qandroidinputcontext.cpp
index d264f74d66..b44340106d 100644
--- a/src/plugins/platforms/android/qandroidinputcontext.cpp
+++ b/src/plugins/platforms/android/qandroidinputcontext.cpp
@@ -545,7 +545,9 @@ void QAndroidInputContext::showInputPanel()
rect.top(),
rect.width(),
rect.height(),
- query->value(Qt::ImHints).toUInt());
+ query->value(Qt::ImHints).toUInt(),
+ query->value(Qt::ImEnterKeyType).toUInt()
+ );
}
void QAndroidInputContext::showInputPanelLater(Qt::ApplicationState state)
diff --git a/src/plugins/platforms/cocoa/cocoa.pro b/src/plugins/platforms/cocoa/cocoa.pro
index ad6cb3a1fc..ba0e6b001a 100644
--- a/src/plugins/platforms/cocoa/cocoa.pro
+++ b/src/plugins/platforms/cocoa/cocoa.pro
@@ -12,7 +12,6 @@ OBJECTIVE_SOURCES += main.mm \
qcocoawindow.mm \
qnsview.mm \
qnsviewaccessibility.mm \
- qcocoaautoreleasepool.mm \
qnswindowdelegate.mm \
qcocoanativeinterface.mm \
qcocoaeventdispatcher.mm \
@@ -48,7 +47,6 @@ HEADERS += qcocoaintegration.h \
qcocoabackingstore.h \
qcocoawindow.h \
qnsview.h \
- qcocoaautoreleasepool.h \
qnswindowdelegate.h \
qcocoanativeinterface.h \
qcocoaeventdispatcher.h \
diff --git a/src/plugins/platforms/cocoa/main.mm b/src/plugins/platforms/cocoa/main.mm
index b7e8fa1fca..43ff715161 100644
--- a/src/plugins/platforms/cocoa/main.mm
+++ b/src/plugins/platforms/cocoa/main.mm
@@ -50,11 +50,9 @@ public:
QPlatformIntegration * QCocoaIntegrationPlugin::create(const QString& system, const QStringList& paramList)
{
- Q_UNUSED(paramList);
-
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (system.compare(QLatin1String("cocoa"), Qt::CaseInsensitive) == 0)
- return new QCocoaIntegration;
+ return new QCocoaIntegration(paramList);
return 0;
}
diff --git a/src/plugins/platforms/cocoa/qcocoaaccessibility.h b/src/plugins/platforms/cocoa/qcocoaaccessibility.h
index 061dfac156..18ff9aeb29 100644
--- a/src/plugins/platforms/cocoa/qcocoaaccessibility.h
+++ b/src/plugins/platforms/cocoa/qcocoaaccessibility.h
@@ -45,10 +45,10 @@ class QCocoaAccessibility : public QPlatformAccessibility
public:
QCocoaAccessibility();
~QCocoaAccessibility();
- void notifyAccessibilityUpdate(QAccessibleEvent *event);
- void setRootObject(QObject *o);
- void initialize();
- void cleanup();
+ void notifyAccessibilityUpdate(QAccessibleEvent *event) Q_DECL_OVERRIDE;
+ void setRootObject(QObject *o) Q_DECL_OVERRIDE;
+ void initialize() Q_DECL_OVERRIDE;
+ void cleanup() Q_DECL_OVERRIDE;
};
namespace QCocoaAccessible {
diff --git a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
index 04e51d5392..abaaba91a5 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
+++ b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
@@ -100,6 +100,7 @@
- (void)setReflectionDelegate:(NSObject <NSApplicationDelegate> *)oldDelegate;
- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent;
- (void) removeAppleEventHandlers;
+- (bool) inLaunch;
@end
QT_NAMESPACE_ALIAS_OBJC_CLASS(QCocoaApplicationDelegate);
diff --git a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
index 6c673a4f5d..cac50825af 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
+++ b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
@@ -284,6 +284,11 @@ QT_END_NAMESPACE
[eventManager removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
}
+- (bool) inLaunch
+{
+ return inLaunch;
+}
+
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
Q_UNUSED(aNotification);
diff --git a/src/plugins/platforms/cocoa/qcocoabackingstore.h b/src/plugins/platforms/cocoa/qcocoabackingstore.h
index 3737584c4c..5a199de4a5 100644
--- a/src/plugins/platforms/cocoa/qcocoabackingstore.h
+++ b/src/plugins/platforms/cocoa/qcocoabackingstore.h
@@ -49,12 +49,12 @@ public:
QCocoaBackingStore(QWindow *window);
~QCocoaBackingStore();
- QPaintDevice *paintDevice();
- void flush(QWindow *widget, const QRegion &region, const QPoint &offset);
- QImage toImage() const;
- void resize (const QSize &size, const QRegion &);
- bool scroll(const QRegion &area, int dx, int dy);
- void beginPaint(const QRegion &region);
+ QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
+ void flush(QWindow *widget, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
+ QImage toImage() const Q_DECL_OVERRIDE;
+ void resize (const QSize &size, const QRegion &) Q_DECL_OVERRIDE;
+ bool scroll(const QRegion &area, int dx, int dy) Q_DECL_OVERRIDE;
+ void beginPaint(const QRegion &region) Q_DECL_OVERRIDE;
qreal getBackingStoreDevicePixelRatio();
private:
diff --git a/src/plugins/platforms/cocoa/qcocoaclipboard.h b/src/plugins/platforms/cocoa/qcocoaclipboard.h
index e3df9a99b1..e53942b068 100644
--- a/src/plugins/platforms/cocoa/qcocoaclipboard.h
+++ b/src/plugins/platforms/cocoa/qcocoaclipboard.h
@@ -47,10 +47,10 @@ class QCocoaClipboard : public QObject, public QPlatformClipboard
public:
QCocoaClipboard();
- QMimeData *mimeData(QClipboard::Mode mode = QClipboard::Clipboard);
- void setMimeData(QMimeData *data, QClipboard::Mode mode = QClipboard::Clipboard);
- bool supportsMode(QClipboard::Mode mode) const;
- bool ownsMode(QClipboard::Mode mode) const;
+ QMimeData *mimeData(QClipboard::Mode mode = QClipboard::Clipboard) Q_DECL_OVERRIDE;
+ void setMimeData(QMimeData *data, QClipboard::Mode mode = QClipboard::Clipboard) Q_DECL_OVERRIDE;
+ bool supportsMode(QClipboard::Mode mode) const Q_DECL_OVERRIDE;
+ bool ownsMode(QClipboard::Mode mode) const Q_DECL_OVERRIDE;
private Q_SLOTS:
void handleApplicationStateChanged(Qt::ApplicationState state);
diff --git a/src/plugins/platforms/cocoa/qcocoacolordialoghelper.h b/src/plugins/platforms/cocoa/qcocoacolordialoghelper.h
index 3183705330..705f97cd2a 100644
--- a/src/plugins/platforms/cocoa/qcocoacolordialoghelper.h
+++ b/src/plugins/platforms/cocoa/qcocoacolordialoghelper.h
@@ -43,14 +43,14 @@ class QCocoaColorDialogHelper : public QPlatformColorDialogHelper
{
public:
QCocoaColorDialogHelper();
- virtual ~QCocoaColorDialogHelper();
+ ~QCocoaColorDialogHelper();
- void exec();
- bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent);
- void hide();
+ void exec() Q_DECL_OVERRIDE;
+ bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent) Q_DECL_OVERRIDE;
+ void hide() Q_DECL_OVERRIDE;
- void setCurrentColor(const QColor&);
- QColor currentColor() const;
+ void setCurrentColor(const QColor&) Q_DECL_OVERRIDE;
+ QColor currentColor() const Q_DECL_OVERRIDE;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoacursor.h b/src/plugins/platforms/cocoa/qcocoacursor.h
index cc6cbaf59e..d104939f0c 100644
--- a/src/plugins/platforms/cocoa/qcocoacursor.h
+++ b/src/plugins/platforms/cocoa/qcocoacursor.h
@@ -47,9 +47,9 @@ public:
QCocoaCursor();
~QCocoaCursor();
- virtual void changeCursor(QCursor *cursor, QWindow *window);
- virtual QPoint pos() const;
- virtual void setPos(const QPoint &position);
+ void changeCursor(QCursor *cursor, QWindow *window) Q_DECL_OVERRIDE;
+ QPoint pos() const Q_DECL_OVERRIDE;
+ void setPos(const QPoint &position) Q_DECL_OVERRIDE;
private:
QHash<Qt::CursorShape, NSCursor *> m_cursors;
NSCursor *convertCursor(QCursor *cursor);
diff --git a/src/plugins/platforms/cocoa/qcocoacursor.mm b/src/plugins/platforms/cocoa/qcocoacursor.mm
index 922809f90d..2098f0dc8c 100644
--- a/src/plugins/platforms/cocoa/qcocoacursor.mm
+++ b/src/plugins/platforms/cocoa/qcocoacursor.mm
@@ -34,7 +34,6 @@
#include "qcocoacursor.h"
#include "qcocoawindow.h"
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include <QtGui/QBitmap>
diff --git a/src/plugins/platforms/cocoa/qcocoadrag.h b/src/plugins/platforms/cocoa/qcocoadrag.h
index e087fcee26..c1eeb34679 100644
--- a/src/plugins/platforms/cocoa/qcocoadrag.h
+++ b/src/plugins/platforms/cocoa/qcocoadrag.h
@@ -47,13 +47,13 @@ class QCocoaDrag : public QPlatformDrag
{
public:
QCocoaDrag();
- virtual ~QCocoaDrag();
+ ~QCocoaDrag();
- virtual QMimeData *platformDropData();
- virtual Qt::DropAction drag(QDrag *m_drag);
+ QMimeData *platformDropData() Q_DECL_OVERRIDE;
+ Qt::DropAction drag(QDrag *m_drag) Q_DECL_OVERRIDE;
- virtual Qt::DropAction defaultAction(Qt::DropActions possibleActions,
- Qt::KeyboardModifiers modifiers) const;
+ Qt::DropAction defaultAction(Qt::DropActions possibleActions,
+ Qt::KeyboardModifiers modifiers) const Q_DECL_OVERRIDE;
/**
* to meet NSView dragImage:at guarantees, we need to record the original
diff --git a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.h b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.h
index 13a8c89dbb..4a2cb42f87 100644
--- a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.h
+++ b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.h
@@ -80,7 +80,6 @@
//
#include <QtCore/qabstracteventdispatcher.h>
-#include <QtCore/qhash.h>
#include <QtCore/qstack.h>
#include <QtGui/qwindowdefs.h>
#include <QtCore/private/qabstracteventdispatcher_p.h>
diff --git a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
index 52b2e23345..1865624d57 100644
--- a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
+++ b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
@@ -66,13 +66,11 @@
****************************************************************************/
#include "qcocoaeventdispatcher.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoawindow.h"
#include "qcocoahelpers.h"
#include "qguiapplication.h"
#include "qevent.h"
-#include "qhash.h"
#include "qmutex.h"
#include "qsocketnotifier.h"
#include <qpa/qplatformwindow.h>
@@ -365,7 +363,7 @@ bool QCocoaEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags)
if (d->interrupt)
break;
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSEvent* event = 0;
// First, send all previously excluded input events, if any:
@@ -623,7 +621,7 @@ NSModalSession QCocoaEventDispatcherPrivate::currentModalSession()
continue;
if (!info.session) {
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(info.window->handle());
NSWindow *nswindow = cocoaWindow->nativeWindow();
if (!nswindow)
@@ -671,7 +669,7 @@ void QCocoaEventDispatcherPrivate::updateChildrenWorksWhenModal()
// Make the dialog children of the window
// active. And make the dialog children of
// the previous modal dialog unactive again:
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
int size = cocoaModalSessionStack.size();
if (size > 0){
if (QWindow *prevModal = cocoaModalSessionStack[size-1].window)
@@ -692,7 +690,7 @@ void QCocoaEventDispatcherPrivate::cleanupModalSessions()
// 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.
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
int stackSize = cocoaModalSessionStack.size();
for (int i=stackSize-1; i>=0; --i) {
@@ -927,7 +925,7 @@ void QCocoaEventDispatcherPrivate::cancelWaitForMoreEvents()
{
// In case the event dispatcher is waiting for more
// events somewhere, we post a dummy event to wake it up:
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
[NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint
modifierFlags:0 timestamp:0. windowNumber:0 context:0
subtype:QtCocoaEventSubTypeWakeup data1:0 data2:0] atStart:NO];
diff --git a/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm b/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
index 4ece1b5a22..93ee4e8624 100644
--- a/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
+++ b/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
@@ -53,7 +53,6 @@
#include <qvarlengtharray.h>
#include <stdlib.h>
#include <qabstracteventdispatcher.h>
-#include "qcocoaautoreleasepool.h"
#include <QDir>
#include <qpa/qplatformnativeinterface.h>
@@ -557,7 +556,7 @@ QCocoaFileDialogHelper::~QCocoaFileDialogHelper()
{
if (!mDelegate)
return;
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
[mDelegate release];
mDelegate = 0;
}
@@ -687,7 +686,7 @@ bool QCocoaFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModalit
void QCocoaFileDialogHelper::createNSOpenSavePanelDelegate()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
const SharedPointerFileDialogOptions &opts = options();
const QList<QUrl> selectedFiles = opts->initiallySelectedFiles();
@@ -737,7 +736,7 @@ void QCocoaFileDialogHelper::exec()
// 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.
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if ([mDelegate runApplicationModalPanel])
emit accept();
else
diff --git a/src/plugins/platforms/cocoa/qcocoafontdialoghelper.h b/src/plugins/platforms/cocoa/qcocoafontdialoghelper.h
index 5a241bc242..23266cfa79 100644
--- a/src/plugins/platforms/cocoa/qcocoafontdialoghelper.h
+++ b/src/plugins/platforms/cocoa/qcocoafontdialoghelper.h
@@ -45,13 +45,13 @@ public:
QCocoaFontDialogHelper();
~QCocoaFontDialogHelper();
- void exec();
+ void exec() Q_DECL_OVERRIDE;
- bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent);
- void hide();
+ bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent) Q_DECL_OVERRIDE;
+ void hide() Q_DECL_OVERRIDE;
- void setCurrentFont(const QFont &);
- QFont currentFont() const;
+ void setCurrentFont(const QFont &) Q_DECL_OVERRIDE;
+ QFont currentFont() const Q_DECL_OVERRIDE;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoaglcontext.h b/src/plugins/platforms/cocoa/qcocoaglcontext.h
index 2c8a3e39f3..fa6db018a7 100644
--- a/src/plugins/platforms/cocoa/qcocoaglcontext.h
+++ b/src/plugins/platforms/cocoa/qcocoaglcontext.h
@@ -50,22 +50,22 @@ public:
QCocoaGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, const QVariant &nativeHandle);
~QCocoaGLContext();
- QSurfaceFormat format() const;
+ QSurfaceFormat format() const Q_DECL_OVERRIDE;
- void swapBuffers(QPlatformSurface *surface);
+ void swapBuffers(QPlatformSurface *surface) Q_DECL_OVERRIDE;
- bool makeCurrent(QPlatformSurface *surface);
- void doneCurrent();
+ bool makeCurrent(QPlatformSurface *surface) Q_DECL_OVERRIDE;
+ void doneCurrent() Q_DECL_OVERRIDE;
- void (*getProcAddress(const QByteArray &procName)) ();
+ void (*getProcAddress(const QByteArray &procName)) () Q_DECL_OVERRIDE;
void update();
static NSOpenGLPixelFormat *createNSOpenGLPixelFormat(const QSurfaceFormat &format);
NSOpenGLContext *nsOpenGLContext() const;
- bool isSharing() const;
- bool isValid() const;
+ bool isSharing() const Q_DECL_OVERRIDE;
+ bool isValid() const Q_DECL_OVERRIDE;
void windowWasHidden();
diff --git a/src/plugins/platforms/cocoa/qcocoaglcontext.mm b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
index a3c72c58b9..1d8a1c5e70 100644
--- a/src/plugins/platforms/cocoa/qcocoaglcontext.mm
+++ b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
@@ -33,7 +33,6 @@
#include "qcocoaglcontext.h"
#include "qcocoawindow.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoahelpers.h"
#include <qdebug.h>
#include <QtCore/private/qcore_mac_p.h>
@@ -145,7 +144,7 @@ QCocoaGLContext::QCocoaGLContext(const QSurfaceFormat &format, QPlatformOpenGLCo
if (m_format.renderableType() != QSurfaceFormat::OpenGL)
return;
- QCocoaAutoReleasePool pool; // For the SG Canvas render thread
+ QMacAutoReleasePool pool; // For the SG Canvas render thread
NSOpenGLPixelFormat *pixelFormat = static_cast <NSOpenGLPixelFormat *>(qcgl_createNSOpenGLPixelFormat(m_format));
m_shareContext = share ? static_cast<QCocoaGLContext *>(share)->nsOpenGLContext() : nil;
@@ -218,7 +217,7 @@ bool QCocoaGLContext::makeCurrent(QPlatformSurface *surface)
{
Q_ASSERT(surface->surface()->supportsOpenGL());
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QWindow *window = static_cast<QCocoaWindow *>(surface)->window();
setActiveWindow(window);
diff --git a/src/plugins/platforms/cocoa/qcocoahelpers.mm b/src/plugins/platforms/cocoa/qcocoahelpers.mm
index 5f97e2996c..bb493ef2be 100644
--- a/src/plugins/platforms/cocoa/qcocoahelpers.mm
+++ b/src/plugins/platforms/cocoa/qcocoahelpers.mm
@@ -33,7 +33,6 @@
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include <QtCore>
#include <QtGui>
@@ -270,10 +269,14 @@ bool operator<(const KeyPair &entry, const Qt::Key &key)
return entry.qtKey < key;
}
-static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
+struct qtKey2CocoaKeySortLessThan
{
- return entry1.qtKey < entry2.qtKey;
-}
+ typedef bool result_type;
+ Q_DECL_CONSTEXPR result_type operator()(const KeyPair &entry1, const KeyPair &entry2) const Q_DECL_NOTHROW
+ {
+ return entry1.qtKey < entry2.qtKey;
+ }
+};
static const int NumEntries = 59;
static const KeyPair entries[NumEntries] = {
@@ -353,7 +356,7 @@ QChar qt_mac_qtKey2CocoaKey(Qt::Key key)
mustInit = false;
for (int i=0; i<NumEntries; ++i)
rev_entries[i] = entries[i];
- std::sort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan);
+ std::sort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan());
}
const QVector<KeyPair>::iterator i
= std::lower_bound(rev_entries.begin(), rev_entries.end(), key);
@@ -630,7 +633,7 @@ QString qt_mac_applicationName()
int qt_mac_mainScreenHeight()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
// The first screen in the screens array is documented
// to have the (0,0) origin.
NSRect screenFrame = [[[NSScreen screens] firstObject] frame];
diff --git a/src/plugins/platforms/cocoa/qcocoainputcontext.h b/src/plugins/platforms/cocoa/qcocoainputcontext.h
index abe45344a9..c7df823dc4 100644
--- a/src/plugins/platforms/cocoa/qcocoainputcontext.h
+++ b/src/plugins/platforms/cocoa/qcocoainputcontext.h
@@ -46,9 +46,9 @@ public:
explicit QCocoaInputContext();
~QCocoaInputContext();
- virtual bool isValid() const { return true; }
+ bool isValid() const Q_DECL_OVERRIDE { return true; }
- virtual void reset();
+ void reset() Q_DECL_OVERRIDE;
private Q_SLOTS:
void connectSignals();
diff --git a/src/plugins/platforms/cocoa/qcocoainputcontext.mm b/src/plugins/platforms/cocoa/qcocoainputcontext.mm
index c22fe8774b..f072991bdd 100644
--- a/src/plugins/platforms/cocoa/qcocoainputcontext.mm
+++ b/src/plugins/platforms/cocoa/qcocoainputcontext.mm
@@ -34,7 +34,6 @@
#include "qnsview.h"
#include "qcocoainputcontext.h"
#include "qcocoanativeinterface.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoawindow.h"
#include <QtCore/QRect>
@@ -98,7 +97,7 @@ void QCocoaInputContext::reset()
if (!view)
return;
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (NSTextInputContext *ctxt = [NSTextInputContext currentInputContext]) {
[ctxt discardMarkedText];
[view unmarkText];
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.h b/src/plugins/platforms/cocoa/qcocoaintegration.h
index 8b5d78826c..32a08dbb0d 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.h
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.h
@@ -36,7 +36,6 @@
#include <Cocoa/Cocoa.h>
-#include "qcocoaautoreleasepool.h"
#include "qcocoacursor.h"
#include "qcocoawindow.h"
#include "qcocoanativeinterface.h"
@@ -74,6 +73,7 @@ public:
QPlatformCursor *cursor() const Q_DECL_OVERRIDE { return m_cursor; }
QWindow *topLevelAt(const QPoint &point) const Q_DECL_OVERRIDE;
QList<QPlatformScreen *> virtualSiblings() const Q_DECL_OVERRIDE { return m_siblings; }
+ QPlatformScreen::SubpixelAntialiasingType subpixelAntialiasingTypeHint() const Q_DECL_OVERRIDE;
// ----------------------------------------------------
// Additional methods
@@ -98,34 +98,40 @@ public:
class QCocoaIntegration : public QPlatformIntegration
{
public:
- QCocoaIntegration();
+ enum Option {
+ UseFreeTypeFontEngine = 0x1
+ };
+ Q_DECLARE_FLAGS(Options, Option)
+
+ QCocoaIntegration(const QStringList &paramList);
~QCocoaIntegration();
static QCocoaIntegration *instance();
+ Options options() const;
- bool hasCapability(QPlatformIntegration::Capability cap) const;
- QPlatformWindow *createPlatformWindow(QWindow *window) const;
+ bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
+ QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
#ifndef QT_NO_OPENGL
- QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const;
+ QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const Q_DECL_OVERRIDE;
#endif
- QPlatformBackingStore *createPlatformBackingStore(QWindow *widget) const;
+ QPlatformBackingStore *createPlatformBackingStore(QWindow *widget) const Q_DECL_OVERRIDE;
- QAbstractEventDispatcher *createEventDispatcher() const;
+ QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
- QCoreTextFontDatabase *fontDatabase() const;
- QCocoaNativeInterface *nativeInterface() const;
- QCocoaInputContext *inputContext() const;
- QCocoaAccessibility *accessibility() const;
- QCocoaClipboard *clipboard() const;
- QCocoaDrag *drag() const;
+ QCoreTextFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
+ QCocoaNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
+ QPlatformInputContext *inputContext() const Q_DECL_OVERRIDE;
+ QCocoaAccessibility *accessibility() const Q_DECL_OVERRIDE;
+ QCocoaClipboard *clipboard() const Q_DECL_OVERRIDE;
+ QCocoaDrag *drag() const Q_DECL_OVERRIDE;
- QStringList themeNames() const;
- QPlatformTheme *createPlatformTheme(const QString &name) const;
- QCocoaServices *services() const;
- QVariant styleHint(StyleHint hint) const;
+ QStringList themeNames() const Q_DECL_OVERRIDE;
+ QPlatformTheme *createPlatformTheme(const QString &name) const Q_DECL_OVERRIDE;
+ QCocoaServices *services() const Q_DECL_OVERRIDE;
+ QVariant styleHint(StyleHint hint) const Q_DECL_OVERRIDE;
- Qt::KeyboardModifiers queryKeyboardModifiers() const;
- QList<int> possibleKeys(const QKeyEvent *event) const;
+ Qt::KeyboardModifiers queryKeyboardModifiers() const Q_DECL_OVERRIDE;
+ QList<int> possibleKeys(const QKeyEvent *event) const Q_DECL_OVERRIDE;
void updateScreens();
QCocoaScreen *screenAtIndex(int index);
@@ -139,13 +145,14 @@ public:
QCocoaWindow *activePopupWindow() const;
QList<QCocoaWindow *> *popupWindowStack();
- void setApplicationIcon(const QIcon &icon) const;
+ void setApplicationIcon(const QIcon &icon) const Q_DECL_OVERRIDE;
private:
static QCocoaIntegration *mInstance;
+ Options mOptions;
QScopedPointer<QCoreTextFontDatabase> mFontDb;
- QScopedPointer<QCocoaInputContext> mInputContext;
+ QScopedPointer<QPlatformInputContext> mInputContext;
#ifndef QT_NO_ACCESSIBILITY
QScopedPointer<QCocoaAccessibility> mAccessibility;
#endif
@@ -161,6 +168,8 @@ private:
QList<QCocoaWindow *> m_popupWindowStack;
};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QCocoaIntegration::Options)
+
QT_END_NAMESPACE
#endif
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.mm b/src/plugins/platforms/cocoa/qcocoaintegration.mm
index c8f6dd05db..051a1c8710 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.mm
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.mm
@@ -33,7 +33,6 @@
#include "qcocoaintegration.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoawindow.h"
#include "qcocoabackingstore.h"
#include "qcocoanativeinterface.h"
@@ -48,7 +47,9 @@
#include "qcocoamimetypes.h"
#include "qcocoaaccessibility.h"
+#include <qpa/qplatforminputcontextfactory_p.h>
#include <qpa/qplatformaccessibility.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
#include <QtCore/qcoreapplication.h>
#include <IOKit/graphics/IOGraphicsLib.h>
@@ -137,11 +138,21 @@ void QCocoaScreen::updateGeometry()
qreal QCocoaScreen::devicePixelRatio() const
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSScreen * screen = osScreen();
return qreal(screen ? [screen backingScaleFactor] : 1.0);
}
+QPlatformScreen::SubpixelAntialiasingType QCocoaScreen::subpixelAntialiasingTypeHint() const
+{
+ QPlatformScreen::SubpixelAntialiasingType type = QPlatformScreen::subpixelAntialiasingTypeHint();
+ if (type == QPlatformScreen::Subpixel_None) {
+ // Every OSX machine has RGB pixels unless a peculiar or rotated non-Apple screen is attached
+ type = QPlatformScreen::Subpixel_RGB;
+ }
+ return type;
+}
+
QWindow *QCocoaScreen::topLevelAt(const QPoint &point) const
{
NSPoint screenPoint = qt_mac_flipPoint(point);
@@ -244,11 +255,25 @@ QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height
return windowPixmap;
}
+static QCocoaIntegration::Options parseOptions(const QStringList &paramList)
+{
+ QCocoaIntegration::Options options;
+ foreach (const QString &param, paramList) {
+#ifndef QT_NO_FREETYPE
+ if (param == QLatin1String("fontengine=freetype"))
+ options |= QCocoaIntegration::UseFreeTypeFontEngine;
+ else
+#endif
+ qWarning() << "Unknown option" << param;
+ }
+ return options;
+}
+
QCocoaIntegration *QCocoaIntegration::mInstance = 0;
-QCocoaIntegration::QCocoaIntegration()
- : mFontDb(new QCoreTextFontDatabase())
- , mInputContext(new QCocoaInputContext)
+QCocoaIntegration::QCocoaIntegration(const QStringList &paramList)
+ : mOptions(parseOptions(paramList))
+ , mFontDb(new QCoreTextFontDatabase(mOptions.testFlag(UseFreeTypeFontEngine)))
#ifndef QT_NO_ACCESSIBILITY
, mAccessibility(new QCocoaAccessibility)
#endif
@@ -262,8 +287,12 @@ QCocoaIntegration::QCocoaIntegration()
qWarning("Creating multiple Cocoa platform integrations is not supported");
mInstance = this;
+ QString icStr = QPlatformInputContextFactory::requested();
+ icStr.isNull() ? mInputContext.reset(new QCocoaInputContext)
+ : mInputContext.reset(QPlatformInputContextFactory::create(icStr));
+
initResources();
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
qApp->setAttribute(Qt::AA_DontUseNativeMenuBar, false);
@@ -314,7 +343,7 @@ QCocoaIntegration::~QCocoaIntegration()
qt_resetNSApplicationSendEvent();
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (!QCoreApplication::testAttribute(Qt::AA_MacPluginApplication)) {
// remove the apple event handlers installed by QCocoaApplicationDelegate
QCocoaApplicationDelegate *delegate = [QCocoaApplicationDelegate sharedDelegate];
@@ -342,6 +371,11 @@ QCocoaIntegration *QCocoaIntegration::instance()
return mInstance;
}
+QCocoaIntegration::Options QCocoaIntegration::options() const
+{
+ return mOptions;
+}
+
/*!
\brief Synchronizes the screen list, adds new screens, removes deleted ones
*/
@@ -463,7 +497,7 @@ QCocoaNativeInterface *QCocoaIntegration::nativeInterface() const
return mNativeInterface.data();
}
-QCocoaInputContext *QCocoaIntegration::inputContext() const
+QPlatformInputContext *QCocoaIntegration::inputContext() const
{
return mInputContext.data();
}
diff --git a/src/plugins/platforms/cocoa/qcocoamenu.h b/src/plugins/platforms/cocoa/qcocoamenu.h
index 59807deb5a..eccc5230b5 100644
--- a/src/plugins/platforms/cocoa/qcocoamenu.h
+++ b/src/plugins/platforms/cocoa/qcocoamenu.h
@@ -49,29 +49,29 @@ public:
QCocoaMenu();
~QCocoaMenu();
- inline virtual void setTag(quintptr tag)
- { m_tag = tag; }
- inline virtual quintptr tag() const
- { return m_tag; }
-
- void insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before);
- void removeMenuItem(QPlatformMenuItem *menuItem);
- void syncMenuItem(QPlatformMenuItem *menuItem);
- void setEnabled(bool enabled);
- bool isEnabled() const;
- void setVisible(bool visible);
- void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item);
- void dismiss();
-
- void syncSeparatorsCollapsible(bool enable);
+ void setTag(quintptr tag) Q_DECL_OVERRIDE
+ { m_tag = tag; }
+ quintptr tag() const Q_DECL_OVERRIDE
+ { return m_tag; }
+
+ void insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) Q_DECL_OVERRIDE;
+ void removeMenuItem(QPlatformMenuItem *menuItem) Q_DECL_OVERRIDE;
+ void syncMenuItem(QPlatformMenuItem *menuItem) Q_DECL_OVERRIDE;
+ void setEnabled(bool enabled) Q_DECL_OVERRIDE;
+ bool isEnabled() const Q_DECL_OVERRIDE;
+ void setVisible(bool visible) Q_DECL_OVERRIDE;
+ void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) Q_DECL_OVERRIDE;
+ void dismiss() Q_DECL_OVERRIDE;
+
+ void syncSeparatorsCollapsible(bool enable) Q_DECL_OVERRIDE;
void syncModalState(bool modal);
- virtual void setIcon(const QIcon &icon) { Q_UNUSED(icon) }
+ void setIcon(const QIcon &icon) Q_DECL_OVERRIDE { Q_UNUSED(icon) }
- void setText(const QString &text);
- void setMinimumWidth(int width);
- void setFont(const QFont &font);
+ void setText(const QString &text) Q_DECL_OVERRIDE;
+ void setMinimumWidth(int width) Q_DECL_OVERRIDE;
+ void setFont(const QFont &font) Q_DECL_OVERRIDE;
inline NSMenu *nsMenu() const
{ return m_nativeMenu; }
@@ -80,8 +80,8 @@ public:
inline bool isVisible() const { return m_visible; }
- virtual QPlatformMenuItem *menuItemAt(int position) const;
- virtual QPlatformMenuItem *menuItemForTag(quintptr tag) const;
+ QPlatformMenuItem *menuItemAt(int position) const Q_DECL_OVERRIDE;
+ QPlatformMenuItem *menuItemForTag(quintptr tag) const Q_DECL_OVERRIDE;
QList<QCocoaMenuItem *> items() const;
QList<QCocoaMenuItem *> merged() const;
diff --git a/src/plugins/platforms/cocoa/qcocoamenu.mm b/src/plugins/platforms/cocoa/qcocoamenu.mm
index 6668080725..57739f3a58 100644
--- a/src/plugins/platforms/cocoa/qcocoamenu.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenu.mm
@@ -34,7 +34,6 @@
#include "qcocoamenu.h"
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include <QtCore/QtDebug>
#include <QtCore/qmetaobject.h>
@@ -235,7 +234,7 @@ QCocoaMenu::QCocoaMenu() :
m_menuBar(0),
m_containingMenuItem(0)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
m_delegate = [[QCocoaMenuDelegate alloc] initWithMenu:this];
m_nativeItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
@@ -255,7 +254,7 @@ QCocoaMenu::~QCocoaMenu()
if (m_containingMenuItem)
m_containingMenuItem->clearMenu(this);
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
[m_nativeItem setSubmenu:nil];
[m_nativeMenu release];
[m_delegate release];
@@ -264,7 +263,7 @@ QCocoaMenu::~QCocoaMenu()
void QCocoaMenu::setText(const QString &text)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QString stripped = qt_mac_removeAmpersandEscapes(text);
[m_nativeMenu setTitle:QCFString::toNSString(stripped)];
[m_nativeItem setTitle:QCFString::toNSString(stripped)];
@@ -286,7 +285,7 @@ void QCocoaMenu::setFont(const QFont &font)
void QCocoaMenu::insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenuItem *cocoaItem = static_cast<QCocoaMenuItem *>(menuItem);
QCocoaMenuItem *beforeItem = static_cast<QCocoaMenuItem *>(before);
@@ -340,7 +339,7 @@ void QCocoaMenu::insertNative(QCocoaMenuItem *item, QCocoaMenuItem *beforeItem)
void QCocoaMenu::removeMenuItem(QPlatformMenuItem *menuItem)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenuItem *cocoaItem = static_cast<QCocoaMenuItem *>(menuItem);
if (!m_menuItems.contains(cocoaItem)) {
qWarning() << Q_FUNC_INFO << "Menu does not contain the item to be removed";
@@ -370,7 +369,7 @@ QCocoaMenuItem *QCocoaMenu::itemOrNull(int index) const
void QCocoaMenu::syncMenuItem(QPlatformMenuItem *menuItem)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenuItem *cocoaItem = static_cast<QCocoaMenuItem *>(menuItem);
if (!m_menuItems.contains(cocoaItem)) {
qWarning() << Q_FUNC_INFO << "Item does not belong to this menu";
@@ -399,7 +398,7 @@ void QCocoaMenu::syncMenuItem(QPlatformMenuItem *menuItem)
void QCocoaMenu::syncSeparatorsCollapsible(bool enable)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (enable) {
bool previousIsSeparator = true; // setting to true kills all the separators placed at the top.
NSMenuItem *previousItem = nil;
@@ -457,7 +456,7 @@ void QCocoaMenu::setVisible(bool visible)
void QCocoaMenu::showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QPoint pos = QPoint(targetRect.left(), targetRect.top() + targetRect.height());
QCocoaWindow *cocoaWindow = parentWindow ? static_cast<QCocoaWindow *>(parentWindow->handle()) : 0;
@@ -562,7 +561,7 @@ QList<QCocoaMenuItem *> QCocoaMenu::merged() const
void QCocoaMenu::syncModalState(bool modal)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (!m_enabled)
modal = true;
diff --git a/src/plugins/platforms/cocoa/qcocoamenubar.h b/src/plugins/platforms/cocoa/qcocoamenubar.h
index b5ee21ca52..d5f75abf34 100644
--- a/src/plugins/platforms/cocoa/qcocoamenubar.h
+++ b/src/plugins/platforms/cocoa/qcocoamenubar.h
@@ -48,13 +48,13 @@ class QCocoaMenuBar : public QPlatformMenuBar
Q_OBJECT
public:
QCocoaMenuBar();
- virtual ~QCocoaMenuBar();
+ ~QCocoaMenuBar();
- virtual void insertMenu(QPlatformMenu *menu, QPlatformMenu* before);
- virtual void removeMenu(QPlatformMenu *menu);
- virtual void syncMenu(QPlatformMenu *menuItem);
- virtual void handleReparent(QWindow *newParentWindow);
- virtual QPlatformMenu *menuForTag(quintptr tag) const;
+ void insertMenu(QPlatformMenu *menu, QPlatformMenu* before) Q_DECL_OVERRIDE;
+ void removeMenu(QPlatformMenu *menu) Q_DECL_OVERRIDE;
+ void syncMenu(QPlatformMenu *menuItem) Q_DECL_OVERRIDE;
+ void handleReparent(QWindow *newParentWindow) Q_DECL_OVERRIDE;
+ QPlatformMenu *menuForTag(quintptr tag) const Q_DECL_OVERRIDE;
inline NSMenu *nsMenu() const
{ return m_nativeMenu; }
diff --git a/src/plugins/platforms/cocoa/qcocoamenubar.mm b/src/plugins/platforms/cocoa/qcocoamenubar.mm
index 764a01370d..7775cdbde6 100644
--- a/src/plugins/platforms/cocoa/qcocoamenubar.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenubar.mm
@@ -37,7 +37,7 @@
#include "qcocoawindow.h"
#include "qcocoamenuloader.h"
#include "qcocoaapplication.h" // for custom application category
-#include "qcocoaautoreleasepool.h"
+#include "qcocoaapplicationdelegate.h"
#include <QtGui/QGuiApplication>
#include <QtCore/QDebug>
@@ -83,7 +83,7 @@ QCocoaMenuBar::~QCocoaMenuBar()
void QCocoaMenuBar::insertNativeMenu(QCocoaMenu *menu, QCocoaMenu *beforeMenu)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (beforeMenu) {
NSUInteger nativeIndex = [m_nativeMenu indexOfItem:beforeMenu->nsMenuItem()];
@@ -126,7 +126,7 @@ void QCocoaMenuBar::insertMenu(QPlatformMenu *platformMenu, QPlatformMenu *befor
void QCocoaMenuBar::removeNativeMenu(QCocoaMenu *menu)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (menu->menuBar() == this)
menu->setMenuBar(0);
@@ -147,7 +147,7 @@ void QCocoaMenuBar::removeMenu(QPlatformMenu *platformMenu)
void QCocoaMenuBar::syncMenu(QPlatformMenu *menu)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenu *cocoaMenu = static_cast<QCocoaMenu *>(menu);
Q_FOREACH (QCocoaMenuItem *item, cocoaMenu->items())
@@ -260,13 +260,26 @@ void QCocoaMenuBar::resetKnownMenuItemsToQt()
void QCocoaMenuBar::updateMenuBarImmediately()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenuBar *mb = findGlobalMenubar();
QCocoaWindow *cw = findWindowForMenubar();
QWindow *win = cw ? cw->window() : 0;
- if (win && (win->flags() & Qt::Popup) == Qt::Popup)
- return; // context menus, comboboxes, etc. don't need to update the menubar
+ if (win && (win->flags() & Qt::Popup) == Qt::Popup) {
+ // context menus, comboboxes, etc. don't need to update the menubar,
+ // but if an application has only Qt::Tool window(s) on start,
+ // we still have to update the menubar.
+ if ((win->flags() & Qt::WindowType_Mask) != Qt::Tool)
+ return;
+ typedef QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) AppDelegate;
+ NSApplication *app = [NSApplication sharedApplication];
+ if (![app.delegate isKindOfClass:[AppDelegate class]])
+ return;
+ // We apply this logic _only_ during the startup.
+ AppDelegate *appDelegate = app.delegate;
+ if (!appDelegate.inLaunch)
+ return;
+ }
if (cw && cw->menubar())
mb = cw->menubar();
diff --git a/src/plugins/platforms/cocoa/qcocoamenuitem.h b/src/plugins/platforms/cocoa/qcocoamenuitem.h
index 5c85824ab8..289f38fd18 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuitem.h
+++ b/src/plugins/platforms/cocoa/qcocoamenuitem.h
@@ -60,27 +60,27 @@ class QCocoaMenuItem : public QPlatformMenuItem
{
public:
QCocoaMenuItem();
- virtual ~QCocoaMenuItem();
+ ~QCocoaMenuItem();
- inline virtual void setTag(quintptr tag)
+ void setTag(quintptr tag) Q_DECL_OVERRIDE
{ m_tag = tag; }
- inline virtual quintptr tag() const
+ quintptr tag() const Q_DECL_OVERRIDE
{ return m_tag; }
- void setText(const QString &text);
- void setIcon(const QIcon &icon);
- void setMenu(QPlatformMenu *menu);
- void setVisible(bool isVisible);
- void setIsSeparator(bool isSeparator);
- void setFont(const QFont &font);
- void setRole(MenuRole role);
- void setShortcut(const QKeySequence& shortcut);
- void setCheckable(bool checkable) { Q_UNUSED(checkable) }
- void setChecked(bool isChecked);
- void setEnabled(bool isEnabled);
- void setIconSize(int size);
-
- void setNativeContents(WId item);
+ void setText(const QString &text) Q_DECL_OVERRIDE;
+ void setIcon(const QIcon &icon) Q_DECL_OVERRIDE;
+ void setMenu(QPlatformMenu *menu) Q_DECL_OVERRIDE;
+ void setVisible(bool isVisible) Q_DECL_OVERRIDE;
+ void setIsSeparator(bool isSeparator) Q_DECL_OVERRIDE;
+ void setFont(const QFont &font) Q_DECL_OVERRIDE;
+ void setRole(MenuRole role) Q_DECL_OVERRIDE;
+ void setShortcut(const QKeySequence& shortcut) Q_DECL_OVERRIDE;
+ void setCheckable(bool checkable) Q_DECL_OVERRIDE { Q_UNUSED(checkable) }
+ void setChecked(bool isChecked) Q_DECL_OVERRIDE;
+ void setEnabled(bool isEnabled) Q_DECL_OVERRIDE;
+ void setIconSize(int size) Q_DECL_OVERRIDE;
+
+ void setNativeContents(WId item) Q_DECL_OVERRIDE;
inline QString text() const { return m_text; }
inline NSMenuItem * nsItem() { return m_native; }
diff --git a/src/plugins/platforms/cocoa/qcocoamenuitem.mm b/src/plugins/platforms/cocoa/qcocoamenuitem.mm
index f288ab85c0..942fc8db21 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuitem.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenuitem.mm
@@ -37,7 +37,6 @@
#include "qcocoamenubar.h"
#include "messages.h"
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include "qt_mac_p.h"
#include "qcocoaapplication.h" // for custom application category
#include "qcocoamenuloader.h"
@@ -104,7 +103,7 @@ QCocoaMenuItem::QCocoaMenuItem() :
QCocoaMenuItem::~QCocoaMenuItem()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (m_menu && COCOA_MENU_ANCESTOR(m_menu) == this)
SET_COCOA_MENU_ANCESTOR(m_menu, 0);
@@ -139,7 +138,7 @@ void QCocoaMenuItem::setMenu(QPlatformMenu *menu)
m_menu->setContainingMenuItem(0);
}
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
m_menu = static_cast<QCocoaMenu *>(menu);
if (m_menu) {
SET_COCOA_MENU_ANCESTOR(m_menu, this);
diff --git a/src/plugins/platforms/cocoa/qcocoanativeinterface.h b/src/plugins/platforms/cocoa/qcocoanativeinterface.h
index 2250f7c084..d018c05635 100644
--- a/src/plugins/platforms/cocoa/qcocoanativeinterface.h
+++ b/src/plugins/platforms/cocoa/qcocoanativeinterface.h
@@ -67,6 +67,8 @@ public:
static void *nsOpenGLContextForContext(QOpenGLContext* context);
#endif
+ QFunctionPointer platformFunction(const QByteArray &function) const Q_DECL_OVERRIDE;
+
public Q_SLOTS:
void onAppFocusWindowChanged(QWindow *window);
diff --git a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
index 205a49d25a..41ea1fa49c 100644
--- a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
+++ b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
@@ -58,6 +58,8 @@
#include <qpa/qplatformprintersupport.h>
#endif
+#include <QtPlatformHeaders/qcocoawindowfunctions.h>
+
#include <Cocoa/Cocoa.h>
QT_BEGIN_NAMESPACE
@@ -217,6 +219,14 @@ void *QCocoaNativeInterface::nsOpenGLContextForContext(QOpenGLContext* context)
}
#endif
+QFunctionPointer QCocoaNativeInterface::platformFunction(const QByteArray &function) const
+{
+ if (function == QCocoaWindowFunctions::bottomLeftClippedByNSWindowOffsetIdentifier())
+ return QFunctionPointer(QCocoaWindowFunctions::BottomLeftClippedByNSWindowOffset(QCocoaWindow::bottomLeftClippedByNSWindowOffsetStatic));
+
+ return Q_NULLPTR;
+}
+
void QCocoaNativeInterface::addToMimeList(void *macPasteboardMime)
{
qt_mac_addToGlobalMimeList(reinterpret_cast<QMacInternalPasteboardMime *>(macPasteboardMime));
@@ -234,7 +244,7 @@ void QCocoaNativeInterface::registerDraggedTypes(const QStringList &types)
void QCocoaNativeInterface::setDockMenu(QPlatformMenu *platformMenu)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaMenu *cocoaPlatformMenu = static_cast<QCocoaMenu *>(platformMenu);
NSMenu *menu = cocoaPlatformMenu->nsMenu();
[NSApp QT_MANGLE_NAMESPACE(qt_setDockMenu): menu];
diff --git a/src/plugins/platforms/cocoa/qcocoaprintdevice.mm b/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
index 4d319e149b..b0d04f6f82 100644
--- a/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
+++ b/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
@@ -100,7 +100,7 @@ QCocoaPrintDevice::~QCocoaPrintDevice()
{
if (m_ppd)
ppdClose(m_ppd);
- foreach (PMPaper paper, m_macPapers.values())
+ foreach (PMPaper paper, m_macPapers)
PMRelease(paper);
// Releasing the session appears to also release the printer
if (m_session)
@@ -154,7 +154,7 @@ QPageSize QCocoaPrintDevice::createPageSize(const PMPaper &paper) const
void QCocoaPrintDevice::loadPageSizes() const
{
m_pageSizes.clear();
- foreach (PMPaper paper, m_macPapers.values())
+ foreach (PMPaper paper, m_macPapers)
PMRelease(paper);
m_macPapers.clear();
m_printableMargins.clear();
diff --git a/src/plugins/platforms/cocoa/qcocoaservices.h b/src/plugins/platforms/cocoa/qcocoaservices.h
index 331fe810fa..1a447c6242 100644
--- a/src/plugins/platforms/cocoa/qcocoaservices.h
+++ b/src/plugins/platforms/cocoa/qcocoaservices.h
@@ -41,8 +41,8 @@ QT_BEGIN_NAMESPACE
class QCocoaServices : public QPlatformServices
{
public:
- bool openUrl(const QUrl &url);
- bool openDocument(const QUrl &url);
+ bool openUrl(const QUrl &url) Q_DECL_OVERRIDE;
+ bool openDocument(const QUrl &url) Q_DECL_OVERRIDE;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
index 65cc9bc38b..93f8b2ba6f 100644
--- a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
+++ b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
@@ -33,7 +33,6 @@
#include "qcocoasystemsettings.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoahelpers.h"
#include <QtCore/private/qcore_mac_p.h>
@@ -45,7 +44,7 @@ QT_BEGIN_NAMESPACE
QColor qt_mac_colorForTheme(ThemeBrush brush)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCFType<CGColorRef> cgClr = 0;
HIThemeBrushCreateCGColor(brush, &cgClr);
diff --git a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.h b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.h
index b5f038094f..cdfd92c0aa 100755..100644
--- a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.h
+++ b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.h
@@ -51,17 +51,17 @@ class Q_GUI_EXPORT QCocoaSystemTrayIcon : public QPlatformSystemTrayIcon
public:
QCocoaSystemTrayIcon() : m_sys(0) {}
- virtual void init();
- virtual void cleanup();
- virtual void updateIcon(const QIcon &icon);
- virtual void updateToolTip(const QString &toolTip);
- virtual void updateMenu(QPlatformMenu *menu);
- virtual QRect geometry() const;
- virtual void showMessage(const QString &title, const QString &msg,
- const QIcon& icon, MessageIcon iconType, int secs);
+ void init() Q_DECL_OVERRIDE;
+ void cleanup() Q_DECL_OVERRIDE;
+ void updateIcon(const QIcon &icon) Q_DECL_OVERRIDE;
+ void updateToolTip(const QString &toolTip) Q_DECL_OVERRIDE;
+ void updateMenu(QPlatformMenu *menu) Q_DECL_OVERRIDE;
+ QRect geometry() const Q_DECL_OVERRIDE;
+ void showMessage(const QString &title, const QString &msg,
+ const QIcon& icon, MessageIcon iconType, int secs) Q_DECL_OVERRIDE;
- virtual bool isSystemTrayAvailable() const;
- virtual bool supportsMessages() const;
+ bool isSystemTrayAvailable() const Q_DECL_OVERRIDE;
+ bool supportsMessages() const Q_DECL_OVERRIDE;
private:
QSystemTrayIconSys *m_sys;
diff --git a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
index 713758cc7e..a3ffb5be66 100755..100644
--- a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
+++ b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
@@ -252,6 +252,7 @@ void QCocoaSystemTrayIcon::updateIcon(const QIcon &icon)
}
NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(fullHeightPixmap));
+ [nsimage setTemplate:icon.isMask()];
[(NSImageView*)[[m_sys->item item] view] setImage: nsimage];
[nsimage release];
}
diff --git a/src/plugins/platforms/cocoa/qcocoatheme.mm b/src/plugins/platforms/cocoa/qcocoatheme.mm
index 11749e14de..4b73d0af08 100644
--- a/src/plugins/platforms/cocoa/qcocoatheme.mm
+++ b/src/plugins/platforms/cocoa/qcocoatheme.mm
@@ -47,7 +47,6 @@
#include "qcocoamenu.h"
#include "qcocoamenubar.h"
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include <QtCore/qfileinfo.h>
#include <QtGui/private/qguiapplication_p.h>
@@ -253,7 +252,7 @@ QPixmap QCocoaTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &siz
QPlatformTheme::IconOptions iconOptions) const
{
Q_UNUSED(iconOptions);
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile:QCFString::toNSString(fileInfo.canonicalFilePath())];
if (!iconImage)
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.h b/src/plugins/platforms/cocoa/qcocoawindow.h
index 455d4a8580..51679116b5 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.h
+++ b/src/plugins/platforms/cocoa/qcocoawindow.h
@@ -227,6 +227,9 @@ public:
void updateExposedGeometry();
QWindow *childWindowAt(QPoint windowPoint);
bool shouldRefuseKeyWindowAndFirstResponder();
+
+ static QPoint bottomLeftClippedByNSWindowOffsetStatic(QWindow *window);
+ QPoint bottomLeftClippedByNSWindowOffset() const;
protected:
void recreateWindow(const QPlatformWindow *parentWindow);
QCocoaNSWindow *createNSWindow();
@@ -234,7 +237,7 @@ protected:
bool shouldUseNSPanel();
- QRect windowGeometry() const;
+ QRect nativeWindowGeometry() const;
QCocoaWindow *parentCocoaWindow() const;
void syncWindowState(Qt::WindowState newState);
void reinsertChildWindow(QCocoaWindow *child);
@@ -245,6 +248,8 @@ public: // for QNSView
friend class QCocoaBackingStore;
friend class QCocoaNativeInterface;
+ void removeMonitor();
+
NSView *m_contentView;
QNSView *m_qtView;
QCocoaNSWindow *m_nsWindow;
@@ -269,6 +274,7 @@ public: // for QNSView
bool m_inConstructor;
bool m_inSetVisible;
bool m_inSetGeometry;
+ bool m_inSetStyleMask;
#ifndef QT_NO_OPENGL
QCocoaGLContext *m_glContext;
#endif
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.mm b/src/plugins/platforms/cocoa/qcocoawindow.mm
index 3188463dbe..5606f050a3 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.mm
+++ b/src/plugins/platforms/cocoa/qcocoawindow.mm
@@ -33,7 +33,6 @@
#include "qcocoawindow.h"
#include "qcocoaintegration.h"
#include "qnswindowdelegate.h"
-#include "qcocoaautoreleasepool.h"
#include "qcocoaeventdispatcher.h"
#ifndef QT_NO_OPENGL
#include "qcocoaglcontext.h"
@@ -350,6 +349,7 @@ QCocoaWindow::QCocoaWindow(QWindow *tlw)
, m_inConstructor(true)
, m_inSetVisible(false)
, m_inSetGeometry(false)
+ , m_inSetStyleMask(false)
#ifndef QT_NO_OPENGL
, m_glContext(0)
#endif
@@ -373,7 +373,7 @@ QCocoaWindow::QCocoaWindow(QWindow *tlw)
#ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
qDebug() << "QCocoaWindow::QCocoaWindow" << this;
#endif
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (tlw->type() == Qt::ForeignWindow) {
NSView *foreignView = (NSView *)WId(tlw->property("_q_foreignWinId").value<WId>());
@@ -409,7 +409,7 @@ QCocoaWindow::~QCocoaWindow()
qDebug() << "QCocoaWindow::~QCocoaWindow" << this;
#endif
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
[m_nsWindow setContentView:nil];
[m_nsWindow.helper detachFromPlatformWindow];
if (m_isNSWindowChild) {
@@ -419,6 +419,8 @@ QCocoaWindow::~QCocoaWindow()
[m_contentView removeFromSuperview];
}
+ removeMonitor();
+
// Make sure to disconnect observer in all case if view is valid
// to avoid notifications received when deleting when using Qt::AA_NativeWindows attribute
if (m_qtView) {
@@ -499,7 +501,7 @@ QRect QCocoaWindow::geometry() const
void QCocoaWindow::setCocoaGeometry(const QRect &rect)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (m_contentViewIsEmbedded) {
QPlatformWindow::setGeometry(rect);
@@ -604,7 +606,7 @@ void QCocoaWindow::show(bool becauseOfAncestor)
&& !m_hiddenByClipping) { // ... NOR clipped
if (m_isNSWindowChild) {
m_hiddenByAncestor = false;
- setCocoaGeometry(window()->geometry());
+ setCocoaGeometry(windowGeometry());
}
if (!m_hiddenByClipping) { // setCocoaGeometry() can change the clipping status
[m_nsWindow orderFront:nil];
@@ -623,7 +625,7 @@ void QCocoaWindow::setVisible(bool visible)
m_inSetVisible = true;
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QCocoaWindow *parentCocoaWindow = 0;
if (window()->transientParent())
parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
@@ -643,7 +645,7 @@ void QCocoaWindow::setVisible(bool visible)
if (parentCocoaWindow) {
// The parent window might have moved while this window was hidden,
// update the window geometry if there is a parent.
- setGeometry(window()->geometry());
+ setGeometry(windowGeometry());
if (window()->type() == Qt::Popup) {
// QTBUG-30266: a window should not be resizable while a transient popup is open
@@ -696,6 +698,7 @@ void QCocoaWindow::setVisible(bool visible)
&& [m_nsWindow isKindOfClass:[NSPanel class]]) {
[(NSPanel *)m_nsWindow setWorksWhenModal:YES];
if (!(parentCocoaWindow && window()->transientParent()->isActive()) && window()->type() == Qt::Popup) {
+ removeMonitor();
monitor = [NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDownMask|NSRightMouseDownMask|NSOtherMouseDownMask|NSMouseMovedMask handler:^(NSEvent *e) {
QPointF localPoint = qt_mac_flipPoint([NSEvent mouseLocation]);
QWindowSystemInterface::handleMouseEvent(window(), window()->mapFromGlobal(localPoint.toPoint()), localPoint,
@@ -744,10 +747,7 @@ void QCocoaWindow::setVisible(bool visible)
} else {
[m_contentView setHidden:YES];
}
- if (monitor && window()->type() == Qt::Popup) {
- [NSEvent removeMonitor:monitor];
- monitor = nil;
- }
+ removeMonitor();
if (window()->type() == Qt::Popup || window()->type() == Qt::ToolTip)
QCocoaIntegration::instance()->popupWindowStack()->removeAll(this);
@@ -864,8 +864,8 @@ void QCocoaWindow::setWindowZoomButton(Qt::WindowFlags flags)
// no-WindowMaximizeButtonHint windows. From a Qt perspective it migth be expected
// that the button would be removed in the latter case, but disabling it is more
// in line with the platform style guidelines.
- bool fixedSizeNoZoom = (window()->minimumSize().isValid() && window()->maximumSize().isValid()
- && window()->minimumSize() == window()->maximumSize());
+ bool fixedSizeNoZoom = (windowMinimumSize().isValid() && windowMaximumSize().isValid()
+ && windowMinimumSize() == windowMaximumSize());
bool customizeNoZoom = ((flags & Qt::CustomizeWindowHint) && !(flags & Qt::WindowMaximizeButtonHint));
[[m_nsWindow standardWindowButton:NSWindowZoomButton] setEnabled:!(fixedSizeNoZoom || customizeNoZoom)];
}
@@ -875,10 +875,14 @@ void QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
if (m_nsWindow && !m_isNSWindowChild) {
NSUInteger styleMask = windowStyleMask(flags);
NSInteger level = this->windowLevel(flags);
+ // While setting style mask we can have -updateGeometry calls on a content
+ // view with null geometry, reporting an invalid coordinates as a result.
+ m_inSetStyleMask = true;
[m_nsWindow setStyleMask:styleMask];
+ m_inSetStyleMask = false;
[m_nsWindow setLevel:level];
setWindowShadow(flags);
- if (!(styleMask & NSBorderlessWindowMask)) {
+ if (!(flags & Qt::FramelessWindowHint)) {
setWindowTitle(window()->title());
}
@@ -905,7 +909,7 @@ void QCocoaWindow::setWindowState(Qt::WindowState state)
void QCocoaWindow::setWindowTitle(const QString &title)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (!m_nsWindow)
return;
@@ -916,7 +920,7 @@ void QCocoaWindow::setWindowTitle(const QString &title)
void QCocoaWindow::setWindowFilePath(const QString &filePath)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (!m_nsWindow)
return;
@@ -926,7 +930,7 @@ void QCocoaWindow::setWindowFilePath(const QString &filePath)
void QCocoaWindow::setWindowIcon(const QIcon &icon)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSButton *iconButton = [m_nsWindow standardWindowButton:NSWindowDocumentIconButton];
if (iconButton == nil) {
@@ -1044,26 +1048,26 @@ bool QCocoaWindow::isOpaque() const
void QCocoaWindow::propagateSizeHints()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
if (!m_nsWindow)
return;
#ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
qDebug() << "QCocoaWindow::propagateSizeHints" << this;
- qDebug() << " min/max " << window()->minimumSize() << window()->maximumSize();
- qDebug() << "size increment" << window()->sizeIncrement();
- qDebug() << " basesize" << window()->baseSize();
- qDebug() << " geometry" << geometry();
+ qDebug() << " min/max" << windowMinimumSize() << windowMaximumSize();
+ qDebug() << "size increment" << windowSizeIncrement();
+ qDebug() << " basesize" << windowBaseSize();
+ qDebug() << " geometry" << windowGeometry();
#endif
// Set the minimum content size.
- const QSize minimumSize = window()->minimumSize();
+ const QSize minimumSize = windowMinimumSize();
if (!minimumSize.isValid()) // minimumSize is (-1, -1) when not set. Make that (0, 0) for Cocoa.
[m_nsWindow setContentMinSize : NSMakeSize(0.0, 0.0)];
[m_nsWindow setContentMinSize : NSMakeSize(minimumSize.width(), minimumSize.height())];
// Set the maximum content size.
- const QSize maximumSize = window()->maximumSize();
+ const QSize maximumSize = windowMaximumSize();
[m_nsWindow setContentMaxSize : NSMakeSize(maximumSize.width(), maximumSize.height())];
// The window may end up with a fixed size; in this case the zoom button should be disabled.
@@ -1071,13 +1075,14 @@ void QCocoaWindow::propagateSizeHints()
// sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
// resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
- if (!window()->sizeIncrement().isEmpty())
- [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
+ const QSize sizeIncrement = windowSizeIncrement();
+ if (!sizeIncrement.isEmpty())
+ [m_nsWindow setResizeIncrements : qt_mac_toNSSize(sizeIncrement)];
else
[m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
QRect rect = geometry();
- QSize baseSize = window()->baseSize();
+ QSize baseSize = windowBaseSize();
if (!baseSize.isNull() && baseSize.isValid()) {
[m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
}
@@ -1323,7 +1328,7 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
| NSWindowCollectionBehaviorFullScreenAuxiliary;
m_nsWindow.animationBehavior = NSWindowAnimationBehaviorNone;
m_nsWindow.collectionBehavior = collectionBehavior;
- setCocoaGeometry(window()->geometry());
+ setCocoaGeometry(windowGeometry());
QList<QCocoaWindow *> &siblings = m_parentCocoaWindow->m_childWindows;
if (siblings.contains(this)) {
@@ -1337,7 +1342,7 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
} else {
// Child windows have no NSWindow, link the NSViews instead.
[m_parentCocoaWindow->m_contentView addSubview : m_contentView];
- QRect rect = window()->geometry();
+ QRect rect = windowGeometry();
// Prevent setting a (0,0) window size; causes opengl context
// "Invalid Drawable" warnings.
if (rect.isNull())
@@ -1387,9 +1392,9 @@ bool QCocoaWindow::shouldUseNSPanel()
QCocoaNSWindow * QCocoaWindow::createNSWindow()
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
- QRect rect = initialGeometry(window(), window()->geometry(), defaultWindowWidth, defaultWindowHeight);
+ QRect rect = initialGeometry(window(), windowGeometry(), defaultWindowWidth, defaultWindowHeight);
NSRect frame = qt_mac_flipRect(rect);
Qt::WindowType type = window()->type();
@@ -1476,8 +1481,16 @@ void QCocoaWindow::removeChildWindow(QCocoaWindow *child)
[m_nsWindow removeChildWindow:child->m_nsWindow];
}
+void QCocoaWindow::removeMonitor()
+{
+ if (!monitor)
+ return;
+ [NSEvent removeMonitor:monitor];
+ monitor = nil;
+}
+
// Returns the current global screen geometry for the nswindow associated with this window.
-QRect QCocoaWindow::windowGeometry() const
+QRect QCocoaWindow::nativeWindowGeometry() const
{
if (!m_nsWindow || m_isNSWindowChild)
return geometry();
@@ -1560,7 +1573,7 @@ void QCocoaWindow::syncWindowState(Qt::WindowState newState)
if (m_normalGeometry.width() < 0) {
m_oldWindowFlags = m_windowFlags;
window()->setFlags(window()->flags() | Qt::FramelessWindowHint);
- m_normalGeometry = windowGeometry();
+ m_normalGeometry = nativeWindowGeometry();
setGeometry(screen->geometry());
m_presentationOptions = [NSApp presentationOptions];
[NSApp setPresentationOptions : m_presentationOptions | NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];
@@ -1827,6 +1840,24 @@ bool QCocoaWindow::shouldRefuseKeyWindowAndFirstResponder()
return false;
}
+QPoint QCocoaWindow::bottomLeftClippedByNSWindowOffsetStatic(QWindow *window)
+{
+ if (window->handle())
+ return static_cast<QCocoaWindow *>(window->handle())->bottomLeftClippedByNSWindowOffset();
+ return QPoint();
+}
+
+QPoint QCocoaWindow::bottomLeftClippedByNSWindowOffset() const
+{
+ if (!m_contentView)
+ return QPoint();
+ const NSPoint origin = [m_contentView isFlipped] ? NSMakePoint(0, [m_contentView frame].size.height)
+ : NSMakePoint(0, 0);
+ const NSRect visibleRect = [m_contentView visibleRect];
+
+ return QPoint(visibleRect.origin.x, -visibleRect.origin.y + (origin.y - visibleRect.size.height));
+}
+
QMargins QCocoaWindow::frameMargins() const
{
NSRect frameW = [m_nsWindow frame];
diff --git a/src/plugins/platforms/cocoa/qmacclipboard.mm b/src/plugins/platforms/cocoa/qmacclipboard.mm
index 3d88a8d5df..f4fd32ffd1 100644
--- a/src/plugins/platforms/cocoa/qmacclipboard.mm
+++ b/src/plugins/platforms/cocoa/qmacclipboard.mm
@@ -43,7 +43,6 @@
#include <stdlib.h>
#include <string.h>
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
QT_BEGIN_NAMESPACE
@@ -555,7 +554,7 @@ QMacPasteboard::sync() const
QString qt_mac_get_pasteboardString(PasteboardRef paste)
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSPasteboard *pb = nil;
CFStringRef pbname;
if (PasteboardCopyName(paste, &pbname) == noErr) {
diff --git a/src/plugins/platforms/cocoa/qmultitouch_mac.mm b/src/plugins/platforms/cocoa/qmultitouch_mac.mm
index 6e7ebcc37c..6099add6bb 100644
--- a/src/plugins/platforms/cocoa/qmultitouch_mac.mm
+++ b/src/plugins/platforms/cocoa/qmultitouch_mac.mm
@@ -173,7 +173,7 @@ QCocoaTouch::getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch)
if (_touchCount != _currentTouches.size()) {
// Remove all instances, and basically start from scratch:
touchPoints.clear();
- foreach (QCocoaTouch *qcocoaTouch, _currentTouches.values()) {
+ foreach (QCocoaTouch *qcocoaTouch, _currentTouches) {
if (!_updateInternalStateOnly) {
qcocoaTouch->_touchPoint.state = Qt::TouchPointReleased;
touchPoints.insert(qcocoaTouch->_touchPoint.id, qcocoaTouch->_touchPoint);
@@ -190,7 +190,7 @@ QCocoaTouch::getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch)
// touch now (and refake a begin for it later, if needed).
if (_updateInternalStateOnly && !wasUpdateInternalStateOnly && !_currentTouches.isEmpty()) {
- QCocoaTouch *qcocoaTouch = _currentTouches.values().first();
+ QCocoaTouch *qcocoaTouch = _currentTouches.cbegin().value();
qcocoaTouch->_touchPoint.state = Qt::TouchPointReleased;
touchPoints.insert(qcocoaTouch->_touchPoint.id, qcocoaTouch->_touchPoint);
// Since this last touch also will end up being the first
diff --git a/src/plugins/platforms/cocoa/qnsview.mm b/src/plugins/platforms/cocoa/qnsview.mm
index f27335d752..4db55c1b73 100644
--- a/src/plugins/platforms/cocoa/qnsview.mm
+++ b/src/plugins/platforms/cocoa/qnsview.mm
@@ -39,7 +39,6 @@
#include "qnsview.h"
#include "qcocoawindow.h"
#include "qcocoahelpers.h"
-#include "qcocoaautoreleasepool.h"
#include "qmultitouch_mac_p.h"
#include "qcocoadrag.h"
#include <qpa/qplatformintegration.h>
@@ -347,6 +346,12 @@ static NSString *_q_NSWindowDidChangeOcclusionStateNotification = nil;
if (m_platformWindow->m_nsWindow && geometry == m_platformWindow->geometry())
return;
+ // It can happen that self.window is nil (if we are changing
+ // styleMask from/to borderless and content view is being re-parented)
+ // - this results in an invalid coordinates.
+ if (m_platformWindow->m_inSetStyleMask && !self.window)
+ return;
+
#ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
qDebug() << "QNSView::udpateGeometry" << m_platformWindow << geometry;
#endif
@@ -848,7 +853,7 @@ QT_WARNING_POP
{
[super updateTrackingAreas];
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
// NSTrackingInVisibleRect keeps care of updating once the tracking is set up, so bail out early
if (m_trackingArea && [[self trackingAreas] containsObject:m_trackingArea])
@@ -1789,7 +1794,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
-(void)registerDragTypes
{
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
QStringList customTypes = qt_mac_enabledDraggedTypes();
if (currentCustomDragTypes == 0 || *currentCustomDragTypes != customTypes) {
if (currentCustomDragTypes == 0)
diff --git a/src/plugins/platforms/cocoa/qprintengine_mac.mm b/src/plugins/platforms/cocoa/qprintengine_mac.mm
index 9e8fe8f1c8..edd1d656f0 100644
--- a/src/plugins/platforms/cocoa/qprintengine_mac.mm
+++ b/src/plugins/platforms/cocoa/qprintengine_mac.mm
@@ -38,7 +38,6 @@
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdebug.h>
-#include "qcocoaautoreleasepool.h"
#ifndef QT_NO_PRINTER
@@ -212,6 +211,9 @@ int QMacPrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
case QPaintDevice::PdmDevicePixelRatio:
val = 1;
break;
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ val = 1 * QPaintDevice::devicePixelRatioFScale();
+ break;
default:
val = 0;
qWarning("QPrinter::metric: Invalid metric command");
@@ -230,7 +232,7 @@ void QMacPrintEnginePrivate::initialize()
q->gccaps = paintEngine->gccaps;
- QCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
printInfo = [[NSPrintInfo alloc] initWithDictionary:[NSDictionary dictionary]];
QList<int> resolutions = m_printDevice->supportedResolutions();
diff --git a/src/plugins/platforms/cocoa/qt_mac_p.h b/src/plugins/platforms/cocoa/qt_mac_p.h
index e210f0221f..576e0f9729 100644
--- a/src/plugins/platforms/cocoa/qt_mac_p.h
+++ b/src/plugins/platforms/cocoa/qt_mac_p.h
@@ -103,17 +103,6 @@ public:
}
};
-class Q_WIDGETS_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_WIDGETS_EXPORT QMacWindowChangeEvent
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dpaintdevice.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dpaintdevice.cpp
index fee9ad88fa..40709fc3d0 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dpaintdevice.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dpaintdevice.cpp
@@ -113,6 +113,9 @@ int QWindowsDirect2DPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric)
case QPaintDevice::PdmDevicePixelRatio:
return 1;
break;
+ case QPaintDevice::PdmDevicePixelRatioScaled:
+ return 1 * devicePixelRatioFScale();
+ break;
case QPaintDevice::PdmWidthMM:
case QPaintDevice::PdmHeightMM:
return -1;
diff --git a/src/plugins/platforms/directfb/qdirectfbconvenience.cpp b/src/plugins/platforms/directfb/qdirectfbconvenience.cpp
index e635d4fd22..e1d97d9628 100644
--- a/src/plugins/platforms/directfb/qdirectfbconvenience.cpp
+++ b/src/plugins/platforms/directfb/qdirectfbconvenience.cpp
@@ -217,7 +217,7 @@ Qt::KeyboardModifiers QDirectFbConvenience::keyboardModifiers(DFBInputDeviceModi
modifiers |= Qt::ControlModifier;
}
if (mask & DIMM_META) {
- modifiers | Qt::MetaModifier;
+ modifiers |= Qt::MetaModifier;
}
return modifiers;
}
diff --git a/src/plugins/platforms/eglfs/cursor-atlas.png b/src/plugins/platforms/eglfs/cursor-atlas.png
index 40c5b6ef4f..40c5b6ef4f 100755..100644
--- a/src/plugins/platforms/eglfs/cursor-atlas.png
+++ b/src/plugins/platforms/eglfs/cursor-atlas.png
Binary files differ
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.cpp
index 18a66e34f5..f3df1f8445 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.cpp
@@ -208,6 +208,7 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
}
QList<drmModeModeInfo> modes;
+ modes.reserve(connector->count_modes);
qCDebug(qLcEglfsKmsDebug) << connectorName << "mode count:" << connector->count_modes;
for (int i = 0; i < connector->count_modes; i++) {
const drmModeModeInfo &mode = connector->modes[i];
@@ -282,7 +283,8 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
selected_mode,
false,
drmModeGetCrtc(m_dri_fd, crtc_id),
- modes
+ modes,
+ connectorProperty(connector, QByteArrayLiteral("DPMS"))
};
m_crtc_allocator |= (1 << output.crtc_id);
@@ -291,6 +293,22 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
return new QEglFSKmsScreen(m_integration, this, output, pos);
}
+drmModePropertyPtr QEglFSKmsDevice::connectorProperty(drmModeConnectorPtr connector, const QByteArray &name)
+{
+ drmModePropertyPtr prop;
+
+ for (int i = 0; i < connector->count_props; i++) {
+ prop = drmModeGetProperty(m_dri_fd, connector->props[i]);
+ if (!prop)
+ continue;
+ if (strcmp(prop->name, name.constData()) == 0)
+ return prop;
+ drmModeFreeProperty(prop);
+ }
+
+ return Q_NULLPTR;
+}
+
void QEglFSKmsDevice::pageFlipHandler(int fd, unsigned int sequence, unsigned int tv_sec, unsigned int tv_usec, void *user_data)
{
Q_UNUSED(fd);
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.h
index 23fca934e5..411f9a7200 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsdevice.h
@@ -78,6 +78,7 @@ private:
int crtcForConnector(drmModeResPtr resources, drmModeConnectorPtr connector);
QEglFSKmsScreen *screenForConnector(drmModeResPtr resources, drmModeConnectorPtr connector, QPoint pos);
+ drmModePropertyPtr connectorProperty(drmModeConnectorPtr connector, const QByteArray &name);
static void pageFlipHandler(int fd,
unsigned int sequence,
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsintegration.cpp
index 45224ccb87..d1814fb85d 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsintegration.cpp
@@ -36,8 +36,8 @@
#include "qeglfskmsdevice.h"
#include "qeglfskmsscreen.h"
#include "qeglfskmscursor.h"
+#include "qeglfscursor.h"
-#include <QtPlatformSupport/private/qeglplatformcursor_p.h>
#include <QtPlatformSupport/private/qdevicediscovery_p.h>
#include <QtCore/QLoggingCategory>
#include <QtCore/QJsonDocument>
@@ -176,7 +176,7 @@ QPlatformCursor *QEglFSKmsIntegration::createCursor(QPlatformScreen *screen) con
if (m_hwCursor)
return Q_NULLPTR;
else
- return new QEGLPlatformCursor(screen);
+ return new QEglFSCursor(screen);
}
void QEglFSKmsIntegration::waitForVSync(QPlatformSurface *surface) const
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.cpp
index 5e49c224a0..227c8f9a62 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.cpp
@@ -35,11 +35,11 @@
#include "qeglfskmsscreen.h"
#include "qeglfskmsdevice.h"
#include "qeglfskmscursor.h"
+#include "qeglfsintegration.h"
#include <QtCore/QLoggingCategory>
#include <QtGui/private/qguiapplication_p.h>
-#include <QtPlatformSupport/private/qeglplatformintegration_p.h>
#include <QtPlatformSupport/private/qfbvthandler_p.h>
QT_BEGIN_NAMESPACE
@@ -50,7 +50,7 @@ class QEglFSKmsInterruptHandler : public QObject
{
public:
QEglFSKmsInterruptHandler(QEglFSKmsScreen *screen) : m_screen(screen) {
- m_vtHandler = static_cast<QEGLPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration())->vtHandler();
+ m_vtHandler = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration())->vtHandler();
connect(m_vtHandler, &QFbVtHandler::interrupted, this, &QEglFSKmsInterruptHandler::restoreVideoMode);
connect(m_vtHandler, &QFbVtHandler::suspendRequested, this, &QEglFSKmsInterruptHandler::handleSuspendRequest);
}
@@ -119,6 +119,7 @@ QEglFSKmsScreen::QEglFSKmsScreen(QEglFSKmsIntegration *integration,
, m_output(output)
, m_pos(position)
, m_cursor(Q_NULLPTR)
+ , m_powerState(PowerStateOn)
, m_interruptHandler(new QEglFSKmsInterruptHandler(this))
{
m_siblings << this;
@@ -126,6 +127,10 @@ QEglFSKmsScreen::QEglFSKmsScreen(QEglFSKmsIntegration *integration,
QEglFSKmsScreen::~QEglFSKmsScreen()
{
+ if (m_output.dpms_prop) {
+ drmModeFreeProperty(m_output.dpms_prop);
+ m_output.dpms_prop = Q_NULLPTR;
+ }
restoreMode();
if (m_output.saved_crtc) {
drmModeFreeCrtc(m_output.saved_crtc);
@@ -266,10 +271,12 @@ void QEglFSKmsScreen::flip()
&m_output.connector_id, 1,
&m_output.modes[m_output.mode]);
- if (ret)
+ if (ret) {
qErrnoWarning("Could not set DRM mode!");
- else
+ } else {
m_output.mode_set = true;
+ setPowerState(PowerStateOn);
+ }
}
int ret = drmModePageFlip(m_device->fd(),
@@ -314,4 +321,19 @@ qreal QEglFSKmsScreen::refreshRate() const
return refresh > 0 ? refresh : 60;
}
+QPlatformScreen::PowerState QEglFSKmsScreen::powerState() const
+{
+ return m_powerState;
+}
+
+void QEglFSKmsScreen::setPowerState(QPlatformScreen::PowerState state)
+{
+ if (!m_output.dpms_prop)
+ return;
+
+ drmModeConnectorSetProperty(m_device->fd(), m_output.connector_id,
+ m_output.dpms_prop->prop_id, (int)state);
+ m_powerState = state;
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.h
index 4c1b0d02ad..2ce8700478 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsscreen.h
@@ -60,6 +60,7 @@ struct QEglFSKmsOutput
bool mode_set;
drmModeCrtcPtr saved_crtc;
QList<drmModeModeInfo> modes;
+ drmModePropertyPtr dpms_prop;
};
class QEglFSKmsScreen : public QEglFSScreen
@@ -103,6 +104,9 @@ public:
QEglFSKmsOutput &output() { return m_output; }
void restoreMode();
+ QPlatformScreen::PowerState powerState() const Q_DECL_OVERRIDE;
+ void setPowerState(QPlatformScreen::PowerState state) Q_DECL_OVERRIDE;
+
private:
QEglFSKmsIntegration *m_integration;
QEglFSKmsDevice *m_device;
@@ -117,6 +121,8 @@ private:
QList<QPlatformScreen *> m_siblings;
+ PowerState m_powerState;
+
struct FrameBuffer {
FrameBuffer() : fb(0) {}
uint32_t fb;
diff --git a/src/plugins/platforms/eglfs/eglfs_device_lib.pro b/src/plugins/platforms/eglfs/eglfs_device_lib.pro
index 729290706d..22a32663c7 100644
--- a/src/plugins/platforms/eglfs/eglfs_device_lib.pro
+++ b/src/plugins/platforms/eglfs/eglfs_device_lib.pro
@@ -26,6 +26,7 @@ DEFINES += QT_BUILD_EGL_DEVICE_LIB
SOURCES += $$PWD/qeglfsintegration.cpp \
$$PWD/qeglfswindow.cpp \
$$PWD/qeglfsscreen.cpp \
+ $$PWD/qeglfscursor.cpp \
$$PWD/qeglfshooks.cpp \
$$PWD/qeglfscontext.cpp \
$$PWD/qeglfsoffscreenwindow.cpp \
@@ -34,6 +35,7 @@ SOURCES += $$PWD/qeglfsintegration.cpp \
HEADERS += $$PWD/qeglfsintegration.h \
$$PWD/qeglfswindow.h \
$$PWD/qeglfsscreen.h \
+ $$PWD/qeglfscursor.h \
$$PWD/qeglfshooks.h \
$$PWD/qeglfscontext.h \
$$PWD/qeglfsoffscreenwindow.h \
diff --git a/src/plugins/platforms/eglfs/qeglfscontext.cpp b/src/plugins/platforms/eglfs/qeglfscontext.cpp
index 9216b7a85d..e2223aba43 100644
--- a/src/plugins/platforms/eglfs/qeglfscontext.cpp
+++ b/src/plugins/platforms/eglfs/qeglfscontext.cpp
@@ -32,15 +32,13 @@
****************************************************************************/
#include <QtGui/QSurface>
-#include <QtDebug>
-
-#include <QtPlatformSupport/private/qeglplatformcursor_p.h>
#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include "qeglfscontext.h"
#include "qeglfswindow.h"
#include "qeglfshooks.h"
-#include "qeglfscontext.h"
+#include "qeglfscursor.h"
QT_BEGIN_NAMESPACE
@@ -91,7 +89,7 @@ void QEglFSContext::swapBuffers(QPlatformSurface *surface)
// draw the cursor
if (surface->surface()->surfaceClass() == QSurface::Window) {
QPlatformWindow *window = static_cast<QPlatformWindow *>(surface);
- if (QEGLPlatformCursor *cursor = qobject_cast<QEGLPlatformCursor *>(window->screen()->cursor()))
+ if (QEglFSCursor *cursor = qobject_cast<QEglFSCursor *>(window->screen()->cursor()))
cursor->paintOnScreen();
}
diff --git a/src/platformsupport/eglconvenience/qeglplatformcursor.cpp b/src/plugins/platforms/eglfs/qeglfscursor.cpp
index 09243487c7..eea130a754 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcursor.cpp
+++ b/src/plugins/platforms/eglfs/qeglfscursor.cpp
@@ -31,36 +31,30 @@
**
****************************************************************************/
+#include "qeglfscursor.h"
+#include "qeglfsintegration.h"
+#include "qeglfsscreen.h"
+
#include <qpa/qwindowsysteminterface.h>
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLShaderProgram>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
-#include <QtDebug>
#include <QtGui/private/qguiapplication_p.h>
+#include <QtGui/private/qopenglvertexarrayobject_p.h>
-#include "qeglplatformcursor_p.h"
-#include "qeglplatformintegration_p.h"
-#include "qeglplatformscreen_p.h"
+#ifndef GL_VERTEX_ARRAY_BINDING
+#define GL_VERTEX_ARRAY_BINDING 0x85B5
+#endif
QT_BEGIN_NAMESPACE
-/*!
- \class QEGLPlatformCursor
- \brief Mouse cursor implementation using OpenGL.
- \since 5.2
- \internal
- \ingroup qpa
- */
-
-QEGLPlatformCursor::QEGLPlatformCursor(QPlatformScreen *screen)
+QEglFSCursor::QEglFSCursor(QPlatformScreen *screen)
: m_visible(true),
- m_screen(static_cast<QEGLPlatformScreen *>(screen)),
+ m_screen(static_cast<QEglFSScreen *>(screen)),
m_program(0),
- m_vertexCoordEntry(0),
- m_textureCoordEntry(0),
m_textureEntry(0),
m_deviceListener(0),
m_updateRequested(false)
@@ -81,35 +75,35 @@ QEGLPlatformCursor::QEGLPlatformCursor(QPlatformScreen *screen)
setCurrentCursor(&cursor);
#endif
- m_deviceListener = new QEGLPlatformCursorDeviceListener(this);
+ m_deviceListener = new QEglFSCursorDeviceListener(this);
connect(QGuiApplicationPrivate::inputDeviceManager(), &QInputDeviceManager::deviceListChanged,
- m_deviceListener, &QEGLPlatformCursorDeviceListener::onDeviceListChanged);
+ m_deviceListener, &QEglFSCursorDeviceListener::onDeviceListChanged);
updateMouseStatus();
}
-QEGLPlatformCursor::~QEGLPlatformCursor()
+QEglFSCursor::~QEglFSCursor()
{
resetResources();
delete m_deviceListener;
}
-void QEGLPlatformCursor::updateMouseStatus()
+void QEglFSCursor::updateMouseStatus()
{
m_visible = m_deviceListener->hasMouse();
}
-bool QEGLPlatformCursorDeviceListener::hasMouse() const
+bool QEglFSCursorDeviceListener::hasMouse() const
{
return QGuiApplicationPrivate::inputDeviceManager()->deviceCount(QInputDeviceManager::DeviceTypePointer) > 0;
}
-void QEGLPlatformCursorDeviceListener::onDeviceListChanged(QInputDeviceManager::DeviceType type)
+void QEglFSCursorDeviceListener::onDeviceListChanged(QInputDeviceManager::DeviceType type)
{
if (type == QInputDeviceManager::DeviceTypePointer)
m_cursor->updateMouseStatus();
}
-void QEGLPlatformCursor::resetResources()
+void QEglFSCursor::resetResources()
{
if (QOpenGLContext::currentContext()) {
delete m_program;
@@ -122,7 +116,7 @@ void QEGLPlatformCursor::resetResources()
m_cursorAtlas.texture = 0;
}
-void QEGLPlatformCursor::createShaderPrograms()
+void QEglFSCursor::createShaderPrograms()
{
static const char *textureVertexProgram =
"attribute highp vec2 vertexCoordEntry;\n"
@@ -143,14 +137,14 @@ void QEGLPlatformCursor::createShaderPrograms()
m_program = new QOpenGLShaderProgram;
m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
+ m_program->bindAttributeLocation("vertexCoordEntry", 0);
+ m_program->bindAttributeLocation("textureCoordEntry", 1);
m_program->link();
- m_vertexCoordEntry = m_program->attributeLocation("vertexCoordEntry");
- m_textureCoordEntry = m_program->attributeLocation("textureCoordEntry");
m_textureEntry = m_program->uniformLocation("texture");
}
-void QEGLPlatformCursor::createCursorTexture(uint *texture, const QImage &image)
+void QEglFSCursor::createCursorTexture(uint *texture, const QImage &image)
{
if (!*texture)
glGenTextures(1, texture);
@@ -164,7 +158,7 @@ void QEGLPlatformCursor::createCursorTexture(uint *texture, const QImage &image)
GL_RGBA, GL_UNSIGNED_BYTE, image.constBits());
}
-void QEGLPlatformCursor::initCursorAtlas()
+void QEglFSCursor::initCursorAtlas()
{
static QByteArray json = qgetenv("QT_QPA_EGLFS_CURSOR");
if (json.isEmpty())
@@ -202,7 +196,7 @@ void QEGLPlatformCursor::initCursorAtlas()
}
#ifndef QT_NO_CURSOR
-void QEGLPlatformCursor::changeCursor(QCursor *cursor, QWindow *window)
+void QEglFSCursor::changeCursor(QCursor *cursor, QWindow *window)
{
Q_UNUSED(window);
const QRect oldCursorRect = cursorRect();
@@ -210,7 +204,7 @@ void QEGLPlatformCursor::changeCursor(QCursor *cursor, QWindow *window)
update(oldCursorRect | cursorRect());
}
-bool QEGLPlatformCursor::setCurrentCursor(QCursor *cursor)
+bool QEglFSCursor::setCurrentCursor(QCursor *cursor)
{
if (!m_visible)
return false;
@@ -263,7 +257,7 @@ private:
QRegion m_region;
};
-bool QEGLPlatformCursor::event(QEvent *e)
+bool QEglFSCursor::event(QEvent *e)
{
if (e->type() == QEvent::User + 1) {
CursorUpdateEvent *ev = static_cast<CursorUpdateEvent *>(e);
@@ -275,7 +269,7 @@ bool QEGLPlatformCursor::event(QEvent *e)
return QPlatformCursor::event(e);
}
-void QEGLPlatformCursor::update(const QRegion &rgn)
+void QEglFSCursor::update(const QRegion &rgn)
{
if (!m_updateRequested) {
// Must not flush the window system events directly from here since we are likely to
@@ -286,17 +280,17 @@ void QEGLPlatformCursor::update(const QRegion &rgn)
}
}
-QRect QEGLPlatformCursor::cursorRect() const
+QRect QEglFSCursor::cursorRect() const
{
return QRect(m_cursor.pos - m_cursor.hotSpot, m_cursor.size);
}
-QPoint QEGLPlatformCursor::pos() const
+QPoint QEglFSCursor::pos() const
{
return m_cursor.pos;
}
-void QEGLPlatformCursor::setPos(const QPoint &pos)
+void QEglFSCursor::setPos(const QPoint &pos)
{
QGuiApplicationPrivate::inputDeviceManager()->setCursorPos(pos);
const QRect oldCursorRect = cursorRect();
@@ -305,7 +299,7 @@ void QEGLPlatformCursor::setPos(const QPoint &pos)
m_screen->handleCursorMove(m_cursor.pos);
}
-void QEGLPlatformCursor::pointerEvent(const QMouseEvent &event)
+void QEglFSCursor::pointerEvent(const QMouseEvent &event)
{
if (event.type() != QEvent::MouseMove)
return;
@@ -315,7 +309,7 @@ void QEGLPlatformCursor::pointerEvent(const QMouseEvent &event)
m_screen->handleCursorMove(m_cursor.pos);
}
-void QEGLPlatformCursor::paintOnScreen()
+void QEglFSCursor::paintOnScreen()
{
if (!m_visible)
return;
@@ -331,8 +325,105 @@ void QEGLPlatformCursor::paintOnScreen()
draw(r);
}
-void QEGLPlatformCursor::draw(const QRectF &r)
+// In order to prevent breaking code doing custom OpenGL rendering while
+// expecting the state in the context unchanged, save and restore all the state
+// we touch. The exception is Qt Quick where the scenegraph is known to be able
+// to deal with the changes we make.
+struct StateSaver
{
+ StateSaver() {
+ f = QOpenGLContext::currentContext()->functions();
+ vaoHelper = new QOpenGLVertexArrayObjectHelper(QOpenGLContext::currentContext());
+
+ static bool windowsChecked = false;
+ static bool shouldSave = true;
+ if (!windowsChecked) {
+ windowsChecked = true;
+ QWindowList windows = QGuiApplication::allWindows();
+ if (!windows.isEmpty() && windows[0]->inherits("QQuickWindow"))
+ shouldSave = false;
+ }
+ saved = shouldSave;
+ if (!shouldSave)
+ return;
+
+ f->glGetIntegerv(GL_CURRENT_PROGRAM, &program);
+ f->glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
+ f->glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture);
+ f->glGetIntegerv(GL_FRONT_FACE, &frontFace);
+ cull = f->glIsEnabled(GL_CULL_FACE);
+ depthTest = f->glIsEnabled(GL_DEPTH_TEST);
+ blend = f->glIsEnabled(GL_BLEND);
+ f->glGetIntegerv(GL_BLEND_SRC_RGB, blendFunc);
+ f->glGetIntegerv(GL_BLEND_SRC_ALPHA, blendFunc + 1);
+ f->glGetIntegerv(GL_BLEND_DST_RGB, blendFunc + 2);
+ f->glGetIntegerv(GL_BLEND_DST_ALPHA, blendFunc + 3);
+ f->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBuf);
+ if (vaoHelper->isValid())
+ f->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vao);
+ for (int i = 0; i < 2; ++i) {
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &va[i].enabled);
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &va[i].size);
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &va[i].type);
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &va[i].normalized);
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &va[i].stride);
+ f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &va[i].buffer);
+ f->glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &va[i].pointer);
+ }
+ }
+ ~StateSaver() {
+ if (saved) {
+ f->glUseProgram(program);
+ f->glBindTexture(GL_TEXTURE_2D, texture);
+ f->glActiveTexture(activeTexture);
+ f->glFrontFace(frontFace);
+ if (cull)
+ f->glEnable(GL_CULL_FACE);
+ else
+ f->glDisable(GL_CULL_FACE);
+ if (depthTest)
+ f->glEnable(GL_DEPTH_TEST);
+ else
+ f->glDisable(GL_DEPTH_TEST);
+ if (blend)
+ f->glEnable(GL_BLEND);
+ else
+ f->glDisable(GL_BLEND);
+ f->glBlendFuncSeparate(blendFunc[0], blendFunc[1], blendFunc[2], blendFunc[3]);
+ f->glBindBuffer(GL_ARRAY_BUFFER, arrayBuf);
+ if (vaoHelper->isValid())
+ vaoHelper->glBindVertexArray(vao);
+ for (int i = 0; i < 2; ++i) {
+ if (va[i].enabled)
+ f->glEnableVertexAttribArray(i);
+ else
+ f->glDisableVertexAttribArray(i);
+ f->glBindBuffer(GL_ARRAY_BUFFER, va[i].buffer);
+ f->glVertexAttribPointer(i, va[i].size, va[i].type, va[i].normalized, va[i].stride, va[i].pointer);
+ }
+ }
+ delete vaoHelper;
+ }
+ QOpenGLFunctions *f;
+ QOpenGLVertexArrayObjectHelper *vaoHelper;
+ bool saved;
+ GLint program;
+ GLint texture;
+ GLint activeTexture;
+ GLint frontFace;
+ bool cull;
+ bool depthTest;
+ bool blend;
+ GLint blendFunc[4];
+ GLint vao;
+ GLint arrayBuf;
+ struct { GLint enabled, type, size, normalized, stride, buffer; GLvoid *pointer; } va[2];
+};
+
+void QEglFSCursor::draw(const QRectF &r)
+{
+ StateSaver stateSaver;
+
if (!m_program) {
// one time initialization
initializeOpenGLFunctions();
@@ -382,13 +473,16 @@ void QEGLPlatformCursor::draw(const QRectF &r)
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_cursor.texture);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- m_program->enableAttributeArray(m_vertexCoordEntry);
- m_program->enableAttributeArray(m_textureCoordEntry);
+ if (stateSaver.vaoHelper->isValid())
+ stateSaver.vaoHelper->glBindVertexArray(0);
- m_program->setAttributeArray(m_vertexCoordEntry, cursorCoordinates, 2);
- m_program->setAttributeArray(m_textureCoordEntry, textureCoordinates, 2);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+ m_program->enableAttributeArray(0);
+ m_program->enableAttributeArray(1);
+ m_program->setAttributeArray(0, cursorCoordinates, 2);
+ m_program->setAttributeArray(1, textureCoordinates, 2);
m_program->setUniformValue(m_textureEntry, 0);
@@ -397,13 +491,11 @@ void QEGLPlatformCursor::draw(const QRectF &r)
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST); // disable depth testing to make sure cursor is always on top
- glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
- glDisable(GL_BLEND);
- glBindTexture(GL_TEXTURE_2D, 0);
- m_program->disableAttributeArray(m_textureCoordEntry);
- m_program->disableAttributeArray(m_vertexCoordEntry);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+ m_program->disableAttributeArray(0);
+ m_program->disableAttributeArray(1);
m_program->release();
}
diff --git a/src/platformsupport/eglconvenience/qeglplatformcursor_p.h b/src/plugins/platforms/eglfs/qeglfscursor.h
index b89dd1ca43..be5db41b37 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcursor_p.h
+++ b/src/plugins/platforms/eglfs/qeglfscursor.h
@@ -31,8 +31,8 @@
**
****************************************************************************/
-#ifndef QEGLPLATFORMCURSOR_H
-#define QEGLPLATFORMCURSOR_H
+#ifndef QEGLFSCURSOR_H
+#define QEGLFSCURSOR_H
//
// W A R N I N G
@@ -45,6 +45,7 @@
// We mean it.
//
+#include "qeglfsglobal.h"
#include <qpa/qplatformcursor.h>
#include <qpa/qplatformscreen.h>
#include <QtGui/QOpenGLFunctions>
@@ -53,30 +54,30 @@
QT_BEGIN_NAMESPACE
class QOpenGLShaderProgram;
-class QEGLPlatformCursor;
-class QEGLPlatformScreen;
+class QEglFSCursor;
+class QEglFSScreen;
-class QEGLPlatformCursorDeviceListener : public QObject
+class QEglFSCursorDeviceListener : public QObject
{
Q_OBJECT
public:
- QEGLPlatformCursorDeviceListener(QEGLPlatformCursor *cursor) : m_cursor(cursor) { }
+ QEglFSCursorDeviceListener(QEglFSCursor *cursor) : m_cursor(cursor) { }
bool hasMouse() const;
public slots:
void onDeviceListChanged(QInputDeviceManager::DeviceType type);
private:
- QEGLPlatformCursor *m_cursor;
+ QEglFSCursor *m_cursor;
};
-class QEGLPlatformCursor : public QPlatformCursor, protected QOpenGLFunctions
+class Q_EGLFS_EXPORT QEglFSCursor : public QPlatformCursor, protected QOpenGLFunctions
{
Q_OBJECT
public:
- QEGLPlatformCursor(QPlatformScreen *screen);
- ~QEGLPlatformCursor();
+ QEglFSCursor(QPlatformScreen *screen);
+ ~QEglFSCursor();
#ifndef QT_NO_CURSOR
void changeCursor(QCursor *cursor, QWindow *widget) Q_DECL_OVERRIDE;
@@ -128,15 +129,13 @@ private:
} m_cursorAtlas;
bool m_visible;
- QEGLPlatformScreen *m_screen;
+ QEglFSScreen *m_screen;
QOpenGLShaderProgram *m_program;
- int m_vertexCoordEntry;
- int m_textureCoordEntry;
int m_textureEntry;
- QEGLPlatformCursorDeviceListener *m_deviceListener;
+ QEglFSCursorDeviceListener *m_deviceListener;
bool m_updateRequested;
};
QT_END_NAMESPACE
-#endif // QEGLPLATFORMCURSOR_H
+#endif // QEGLFSCURSOR_H
diff --git a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp b/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
index 359b90f205..d27c949c8d 100644
--- a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
+++ b/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
@@ -33,8 +33,8 @@
#include "qeglfsdeviceintegration.h"
#include "qeglfsintegration.h"
+#include "qeglfscursor.h"
#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qeglplatformcursor_p.h>
#include <QGuiApplication>
#include <private/qguiapplication_p.h>
#include <QScreen>
@@ -99,6 +99,7 @@ QStringList QEGLDeviceIntegrationFactory::keys(const QString &pluginPath)
qCDebug(qLcEglDevDebug) << "EGL device integration plugin keys:" << list;
return list;
#else
+ Q_UNUSED(pluginPath);
return QStringList();
#endif
}
@@ -117,6 +118,9 @@ QEGLDeviceIntegration *QEGLDeviceIntegrationFactory::create(const QString &key,
qCDebug(qLcEglDevDebug) << "Using EGL device integration" << key;
else
qCWarning(qLcEglDevDebug) << "Failed to load EGL device integration" << key;
+#else
+ Q_UNUSED(key);
+ Q_UNUSED(pluginPath);
#endif
return integration;
}
@@ -282,7 +286,7 @@ bool QEGLDeviceIntegration::hasCapability(QPlatformIntegration::Capability cap)
QPlatformCursor *QEGLDeviceIntegration::createCursor(QPlatformScreen *screen) const
{
- return new QEGLPlatformCursor(screen);
+ return new QEglFSCursor(screen);
}
void QEGLDeviceIntegration::waitForVSync(QPlatformSurface *surface) const
diff --git a/src/plugins/platforms/eglfs/qeglfsintegration.cpp b/src/plugins/platforms/eglfs/qeglfsintegration.cpp
index 5eb8485dc7..5f2cc9abbc 100644
--- a/src/plugins/platforms/eglfs/qeglfsintegration.cpp
+++ b/src/plugins/platforms/eglfs/qeglfsintegration.cpp
@@ -39,19 +39,46 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QScreen>
#include <QtGui/QOffscreenSurface>
-#include <qpa/qplatformcursor.h>
+#include <QtGui/QWindow>
+#include <QtCore/QLoggingCategory>
+#include <qpa/qwindowsysteminterface.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
#include "qeglfsintegration.h"
#include "qeglfswindow.h"
#include "qeglfshooks.h"
#include "qeglfscontext.h"
#include "qeglfsoffscreenwindow.h"
+#include "qeglfscursor.h"
#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+
+#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtPlatformSupport/private/qgenericunixservices_p.h>
+#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtPlatformSupport/private/qfbvthandler_p.h>
+#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
+
#include <QtPlatformHeaders/QEGLNativeContext>
+#ifndef QT_NO_LIBINPUT
+#include <QtPlatformSupport/private/qlibinputhandler_p.h>
+#endif
+
+#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
+#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
+#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
+#include <QtPlatformSupport/private/qevdevtouchmanager_p.h>
+#endif
+
+#if !defined(QT_NO_TSLIB) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
+#include <QtPlatformSupport/private/qtslib_p.h>
+#endif
+
+#include <QtPlatformHeaders/qeglfsfunctions.h>
+
#include <EGL/egl.h>
static void initResources()
@@ -64,21 +91,18 @@ static void initResources()
QT_BEGIN_NAMESPACE
QEglFSIntegration::QEglFSIntegration()
+ : m_display(EGL_NO_DISPLAY),
+ m_inputContext(0),
+ m_fontDb(new QGenericUnixFontDatabase),
+ m_services(new QGenericUnixServices),
+ m_kbdMgr(0),
+ m_disableInputHandlers(false)
{
- mDisableInputHandlers = qEnvironmentVariableIntValue("QT_QPA_EGLFS_DISABLE_INPUT");
+ m_disableInputHandlers = qEnvironmentVariableIntValue("QT_QPA_EGLFS_DISABLE_INPUT");
initResources();
}
-bool QEglFSIntegration::hasCapability(QPlatformIntegration::Capability cap) const
-{
- // We assume that devices will have more and not less capabilities
- if (qt_egl_device_integration()->hasCapability(cap))
- return true;
-
- return QEGLPlatformIntegration::hasCapability(cap);
-}
-
void QEglFSIntegration::addScreen(QPlatformScreen *screen)
{
screenAdded(screen);
@@ -93,9 +117,19 @@ void QEglFSIntegration::initialize()
{
qt_egl_device_integration()->platformInit();
- QEGLPlatformIntegration::initialize();
+ m_display = eglGetDisplay(nativeDisplay());
+ if (m_display == EGL_NO_DISPLAY)
+ qFatal("Could not open egl display");
+
+ EGLint major, minor;
+ if (!eglInitialize(m_display, &major, &minor))
+ qFatal("Could not initialize egl display");
- if (!mDisableInputHandlers)
+ m_inputContext = QPlatformInputContextFactory::create();
+
+ m_vtHandler.reset(new QFbVtHandler);
+
+ if (!m_disableInputHandlers)
createInputHandlers();
if (qt_egl_device_integration()->usesDefaultScreen())
@@ -108,52 +142,283 @@ void QEglFSIntegration::destroy()
{
foreach (QWindow *w, qGuiApp->topLevelWindows())
w->destroy();
+
qt_egl_device_integration()->screenDestroy();
- if (display() != EGL_NO_DISPLAY)
- eglTerminate(display());
+
+ if (m_display != EGL_NO_DISPLAY)
+ eglTerminate(m_display);
+
qt_egl_device_integration()->platformDestroy();
}
-EGLNativeDisplayType QEglFSIntegration::nativeDisplay() const
+QAbstractEventDispatcher *QEglFSIntegration::createEventDispatcher() const
{
- return qt_egl_device_integration()->platformDisplay();
+ return createUnixEventDispatcher();
+}
+
+QPlatformServices *QEglFSIntegration::services() const
+{
+ return m_services.data();
}
-QEGLPlatformWindow *QEglFSIntegration::createWindow(QWindow *window) const
+QPlatformFontDatabase *QEglFSIntegration::fontDatabase() const
{
- return new QEglFSWindow(window);
+ return m_fontDb.data();
}
-QEGLPlatformContext *QEglFSIntegration::createContext(const QSurfaceFormat &format,
- QPlatformOpenGLContext *shareContext,
- EGLDisplay display,
- QVariant *nativeHandle) const
+QPlatformBackingStore *QEglFSIntegration::createPlatformBackingStore(QWindow *window) const
{
+ QOpenGLCompositorBackingStore *bs = new QOpenGLCompositorBackingStore(window);
+ if (!window->handle())
+ window->create();
+ static_cast<QEglFSWindow *>(window->handle())->setBackingStore(bs);
+ return bs;
+}
+
+QPlatformWindow *QEglFSIntegration::createPlatformWindow(QWindow *window) const
+{
+ QWindowSystemInterface::flushWindowSystemEvents();
+ QEglFSWindow *w = new QEglFSWindow(window);
+ w->create();
+ if (window->type() != Qt::ToolTip)
+ w->requestActivateWindow();
+ return w;
+}
+
+QPlatformOpenGLContext *QEglFSIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
+{
+ // If there is a "root" window into which raster and QOpenGLWidget content is
+ // composited, all other contexts must share with its context.
+ QOpenGLContext *compositingContext = QOpenGLCompositor::instance()->context();
+ EGLDisplay dpy = context->screen() ? static_cast<QEglFSScreen *>(context->screen()->handle())->display() : display();
+ QPlatformOpenGLContext *share = compositingContext ? compositingContext->handle() : context->shareHandle();
+ QVariant nativeHandle = context->nativeHandle();
+
QEglFSContext *ctx;
- QSurfaceFormat adjustedFormat = qt_egl_device_integration()->surfaceFormatFor(format);
- if (!nativeHandle || nativeHandle->isNull()) {
- EGLConfig config = QEglFSIntegration::chooseConfig(display, adjustedFormat);
- ctx = new QEglFSContext(adjustedFormat, shareContext, display, &config, QVariant());
+ QSurfaceFormat adjustedFormat = qt_egl_device_integration()->surfaceFormatFor(context->format());
+ if (nativeHandle.isNull()) {
+ EGLConfig config = QEglFSIntegration::chooseConfig(dpy, adjustedFormat);
+ ctx = new QEglFSContext(adjustedFormat, share, dpy, &config, QVariant());
} else {
- ctx = new QEglFSContext(adjustedFormat, shareContext, display, 0, *nativeHandle);
+ ctx = new QEglFSContext(adjustedFormat, share, dpy, 0, nativeHandle);
}
- *nativeHandle = QVariant::fromValue<QEGLNativeContext>(QEGLNativeContext(ctx->eglContext(), display));
+ nativeHandle = QVariant::fromValue<QEGLNativeContext>(QEGLNativeContext(ctx->eglContext(), dpy));
+
+ context->setNativeHandle(nativeHandle);
return ctx;
}
-QPlatformOffscreenSurface *QEglFSIntegration::createOffscreenSurface(EGLDisplay display,
- const QSurfaceFormat &format,
- QOffscreenSurface *surface) const
+QPlatformOffscreenSurface *QEglFSIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const
{
- QSurfaceFormat fmt = qt_egl_device_integration()->surfaceFormatFor(format);
+ EGLDisplay dpy = surface->screen() ? static_cast<QEglFSScreen *>(surface->screen()->handle())->display() : display();
+ QSurfaceFormat fmt = qt_egl_device_integration()->surfaceFormatFor(surface->requestedFormat());
if (qt_egl_device_integration()->supportsPBuffers())
- return new QEGLPbuffer(display, fmt, surface);
+ return new QEGLPbuffer(dpy, fmt, surface);
else
- return new QEglFSOffscreenWindow(display, fmt, surface);
-
+ return new QEglFSOffscreenWindow(dpy, fmt, surface);
// Never return null. Multiple QWindows are not supported by this plugin.
}
+bool QEglFSIntegration::hasCapability(QPlatformIntegration::Capability cap) const
+{
+ // We assume that devices will have more and not less capabilities
+ if (qt_egl_device_integration()->hasCapability(cap))
+ return true;
+
+ switch (cap) {
+ case ThreadedPixmaps: return true;
+ case OpenGL: return true;
+ case ThreadedOpenGL: return true;
+ case WindowManagement: return false;
+ case RasterGLSurface: return true;
+ default: return QPlatformIntegration::hasCapability(cap);
+ }
+}
+
+QPlatformNativeInterface *QEglFSIntegration::nativeInterface() const
+{
+ return const_cast<QEglFSIntegration *>(this);
+}
+
+enum ResourceType {
+ EglDisplay,
+ EglWindow,
+ EglContext,
+ EglConfig,
+ NativeDisplay,
+ XlibDisplay
+};
+
+static int resourceType(const QByteArray &key)
+{
+ static const QByteArray names[] = { // match ResourceType
+ QByteArrayLiteral("egldisplay"),
+ QByteArrayLiteral("eglwindow"),
+ QByteArrayLiteral("eglcontext"),
+ QByteArrayLiteral("eglconfig"),
+ QByteArrayLiteral("nativedisplay"),
+ QByteArrayLiteral("display")
+ };
+ const QByteArray *end = names + sizeof(names) / sizeof(names[0]);
+ const QByteArray *result = std::find(names, end, key);
+ if (result == end)
+ result = std::find(names, end, key.toLower());
+ return int(result - names);
+}
+
+void *QEglFSIntegration::nativeResourceForIntegration(const QByteArray &resource)
+{
+ void *result = 0;
+
+ switch (resourceType(resource)) {
+ case EglDisplay:
+ result = display();
+ break;
+ case NativeDisplay:
+ result = reinterpret_cast<void*>(nativeDisplay());
+ break;
+ default:
+ break;
+ }
+
+ return result;
+}
+
+void *QEglFSIntegration::nativeResourceForScreen(const QByteArray &resource, QScreen *)
+{
+ void *result = 0;
+
+ switch (resourceType(resource)) {
+ case XlibDisplay:
+ // Play nice when using the x11 hooks: Be compatible with xcb that allows querying
+ // the X Display pointer, which is nothing but our native display.
+ result = reinterpret_cast<void*>(nativeDisplay());
+ break;
+ default:
+ break;
+ }
+
+ return result;
+}
+
+void *QEglFSIntegration::nativeResourceForWindow(const QByteArray &resource, QWindow *window)
+{
+ void *result = 0;
+
+ switch (resourceType(resource)) {
+ case EglDisplay:
+ if (window && window->handle())
+ result = static_cast<QEglFSScreen *>(window->handle()->screen())->display();
+ else
+ result = display();
+ break;
+ case EglWindow:
+ if (window && window->handle())
+ result = reinterpret_cast<void*>(static_cast<QEglFSWindow *>(window->handle())->eglWindow());
+ break;
+ default:
+ break;
+ }
+
+ return result;
+}
+
+void *QEglFSIntegration::nativeResourceForContext(const QByteArray &resource, QOpenGLContext *context)
+{
+ void *result = 0;
+
+ switch (resourceType(resource)) {
+ case EglContext:
+ if (context->handle())
+ result = static_cast<QEglFSContext *>(context->handle())->eglContext();
+ break;
+ case EglConfig:
+ if (context->handle())
+ result = static_cast<QEglFSContext *>(context->handle())->eglConfig();
+ break;
+ case EglDisplay:
+ if (context->handle())
+ result = static_cast<QEglFSContext *>(context->handle())->eglDisplay();
+ break;
+ default:
+ break;
+ }
+
+ return result;
+}
+
+static void *eglContextForContext(QOpenGLContext *context)
+{
+ Q_ASSERT(context);
+
+ QEglFSContext *handle = static_cast<QEglFSContext *>(context->handle());
+ if (!handle)
+ return 0;
+
+ return handle->eglContext();
+}
+
+QPlatformNativeInterface::NativeResourceForContextFunction QEglFSIntegration::nativeResourceFunctionForContext(const QByteArray &resource)
+{
+ QByteArray lowerCaseResource = resource.toLower();
+ if (lowerCaseResource == "get_egl_context")
+ return NativeResourceForContextFunction(eglContextForContext);
+
+ return 0;
+}
+
+QFunctionPointer QEglFSIntegration::platformFunction(const QByteArray &function) const
+{
+#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
+ if (function == QEglFSFunctions::loadKeymapTypeIdentifier())
+ return QFunctionPointer(loadKeymapStatic);
+#else
+ Q_UNUSED(function)
+#endif
+
+ return 0;
+}
+
+void QEglFSIntegration::loadKeymapStatic(const QString &filename)
+{
+#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
+ QEglFSIntegration *self = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration());
+ if (self->m_kbdMgr)
+ self->m_kbdMgr->loadKeymap(filename);
+ else
+ qWarning("QEglFSIntegration: Cannot load keymap, no keyboard handler found");
+#else
+ Q_UNUSED(filename);
+#endif
+}
+
+void QEglFSIntegration::createInputHandlers()
+{
+#ifndef QT_NO_LIBINPUT
+ if (!qEnvironmentVariableIntValue("QT_QPA_EGLFS_NO_LIBINPUT")) {
+ new QLibInputHandler(QLatin1String("libinput"), QString());
+ return;
+ }
+#endif
+
+#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
+ m_kbdMgr = new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString() /* spec */, this);
+ new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString() /* spec */, this);
+#ifndef QT_NO_TSLIB
+ const bool useTslib = qEnvironmentVariableIntValue("QT_QPA_EGLFS_TSLIB");
+ if (useTslib)
+ new QTsLibMouseHandler(QLatin1String("TsLib"), QString() /* spec */);
+ else
+#endif // QT_NO_TSLIB
+ new QEvdevTouchManager(QLatin1String("EvdevTouch"), QString() /* spec */, this);
+#endif
+}
+
+EGLNativeDisplayType QEglFSIntegration::nativeDisplay() const
+{
+ return qt_egl_device_integration()->platformDisplay();
+}
+
EGLConfig QEglFSIntegration::chooseConfig(EGLDisplay display, const QSurfaceFormat &format)
{
class Chooser : public QEglConfigChooser {
diff --git a/src/plugins/platforms/eglfs/qeglfsintegration.h b/src/plugins/platforms/eglfs/qeglfsintegration.h
index 11b643d540..98c7ee9f78 100644
--- a/src/plugins/platforms/eglfs/qeglfsintegration.h
+++ b/src/plugins/platforms/eglfs/qeglfsintegration.h
@@ -34,41 +34,72 @@
#ifndef QEGLFSINTEGRATION_H
#define QEGLFSINTEGRATION_H
-#include <QtPlatformSupport/private/qeglplatformintegration_p.h>
+#include <QtCore/QVariant>
+#include <qpa/qplatformintegration.h>
+#include <qpa/qplatformnativeinterface.h>
#include <qpa/qplatformscreen.h>
#include <EGL/egl.h>
#include "qeglfsglobal.h"
QT_BEGIN_NAMESPACE
-class Q_EGLFS_EXPORT QEglFSIntegration : public QEGLPlatformIntegration
+class QEglFSWindow;
+class QEglFSContext;
+class QFbVtHandler;
+class QEvdevKeyboardManager;
+
+class Q_EGLFS_EXPORT QEglFSIntegration : public QPlatformIntegration, public QPlatformNativeInterface
{
public:
QEglFSIntegration();
- void addScreen(QPlatformScreen *screen);
- void removeScreen(QPlatformScreen *screen);
-
void initialize() Q_DECL_OVERRIDE;
void destroy() Q_DECL_OVERRIDE;
+ EGLDisplay display() const { return m_display; }
+
+ QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
+ QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
+ QPlatformServices *services() const Q_DECL_OVERRIDE;
+ QPlatformInputContext *inputContext() const Q_DECL_OVERRIDE { return m_inputContext; }
+
+ QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
+ QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const Q_DECL_OVERRIDE;
+ QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const Q_DECL_OVERRIDE;
+ QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
+
bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
- static EGLConfig chooseConfig(EGLDisplay display, const QSurfaceFormat &format);
+ QPlatformNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
-protected:
- QEGLPlatformWindow *createWindow(QWindow *window) const Q_DECL_OVERRIDE;
- QEGLPlatformContext *createContext(const QSurfaceFormat &format,
- QPlatformOpenGLContext *shareContext,
- EGLDisplay display,
- QVariant *nativeHandle) const Q_DECL_OVERRIDE;
- QPlatformOffscreenSurface *createOffscreenSurface(EGLDisplay display,
- const QSurfaceFormat &format,
- QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
- EGLNativeDisplayType nativeDisplay() const Q_DECL_OVERRIDE;
+ // QPlatformNativeInterface
+ void *nativeResourceForIntegration(const QByteArray &resource) Q_DECL_OVERRIDE;
+ void *nativeResourceForScreen(const QByteArray &resource, QScreen *screen) Q_DECL_OVERRIDE;
+ void *nativeResourceForWindow(const QByteArray &resource, QWindow *window) Q_DECL_OVERRIDE;
+ void *nativeResourceForContext(const QByteArray &resource, QOpenGLContext *context) Q_DECL_OVERRIDE;
+ NativeResourceForContextFunction nativeResourceFunctionForContext(const QByteArray &resource) Q_DECL_OVERRIDE;
+
+ QFunctionPointer platformFunction(const QByteArray &function) const Q_DECL_OVERRIDE;
+
+ QFbVtHandler *vtHandler() { return m_vtHandler.data(); }
+
+ void addScreen(QPlatformScreen *screen);
+ void removeScreen(QPlatformScreen *screen);
+
+ static EGLConfig chooseConfig(EGLDisplay display, const QSurfaceFormat &format);
private:
- bool mDisableInputHandlers;
+ EGLNativeDisplayType nativeDisplay() const;
+ void createInputHandlers();
+ static void loadKeymapStatic(const QString &filename);
+
+ EGLDisplay m_display;
+ QPlatformInputContext *m_inputContext;
+ QScopedPointer<QPlatformFontDatabase> m_fontDb;
+ QScopedPointer<QPlatformServices> m_services;
+ QScopedPointer<QFbVtHandler> m_vtHandler;
+ QEvdevKeyboardManager *m_kbdMgr;
+ bool m_disableInputHandlers;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsscreen.cpp b/src/plugins/platforms/eglfs/qeglfsscreen.cpp
index 1b6e2307f8..22ec424451 100644
--- a/src/plugins/platforms/eglfs/qeglfsscreen.cpp
+++ b/src/plugins/platforms/eglfs/qeglfsscreen.cpp
@@ -32,7 +32,10 @@
****************************************************************************/
#include <QtCore/qtextstream.h>
-#include <QtGui/qpa/qplatformcursor.h>
+#include <QtGui/qwindow.h>
+#include <qpa/qwindowsysteminterface.h>
+#include <qpa/qplatformcursor.h>
+#include <QtPlatformSupport/private/qopenglcompositor_p.h>
#include "qeglfsscreen.h"
#include "qeglfswindow.h"
@@ -41,7 +44,8 @@
QT_BEGIN_NAMESPACE
QEglFSScreen::QEglFSScreen(EGLDisplay dpy)
- : QEGLPlatformScreen(dpy),
+ : m_dpy(dpy),
+ m_pointerWindow(0),
m_surface(EGL_NO_SURFACE),
m_cursor(0)
{
@@ -51,6 +55,7 @@ QEglFSScreen::QEglFSScreen(EGLDisplay dpy)
QEglFSScreen::~QEglFSScreen()
{
delete m_cursor;
+ QOpenGLCompositor::destroy();
}
QRect QEglFSScreen::geometry() const
@@ -103,4 +108,89 @@ void QEglFSScreen::setPrimarySurface(EGLSurface surface)
m_surface = surface;
}
+void QEglFSScreen::handleCursorMove(const QPoint &pos)
+{
+ const QOpenGLCompositor *compositor = QOpenGLCompositor::instance();
+ const QList<QOpenGLCompositorWindow *> windows = compositor->windows();
+
+ // Generate enter and leave events like a real windowing system would do.
+ if (windows.isEmpty())
+ return;
+
+ // First window is always fullscreen.
+ if (windows.count() == 1) {
+ QWindow *window = windows[0]->sourceWindow();
+ if (m_pointerWindow != window) {
+ m_pointerWindow = window;
+ QWindowSystemInterface::handleEnterEvent(window, window->mapFromGlobal(pos), pos);
+ }
+ return;
+ }
+
+ QWindow *enter = 0, *leave = 0;
+ for (int i = windows.count() - 1; i >= 0; --i) {
+ QWindow *window = windows[i]->sourceWindow();
+ const QRect geom = window->geometry();
+ if (geom.contains(pos)) {
+ if (m_pointerWindow != window) {
+ leave = m_pointerWindow;
+ m_pointerWindow = window;
+ enter = window;
+ }
+ break;
+ }
+ }
+
+ if (enter && leave)
+ QWindowSystemInterface::handleEnterLeaveEvent(enter, leave, enter->mapFromGlobal(pos), pos);
+}
+
+QPixmap QEglFSScreen::grabWindow(WId wid, int x, int y, int width, int height) const
+{
+ QOpenGLCompositor *compositor = QOpenGLCompositor::instance();
+ const QList<QOpenGLCompositorWindow *> windows = compositor->windows();
+ Q_ASSERT(!windows.isEmpty());
+
+ QImage img;
+
+ if (static_cast<QEglFSWindow *>(windows.first()->sourceWindow()->handle())->isRaster()) {
+ // Request the compositor to render everything into an FBO and read it back. This
+ // is of course slow, but it's safe and reliable. It will not include the mouse
+ // cursor, which is a plus.
+ img = compositor->grab();
+ } else {
+ // Just a single OpenGL window without compositing. Do not support this case for now. Doing
+ // glReadPixels is not an option since it would read from the back buffer which may have
+ // undefined content when calling right after a swapBuffers (unless preserved swap is
+ // available and enabled, but we have no support for that).
+ qWarning("grabWindow: Not supported for non-composited OpenGL content. Use QQuickWindow::grabWindow() instead.");
+ return QPixmap();
+ }
+
+ if (!wid) {
+ const QSize screenSize = geometry().size();
+ if (width < 0)
+ width = screenSize.width() - x;
+ if (height < 0)
+ height = screenSize.height() - y;
+ return QPixmap::fromImage(img).copy(x, y, width, height);
+ }
+
+ foreach (QOpenGLCompositorWindow *w, windows) {
+ const QWindow *window = w->sourceWindow();
+ if (window->winId() == wid) {
+ const QRect geom = window->geometry();
+ if (width < 0)
+ width = geom.width() - x;
+ if (height < 0)
+ height = geom.height() - y;
+ QRect rect(geom.topLeft() + QPoint(x, y), QSize(width, height));
+ rect &= window->geometry();
+ return QPixmap::fromImage(img).copy(rect);
+ }
+ }
+
+ return QPixmap();
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsscreen.h b/src/plugins/platforms/eglfs/qeglfsscreen.h
index 07b6ff63ef..dc291285ad 100644
--- a/src/plugins/platforms/eglfs/qeglfsscreen.h
+++ b/src/plugins/platforms/eglfs/qeglfsscreen.h
@@ -35,7 +35,6 @@
#define QEGLFSSCREEN_H
#include "qeglfsglobal.h"
-#include <QtPlatformSupport/private/qeglplatformscreen_p.h>
#include <EGL/egl.h>
QT_BEGIN_NAMESPACE
@@ -43,7 +42,7 @@ QT_BEGIN_NAMESPACE
class QEglFSWindow;
class QOpenGLContext;
-class Q_EGLFS_EXPORT QEglFSScreen : public QEGLPlatformScreen
+class Q_EGLFS_EXPORT QEglFSScreen : public QPlatformScreen
{
public:
QEglFSScreen(EGLDisplay display);
@@ -62,16 +61,23 @@ public:
qreal refreshRate() const Q_DECL_OVERRIDE;
+ QPixmap grabWindow(WId wid, int x, int y, int width, int height) const Q_DECL_OVERRIDE;
+
EGLSurface primarySurface() const { return m_surface; }
-protected:
- void setPrimarySurface(EGLSurface surface);
+ EGLDisplay display() const { return m_dpy; }
+
+ void handleCursorMove(const QPoint &pos);
private:
- friend class QEglFSWindow;
+ void setPrimarySurface(EGLSurface surface);
+ EGLDisplay m_dpy;
+ QWindow *m_pointerWindow;
EGLSurface m_surface;
QPlatformCursor *m_cursor;
+
+ friend class QEglFSWindow;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfswindow.cpp b/src/plugins/platforms/eglfs/qeglfswindow.cpp
index c0d51c94a5..c3b9dd6ef0 100644
--- a/src/plugins/platforms/eglfs/qeglfswindow.cpp
+++ b/src/plugins/platforms/eglfs/qeglfswindow.cpp
@@ -37,21 +37,23 @@
#include <private/qguiapplication_p.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <QtGui/QOpenGLContext>
-#include <QtPlatformSupport/private/qeglplatformcursor_p.h>
#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
#include "qeglfswindow.h"
+#include "qeglfscursor.h"
#include "qeglfshooks.h"
-#include <QtDebug>
-
QT_BEGIN_NAMESPACE
QEglFSWindow::QEglFSWindow(QWindow *w)
- : QEGLPlatformWindow(w)
- , m_surface(0)
- , m_window(0)
- , m_flags(0)
+ : QPlatformWindow(w),
+ m_backingStore(0),
+ m_raster(false),
+ m_winId(0),
+ m_surface(0),
+ m_window(0),
+ m_flags(0)
{
}
@@ -60,12 +62,34 @@ QEglFSWindow::~QEglFSWindow()
destroy();
}
+static WId newWId()
+{
+ static WId id = 0;
+
+ if (id == std::numeric_limits<WId>::max())
+ qWarning("QEGLPlatformWindow: Out of window IDs");
+
+ return ++id;
+}
+
void QEglFSWindow::create()
{
if (m_flags.testFlag(Created))
return;
- QEGLPlatformWindow::create();
+ m_winId = newWId();
+
+ // Save the original surface type before changing to OpenGLSurface.
+ m_raster = (window()->surfaceType() == QSurface::RasterSurface);
+ if (m_raster) // change to OpenGL, but not for RasterGLSurface
+ window()->setSurfaceType(QSurface::OpenGLSurface);
+
+ if (window()->type() == Qt::Desktop) {
+ QRect fullscreenRect(QPoint(), screen()->availableGeometry().size());
+ QPlatformWindow::setGeometry(fullscreenRect);
+ QWindowSystemInterface::handleGeometryChange(window(), fullscreenRect);
+ return;
+ }
m_flags = Created;
@@ -120,7 +144,7 @@ void QEglFSWindow::destroy()
{
QEglFSScreen *screen = this->screen();
if (m_flags.testFlag(HasNativeWindow)) {
- QEGLPlatformCursor *cursor = qobject_cast<QEGLPlatformCursor *>(screen->cursor());
+ QEglFSCursor *cursor = qobject_cast<QEglFSCursor *>(screen->cursor());
if (cursor)
cursor->resetResources();
@@ -265,4 +289,41 @@ QEglFSScreen *QEglFSWindow::screen() const
return static_cast<QEglFSScreen *>(QPlatformWindow::screen());
}
+bool QEglFSWindow::isRaster() const
+{
+ return m_raster || window()->surfaceType() == QSurface::RasterGLSurface;
+}
+
+QWindow *QEglFSWindow::sourceWindow() const
+{
+ return window();
+}
+
+const QPlatformTextureList *QEglFSWindow::textures() const
+{
+ if (m_backingStore)
+ return m_backingStore->textures();
+
+ return 0;
+}
+
+void QEglFSWindow::endCompositing()
+{
+ if (m_backingStore)
+ m_backingStore->notifyComposited();
+}
+
+WId QEglFSWindow::winId() const
+{
+ return m_winId;
+}
+
+void QEglFSWindow::setOpacity(qreal)
+{
+ if (!isRaster())
+ qWarning("QEglFSWindow: Cannot set opacity for non-raster windows");
+
+ // Nothing to do here. The opacity is stored in the QWindow.
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfswindow.h b/src/plugins/platforms/eglfs/qeglfswindow.h
index f9d207c153..53b9e18dc1 100644
--- a/src/plugins/platforms/eglfs/qeglfswindow.h
+++ b/src/plugins/platforms/eglfs/qeglfswindow.h
@@ -37,17 +37,23 @@
#include "qeglfsintegration.h"
#include "qeglfsscreen.h"
#include "qeglfsglobal.h"
-#include <QtPlatformSupport/private/qeglplatformwindow_p.h>
+
+#include <qpa/qplatformwindow.h>
+#include <QtPlatformSupport/private/qopenglcompositor_p.h>
+#include <EGL/egl.h>
QT_BEGIN_NAMESPACE
-class Q_EGLFS_EXPORT QEglFSWindow : public QEGLPlatformWindow
+class QOpenGLCompositorBackingStore;
+class QPlatformTextureList;
+
+class Q_EGLFS_EXPORT QEglFSWindow : public QPlatformWindow, public QOpenGLCompositorWindow
{
public:
QEglFSWindow(QWindow *w);
~QEglFSWindow();
- void create() Q_DECL_OVERRIDE;
+ void create();
void destroy();
void setGeometry(const QRect &) Q_DECL_OVERRIDE;
@@ -58,13 +64,15 @@ public:
void lower() Q_DECL_OVERRIDE;
void propagateSizeHints() Q_DECL_OVERRIDE { }
- void setOpacity(qreal) Q_DECL_OVERRIDE { }
void setMask(const QRegion &) Q_DECL_OVERRIDE { }
bool setKeyboardGrabEnabled(bool) Q_DECL_OVERRIDE { return false; }
bool setMouseGrabEnabled(bool) Q_DECL_OVERRIDE { return false; }
+ void setOpacity(qreal) Q_DECL_OVERRIDE;
+ WId winId() const Q_DECL_OVERRIDE;
QSurfaceFormat format() const Q_DECL_OVERRIDE;
- EGLNativeWindowType eglWindow() const Q_DECL_OVERRIDE;
+
+ EGLNativeWindowType eglWindow() const;
EGLSurface surface() const;
QEglFSScreen *screen() const;
@@ -73,11 +81,22 @@ public:
virtual void invalidateSurface() Q_DECL_OVERRIDE;
virtual void resetSurface();
-protected:
+ QOpenGLCompositorBackingStore *backingStore() { return m_backingStore; }
+ void setBackingStore(QOpenGLCompositorBackingStore *backingStore) { m_backingStore = backingStore; }
+ bool isRaster() const;
+
+ QWindow *sourceWindow() const Q_DECL_OVERRIDE;
+ const QPlatformTextureList *textures() const Q_DECL_OVERRIDE;
+ void endCompositing() Q_DECL_OVERRIDE;
+
+private:
+ QOpenGLCompositorBackingStore *m_backingStore;
+ bool m_raster;
+ WId m_winId;
+
EGLSurface m_surface;
EGLNativeWindowType m_window;
-private:
EGLConfig m_config;
QSurfaceFormat m_format;
diff --git a/src/plugins/platforms/haiku/qhaikuclipboard.cpp b/src/plugins/platforms/haiku/qhaikuclipboard.cpp
index f3aa9dc36e..a2d7e96d71 100644
--- a/src/plugins/platforms/haiku/qhaikuclipboard.cpp
+++ b/src/plugins/platforms/haiku/qhaikuclipboard.cpp
@@ -41,6 +41,8 @@
#include <Clipboard.h>
QHaikuClipboard::QHaikuClipboard()
+ : m_systemMimeData(Q_NULLPTR)
+ , m_userMimeData(Q_NULLPTR)
{
if (be_clipboard)
be_clipboard->StartWatching(BMessenger(this));
@@ -50,17 +52,26 @@ QHaikuClipboard::~QHaikuClipboard()
{
if (be_clipboard)
be_clipboard->StopWatching(BMessenger(this));
+
+ delete m_userMimeData;
+ delete m_systemMimeData;
}
QMimeData *QHaikuClipboard::mimeData(QClipboard::Mode mode)
{
- QMimeData *mimeData = new QMimeData();
-
if (mode != QClipboard::Clipboard)
- return mimeData;
+ return 0;
+
+ if (m_userMimeData)
+ return m_userMimeData;
if (!be_clipboard->Lock())
- return mimeData;
+ return 0;
+
+ if (!m_systemMimeData)
+ m_systemMimeData = new QMimeData();
+ else
+ m_systemMimeData->clear();
const BMessage *clipboard = be_clipboard->Data();
if (clipboard) {
@@ -76,11 +87,11 @@ QMimeData *QHaikuClipboard::mimeData(QClipboard::Mode mode)
if (dataLen && (status == B_OK)) {
const QString format = QString::fromLatin1(name);
if (format == QStringLiteral("text/plain")) {
- mimeData->setText(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
+ m_systemMimeData->setText(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
} else if (format == QStringLiteral("text/html")) {
- mimeData->setHtml(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
+ m_systemMimeData->setHtml(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
} else {
- mimeData->setData(format, QByteArray(reinterpret_cast<const char*>(data), dataLen));
+ m_systemMimeData->setData(format, QByteArray(reinterpret_cast<const char*>(data), dataLen));
}
}
}
@@ -88,7 +99,7 @@ QMimeData *QHaikuClipboard::mimeData(QClipboard::Mode mode)
be_clipboard->Unlock();
- return mimeData;
+ return m_systemMimeData;
}
void QHaikuClipboard::setMimeData(QMimeData *mimeData, QClipboard::Mode mode)
@@ -96,6 +107,14 @@ void QHaikuClipboard::setMimeData(QMimeData *mimeData, QClipboard::Mode mode)
if (mode != QClipboard::Clipboard)
return;
+ if (mimeData) {
+ if (m_systemMimeData == mimeData)
+ return;
+
+ if (m_userMimeData == mimeData)
+ return;
+ }
+
if (!be_clipboard->Lock())
return;
@@ -115,6 +134,10 @@ void QHaikuClipboard::setMimeData(QMimeData *mimeData, QClipboard::Mode mode)
qWarning("Unable to store mime data on clipboard");
be_clipboard->Unlock();
+
+ m_userMimeData = mimeData;
+
+ emitChanged(QClipboard::Clipboard);
}
bool QHaikuClipboard::supportsMode(QClipboard::Mode mode) const
@@ -131,8 +154,12 @@ bool QHaikuClipboard::ownsMode(QClipboard::Mode mode) const
void QHaikuClipboard::MessageReceived(BMessage* message)
{
- if (message->what == B_CLIPBOARD_CHANGED)
+ if (message->what == B_CLIPBOARD_CHANGED) {
+ delete m_userMimeData;
+ m_userMimeData = Q_NULLPTR;
+
emitChanged(QClipboard::Clipboard);
+ }
BHandler::MessageReceived(message);
}
diff --git a/src/plugins/platforms/haiku/qhaikuclipboard.h b/src/plugins/platforms/haiku/qhaikuclipboard.h
index 0dc2bfdd3b..3c1f92c615 100644
--- a/src/plugins/platforms/haiku/qhaikuclipboard.h
+++ b/src/plugins/platforms/haiku/qhaikuclipboard.h
@@ -55,6 +55,10 @@ public:
// override from BHandler to catch change notifications from Haiku clipboard
void MessageReceived(BMessage* message) Q_DECL_OVERRIDE;
+
+private:
+ QMimeData *m_systemMimeData;
+ QMimeData *m_userMimeData;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/haiku/qhaikuwindow.cpp b/src/plugins/platforms/haiku/qhaikuwindow.cpp
index 5768e1cb40..9622d12111 100644
--- a/src/plugins/platforms/haiku/qhaikuwindow.cpp
+++ b/src/plugins/platforms/haiku/qhaikuwindow.cpp
@@ -130,6 +130,7 @@ QHaikuWindow::QHaikuWindow(QWindow *window)
if (!m_window)
qFatal("QHaikuWindow: failed to create window");
+ setGeometry(rect);
setWindowFlags(window->flags());
}
@@ -164,13 +165,13 @@ void QHaikuWindow::setVisible(bool visible)
{
if (visible) {
m_window->Show();
+
+ window()->requestActivate();
+
+ QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), window()->geometry().size()));
} else {
m_window->Hide();
}
-
- window()->requestActivate();
-
- QWindowSystemInterface::handleExposeEvent(window(), window()->geometry());
}
bool QHaikuWindow::isExposed() const
@@ -306,10 +307,8 @@ void QHaikuWindow::haikuWindowMoved(const QPoint &pos)
const QRect newGeometry(pos, geometry().size());
QPlatformWindow::setGeometry(newGeometry);
- QWindowSystemInterface::setSynchronousWindowsSystemEvents(true);
QWindowSystemInterface::handleGeometryChange(window(), newGeometry);
- QWindowSystemInterface::handleExposeEvent(window(), newGeometry);
- QWindowSystemInterface::setSynchronousWindowsSystemEvents(false);
+ QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), newGeometry.size()));
}
void QHaikuWindow::haikuWindowResized(const QSize &size, bool zoomInProgress)
@@ -317,10 +316,8 @@ void QHaikuWindow::haikuWindowResized(const QSize &size, bool zoomInProgress)
const QRect newGeometry(geometry().topLeft(), size);
QPlatformWindow::setGeometry(newGeometry);
- QWindowSystemInterface::setSynchronousWindowsSystemEvents(true);
QWindowSystemInterface::handleGeometryChange(window(), newGeometry);
- QWindowSystemInterface::handleExposeEvent(window(), newGeometry);
- QWindowSystemInterface::setSynchronousWindowsSystemEvents(false);
+ QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), newGeometry.size()));
if ((m_windowState == Qt::WindowMaximized) && !zoomInProgress) {
// the user has resized the window while maximized -> reset maximized flag
diff --git a/src/plugins/platforms/ios/qiosapplicationstate.mm b/src/plugins/platforms/ios/qiosapplicationstate.mm
index 92799f80c1..7a37e213bd 100644
--- a/src/plugins/platforms/ios/qiosapplicationstate.mm
+++ b/src/plugins/platforms/ios/qiosapplicationstate.mm
@@ -43,7 +43,7 @@
@implementation QIOSApplicationStateListener
-- (id) init
+- (id)init
{
self = [super init];
if (self) {
@@ -75,7 +75,7 @@
return self;
}
-- (void) dealloc
+- (void)dealloc
{
[[NSNotificationCenter defaultCenter]
removeObserver:self
@@ -92,12 +92,12 @@
[super dealloc];
}
-- (void) applicationDidBecomeActive
+- (void)applicationDidBecomeActive
{
[self handleApplicationStateChanged:UIApplicationStateActive];
}
-- (void) applicationWillResignActive
+- (void)applicationWillResignActive
{
// Note that UIApplication is still UIApplicationStateActive at this
// point, but since there is no separate notification for the inactive
@@ -105,12 +105,12 @@
[self handleApplicationStateChanged:UIApplicationStateInactive];
}
-- (void) applicationDidEnterBackground
+- (void)applicationDidEnterBackground
{
[self handleApplicationStateChanged:UIApplicationStateBackground];
}
-- (void) handleApplicationStateChanged:(UIApplicationState) uiApplicationState
+- (void)handleApplicationStateChanged:(UIApplicationState)uiApplicationState
{
// We may receive application state changes after QCoreApplication has
// gone down, as the block we schedule on the main queue keeps the
diff --git a/src/plugins/platforms/ios/qiosclipboard.mm b/src/plugins/platforms/ios/qiosclipboard.mm
index 192ee67689..e0c6ec5d72 100644
--- a/src/plugins/platforms/ios/qiosclipboard.mm
+++ b/src/plugins/platforms/ios/qiosclipboard.mm
@@ -62,7 +62,7 @@
@implementation QUIClipboard
--(id)initWithQIOSClipboard:(QIOSClipboard *)qiosClipboard
+- (id)initWithQIOSClipboard:(QIOSClipboard *)qiosClipboard
{
self = [super init];
if (self) {
@@ -87,7 +87,7 @@
return self;
}
--(void)dealloc
+- (void)dealloc
{
[[NSNotificationCenter defaultCenter]
removeObserver:self
diff --git a/src/plugins/platforms/ios/qioseventdispatcher.mm b/src/plugins/platforms/ios/qioseventdispatcher.mm
index fc12e83a81..bd4b8778ed 100644
--- a/src/plugins/platforms/ios/qioseventdispatcher.mm
+++ b/src/plugins/platforms/ios/qioseventdispatcher.mm
@@ -198,7 +198,7 @@ namespace
bool debugStackUsage = false;
}
-extern "C" int __attribute__((weak)) main(int argc, char *argv[])
+extern "C" int qt_main_wrapper(int argc, char *argv[])
{
@autoreleasepool {
size_t defaultStackSize = 512 * kBytesPerKiloByte; // Same as secondary threads
@@ -233,18 +233,7 @@ enum SetJumpResult
kJumpedFromUserMainTrampoline,
};
-// We define qtmn so that user_main_trampoline() will not cause
-// missing symbols in the case of hybrid applications that don't
-// use our main wrapper. Since the symbol is weak, it will not
-// get used or cause a clash in the normal Qt application usecase,
-// where we rename main to qtmn before linking.
-extern "C" int __attribute__((weak)) qtmn(int argc, char *argv[])
-{
- Q_UNUSED(argc);
- Q_UNUSED(argv);
-
- Q_UNREACHABLE();
-}
+extern "C" int main(int argc, char *argv[]);
static void __attribute__((noinline, noreturn)) user_main_trampoline()
{
@@ -263,7 +252,7 @@ static void __attribute__((noinline, noreturn)) user_main_trampoline()
qFatal("Could not convert argv[%d] to C string", i);
}
- int exitCode = qtmn(argc, argv);
+ int exitCode = main(argc, argv);
delete[] argv;
qEventDispatcherDebug() << "Returned from main with exit code " << exitCode;
@@ -293,7 +282,7 @@ static bool rootLevelRunLoopIntegration()
@implementation QIOSApplicationStateTracker
-+ (void) load
++ (void)load
{
[[NSNotificationCenter defaultCenter]
addObserver:self
@@ -323,7 +312,7 @@ static bool rootLevelRunLoopIntegration()
# error "Unknown processor family"
#endif
-+ (void) applicationDidFinishLaunching
++ (void)applicationDidFinishLaunching
{
if (!isQtApplication())
return;
@@ -377,7 +366,7 @@ static bool rootLevelRunLoopIntegration()
// four bits of the exit code (exit(3) will only pass on the lower 8 bits).
static const char kApplicationWillTerminateExitCode = SIGTERM | 0x80;
-+ (void) applicationWillTerminate
++ (void)applicationWillTerminate
{
if (!isQtApplication())
return;
diff --git a/src/plugins/platforms/ios/qiosglobal.h b/src/plugins/platforms/ios/qiosglobal.h
index 86b784618f..544f9e0a42 100644
--- a/src/plugins/platforms/ios/qiosglobal.h
+++ b/src/plugins/platforms/ios/qiosglobal.h
@@ -68,7 +68,7 @@ int infoPlistValue(NSString* key, int defaultValue);
QT_END_NAMESPACE
@interface UIResponder (QtFirstResponder)
-+(id)currentFirstResponder;
++ (id)currentFirstResponder;
@end
class FirstResponderCandidate : public QScopedValueRollback<UIResponder *>
diff --git a/src/plugins/platforms/ios/qiosglobal.mm b/src/plugins/platforms/ios/qiosglobal.mm
index ef24abbfd9..f5b971391d 100644
--- a/src/plugins/platforms/ios/qiosglobal.mm
+++ b/src/plugins/platforms/ios/qiosglobal.mm
@@ -133,7 +133,7 @@ int infoPlistValue(NSString* key, int defaultValue)
@end
@implementation QtFirstResponderEvent
-- (void) dealloc
+- (void)dealloc
{
self.firstResponder = 0;
[super dealloc];
@@ -158,7 +158,7 @@ int infoPlistValue(NSString* key, int defaultValue)
@implementation UIResponder (QtFirstResponder)
-+(id)currentFirstResponder
++ (id)currentFirstResponder
{
QtFirstResponderEvent *event = [[[QtFirstResponderEvent alloc] init] autorelease];
[[UIApplication sharedApplication] sendAction:@selector(qt_findFirstResponder:event:) to:nil from:nil forEvent:event];
diff --git a/src/plugins/platforms/ios/qiosinputcontext.mm b/src/plugins/platforms/ios/qiosinputcontext.mm
index 090df66e0d..d03c589b2a 100644
--- a/src/plugins/platforms/ios/qiosinputcontext.mm
+++ b/src/plugins/platforms/ios/qiosinputcontext.mm
@@ -579,7 +579,7 @@ void QIOSInputContext::focusWindowChanged(QWindow *focusWindow)
void QIOSInputContext::update(Qt::InputMethodQueries updatedProperties)
{
// Mask for properties that we are interested in and see if any of them changed
- updatedProperties &= (Qt::ImEnabled | Qt::ImHints | Qt::ImQueryInput | Qt::ImPlatformData);
+ updatedProperties &= (Qt::ImEnabled | Qt::ImHints | Qt::ImQueryInput | Qt::ImEnterKeyType | Qt::ImPlatformData);
qImDebug() << "fw =" << qApp->focusWindow() << "fo =" << qApp->focusObject();
diff --git a/src/plugins/platforms/ios/qiosintegration.mm b/src/plugins/platforms/ios/qiosintegration.mm
index 8395db81ff..eaff0daf19 100644
--- a/src/plugins/platforms/ios/qiosintegration.mm
+++ b/src/plugins/platforms/ios/qiosintegration.mm
@@ -219,6 +219,10 @@ QPlatformServices *QIOSIntegration::services() const
QVariant QIOSIntegration::styleHint(StyleHint hint) const
{
switch (hint) {
+ case PasswordMaskDelay:
+ // this number is based on timing the native delay
+ // since there is no API to get it
+ return 2000;
case ShowIsMaximized:
return true;
case SetFocusOnTouchRelease:
diff --git a/src/plugins/platforms/ios/qiosmenu.mm b/src/plugins/platforms/ios/qiosmenu.mm
index 08fc8a5e9c..045d39e328 100644
--- a/src/plugins/platforms/ios/qiosmenu.mm
+++ b/src/plugins/platforms/ios/qiosmenu.mm
@@ -165,7 +165,7 @@ static NSString *const kSelectorPrefix = @"_qtMenuItem_";
[self reloadAllComponents];
}
--(void)listenForKeyboardWillHideNotification:(BOOL)listen
+- (void)listenForKeyboardWillHideNotification:(BOOL)listen
{
if (listen) {
[[NSNotificationCenter defaultCenter]
@@ -179,7 +179,7 @@ static NSString *const kSelectorPrefix = @"_qtMenuItem_";
}
}
--(void)dealloc
+- (void)dealloc
{
[self listenForKeyboardWillHideNotification:NO];
self.toolbar = 0;
diff --git a/src/plugins/platforms/ios/qiosscreen.mm b/src/plugins/platforms/ios/qiosscreen.mm
index 324133074b..3e16efcd22 100644
--- a/src/plugins/platforms/ios/qiosscreen.mm
+++ b/src/plugins/platforms/ios/qiosscreen.mm
@@ -104,12 +104,12 @@ static QIOSScreen* qtPlatformScreenFor(UIScreen *uiScreen)
@public
QIOSScreen *m_screen;
}
-- (id) initWithQIOSScreen:(QIOSScreen *)screen;
+- (id)initWithQIOSScreen:(QIOSScreen *)screen;
@end
@implementation QIOSOrientationListener
-- (id) initWithQIOSScreen:(QIOSScreen *)screen
+- (id)initWithQIOSScreen:(QIOSScreen *)screen
{
self = [super init];
if (self) {
@@ -123,7 +123,7 @@ static QIOSScreen* qtPlatformScreenFor(UIScreen *uiScreen)
return self;
}
-- (void) dealloc
+- (void)dealloc
{
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
@@ -132,7 +132,7 @@ static QIOSScreen* qtPlatformScreenFor(UIScreen *uiScreen)
[super dealloc];
}
-- (void) orientationChanged:(NSNotification *)notification
+- (void)orientationChanged:(NSNotification *)notification
{
Q_UNUSED(notification);
m_screen->updateProperties();
diff --git a/src/plugins/platforms/ios/qiostextresponder.mm b/src/plugins/platforms/ios/qiostextresponder.mm
index be9c3b9e27..e4917593db 100644
--- a/src/plugins/platforms/ios/qiostextresponder.mm
+++ b/src/plugins/platforms/ios/qiostextresponder.mm
@@ -92,12 +92,12 @@
return [QUITextPosition positionWithIndex:(self.range.location + self.range.length)];
}
-- (NSRange) range
+- (NSRange)range
{
return _range;
}
--(BOOL)isEmpty
+- (BOOL)isEmpty
{
return (self.range.length == 0);
}
@@ -111,7 +111,7 @@
@implementation WrapperView
--(id)initWithView:(UIView *)view
+- (id)initWithView:(UIView *)view
{
if (self = [self init]) {
[self addSubview:view];
@@ -143,7 +143,7 @@
// retained, we ensure that all messages sent to the view during
// its lifetime in a window hierarcy will be able to traverse the
// responder chain.
--(void)willMoveToWindow:(UIWindow *)window
+- (void)willMoveToWindow:(UIWindow *)window
{
if (window)
[[self nextResponder] retain];
@@ -170,9 +170,31 @@
QVariantMap platformData = m_configuredImeState->value(Qt::ImPlatformData).toMap();
Qt::InputMethodHints hints = Qt::InputMethodHints(m_configuredImeState->value(Qt::ImHints).toUInt());
- self.returnKeyType = platformData.value(kImePlatformDataReturnKeyType).isValid() ?
- UIReturnKeyType(platformData.value(kImePlatformDataReturnKeyType).toInt()) :
- (hints & Qt::ImhMultiLine) ? UIReturnKeyDefault : UIReturnKeyDone;
+ Qt::EnterKeyType enterKeyType = Qt::EnterKeyType(m_configuredImeState->value(Qt::ImEnterKeyType).toUInt());
+
+ switch (enterKeyType) {
+ case Qt::EnterKeyReturn:
+ self.returnKeyType = UIReturnKeyDefault;
+ break;
+ case Qt::EnterKeyDone:
+ self.returnKeyType = UIReturnKeyDone;
+ break;
+ case Qt::EnterKeyGo:
+ self.returnKeyType = UIReturnKeyGo;
+ break;
+ case Qt::EnterKeySend:
+ self.returnKeyType = UIReturnKeySend;
+ break;
+ case Qt::EnterKeySearch:
+ self.returnKeyType = UIReturnKeySearch;
+ break;
+ case Qt::EnterKeyNext:
+ self.returnKeyType = UIReturnKeyNext;
+ break;
+ default:
+ self.returnKeyType = (hints & Qt::ImhMultiLine) ? UIReturnKeyDefault : UIReturnKeyDone;
+ break;
+ }
self.secureTextEntry = BOOL(hints & Qt::ImhHiddenText);
self.autocorrectionType = (hints & Qt::ImhNoPredictiveText) ?
@@ -235,7 +257,7 @@
}
// Based on what we set up in initWithInputContext above
- updatedProperties &= (Qt::ImHints | Qt::ImPlatformData);
+ updatedProperties &= (Qt::ImHints | Qt::ImEnterKeyType | Qt::ImPlatformData);
if (!updatedProperties)
return NO;
@@ -403,17 +425,17 @@
return m_inputContext->imeState().currentState.value(query);
}
--(id<UITextInputTokenizer>)tokenizer
+- (id<UITextInputTokenizer>)tokenizer
{
return [[[UITextInputStringTokenizer alloc] initWithTextInput:id<UITextInput>(self)] autorelease];
}
--(UITextPosition *)beginningOfDocument
+- (UITextPosition *)beginningOfDocument
{
return [QUITextPosition positionWithIndex:0];
}
--(UITextPosition *)endOfDocument
+- (UITextPosition *)endOfDocument
{
int endPosition = [self currentImeState:Qt::ImSurroundingText].toString().length();
return [QUITextPosition positionWithIndex:endPosition];
@@ -679,7 +701,7 @@
return [NSDictionary dictionaryWithObject:uifont forKey:UITextInputTextFontKey];
}
--(NSDictionary *)markedTextStyle
+- (NSDictionary *)markedTextStyle
{
return [NSDictionary dictionary];
}
@@ -698,7 +720,8 @@
if ([text isEqualToString:@"\n"]) {
[self sendKeyPressRelease:Qt::Key_Return modifiers:Qt::NoModifier];
- if (self.returnKeyType == UIReturnKeyDone)
+ if (self.returnKeyType == UIReturnKeyDone || self.returnKeyType == UIReturnKeyGo
+ || self.returnKeyType == UIReturnKeySend || self.returnKeyType == UIReturnKeySearch)
[self resignFirstResponder];
return;
diff --git a/src/plugins/platforms/ios/qiosviewcontroller.mm b/src/plugins/platforms/ios/qiosviewcontroller.mm
index a7068b9246..be89521c04 100644
--- a/src/plugins/platforms/ios/qiosviewcontroller.mm
+++ b/src/plugins/platforms/ios/qiosviewcontroller.mm
@@ -289,13 +289,13 @@
// -------------------------------------------------------------------------
--(BOOL)shouldAutorotate
+- (BOOL)shouldAutorotate
{
return m_screen && m_screen->uiScreen() == [UIScreen mainScreen] && !self.lockedOrientation;
}
#if QT_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__IPHONE_6_0)
--(NSUInteger)supportedInterfaceOrientations
+- (NSUInteger)supportedInterfaceOrientations
{
// As documented by Apple in the iOS 6.0 release notes, setStatusBarOrientation:animated:
// only works if the supportedInterfaceOrientations of the view controller is 0, making
@@ -308,7 +308,7 @@
#endif
#if QT_IOS_DEPLOYMENT_TARGET_BELOW(__IPHONE_6_0)
--(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
+- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
Q_UNUSED(interfaceOrientation);
return [self shouldAutorotate];
diff --git a/src/plugins/platforms/ios/quiaccessibilityelement.h b/src/plugins/platforms/ios/quiaccessibilityelement.h
index a690e12c7d..c76e3a6a1e 100644
--- a/src/plugins/platforms/ios/quiaccessibilityelement.h
+++ b/src/plugins/platforms/ios/quiaccessibilityelement.h
@@ -42,8 +42,8 @@
@property (readonly) QAccessible::Id axid;
-- (id) initWithId: (QAccessible::Id) anId withAccessibilityContainer: (id) view;
-+ (QMacAccessibilityElement *) elementWithId: (QAccessible::Id) anId withAccessibilityContainer: (id) view;
+- (id)initWithId:(QAccessible::Id)anId withAccessibilityContainer:(id)view;
++ (QMacAccessibilityElement *)elementWithId:(QAccessible::Id)anId withAccessibilityContainer:(id)view;
@end
diff --git a/src/plugins/platforms/ios/quiaccessibilityelement.mm b/src/plugins/platforms/ios/quiaccessibilityelement.mm
index 2cecfc1126..3bac1ca88d 100644
--- a/src/plugins/platforms/ios/quiaccessibilityelement.mm
+++ b/src/plugins/platforms/ios/quiaccessibilityelement.mm
@@ -37,7 +37,7 @@
@implementation QMacAccessibilityElement
-- (id) initWithId: (QAccessible::Id) anId withAccessibilityContainer: (id) view
+- (id)initWithId:(QAccessible::Id)anId withAccessibilityContainer:(id)view
{
Q_ASSERT((int)anId < 0);
self = [super initWithAccessibilityContainer: view];
@@ -47,7 +47,7 @@
return self;
}
-+ (id) elementWithId: (QAccessible::Id) anId withAccessibilityContainer: (id) view
++ (id)elementWithId:(QAccessible::Id)anId withAccessibilityContainer:(id)view
{
Q_ASSERT(anId);
if (!anId)
@@ -64,17 +64,17 @@
return element;
}
-- (void) invalidate
+- (void)invalidate
{
[self release];
}
-- (BOOL) isAccessibilityElement
+- (BOOL)isAccessibilityElement
{
return YES;
}
-- (NSString*) accessibilityLabel
+- (NSString*)accessibilityLabel
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (!iface) {
@@ -85,7 +85,7 @@
return iface->text(QAccessible::Name).toNSString();
}
-- (NSString*) accessibilityHint
+- (NSString*)accessibilityHint
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (!iface) {
@@ -95,7 +95,7 @@
return iface->text(QAccessible::Description).toNSString();
}
-- (NSString*) accessibilityValue
+- (NSString*)accessibilityValue
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (!iface) {
@@ -119,7 +119,7 @@
return [super accessibilityHint];
}
-- (CGRect) accessibilityFrame
+- (CGRect)accessibilityFrame
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (!iface) {
@@ -131,7 +131,7 @@
return CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
}
-- (UIAccessibilityTraits) accessibilityTraits
+- (UIAccessibilityTraits)accessibilityTraits
{
UIAccessibilityTraits traits = UIAccessibilityTraitNone;
@@ -156,7 +156,7 @@
return traits;
}
-- (BOOL) accessibilityActivate
+- (BOOL)accessibilityActivate
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (QAccessibleActionInterface *action = iface->actionInterface()) {
@@ -171,21 +171,21 @@
return NO; // fall back to sending mouse clicks
}
-- (void) accessibilityIncrement
+- (void)accessibilityIncrement
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (QAccessibleActionInterface *action = iface->actionInterface())
action->doAction(QAccessibleActionInterface::increaseAction());
}
-- (void) accessibilityDecrement
+- (void)accessibilityDecrement
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
if (QAccessibleActionInterface *action = iface->actionInterface())
action->doAction(QAccessibleActionInterface::decreaseAction());
}
-- (BOOL) accessibilityScroll : (UIAccessibilityScrollDirection) direction
+- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction
{
QAccessibleInterface *iface = QAccessible::accessibleInterface(self.axid);
QAccessibleActionInterface *action = iface->actionInterface();
diff --git a/src/plugins/platforms/ios/quiview.mm b/src/plugins/platforms/ios/quiview.mm
index 87dc3b9dcb..c6ef843b9f 100644
--- a/src/plugins/platforms/ios/quiview.mm
+++ b/src/plugins/platforms/ios/quiview.mm
@@ -50,7 +50,7 @@
return [CAEAGLLayer class];
}
--(id)initWithQIOSWindow:(QIOSWindow *)window
+- (id)initWithQIOSWindow:(QIOSWindow *)window
{
if (self = [self initWithFrame:toCGRect(window->geometry())])
m_qioswindow = window;
@@ -316,7 +316,7 @@
}
}
-- (void) sendTouchEventWithTimestamp:(ulong)timeStamp
+- (void)sendTouchEventWithTimestamp:(ulong)timeStamp
{
// Send touch event synchronously
QIOSIntegration *iosIntegration = QIOSIntegration::instance();
diff --git a/src/plugins/platforms/kms/kms.json b/src/plugins/platforms/kms/kms.json
deleted file mode 100644
index be662226ae..0000000000
--- a/src/plugins/platforms/kms/kms.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "Keys": [ "kms" ]
-}
diff --git a/src/plugins/platforms/kms/kms.pro b/src/plugins/platforms/kms/kms.pro
deleted file mode 100644
index baa8778153..0000000000
--- a/src/plugins/platforms/kms/kms.pro
+++ /dev/null
@@ -1,37 +0,0 @@
-TARGET = qkms
-
-PLUGIN_TYPE = platforms
-PLUGIN_CLASS_NAME = QKmsIntegrationPlugin
-!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
-load(qt_plugin)
-
-QT += core-private gui-private platformsupport-private
-qtHaveModule(opengl):QT += opengl-private
-
-DEFINES += MESA_EGL_NO_X11_HEADERS __GBM__
-
-CONFIG += link_pkgconfig egl qpa/genericunixfontdatabase
-
-PKGCONFIG += libdrm libudev egl gbm glesv2
-
-SOURCES = main.cpp \
- qkmsintegration.cpp \
- qkmsscreen.cpp \
- qkmscontext.cpp \
- qkmswindow.cpp \
- qkmscursor.cpp \
- qkmsdevice.cpp \
- qkmsbackingstore.cpp \
- qkmsnativeinterface.cpp
-
-HEADERS = qkmsintegration.h \
- qkmsscreen.h \
- qkmscontext.h \
- qkmswindow.h \
- qkmscursor.h \
- qkmsdevice.h \
- qkmsbackingstore.h \
- qkmsnativeinterface.h
-
-OTHER_FILES += \
- kms.json
diff --git a/src/plugins/platforms/kms/qkmsbackingstore.cpp b/src/plugins/platforms/kms/qkmsbackingstore.cpp
deleted file mode 100644
index 6e5a3f9192..0000000000
--- a/src/plugins/platforms/kms/qkmsbackingstore.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkmsbackingstore.h"
-
-#include <QtGui/QOpenGLContext>
-#include <QtGui/QOpenGLShaderProgram>
-#include <QtGui/QScreen>
-
-QT_BEGIN_NAMESPACE
-
-QKmsBackingStore::QKmsBackingStore(QWindow *window)
- : QPlatformBackingStore(window)
- , m_context(new QOpenGLContext)
- , m_texture(0)
- , m_program(0)
- , m_initialized(false)
-{
- m_context->setFormat(window->requestedFormat());
- m_context->setScreen(window->screen());
- m_context->create();
-}
-
-QKmsBackingStore::~QKmsBackingStore()
-{
- delete m_program;
- if (m_texture)
- glDeleteTextures(1, &m_texture);
-
- delete m_context;
-}
-
-QPaintDevice *QKmsBackingStore::paintDevice()
-{
- return &m_image;
-}
-
-void QKmsBackingStore::beginPaint(const QRegion &rgn)
-{
- m_dirty |= rgn;
-}
-
-void QKmsBackingStore::flush(QWindow *window, const QRegion &region, const QPoint &offset)
-{
- Q_UNUSED(region)
- Q_UNUSED(offset)
-
- m_context->makeCurrent(window);
-
- if (!m_initialized) {
- initializeOpenGLFunctions();
- m_initialized = true;
- }
-
- if (!m_program) {
- static const char *textureVertexProgram =
- "attribute highp vec2 vertexCoordEntry;\n"
- "attribute highp vec2 textureCoordEntry;\n"
- "varying highp vec2 textureCoord;\n"
- "void main() {\n"
- " textureCoord = textureCoordEntry;\n"
- " gl_Position = vec4(vertexCoordEntry, 0.0, 1.0);\n"
- "}\n";
-
- static const char *textureFragmentProgram =
- "uniform sampler2D texture;\n"
- "varying highp vec2 textureCoord;\n"
- "void main() {\n"
- " gl_FragColor = texture2D(texture, textureCoord).bgra;\n"
- "}\n";
-
- m_program = new QOpenGLShaderProgram;
-
- m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
- m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
- m_program->bindAttributeLocation("vertexCoordEntry", 0);
- m_program->bindAttributeLocation("textureCoordEntry", 1);
- m_program->link();
- }
-
- m_program->bind();
-
- QRectF r = window->geometry();
- QRectF sr = window->screen()->geometry();
-
- GLfloat x1 = (r.left() / sr.width()) * 2 - 1;
- GLfloat x2 = (r.right() / sr.width()) * 2 - 1;
- GLfloat y1 = -1 * ((r.top() / sr.height()) * 2 - 1);
- GLfloat y2 = -1 * ((r.bottom() / sr.height()) * 2 - 1);
-
- const GLfloat vertexCoordinates[] = {
- x1, y1,
- x2, y1,
- x2, y2,
- x1, y2
- };
-
- const GLfloat textureCoordinates[] = {
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- };
-
- glEnableVertexAttribArray(0);
- glEnableVertexAttribArray(1);
-
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinates);
- glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);
-
- glBindTexture(GL_TEXTURE_2D, m_texture);
-
- if (!m_dirty.isNull()) {
- QRect imageRect = m_image.rect();
- QRegion fixed;
- Q_FOREACH (const QRect &rect, m_dirty.rects()) {
- // intersect with image rect to be sure
- QRect r = imageRect & rect;
- // if the rect is wide enough it's cheaper to just
- // extend it instead of doing an image copy
- if (r.width() >= imageRect.width() / 2) {
- r.setX(0);
- r.setWidth(imageRect.width());
- }
- fixed |= r;
- }
-
- Q_FOREACH (const QRect &rect, fixed.rects()) {
- // if the sub-rect is full-width we can pass the image data directly to
- // OpenGL instead of copying, since there's no gap between scanlines
- if (rect.width() == imageRect.width()) {
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(),
- rect.width(), rect.height(),
- GL_RGBA, GL_UNSIGNED_BYTE,
- m_image.constScanLine(rect.y()));
- } else {
- glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(),
- rect.width(), rect.height(),
- GL_RGBA, GL_UNSIGNED_BYTE,
- m_image.copy(rect).constBits());
- }
- }
-
- m_dirty = QRegion();
- }
-
- glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-
- m_program->release();
- glBindTexture(GL_TEXTURE_2D, 0);
- glDisableVertexAttribArray(0);
- glDisableVertexAttribArray(1);
-
- m_context->swapBuffers(window);
-
- m_context->doneCurrent();
-}
-
-void QKmsBackingStore::resize(const QSize &size, const QRegion &staticContents)
-{
- Q_UNUSED(staticContents)
-
- m_image = QImage(size, QImage::Format_RGB32);
-
- m_context->makeCurrent(window());
-
- if (!m_initialized) {
- initializeOpenGLFunctions();
- m_initialized = true;
- }
-
- if (m_texture)
- glDeleteTextures(1, &m_texture);
-
- glGenTextures(1, &m_texture);
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.width(), size.height(),
- 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
-
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmsbackingstore.h b/src/plugins/platforms/kms/qkmsbackingstore.h
deleted file mode 100644
index a34b10d3d9..0000000000
--- a/src/plugins/platforms/kms/qkmsbackingstore.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QBACKINGSTORE_KMS_H
-#define QBACKINGSTORE_KMS_H
-
-#include <qpa/qplatformbackingstore.h>
-#include <QtGui/QOpenGLFunctions>
-#include <QImage>
-
-QT_BEGIN_NAMESPACE
-
-class QOpenGLContext;
-class QOpenGLShaderProgram;
-
-class QKmsBackingStore : public QPlatformBackingStore, public QOpenGLFunctions
-{
-public:
- QKmsBackingStore(QWindow *window);
- ~QKmsBackingStore();
-
- QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
-
- void beginPaint(const QRegion &) Q_DECL_OVERRIDE;
-
- void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
- void resize(const QSize &size, const QRegion &staticContents) Q_DECL_OVERRIDE;
-
- QImage toImage() const Q_DECL_OVERRIDE { return m_image; }
-
-private:
- QOpenGLContext *m_context;
- QImage m_image;
- uint m_texture;
- QOpenGLShaderProgram *m_program;
- QRegion m_dirty;
- bool m_initialized;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/platforms/kms/qkmscontext.cpp b/src/plugins/platforms/kms/qkmscontext.cpp
deleted file mode 100644
index e00835fbac..0000000000
--- a/src/plugins/platforms/kms/qkmscontext.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkmsscreen.h"
-#include "qkmsdevice.h"
-#include "qkmscontext.h"
-#include "qkmswindow.h"
-#include "qkmsintegration.h"
-
-#include <QtGui/QOpenGLContext>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QKmsContext::QKmsContext(QOpenGLContext *context, QKmsDevice *device)
- : m_device(device)
-{
- EGLDisplay display = m_device->eglDisplay();
- EGLConfig config = q_configFromGLFormat(display, QKmsScreen::tweakFormat(context->format()));
- m_format = q_glFormatFromConfig(display, config);
-
- //Initialize EGLContext
- static EGLint contextAttribs[] = {
- EGL_CONTEXT_CLIENT_VERSION, context->format().majorVersion(),
- EGL_NONE
- };
-
- eglBindAPI(EGL_OPENGL_ES_API);
-
- EGLContext share = EGL_NO_CONTEXT;
- if (context->shareContext())
- share = static_cast<QKmsContext *>(context->shareContext()->handle())->eglContext();
-
- m_eglContext = eglCreateContext(display, config, share, contextAttribs);
- if (m_eglContext == EGL_NO_CONTEXT) {
- qWarning("QKmsContext::QKmsContext(): eglError: %x, this: %p",
- eglGetError(), this);
- m_eglContext = 0;
- }
-}
-
-bool QKmsContext::isValid() const
-{
- return m_eglContext != EGL_NO_CONTEXT;
-}
-
-bool QKmsContext::makeCurrent(QPlatformSurface *surface)
-{
- Q_ASSERT(surface->surface()->supportsOpenGL());
-
- EGLDisplay display = m_device->eglDisplay();
- EGLSurface eglSurface;
-
- if (surface->surface()->surfaceClass() == QSurface::Window) {
- QPlatformWindow *window = static_cast<QPlatformWindow *>(surface);
- QKmsScreen *screen = static_cast<QKmsScreen *>(QPlatformScreen::platformScreenForWindow(window->window()));
- eglSurface = screen->eglSurface();
- screen->waitForPageFlipComplete();
- } else {
- eglSurface = static_cast<QKmsOffscreenWindow *>(surface)->surface();
- }
-
- bool ok = eglMakeCurrent(display, eglSurface, eglSurface, m_eglContext);
- if (!ok)
- qWarning("QKmsContext::makeCurrent(): eglError: %x, this: %p",
- eglGetError(), this);
-
- return true;
-}
-
-void QKmsContext::doneCurrent()
-{
- bool ok = eglMakeCurrent(m_device->eglDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE,
- EGL_NO_CONTEXT);
- if (!ok)
- qWarning("QKmsContext::doneCurrent(): eglError: %x, this: %p",
- eglGetError(), this);
-
-}
-
-void QKmsContext::swapBuffers(QPlatformSurface *surface)
-{
- //Cast context to a window surface and get the screen the context
- //is on and call swapBuffers on that screen.
- QPlatformWindow *window = static_cast<QPlatformWindow *>(surface);
- QKmsScreen *screen = static_cast<QKmsScreen *> (QPlatformScreen::platformScreenForWindow(window->window()));
- screen->swapBuffers();
-}
-
-void (*QKmsContext::getProcAddress(const QByteArray &procName)) ()
-{
- return eglGetProcAddress(procName.data());
-}
-
-
-EGLContext QKmsContext::eglContext() const
-{
- return m_eglContext;
-}
-
-QSurfaceFormat QKmsContext::format() const
-{
- return m_format;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmscontext.h b/src/plugins/platforms/kms/qkmscontext.h
deleted file mode 100644
index 59cf9b1e34..0000000000
--- a/src/plugins/platforms/kms/qkmscontext.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QKMSCONTEXT_H
-#define QKMSCONTEXT_H
-
-#include <qpa/qplatformopenglcontext.h>
-
-#define EGL_EGLEXT_PROTOTYPES 1
-#include <EGL/egl.h>
-
-QT_BEGIN_NAMESPACE
-
-class QKmsDevice;
-
-class QKmsContext : public QPlatformOpenGLContext
-{
-public:
- QKmsContext(QOpenGLContext *context, QKmsDevice *device);
-
- bool makeCurrent(QPlatformSurface *surface) Q_DECL_OVERRIDE;
- void doneCurrent() Q_DECL_OVERRIDE;
- void swapBuffers(QPlatformSurface *surface) Q_DECL_OVERRIDE;
- void (*getProcAddress(const QByteArray &procName)) () Q_DECL_OVERRIDE;
-
- bool isValid() const Q_DECL_OVERRIDE;
-
- QSurfaceFormat format() const Q_DECL_OVERRIDE;
-
- EGLContext eglContext() const;
-
-private:
- EGLContext m_eglContext;
- QSurfaceFormat m_format;
-
- QKmsDevice *m_device;
-};
-
-QT_END_NAMESPACE
-
-#endif // QKMSCONTEXT_H
diff --git a/src/plugins/platforms/kms/qkmscursor.cpp b/src/plugins/platforms/kms/qkmscursor.cpp
deleted file mode 100644
index 44212cd3c8..0000000000
--- a/src/plugins/platforms/kms/qkmscursor.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-//#include <QDebug>
-#include "qkmscursor.h"
-#include "qkmsscreen.h"
-#include "qkmsdevice.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef DRM_CAP_CURSOR_WIDTH
-#define DRM_CAP_CURSOR_WIDTH 0x8
-#endif
-
-#ifndef DRM_CAP_CURSOR_HEIGHT
-#define DRM_CAP_CURSOR_HEIGHT 0x9
-#endif
-
-QKmsCursor::QKmsCursor(QKmsScreen *screen)
- : m_screen(screen),
- m_graphicsBufferManager(screen->device()->gbmDevice()),
- m_cursorImage(new QPlatformCursorImage(0, 0, 0, 0, 0, 0)),
- m_moved(false),
- m_cursorSize(64, 64)
-{
- uint64_t value = 0;
- if (!drmGetCap(m_screen->device()->fd(), DRM_CAP_CURSOR_WIDTH, &value))
- m_cursorSize.setWidth(value);
- if (!drmGetCap(m_screen->device()->fd(), DRM_CAP_CURSOR_HEIGHT, &value))
- m_cursorSize.setHeight(value);
-
- m_cursorBufferObject = gbm_bo_create(m_graphicsBufferManager, m_cursorSize.width(), m_cursorSize.height(),
- GBM_FORMAT_ARGB8888, GBM_BO_USE_CURSOR_64X64 | GBM_BO_USE_WRITE);
-}
-
-QKmsCursor::~QKmsCursor()
-{
- drmModeSetCursor(m_screen->device()->fd(), m_screen->crtcId(), 0, 0, 0);
- gbm_bo_destroy(m_cursorBufferObject);
-}
-
-void QKmsCursor::pointerEvent(const QMouseEvent &event)
-{
- m_moved = true;
- int status = drmModeMoveCursor(m_screen->device()->fd(),
- m_screen->crtcId(),
- event.globalX(),
- event.globalY());
- if (status) {
- qWarning("failed to move cursor: %d", status);
- }
-}
-
-void QKmsCursor::changeCursor(QCursor *windowCursor, QWindow *window)
-{
- Q_UNUSED(window)
-
- if (!m_moved)
- drmModeMoveCursor(m_screen->device()->fd(), m_screen->crtcId(), 0, 0);
-
- const Qt::CursorShape newShape = windowCursor ? windowCursor->shape() : Qt::ArrowCursor;
- if (newShape != Qt::BitmapCursor) {
- m_cursorImage->set(newShape);
- } else {
- m_cursorImage->set(windowCursor->pixmap().toImage(),
- windowCursor->hotSpot().x(),
- windowCursor->hotSpot().y());
- }
-
- if (m_cursorImage->image()->width() > m_cursorSize.width() || m_cursorImage->image()->width() > m_cursorSize.height())
- qWarning("cursor larger than %dx%d, cursor truncated", m_cursorSize.width(), m_cursorSize.height());
-
- QImage cursorImage = m_cursorImage->image()->convertToFormat(QImage::Format_ARGB32)
- .copy(0, 0, m_cursorSize.width(), m_cursorSize.height());
- gbm_bo_write(m_cursorBufferObject, cursorImage.constBits(), cursorImage.byteCount());
-
- quint32 handle = gbm_bo_get_handle(m_cursorBufferObject).u32;
- int status = drmModeSetCursor(m_screen->device()->fd(),
- m_screen->crtcId(), handle,
- m_cursorSize.width(), m_cursorSize.height());
-
- if (status) {
- qWarning("failed to set cursor: %d", status);
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmsdevice.cpp b/src/plugins/platforms/kms/qkmsdevice.cpp
deleted file mode 100644
index 74fa59c16a..0000000000
--- a/src/plugins/platforms/kms/qkmsdevice.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-//#include <QDebug>
-#include "qkmsscreen.h"
-#include "qkmsdevice.h"
-
-#include "qkmsintegration.h"
-
-#include <QtCore/QSocketNotifier>
-#include <QtCore/private/qcore_unix_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QKmsDevice::QKmsDevice(const QString &path, QKmsIntegration *parent) :
- QObject(0), m_integration(parent)
-{
- m_fd = QT_OPEN(path.toLatin1().constData(), O_RDWR);
- if (m_fd < 0) {
- qWarning("Could not open %s.", path.toLatin1().constData());
- qFatal("No DRM display device");
- }
-
- m_graphicsBufferManager = gbm_create_device(m_fd);
- m_eglDisplay = eglGetDisplay(m_graphicsBufferManager);
-
- if (m_eglDisplay == EGL_NO_DISPLAY) {
- qWarning("Could not open EGL display");
- qFatal("EGL error");
- }
-
- EGLint major;
- EGLint minor;
- if (!eglInitialize(m_eglDisplay, &major, &minor)) {
- qWarning("Could not initialize EGL display");
- qFatal("EGL error");
- }
-
- createScreens();
-
-// QSocketNotifier *notifier = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);
-// connect(notifier, SIGNAL(activated(int)), this, SLOT(handlePageFlipCompleted()));
-}
-
-QKmsDevice::~QKmsDevice()
-{
-}
-
-void QKmsDevice::createScreens()
-{
- drmModeRes *resources = drmModeGetResources(m_fd);
- if (!resources)
- qFatal("drmModeGetResources failed");
-
- //Iterate connectors and create screens on each one active
- for (int i = 0; i < resources->count_connectors; i++) {
- drmModeConnector *connector = 0;
- connector = drmModeGetConnector(m_fd, resources->connectors[i]);
- if (connector && connector->connection == DRM_MODE_CONNECTED) {
- m_integration->addScreen(new QKmsScreen(this, resources, connector));
- }
- drmModeFreeConnector(connector);
- }
- drmModeFreeResources(resources);
-}
-
-void QKmsDevice::handlePageFlipCompleted()
-{
- drmEventContext eventContext;
-
- memset(&eventContext, 0, sizeof eventContext);
- eventContext.version = DRM_EVENT_CONTEXT_VERSION;
- eventContext.page_flip_handler = QKmsDevice::pageFlipHandler;
- drmHandleEvent(m_fd, &eventContext);
-
-}
-
-void QKmsDevice::pageFlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
-{
- Q_UNUSED(fd)
- Q_UNUSED(frame)
- Q_UNUSED(sec)
- Q_UNUSED(usec)
-
- QKmsScreen *screen = static_cast<QKmsScreen *>(data);
- screen->handlePageFlipped();
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmsdevice.h b/src/plugins/platforms/kms/qkmsdevice.h
deleted file mode 100644
index d5e33cb8c7..0000000000
--- a/src/plugins/platforms/kms/qkmsdevice.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QKMSDEVICE_H
-#define QKMSDEVICE_H
-
-#include <stddef.h>
-
-extern "C" {
-#include <gbm.h>
-}
-#include <EGL/egl.h>
-
-#include <QObject>
-
-struct gbm_device;
-
-QT_BEGIN_NAMESPACE
-
-class QKmsIntegration;
-
-class QKmsDevice : public QObject
-{
- Q_OBJECT
-public:
- explicit QKmsDevice(const QString &path, QKmsIntegration *parent);
- ~QKmsDevice();
-
- EGLDisplay eglDisplay() { return m_eglDisplay; }
- gbm_device *gbmDevice() { return m_graphicsBufferManager; }
- int fd() const { return m_fd; }
-
- static void pageFlipHandler(int fd, unsigned int frame, unsigned int sec,
- unsigned int usec, void *data);
-
-public slots:
- void handlePageFlipCompleted();
-private:
- void createScreens();
-
- QKmsIntegration *m_integration;
-
- EGLDisplay m_eglDisplay;
- EGLContext m_eglContext;
- gbm_device *m_graphicsBufferManager;
- int m_fd;
-};
-
-QT_END_NAMESPACE
-
-#endif // QKMSDEVICE_H
diff --git a/src/plugins/platforms/kms/qkmsintegration.cpp b/src/plugins/platforms/kms/qkmsintegration.cpp
deleted file mode 100644
index f48c868ae5..0000000000
--- a/src/plugins/platforms/kms/qkmsintegration.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkmsintegration.h"
-#include "qkmsdevice.h"
-#include "qkmsscreen.h"
-#include "qkmswindow.h"
-#include "qkmsbackingstore.h"
-#include "qkmscontext.h"
-#include "qkmsnativeinterface.h"
-
-#if !defined(QT_NO_EVDEV)
-#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
-#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
-#include <QtPlatformSupport/private/qevdevtouch_p.h>
-#endif
-
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-
-#include <QtGui/private/qguiapplication_p.h>
-#include <QtGui/QOpenGLContext>
-#include <QtGui/QScreen>
-#include <QtGui/QOffscreenSurface>
-#include <qpa/qplatformoffscreensurface.h>
-
-QT_BEGIN_NAMESPACE
-
-QKmsIntegration::QKmsIntegration()
- : QPlatformIntegration(),
- m_fontDatabase(new QGenericUnixFontDatabase()),
- m_nativeInterface(new QKmsNativeInterface),
- m_vtHandler(0),
- m_deviceDiscovery(0)
-{
-}
-
-QKmsIntegration::~QKmsIntegration()
-{
- delete m_deviceDiscovery;
- foreach (QKmsDevice *device, m_devices) {
- delete device;
- }
- foreach (QPlatformScreen *screen, m_screens) {
- destroyScreen(screen);
- }
- delete m_fontDatabase;
- delete m_vtHandler;
-}
-
-void QKmsIntegration::initialize()
-{
- qputenv("EGL_PLATFORM", "drm");
- m_vtHandler = new QFbVtHandler;
-
- m_deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_DRM | QDeviceDiscovery::Device_DRM_PrimaryGPU, 0);
- if (m_deviceDiscovery) {
- QStringList devices = m_deviceDiscovery->scanConnectedDevices();
- foreach (const QString &device, devices)
- addDevice(device);
-
- connect(m_deviceDiscovery, SIGNAL(deviceDetected(QString)), this, SLOT(addDevice(QString)));
- connect(m_deviceDiscovery, SIGNAL(deviceRemoved(QString)), this, SLOT(removeDevice(QString)));
- }
-
-#if !defined(QT_NO_EVDEV)
- new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString() /* spec */, this);
- new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString() /* spec */, this);
- new QEvdevTouchScreenHandlerThread(QString() /* spec */, this);
-#endif
-}
-
-void QKmsIntegration::addDevice(const QString &deviceNode)
-{
- m_devices.append(new QKmsDevice(deviceNode, this));
-}
-
-void QKmsIntegration::removeDevice(const QString &deviceNode)
-{
- // TODO: support hot-plugging some day?
- Q_UNUSED(deviceNode);
-}
-
-bool QKmsIntegration::hasCapability(QPlatformIntegration::Capability cap) const
-{
- switch (cap) {
- case ThreadedPixmaps: return true;
- case OpenGL: return true;
- case ThreadedOpenGL: return false;
- case RasterGLSurface: return true;
- default: return QPlatformIntegration::hasCapability(cap);
- }
-}
-
-QPlatformOpenGLContext *QKmsIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
-{
- QKmsScreen *screen = static_cast<QKmsScreen *>(context->screen()->handle());
- return new QKmsContext(context, screen->device());
-}
-
-QPlatformWindow *QKmsIntegration::createPlatformWindow(QWindow *window) const
-{
- QKmsWindow *w = new QKmsWindow(window);
- w->requestActivateWindow();
- return w;
-}
-
-QPlatformBackingStore *QKmsIntegration::createPlatformBackingStore(QWindow *window) const
-{
- return new QKmsBackingStore(window);
-}
-
-// Neither a pbuffer nor a hidden QWindow is suitable. Just use an additional, small gbm surface.
-QKmsOffscreenWindow::QKmsOffscreenWindow(EGLDisplay display, const QSurfaceFormat &format, QOffscreenSurface *offscreenSurface)
- : QPlatformOffscreenSurface(offscreenSurface)
- , m_format(format)
- , m_display(display)
- , m_surface(EGL_NO_SURFACE)
- , m_window(0)
-{
- QKmsScreen *screen = static_cast<QKmsScreen *>(offscreenSurface->screen()->handle());
- m_window = gbm_surface_create(screen->device()->gbmDevice(),
- 10, 10,
- GBM_FORMAT_XRGB8888,
- GBM_BO_USE_RENDERING);
- if (!m_window) {
- qWarning("QKmsOffscreenWindow: Failed to create native window");
- return;
- }
-
- EGLConfig config = q_configFromGLFormat(m_display, m_format);
- m_surface = eglCreateWindowSurface(m_display, config, m_window, 0);
- if (m_surface != EGL_NO_SURFACE)
- m_format = q_glFormatFromConfig(m_display, config);
-}
-
-QKmsOffscreenWindow::~QKmsOffscreenWindow()
-{
- if (m_surface != EGL_NO_SURFACE)
- eglDestroySurface(m_display, m_surface);
- if (m_window)
- gbm_surface_destroy((gbm_surface *) m_window);
-}
-
-QPlatformOffscreenSurface *QKmsIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const
-{
- QKmsScreen *screen = static_cast<QKmsScreen *>(surface->screen()->handle());
- return new QKmsOffscreenWindow(screen->device()->eglDisplay(), QKmsScreen::tweakFormat(surface->format()), surface);
-}
-
-QPlatformFontDatabase *QKmsIntegration::fontDatabase() const
-{
- return m_fontDatabase;
-}
-
-void QKmsIntegration::addScreen(QKmsScreen *screen)
-{
- m_screens.append(screen);
- screenAdded(screen);
-}
-
-QAbstractEventDispatcher *QKmsIntegration::createEventDispatcher() const
-{
- return createUnixEventDispatcher();
-}
-
-QPlatformNativeInterface *QKmsIntegration::nativeInterface() const
-{
- return m_nativeInterface;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmsintegration.h b/src/plugins/platforms/kms/qkmsintegration.h
deleted file mode 100644
index bcf9ac7296..0000000000
--- a/src/plugins/platforms/kms/qkmsintegration.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMINTEGRATION_KMS_H
-#define QPLATFORMINTEGRATION_KMS_H
-
-#include <qpa/qplatformintegration.h>
-#include <qpa/qplatformnativeinterface.h>
-#include <qpa/qplatformoffscreensurface.h>
-#include <QtPlatformSupport/private/qdevicediscovery_p.h>
-#include <EGL/egl.h>
-
-QT_BEGIN_NAMESPACE
-
-class QKmsScreen;
-class QKmsDevice;
-class QFbVtHandler;
-
-class QKmsOffscreenWindow : public QPlatformOffscreenSurface
-{
-public:
- QKmsOffscreenWindow(EGLDisplay display, const QSurfaceFormat &format, QOffscreenSurface *offscreenSurface);
- ~QKmsOffscreenWindow();
-
- QSurfaceFormat format() const Q_DECL_OVERRIDE { return m_format; }
- bool isValid() const Q_DECL_OVERRIDE { return m_surface != EGL_NO_SURFACE; }
-
- EGLSurface surface() const { return m_surface; }
-
-private:
- QSurfaceFormat m_format;
- EGLDisplay m_display;
- EGLSurface m_surface;
- EGLNativeWindowType m_window;
-};
-
-class QKmsIntegration : public QObject, public QPlatformIntegration
-{
- Q_OBJECT
-
-public:
- QKmsIntegration();
- ~QKmsIntegration();
-
- void initialize() Q_DECL_OVERRIDE;
- bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
-
- QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const Q_DECL_OVERRIDE;
- QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
- QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const Q_DECL_OVERRIDE;
- QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
-
- QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
- QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
-
- QPlatformNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
-
- void addScreen(QKmsScreen *screen);
- QObject *createDevice(const char *);
-
-private slots:
- void addDevice(const QString &deviceNode);
- void removeDevice(const QString &deviceNode);
-
-private:
- QStringList findDrmDevices();
-
- QList<QPlatformScreen *> m_screens;
- QList<QKmsDevice *> m_devices;
- QPlatformFontDatabase *m_fontDatabase;
- QPlatformNativeInterface *m_nativeInterface;
- QFbVtHandler *m_vtHandler;
- QDeviceDiscovery *m_deviceDiscovery;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/platforms/kms/qkmsnativeinterface.cpp b/src/plugins/platforms/kms/qkmsnativeinterface.cpp
deleted file mode 100644
index 1538a7f8c3..0000000000
--- a/src/plugins/platforms/kms/qkmsnativeinterface.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qguiapplication_p.h>
-#include "qkmsnativeinterface.h"
-#include "qkmsdevice.h"
-
-#include "qscreen.h"
-#include "qkmscontext.h"
-#include <QOpenGLContext>
-
-class QKmsResourceMap : public QMap<QByteArray, QKmsNativeInterface::ResourceType>
-{
-public:
- QKmsResourceMap()
- :QMap<QByteArray, QKmsNativeInterface::ResourceType>()
- {
- insert("egldisplay", QKmsNativeInterface::EglDisplay);
- insert("eglcontext", QKmsNativeInterface::EglContext);
- }
-};
-
-Q_GLOBAL_STATIC(QKmsResourceMap, qKmsResourceMap)
-
-void *QKmsNativeInterface::nativeResourceForIntegration(const QByteArray &resourceString)
-{
- QByteArray lowerCaseResource = resourceString.toLower();
- ResourceType resource = qKmsResourceMap()->value(lowerCaseResource);
- void *result = 0;
- switch (resource) {
- case EglDisplay:
- result = eglDisplay();
- break;
- default:
- result = 0;
- }
- return result;
-
-}
-void *QKmsNativeInterface::nativeResourceForWindow(const QByteArray &resourceString, QWindow *window)
-{
- QByteArray lowerCaseResource = resourceString.toLower();
- ResourceType resource = qKmsResourceMap()->value(lowerCaseResource);
- void *result = 0;
- switch (resource) {
- case EglDisplay:
- result = eglDisplayForWindow(window);
- break;
- case EglContext:
- result = eglContextForWindow(window);
- break;
- default:
- result = 0;
- }
- return result;
-}
-
-QPlatformNativeInterface::NativeResourceForContextFunction QKmsNativeInterface::nativeResourceFunctionForContext(const QByteArray &resource)
-{
- QByteArray lowerCaseResource = resource.toLower();
- if (lowerCaseResource == "get_egl_context") {
- return eglContextForContext;
- }
- return 0;
-}
-
-void *QKmsNativeInterface::eglDisplay()
-{
- //QKmsIntegration *integration = static_cast<QKmsIntegration *>(QGuiApplicationPrivate::platformIntegration());
- QKmsScreen *screen = static_cast<QKmsScreen *>(QGuiApplication::primaryScreen()->handle());
- if (!screen || !screen->device())
- return 0;
- return screen->device()->eglDisplay();
-}
-
-void *QKmsNativeInterface::eglDisplayForWindow(QWindow *window)
-{
- QKmsScreen *screen = qPlatformScreenForWindow(window);
- if (!screen)
- return 0;
- QKmsDevice *device = screen->device();
- if (!device)
- return 0;
- return device->eglDisplay();
-}
-
-void *QKmsNativeInterface::eglContextForWindow(QWindow *)
-{
- return 0;
-}
-
-QKmsScreen *QKmsNativeInterface::qPlatformScreenForWindow(QWindow *window)
-{
- QScreen *screen = window ? window->screen() : QGuiApplication::primaryScreen();
- return static_cast<QKmsScreen *>(screen->handle());
-}
-
-void *QKmsNativeInterface::eglContextForContext(QOpenGLContext *context)
-{
- Q_ASSERT(context);
-
- QKmsContext *eglPlatformContext = static_cast<QKmsContext *>(context->handle());
-
- return eglPlatformContext->eglContext();
-}
diff --git a/src/plugins/platforms/kms/qkmsnativeinterface.h b/src/plugins/platforms/kms/qkmsnativeinterface.h
deleted file mode 100644
index 56879d0a3a..0000000000
--- a/src/plugins/platforms/kms/qkmsnativeinterface.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QKMSNATIVEINTERFACE_H
-#define QKMSNATIVEINTERFACE_H
-
-#include "qkmsscreen.h"
-
-#include <qpa/qplatformnativeinterface.h>
-
-class QKmsNativeInterface : public QPlatformNativeInterface
-{
-public:
- enum ResourceType {
- EglDisplay,
- EglContext
- };
-
- void *nativeResourceForIntegration(const QByteArray &resource) Q_DECL_OVERRIDE;
- void *nativeResourceForWindow(const QByteArray &resourceString, QWindow *window) Q_DECL_OVERRIDE;
-
- NativeResourceForContextFunction nativeResourceFunctionForContext(const QByteArray &resource) Q_DECL_OVERRIDE;
-
- void *eglDisplay();
- void *eglDisplayForWindow(QWindow *window);
- void *eglContextForWindow(QWindow *window);
- static void *eglContextForContext(QOpenGLContext *context);
-
-private:
- static QKmsScreen *qPlatformScreenForWindow(QWindow *window);
-};
-
-
-#endif // QKMSNATIVEINTERFACE_H
diff --git a/src/plugins/platforms/kms/qkmsscreen.cpp b/src/plugins/platforms/kms/qkmsscreen.cpp
deleted file mode 100644
index 6392b99cd5..0000000000
--- a/src/plugins/platforms/kms/qkmsscreen.cpp
+++ /dev/null
@@ -1,275 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkmsscreen.h"
-#include "qkmscursor.h"
-#include "qkmsdevice.h"
-#include "qkmscontext.h"
-
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-
-#include <QCoreApplication>
-#include <QtDebug>
-
-QT_BEGIN_NAMESPACE
-
-Q_LOGGING_CATEGORY(lcQpaScreen, "qt.qpa.kms.screen")
-
-//Fallback mode (taken from Wayland DRM demo compositor)
-static drmModeModeInfo builtin_1024x768 = {
- 63500, //clock
- 1024, 1072, 1176, 1328, 0,
- 768, 771, 775, 798, 0,
- 59920,
- DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC,
- 0,
- "1024x768"
-};
-
-QKmsScreen::QKmsScreen(QKmsDevice *device, const drmModeRes *resources, const drmModeConnector *connector)
- : m_device(device),
- m_current_bo(0),
- m_next_bo(0),
- m_connectorId(connector->connector_id),
- m_depth(32),
- m_format(QImage::Format_Invalid),
- m_eglWindowSurface(EGL_NO_SURFACE),
- m_modeSet(false)
-{
- m_cursor = new QKmsCursor(this);
- initializeScreenMode(resources, connector);
-}
-
-QKmsScreen::~QKmsScreen()
-{
- delete m_cursor;
- drmModeSetCrtc(m_device->fd(), m_oldCrtc->crtc_id, m_oldCrtc->buffer_id,
- m_oldCrtc->x, m_oldCrtc->y,
- &m_connectorId, 1, &m_oldCrtc->mode);
- drmModeFreeCrtc(m_oldCrtc);
- if (m_eglWindowSurface != EGL_NO_SURFACE)
- eglDestroySurface(m_device->eglDisplay(), m_eglWindowSurface);
- gbm_surface_destroy(m_gbmSurface);
-}
-
-QRect QKmsScreen::geometry() const
-{
- return m_geometry;
-}
-
-int QKmsScreen::depth() const
-{
- return m_depth;
-}
-
-QImage::Format QKmsScreen::format() const
-{
- return m_format;
-}
-
-QSizeF QKmsScreen::physicalSize() const
-{
- return m_physicalSize;
-}
-
-QPlatformCursor *QKmsScreen::cursor() const
-{
- return m_cursor;
-}
-
-void QKmsScreen::initializeScreenMode(const drmModeRes *resources, const drmModeConnector *connector)
-{
- //Determine optimal mode for screen
- drmModeModeInfo *mode = 0;
- for (int i = 0; i < connector->count_modes; ++i) {
- if (connector->modes[i].type & DRM_MODE_TYPE_PREFERRED) {
- mode = &connector->modes[i];
- break;
- }
- }
- if (!mode) {
- if (connector->count_modes > 0)
- mode = &connector->modes[0];
- else
- mode = &builtin_1024x768;
- }
-
- drmModeEncoder *encoder = drmModeGetEncoder(m_device->fd(), connector->encoders[0]);
- if (encoder == 0)
- qFatal("No encoder for connector.");
-
- int i;
- for (i = 0; i < resources->count_crtcs; i++) {
- if (encoder->possible_crtcs & (1 << i))
- break;
- }
- if (i == resources->count_crtcs)
- qFatal("No usable crtc for encoder.");
-
- m_oldCrtc = drmModeGetCrtc(m_device->fd(), encoder->crtc_id);
-
- m_crtcId = resources->crtcs[i];
- m_mode = *mode;
- m_geometry = QRect(0, 0, m_mode.hdisplay, m_mode.vdisplay);
- qCDebug(lcQpaScreen) << "kms initialized with geometry" << m_geometry;
- m_depth = 32;
- m_format = QImage::Format_RGB32;
- m_physicalSize = QSizeF(connector->mmWidth, connector->mmHeight);
-
- m_gbmSurface = gbm_surface_create(m_device->gbmDevice(),
- m_mode.hdisplay, m_mode.vdisplay,
- GBM_BO_FORMAT_XRGB8888,
- GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
-
- qCDebug(lcQpaScreen) << "created gbm surface" << m_gbmSurface << m_mode.hdisplay << m_mode.vdisplay;
- //Cleanup
- drmModeFreeEncoder(encoder);
-}
-
-QSurfaceFormat QKmsScreen::tweakFormat(const QSurfaceFormat &format)
-{
- QSurfaceFormat fmt = format;
- fmt.setRedBufferSize(8);
- fmt.setGreenBufferSize(8);
- fmt.setBlueBufferSize(8);
- if (fmt.alphaBufferSize() != -1)
- fmt.setAlphaBufferSize(8);
- return fmt;
-}
-
-void QKmsScreen::initializeWithFormat(const QSurfaceFormat &format)
-{
- EGLDisplay display = m_device->eglDisplay();
- EGLConfig config = q_configFromGLFormat(display, tweakFormat(format));
-
- m_eglWindowSurface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_gbmSurface, NULL);
- qCDebug(lcQpaScreen) << "created window surface";
- m_surfaceFormat = q_glFormatFromConfig(display, config);
-}
-
-void QKmsScreen::swapBuffers()
-{
- eglSwapBuffers(m_device->eglDisplay(), m_eglWindowSurface);
-
- m_next_bo = gbm_surface_lock_front_buffer(m_gbmSurface);
- if (!m_next_bo)
- qFatal("kms: Failed to lock front buffer");
-
- performPageFlip();
-}
-
-void QKmsScreen::performPageFlip()
-{
- if (!m_next_bo)
- return;
-
- uint32_t width = gbm_bo_get_width(m_next_bo);
- uint32_t height = gbm_bo_get_height(m_next_bo);
- uint32_t stride = gbm_bo_get_stride(m_next_bo);
- uint32_t handle = gbm_bo_get_handle(m_next_bo).u32;
-
- uint32_t fb_id;
- int ret = drmModeAddFB(m_device->fd(), width, height, 24, 32,
- stride, handle, &fb_id);
- if (ret) {
- qFatal("kms: Failed to create fb: fd %d, w %d, h %d, stride %d, handle %d, ret %d",
- m_device->fd(), width, height, stride, handle, ret);
- }
-
- if (!m_modeSet) {
- //Set the Mode of the screen.
- int ret = drmModeSetCrtc(m_device->fd(), m_crtcId, fb_id,
- 0, 0, &m_connectorId, 1, &m_mode);
- if (ret)
- qFatal("failed to set mode");
- m_modeSet = true;
-
- // Initialize cursor
-
- static int hideCursor = qEnvironmentVariableIntValue("QT_QPA_KMS_HIDECURSOR");
- if (!hideCursor) {
- QCursor cursor(Qt::ArrowCursor);
- m_cursor->changeCursor(&cursor, 0);
- }
- }
-
- int pageFlipStatus = drmModePageFlip(m_device->fd(), m_crtcId,
- fb_id,
- DRM_MODE_PAGE_FLIP_EVENT, this);
- if (pageFlipStatus)
- {
- qWarning("Pageflip status: %d", pageFlipStatus);
- gbm_surface_release_buffer(m_gbmSurface, m_next_bo);
- m_next_bo = 0;
- }
-}
-
-void QKmsScreen::handlePageFlipped()
-{
- if (m_current_bo)
- gbm_surface_release_buffer(m_gbmSurface, m_current_bo);
-
- m_current_bo = m_next_bo;
- m_next_bo = 0;
-}
-
-QKmsDevice * QKmsScreen::device() const
-{
- return m_device;
-}
-
-void QKmsScreen::waitForPageFlipComplete()
-{
- while (m_next_bo) {
-#if 0
- //Check manually if there is something to be read on the device
- //as there are senarios where the signal is not received (starvation)
- fd_set fdSet;
- timeval timeValue;
- int returnValue;
-
- FD_ZERO(&fdSet);
- FD_SET(m_device->fd(), &fdSet);
- timeValue.tv_sec = 0;
- timeValue.tv_usec = 1000;
-
- returnValue = select(1, &fdSet, 0, 0, &timeValue);
- printf("select returns %d\n", returnValue);
-#endif
-
- m_device->handlePageFlipCompleted();
- }
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/kms/qkmsscreen.h b/src/plugins/platforms/kms/qkmsscreen.h
deleted file mode 100644
index c52d0211b3..0000000000
--- a/src/plugins/platforms/kms/qkmsscreen.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QKMSSCREEN_H
-#define QKMSSCREEN_H
-
-#include <stddef.h>
-
-#define EGL_EGLEXT_PROTOTYPES 1
-#define GL_GLEXT_PROTOTYPES 1
-
-extern "C" {
-#include <gbm.h>
-#include <xf86drmMode.h>
-#include <xf86drm.h>
-}
-
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-#include <QtGui/qopengl.h>
-#include <QtGui/qsurfaceformat.h>
-#include <QtCore/qloggingcategory.h>
-
-#include <qpa/qplatformscreen.h>
-
-QT_BEGIN_NAMESPACE
-
-Q_DECLARE_LOGGING_CATEGORY(lcQpaScreen)
-
-class QKmsCursor;
-class QKmsDevice;
-class QKmsContext;
-
-class QKmsScreen : public QPlatformScreen
-{
-public:
- QKmsScreen(QKmsDevice *device, const drmModeRes *resources, const drmModeConnector *connector);
- ~QKmsScreen();
-
- QRect geometry() const Q_DECL_OVERRIDE;
- int depth() const Q_DECL_OVERRIDE;
- QImage::Format format() const Q_DECL_OVERRIDE;
- QSizeF physicalSize() const Q_DECL_OVERRIDE;
- QPlatformCursor *cursor() const Q_DECL_OVERRIDE;
-
- quint32 crtcId() const { return m_crtcId; }
- QKmsDevice *device() const;
-
- void initializeWithFormat(const QSurfaceFormat &format);
-
- //Called by context for each screen
- void swapBuffers();
- void handlePageFlipped();
-
- EGLSurface eglSurface() const { return m_eglWindowSurface; }
-
- void waitForPageFlipComplete();
-
- static QSurfaceFormat tweakFormat(const QSurfaceFormat &format);
-
- QSurfaceFormat surfaceFormat() const { return m_surfaceFormat; }
-
-private:
- void performPageFlip();
- void initializeScreenMode(const drmModeRes *resources, const drmModeConnector *connector);
-
- QKmsDevice *m_device;
- gbm_bo *m_current_bo;
- gbm_bo *m_next_bo;
- quint32 m_connectorId;
-
- quint32 m_crtcId;
- drmModeModeInfo m_mode;
- QRect m_geometry;
- QSizeF m_physicalSize;
- int m_depth;
- QImage::Format m_format;
-
- drmModeCrtcPtr m_oldCrtc;
-
- QKmsCursor *m_cursor;
-
- gbm_surface *m_gbmSurface;
- EGLSurface m_eglWindowSurface;
-
- bool m_modeSet;
- QSurfaceFormat m_surfaceFormat;
-};
-
-QT_END_NAMESPACE
-
-#endif // QKMSSCREEN_H
diff --git a/src/plugins/platforms/kms/qkmswindow.cpp b/src/plugins/platforms/kms/qkmswindow.cpp
deleted file mode 100644
index 3b01dfedca..0000000000
--- a/src/plugins/platforms/kms/qkmswindow.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkmswindow.h"
-#include "qkmsscreen.h"
-
-#include <qpa/qwindowsysteminterface.h>
-#include <qpa/qplatformwindow_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QKmsWindow::QKmsWindow(QWindow *window)
- : QPlatformWindow(window)
-{
- Q_D(QPlatformWindow);
- m_screen = QPlatformScreen::platformScreenForWindow(window);
- static_cast<QKmsScreen *>(m_screen)->initializeWithFormat(window->requestedFormat());
- setGeometry(d->rect); // rect is set to window->geometry() in base ctor
-}
-
-void QKmsWindow::setGeometry(const QRect &rect)
-{
- // All windows must be fullscreen
- QRect fullscreenRect = m_screen->availableGeometry();
- if (rect != fullscreenRect)
- QWindowSystemInterface::handleGeometryChange(window(), fullscreenRect);
-
- QPlatformWindow::setGeometry(fullscreenRect);
-}
-
-QSurfaceFormat QKmsWindow::format() const
-{
- return static_cast<QKmsScreen *>(m_screen)->surfaceFormat();
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp b/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
index ccf86dafb2..8c8c8a15ea 100644
--- a/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
+++ b/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
@@ -46,6 +46,10 @@
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatforminputcontextfactory_p.h>
+#ifndef QT_NO_LIBINPUT
+#include <QtPlatformSupport/private/qlibinputhandler_p.h>
+#endif
+
#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
@@ -130,6 +134,13 @@ QPlatformServices *QLinuxFbIntegration::services() const
void QLinuxFbIntegration::createInputHandlers()
{
+#ifndef QT_NO_LIBINPUT
+ if (!qEnvironmentVariableIntValue("QT_QPA_FB_NO_LIBINPUT")) {
+ new QLibInputHandler(QLatin1String("libinput"), QString());
+ return;
+ }
+#endif
+
#if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK))
new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString(), this);
new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString(), this);
diff --git a/src/plugins/platforms/mirclient/mirclient.json b/src/plugins/platforms/mirclient/mirclient.json
new file mode 100644
index 0000000000..c31558a2f1
--- /dev/null
+++ b/src/plugins/platforms/mirclient/mirclient.json
@@ -0,0 +1,3 @@
+{
+ "Keys": [ "mirclient" ]
+}
diff --git a/src/plugins/platforms/mirclient/mirclient.pro b/src/plugins/platforms/mirclient/mirclient.pro
new file mode 100644
index 0000000000..033ce579b9
--- /dev/null
+++ b/src/plugins/platforms/mirclient/mirclient.pro
@@ -0,0 +1,47 @@
+TARGET = mirclient
+TEMPLATE = lib
+
+PLUGIN_TYPE = platforms
+PLUGIN_CLASS_NAME = MirServerIntegrationPlugin
+!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
+load(qt_plugin)
+
+QT += core-private gui-private platformsupport-private dbus
+
+CONFIG += qpa/genericunixfontdatabase
+
+DEFINES += MESA_EGL_NO_X11_HEADERS
+# CONFIG += c++11 # only enables C++0x
+QMAKE_CXXFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -Werror -Wall
+QMAKE_LFLAGS += -std=c++11 -Wl,-no-undefined
+
+CONFIG += link_pkgconfig
+PKGCONFIG += egl mirclient ubuntu-platform-api
+
+SOURCES = \
+ qmirclientbackingstore.cpp \
+ qmirclientclipboard.cpp \
+ qmirclientglcontext.cpp \
+ qmirclientinput.cpp \
+ qmirclientintegration.cpp \
+ qmirclientnativeinterface.cpp \
+ qmirclientplatformservices.cpp \
+ qmirclientplugin.cpp \
+ qmirclientscreen.cpp \
+ qmirclienttheme.cpp \
+ qmirclientwindow.cpp
+
+HEADERS = \
+ qmirclientbackingstore.h \
+ qmirclientclipboard.h \
+ qmirclientglcontext.h \
+ qmirclientinput.h \
+ qmirclientintegration.h \
+ qmirclientlogging.h \
+ qmirclientnativeinterface.h \
+ qmirclientorientationchangeevent_p.h \
+ qmirclientplatformservices.h \
+ qmirclientplugin.h \
+ qmirclientscreen.h \
+ qmirclienttheme.h \
+ qmirclientwindow.h
diff --git a/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp b/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
new file mode 100644
index 0000000000..daa0b229ec
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
@@ -0,0 +1,146 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientbackingstore.h"
+#include "qmirclientlogging.h"
+#include <QtGui/QOpenGLContext>
+#include <QtGui/QOpenGLTexture>
+#include <QtGui/QMatrix4x4>
+#include <QtGui/private/qopengltextureblitter_p.h>
+#include <QtGui/qopenglfunctions.h>
+
+QMirClientBackingStore::QMirClientBackingStore(QWindow* window)
+ : QPlatformBackingStore(window)
+ , mContext(new QOpenGLContext)
+ , mTexture(new QOpenGLTexture(QOpenGLTexture::Target2D))
+ , mBlitter(new QOpenGLTextureBlitter)
+{
+ mContext->setFormat(window->requestedFormat());
+ mContext->setScreen(window->screen());
+ mContext->create();
+
+ window->setSurfaceType(QSurface::OpenGLSurface);
+}
+
+QMirClientBackingStore::~QMirClientBackingStore()
+{
+}
+
+void QMirClientBackingStore::flush(QWindow* window, const QRegion& region, const QPoint& offset)
+{
+ Q_UNUSED(region);
+ Q_UNUSED(offset);
+ mContext->makeCurrent(window);
+ glViewport(0, 0, window->width(), window->height());
+
+ updateTexture();
+
+ if (!mBlitter->isCreated())
+ mBlitter->create();
+
+ mBlitter->bind();
+ mBlitter->setSwizzleRB(true);
+ mBlitter->blit(mTexture->textureId(), QMatrix4x4(), QOpenGLTextureBlitter::OriginTopLeft);
+ mBlitter->release();
+
+ mContext->swapBuffers(window);
+}
+
+void QMirClientBackingStore::updateTexture()
+{
+ if (mDirty.isNull())
+ return;
+
+ if (!mTexture->isCreated()) {
+ mTexture->setMinificationFilter(QOpenGLTexture::Nearest);
+ mTexture->setMagnificationFilter(QOpenGLTexture::Nearest);
+ mTexture->setWrapMode(QOpenGLTexture::ClampToEdge);
+ mTexture->setData(mImage, QOpenGLTexture::DontGenerateMipMaps);
+ mTexture->create();
+ }
+ mTexture->bind();
+
+ QRegion fixed;
+ QRect imageRect = mImage.rect();
+
+ Q_FOREACH (const QRect &rect, mDirty.rects()) {
+ // intersect with image rect to be sure
+ QRect r = imageRect & rect;
+
+ // if the rect is wide enough it is cheaper to just extend it instead of doing an image copy
+ if (r.width() >= imageRect.width() / 2) {
+ r.setX(0);
+ r.setWidth(imageRect.width());
+ }
+
+ fixed |= r;
+ }
+
+ Q_FOREACH (const QRect &rect, fixed.rects()) {
+ // if the sub-rect is full-width we can pass the image data directly to
+ // OpenGL instead of copying, since there is no gap between scanlines
+ if (rect.width() == imageRect.width()) {
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+ mImage.constScanLine(rect.y()));
+ } else {
+ glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+ mImage.copy(rect).constBits());
+ }
+ }
+ /* End of code taken from QEGLPlatformBackingStore */
+
+ mDirty = QRegion();
+}
+
+
+void QMirClientBackingStore::beginPaint(const QRegion& region)
+{
+ mDirty |= region;
+}
+
+void QMirClientBackingStore::resize(const QSize& size, const QRegion& /*staticContents*/)
+{
+ mImage = QImage(size, QImage::Format_RGB32);
+
+ if (mTexture->isCreated())
+ mTexture->destroy();
+}
+
+QPaintDevice* QMirClientBackingStore::paintDevice()
+{
+ return &mImage;
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientbackingstore.h b/src/plugins/platforms/mirclient/qmirclientbackingstore.h
new file mode 100644
index 0000000000..22b8bf9bc5
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientbackingstore.h
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTBACKINGSTORE_H
+#define QMIRCLIENTBACKINGSTORE_H
+
+#include <qpa/qplatformbackingstore.h>
+
+class QOpenGLContext;
+class QOpenGLTexture;
+class QOpenGLTextureBlitter;
+
+class QMirClientBackingStore : public QPlatformBackingStore
+{
+public:
+ QMirClientBackingStore(QWindow* window);
+ virtual ~QMirClientBackingStore();
+
+ // QPlatformBackingStore methods.
+ void beginPaint(const QRegion&) override;
+ void flush(QWindow* window, const QRegion& region, const QPoint& offset) override;
+ void resize(const QSize& size, const QRegion& staticContents) override;
+ QPaintDevice* paintDevice() override;
+
+protected:
+ void updateTexture();
+
+private:
+ QScopedPointer<QOpenGLContext> mContext;
+ QScopedPointer<QOpenGLTexture> mTexture;
+ QScopedPointer<QOpenGLTextureBlitter> mBlitter;
+ QImage mImage;
+ QRegion mDirty;
+};
+
+#endif // QMIRCLIENTBACKINGSTORE_H
diff --git a/src/plugins/platforms/mirclient/qmirclientclipboard.cpp b/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
new file mode 100644
index 0000000000..aa2ddf2103
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
@@ -0,0 +1,305 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientclipboard.h"
+
+#include <QtCore/QMimeData>
+#include <QtCore/QStringList>
+#include <QDBusInterface>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+
+// FIXME(loicm) The clipboard data format is not defined by Ubuntu Platform API
+// which makes it impossible to have non-Qt applications communicate with Qt
+// applications through the clipboard API. The solution would be to have
+// Ubuntu Platform define the data format or propose an API that supports
+// embedding different mime types in the clipboard.
+
+// Data format:
+// number of mime types (sizeof(int))
+// data layout ((4 * sizeof(int)) * number of mime types)
+// mime type string offset (sizeof(int))
+// mime type string size (sizeof(int))
+// data offset (sizeof(int))
+// data size (sizeof(int))
+// data (n bytes)
+
+namespace {
+
+const int maxFormatsCount = 16;
+const int maxBufferSize = 4 * 1024 * 1024; // 4 Mb
+
+}
+
+QMirClientClipboard::QMirClientClipboard()
+ : mMimeData(new QMimeData)
+ , mIsOutdated(true)
+ , mUpdatesDisabled(false)
+ , mDBusSetupDone(false)
+{
+}
+
+QMirClientClipboard::~QMirClientClipboard()
+{
+ delete mMimeData;
+}
+
+void QMirClientClipboard::requestDBusClipboardContents()
+{
+ if (!mDBusSetupDone) {
+ setupDBus();
+ }
+
+ if (!mPendingGetContentsCall.isNull())
+ return;
+
+ QDBusPendingCall pendingCall = mDBusClipboard->asyncCall("GetContents");
+
+ mPendingGetContentsCall = new QDBusPendingCallWatcher(pendingCall, this);
+
+ QObject::connect(mPendingGetContentsCall.data(), SIGNAL(finished(QDBusPendingCallWatcher*)),
+ this, SLOT(onDBusClipboardGetContentsFinished(QDBusPendingCallWatcher*)));
+}
+
+void QMirClientClipboard::onDBusClipboardGetContentsFinished(QDBusPendingCallWatcher* call)
+{
+ Q_ASSERT(call == mPendingGetContentsCall.data());
+
+ QDBusPendingReply<QByteArray> reply = *call;
+ if (reply.isError()) {
+ qCritical("QMirClientClipboard - Failed to get system clipboard contents via D-Bus. %s, %s",
+ qPrintable(reply.error().name()), qPrintable(reply.error().message()));
+ // TODO: Might try again later a number of times...
+ } else {
+ QByteArray serializedMimeData = reply.argumentAt<0>();
+ updateMimeData(serializedMimeData);
+ }
+ call->deleteLater();
+}
+
+void QMirClientClipboard::onDBusClipboardSetContentsFinished(QDBusPendingCallWatcher *call)
+{
+ QDBusPendingReply<void> reply = *call;
+ if (reply.isError()) {
+ qCritical("QMirClientClipboard - Failed to set the system clipboard contents via D-Bus. %s, %s",
+ qPrintable(reply.error().name()), qPrintable(reply.error().message()));
+ // TODO: Might try again later a number of times...
+ }
+ call->deleteLater();
+}
+
+void QMirClientClipboard::updateMimeData(const QByteArray &serializedMimeData)
+{
+ if (mUpdatesDisabled)
+ return;
+
+ QMimeData *newMimeData = deserializeMimeData(serializedMimeData);
+ if (newMimeData) {
+ delete mMimeData;
+ mMimeData = newMimeData;
+ mIsOutdated = false;
+ emitChanged(QClipboard::Clipboard);
+ } else {
+ qWarning("QMirClientClipboard - Got invalid serialized mime data. Ignoring it.");
+ }
+}
+
+void QMirClientClipboard::setupDBus()
+{
+ QDBusConnection dbusConnection = QDBusConnection::sessionBus();
+
+ bool ok = dbusConnection.connect(
+ "com.canonical.QtMir",
+ "/com/canonical/QtMir/Clipboard",
+ "com.canonical.QtMir.Clipboard",
+ "ContentsChanged",
+ this, SLOT(updateMimeData(QByteArray)));
+ if (!ok) {
+ qCritical("QMirClientClipboard - Failed to connect to ContentsChanged signal form the D-Bus system clipboard.");
+ }
+
+ mDBusClipboard = new QDBusInterface("com.canonical.QtMir",
+ "/com/canonical/QtMir/Clipboard",
+ "com.canonical.QtMir.Clipboard",
+ dbusConnection);
+
+ mDBusSetupDone = true;
+}
+
+QByteArray QMirClientClipboard::serializeMimeData(QMimeData *mimeData) const
+{
+ const QStringList formats = mimeData->formats();
+ const int formatCount = qMin(formats.size(), maxFormatsCount);
+ const int headerSize = sizeof(int) + (formatCount * 4 * sizeof(int));
+ int bufferSize = headerSize;
+
+ for (int i = 0; i < formatCount; i++)
+ bufferSize += formats[i].size() + mimeData->data(formats[i]).size();
+
+ QByteArray serializedMimeData;
+ if (bufferSize <= maxBufferSize) {
+ // Serialize data.
+ serializedMimeData.resize(bufferSize);
+ {
+ char *buffer = serializedMimeData.data();
+ int* header = reinterpret_cast<int*>(serializedMimeData.data());
+ int offset = headerSize;
+ header[0] = formatCount;
+ for (int i = 0; i < formatCount; i++) {
+ const int formatOffset = offset;
+ const int formatSize = formats[i].size();
+ const int dataOffset = offset + formatSize;
+ const int dataSize = mimeData->data(formats[i]).size();
+ memcpy(&buffer[formatOffset], formats[i].toLatin1().data(), formatSize);
+ memcpy(&buffer[dataOffset], mimeData->data(formats[i]).data(), dataSize);
+ header[i*4+1] = formatOffset;
+ header[i*4+2] = formatSize;
+ header[i*4+3] = dataOffset;
+ header[i*4+4] = dataSize;
+ offset += formatSize + dataSize;
+ }
+ }
+ } else {
+ qWarning("QMirClientClipboard: Not sending contents (%d bytes) to the global clipboard as it's"
+ " bigger than the maximum allowed size of %d bytes", bufferSize, maxBufferSize);
+ }
+
+ return serializedMimeData;
+}
+
+QMimeData *QMirClientClipboard::deserializeMimeData(const QByteArray &serializedMimeData) const
+{
+ if (static_cast<std::size_t>(serializedMimeData.size()) < sizeof(int)) {
+ // Data is invalid
+ return nullptr;
+ }
+
+ QMimeData *mimeData = new QMimeData;
+
+ const char* const buffer = serializedMimeData.constData();
+ const int* const header = reinterpret_cast<const int*>(serializedMimeData.constData());
+
+ const int count = qMin(header[0], maxFormatsCount);
+
+ for (int i = 0; i < count; i++) {
+ const int formatOffset = header[i*4+1];
+ const int formatSize = header[i*4+2];
+ const int dataOffset = header[i*4+3];
+ const int dataSize = header[i*4+4];
+
+ if (formatOffset + formatSize <= serializedMimeData.size()
+ && dataOffset + dataSize <= serializedMimeData.size()) {
+
+ QString mimeType = QString::fromLatin1(&buffer[formatOffset], formatSize);
+ QByteArray mimeDataBytes(&buffer[dataOffset], dataSize);
+
+ mimeData->setData(mimeType, mimeDataBytes);
+ }
+ }
+
+ return mimeData;
+}
+
+QMimeData* QMirClientClipboard::mimeData(QClipboard::Mode mode)
+{
+ if (mode != QClipboard::Clipboard)
+ return nullptr;
+
+ if (mIsOutdated && mPendingGetContentsCall.isNull()) {
+ requestDBusClipboardContents();
+ }
+
+ // Return whatever we have at the moment instead of blocking until we have something.
+ //
+ // This might be called during app startup just for the sake of checking if some
+ // "Paste" UI control should be enabled or not.
+ // We will emit QClipboard::changed() once we finally have something.
+ return mMimeData;
+}
+
+void QMirClientClipboard::setMimeData(QMimeData* mimeData, QClipboard::Mode mode)
+{
+ if (mode != QClipboard::Clipboard)
+ return;
+
+ if (!mPendingGetContentsCall.isNull()) {
+ // Ignore whatever comes from the system clipboard as we are going to change it anyway
+ QObject::disconnect(mPendingGetContentsCall.data(), 0, this, 0);
+ mUpdatesDisabled = true;
+ mPendingGetContentsCall->waitForFinished();
+ mUpdatesDisabled = false;
+ delete mPendingGetContentsCall.data();
+ }
+
+ QByteArray serializedMimeData = serializeMimeData(mimeData);
+ if (!serializedMimeData.isEmpty()) {
+ setDBusClipboardContents(serializedMimeData);
+ }
+
+ mMimeData = mimeData;
+ emitChanged(QClipboard::Clipboard);
+}
+
+bool QMirClientClipboard::supportsMode(QClipboard::Mode mode) const
+{
+ return mode == QClipboard::Clipboard;
+}
+
+bool QMirClientClipboard::ownsMode(QClipboard::Mode mode) const
+{
+ Q_UNUSED(mode);
+ return false;
+}
+
+void QMirClientClipboard::setDBusClipboardContents(const QByteArray &clipboardContents)
+{
+ if (!mPendingSetContentsCall.isNull()) {
+ // Ignore any previous set call as we are going to overwrite it anyway
+ QObject::disconnect(mPendingSetContentsCall.data(), 0, this, 0);
+ mUpdatesDisabled = true;
+ mPendingSetContentsCall->waitForFinished();
+ mUpdatesDisabled = false;
+ delete mPendingSetContentsCall.data();
+ }
+
+ QDBusPendingCall pendingCall = mDBusClipboard->asyncCall("SetContents", clipboardContents);
+
+ mPendingSetContentsCall = new QDBusPendingCallWatcher(pendingCall, this);
+
+ QObject::connect(mPendingSetContentsCall.data(), SIGNAL(finished(QDBusPendingCallWatcher*)),
+ this, SLOT(onDBusClipboardSetContentsFinished(QDBusPendingCallWatcher*)));
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientclipboard.h b/src/plugins/platforms/mirclient/qmirclientclipboard.h
new file mode 100644
index 0000000000..d3d3d400d2
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientclipboard.h
@@ -0,0 +1,88 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTCLIPBOARD_H
+#define QMIRCLIENTCLIPBOARD_H
+
+#include <qpa/qplatformclipboard.h>
+
+#include <QMimeData>
+#include <QPointer>
+class QDBusInterface;
+class QDBusPendingCallWatcher;
+
+class QMirClientClipboard : public QObject, public QPlatformClipboard
+{
+ Q_OBJECT
+public:
+ QMirClientClipboard();
+ virtual ~QMirClientClipboard();
+
+ // QPlatformClipboard methods.
+ QMimeData* mimeData(QClipboard::Mode mode = QClipboard::Clipboard) override;
+ void setMimeData(QMimeData* data, QClipboard::Mode mode = QClipboard::Clipboard) override;
+ bool supportsMode(QClipboard::Mode mode) const override;
+ bool ownsMode(QClipboard::Mode mode) const override;
+
+ void requestDBusClipboardContents();
+
+private Q_SLOTS:
+ void onDBusClipboardGetContentsFinished(QDBusPendingCallWatcher*);
+ void onDBusClipboardSetContentsFinished(QDBusPendingCallWatcher*);
+ void updateMimeData(const QByteArray &serializedMimeData);
+
+private:
+ void setupDBus();
+
+ QByteArray serializeMimeData(QMimeData *mimeData) const;
+ QMimeData *deserializeMimeData(const QByteArray &serializedMimeData) const;
+
+ void setDBusClipboardContents(const QByteArray &clipboardContents);
+
+ QMimeData *mMimeData;
+ bool mIsOutdated;
+
+ QPointer<QDBusInterface> mDBusClipboard;
+
+ QPointer<QDBusPendingCallWatcher> mPendingGetContentsCall;
+ QPointer<QDBusPendingCallWatcher> mPendingSetContentsCall;
+
+ bool mUpdatesDisabled;
+ bool mDBusSetupDone;
+};
+
+#endif // QMIRCLIENTCLIPBOARD_H
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
new file mode 100644
index 0000000000..bfba5051e5
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
@@ -0,0 +1,156 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientglcontext.h"
+#include "qmirclientwindow.h"
+#include "qmirclientlogging.h"
+#include <QtPlatformSupport/private/qeglconvenience_p.h>
+
+#if !defined(QT_NO_DEBUG)
+static void printOpenGLESConfig() {
+ static bool once = true;
+ if (once) {
+ const char* string = (const char*) glGetString(GL_VENDOR);
+ LOG("OpenGL ES vendor: %s", string);
+ string = (const char*) glGetString(GL_RENDERER);
+ LOG("OpenGL ES renderer: %s", string);
+ string = (const char*) glGetString(GL_VERSION);
+ LOG("OpenGL ES version: %s", string);
+ string = (const char*) glGetString(GL_SHADING_LANGUAGE_VERSION);
+ LOG("OpenGL ES Shading Language version: %s", string);
+ string = (const char*) glGetString(GL_EXTENSIONS);
+ LOG("OpenGL ES extensions: %s", string);
+ once = false;
+ }
+}
+#endif
+
+static EGLenum api_in_use()
+{
+#ifdef QTUBUNTU_USE_OPENGL
+ return EGL_OPENGL_API;
+#else
+ return EGL_OPENGL_ES_API;
+#endif
+}
+
+QMirClientOpenGLContext::QMirClientOpenGLContext(QMirClientScreen* screen, QMirClientOpenGLContext* share)
+{
+ ASSERT(screen != NULL);
+ mEglDisplay = screen->eglDisplay();
+ mScreen = screen;
+
+ // Create an OpenGL ES 2 context.
+ QVector<EGLint> attribs;
+ attribs.append(EGL_CONTEXT_CLIENT_VERSION);
+ attribs.append(2);
+ attribs.append(EGL_NONE);
+ ASSERT(eglBindAPI(api_in_use()) == EGL_TRUE);
+
+ mEglContext = eglCreateContext(mEglDisplay, screen->eglConfig(), share ? share->eglContext() : EGL_NO_CONTEXT,
+ attribs.constData());
+ DASSERT(mEglContext != EGL_NO_CONTEXT);
+}
+
+QMirClientOpenGLContext::~QMirClientOpenGLContext()
+{
+ ASSERT(eglDestroyContext(mEglDisplay, mEglContext) == EGL_TRUE);
+}
+
+bool QMirClientOpenGLContext::makeCurrent(QPlatformSurface* surface)
+{
+ DASSERT(surface->surface()->surfaceType() == QSurface::OpenGLSurface);
+ EGLSurface eglSurface = static_cast<QMirClientWindow*>(surface)->eglSurface();
+#if defined(QT_NO_DEBUG)
+ eglBindAPI(api_in_use());
+ eglMakeCurrent(mEglDisplay, eglSurface, eglSurface, mEglContext);
+#else
+ ASSERT(eglBindAPI(api_in_use()) == EGL_TRUE);
+ ASSERT(eglMakeCurrent(mEglDisplay, eglSurface, eglSurface, mEglContext) == EGL_TRUE);
+ printOpenGLESConfig();
+#endif
+ return true;
+}
+
+void QMirClientOpenGLContext::doneCurrent()
+{
+#if defined(QT_NO_DEBUG)
+ eglBindAPI(api_in_use());
+ eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+#else
+ ASSERT(eglBindAPI(api_in_use()) == EGL_TRUE);
+ ASSERT(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_TRUE);
+#endif
+}
+
+void QMirClientOpenGLContext::swapBuffers(QPlatformSurface* surface)
+{
+ QMirClientWindow *ubuntuWindow = static_cast<QMirClientWindow*>(surface);
+
+ EGLSurface eglSurface = ubuntuWindow->eglSurface();
+#if defined(QT_NO_DEBUG)
+ eglBindAPI(api_in_use());
+ eglSwapBuffers(mEglDisplay, eglSurface);
+#else
+ ASSERT(eglBindAPI(api_in_use()) == EGL_TRUE);
+ ASSERT(eglSwapBuffers(mEglDisplay, eglSurface) == EGL_TRUE);
+#endif
+
+ // "Technique" copied from mir, in examples/eglapp.c around line 96
+ EGLint newBufferWidth = -1;
+ EGLint newBufferHeight = -1;
+ /*
+ * Querying the surface (actually the current buffer) dimensions here is
+ * the only truly safe way to be sure that the dimensions we think we
+ * have are those of the buffer being rendered to. But this should be
+ * improved in future; https://bugs.launchpad.net/mir/+bug/1194384
+ */
+ eglQuerySurface(mEglDisplay, eglSurface, EGL_WIDTH, &newBufferWidth);
+ eglQuerySurface(mEglDisplay, eglSurface, EGL_HEIGHT, &newBufferHeight);
+
+ ubuntuWindow->onBuffersSwapped_threadSafe(newBufferWidth, newBufferHeight);
+}
+
+void (*QMirClientOpenGLContext::getProcAddress(const QByteArray& procName)) ()
+{
+#if defined(QT_NO_DEBUG)
+ eglBindAPI(api_in_use());
+#else
+ ASSERT(eglBindAPI(api_in_use()) == EGL_TRUE);
+#endif
+ return eglGetProcAddress(procName.constData());
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.h b/src/plugins/platforms/mirclient/qmirclientglcontext.h
new file mode 100644
index 0000000000..cc40298259
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientglcontext.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTGLCONTEXT_H
+#define QMIRCLIENTGLCONTEXT_H
+
+#include <qpa/qplatformopenglcontext.h>
+#include "qmirclientscreen.h"
+
+class QMirClientOpenGLContext : public QPlatformOpenGLContext
+{
+public:
+ QMirClientOpenGLContext(QMirClientScreen* screen, QMirClientOpenGLContext* share);
+ virtual ~QMirClientOpenGLContext();
+
+ // QPlatformOpenGLContext methods.
+ QSurfaceFormat format() const override { return mScreen->surfaceFormat(); }
+ void swapBuffers(QPlatformSurface* surface) override;
+ bool makeCurrent(QPlatformSurface* surface) override;
+ void doneCurrent() override;
+ bool isValid() const override { return mEglContext != EGL_NO_CONTEXT; }
+ void (*getProcAddress(const QByteArray& procName)) ();
+
+ EGLContext eglContext() const { return mEglContext; }
+
+private:
+ QMirClientScreen* mScreen;
+ EGLContext mEglContext;
+ EGLDisplay mEglDisplay;
+};
+
+#endif // QMIRCLIENTGLCONTEXT_H
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.cpp b/src/plugins/platforms/mirclient/qmirclientinput.cpp
new file mode 100644
index 0000000000..56bc21f420
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientinput.cpp
@@ -0,0 +1,520 @@
+/****************************************************************************
+**
+** Copyright (C) 2014-2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+// Local
+#include "qmirclientinput.h"
+#include "qmirclientintegration.h"
+#include "qmirclientnativeinterface.h"
+#include "qmirclientscreen.h"
+#include "qmirclientwindow.h"
+#include "qmirclientlogging.h"
+#include "qmirclientorientationchangeevent_p.h"
+
+// Qt
+#if !defined(QT_NO_DEBUG)
+#include <QtCore/QThread>
+#endif
+#include <QtCore/qglobal.h>
+#include <QtCore/QCoreApplication>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatforminputcontext.h>
+#include <qpa/qwindowsysteminterface.h>
+
+#include <xkbcommon/xkbcommon.h>
+#include <xkbcommon/xkbcommon-keysyms.h>
+
+#include <mir_toolkit/mir_client_library.h>
+
+#define LOG_EVENTS 0
+
+// XKB Keysyms which do not map directly to Qt types (i.e. Unicode points)
+static const uint32_t KeyTable[] = {
+ XKB_KEY_Escape, Qt::Key_Escape,
+ XKB_KEY_Tab, Qt::Key_Tab,
+ XKB_KEY_ISO_Left_Tab, Qt::Key_Backtab,
+ XKB_KEY_BackSpace, Qt::Key_Backspace,
+ XKB_KEY_Return, Qt::Key_Return,
+ XKB_KEY_Insert, Qt::Key_Insert,
+ XKB_KEY_Delete, Qt::Key_Delete,
+ XKB_KEY_Clear, Qt::Key_Delete,
+ XKB_KEY_Pause, Qt::Key_Pause,
+ XKB_KEY_Print, Qt::Key_Print,
+
+ XKB_KEY_Home, Qt::Key_Home,
+ XKB_KEY_End, Qt::Key_End,
+ XKB_KEY_Left, Qt::Key_Left,
+ XKB_KEY_Up, Qt::Key_Up,
+ XKB_KEY_Right, Qt::Key_Right,
+ XKB_KEY_Down, Qt::Key_Down,
+ XKB_KEY_Prior, Qt::Key_PageUp,
+ XKB_KEY_Next, Qt::Key_PageDown,
+
+ XKB_KEY_Shift_L, Qt::Key_Shift,
+ XKB_KEY_Shift_R, Qt::Key_Shift,
+ XKB_KEY_Shift_Lock, Qt::Key_Shift,
+ XKB_KEY_Control_L, Qt::Key_Control,
+ XKB_KEY_Control_R, Qt::Key_Control,
+ XKB_KEY_Meta_L, Qt::Key_Meta,
+ XKB_KEY_Meta_R, Qt::Key_Meta,
+ XKB_KEY_Alt_L, Qt::Key_Alt,
+ XKB_KEY_Alt_R, Qt::Key_Alt,
+ XKB_KEY_Caps_Lock, Qt::Key_CapsLock,
+ XKB_KEY_Num_Lock, Qt::Key_NumLock,
+ XKB_KEY_Scroll_Lock, Qt::Key_ScrollLock,
+ XKB_KEY_Super_L, Qt::Key_Super_L,
+ XKB_KEY_Super_R, Qt::Key_Super_R,
+ XKB_KEY_Menu, Qt::Key_Menu,
+ XKB_KEY_Hyper_L, Qt::Key_Hyper_L,
+ XKB_KEY_Hyper_R, Qt::Key_Hyper_R,
+ XKB_KEY_Help, Qt::Key_Help,
+
+ XKB_KEY_KP_Space, Qt::Key_Space,
+ XKB_KEY_KP_Tab, Qt::Key_Tab,
+ XKB_KEY_KP_Enter, Qt::Key_Enter,
+ XKB_KEY_KP_Home, Qt::Key_Home,
+ XKB_KEY_KP_Left, Qt::Key_Left,
+ XKB_KEY_KP_Up, Qt::Key_Up,
+ XKB_KEY_KP_Right, Qt::Key_Right,
+ XKB_KEY_KP_Down, Qt::Key_Down,
+ XKB_KEY_KP_Prior, Qt::Key_PageUp,
+ XKB_KEY_KP_Next, Qt::Key_PageDown,
+ XKB_KEY_KP_End, Qt::Key_End,
+ XKB_KEY_KP_Begin, Qt::Key_Clear,
+ XKB_KEY_KP_Insert, Qt::Key_Insert,
+ XKB_KEY_KP_Delete, Qt::Key_Delete,
+ XKB_KEY_KP_Equal, Qt::Key_Equal,
+ XKB_KEY_KP_Multiply, Qt::Key_Asterisk,
+ XKB_KEY_KP_Add, Qt::Key_Plus,
+ XKB_KEY_KP_Separator, Qt::Key_Comma,
+ XKB_KEY_KP_Subtract, Qt::Key_Minus,
+ XKB_KEY_KP_Decimal, Qt::Key_Period,
+ XKB_KEY_KP_Divide, Qt::Key_Slash,
+
+ XKB_KEY_ISO_Level3_Shift, Qt::Key_AltGr,
+ XKB_KEY_Multi_key, Qt::Key_Multi_key,
+ XKB_KEY_Codeinput, Qt::Key_Codeinput,
+ XKB_KEY_SingleCandidate, Qt::Key_SingleCandidate,
+ XKB_KEY_MultipleCandidate, Qt::Key_MultipleCandidate,
+ XKB_KEY_PreviousCandidate, Qt::Key_PreviousCandidate,
+
+ XKB_KEY_Mode_switch, Qt::Key_Mode_switch,
+ XKB_KEY_script_switch, Qt::Key_Mode_switch,
+ XKB_KEY_XF86AudioRaiseVolume, Qt::Key_VolumeUp,
+ XKB_KEY_XF86AudioLowerVolume, Qt::Key_VolumeDown,
+ XKB_KEY_XF86PowerOff, Qt::Key_PowerOff,
+ XKB_KEY_XF86PowerDown, Qt::Key_PowerDown,
+
+ 0, 0
+};
+
+class QMirClientEvent : public QEvent
+{
+public:
+ QMirClientEvent(QMirClientWindow* window, const MirEvent *event, QEvent::Type type)
+ : QEvent(type), window(window) {
+ nativeEvent = mir_event_ref(event);
+ }
+ ~QMirClientEvent()
+ {
+ mir_event_unref(nativeEvent);
+ }
+
+ QPointer<QMirClientWindow> window;
+ const MirEvent *nativeEvent;
+};
+
+QMirClientInput::QMirClientInput(QMirClientClientIntegration* integration)
+ : QObject(nullptr)
+ , mIntegration(integration)
+ , mEventFilterType(static_cast<QMirClientNativeInterface*>(
+ integration->nativeInterface())->genericEventFilterType())
+ , mEventType(static_cast<QEvent::Type>(QEvent::registerEventType()))
+{
+ // Initialize touch device.
+ mTouchDevice = new QTouchDevice;
+ mTouchDevice->setType(QTouchDevice::TouchScreen);
+ mTouchDevice->setCapabilities(
+ QTouchDevice::Position | QTouchDevice::Area | QTouchDevice::Pressure |
+ QTouchDevice::NormalizedPosition);
+ QWindowSystemInterface::registerTouchDevice(mTouchDevice);
+}
+
+QMirClientInput::~QMirClientInput()
+{
+ // Qt will take care of deleting mTouchDevice.
+}
+
+#if (LOG_EVENTS != 0)
+static const char* nativeEventTypeToStr(MirEventType t)
+{
+ switch (t)
+ {
+ case mir_event_type_key:
+ return "mir_event_type_key";
+ case mir_event_type_motion:
+ return "mir_event_type_motion";
+ case mir_event_type_surface:
+ return "mir_event_type_surface";
+ case mir_event_type_resize:
+ return "mir_event_type_resize";
+ case mir_event_type_prompt_session_state_change:
+ return "mir_event_type_prompt_session_state_change";
+ case mir_event_type_orientation:
+ return "mir_event_type_orientation";
+ case mir_event_type_close_surface:
+ return "mir_event_type_close_surface";
+ case mir_event_type_input:
+ return "mir_event_type_input";
+ default:
+ DLOG("Invalid event type %d", t);
+ return "invalid";
+ }
+}
+#endif // LOG_EVENTS != 0
+
+void QMirClientInput::customEvent(QEvent* event)
+{
+ DASSERT(QThread::currentThread() == thread());
+ QMirClientEvent* ubuntuEvent = static_cast<QMirClientEvent*>(event);
+ const MirEvent *nativeEvent = ubuntuEvent->nativeEvent;
+
+ if ((ubuntuEvent->window == nullptr) || (ubuntuEvent->window->window() == nullptr)) {
+ qWarning() << "Attempted to deliver an event to a non-existent window, ignoring.";
+ return;
+ }
+
+ // Event filtering.
+ long result;
+ if (QWindowSystemInterface::handleNativeEvent(
+ ubuntuEvent->window->window(), mEventFilterType,
+ const_cast<void *>(static_cast<const void *>(nativeEvent)), &result) == true) {
+ DLOG("event filtered out by native interface");
+ return;
+ }
+
+ #if (LOG_EVENTS != 0)
+ LOG("QMirClientInput::customEvent(type=%s)", nativeEventTypeToStr(mir_event_get_type(nativeEvent)));
+ #endif
+
+ // Event dispatching.
+ switch (mir_event_get_type(nativeEvent))
+ {
+ case mir_event_type_input:
+ dispatchInputEvent(ubuntuEvent->window->window(), mir_event_get_input_event(nativeEvent));
+ break;
+ case mir_event_type_resize:
+ {
+ Q_ASSERT(ubuntuEvent->window->screen() == mIntegration->screen());
+
+ auto resizeEvent = mir_event_get_resize_event(nativeEvent);
+
+ mIntegration->screen()->handleWindowSurfaceResize(
+ mir_resize_event_get_width(resizeEvent),
+ mir_resize_event_get_height(resizeEvent));
+
+ ubuntuEvent->window->handleSurfaceResize(mir_resize_event_get_width(resizeEvent),
+ mir_resize_event_get_height(resizeEvent));
+ break;
+ }
+ case mir_event_type_surface:
+ {
+ auto surfaceEvent = mir_event_get_surface_event(nativeEvent);
+ if (mir_surface_event_get_attribute(surfaceEvent) == mir_surface_attrib_focus) {
+ ubuntuEvent->window->handleSurfaceFocusChange(mir_surface_event_get_attribute_value(surfaceEvent) ==
+ mir_surface_focused);
+ }
+ break;
+ }
+ case mir_event_type_orientation:
+ dispatchOrientationEvent(ubuntuEvent->window->window(), mir_event_get_orientation_event(nativeEvent));
+ break;
+ case mir_event_type_close_surface:
+ QWindowSystemInterface::handleCloseEvent(ubuntuEvent->window->window());
+ break;
+ default:
+ DLOG("unhandled event type: %d", static_cast<int>(mir_event_get_type(nativeEvent)));
+ }
+}
+
+void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent *event)
+{
+ QWindow *window = platformWindow->window();
+
+ QCoreApplication::postEvent(this, new QMirClientEvent(
+ platformWindow, event, mEventType));
+
+ if ((window->flags().testFlag(Qt::WindowTransparentForInput)) && window->parent()) {
+ QCoreApplication::postEvent(this, new QMirClientEvent(
+ static_cast<QMirClientWindow*>(platformWindow->QPlatformWindow::parent()),
+ event, mEventType));
+ }
+}
+
+void QMirClientInput::dispatchInputEvent(QWindow *window, const MirInputEvent *ev)
+{
+ switch (mir_input_event_get_type(ev))
+ {
+ case mir_input_event_type_key:
+ dispatchKeyEvent(window, ev);
+ break;
+ case mir_input_event_type_touch:
+ dispatchTouchEvent(window, ev);
+ break;
+ case mir_input_event_type_pointer:
+ dispatchPointerEvent(window, ev);
+ break;
+ default:
+ break;
+ }
+}
+
+void QMirClientInput::dispatchTouchEvent(QWindow *window, const MirInputEvent *ev)
+{
+ const MirTouchEvent *tev = mir_input_event_get_touch_event(ev);
+
+ // FIXME(loicm) Max pressure is device specific. That one is for the Samsung Galaxy Nexus. That
+ // needs to be fixed as soon as the compat input lib adds query support.
+ const float kMaxPressure = 1.28;
+ const QRect kWindowGeometry = window->geometry();
+ QList<QWindowSystemInterface::TouchPoint> touchPoints;
+
+
+ // TODO: Is it worth setting the Qt::TouchPointStationary ones? Currently they are left
+ // as Qt::TouchPointMoved
+ const unsigned int kPointerCount = mir_touch_event_point_count(tev);
+ for (unsigned int i = 0; i < kPointerCount; ++i) {
+ QWindowSystemInterface::TouchPoint touchPoint;
+
+ const float kX = mir_touch_event_axis_value(tev, i, mir_touch_axis_x) + kWindowGeometry.x();
+ const float kY = mir_touch_event_axis_value(tev, i, mir_touch_axis_y) + kWindowGeometry.y(); // see bug lp:1346633 workaround comments elsewhere
+ const float kW = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_major);
+ const float kH = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_minor);
+ const float kP = mir_touch_event_axis_value(tev, i, mir_touch_axis_pressure);
+ touchPoint.id = mir_touch_event_id(tev, i);
+ touchPoint.normalPosition = QPointF(kX / kWindowGeometry.width(), kY / kWindowGeometry.height());
+ touchPoint.area = QRectF(kX - (kW / 2.0), kY - (kH / 2.0), kW, kH);
+ touchPoint.pressure = kP / kMaxPressure;
+
+ MirTouchAction touch_action = mir_touch_event_action(tev, i);
+ switch (touch_action)
+ {
+ case mir_touch_action_down:
+ touchPoint.state = Qt::TouchPointPressed;
+ break;
+ case mir_touch_action_up:
+ touchPoint.state = Qt::TouchPointReleased;
+ break;
+ case mir_touch_action_change:
+ default:
+ touchPoint.state = Qt::TouchPointMoved;
+ }
+
+ touchPoints.append(touchPoint);
+ }
+
+ ulong timestamp = mir_input_event_get_event_time(ev) / 1000000;
+ QWindowSystemInterface::handleTouchEvent(window, timestamp,
+ mTouchDevice, touchPoints);
+}
+
+static uint32_t translateKeysym(uint32_t sym, char *string, size_t size)
+{
+ Q_UNUSED(size);
+ string[0] = '\0';
+
+ if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F35)
+ return Qt::Key_F1 + (int(sym) - XKB_KEY_F1);
+
+ for (int i = 0; KeyTable[i]; i += 2) {
+ if (sym == KeyTable[i])
+ return KeyTable[i + 1];
+ }
+
+ string[0] = sym;
+ string[1] = '\0';
+ return toupper(sym);
+}
+
+namespace
+{
+Qt::KeyboardModifiers qt_modifiers_from_mir(MirInputEventModifiers modifiers)
+{
+ Qt::KeyboardModifiers q_modifiers = Qt::NoModifier;
+ if (modifiers & mir_input_event_modifier_shift) {
+ q_modifiers |= Qt::ShiftModifier;
+ }
+ if (modifiers & mir_input_event_modifier_ctrl) {
+ q_modifiers |= Qt::ControlModifier;
+ }
+ if (modifiers & mir_input_event_modifier_alt) {
+ q_modifiers |= Qt::AltModifier;
+ }
+ if (modifiers & mir_input_event_modifier_meta) {
+ q_modifiers |= Qt::MetaModifier;
+ }
+ return q_modifiers;
+}
+}
+
+void QMirClientInput::dispatchKeyEvent(QWindow *window, const MirInputEvent *event)
+{
+ const MirKeyboardEvent *key_event = mir_input_event_get_keyboard_event(event);
+
+ ulong timestamp = mir_input_event_get_event_time(event) / 1000000;
+ xkb_keysym_t xk_sym = mir_keyboard_event_key_code(key_event);
+
+ // Key modifier and unicode index mapping.
+ auto modifiers = qt_modifiers_from_mir(mir_keyboard_event_modifiers(key_event));
+
+ MirKeyboardAction action = mir_keyboard_event_action(key_event);
+ QEvent::Type keyType = action == mir_keyboard_action_up
+ ? QEvent::KeyRelease : QEvent::KeyPress;
+
+ char s[2];
+ int sym = translateKeysym(xk_sym, s, sizeof(s));
+ QString text = QString::fromLatin1(s);
+
+ bool is_auto_rep = action == mir_keyboard_action_repeat;
+
+ QPlatformInputContext *context = QGuiApplicationPrivate::platformIntegration()->inputContext();
+ if (context) {
+ QKeyEvent qKeyEvent(keyType, sym, modifiers, text, is_auto_rep);
+ qKeyEvent.setTimestamp(timestamp);
+ if (context->filterEvent(&qKeyEvent)) {
+ DLOG("key event filtered out by input context");
+ return;
+ }
+ }
+
+ QWindowSystemInterface::handleKeyEvent(window, timestamp, keyType, sym, modifiers, text, is_auto_rep);
+}
+
+namespace
+{
+Qt::MouseButtons extract_buttons(const MirPointerEvent *pev)
+{
+ Qt::MouseButtons buttons = Qt::NoButton;
+ if (mir_pointer_event_button_state(pev, mir_pointer_button_primary))
+ buttons |= Qt::LeftButton;
+ if (mir_pointer_event_button_state(pev, mir_pointer_button_secondary))
+ buttons |= Qt::RightButton;
+ if (mir_pointer_event_button_state(pev, mir_pointer_button_tertiary))
+ buttons |= Qt::MidButton;
+
+ // TODO: Should mir back and forward buttons exist?
+ // should they be Qt::X button 1 and 2?
+ return buttons;
+}
+}
+
+void QMirClientInput::dispatchPointerEvent(QWindow *window, const MirInputEvent *ev)
+{
+ auto timestamp = mir_input_event_get_event_time(ev) / 1000000;
+
+ auto pev = mir_input_event_get_pointer_event(ev);
+ auto modifiers = qt_modifiers_from_mir(mir_pointer_event_modifiers(pev));
+ auto buttons = extract_buttons(pev);
+
+ auto local_point = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
+ mir_pointer_event_axis_value(pev, mir_pointer_axis_y));
+
+ QWindowSystemInterface::handleMouseEvent(window, timestamp, local_point, local_point /* Should we omit global point instead? */,
+ buttons, modifiers);
+}
+
+#if (LOG_EVENTS != 0)
+static const char* nativeOrientationDirectionToStr(MirOrientation orientation)
+{
+ switch (orientation) {
+ case mir_orientation_normal:
+ return "Normal";
+ break;
+ case mir_orientation_left:
+ return "Left";
+ break;
+ case mir_orientation_inverted:
+ return "Inverted";
+ break;
+ case mir_orientation_right:
+ return "Right";
+ break;
+ default:
+ return "INVALID!";
+ }
+}
+#endif
+
+void QMirClientInput::dispatchOrientationEvent(QWindow *window, const MirOrientationEvent *event)
+{
+ MirOrientation mir_orientation = mir_orientation_event_get_direction(event);
+ #if (LOG_EVENTS != 0)
+ // Orientation event logging.
+ LOG("ORIENTATION direction: %s", nativeOrientationDirectionToStr(mir_orientation));
+ #endif
+
+ if (!window->screen()) {
+ DLOG("Window has no associated screen, dropping orientation event");
+ return;
+ }
+
+ OrientationChangeEvent::Orientation orientation;
+ switch (mir_orientation) {
+ case mir_orientation_normal:
+ orientation = OrientationChangeEvent::TopUp;
+ break;
+ case mir_orientation_left:
+ orientation = OrientationChangeEvent::LeftUp;
+ break;
+ case mir_orientation_inverted:
+ orientation = OrientationChangeEvent::TopDown;
+ break;
+ case mir_orientation_right:
+ orientation = OrientationChangeEvent::RightUp;
+ break;
+ default:
+ DLOG("No such orientation %d", mir_orientation);
+ return;
+ }
+
+ // Dispatch orientation event to [Platform]Screen, as that is where Qt reads it. Screen will handle
+ // notifying Qt of the actual orientation change - done to prevent multiple Windows each creating
+ // an identical orientation change event and passing it directly to Qt.
+ // [Platform]Screen can also factor in the native orientation.
+ QCoreApplication::postEvent(static_cast<QMirClientScreen*>(window->screen()->handle()),
+ new OrientationChangeEvent(OrientationChangeEvent::mType, orientation));
+}
+
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.h b/src/plugins/platforms/mirclient/qmirclientinput.h
new file mode 100644
index 0000000000..c987d18c12
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientinput.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2014-2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTINPUT_H
+#define QMIRCLIENTINPUT_H
+
+// Qt
+#include <qpa/qwindowsysteminterface.h>
+
+#include <mir_toolkit/mir_client_library.h>
+
+class QMirClientClientIntegration;
+class QMirClientWindow;
+
+class QMirClientInput : public QObject
+{
+ Q_OBJECT
+
+public:
+ QMirClientInput(QMirClientClientIntegration* integration);
+ virtual ~QMirClientInput();
+
+ // QObject methods.
+ void customEvent(QEvent* event) override;
+
+ void postEvent(QMirClientWindow* window, const MirEvent *event);
+ QMirClientClientIntegration* integration() const { return mIntegration; }
+
+protected:
+ void dispatchKeyEvent(QWindow *window, const MirInputEvent *event);
+ void dispatchPointerEvent(QWindow *window, const MirInputEvent *event);
+ void dispatchTouchEvent(QWindow *window, const MirInputEvent *event);
+ void dispatchInputEvent(QWindow *window, const MirInputEvent *event);
+
+ void dispatchOrientationEvent(QWindow* window, const MirOrientationEvent *event);
+
+private:
+ QMirClientClientIntegration* mIntegration;
+ QTouchDevice* mTouchDevice;
+ const QByteArray mEventFilterType;
+ const QEvent::Type mEventType;
+};
+
+#endif // QMIRCLIENTINPUT_H
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.cpp b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
new file mode 100644
index 0000000000..a234f4eac6
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
@@ -0,0 +1,264 @@
+/****************************************************************************
+**
+** Copyright (C) 2014-2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+// Qt
+#include <QGuiApplication>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformnativeinterface.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
+#include <qpa/qplatforminputcontext.h>
+#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QOpenGLContext>
+
+// Local
+#include "qmirclientbackingstore.h"
+#include "qmirclientclipboard.h"
+#include "qmirclientglcontext.h"
+#include "qmirclientinput.h"
+#include "qmirclientintegration.h"
+#include "qmirclientlogging.h"
+#include "qmirclientnativeinterface.h"
+#include "qmirclientscreen.h"
+#include "qmirclienttheme.h"
+#include "qmirclientwindow.h"
+
+// platform-api
+#include <ubuntu/application/lifecycle_delegate.h>
+#include <ubuntu/application/id.h>
+#include <ubuntu/application/options.h>
+
+static void resumedCallback(const UApplicationOptions *options, void* context)
+{
+ Q_UNUSED(options)
+ Q_UNUSED(context)
+ DASSERT(context != NULL);
+ QCoreApplication::postEvent(QCoreApplication::instance(),
+ new QEvent(QEvent::ApplicationActivate));
+}
+
+static void aboutToStopCallback(UApplicationArchive *archive, void* context)
+{
+ Q_UNUSED(archive)
+ DASSERT(context != NULL);
+ QMirClientClientIntegration* integration = static_cast<QMirClientClientIntegration*>(context);
+ integration->inputContext()->hideInputPanel();
+ QCoreApplication::postEvent(QCoreApplication::instance(),
+ new QEvent(QEvent::ApplicationDeactivate));
+}
+
+QMirClientClientIntegration::QMirClientClientIntegration()
+ : QPlatformIntegration()
+ , mNativeInterface(new QMirClientNativeInterface)
+ , mFontDb(new QGenericUnixFontDatabase)
+ , mServices(new QMirClientPlatformServices)
+ , mClipboard(new QMirClientClipboard)
+ , mScaleFactor(1.0)
+{
+ setupOptions();
+ setupDescription();
+
+ // Create new application instance
+ mInstance = u_application_instance_new_from_description_with_options(mDesc, mOptions);
+
+ if (mInstance == nullptr)
+ qFatal("QMirClientClientIntegration: connection to Mir server failed. Check that a Mir server is\n"
+ "running, and the correct socket is being used and is accessible. The shell may have\n"
+ "rejected the incoming connection, so check its log file");
+
+ // Create default screen.
+ mScreen = new QMirClientScreen(u_application_instance_get_mir_connection(mInstance));
+ screenAdded(mScreen);
+
+ // Initialize input.
+ if (qEnvironmentVariableIsEmpty("QTUBUNTU_NO_INPUT")) {
+ mInput = new QMirClientInput(this);
+ mInputContext = QPlatformInputContextFactory::create();
+ } else {
+ mInput = nullptr;
+ mInputContext = nullptr;
+ }
+
+ // compute the scale factor
+ const int defaultGridUnit = 8;
+ int gridUnit = defaultGridUnit;
+ QByteArray gridUnitString = qgetenv("GRID_UNIT_PX");
+ if (!gridUnitString.isEmpty()) {
+ bool ok;
+ gridUnit = gridUnitString.toInt(&ok);
+ if (!ok) {
+ gridUnit = defaultGridUnit;
+ }
+ }
+ mScaleFactor = static_cast<qreal>(gridUnit) / defaultGridUnit;
+}
+
+QMirClientClientIntegration::~QMirClientClientIntegration()
+{
+ delete mInput;
+ delete mInputContext;
+ delete mScreen;
+ delete mServices;
+}
+
+QPlatformServices *QMirClientClientIntegration::services() const
+{
+ return mServices;
+}
+
+void QMirClientClientIntegration::setupOptions()
+{
+ QStringList args = QCoreApplication::arguments();
+ int argc = args.size() + 1;
+ char **argv = new char*[argc];
+ for (int i = 0; i < argc - 1; i++)
+ argv[i] = qstrdup(args.at(i).toLocal8Bit());
+ argv[argc - 1] = nullptr;
+
+ mOptions = u_application_options_new_from_cmd_line(argc - 1, argv);
+
+ for (int i = 0; i < argc; i++)
+ delete [] argv[i];
+ delete [] argv;
+}
+
+void QMirClientClientIntegration::setupDescription()
+{
+ mDesc = u_application_description_new();
+ UApplicationId* id = u_application_id_new_from_stringn("QtUbuntu", 8);
+ u_application_description_set_application_id(mDesc, id);
+
+ UApplicationLifecycleDelegate* delegate = u_application_lifecycle_delegate_new();
+ u_application_lifecycle_delegate_set_application_resumed_cb(delegate, &resumedCallback);
+ u_application_lifecycle_delegate_set_application_about_to_stop_cb(delegate, &aboutToStopCallback);
+ u_application_lifecycle_delegate_set_context(delegate, this);
+ u_application_description_set_application_lifecycle_delegate(mDesc, delegate);
+}
+
+QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* window) const
+{
+ return const_cast<QMirClientClientIntegration*>(this)->createPlatformWindow(window);
+}
+
+QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* window)
+{
+ QPlatformWindow* platformWindow = new QMirClientWindow(
+ window, mClipboard, static_cast<QMirClientScreen*>(mScreen), mInput, u_application_instance_get_mir_connection(mInstance));
+ platformWindow->requestActivateWindow();
+ return platformWindow;
+}
+
+bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability cap) const
+{
+ switch (cap) {
+ case ThreadedPixmaps:
+ return true;
+ break;
+
+ case OpenGL:
+ return true;
+ break;
+
+ case ThreadedOpenGL:
+ if (qEnvironmentVariableIsEmpty("QTUBUNTU_NO_THREADED_OPENGL")) {
+ return true;
+ } else {
+ DLOG("ubuntumirclient: disabled threaded OpenGL");
+ return false;
+ }
+ break;
+
+ default:
+ return QPlatformIntegration::hasCapability(cap);
+ }
+}
+
+QAbstractEventDispatcher *QMirClientClientIntegration::createEventDispatcher() const
+{
+ return createUnixEventDispatcher();
+}
+
+QPlatformBackingStore* QMirClientClientIntegration::createPlatformBackingStore(QWindow* window) const
+{
+ return new QMirClientBackingStore(window);
+}
+
+QPlatformOpenGLContext* QMirClientClientIntegration::createPlatformOpenGLContext(
+ QOpenGLContext* context) const
+{
+ return const_cast<QMirClientClientIntegration*>(this)->createPlatformOpenGLContext(context);
+}
+
+QPlatformOpenGLContext* QMirClientClientIntegration::createPlatformOpenGLContext(
+ QOpenGLContext* context)
+{
+ return new QMirClientOpenGLContext(static_cast<QMirClientScreen*>(context->screen()->handle()),
+ static_cast<QMirClientOpenGLContext*>(context->shareHandle()));
+}
+
+QStringList QMirClientClientIntegration::themeNames() const
+{
+ return QStringList(QMirClientTheme::name);
+}
+
+QPlatformTheme* QMirClientClientIntegration::createPlatformTheme(const QString& name) const
+{
+ Q_UNUSED(name);
+ return new QMirClientTheme;
+}
+
+QVariant QMirClientClientIntegration::styleHint(StyleHint hint) const
+{
+ switch (hint) {
+ case QPlatformIntegration::StartDragDistance: {
+ // default is 10 pixels (see QPlatformTheme::defaultThemeHint)
+ return 10.0 * mScaleFactor;
+ }
+ case QPlatformIntegration::PasswordMaskDelay: {
+ // return time in milliseconds - 1 second
+ return QVariant(1000);
+ }
+ default:
+ break;
+ }
+ return QPlatformIntegration::styleHint(hint);
+}
+
+QPlatformClipboard* QMirClientClientIntegration::clipboard() const
+{
+ return mClipboard.data();
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.h b/src/plugins/platforms/mirclient/qmirclientintegration.h
new file mode 100644
index 0000000000..2960209691
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientintegration.h
@@ -0,0 +1,99 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTINTEGRATION_H
+#define QMIRCLIENTINTEGRATION_H
+
+#include <qpa/qplatformintegration.h>
+#include <QSharedPointer>
+
+#include "qmirclientplatformservices.h"
+
+// platform-api
+#include <ubuntu/application/description.h>
+#include <ubuntu/application/instance.h>
+
+class QMirClientClipboard;
+class QMirClientInput;
+class QMirClientScreen;
+
+class QMirClientClientIntegration : public QPlatformIntegration {
+public:
+ QMirClientClientIntegration();
+ virtual ~QMirClientClientIntegration();
+
+ // QPlatformIntegration methods.
+ bool hasCapability(QPlatformIntegration::Capability cap) const override;
+ QAbstractEventDispatcher *createEventDispatcher() const override;
+ QPlatformNativeInterface* nativeInterface() const override { return mNativeInterface; }
+ QPlatformBackingStore* createPlatformBackingStore(QWindow* window) const override;
+ QPlatformOpenGLContext* createPlatformOpenGLContext(QOpenGLContext* context) const override;
+ QPlatformFontDatabase* fontDatabase() const override { return mFontDb; }
+ QStringList themeNames() const override;
+ QPlatformTheme* createPlatformTheme(const QString& name) const override;
+ QVariant styleHint(StyleHint hint) const override;
+ QPlatformServices *services() const override;
+ QPlatformWindow* createPlatformWindow(QWindow* window) const override;
+ QPlatformInputContext* inputContext() const override { return mInputContext; }
+ QPlatformClipboard* clipboard() const override;
+
+ QPlatformOpenGLContext* createPlatformOpenGLContext(QOpenGLContext* context);
+ QPlatformWindow* createPlatformWindow(QWindow* window);
+ QMirClientScreen* screen() const { return mScreen; }
+
+private:
+ void setupOptions();
+ void setupDescription();
+
+ QPlatformNativeInterface* mNativeInterface;
+ QPlatformFontDatabase* mFontDb;
+
+ QMirClientPlatformServices* mServices;
+
+ QMirClientScreen* mScreen;
+ QMirClientInput* mInput;
+ QPlatformInputContext* mInputContext;
+ QSharedPointer<QMirClientClipboard> mClipboard;
+ qreal mScaleFactor;
+
+ // Platform API stuff
+ UApplicationOptions* mOptions;
+ UApplicationDescription* mDesc;
+ UApplicationInstance* mInstance;
+};
+
+#endif // QMIRCLIENTINTEGRATION_H
diff --git a/src/plugins/platforms/mirclient/qmirclientlogging.h b/src/plugins/platforms/mirclient/qmirclientlogging.h
new file mode 100644
index 0000000000..80914d28b9
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientlogging.h
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTLOGGING_H
+#define QMIRCLIENTLOGGING_H
+
+// Logging and assertion macros.
+#define LOG(...) qDebug(__VA_ARGS__)
+#define LOG_IF(cond,...) do { if (cond) qDebug(__VA_ARGS__); } while (0)
+#define ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop())
+#define NOT_REACHED() qt_assert("Not reached!",__FILE__,__LINE__)
+
+// Logging and assertion macros are compiled out for release builds.
+#if !defined(QT_NO_DEBUG)
+#define DLOG(...) LOG(__VA_ARGS__)
+#define DLOG_IF(cond,...) LOG_IF((cond), __VA_ARGS__)
+#define DASSERT(cond) ASSERT((cond))
+#define DNOT_REACHED() NOT_REACHED()
+#else
+#define DLOG(...) qt_noop()
+#define DLOG_IF(cond,...) qt_noop()
+#define DASSERT(cond) qt_noop()
+#define DNOT_REACHED() qt_noop()
+#endif
+
+#endif // QMIRCLIENTLOGGING_H
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp b/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
new file mode 100644
index 0000000000..a0bb932df3
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+// Qt
+#include <private/qguiapplication_p.h>
+#include <QtGui/qopenglcontext.h>
+#include <QtGui/qscreen.h>
+#include <QtCore/QMap>
+
+// Local
+#include "qmirclientnativeinterface.h"
+#include "qmirclientscreen.h"
+#include "qmirclientglcontext.h"
+
+class QMirClientResourceMap : public QMap<QByteArray, QMirClientNativeInterface::ResourceType>
+{
+public:
+ QMirClientResourceMap()
+ : QMap<QByteArray, QMirClientNativeInterface::ResourceType>() {
+ insert("egldisplay", QMirClientNativeInterface::EglDisplay);
+ insert("eglcontext", QMirClientNativeInterface::EglContext);
+ insert("nativeorientation", QMirClientNativeInterface::NativeOrientation);
+ insert("display", QMirClientNativeInterface::Display);
+ }
+};
+
+Q_GLOBAL_STATIC(QMirClientResourceMap, ubuntuResourceMap)
+
+QMirClientNativeInterface::QMirClientNativeInterface()
+ : mGenericEventFilterType(QByteArrayLiteral("Event"))
+ , mNativeOrientation(nullptr)
+{
+}
+
+QMirClientNativeInterface::~QMirClientNativeInterface()
+{
+ delete mNativeOrientation;
+ mNativeOrientation = nullptr;
+}
+
+void* QMirClientNativeInterface::nativeResourceForContext(
+ const QByteArray& resourceString, QOpenGLContext* context)
+{
+ if (!context)
+ return nullptr;
+
+ const QByteArray kLowerCaseResource = resourceString.toLower();
+
+ if (!ubuntuResourceMap()->contains(kLowerCaseResource))
+ return nullptr;
+
+ const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
+
+ if (kResourceType == QMirClientNativeInterface::EglContext)
+ return static_cast<QMirClientOpenGLContext*>(context->handle())->eglContext();
+ else
+ return nullptr;
+}
+
+void* QMirClientNativeInterface::nativeResourceForWindow(const QByteArray& resourceString, QWindow* window)
+{
+ const QByteArray kLowerCaseResource = resourceString.toLower();
+ if (!ubuntuResourceMap()->contains(kLowerCaseResource))
+ return NULL;
+ const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
+ if (kResourceType == QMirClientNativeInterface::EglDisplay) {
+ if (window) {
+ return static_cast<QMirClientScreen*>(window->screen()->handle())->eglDisplay();
+ } else {
+ return static_cast<QMirClientScreen*>(
+ QGuiApplication::primaryScreen()->handle())->eglDisplay();
+ }
+ } else if (kResourceType == QMirClientNativeInterface::NativeOrientation) {
+ // Return the device's native screen orientation.
+ if (window) {
+ QMirClientScreen *ubuntuScreen = static_cast<QMirClientScreen*>(window->screen()->handle());
+ mNativeOrientation = new Qt::ScreenOrientation(ubuntuScreen->nativeOrientation());
+ } else {
+ QPlatformScreen *platformScreen = QGuiApplication::primaryScreen()->handle();
+ mNativeOrientation = new Qt::ScreenOrientation(platformScreen->nativeOrientation());
+ }
+ return mNativeOrientation;
+ } else {
+ return NULL;
+ }
+}
+
+void* QMirClientNativeInterface::nativeResourceForScreen(const QByteArray& resourceString, QScreen* screen)
+{
+ const QByteArray kLowerCaseResource = resourceString.toLower();
+ if (!ubuntuResourceMap()->contains(kLowerCaseResource))
+ return NULL;
+ const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
+ if (kResourceType == QMirClientNativeInterface::Display) {
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ return static_cast<QMirClientScreen*>(screen->handle())->eglNativeDisplay();
+ } else
+ return NULL;
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.h b/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
new file mode 100644
index 0000000000..84f03bb915
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTNATIVEINTERFACE_H
+#define QMIRCLIENTNATIVEINTERFACE_H
+
+#include <qpa/qplatformnativeinterface.h>
+
+class QMirClientNativeInterface : public QPlatformNativeInterface {
+public:
+ enum ResourceType { EglDisplay, EglContext, NativeOrientation, Display };
+
+ QMirClientNativeInterface();
+ ~QMirClientNativeInterface();
+
+ // QPlatformNativeInterface methods.
+ void* nativeResourceForContext(const QByteArray& resourceString,
+ QOpenGLContext* context) override;
+ void* nativeResourceForWindow(const QByteArray& resourceString,
+ QWindow* window) override;
+ void* nativeResourceForScreen(const QByteArray& resourceString,
+ QScreen* screen) override;
+
+ // New methods.
+ const QByteArray& genericEventFilterType() const { return mGenericEventFilterType; }
+
+private:
+ const QByteArray mGenericEventFilterType;
+ Qt::ScreenOrientation* mNativeOrientation;
+};
+
+#endif // QMIRCLIENTNATIVEINTERFACE_H
diff --git a/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h b/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
new file mode 100644
index 0000000000..24d7307faa
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
+#define QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
+
+#include <QEvent>
+#include "qmirclientlogging.h"
+
+class OrientationChangeEvent : public QEvent {
+public:
+ enum Orientation {
+ Undefined = 0,
+ TopUp,
+ TopDown,
+ LeftUp,
+ RightUp,
+ FaceUp,
+ FaceDown
+ };
+
+ OrientationChangeEvent(QEvent::Type type, Orientation orientation)
+ : QEvent(type)
+ , mOrientation(orientation)
+ {
+ }
+
+ static const QEvent::Type mType;
+ Orientation mOrientation;
+};
+
+#endif // QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
diff --git a/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp b/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp
new file mode 100644
index 0000000000..d0260c79d3
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientplatformservices.h"
+
+#include <QUrl>
+
+#include <ubuntu/application/url_dispatcher/service.h>
+#include <ubuntu/application/url_dispatcher/session.h>
+
+bool QMirClientPlatformServices::openUrl(const QUrl &url)
+{
+ return callDispatcher(url);
+}
+
+bool QMirClientPlatformServices::openDocument(const QUrl &url)
+{
+ return callDispatcher(url);
+}
+
+bool QMirClientPlatformServices::callDispatcher(const QUrl &url)
+{
+ UAUrlDispatcherSession* session = ua_url_dispatcher_session();
+ if (!session)
+ return false;
+
+ ua_url_dispatcher_session_open(session, url.toEncoded().constData(), NULL, NULL);
+
+ free(session);
+
+ // We are returning true here because the other option
+ // is spawning a nested event loop and wait for the
+ // callback. But there is no guarantee on how fast
+ // the callback is going to be so we prefer to avoid the
+ // nested event loop. Long term plan is improve Qt API
+ // to support an async openUrl
+ return true;
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientplatformservices.h b/src/plugins/platforms/mirclient/qmirclientplatformservices.h
new file mode 100644
index 0000000000..64a0432d06
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientplatformservices.h
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTPLATFORMSERVICES_H
+#define QMIRCLIENTPLATFORMSERVICES_H
+
+#include <qpa/qplatformservices.h>
+#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+
+class QMirClientPlatformServices : public QPlatformServices {
+public:
+ bool openUrl(const QUrl &url) override;
+ bool openDocument(const QUrl &url) override;
+
+private:
+ bool callDispatcher(const QUrl &url);
+};
+
+#endif // QMIRCLIENTPLATFORMSERVICES_H
diff --git a/src/plugins/platforms/mirclient/qmirclientplugin.cpp b/src/plugins/platforms/mirclient/qmirclientplugin.cpp
new file mode 100644
index 0000000000..43d913f8d2
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientplugin.cpp
@@ -0,0 +1,61 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientplugin.h"
+#include "qmirclientintegration.h"
+
+QStringList QMirClientIntegrationPlugin::keys() const
+{
+ QStringList list;
+ list << "mirclient";
+ return list;
+}
+
+QPlatformIntegration* QMirClientIntegrationPlugin::create(const QString &system,
+ const QStringList &)
+{
+ if (system.toLower() == "mirclient") {
+#ifdef PLATFORM_API_TOUCH
+ setenv("UBUNTU_PLATFORM_API_BACKEND", "touch_mirclient", 1);
+#else
+ setenv("UBUNTU_PLATFORM_API_BACKEND", "desktop_mirclient", 1);
+#endif
+ return new QMirClientClientIntegration;
+ } else {
+ return 0;
+ }
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientplugin.h b/src/plugins/platforms/mirclient/qmirclientplugin.h
new file mode 100644
index 0000000000..a6f1a1081a
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientplugin.h
@@ -0,0 +1,53 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTPLUGIN_H
+#define QMIRCLIENTPLUGIN_H
+
+#include <qpa/qplatformintegrationplugin.h>
+
+class QMirClientIntegrationPlugin : public QPlatformIntegrationPlugin
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "mirclient.json")
+
+public:
+ QStringList keys() const;
+ QPlatformIntegration* create(const QString&, const QStringList&);
+};
+
+#endif // QMIRCLIENTPLUGIN_H
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.cpp b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
new file mode 100644
index 0000000000..5c4b1cd0d6
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
@@ -0,0 +1,296 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include <mir_toolkit/mir_client_library.h>
+
+// Qt
+#include <QCoreApplication>
+#include <QtCore/qmath.h>
+#include <QScreen>
+#include <QThread>
+#include <qpa/qwindowsysteminterface.h>
+#include <QtPlatformSupport/private/qeglconvenience_p.h>
+
+// local
+#include "qmirclientscreen.h"
+#include "qmirclientlogging.h"
+#include "qmirclientorientationchangeevent_p.h"
+
+#include "memory"
+
+static const int kSwapInterval = 1;
+
+#if !defined(QT_NO_DEBUG)
+
+static const char *orientationToStr(Qt::ScreenOrientation orientation) {
+ switch (orientation) {
+ case Qt::PrimaryOrientation:
+ return "primary";
+ case Qt::PortraitOrientation:
+ return "portrait";
+ case Qt::LandscapeOrientation:
+ return "landscape";
+ case Qt::InvertedPortraitOrientation:
+ return "inverted portrait";
+ case Qt::InvertedLandscapeOrientation:
+ return "inverted landscape";
+ default:
+ return "INVALID!";
+ }
+}
+
+static void printEglConfig(EGLDisplay display, EGLConfig config) {
+ DASSERT(display != EGL_NO_DISPLAY);
+ DASSERT(config != nullptr);
+ static const struct { const EGLint attrib; const char* name; } kAttribs[] = {
+ { EGL_BUFFER_SIZE, "EGL_BUFFER_SIZE" },
+ { EGL_ALPHA_SIZE, "EGL_ALPHA_SIZE" },
+ { EGL_BLUE_SIZE, "EGL_BLUE_SIZE" },
+ { EGL_GREEN_SIZE, "EGL_GREEN_SIZE" },
+ { EGL_RED_SIZE, "EGL_RED_SIZE" },
+ { EGL_DEPTH_SIZE, "EGL_DEPTH_SIZE" },
+ { EGL_STENCIL_SIZE, "EGL_STENCIL_SIZE" },
+ { EGL_CONFIG_CAVEAT, "EGL_CONFIG_CAVEAT" },
+ { EGL_CONFIG_ID, "EGL_CONFIG_ID" },
+ { EGL_LEVEL, "EGL_LEVEL" },
+ { EGL_MAX_PBUFFER_HEIGHT, "EGL_MAX_PBUFFER_HEIGHT" },
+ { EGL_MAX_PBUFFER_PIXELS, "EGL_MAX_PBUFFER_PIXELS" },
+ { EGL_MAX_PBUFFER_WIDTH, "EGL_MAX_PBUFFER_WIDTH" },
+ { EGL_NATIVE_RENDERABLE, "EGL_NATIVE_RENDERABLE" },
+ { EGL_NATIVE_VISUAL_ID, "EGL_NATIVE_VISUAL_ID" },
+ { EGL_NATIVE_VISUAL_TYPE, "EGL_NATIVE_VISUAL_TYPE" },
+ { EGL_SAMPLES, "EGL_SAMPLES" },
+ { EGL_SAMPLE_BUFFERS, "EGL_SAMPLE_BUFFERS" },
+ { EGL_SURFACE_TYPE, "EGL_SURFACE_TYPE" },
+ { EGL_TRANSPARENT_TYPE, "EGL_TRANSPARENT_TYPE" },
+ { EGL_TRANSPARENT_BLUE_VALUE, "EGL_TRANSPARENT_BLUE_VALUE" },
+ { EGL_TRANSPARENT_GREEN_VALUE, "EGL_TRANSPARENT_GREEN_VALUE" },
+ { EGL_TRANSPARENT_RED_VALUE, "EGL_TRANSPARENT_RED_VALUE" },
+ { EGL_BIND_TO_TEXTURE_RGB, "EGL_BIND_TO_TEXTURE_RGB" },
+ { EGL_BIND_TO_TEXTURE_RGBA, "EGL_BIND_TO_TEXTURE_RGBA" },
+ { EGL_MIN_SWAP_INTERVAL, "EGL_MIN_SWAP_INTERVAL" },
+ { EGL_MAX_SWAP_INTERVAL, "EGL_MAX_SWAP_INTERVAL" },
+ { -1, NULL }
+ };
+ const char* string = eglQueryString(display, EGL_VENDOR);
+ LOG("EGL vendor: %s", string);
+ string = eglQueryString(display, EGL_VERSION);
+ LOG("EGL version: %s", string);
+ string = eglQueryString(display, EGL_EXTENSIONS);
+ LOG("EGL extensions: %s", string);
+ LOG("EGL configuration attibutes:");
+ for (int index = 0; kAttribs[index].attrib != -1; index++) {
+ EGLint value;
+ if (eglGetConfigAttrib(display, config, kAttribs[index].attrib, &value))
+ LOG(" %s: %d", kAttribs[index].name, static_cast<int>(value));
+ }
+}
+#endif
+
+
+const QEvent::Type OrientationChangeEvent::mType =
+ static_cast<QEvent::Type>(QEvent::registerEventType());
+
+static const MirDisplayOutput *find_active_output(
+ const MirDisplayConfiguration *conf)
+{
+ const MirDisplayOutput *output = NULL;
+ for (uint32_t d = 0; d < conf->num_outputs; d++)
+ {
+ const MirDisplayOutput *out = conf->outputs + d;
+
+ if (out->used &&
+ out->connected &&
+ out->num_modes &&
+ out->current_mode < out->num_modes)
+ {
+ output = out;
+ break;
+ }
+ }
+
+ return output;
+}
+
+QMirClientScreen::QMirClientScreen(MirConnection *connection)
+ : mFormat(QImage::Format_RGB32)
+ , mDepth(32)
+ , mSurfaceFormat()
+ , mEglDisplay(EGL_NO_DISPLAY)
+ , mEglConfig(nullptr)
+{
+ // Initialize EGL.
+ ASSERT(eglBindAPI(EGL_OPENGL_ES_API) == EGL_TRUE);
+
+ mEglNativeDisplay = mir_connection_get_egl_native_display(connection);
+ ASSERT((mEglDisplay = eglGetDisplay(mEglNativeDisplay)) != EGL_NO_DISPLAY);
+ ASSERT(eglInitialize(mEglDisplay, nullptr, nullptr) == EGL_TRUE);
+
+ // Configure EGL buffers format.
+ mSurfaceFormat.setRedBufferSize(8);
+ mSurfaceFormat.setGreenBufferSize(8);
+ mSurfaceFormat.setBlueBufferSize(8);
+ mSurfaceFormat.setAlphaBufferSize(8);
+ mSurfaceFormat.setDepthBufferSize(24);
+ mSurfaceFormat.setStencilBufferSize(8);
+ if (!qEnvironmentVariableIsEmpty("QTUBUNTU_MULTISAMPLE")) {
+ mSurfaceFormat.setSamples(4);
+ DLOG("ubuntumirclient: setting MSAA to 4 samples");
+ }
+#ifdef QTUBUNTU_USE_OPENGL
+ mSurfaceFormat.setRenderableType(QSurfaceFormat::OpenGL);
+#else
+ mSurfaceFormat.setRenderableType(QSurfaceFormat::OpenGLES);
+#endif
+ mEglConfig = q_configFromGLFormat(mEglDisplay, mSurfaceFormat, true);
+
+ #if !defined(QT_NO_DEBUG)
+ printEglConfig(mEglDisplay, mEglConfig);
+ #endif
+
+ // Set vblank swap interval.
+ int swapInterval = kSwapInterval;
+ QByteArray swapIntervalString = qgetenv("QTUBUNTU_SWAPINTERVAL");
+ if (!swapIntervalString.isEmpty()) {
+ bool ok;
+ swapInterval = swapIntervalString.toInt(&ok);
+ if (!ok)
+ swapInterval = kSwapInterval;
+ }
+ DLOG("ubuntumirclient: setting swap interval to %d", swapInterval);
+ eglSwapInterval(mEglDisplay, swapInterval);
+
+ // Get screen resolution.
+ auto configDeleter = [](MirDisplayConfiguration *config) { mir_display_config_destroy(config); };
+ using configUp = std::unique_ptr<MirDisplayConfiguration, decltype(configDeleter)>;
+ configUp displayConfig(mir_connection_create_display_config(connection), configDeleter);
+ ASSERT(displayConfig != nullptr);
+
+ auto const displayOutput = find_active_output(displayConfig.get());
+ ASSERT(displayOutput != nullptr);
+
+ const MirDisplayMode *mode = &displayOutput->modes[displayOutput->current_mode];
+ const int kScreenWidth = mode->horizontal_resolution;
+ const int kScreenHeight = mode->vertical_resolution;
+ DASSERT(kScreenWidth > 0 && kScreenHeight > 0);
+
+ DLOG("ubuntumirclient: screen resolution: %dx%d", kScreenWidth, kScreenHeight);
+
+ mGeometry = QRect(0, 0, kScreenWidth, kScreenHeight);
+
+ DLOG("QQMirClientScreen::QQMirClientScreen (this=%p)", this);
+
+ // Set the default orientation based on the initial screen dimmensions.
+ mNativeOrientation = (mGeometry.width() >= mGeometry.height()) ? Qt::LandscapeOrientation : Qt::PortraitOrientation;
+
+ // If it's a landscape device (i.e. some tablets), start in landscape, otherwise portrait
+ mCurrentOrientation = (mNativeOrientation == Qt::LandscapeOrientation) ? Qt::LandscapeOrientation : Qt::PortraitOrientation;
+}
+
+QMirClientScreen::~QMirClientScreen()
+{
+ eglTerminate(mEglDisplay);
+}
+
+void QMirClientScreen::customEvent(QEvent* event) {
+ DASSERT(QThread::currentThread() == thread());
+
+ OrientationChangeEvent* oReadingEvent = static_cast<OrientationChangeEvent*>(event);
+ switch (oReadingEvent->mOrientation) {
+ case OrientationChangeEvent::LeftUp: {
+ mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
+ Qt::InvertedPortraitOrientation : Qt::LandscapeOrientation;
+ break;
+ }
+ case OrientationChangeEvent::TopUp: {
+ mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
+ Qt::LandscapeOrientation : Qt::PortraitOrientation;
+ break;
+ }
+ case OrientationChangeEvent::RightUp: {
+ mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
+ Qt::PortraitOrientation : Qt::InvertedLandscapeOrientation;
+ break;
+ }
+ case OrientationChangeEvent::TopDown: {
+ mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
+ Qt::InvertedLandscapeOrientation : Qt::InvertedPortraitOrientation;
+ break;
+ }
+ default: {
+ DLOG("QMirClientScreen::customEvent - Unknown orientation.");
+ return;
+ }
+ }
+
+ // Raise the event signal so that client apps know the orientation changed
+ DLOG("QMirClientScreen::customEvent - handling orientation change to %s", orientationToStr(mCurrentOrientation));
+ QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation);
+}
+
+void QMirClientScreen::handleWindowSurfaceResize(int windowWidth, int windowHeight)
+{
+ if ((windowWidth > windowHeight && mGeometry.width() < mGeometry.height())
+ || (windowWidth < windowHeight && mGeometry.width() > mGeometry.height())) {
+
+ // The window aspect ratio differ's from the screen one. This means that
+ // unity8 has rotated the window in its scene.
+ // As there's no way to express window rotation in Qt's API, we have
+ // Flip QScreen's dimensions so that orientation properties match
+ // (primaryOrientation particularly).
+ // FIXME: This assumes a phone scenario. Won't work, or make sense,
+ // on the desktop
+
+ QRect currGeometry = mGeometry;
+ mGeometry.setWidth(currGeometry.height());
+ mGeometry.setHeight(currGeometry.width());
+
+ DLOG("QMirClientScreen::handleWindowSurfaceResize - new screen geometry (w=%d, h=%d)",
+ mGeometry.width(), mGeometry.height());
+ QWindowSystemInterface::handleScreenGeometryChange(screen(),
+ mGeometry /* newGeometry */,
+ mGeometry /* newAvailableGeometry */);
+
+ if (mGeometry.width() < mGeometry.height()) {
+ mCurrentOrientation = Qt::PortraitOrientation;
+ } else {
+ mCurrentOrientation = Qt::LandscapeOrientation;
+ }
+ DLOG("QMirClientScreen::handleWindowSurfaceResize - new orientation %s",orientationToStr(mCurrentOrientation));
+ QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation);
+ }
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.h b/src/plugins/platforms/mirclient/qmirclientscreen.h
new file mode 100644
index 0000000000..5d9325354f
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientscreen.h
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTSCREEN_H
+#define QMIRCLIENTSCREEN_H
+
+#include <qpa/qplatformscreen.h>
+#include <QSurfaceFormat>
+#include <EGL/egl.h>
+
+struct MirConnection;
+
+class QMirClientScreen : public QObject, public QPlatformScreen
+{
+ Q_OBJECT
+public:
+ QMirClientScreen(MirConnection *connection);
+ virtual ~QMirClientScreen();
+
+ // QPlatformScreen methods.
+ QImage::Format format() const override { return mFormat; }
+ int depth() const override { return mDepth; }
+ QRect geometry() const override { return mGeometry; }
+ QRect availableGeometry() const override { return mGeometry; }
+ Qt::ScreenOrientation nativeOrientation() const override { return mNativeOrientation; }
+ Qt::ScreenOrientation orientation() const override { return mNativeOrientation; }
+
+ // New methods.
+ QSurfaceFormat surfaceFormat() const { return mSurfaceFormat; }
+ EGLDisplay eglDisplay() const { return mEglDisplay; }
+ EGLConfig eglConfig() const { return mEglConfig; }
+ EGLNativeDisplayType eglNativeDisplay() const { return mEglNativeDisplay; }
+ void handleWindowSurfaceResize(int width, int height);
+
+ // QObject methods.
+ void customEvent(QEvent* event);
+
+private:
+ QRect mGeometry;
+ Qt::ScreenOrientation mNativeOrientation;
+ Qt::ScreenOrientation mCurrentOrientation;
+ QImage::Format mFormat;
+ int mDepth;
+ QSurfaceFormat mSurfaceFormat;
+ EGLDisplay mEglDisplay;
+ EGLConfig mEglConfig;
+ EGLNativeDisplayType mEglNativeDisplay;
+};
+
+#endif // QMIRCLIENTSCREEN_H
diff --git a/src/plugins/platforms/mirclient/qmirclienttheme.cpp b/src/plugins/platforms/mirclient/qmirclienttheme.cpp
new file mode 100644
index 0000000000..c15da23945
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclienttheme.cpp
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclienttheme.h"
+
+#include <QtCore/QVariant>
+
+const char *QMirClientTheme::name = "ubuntu";
+
+QMirClientTheme::QMirClientTheme()
+{
+}
+
+QMirClientTheme::~QMirClientTheme()
+{
+}
+
+QVariant QMirClientTheme::themeHint(ThemeHint hint) const
+{
+ if (hint == QPlatformTheme::SystemIconThemeName) {
+ QByteArray iconTheme = qgetenv("QTUBUNTU_ICON_THEME");
+ if (iconTheme.isEmpty()) {
+ return QVariant(QStringLiteral("ubuntu-mobile"));
+ } else {
+ return QVariant(QString(iconTheme));
+ }
+ } else {
+ return QGenericUnixTheme::themeHint(hint);
+ }
+}
diff --git a/src/plugins/platforms/mirclient/qmirclienttheme.h b/src/plugins/platforms/mirclient/qmirclienttheme.h
new file mode 100644
index 0000000000..8f330395a0
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclienttheme.h
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTTHEME_H
+#define QMIRCLIENTTHEME_H
+
+#include <QtPlatformSupport/private/qgenericunixthemes_p.h>
+
+class QMirClientTheme : public QGenericUnixTheme
+{
+public:
+ static const char* name;
+ QMirClientTheme();
+ virtual ~QMirClientTheme();
+
+ // From QPlatformTheme
+ QVariant themeHint(ThemeHint hint) const override;
+};
+
+#endif // QMIRCLIENTTHEME_H
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.cpp b/src/plugins/platforms/mirclient/qmirclientwindow.cpp
new file mode 100644
index 0000000000..f3fd1e756d
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientwindow.cpp
@@ -0,0 +1,452 @@
+/****************************************************************************
+**
+** Copyright (C) 2014-2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+// Local
+#include "qmirclientclipboard.h"
+#include "qmirclientinput.h"
+#include "qmirclientwindow.h"
+#include "qmirclientscreen.h"
+#include "qmirclientlogging.h"
+
+// Qt
+#include <qpa/qwindowsysteminterface.h>
+#include <qpa/qwindowsysteminterface.h>
+#include <QMutex>
+#include <QMutexLocker>
+#include <QSize>
+#include <QtMath>
+
+// Platform API
+#include <ubuntu/application/instance.h>
+
+#include <EGL/egl.h>
+
+#define IS_OPAQUE_FLAG 1
+
+namespace
+{
+MirSurfaceState qtWindowStateToMirSurfaceState(Qt::WindowState state)
+{
+ switch (state) {
+ case Qt::WindowNoState:
+ return mir_surface_state_restored;
+
+ case Qt::WindowFullScreen:
+ return mir_surface_state_fullscreen;
+
+ case Qt::WindowMaximized:
+ return mir_surface_state_maximized;
+
+ case Qt::WindowMinimized:
+ return mir_surface_state_minimized;
+
+ default:
+ LOG("Unexpected Qt::WindowState: %d", state);
+ return mir_surface_state_restored;
+ }
+}
+
+#if !defined(QT_NO_DEBUG)
+const char *qtWindowStateToStr(Qt::WindowState state)
+{
+ switch (state) {
+ case Qt::WindowNoState:
+ return "NoState";
+
+ case Qt::WindowFullScreen:
+ return "FullScreen";
+
+ case Qt::WindowMaximized:
+ return "Maximized";
+
+ case Qt::WindowMinimized:
+ return "Minimized";
+
+ default:
+ return "!?";
+ }
+}
+#endif
+
+} // anonymous namespace
+
+class QMirClientWindowPrivate
+{
+public:
+ void createEGLSurface(EGLNativeWindowType nativeWindow);
+ void destroyEGLSurface();
+ int panelHeight();
+
+ QMirClientScreen* screen;
+ EGLSurface eglSurface;
+ WId id;
+ QMirClientInput* input;
+ Qt::WindowState state;
+ MirConnection *connection;
+ MirSurface* surface;
+ QSize bufferSize;
+ QMutex mutex;
+ QSharedPointer<QMirClientClipboard> clipboard;
+};
+
+static void eventCallback(MirSurface* surface, const MirEvent *event, void* context)
+{
+ (void) surface;
+ DASSERT(context != NULL);
+ QMirClientWindow* platformWindow = static_cast<QMirClientWindow*>(context);
+ platformWindow->priv()->input->postEvent(platformWindow, event);
+}
+
+static void surfaceCreateCallback(MirSurface* surface, void* context)
+{
+ DASSERT(context != NULL);
+ QMirClientWindow* platformWindow = static_cast<QMirClientWindow*>(context);
+ platformWindow->priv()->surface = surface;
+
+ mir_surface_set_event_handler(surface, eventCallback, context);
+}
+
+QMirClientWindow::QMirClientWindow(QWindow* w, QSharedPointer<QMirClientClipboard> clipboard, QMirClientScreen* screen,
+ QMirClientInput* input, MirConnection* connection)
+ : QObject(nullptr), QPlatformWindow(w)
+{
+ DASSERT(screen != NULL);
+
+ d = new QMirClientWindowPrivate;
+ d->screen = screen;
+ d->eglSurface = EGL_NO_SURFACE;
+ d->input = input;
+ d->state = window()->windowState();
+ d->connection = connection;
+ d->clipboard = clipboard;
+
+ static int id = 1;
+ d->id = id++;
+
+ // Use client geometry if set explicitly, use available screen geometry otherwise.
+ QPlatformWindow::setGeometry(window()->geometry() != screen->geometry() ?
+ window()->geometry() : screen->availableGeometry());
+ createWindow();
+ DLOG("QMirClientWindow::QMirClientWindow (this=%p, w=%p, screen=%p, input=%p)", this, w, screen, input);
+}
+
+QMirClientWindow::~QMirClientWindow()
+{
+ DLOG("QMirClientWindow::~QMirClientWindow");
+ d->destroyEGLSurface();
+
+ mir_surface_release_sync(d->surface);
+
+ delete d;
+}
+
+void QMirClientWindowPrivate::createEGLSurface(EGLNativeWindowType nativeWindow)
+{
+ DLOG("QMirClientWindowPrivate::createEGLSurface (this=%p, nativeWindow=%p)",
+ this, reinterpret_cast<void*>(nativeWindow));
+
+ eglSurface = eglCreateWindowSurface(screen->eglDisplay(), screen->eglConfig(),
+ nativeWindow, nullptr);
+
+ DASSERT(eglSurface != EGL_NO_SURFACE);
+}
+
+void QMirClientWindowPrivate::destroyEGLSurface()
+{
+ DLOG("QMirClientWindowPrivate::destroyEGLSurface (this=%p)", this);
+ if (eglSurface != EGL_NO_SURFACE) {
+ eglDestroySurface(screen->eglDisplay(), eglSurface);
+ eglSurface = EGL_NO_SURFACE;
+ }
+}
+
+// FIXME - in order to work around https://bugs.launchpad.net/mir/+bug/1346633
+// we need to guess the panel height (3GU + 2DP)
+int QMirClientWindowPrivate::panelHeight()
+{
+ const int defaultGridUnit = 8;
+ int gridUnit = defaultGridUnit;
+ QByteArray gridUnitString = qgetenv("GRID_UNIT_PX");
+ if (!gridUnitString.isEmpty()) {
+ bool ok;
+ gridUnit = gridUnitString.toInt(&ok);
+ if (!ok) {
+ gridUnit = defaultGridUnit;
+ }
+ }
+ qreal densityPixelRatio = static_cast<qreal>(gridUnit) / defaultGridUnit;
+ return gridUnit * 3 + qFloor(densityPixelRatio) * 2;
+}
+
+namespace
+{
+static MirPixelFormat
+mir_choose_default_pixel_format(MirConnection *connection)
+{
+ MirPixelFormat format[mir_pixel_formats];
+ unsigned int nformats;
+
+ mir_connection_get_available_surface_formats(connection,
+ format, mir_pixel_formats, &nformats);
+
+ return format[0];
+}
+}
+
+void QMirClientWindow::createWindow()
+{
+ DLOG("QMirClientWindow::createWindow (this=%p)", this);
+
+ // FIXME: remove this remnant of an old platform-api enum - needs ubuntu-keyboard update
+ const int SCREEN_KEYBOARD_ROLE = 7;
+ // Get surface role and flags.
+ QVariant roleVariant = window()->property("role");
+ int role = roleVariant.isValid() ? roleVariant.toUInt() : 1; // 1 is the default role for apps.
+ QVariant opaqueVariant = window()->property("opaque");
+ uint flags = opaqueVariant.isValid() ?
+ opaqueVariant.toUInt() ? static_cast<uint>(IS_OPAQUE_FLAG) : 0 : 0;
+
+ // FIXME(loicm) Opaque flag is forced for now for non-system sessions (applications) for
+ // performance reasons.
+ flags |= static_cast<uint>(IS_OPAQUE_FLAG);
+
+ const QByteArray title = (!window()->title().isNull()) ? window()->title().toUtf8() : "Window 1"; // legacy title
+ const int panelHeight = d->panelHeight();
+
+#if !defined(QT_NO_DEBUG)
+ LOG("panelHeight: '%d'", panelHeight);
+ LOG("role: '%d'", role);
+ LOG("flags: '%s'", (flags & static_cast<uint>(1)) ? "Opaque" : "NotOpaque");
+ LOG("title: '%s'", title.constData());
+#endif
+
+ // Get surface geometry.
+ QRect geometry;
+ if (d->state == Qt::WindowFullScreen) {
+ printf("QMirClientWindow - fullscreen geometry\n");
+ geometry = screen()->geometry();
+ } else if (d->state == Qt::WindowMaximized) {
+ printf("QMirClientWindow - maximized geometry\n");
+ geometry = screen()->availableGeometry();
+ /*
+ * FIXME: Autopilot relies on being able to convert coordinates relative of the window
+ * into absolute screen coordinates. Mir does not allow this, see bug lp:1346633
+ * Until there's a correct way to perform this transformation agreed, this horrible hack
+ * guesses the transformation heuristically.
+ *
+ * Assumption: this method only used on phone devices!
+ */
+ geometry.setY(panelHeight);
+ } else {
+ printf("QMirClientWindow - regular geometry\n");
+ geometry = this->geometry();
+ geometry.setY(panelHeight);
+ }
+
+ DLOG("[ubuntumirclient QPA] creating surface at (%d, %d) with size (%d, %d) with title '%s'\n",
+ geometry.x(), geometry.y(), geometry.width(), geometry.height(), title.data());
+
+ MirSurfaceSpec *spec;
+ if (role == SCREEN_KEYBOARD_ROLE)
+ {
+ spec = mir_connection_create_spec_for_input_method(d->connection, geometry.width(),
+ geometry.height(), mir_choose_default_pixel_format(d->connection));
+ }
+ else
+ {
+ spec = mir_connection_create_spec_for_normal_surface(d->connection, geometry.width(),
+ geometry.height(), mir_choose_default_pixel_format(d->connection));
+ }
+ mir_surface_spec_set_name(spec, title.data());
+
+ // Create platform window
+ mir_wait_for(mir_surface_create(spec, surfaceCreateCallback, this));
+ mir_surface_spec_release(spec);
+
+ DASSERT(d->surface != NULL);
+ d->createEGLSurface((EGLNativeWindowType)mir_buffer_stream_get_egl_native_window(mir_surface_get_buffer_stream(d->surface)));
+
+ if (d->state == Qt::WindowFullScreen) {
+ // TODO: We could set this on creation once surface spec supports it (mps already up)
+ mir_wait_for(mir_surface_set_state(d->surface, mir_surface_state_fullscreen));
+ }
+
+ // Window manager can give us a final size different from what we asked for
+ // so let's check what we ended up getting
+ {
+ MirSurfaceParameters parameters;
+ mir_surface_get_parameters(d->surface, &parameters);
+
+ geometry.setWidth(parameters.width);
+ geometry.setHeight(parameters.height);
+ }
+
+ DLOG("[ubuntumirclient QPA] created surface has size (%d, %d)",
+ geometry.width(), geometry.height());
+
+ // Assume that the buffer size matches the surface size at creation time
+ d->bufferSize = geometry.size();
+
+ // Tell Qt about the geometry.
+ QWindowSystemInterface::handleGeometryChange(window(), geometry);
+ QPlatformWindow::setGeometry(geometry);
+}
+
+void QMirClientWindow::moveResize(const QRect& rect)
+{
+ (void) rect;
+ // TODO: Not yet supported by mir.
+}
+
+void QMirClientWindow::handleSurfaceResize(int width, int height)
+{
+ QMutexLocker(&d->mutex);
+ LOG("QMirClientWindow::handleSurfaceResize(width=%d, height=%d)", width, height);
+
+ // The current buffer size hasn't actually changed. so just render on it and swap
+ // buffers in the hope that the next buffer will match the surface size advertised
+ // in this event.
+ // But since this event is processed by a thread different from the one that swaps
+ // buffers, you can never know if this information is already outdated as there's
+ // no synchronicity whatsoever between the processing of resize events and the
+ // consumption of buffers.
+ if (d->bufferSize.width() != width || d->bufferSize.height() != height) {
+ QWindowSystemInterface::handleExposeEvent(window(), geometry());
+ QWindowSystemInterface::flushWindowSystemEvents();
+ }
+}
+
+void QMirClientWindow::handleSurfaceFocusChange(bool focused)
+{
+ LOG("QMirClientWindow::handleSurfaceFocusChange(focused=%s)", focused ? "true" : "false");
+ QWindow *activatedWindow = focused ? window() : nullptr;
+
+ // System clipboard contents might have changed while this window was unfocused and wihtout
+ // this process getting notified about it because it might have been suspended (due to
+ // application lifecycle policies), thus unable to listen to any changes notified through
+ // D-Bus.
+ // Therefore let's ensure we are up to date with the system clipboard now that we are getting
+ // focused again.
+ if (focused) {
+ d->clipboard->requestDBusClipboardContents();
+ }
+
+ QWindowSystemInterface::handleWindowActivated(activatedWindow, Qt::ActiveWindowFocusReason);
+}
+
+void QMirClientWindow::setWindowState(Qt::WindowState state)
+{
+ QMutexLocker(&d->mutex);
+ DLOG("QMirClientWindow::setWindowState (this=%p, %s)", this, qtWindowStateToStr(state));
+
+ if (state == d->state)
+ return;
+
+ // TODO: Perhaps we should check if the states are applied?
+ mir_wait_for(mir_surface_set_state(d->surface, qtWindowStateToMirSurfaceState(state)));
+ d->state = state;
+}
+
+void QMirClientWindow::setGeometry(const QRect& rect)
+{
+ DLOG("QMirClientWindow::setGeometry (this=%p)", this);
+
+ bool doMoveResize;
+
+ {
+ QMutexLocker(&d->mutex);
+ QPlatformWindow::setGeometry(rect);
+ doMoveResize = d->state != Qt::WindowFullScreen && d->state != Qt::WindowMaximized;
+ }
+
+ if (doMoveResize) {
+ moveResize(rect);
+ }
+}
+
+void QMirClientWindow::setVisible(bool visible)
+{
+ QMutexLocker(&d->mutex);
+ DLOG("QMirClientWindow::setVisible (this=%p, visible=%s)", this, visible ? "true" : "false");
+
+ if (visible) {
+ mir_wait_for(mir_surface_set_state(d->surface, qtWindowStateToMirSurfaceState(d->state)));
+
+ QWindowSystemInterface::handleExposeEvent(window(), QRect());
+ QWindowSystemInterface::flushWindowSystemEvents();
+ } else {
+ // TODO: Use the new mir_surface_state_hidden state instead of mir_surface_state_minimized.
+ // Will have to change qtmir and unity8 for that.
+ mir_wait_for(mir_surface_set_state(d->surface, mir_surface_state_minimized));
+ }
+}
+
+void* QMirClientWindow::eglSurface() const
+{
+ return d->eglSurface;
+}
+
+WId QMirClientWindow::winId() const
+{
+ return d->id;
+}
+
+void QMirClientWindow::onBuffersSwapped_threadSafe(int newBufferWidth, int newBufferHeight)
+{
+ QMutexLocker(&d->mutex);
+
+ bool sizeKnown = newBufferWidth > 0 && newBufferHeight > 0;
+
+ if (sizeKnown && (d->bufferSize.width() != newBufferWidth ||
+ d->bufferSize.height() != newBufferHeight)) {
+
+ DLOG("QMirClientWindow::onBuffersSwapped_threadSafe - buffer size changed from (%d,%d) to (%d,%d)",
+ d->bufferSize.width(), d->bufferSize.height(), newBufferWidth, newBufferHeight);
+
+ d->bufferSize.rwidth() = newBufferWidth;
+ d->bufferSize.rheight() = newBufferHeight;
+
+ QRect newGeometry;
+
+ newGeometry = geometry();
+ newGeometry.setWidth(d->bufferSize.width());
+ newGeometry.setHeight(d->bufferSize.height());
+
+ QPlatformWindow::setGeometry(newGeometry);
+ QWindowSystemInterface::handleGeometryChange(window(), newGeometry, QRect());
+ }
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.h b/src/plugins/platforms/mirclient/qmirclientwindow.h
new file mode 100644
index 0000000000..f342669544
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientwindow.h
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** Copyright (C) 2014-2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later as published by the Free
+** Software Foundation and appearing in the file LICENSE.GPL included in
+** the packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTWINDOW_H
+#define QMIRCLIENTWINDOW_H
+
+#include <qpa/qplatformwindow.h>
+#include <QSharedPointer>
+
+#include <mir_toolkit/mir_client_library.h>
+
+class QMirClientClipboard;
+class QMirClientInput;
+class QMirClientScreen;
+class QMirClientWindowPrivate;
+
+class QMirClientWindow : public QObject, public QPlatformWindow
+{
+ Q_OBJECT
+public:
+ QMirClientWindow(QWindow *w, QSharedPointer<QMirClientClipboard> clipboard, QMirClientScreen *screen,
+ QMirClientInput *input, MirConnection *mir_connection);
+ virtual ~QMirClientWindow();
+
+ // QPlatformWindow methods.
+ WId winId() const override;
+ void setGeometry(const QRect&) override;
+ void setWindowState(Qt::WindowState state) override;
+ void setVisible(bool visible) override;
+
+ // New methods.
+ void* eglSurface() const;
+ void handleSurfaceResize(int width, int height);
+ void handleSurfaceFocusChange(bool focused);
+ void onBuffersSwapped_threadSafe(int newBufferWidth, int newBufferHeight);
+
+ QMirClientWindowPrivate* priv() { return d; }
+
+private:
+ void createWindow();
+ void moveResize(const QRect& rect);
+
+ QMirClientWindowPrivate *d;
+};
+
+#endif // QMIRCLIENTWINDOW_H
diff --git a/src/plugins/platforms/platforms.pro b/src/plugins/platforms/platforms.pro
index 22d443733e..43bb04e318 100644
--- a/src/plugins/platforms/platforms.pro
+++ b/src/plugins/platforms/platforms.pro
@@ -40,3 +40,5 @@ contains(QT_CONFIG, linuxfb): SUBDIRS += linuxfb
haiku {
SUBDIRS += haiku
}
+
+contains(QT_CONFIG, mirclient): SUBDIRS += mirclient
diff --git a/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.cpp b/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.cpp
index e5c853dad8..04e264860e 100644
--- a/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.cpp
+++ b/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.cpp
@@ -124,4 +124,25 @@ void QQnxAbstractVirtualKeyboard::setLocale(const QLocale &locale)
emit localeChanged(locale);
}
+QQnxAbstractVirtualKeyboard::EnterKeyType
+ QQnxAbstractVirtualKeyboard::qtEnterKeyTypeToQnx(Qt::EnterKeyType type)
+{
+ switch (type) {
+ case Qt::EnterKeyDone:
+ return Done;
+ case Qt::EnterKeyGo:
+ return Go;
+ case Qt::EnterKeyNext:
+ return Next;
+ case Qt::EnterKeySearch:
+ return Search;
+ case Qt::EnterKeySend:
+ return Send;
+ case Qt::EnterKeyDefault:
+ case Qt::EnterKeyReturn:
+ case Qt::EnterKeyPrevious: // unsupported
+ return DefaultReturn;
+ }
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.h b/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.h
index 8bf8313000..2fa2ed7291 100644
--- a/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.h
+++ b/src/plugins/platforms/qnx/qqnxabstractvirtualkeyboard.h
@@ -74,6 +74,8 @@ public:
KeyboardMode keyboardMode() const { return m_keyboardMode; }
EnterKeyType enterKeyType() const { return m_enterKeyType; }
+ static EnterKeyType qtEnterKeyTypeToQnx(Qt::EnterKeyType type);
+
Q_SIGNALS:
void heightChanged(int height);
void visibilityChanged(bool visible);
diff --git a/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp b/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
index 3506de4bc0..ed0db82685 100644
--- a/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
+++ b/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
@@ -1384,13 +1384,17 @@ void QQnxInputContext::setFocusObject(QObject *object)
if (hasSession())
dispatchFocusLossEvent();
} else {
- QInputMethodQueryEvent query(Qt::ImHints);
+ QInputMethodQueryEvent query(Qt::ImHints | Qt::ImEnterKeyType);
QCoreApplication::sendEvent(object, &query);
int inputHints = query.value(Qt::ImHints).toInt();
+ Qt::EnterKeyType qtEnterKeyType = Qt::EnterKeyType(query.value(Qt::ImEnterKeyType).toInt());
dispatchFocusGainEvent(inputHints);
m_virtualKeyboard.setInputHints(inputHints);
+ m_virtualKeyboard.setEnterKeyType(
+ QQnxAbstractVirtualKeyboard::qtEnterKeyTypeToQnx(qtEnterKeyType)
+ );
if (!m_inputPanelVisible)
showInputPanel();
diff --git a/src/plugins/platforms/qnx/qqnxinputcontext_noimf.cpp b/src/plugins/platforms/qnx/qqnxinputcontext_noimf.cpp
index 91ecffa2aa..3860cdf0db 100644
--- a/src/plugins/platforms/qnx/qqnxinputcontext_noimf.cpp
+++ b/src/plugins/platforms/qnx/qqnxinputcontext_noimf.cpp
@@ -172,11 +172,15 @@ void QQnxInputContext::setFocusObject(QObject *object)
if (m_inputPanelVisible)
hideInputPanel();
} else {
- QInputMethodQueryEvent query(Qt::ImHints);
+ QInputMethodQueryEvent query(Qt::ImHints | Qt::ImEnterKeyType);
QCoreApplication::sendEvent(object, &query);
int inputHints = query.value(Qt::ImHints).toInt();
+ Qt::EnterKeyType qtEnterKeyType = Qt::EnterKeyType(query.value(Qt::ImEnterKeyType).toInt());
m_virtualKeyboard.setInputHints(inputHints);
+ m_virtualKeyboard.setEnterKeyType(
+ QQnxAbstractVirtualKeyboard::qtEnterKeyTypeToQnx(qtEnterKeyType)
+ );
if (!m_inputPanelVisible)
showInputPanel();
diff --git a/src/plugins/platforms/qnx/qqnxintegration.cpp b/src/plugins/platforms/qnx/qqnxintegration.cpp
index 071bab7920..1c825dbbdd 100644
--- a/src/plugins/platforms/qnx/qqnxintegration.cpp
+++ b/src/plugins/platforms/qnx/qqnxintegration.cpp
@@ -95,7 +95,6 @@
#include <private/qsimpledrag_p.h>
#include <QtCore/QDebug>
-#include <QtCore/QHash>
#include <errno.h>
diff --git a/src/plugins/platforms/windows/openglblacklists/default.json b/src/plugins/platforms/windows/openglblacklists/default.json
index 23607523bd..b00c9df408 100644
--- a/src/plugins/platforms/windows/openglblacklists/default.json
+++ b/src/plugins/platforms/windows/openglblacklists/default.json
@@ -17,6 +17,31 @@
"features": [
"disable_desktopgl"
]
- }
+ },
+ {
+ "id": 2,
+ "description": "Intel Q965/Q963 - GMA 3000 has insufficient support of opengl and directx",
+ "vendor_id": "0x8086",
+ "device_id": [ "0x2992" ],
+ "os": {
+ "type": "win"
+ },
+ "features": [
+ "disable_desktopgl",
+ "disable_angle"
+ ]
+ },
+ {
+ "id": 3,
+ "description": "No OpenGL on Intel G33/G31 (QTBUG-47522)",
+ "vendor_id": "0x8086",
+ "device_id": [ "0x29C2" ],
+ "os": {
+ "type": "win"
+ },
+ "features": [
+ "disable_desktopgl"
+ ]
+ }
]
}
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.cpp b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
index 16c278d9df..3f19e4401a 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.cpp
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
@@ -35,10 +35,10 @@
#include "qwindowswindow.h"
#include "qwindowsnativeimage.h"
#include "qwindowscontext.h"
-#include "qwindowsscaling.h"
#include <QtGui/QWindow>
#include <QtGui/QPainter>
+#include <private/qhighdpiscaling_p.h>
#include <QtCore/QDebug>
@@ -68,10 +68,12 @@ QPaintDevice *QWindowsBackingStore::paintDevice()
return &m_image->image();
}
-void QWindowsBackingStore::flushDp(QWindow *window, const QRect &br, const QPoint &offset)
+void QWindowsBackingStore::flush(QWindow *window, const QRegion &region,
+ const QPoint &offset)
{
Q_ASSERT(window);
+ const QRect br = region.boundingRect();
if (QWindowsContext::verbose > 1)
qCDebug(lcQpaBackingStore) << __FUNCTION__ << this << window << offset << br;
QWindowsWindow *rw = QWindowsWindow::baseWindowOf(window);
@@ -81,9 +83,8 @@ void QWindowsBackingStore::flushDp(QWindow *window, const QRect &br, const QPoin
const Qt::WindowFlags flags = window->flags();
if ((flags & Qt::FramelessWindowHint) && QWindowsWindow::setWindowLayered(rw->handle(), flags, hasAlpha, rw->opacity()) && hasAlpha) {
// Windows with alpha: Use blend function to update.
- const QMargins marginsDP = rw->frameMarginsDp();
- const QRect r = rw->geometryDp() + marginsDP;
- const QPoint frameOffset(marginsDP.left(), marginsDP.top());
+ QRect r = QHighDpi::toNativePixels(window->frameGeometry(), window);
+ QPoint frameOffset(QHighDpi::toNativePixels(QPoint(window->frameMargins().left(), window->frameMargins().top()), window));
QRect dirtyRect = br.translated(offset + frameOffset);
SIZE size = {r.width(), r.height()};
@@ -127,15 +128,14 @@ void QWindowsBackingStore::flushDp(QWindow *window, const QRect &br, const QPoin
}
}
-void QWindowsBackingStore::resize(const QSize &sizeDip, const QRegion &regionDip)
+void QWindowsBackingStore::resize(const QSize &size, const QRegion &region)
{
- const QSize size = sizeDip * QWindowsScaling::factor();
if (m_image.isNull() || m_image->image().size() != size) {
#ifndef QT_NO_DEBUG_OUTPUT
if (QWindowsContext::verbose && lcQpaBackingStore().isDebugEnabled()) {
qCDebug(lcQpaBackingStore)
- << __FUNCTION__ << ' ' << window() << ' ' << size << ' ' << sizeDip << ' '
- << regionDip << " from: " << (m_image.isNull() ? QSize() : m_image->image().size());
+ << __FUNCTION__ << ' ' << window() << ' ' << size << ' ' << region
+ << " from: " << (m_image.isNull() ? QSize() : m_image->image().size());
}
#endif
const QImage::Format format = window()->format().hasAlpha() ?
@@ -144,10 +144,10 @@ void QWindowsBackingStore::resize(const QSize &sizeDip, const QRegion &regionDip
QWindowsNativeImage *oldwni = m_image.data();
QWindowsNativeImage *newwni = new QWindowsNativeImage(size.width(), size.height(), format);
- if (oldwni && !regionDip.isEmpty()) {
+ if (oldwni && !region.isEmpty()) {
const QImage &oldimg(oldwni->image());
QImage &newimg(newwni->image());
- QRegion staticRegion = QWindowsScaling::mapToNative(regionDip);
+ QRegion staticRegion(region);
staticRegion &= QRect(0, 0, oldimg.width(), oldimg.height());
staticRegion &= QRect(0, 0, newimg.width(), newimg.height());
QPainter painter(&newimg);
@@ -156,38 +156,36 @@ void QWindowsBackingStore::resize(const QSize &sizeDip, const QRegion &regionDip
painter.drawImage(rect, oldimg, rect);
}
- if (QWindowsScaling::isActive())
- newwni->setDevicePixelRatio(QWindowsScaling::factor());
m_image.reset(newwni);
}
}
Q_GUI_EXPORT void qt_scrollRectInImage(QImage &img, const QRect &rect, const QPoint &offset);
-bool QWindowsBackingStore::scroll(const QRegion &areaDip, int dxDip, int dyDip)
+bool QWindowsBackingStore::scroll(const QRegion &area, int dx, int dy)
{
if (m_image.isNull() || m_image->image().isNull())
return false;
- const QPoint dp = QPoint(dxDip, dyDip) * QWindowsScaling::factor();
- const QVector<QRect> rects = areaDip.rects();
+ const QVector<QRect> rects = area.rects();
+ const QPoint offset(dx, dy);
for (int i = 0; i < rects.size(); ++i)
- qt_scrollRectInImage(m_image->image(), QWindowsScaling::mapToNative(rects.at(i)), dp);
+ qt_scrollRectInImage(m_image->image(), rects.at(i), offset);
return true;
}
-void QWindowsBackingStore::beginPaint(const QRegion &regionDip)
+void QWindowsBackingStore::beginPaint(const QRegion &region)
{
if (QWindowsContext::verbose > 1)
- qCDebug(lcQpaBackingStore) <<__FUNCTION__ << regionDip;
+ qCDebug(lcQpaBackingStore) <<__FUNCTION__ << region;
if (m_image->image().hasAlphaChannel()) {
QPainter p(&m_image->image());
p.setCompositionMode(QPainter::CompositionMode_Source);
const QColor blank = Qt::transparent;
- foreach (const QRect &r, regionDip.rects())
- p.fillRect(QWindowsScaling::mapToNative(r), blank);
+ foreach (const QRect &r, region.rects())
+ p.fillRect(r, blank);
}
}
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.h b/src/plugins/platforms/windows/qwindowsbackingstore.h
index 41ad29babc..4badcf1b09 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.h
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.h
@@ -35,7 +35,6 @@
#define QWINDOWSBACKINGSTORE_H
#include "qtwindows_additional.h"
-#include "qwindowsscaling.h"
#include <qpa/qplatformbackingstore.h>
#include <QtCore/QScopedPointer>
@@ -53,12 +52,7 @@ public:
~QWindowsBackingStore();
QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
- void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE
- {
- flushDp(window, QWindowsScaling::mapToNative(region.boundingRect()),
- offset * QWindowsScaling::factor());
- }
- void flushDp(QWindow *window, const QRect &boundingRect, const QPoint &offset);
+ void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
void resize(const QSize &size, const QRegion &r) Q_DECL_OVERRIDE;
bool scroll(const QRegion &area, int dx, int dy) Q_DECL_OVERRIDE;
void beginPaint(const QRegion &) Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/windows/qwindowscontext.cpp b/src/plugins/platforms/windows/qwindowscontext.cpp
index 3f355db607..717adcc47f 100644
--- a/src/plugins/platforms/windows/qwindowscontext.cpp
+++ b/src/plugins/platforms/windows/qwindowscontext.cpp
@@ -51,7 +51,6 @@
#endif
#include "qwindowsscreen.h"
#include "qwindowstheme.h"
-#include "qwindowsscaling.h"
#include <QtGui/QWindow>
#include <qpa/qwindowsysteminterface.h>
@@ -1232,9 +1231,7 @@ bool QWindowsContext::handleContextMenuEvent(QWindow *window, const MSG &msg)
}
}
- QWindowSystemInterface::handleContextMenuEvent(window, mouseTriggered,
- pos / QWindowsScaling::factor(),
- globalPos / QWindowsScaling::factor(),
+ QWindowSystemInterface::handleContextMenuEvent(window, mouseTriggered, pos, globalPos,
QWindowsKeyMapper::queryKeyboardModifiers());
return true;
}
diff --git a/src/plugins/platforms/windows/qwindowscursor.cpp b/src/plugins/platforms/windows/qwindowscursor.cpp
index 5f443f2675..1fbef61029 100644
--- a/src/plugins/platforms/windows/qwindowscursor.cpp
+++ b/src/plugins/platforms/windows/qwindowscursor.cpp
@@ -36,7 +36,6 @@
#include "qwindowscontext.h"
#include "qwindowswindow.h"
#include "qwindowsscreen.h"
-#include "qwindowsscaling.h"
#include <QtGui/QBitmap>
#include <QtGui/QImage>
@@ -646,13 +645,12 @@ QWindowsCursor::CursorState QWindowsCursor::cursorState()
QPoint QWindowsCursor::pos() const
{
- return mousePosition() / QWindowsScaling::factor();
+ return mousePosition();
}
void QWindowsCursor::setPos(const QPoint &pos)
{
- const QPoint posDp = pos * QWindowsScaling::factor();
- SetCursorPos(posDp.x() , posDp.y());
+ SetCursorPos(pos.x() , pos.y());
}
/*!
diff --git a/src/plugins/platforms/windows/qwindowsdrag.cpp b/src/plugins/platforms/windows/qwindowsdrag.cpp
index 03438e3ee2..d24cba3c68 100644
--- a/src/plugins/platforms/windows/qwindowsdrag.cpp
+++ b/src/plugins/platforms/windows/qwindowsdrag.cpp
@@ -33,7 +33,7 @@
#include "qwindowsdrag.h"
#include "qwindowscontext.h"
-#include "qwindowsscaling.h"
+#include "qwindowsscreen.h"
#ifndef QT_NO_CLIPBOARD
# include "qwindowsclipboard.h"
#endif
@@ -43,7 +43,6 @@
#include "qwindowswindow.h"
#include "qwindowsmousehandler.h"
#include "qwindowscursor.h"
-#include "qwindowsscaling.h"
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
@@ -52,6 +51,7 @@
#include <QtGui/QGuiApplication>
#include <qpa/qwindowsysteminterface_p.h>
#include <QtGui/private/qguiapplication_p.h>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtCore/QDebug>
#include <QtCore/QBuffer>
@@ -280,6 +280,13 @@ QDebug operator<<(QDebug d, const QWindowsOleDropSource::CursorEntry &e)
}
#endif // !QT_NO_DEBUG_OUTPUT
+static qreal dragScaleFactor()
+{
+ const QWindowsScreenManager &screenManager = QWindowsContext::instance()->screenManager();
+ const QWindowsScreen *screen = screenManager.screenAtDp(QWindowsCursor::mousePosition());
+ return screen ? QHighDpiScaling::factor(screen) : qreal(1);
+}
+
/*!
\brief Blend custom pixmap with cursors.
*/
@@ -289,19 +296,22 @@ void QWindowsOleDropSource::createCursors()
const QDrag *drag = m_drag->currentDrag();
const QPixmap pixmap = drag->pixmap();
const bool hasPixmap = !pixmap.isNull();
- const int scaleFactor = QWindowsScaling::factor();
- const QSize pixmapSizeDp = pixmap.size() * scaleFactor;
+
+ const qreal scaleFactor = dragScaleFactor();
const bool scalePixmap = hasPixmap
&& m_mode != TouchDrag // Touch drag: pixmap is shown in a separate QWindow, which will be scaled.
&& (scaleFactor != 1 && scaleFactor != qRound(pixmap.devicePixelRatio()));
- const QPixmap drawPixmap = scalePixmap
- ? pixmap.scaled(pixmapSizeDp, Qt::KeepAspectRatio, Qt::SmoothTransformation) : pixmap;
-
+ const QPixmap scaledPixmap = scalePixmap
+ ? pixmap.scaled((QSizeF(pixmap.size()) * scaleFactor).toSize(),
+ Qt::KeepAspectRatio, Qt::SmoothTransformation)
+ : pixmap;
Qt::DropAction actions[] = { Qt::MoveAction, Qt::CopyAction, Qt::LinkAction, Qt::IgnoreAction };
int actionCount = int(sizeof(actions) / sizeof(actions[0]));
if (!hasPixmap)
--actionCount; // No Qt::IgnoreAction unless pixmap
- const QPoint hotSpot = drag->hotSpot() * scaleFactor;
+ const QPoint hotSpot = scalePixmap
+ ? (QPointF(drag->hotSpot()) * scaleFactor).toPoint()
+ : drag->hotSpot();
for (int cnum = 0; cnum < actionCount; ++cnum) {
const Qt::DropAction action = actions[cnum];
QPixmap cursorPixmap = drag->dragCursor(action);
@@ -321,14 +331,14 @@ void QWindowsOleDropSource::createCursors()
if (hasPixmap) {
const int x1 = qMin(-hotSpot.x(), 0);
- const int x2 = qMax(pixmapSizeDp.width() - hotSpot.x(), cursorPixmap.width());
+ const int x2 = qMax(scaledPixmap.width() - hotSpot.x(), cursorPixmap.width());
const int y1 = qMin(-hotSpot.y(), 0);
- const int y2 = qMax(pixmapSizeDp.height() - hotSpot.y(), cursorPixmap.height());
+ const int y2 = qMax(scaledPixmap.height() - hotSpot.y(), cursorPixmap.height());
QPixmap newCursor(x2 - x1 + 1, y2 - y1 + 1);
newCursor.fill(Qt::transparent);
QPainter p(&newCursor);
const QPoint pmDest = QPoint(qMax(0, -hotSpot.x()), qMax(0, -hotSpot.y()));
- p.drawPixmap(pmDest, drawPixmap);
+ p.drawPixmap(pmDest, scaledPixmap);
p.drawPixmap(qMax(0, hotSpot.x()),qMax(0, hotSpot.y()), cursorPixmap);
newPixmap = newCursor;
newHotSpot = QPoint(qMax(0, hotSpot.x()), qMax(0, hotSpot.y()));
@@ -454,7 +464,7 @@ QWindowsOleDropSource::GiveFeedback(DWORD dwEffect)
if (!m_touchDragWindow)
m_touchDragWindow = new QWindowsDragCursorWindow;
m_touchDragWindow->setPixmap(e.pixmap);
- m_touchDragWindow->setFramePosition((QWindowsCursor::mousePosition() - e.hotSpot) / QWindowsScaling::factor());
+ m_touchDragWindow->setFramePosition(QWindowsCursor::mousePosition() - e.hotSpot);
if (!m_touchDragWindow->isVisible())
m_touchDragWindow->show();
break;
@@ -530,9 +540,7 @@ void QWindowsOleDropTarget::handleDrag(QWindow *window, DWORD grfKeyState,
QGuiApplicationPrivate::mouse_buttons = QWindowsMouseHandler::keyStateToMouseButtons(grfKeyState);
const QPlatformDragQtResponse response =
- QWindowSystemInterface::handleDrag(window, windowsDrag->dropData(),
- m_lastPoint / QWindowsScaling::factor(),
- actions);
+ QWindowSystemInterface::handleDrag(window, windowsDrag->dropData(), m_lastPoint, actions);
m_answerRect = response.answerRect();
const Qt::DropAction action = response.acceptedAction();
@@ -625,9 +633,8 @@ QWindowsOleDropTarget::Drop(LPDATAOBJECT pDataObj, DWORD grfKeyState,
const QPlatformDropQtResponse response =
QWindowSystemInterface::handleDrop(m_window, windowsDrag->dropData(),
- m_lastPoint / QWindowsScaling::factor(),
+ m_lastPoint,
translateToQDragDropActions(*pdwEffect));
-
if (response.isAccepted()) {
const Qt::DropAction action = response.acceptedAction();
if (action == Qt::MoveAction || action == Qt::TargetMoveAction) {
diff --git a/src/plugins/platforms/windows/qwindowsinputcontext.cpp b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
index 68e38dc4a6..554a6c8b4c 100644
--- a/src/plugins/platforms/windows/qwindowsinputcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
@@ -36,7 +36,6 @@
#include "qwindowswindow.h"
#include "qwindowsintegration.h"
#include "qwindowsmousehandler.h"
-#include "qwindowsscaling.h"
#include <QtCore/QDebug>
#include <QtCore/QObject>
@@ -254,10 +253,9 @@ void QWindowsInputContext::cursorRectChanged()
if (!m_compositionContext.hwnd)
return;
const QInputMethod *inputMethod = QGuiApplication::inputMethod();
- const QRect cursorRectangleDip = inputMethod->cursorRectangle().toRect();
- if (!cursorRectangleDip.isValid())
+ const QRect cursorRectangle = inputMethod->cursorRectangle().toRect();
+ if (!cursorRectangle.isValid())
return;
- const QRect cursorRectangle = QWindowsScaling::mapToNative(cursorRectangleDip);
qCDebug(lcQpaInputMethods) << __FUNCTION__<< cursorRectangle;
diff --git a/src/plugins/platforms/windows/qwindowsintegration.cpp b/src/plugins/platforms/windows/qwindowsintegration.cpp
index 79df6ce720..bbb1f68a52 100644
--- a/src/plugins/platforms/windows/qwindowsintegration.cpp
+++ b/src/plugins/platforms/windows/qwindowsintegration.cpp
@@ -33,7 +33,6 @@
****************************************************************************/
#include "qwindowsintegration.h"
-#include "qwindowsscaling.h"
#include "qwindowswindow.h"
#include "qwindowscontext.h"
#include "qwindowsopenglcontext.h"
@@ -64,6 +63,7 @@
# include "qwindowssessionmanager.h"
#endif
#include <QtGui/private/qguiapplication_p.h>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qpa/qplatforminputcontextfactory_p.h>
#include <QtCore/private/qeventdispatcher_win_p.h>
@@ -223,12 +223,8 @@ QWindowsIntegrationPrivate::QWindowsIntegrationPrivate(const QStringList &paramL
m_context.setProcessDpiAwareness(dpiAwareness);
dpiAwarenessSet = true;
}
- // Determine suitable scale factor, don't mix Windows and Qt scaling
- if (dpiAwareness != QtWindows::ProcessDpiUnaware)
- QWindowsScaling::setFactor(QWindowsScaling::determineUiScaleFactor());
qCDebug(lcQpaWindows)
- << __FUNCTION__ << "DpiAwareness=" << dpiAwareness <<",Scaling="
- << QWindowsScaling::factor();
+ << __FUNCTION__ << "DpiAwareness=" << dpiAwareness;
QTouchDevice *touchDevice = m_context.touchDevice();
if (touchDevice) {
@@ -268,10 +264,9 @@ QWindowsIntegration::~QWindowsIntegration()
void QWindowsIntegration::initialize()
{
- if (QPlatformInputContext *pluginContext = QPlatformInputContextFactory::create())
- d->m_inputContext.reset(pluginContext);
- else
- d->m_inputContext.reset(new QWindowsInputContext);
+ QString icStr = QPlatformInputContextFactory::requested();
+ icStr.isNull() ? d->m_inputContext.reset(new QWindowsInputContext)
+ : d->m_inputContext.reset(QPlatformInputContextFactory::create(icStr));
}
bool QWindowsIntegration::hasCapability(QPlatformIntegration::Capability cap) const
@@ -307,7 +302,7 @@ QWindowsWindowData QWindowsIntegration::createWindowData(QWindow *window) const
{
QWindowsWindowData requested;
requested.flags = window->flags();
- requested.geometry = QWindowsScaling::mapToNative(window->geometry());
+ requested.geometry = QHighDpi::toNativePixels(window->geometry(), window);
// Apply custom margins (see QWindowsWindow::setCustomMargins())).
const QVariant customMarginsV = window->property("_q_windowsCustomMargins");
if (customMarginsV.isValid())
@@ -327,7 +322,7 @@ QWindowsWindowData QWindowsIntegration::createWindowData(QWindow *window) const
window->setFlags(obtained.flags);
// Trigger geometry change signals of QWindow.
if ((obtained.flags & Qt::Desktop) != Qt::Desktop && requested.geometry != obtained.geometry)
- QWindowSystemInterface::handleGeometryChange(window, QWindowsScaling::mapFromNative(obtained.geometry));
+ QWindowSystemInterface::handleGeometryChange(window, obtained.geometry);
}
return obtained;
diff --git a/src/plugins/platforms/windows/qwindowskeymapper.cpp b/src/plugins/platforms/windows/qwindowskeymapper.cpp
index d47c7df9e0..3636bb7893 100644
--- a/src/plugins/platforms/windows/qwindowskeymapper.cpp
+++ b/src/plugins/platforms/windows/qwindowskeymapper.cpp
@@ -35,12 +35,12 @@
#include "qwindowscontext.h"
#include "qwindowswindow.h"
#include "qwindowsguieventdispatcher.h"
-#include "qwindowsscaling.h"
#include "qwindowsinputcontext.h"
#include <QtGui/QWindow>
#include <qpa/qwindowsysteminterface.h>
#include <private/qguiapplication_p.h>
+#include <private/qhighdpiscaling_p.h>
#include <QtGui/QKeyEvent>
#if defined(WM_APPCOMMAND)
@@ -792,10 +792,12 @@ static void showSystemMenu(QWindow* w)
#undef enabled
#undef disabled
#endif // !Q_OS_WINCE
- const QPoint topLeft = topLevel->geometry().topLeft() * QWindowsScaling::factor();
+ const QPoint pos = QHighDpi::toNativePixels(topLevel->geometry().topLeft(), topLevel);
const int ret = TrackPopupMenuEx(menu,
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
- topLeft.x(), topLeft.y(), topLevelHwnd, 0);
+ pos.x(), pos.y(),
+ topLevelHwnd,
+ 0);
if (ret)
qWindowsWndProc(topLevelHwnd, WM_SYSCOMMAND, ret, 0);
}
diff --git a/src/plugins/platforms/windows/qwindowsmousehandler.cpp b/src/plugins/platforms/windows/qwindowsmousehandler.cpp
index e6b80f2b93..200eb11855 100644
--- a/src/plugins/platforms/windows/qwindowsmousehandler.cpp
+++ b/src/plugins/platforms/windows/qwindowsmousehandler.cpp
@@ -211,10 +211,8 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
const QPoint globalPosition = winEventPosition;
const QPoint clientPosition = QWindowsGeometryHint::mapFromGlobal(hwnd, globalPosition);
const Qt::MouseButtons buttons = QWindowsMouseHandler::queryMouseButtons();
- QWindowSystemInterface::handleFrameStrutMouseEvent(window,
- clientPosition / QWindowsScaling::factor(),
- globalPosition / QWindowsScaling::factor(),
- buttons,
+ QWindowSystemInterface::handleFrameStrutMouseEvent(window, clientPosition,
+ globalPosition, buttons,
QWindowsKeyMapper::queryKeyboardModifiers(),
source);
return false; // Allow further event processing (dragging of windows).
@@ -279,7 +277,7 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
// ChildWindowFromPointEx() may not find the Qt window (failing with ERROR_ACCESS_DENIED)
if (!currentWindowUnderMouse) {
const QRect clientRect(QPoint(0, 0), window->size());
- if (clientRect.contains(winEventPosition / QWindowsScaling::factor()))
+ if (clientRect.contains(winEventPosition))
currentWindowUnderMouse = window;
}
@@ -366,10 +364,7 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
m_windowUnderMouse = currentWindowUnderMouse;
}
- QWindowSystemInterface::handleMouseEvent(window,
- winEventPosition / QWindowsScaling::factor(),
- globalPosition / QWindowsScaling::factor(),
- buttons,
+ QWindowSystemInterface::handleMouseEvent(window, winEventPosition, globalPosition, buttons,
QWindowsKeyMapper::queryKeyboardModifiers(),
source);
m_previousCaptureWindow = hasCapture ? window : 0;
@@ -404,11 +399,9 @@ static void redirectWheelEvent(QWindow *window, const QPoint &globalPos, int del
}
if (handleEvent) {
- const QPoint posDip = QWindowsGeometryHint::mapFromGlobal(receiver, globalPos) / QWindowsScaling::factor();
QWindowSystemInterface::handleWheelEvent(receiver,
- posDip, globalPos / QWindowsScaling::factor(),
- delta / QWindowsScaling::factor(),
- orientation, mods);
+ QWindowsGeometryHint::mapFromGlobal(receiver, globalPos),
+ globalPos, delta, orientation, mods);
}
}
@@ -494,7 +487,6 @@ bool QWindowsMouseHandler::translateTouchEvent(QWindow *window, HWND,
Q_ASSERT(QWindowsContext::user32dll.getTouchInputInfo);
QWindowsContext::user32dll.getTouchInputInfo((HANDLE) msg.lParam, msg.wParam, winTouchInputs.data(), sizeof(TOUCHINPUT));
- const qreal screenPosFactor = 0.01 / qreal(QWindowsScaling::factor());
for (int i = 0; i < winTouchPointCount; ++i) {
const TOUCHINPUT &winTouchInput = winTouchInputs[i];
int id = m_touchInputIDToTouchPointID.value(winTouchInput.dwID, -1);
@@ -508,9 +500,9 @@ bool QWindowsMouseHandler::translateTouchEvent(QWindow *window, HWND,
if (m_lastTouchPositions.contains(id))
touchPoint.normalPosition = m_lastTouchPositions.value(id);
- const QPointF screenPos = QPointF(winTouchInput.x, winTouchInput.y) * screenPosFactor;
+ const QPointF screenPos = QPointF(winTouchInput.x, winTouchInput.y) / qreal(100.);
if (winTouchInput.dwMask & TOUCHINPUTMASKF_CONTACTAREA)
- touchPoint.area.setSize(QSizeF(winTouchInput.cxContact, winTouchInput.cyContact) * screenPosFactor);
+ touchPoint.area.setSize(QSizeF(winTouchInput.cxContact, winTouchInput.cyContact) / qreal(100.));
touchPoint.area.moveCenter(screenPos);
QPointF normalPosition = QPointF(screenPos.x() / screenGeometry.width(),
screenPos.y() / screenGeometry.height());
diff --git a/src/plugins/platforms/windows/qwindowsnativeimage.h b/src/plugins/platforms/windows/qwindowsnativeimage.h
index 6f9ce93ef0..80a1de1ea5 100644
--- a/src/plugins/platforms/windows/qwindowsnativeimage.h
+++ b/src/plugins/platforms/windows/qwindowsnativeimage.h
@@ -57,8 +57,6 @@ public:
HDC hdc() const { return m_hdc; }
- void setDevicePixelRatio(qreal scaleFactor) { m_image.setDevicePixelRatio(scaleFactor); }
-
static QImage::Format systemFormat();
private:
diff --git a/src/plugins/platforms/windows/qwindowsopengltester.cpp b/src/plugins/platforms/windows/qwindowsopengltester.cpp
index 810fddbca7..52e83395d1 100644
--- a/src/plugins/platforms/windows/qwindowsopengltester.cpp
+++ b/src/plugins/platforms/windows/qwindowsopengltester.cpp
@@ -224,7 +224,7 @@ QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(c
#elif defined(Q_OS_WINCE)
return QWindowsOpenGLTester::Gles;
#else
- QOpenGLConfig::Gpu qgpu = QOpenGLConfig::Gpu::fromDevice(gpu.vendorId, gpu.deviceId, gpu.driverVersion);
+ QOpenGLConfig::Gpu qgpu = QOpenGLConfig::Gpu::fromDevice(gpu.vendorId, gpu.deviceId, gpu.driverVersion, gpu.description);
SupportedRenderersCache *srCache = supportedRenderersCache();
SupportedRenderersCache::const_iterator it = srCache->find(qgpu);
if (it != srCache->cend())
@@ -250,19 +250,19 @@ QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(c
qCDebug(lcQpaGl) << "GPU features:" << features;
if (features.contains(QStringLiteral("disable_desktopgl"))) { // Qt-specific
- qCWarning(lcQpaGl) << "Disabling Desktop GL: " << gpu;
+ qCDebug(lcQpaGl) << "Disabling Desktop GL: " << gpu;
result &= ~QWindowsOpenGLTester::DesktopGl;
}
if (features.contains(QStringLiteral("disable_angle"))) { // Qt-specific keyword
- qCWarning(lcQpaGl) << "Disabling ANGLE: " << gpu;
+ qCDebug(lcQpaGl) << "Disabling ANGLE: " << gpu;
result &= ~QWindowsOpenGLTester::GlesMask;
} else {
if (features.contains(QStringLiteral("disable_d3d11"))) { // standard keyword
- qCWarning(lcQpaGl) << "Disabling D3D11: " << gpu;
+ qCDebug(lcQpaGl) << "Disabling D3D11: " << gpu;
result &= ~QWindowsOpenGLTester::AngleRendererD3d11;
}
if (features.contains(QStringLiteral("disable_d3d9"))) { // Qt-specific
- qCWarning(lcQpaGl) << "Disabling D3D9: " << gpu;
+ qCDebug(lcQpaGl) << "Disabling D3D9: " << gpu;
result &= ~QWindowsOpenGLTester::AngleRendererD3d9;
}
}
diff --git a/src/plugins/platforms/windows/qwindowsopengltester.h b/src/plugins/platforms/windows/qwindowsopengltester.h
index 748885542d..3cd8bf4d4b 100644
--- a/src/plugins/platforms/windows/qwindowsopengltester.h
+++ b/src/plugins/platforms/windows/qwindowsopengltester.h
@@ -36,7 +36,7 @@
#include <QtCore/QByteArray>
#include <QtCore/QFlags>
-#include <private/qversionnumber_p.h>
+#include <QtCore/qversionnumber.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsscaling.cpp b/src/plugins/platforms/windows/qwindowsscaling.cpp
deleted file mode 100644
index 6ab7f254fd..0000000000
--- a/src/plugins/platforms/windows/qwindowsscaling.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsscaling.h"
-#include "qwindowsscreen.h"
-
-#include <QtCore/QDebug>
-#include <QtCore/QCoreApplication>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QWindowsScaling
- \brief Windows scaling utilities
-
- \internal
- \ingroup qt-lighthouse-win
-*/
-
-int QWindowsScaling::m_factor = 1;
-
-static const char devicePixelRatioEnvVar[] = "QT_DEVICE_PIXEL_RATIO";
-
-// Suggest a scale factor by checking monitor sizes.
-int QWindowsScaling::determineUiScaleFactor()
-{
- if (!qEnvironmentVariableIsSet(devicePixelRatioEnvVar))
- return 1;
- const QByteArray envDevicePixelRatioEnv = qgetenv(devicePixelRatioEnvVar);
- // Auto: Suggest a scale factor by checking monitor resolution.
- if (envDevicePixelRatioEnv == "auto") {
- const int maxResolution = QWindowsScreen::maxMonitorHorizResolution();
- return maxResolution > 180 ? maxResolution / 96 : 1;
- }
- // Get factor from environment
- bool ok = false;
- const int envFactor = envDevicePixelRatioEnv.toInt(&ok);
- return ok && envFactor > 0 ? envFactor : 1;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsscaling.h b/src/plugins/platforms/windows/qwindowsscaling.h
deleted file mode 100644
index 39e554bbe2..0000000000
--- a/src/plugins/platforms/windows/qwindowsscaling.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWSSCALING_H
-#define QWINDOWSSCALING_H
-
-#include <QtGui/QRegion>
-#include <QtCore/QVector>
-#include <QtCore/QRect>
-
-QT_BEGIN_NAMESPACE
-
-enum
-#if defined(Q_COMPILER_CLASS_ENUM) || defined(Q_CC_MSVC)
- : int
-#endif
-{ QWINDOWSIZE_MAX = 16777215 };
-
-class QWindowsScaling {
-public:
- static bool isActive() { return m_factor > 1; }
- static int factor() { return m_factor; }
- static void setFactor(int factor) { m_factor = factor; }
- static int determineUiScaleFactor();
-
- // Scaling helpers for size constraints.
- static int mapToNativeConstrained(int qt)
- { return m_factor != 1 && qt > 0 && qt < QWINDOWSIZE_MAX ? qt * m_factor : qt; }
-
- static int mapFromNativeConstrained(int dp)
- { return m_factor != 1 && dp > 0 && dp < QWINDOWSIZE_MAX ? dp / m_factor : dp; }
-
- static QSize mapToNativeConstrained(const QSize &qt)
- { return QSize(mapToNativeConstrained(qt.width()), mapToNativeConstrained(qt.height())); }
-
- static QRect mapToNative(const QRect &qRect)
- {
- return QRect(qRect.x() * m_factor, qRect.y() * m_factor, qRect.width() * m_factor, qRect.height() * m_factor);
- }
-
- static QRect mapFromNative(const QRect &dp)
- {
- return isActive() ?
- QRect(dp.x() / m_factor, dp.y() / m_factor, (dp.width() + 1) / m_factor, (dp.height() + 1) / m_factor) :
- dp;
- }
-
- static QRegion mapToNative(const QRegion &regionQt)
- {
- if (!QWindowsScaling::isActive() || regionQt.isEmpty())
- return regionQt;
-
- QRegion result;
- foreach (const QRect &rectQt, regionQt.rects())
- result += QWindowsScaling::mapToNative(rectQt);
- return result;
- }
-
- static QRegion mapFromNative(const QRegion &regionDp)
- {
- if (!QWindowsScaling::isActive() || regionDp.isEmpty())
- return regionDp;
-
- QRegion result;
- foreach (const QRect &rectDp, regionDp.rects())
- result += QWindowsScaling::mapFromNative(rectDp);
- return result;
- }
-
-private:
- static int m_factor;
-};
-
-QT_END_NAMESPACE
-
-#endif // QWINDOWSSCALING_H
diff --git a/src/plugins/platforms/windows/qwindowsscreen.cpp b/src/plugins/platforms/windows/qwindowsscreen.cpp
index 7756c77001..391735a035 100644
--- a/src/plugins/platforms/windows/qwindowsscreen.cpp
+++ b/src/plugins/platforms/windows/qwindowsscreen.cpp
@@ -43,6 +43,7 @@
#include <QtGui/QPixmap>
#include <QtGui/QGuiApplication>
#include <qpa/qwindowsysteminterface.h>
+#include <private/qhighdpiscaling_p.h>
#include <QtGui/QScreen>
#include <QtCore/QDebug>
@@ -218,36 +219,14 @@ QWindowsScreen::QWindowsScreen(const QWindowsScreenData &data) :
{
}
-BOOL QT_WIN_CALLBACK monitorResolutionEnumCallback(HMONITOR hMonitor, HDC, LPRECT, LPARAM p)
-{
- QWindowsScreenData data;
- if (monitorData(hMonitor, &data)) {
- int *maxHorizResolution = reinterpret_cast<int *>(p);
- const int horizResolution = qRound(data.dpi.first);
- if (horizResolution > *maxHorizResolution)
- *maxHorizResolution = horizResolution;
- }
- return TRUE;
-}
-
-int QWindowsScreen::maxMonitorHorizResolution()
-{
- int result = 0;
- EnumDisplayMonitors(0, 0, monitorResolutionEnumCallback, (LPARAM)&result);
- return result;
-}
-
Q_GUI_EXPORT QPixmap qt_pixmapFromWinHBITMAP(HBITMAP bitmap, int hbitmapFormat = 0);
-QPixmap QWindowsScreen::grabWindow(WId window, int qX, int qY, int qWidth, int qHeight) const
+QPixmap QWindowsScreen::grabWindow(WId window, int x, int y, int width, int height) const
{
RECT r;
HWND hwnd = window ? (HWND)window : GetDesktopWindow();
GetClientRect(hwnd, &r);
- const int x = qX * QWindowsScaling::factor();
- const int y = qY * QWindowsScaling::factor();
- int width = qWidth * QWindowsScaling::factor();
- int height = qHeight * QWindowsScaling::factor();
+
if (width < 0) width = r.right - r.left;
if (height < 0) height = r.bottom - r.top;
@@ -271,10 +250,6 @@ QPixmap QWindowsScreen::grabWindow(WId window, int qX, int qY, int qWidth, int q
DeleteObject(bitmap);
ReleaseDC(0, display_dc);
- if (QWindowsScaling::isActive()) {
- const qreal factor = 1.0 / qreal(QWindowsScaling::factor());
- return pixmap.transformed(QTransform::fromScale(factor, factor));
- }
return pixmap;
}
@@ -285,7 +260,7 @@ QPixmap QWindowsScreen::grabWindow(WId window, int qX, int qY, int qWidth, int q
QWindow *QWindowsScreen::topLevelAt(const QPoint &point) const
{
QWindow *result = 0;
- if (QWindow *child = QWindowsScreen::windowAt(point * QWindowsScaling::factor(), CWP_SKIPINVISIBLE))
+ if (QWindow *child = QWindowsScreen::windowAt(point, CWP_SKIPINVISIBLE))
result = QWindowsWindow::topLevelOf(child);
qCDebug(lcQpaWindows) <<__FUNCTION__ << point << result;
return result;
@@ -313,6 +288,12 @@ QWindowsScreen *QWindowsScreen::screenOf(const QWindow *w)
return 0;
}
+qreal QWindowsScreen::pixelDensity() const
+{
+ const qreal physicalDpi = m_data.geometry.width() / m_data.physicalSizeMM.width() * qreal(25.4);
+ return qRound(physicalDpi / 96);
+}
+
/*!
\brief Determine siblings in a virtual desktop system.
@@ -542,7 +523,7 @@ void QWindowsScreenManager::clearScreens()
const QWindowsScreen *QWindowsScreenManager::screenAtDp(const QPoint &p) const
{
foreach (QWindowsScreen *scr, m_screens) {
- if (scr->geometryDp().contains(p))
+ if (scr->geometry().contains(p))
return scr;
}
return Q_NULLPTR;
diff --git a/src/plugins/platforms/windows/qwindowsscreen.h b/src/plugins/platforms/windows/qwindowsscreen.h
index 7352c45777..67e7ff644b 100644
--- a/src/plugins/platforms/windows/qwindowsscreen.h
+++ b/src/plugins/platforms/windows/qwindowsscreen.h
@@ -34,7 +34,6 @@
#ifndef QWINDOWSSCREEN_H
#define QWINDOWSSCREEN_H
-#include "qwindowsscaling.h"
#include "qtwindowsglobal.h"
#ifdef Q_OS_WINCE
# include "qplatformfunctions_wince.h"
@@ -82,16 +81,14 @@ public:
static QWindowsScreen *screenOf(const QWindow *w = 0);
- QRect geometryDp() const { return m_data.geometry; }
- QRect geometry() const Q_DECL_OVERRIDE { return QWindowsScaling::mapFromNative(geometryDp()); }
- QRect availableGeometryDp() const { return m_data.availableGeometry; }
- QRect availableGeometry() const Q_DECL_OVERRIDE { return QWindowsScaling::mapFromNative(availableGeometryDp()); }
+ QRect geometry() const Q_DECL_OVERRIDE { return m_data.geometry; }
+ QRect availableGeometry() const Q_DECL_OVERRIDE { return m_data.availableGeometry; }
int depth() const Q_DECL_OVERRIDE { return m_data.depth; }
QImage::Format format() const Q_DECL_OVERRIDE { return m_data.format; }
QSizeF physicalSize() const Q_DECL_OVERRIDE { return m_data.physicalSizeMM; }
- QDpi logicalDpi() const Q_DECL_OVERRIDE
- { return QDpi(m_data.dpi.first / QWindowsScaling::factor(), m_data.dpi.second / QWindowsScaling::factor()); }
- qreal devicePixelRatio() const Q_DECL_OVERRIDE { return QWindowsScaling::factor(); }
+ QDpi logicalDpi() const Q_DECL_OVERRIDE { return m_data.dpi; }
+ qreal pixelDensity() const Q_DECL_OVERRIDE;
+ qreal devicePixelRatio() const Q_DECL_OVERRIDE { return 1.0; }
qreal refreshRate() const Q_DECL_OVERRIDE { return m_data.refreshRateHz; }
QString name() const Q_DECL_OVERRIDE { return m_data.name; }
Qt::ScreenOrientation orientation() const Q_DECL_OVERRIDE { return m_data.orientation; }
@@ -112,7 +109,6 @@ public:
#endif // !QT_NO_CURSOR
const QWindowsScreenData &data() const { return m_data; }
- static int maxMonitorHorizResolution();
private:
QWindowsScreenData m_data;
diff --git a/src/plugins/platforms/windows/qwindowstabletsupport.cpp b/src/plugins/platforms/windows/qwindowstabletsupport.cpp
index 7b871be015..3951401273 100644
--- a/src/plugins/platforms/windows/qwindowstabletsupport.cpp
+++ b/src/plugins/platforms/windows/qwindowstabletsupport.cpp
@@ -32,7 +32,6 @@
****************************************************************************/
#include "qwindowstabletsupport.h"
-#include "qwindowsscaling.h"
#ifndef QT_NO_TABLETEVENT
@@ -55,7 +54,7 @@
#include <QtCore/private/qsystemlibrary_p.h>
// Note: The definition of the PACKET structure in pktdef.h depends on this define.
-#define PACKETDATA (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION | PK_CURSOR | PK_Z)
+#define PACKETDATA (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION | PK_CURSOR | PK_Z | PK_TIME)
#include <pktdef.h>
QT_BEGIN_NAMESPACE
@@ -343,17 +342,18 @@ QWindowsTabletDeviceData QWindowsTabletSupport::tabletInit(const quint64 uniqueI
bool QWindowsTabletSupport::translateTabletProximityEvent(WPARAM /* wParam */, LPARAM lParam)
{
+ PACKET proximityBuffer[1]; // we are only interested in the first packet in this case
+ const int totalPacks = QWindowsTabletSupport::m_winTab32DLL.wTPacketsGet(m_context, 1, proximityBuffer);
+ if (!totalPacks)
+ return false;
if (!LOWORD(lParam)) {
qCDebug(lcQpaTablet) << "leave proximity for device #" << m_currentDevice;
- QWindowSystemInterface::handleTabletLeaveProximityEvent(m_devices.at(m_currentDevice).currentDevice,
+ QWindowSystemInterface::handleTabletLeaveProximityEvent(proximityBuffer[0].pkTime,
+ m_devices.at(m_currentDevice).currentDevice,
m_devices.at(m_currentDevice).currentPointerType,
m_devices.at(m_currentDevice).uniqueId);
return true;
}
- PACKET proximityBuffer[1]; // we are only interested in the first packet in this case
- const int totalPacks = QWindowsTabletSupport::m_winTab32DLL.wTPacketsGet(m_context, 1, proximityBuffer);
- if (!totalPacks)
- return false;
const UINT currentCursor = proximityBuffer[0].pkCursor;
UINT physicalCursorId;
QWindowsTabletSupport::m_winTab32DLL.wTInfo(WTI_CURSORS + currentCursor, CSR_PHYSID, &physicalCursorId);
@@ -371,7 +371,8 @@ bool QWindowsTabletSupport::translateTabletProximityEvent(WPARAM /* wParam */, L
m_devices[m_currentDevice].currentPointerType = pointerType(currentCursor);
qCDebug(lcQpaTablet) << "enter proximity for device #"
<< m_currentDevice << m_devices.at(m_currentDevice);
- QWindowSystemInterface::handleTabletEnterProximityEvent(m_devices.at(m_currentDevice).currentDevice,
+ QWindowSystemInterface::handleTabletEnterProximityEvent(proximityBuffer[0].pkTime,
+ m_devices.at(m_currentDevice).currentDevice,
m_devices.at(m_currentDevice).currentPointerType,
m_devices.at(m_currentDevice).uniqueId);
return true;
@@ -399,8 +400,7 @@ bool QWindowsTabletSupport::translateTabletPacketEvent()
// in which case we snap the position to the mouse position.
// It seems there is no way to find out the mode programmatically, the LOGCONTEXT orgX/Y/Ext
// area is always the virtual desktop.
- const QRect virtualDesktopArea
- = QWindowsScaling::mapToNative(QGuiApplication::primaryScreen()->virtualGeometry());
+ const QRect virtualDesktopArea = QGuiApplication::primaryScreen()->virtualGeometry();
qCDebug(lcQpaTablet) << __FUNCTION__ << "processing " << packetCount
<< "target:" << QGuiApplicationPrivate::tabletPressTarget;
@@ -420,7 +420,7 @@ bool QWindowsTabletSupport::translateTabletPacketEvent()
QPoint globalPos = globalPosF.toPoint();
// Get Mouse Position and compare to tablet info
- QPoint mouseLocation = QWindowsCursor::mousePosition();
+ const QPoint mouseLocation = QWindowsCursor::mousePosition();
// Positions should be almost the same if we are in absolute
// mode. If they are not, use the mouse location.
@@ -475,9 +475,7 @@ bool QWindowsTabletSupport::translateTabletPacketEvent()
<< tiltY << "tanP:" << tangentialPressure << "rotation:" << rotation;
}
- const QPointF localPosDip = QPointF(localPos / QWindowsScaling::factor());
- const QPointF globalPosDip = globalPosF / qreal(QWindowsScaling::factor());
- QWindowSystemInterface::handleTabletEvent(target, localPosDip, globalPosDip,
+ QWindowSystemInterface::handleTabletEvent(target, packet.pkTime, QPointF(localPos), globalPosF,
currentDevice, currentPointer,
static_cast<Qt::MouseButtons>(packet.pkButtons),
pressureNew, tiltX, tiltY,
diff --git a/src/plugins/platforms/windows/qwindowstheme.cpp b/src/plugins/platforms/windows/qwindowstheme.cpp
index d3f67e9eaa..33c7ccfdce 100644
--- a/src/plugins/platforms/windows/qwindowstheme.cpp
+++ b/src/plugins/platforms/windows/qwindowstheme.cpp
@@ -43,7 +43,6 @@
#include "qwindowsintegration.h"
#include "qt_windows.h"
#include "qwindowsfontdatabase.h"
-#include "qwindowsscaling.h"
#ifdef Q_OS_WINCE
# include "qplatformfunctions_wince.h"
# include "winuser.h"
@@ -68,6 +67,7 @@
#include <QtGui/QPainter>
#include <QtGui/QPixmapCache>
#include <qpa/qwindowsysteminterface.h>
+#include <private/qhighdpiscaling_p.h>
#include <private/qsystemlibrary_p.h>
#include <algorithm>
@@ -495,7 +495,8 @@ static QPixmap loadIconFromShell32(int resourceId, QSizeF size)
QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &size) const
{
- const int scaleFactor = QWindowsScaling::factor();
+ const QScreen *primaryScreen = QGuiApplication::primaryScreen();
+ const int scaleFactor = primaryScreen ? qRound(QHighDpiScaling::factor(primaryScreen)) : 1;
const QSizeF pixmapSize = size * scaleFactor;
int resourceId = -1;
LPCTSTR iconName = 0;
@@ -632,7 +633,7 @@ public:
static FakePointer *create(T thing)
{
- return reinterpret_cast<FakePointer *>(thing);
+ return reinterpret_cast<FakePointer *>(qintptr(thing));
}
T operator * () const
@@ -720,6 +721,7 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
iconSize|SHGFI_SYSICONINDEX;
#endif // Q_OS_WINCE
unsigned long val = 0;
+#if !defined(QT_NO_WINCE_SHELLSDK)
if (cacheableDirIcon && useDefaultFolderIcon) {
flags |= SHGFI_USEFILEATTRIBUTES;
val = SHGetFileInfo(L"dummy",
@@ -729,6 +731,7 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
val = SHGetFileInfo(reinterpret_cast<const wchar_t *>(filePath.utf16()), 0,
&info, sizeof(SHFILEINFO), flags);
}
+#endif // !QT_NO_WINCE_SHELLSDK
// Even if GetFileInfo returns a valid result, hIcon can be empty in some cases
if (val && info.hIcon) {
diff --git a/src/plugins/platforms/windows/qwindowswindow.cpp b/src/plugins/platforms/windows/qwindowswindow.cpp
index 288f73cb8f..f9b34334df 100644
--- a/src/plugins/platforms/windows/qwindowswindow.cpp
+++ b/src/plugins/platforms/windows/qwindowswindow.cpp
@@ -36,7 +36,6 @@
#include "qwindowscontext.h"
#include "qwindowsdrag.h"
#include "qwindowsscreen.h"
-#include "qwindowsscaling.h"
#include "qwindowsintegration.h"
#include "qwindowsopenglcontext.h"
#ifdef QT_NO_CURSOR
@@ -49,8 +48,9 @@
#include <QtGui/QRegion>
#include <QtGui/QOpenGLContext>
#include <private/qsystemlibrary_p.h>
-#include <private/qwindow_p.h>
+#include <private/qwindow_p.h> // QWINDOWSIZE_MAX
#include <private/qguiapplication_p.h>
+#include <private/qhighdpiscaling_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <QtCore/QDebug>
@@ -169,7 +169,7 @@ static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
const QWindowsScreen *screen = screenManager.screens().size() == 1
? screenManager.screens().first() : screenManager.screenAtDp(point);
if (screen)
- return screen->availableGeometryDp().topLeft() - screen->geometryDp().topLeft();
+ return screen->availableGeometry().topLeft() - screen->geometry().topLeft();
#else
Q_UNUSED(hwnd)
Q_UNUSED(point)
@@ -608,9 +608,7 @@ QWindowsWindowData
const QString windowClassName = QWindowsContext::instance()->registerWindowClass(w);
- const QRect geometryDip = QWindowsScaling::mapFromNative(data.geometry);
- QRect fixedGeometryDip = QPlatformWindow::initialGeometry(w, geometryDip, defaultWindowWidth, defaultWindowHeight);
- const QRect rect = fixedGeometryDip != geometryDip ? QWindowsScaling::mapToNative(fixedGeometryDip) : data.geometry;
+ const QRect rect = QPlatformWindow::initialGeometry(w, data.geometry, defaultWindowWidth, defaultWindowHeight);
if (title.isEmpty() && (result.flags & Qt::WindowTitleHint))
title = topLevel ? qAppName() : w->objectName();
@@ -706,6 +704,20 @@ void WindowCreationData::initialize(const QWindow *w, HWND hwnd, bool frameChang
}
}
+
+// Scaling helpers for size constraints.
+static QSize toNativeSizeConstrained(QSize dip, const QWindow *w)
+{
+ if (QHighDpiScaling::isActive()) {
+ const qreal factor = QHighDpiScaling::factor(w);
+ if (dip.width() > 0 && dip.width() < QWINDOWSIZE_MAX)
+ dip.rwidth() *= factor;
+ if (dip.height() > 0 && dip.height() < QWINDOWSIZE_MAX)
+ dip.rheight() *= factor;
+ }
+ return dip;
+}
+
/*!
\class QWindowsGeometryHint
\brief Stores geometry constraints and provides utility functions.
@@ -718,8 +730,8 @@ void WindowCreationData::initialize(const QWindow *w, HWND hwnd, bool frameChang
*/
QWindowsGeometryHint::QWindowsGeometryHint(const QWindow *w, const QMargins &cm) :
- minimumSize(QWindowsScaling::mapToNativeConstrained(w->minimumSize())),
- maximumSize(QWindowsScaling::mapToNativeConstrained(w->maximumSize())),
+ minimumSize(toNativeSizeConstrained(w->minimumSize(), w)),
+ maximumSize(toNativeSizeConstrained(w->maximumSize(), w)),
customMargins(cm)
{
}
@@ -953,8 +965,7 @@ void QWindowsWindow::fireExpose(const QRegion &region, bool force)
clearFlag(Exposed);
else
setFlag(Exposed);
- QWindowSystemInterface::handleExposeEvent(window(),
- QWindowsScaling::mapFromNative(region));
+ QWindowSystemInterface::handleExposeEvent(window(), region);
}
static inline QWindow *findTransientChild(const QWindow *parent)
@@ -1134,7 +1145,7 @@ bool QWindowsWindow::isEmbedded(const QPlatformWindow *parentWindow) const
return m_data.embedded;
}
-QPoint QWindowsWindow::mapToGlobalDp(const QPoint &pos) const
+QPoint QWindowsWindow::mapToGlobal(const QPoint &pos) const
{
if (m_data.hwnd)
return QWindowsGeometryHint::mapToGlobal(m_data.hwnd, pos);
@@ -1142,7 +1153,7 @@ QPoint QWindowsWindow::mapToGlobalDp(const QPoint &pos) const
return pos;
}
-QPoint QWindowsWindow::mapFromGlobalDp(const QPoint &pos) const
+QPoint QWindowsWindow::mapFromGlobal(const QPoint &pos) const
{
if (m_data.hwnd)
return QWindowsGeometryHint::mapFromGlobal(m_data.hwnd, pos);
@@ -1323,22 +1334,22 @@ static QRect normalFrameGeometry(HWND hwnd)
return QRect();
}
-QRect QWindowsWindow::normalGeometryDp() const
+QRect QWindowsWindow::normalGeometry() const
{
// Check for fake 'fullscreen' mode.
const bool fakeFullScreen = m_savedFrameGeometry.isValid() && window()->windowState() == Qt::WindowFullScreen;
const QRect frame = fakeFullScreen ? m_savedFrameGeometry : normalFrameGeometry(m_data.hwnd);
- const QMargins margins = fakeFullScreen ? QWindowsGeometryHint::frame(m_savedStyle, 0) : frameMarginsDp();
+ const QMargins margins = fakeFullScreen ? QWindowsGeometryHint::frame(m_savedStyle, 0) : frameMargins();
return frame.isValid() ? frame.marginsRemoved(margins) : frame;
}
-void QWindowsWindow::setGeometryDp(const QRect &rectIn)
+void QWindowsWindow::setGeometry(const QRect &rectIn)
{
QRect rect = rectIn;
// This means it is a call from QWindow::setFramePosition() and
// the coordinates include the frame (size is still the contents rectangle).
if (QWindowsGeometryHint::positionIncludesFrame(window())) {
- const QMargins margins = frameMarginsDp();
+ const QMargins margins = frameMargins();
rect.moveTopLeft(rect.topLeft() + QPoint(margins.left(), margins.top()));
}
if (m_windowState == Qt::WindowMinimized)
@@ -1407,9 +1418,8 @@ void QWindowsWindow::handleGeometryChange()
return;
const QRect previousGeometry = m_data.geometry;
m_data.geometry = geometry_sys();
- const QRect geometryDip = QWindowsScaling::mapFromNative(m_data.geometry);
- QPlatformWindow::setGeometry(geometryDip);
- QWindowSystemInterface::handleGeometryChange(window(), geometryDip);
+ QPlatformWindow::setGeometry(m_data.geometry);
+ QWindowSystemInterface::handleGeometryChange(window(), m_data.geometry);
// QTBUG-32121: OpenGL/normal windows (with exception of ANGLE) do not receive
// expose events when shrinking, synthesize.
if (!testFlag(OpenGL_ES2) && isExposed()
@@ -1417,7 +1427,7 @@ void QWindowsWindow::handleGeometryChange()
fireExpose(QRect(QPoint(0, 0), m_data.geometry.size()), true);
}
if (previousGeometry.topLeft() != m_data.geometry.topLeft()) {
- QPlatformScreen *newScreen = screenForGeometry(geometryDip);
+ QPlatformScreen *newScreen = screenForGeometry(m_data.geometry);
if (newScreen != screen())
QWindowSystemInterface::handleWindowScreenChanged(window(), newScreen->screen());
}
@@ -1429,7 +1439,7 @@ void QWindowsWindow::handleGeometryChange()
void QWindowsWindow::setGeometry_sys(const QRect &rect) const
{
- const QMargins margins = frameMarginsDp();
+ const QMargins margins = frameMargins();
const QRect frameGeometry = rect + margins;
qCDebug(lcQpaWindows) << '>' << __FUNCTION__ << window()
@@ -1468,7 +1478,7 @@ QRect QWindowsWindow::frameGeometry_sys() const
QRect QWindowsWindow::geometry_sys() const
{
- return frameGeometry_sys().marginsRemoved(frameMarginsDp());
+ return frameGeometry_sys().marginsRemoved(frameMargins());
}
/*!
@@ -1540,7 +1550,7 @@ void QWindowsWindow::setWindowFlags(Qt::WindowFlags flags)
{
qCDebug(lcQpaWindows) << '>' << __FUNCTION__ << this << window() << "\n from: "
<< m_data.flags << "\n to: " << flags;
- const QRect oldGeometry = geometryDp();
+ const QRect oldGeometry = geometry();
if (m_data.flags != flags) {
m_data.flags = flags;
if (m_data.hwnd) {
@@ -1626,8 +1636,9 @@ void QWindowsWindow::setWindowState(Qt::WindowState state)
bool QWindowsWindow::isFullScreen_sys() const
{
- return window()->isTopLevel()
- && geometry_sys() == QWindowsScaling::mapToNative(window()->screen()->geometry());
+ const QWindow *w = window();
+ return w->isTopLevel()
+ && geometry_sys() == QHighDpi::toNativePixels(w->screen()->geometry(), w);
}
/*!
@@ -1697,15 +1708,14 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
// Use geometry of QWindow::screen() within creation or the virtual screen the
// window is in (QTBUG-31166, QTBUG-30724).
const QScreen *screen = window()->screen();
- const QRect rDip = screen->geometry();
- const QRect r = QWindowsScaling::mapToNative(rDip);
+ const QRect r = QHighDpi::toNativePixels(screen->geometry(), window());
const UINT swpf = SWP_FRAMECHANGED | SWP_NOACTIVATE;
const bool wasSync = testFlag(SynchronousGeometryChangeEvent);
setFlag(SynchronousGeometryChangeEvent);
SetWindowPos(m_data.hwnd, HWND_TOP, r.left(), r.top(), r.width(), r.height(), swpf);
if (!wasSync)
clearFlag(SynchronousGeometryChangeEvent);
- QWindowSystemInterface::handleGeometryChange(window(), rDip);
+ QWindowSystemInterface::handleGeometryChange(window(), r);
QWindowSystemInterface::flushWindowSystemEvents();
} else if (newState != Qt::WindowMinimized) {
// Restore saved state.
@@ -1804,7 +1814,7 @@ void QWindowsWindow::propagateSizeHints()
qCDebug(lcQpaWindows) << __FUNCTION__ << this << window();
}
-bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &marginsDp)
+bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &margins)
{
#ifndef Q_OS_WINCE
if (!qWindow->isTopLevel()) // Implement hasHeightForWidth().
@@ -1812,26 +1822,19 @@ bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *
WINDOWPOS *windowPos = reinterpret_cast<WINDOWPOS *>(message->lParam);
if ((windowPos->flags & (SWP_NOCOPYBITS | SWP_NOSIZE)))
return false;
- const QRect suggestedFrameGeometryDp(windowPos->x, windowPos->y,
- windowPos->cx, windowPos->cy);
- const qreal factor = QWindowsScaling::factor();
- const QRect suggestedGeometryDp = suggestedFrameGeometryDp - marginsDp;
- const QRectF suggestedGeometry = QRectF(QPointF(suggestedGeometryDp.topLeft()) / factor,
- QSizeF(suggestedGeometryDp.size()) / factor);
- const QRectF correctedGeometryF =
- qt_window_private(const_cast<QWindow *>(qWindow))->closestAcceptableGeometry(suggestedGeometry);
+ const QRect suggestedFrameGeometry(windowPos->x, windowPos->y,
+ windowPos->cx, windowPos->cy);
+ const QRect suggestedGeometry = suggestedFrameGeometry - margins;
+ const QRectF correctedGeometryF = qWindow->handle()->windowClosestAcceptableGeometry(suggestedGeometry);
if (!correctedGeometryF.isValid())
return false;
- const QRect correctedFrameGeometryDp
- = QRectF(correctedGeometryF.topLeft() * factor,
- correctedGeometryF.size() * factor).toRect()
- + marginsDp;
- if (correctedFrameGeometryDp == suggestedFrameGeometryDp)
+ const QRect correctedFrameGeometry = correctedGeometryF.toRect() + margins;
+ if (correctedFrameGeometry == suggestedFrameGeometry)
return false;
- windowPos->x = correctedFrameGeometryDp.left();
- windowPos->y = correctedFrameGeometryDp.top();
- windowPos->cx = correctedFrameGeometryDp.width();
- windowPos->cy = correctedFrameGeometryDp.height();
+ windowPos->x = correctedFrameGeometry.left();
+ windowPos->y = correctedFrameGeometry.top();
+ windowPos->cx = correctedFrameGeometry.width();
+ windowPos->cy = correctedFrameGeometry.height();
return true;
#else // !Q_OS_WINCE
Q_UNUSED(message)
@@ -1841,11 +1844,11 @@ bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *
bool QWindowsWindow::handleGeometryChanging(MSG *message) const
{
- const QMargins marginsDp = window()->isTopLevel() ? frameMarginsDp() : QMargins();
- return QWindowsWindow::handleGeometryChangingMessage(message, window(), marginsDp);
+ const QMargins margins = window()->isTopLevel() ? frameMargins() : QMargins();
+ return QWindowsWindow::handleGeometryChangingMessage(message, window(), margins);
}
-QMargins QWindowsWindow::frameMarginsDp() const
+QMargins QWindowsWindow::frameMargins() const
{
// Frames are invalidated by style changes (window state, flags).
// As they are also required for geometry calculations in resize
@@ -1892,17 +1895,17 @@ static inline void addRectToWinRegion(const QRect &rect, HRGN *winRegion)
}
}
-static HRGN qRegionToWinRegion(const QRegion &regionDip)
+static HRGN qRegionToWinRegion(const QRegion &region)
{
- const QVector<QRect> rects = regionDip.rects();
+ const QVector<QRect> rects = region.rects();
if (rects.isEmpty())
return NULL;
const int rectCount = rects.size();
if (rectCount == 1)
- return createRectRegion(QWindowsScaling::mapToNative(regionDip.boundingRect()));
- HRGN hRegion = createRectRegion(QWindowsScaling::mapToNative(rects.front()));
+ return createRectRegion(region.boundingRect());
+ HRGN hRegion = createRectRegion(rects.front());
for (int i = 1; i < rectCount; ++i)
- addRectToWinRegion(QWindowsScaling::mapToNative(rects.at(i)), &hRegion);
+ addRectToWinRegion(rects.at(i), &hRegion);
return hRegion;
}
@@ -1916,7 +1919,7 @@ void QWindowsWindow::setMask(const QRegion &region)
// Mask is in client area coordinates, so offset it in case we have a frame
if (window()->isTopLevel()) {
- const QMargins margins = frameMarginsDp();
+ const QMargins margins = frameMargins();
OffsetRgn(winRegion, margins.left(), margins.top());
}
@@ -2053,23 +2056,23 @@ bool QWindowsWindow::handleNonClientHitTest(const QPoint &globalPos, LRESULT *re
|| (m_data.flags & Qt::FramelessWindowHint)) {
return false;
}
- const QSize minimumSize = QWindowsScaling::mapToNativeConstrained(w->minimumSize());
+ const QSize minimumSize = w->minimumSize();
if (minimumSize.isEmpty())
return false;
- const QSize maximumSize = QWindowsScaling::mapToNativeConstrained(w->maximumSize());
+ const QSize maximumSize = w->maximumSize();
const bool fixedWidth = minimumSize.width() == maximumSize.width();
const bool fixedHeight = minimumSize.height() == maximumSize.height();
if (!fixedWidth && !fixedHeight)
return false;
- const QPoint localPos = mapFromGlobalDp(globalPos);
- const QSize size = w->size() * QWindowsScaling::factor();
+ const QPoint localPos = w->mapFromGlobal(QHighDpi::fromNativePixels(globalPos, w));
+ const QSize size = w->size();
if (fixedHeight) {
if (localPos.y() >= size.height()) {
*result = HTBORDER; // Unspecified border, no resize cursor.
return true;
}
if (localPos.y() < 0) {
- const QMargins margins = frameMarginsDp();
+ const QMargins margins = frameMargins();
const int topResizeBarPos = margins.left() - margins.top();
if (localPos.y() < topResizeBarPos) {
*result = HTCAPTION; // Extend caption over top resize bar, let's user move the window.
@@ -2245,10 +2248,6 @@ void QWindowsWindow::setWindowIcon(const QIcon &icon)
The property can be set using QPlatformNativeInterface::setWindowProperty() or,
before platform window creation, by setting a dynamic property
on the QWindow (see QWindowsIntegration::createPlatformWindow()).
-
- Note: The function uses (unscaled) device pixels since the QWizard also
- uses AdjustWindowRect() and using device independent pixels would introduce
- rounding errors.
*/
void QWindowsWindow::setCustomMargins(const QMargins &newCustomMargins)
diff --git a/src/plugins/platforms/windows/qwindowswindow.h b/src/plugins/platforms/windows/qwindowswindow.h
index fff90b4b11..d96022e3a5 100644
--- a/src/plugins/platforms/windows/qwindowswindow.h
+++ b/src/plugins/platforms/windows/qwindowswindow.h
@@ -38,7 +38,6 @@
#ifdef Q_OS_WINCE
# include "qplatformfunctions_wince.h"
#endif
-#include "qwindowsscaling.h"
#include "qwindowscursor.h"
#include <qpa/qplatformwindow.h>
@@ -145,28 +144,18 @@ public:
~QWindowsWindow();
QSurfaceFormat format() const Q_DECL_OVERRIDE { return m_format; }
- void setGeometryDp(const QRect &rectIn);
- void setGeometry(const QRect &rect) Q_DECL_OVERRIDE
- { setGeometryDp(QWindowsScaling::mapToNative(rect)); }
- QRect geometryDp() const { return m_data.geometry; }
- QRect geometry() const Q_DECL_OVERRIDE
- { return QWindowsScaling::mapFromNative(geometryDp()); }
- QRect normalGeometryDp() const;
- QRect normalGeometry() const Q_DECL_OVERRIDE
- { return QWindowsScaling::mapFromNative(normalGeometryDp()); }
- qreal devicePixelRatio() const Q_DECL_OVERRIDE
- { return qreal(QWindowsScaling::factor()); }
+ void setGeometry(const QRect &rect) Q_DECL_OVERRIDE;
+ QRect geometry() const Q_DECL_OVERRIDE { return m_data.geometry; }
+ QRect normalGeometry() const Q_DECL_OVERRIDE;
+
void setVisible(bool visible) Q_DECL_OVERRIDE;
bool isVisible() const;
bool isExposed() const Q_DECL_OVERRIDE { return testFlag(Exposed); }
bool isActive() const Q_DECL_OVERRIDE;
bool isEmbedded(const QPlatformWindow *parentWindow) const Q_DECL_OVERRIDE;
- QPoint mapToGlobalDp(const QPoint &pos) const;
- QPoint mapToGlobal(const QPoint &pos) const Q_DECL_OVERRIDE
- { return mapToGlobalDp(pos * QWindowsScaling::factor()) / QWindowsScaling::factor(); }
- QPoint mapFromGlobalDp(const QPoint &pos) const;
- QPoint mapFromGlobal(const QPoint &pos) const Q_DECL_OVERRIDE
- { return mapFromGlobalDp(pos * QWindowsScaling::factor()) / QWindowsScaling::factor(); }
+ QPoint mapToGlobal(const QPoint &pos) const Q_DECL_OVERRIDE;
+ QPoint mapFromGlobal(const QPoint &pos) const Q_DECL_OVERRIDE;
+
void setWindowFlags(Qt::WindowFlags flags) Q_DECL_OVERRIDE;
void setWindowState(Qt::WindowState state) Q_DECL_OVERRIDE;
@@ -184,8 +173,7 @@ public:
void propagateSizeHints() Q_DECL_OVERRIDE;
static bool handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &marginsDp);
bool handleGeometryChanging(MSG *message) const;
- QMargins frameMarginsDp() const;
- QMargins frameMargins() const Q_DECL_OVERRIDE { return frameMarginsDp() / QWindowsScaling::factor(); }
+ QMargins frameMargins() const Q_DECL_OVERRIDE;
void setOpacity(qreal level) Q_DECL_OVERRIDE;
void setMask(const QRegion &region) Q_DECL_OVERRIDE;
@@ -196,7 +184,7 @@ public:
bool setMouseGrabEnabled(bool grab) Q_DECL_OVERRIDE;
inline bool hasMouseCapture() const { return GetCapture() == m_data.hwnd; }
- bool startSystemResize(const QPoint &, Qt::Corner corner) Q_DECL_OVERRIDE;
+ bool startSystemResize(const QPoint &pos, Qt::Corner corner) Q_DECL_OVERRIDE;
void setFrameStrutEventsEnabled(bool enabled);
bool frameStrutEventsEnabled() const { return testFlag(FrameStrutEventsEnabled); }
diff --git a/src/plugins/platforms/windows/windows.pri b/src/plugins/platforms/windows/windows.pri
index de901aaeb1..6e5789a86e 100644
--- a/src/plugins/platforms/windows/windows.pri
+++ b/src/plugins/platforms/windows/windows.pri
@@ -40,7 +40,6 @@ SOURCES += \
$$PWD/qwindowsservices.cpp \
$$PWD/qwindowsnativeimage.cpp \
$$PWD/qwindowsnativeinterface.cpp \
- $$PWD/qwindowsscaling.cpp \
$$PWD/qwindowsopengltester.cpp
HEADERS += \
@@ -67,7 +66,6 @@ HEADERS += \
$$PWD/qplatformfunctions_wince.h \
$$PWD/qwindowsnativeimage.h \
$$PWD/qwindowsnativeinterface.h \
- $$PWD/qwindowsscaling.h \
$$PWD/qwindowsopengltester.h
INCLUDEPATH += $$PWD
diff --git a/src/plugins/platforms/winrt/qwinrtcursor.cpp b/src/plugins/platforms/winrt/qwinrtcursor.cpp
index 94ce23bd2c..707f3bf0ba 100644
--- a/src/plugins/platforms/winrt/qwinrtcursor.cpp
+++ b/src/plugins/platforms/winrt/qwinrtcursor.cpp
@@ -36,11 +36,13 @@
#include "qwinrtcursor.h"
#include "qwinrtscreen.h"
+#include <private/qeventdispatcher_winrt_p.h>
#include <QtCore/qfunctions_winrt.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QScreen>
+#include <functional>
#include <wrl.h>
#include <windows.ui.core.h>
#include <windows.foundation.h>
@@ -77,12 +79,17 @@ void QWinRTCursor::changeCursor(QCursor *windowCursor, QWindow *window)
{
Q_D(QWinRTCursor);
+ HRESULT hr;
ICoreWindow *coreWindow = static_cast<QWinRTScreen *>(window->screen()->handle())->coreWindow();
CoreCursorType type;
switch (windowCursor ? windowCursor->shape() : Qt::ArrowCursor) {
case Qt::BlankCursor:
- coreWindow->put_PointerCursor(Q_NULLPTR);
+ hr = QEventDispatcherWinRT::runOnXamlThread([coreWindow]() {
+ coreWindow->put_PointerCursor(Q_NULLPTR);
+ return S_OK;
+ });
+ RETURN_VOID_IF_FAILED("Failed to set blank native cursor");
return;
default:
case Qt::OpenHandCursor:
@@ -142,11 +149,13 @@ void QWinRTCursor::changeCursor(QCursor *windowCursor, QWindow *window)
}
ComPtr<ICoreCursor> cursor;
- HRESULT hr = d->cursorFactory->CreateCursor(type, 0, &cursor);
+ hr = d->cursorFactory->CreateCursor(type, 0, &cursor);
RETURN_VOID_IF_FAILED("Failed to create native cursor.");
- hr = coreWindow->put_PointerCursor(cursor.Get());
- RETURN_VOID_IF_FAILED("Failed to set native cursor.");
+ hr = QEventDispatcherWinRT::runOnXamlThread([coreWindow, &cursor]() {
+ return coreWindow->put_PointerCursor(cursor.Get());
+ });
+ RETURN_VOID_IF_FAILED("Failed to set native cursor");
}
#endif // QT_NO_CURSOR
@@ -154,8 +163,12 @@ QPoint QWinRTCursor::pos() const
{
ICoreWindow *coreWindow =
static_cast<QWinRTScreen *>(QGuiApplication::primaryScreen()->handle())->coreWindow();
+ HRESULT hr;
Point point;
- coreWindow->get_PointerPosition(&point);
+ hr = QEventDispatcherWinRT::runOnXamlThread([coreWindow, &point]() {
+ return coreWindow->get_PointerPosition(&point);
+ });
+ RETURN_IF_FAILED("Failed to get native cursor position", QPoint());
return QPoint(point.X, point.Y);
}
diff --git a/src/plugins/platforms/winrt/qwinrteglcontext.cpp b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
index 42ffe8f716..44aab266ca 100644
--- a/src/plugins/platforms/winrt/qwinrteglcontext.cpp
+++ b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
@@ -35,38 +35,131 @@
****************************************************************************/
#include "qwinrteglcontext.h"
+#include "qwinrtwindow.h"
+#include <private/qeventdispatcher_winrt_p.h>
+#include <functional>
+
+#include <EGL/egl.h>
#define EGL_EGLEXT_PROTOTYPES
-#include "EGL/eglext.h"
+#include <EGL/eglext.h>
+
+#include <QOpenGLContext>
+#include <QtPlatformSupport/private/qeglconvenience_p.h>
QT_BEGIN_NAMESPACE
-QWinRTEGLContext::QWinRTEGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display, EGLSurface surface, EGLConfig config)
- : QEGLPlatformContext(format, share, display, &config), m_eglSurface(surface)
+class QWinRTEGLContextPrivate
+{
+public:
+ QSurfaceFormat format;
+ EGLDisplay eglDisplay;
+ EGLConfig eglConfig;
+ EGLContext eglContext;
+ QHash<QPlatformSurface *, EGLSurface> surfaceForWindow;
+};
+
+QWinRTEGLContext::QWinRTEGLContext(QOpenGLContext *context)
+ : d_ptr(new QWinRTEGLContextPrivate)
+{
+ Q_D(QWinRTEGLContext);
+ d->format = context->format();
+ d->format.setRenderableType(QSurfaceFormat::OpenGLES);
+}
+
+QWinRTEGLContext::~QWinRTEGLContext()
{
+ Q_D(QWinRTEGLContext);
+ foreach (const EGLSurface &surface, d->surfaceForWindow)
+ eglDestroySurface(d->eglDisplay, surface);
+ if (d->eglContext != EGL_NO_CONTEXT)
+ eglDestroyContext(d->eglDisplay, d->eglContext);
+ if (d->eglDisplay != EGL_NO_DISPLAY)
+ eglTerminate(d->eglDisplay);
}
-void QWinRTEGLContext::swapBuffers(QPlatformSurface *surface)
+void QWinRTEGLContext::initialize()
{
-#ifdef Q_OS_WINPHONE
- const QSize size = surface->surface()->size();
- eglPostSubBufferNV(eglDisplay(), eglSurfaceForPlatformSurface(surface),
- 0, 0, size.width(), size.height());
-#else
- eglSwapBuffers(eglDisplay(), eglSurfaceForPlatformSurface(surface));
-#endif
+ Q_D(QWinRTEGLContext);
+
+ eglBindAPI(EGL_OPENGL_ES_API);
+ d->eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
+ if (d->eglDisplay == EGL_NO_DISPLAY)
+ qCritical("Failed to initialize EGL display: 0x%x", eglGetError());
+
+ if (!eglInitialize(d->eglDisplay, nullptr, nullptr))
+ qCritical("Failed to initialize EGL: 0x%x", eglGetError());
+
+ d->eglConfig = q_configFromGLFormat(d->eglDisplay, d->format);
+
+ const EGLint flags = d->format.testOption(QSurfaceFormat::DebugContext)
+ ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0;
+ const EGLint attributes[] = {
+ EGL_CONTEXT_CLIENT_VERSION, d->format.majorVersion(),
+ EGL_CONTEXT_MINOR_VERSION_KHR, d->format.minorVersion(),
+ EGL_CONTEXT_FLAGS_KHR, flags,
+ EGL_NONE
+ };
+ d->eglContext = eglCreateContext(d->eglDisplay, d->eglConfig, nullptr, attributes);
+ if (d->eglContext == EGL_NO_CONTEXT) {
+ qWarning("QEGLPlatformContext: Failed to create context: %x", eglGetError());
+ return;
+ }
}
-EGLSurface QWinRTEGLContext::eglSurfaceForPlatformSurface(QPlatformSurface *surface)
+bool QWinRTEGLContext::makeCurrent(QPlatformSurface *windowSurface)
{
- if (surface->surface()->surfaceClass() == QSurface::Window) {
- // All windows use the same surface
- return m_eglSurface;
- } else {
- // TODO: return EGL surfaces for offscreen surfaces
- qWarning("This plugin does not support offscreen surfaces.");
- return EGL_NO_SURFACE;
+ Q_D(QWinRTEGLContext);
+ Q_ASSERT(windowSurface->surface()->surfaceType() == QSurface::OpenGLSurface);
+
+ EGLSurface surface = d->surfaceForWindow.value(windowSurface);
+ if (surface == EGL_NO_SURFACE) {
+ QWinRTWindow *window = static_cast<QWinRTWindow *>(windowSurface);
+ HRESULT hr = QEventDispatcherWinRT::runOnXamlThread([this, d, window, &surface]() {
+ surface = eglCreateWindowSurface(d->eglDisplay, d->eglConfig,
+ reinterpret_cast<EGLNativeWindowType>(window->winId()),
+ nullptr);
+ if (surface == EGL_NO_SURFACE) {
+ qCritical("Failed to create EGL window surface: 0x%x", eglGetError());
+ return E_FAIL;
+ }
+ return S_OK;
+ });
+ if (FAILED(hr))
+ return false;
+ d->surfaceForWindow.insert(windowSurface, surface);
}
+
+ const bool ok = eglMakeCurrent(d->eglDisplay, surface, surface, d->eglContext);
+ if (!ok) {
+ qWarning("QEGLPlatformContext: eglMakeCurrent failed: %x", eglGetError());
+ return false;
+ }
+
+ eglSwapInterval(d->eglDisplay, d->format.swapInterval());
+ return true;
+}
+
+void QWinRTEGLContext::doneCurrent()
+{
+ Q_D(const QWinRTEGLContext);
+ const bool ok = eglMakeCurrent(d->eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+ if (!ok)
+ qWarning("QEGLPlatformContext: eglMakeCurrent failed: %x", eglGetError());
+}
+
+void QWinRTEGLContext::swapBuffers(QPlatformSurface *windowSurface)
+{
+ Q_D(QWinRTEGLContext);
+ Q_ASSERT(windowSurface->surface()->surfaceType() == QSurface::OpenGLSurface);
+
+ eglSwapBuffers(d->eglDisplay, d->surfaceForWindow.value(windowSurface));
+}
+
+QSurfaceFormat QWinRTEGLContext::format() const
+{
+ Q_D(const QWinRTEGLContext);
+ return d->format;
}
QFunctionPointer QWinRTEGLContext::getProcAddress(const QByteArray &procName)
@@ -221,7 +314,7 @@ QFunctionPointer QWinRTEGLContext::getProcAddress(const QByteArray &procName)
if (i != standardFuncs.end())
return i.value();
- return QEGLPlatformContext::getProcAddress(procName);
+ return eglGetProcAddress(procName.constData());
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrteglcontext.h b/src/plugins/platforms/winrt/qwinrteglcontext.h
index 958d623c4c..31a2124b03 100644
--- a/src/plugins/platforms/winrt/qwinrteglcontext.h
+++ b/src/plugins/platforms/winrt/qwinrteglcontext.h
@@ -37,23 +37,29 @@
#ifndef QWINDOWSEGLCONTEXT_H
#define QWINDOWSEGLCONTEXT_H
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
+#include <qpa/qplatformopenglcontext.h>
QT_BEGIN_NAMESPACE
-class QWinRTEGLContext : public QEGLPlatformContext
+class QWinRTEGLContextPrivate;
+class QWinRTEGLContext : public QPlatformOpenGLContext
{
public:
- explicit QWinRTEGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display, EGLSurface surface, EGLConfig config);
+ explicit QWinRTEGLContext(QOpenGLContext *context);
+ ~QWinRTEGLContext();
- void swapBuffers(QPlatformSurface *surface) Q_DECL_OVERRIDE;
- QFunctionPointer getProcAddress(const QByteArray &procName) Q_DECL_OVERRIDE;
+ void initialize() Q_DECL_OVERRIDE;
+
+ bool makeCurrent(QPlatformSurface *windowSurface) Q_DECL_OVERRIDE;
+ void doneCurrent() Q_DECL_OVERRIDE;
+ void swapBuffers(QPlatformSurface *windowSurface) Q_DECL_OVERRIDE;
-protected:
- EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface);
+ QSurfaceFormat format() const Q_DECL_OVERRIDE;
+ QFunctionPointer getProcAddress(const QByteArray &procName) Q_DECL_OVERRIDE;
private:
- EGLSurface m_eglSurface;
+ QScopedPointer<QWinRTEGLContextPrivate> d_ptr;
+ Q_DECLARE_PRIVATE(QWinRTEGLContext)
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp b/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp
index 09edea52e7..c348faf015 100644
--- a/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp
+++ b/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp
@@ -39,13 +39,11 @@
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
-#ifdef QT_WINRT_USE_DWRITE
#include <QtCore/QUuid>
#include <QtGui/private/qfontengine_ft_p.h>
#include <dwrite_1.h>
#include <wrl.h>
using namespace Microsoft::WRL;
-#endif // QT_WINRT_USE_DWRITE
QT_BEGIN_NAMESPACE
@@ -122,9 +120,7 @@ QString QWinRTFontDatabase::fontDir() const
const QString applicationDirPath = QCoreApplication::applicationDirPath();
fontDirectory = applicationDirPath + QLatin1String("/fonts");
if (!QFile::exists(fontDirectory)) {
-#ifdef QT_WINRT_USE_DWRITE
if (m_fontFamilies.isEmpty())
-#endif
qWarning("No fonts directory found in application package.");
fontDirectory = applicationDirPath;
}
@@ -132,8 +128,6 @@ QString QWinRTFontDatabase::fontDir() const
return fontDirectory;
}
-#ifdef QT_WINRT_USE_DWRITE
-
QWinRTFontDatabase::~QWinRTFontDatabase()
{
foreach (IDWriteFontFile *fontFile, m_fonts.keys())
@@ -449,13 +443,4 @@ void QWinRTFontDatabase::releaseHandle(void *handle)
QBasicFontDatabase::releaseHandle(handle);
}
-#else // QT_WINRT_USE_DWRITE
-
-QFont QWinRTFontDatabase::defaultFont() const
-{
- return QFont(QFontDatabase().families().value(0));
-}
-
-#endif // !QT_WINRT_USE_DWRITE
-
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtfontdatabase.h b/src/plugins/platforms/winrt/qwinrtfontdatabase.h
index 7b3f402c13..a88092e432 100644
--- a/src/plugins/platforms/winrt/qwinrtfontdatabase.h
+++ b/src/plugins/platforms/winrt/qwinrtfontdatabase.h
@@ -39,26 +39,21 @@
#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
-#ifdef QT_WINRT_USE_DWRITE
struct IDWriteFontFile;
struct IDWriteFontFamily;
-#endif
QT_BEGIN_NAMESPACE
-#ifdef QT_WINRT_USE_DWRITE
struct FontDescription
{
quint32 index;
QByteArray uuid;
};
-#endif
class QWinRTFontDatabase : public QBasicFontDatabase
{
public:
QString fontDir() const;
-#ifdef QT_WINRT_USE_DWRITE
~QWinRTFontDatabase();
QFont defaultFont() const Q_DECL_OVERRIDE;
bool fontsAlwaysScalable() const Q_DECL_OVERRIDE;
@@ -69,7 +64,6 @@ public:
private:
QHash<IDWriteFontFile *, FontDescription> m_fonts;
QHash<QString, IDWriteFontFamily *> m_fontFamilies;
-#endif // QT_WINRT_USE_DWRITE
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtinputcontext.cpp b/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
index c94b53ef1c..f3b390b4d6 100644
--- a/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
+++ b/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
@@ -37,7 +37,9 @@
#include "qwinrtinputcontext.h"
#include "qwinrtscreen.h"
#include <QtGui/QWindow>
+#include <private/qeventdispatcher_winrt_p.h>
+#include <functional>
#include <wrl.h>
#include <roapi.h>
#include <windows.ui.viewmanagement.h>
@@ -163,10 +165,14 @@ void QWinRTInputContext::showInputPanel()
if (FAILED(hr))
return;
- boolean success;
- hr = inputPane->TryShow(&success);
- if (FAILED(hr))
- qErrnoWarning(hr, "Failed to show input panel.");
+ QEventDispatcherWinRT::runOnXamlThread([&inputPane]() {
+ HRESULT hr;
+ boolean success;
+ hr = inputPane->TryShow(&success);
+ if (FAILED(hr) || !success)
+ qErrnoWarning(hr, "Failed to show input panel.");
+ return hr;
+ });
}
void QWinRTInputContext::hideInputPanel()
@@ -176,141 +182,16 @@ void QWinRTInputContext::hideInputPanel()
if (FAILED(hr))
return;
- boolean success;
- hr = inputPane->TryHide(&success);
- if (FAILED(hr))
- qErrnoWarning(hr, "Failed to hide input panel.");
-}
-
-#else // Q_OS_WINPHONE
-
-// IRawElementProviderSimple
-HRESULT QWinRTInputContext::get_ProviderOptions(ProviderOptions *retVal)
-{
- *retVal = ProviderOptions_ServerSideProvider|ProviderOptions_UseComThreading;
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::GetPatternProvider(PATTERNID id, IUnknown **retVal)
-{
- switch (id) {
- case 10002: //UIA_ValuePatternId
- return QueryInterface(__uuidof(IValueProvider), (void**)retVal);
- break;
- case 10014: //UIA_TextPatternId:
- return QueryInterface(__uuidof(ITextProvider), (void**)retVal);
- case 10029: //UIA_TextChildPatternId:
- *retVal = nullptr;
- break;
- default:
- qWarning("Unhandled pattern ID: %d", id);
- break;
- }
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::GetPropertyValue(PROPERTYID idProp, VARIANT *retVal)
-{
- switch (idProp) {
- case 30003: //UIA_ControlTypePropertyId
- retVal->vt = VT_I4;
- retVal->lVal = 50025; //UIA_CustomControlTypeId
- break;
- case 30008: //UIA_IsKeyboardFocusablePropertyId
- case 30009: //UIA_HasKeyboardFocusPropertyId
- // These are probably never actually called
- case 30016: //UIA_IsControlElementPropertyId
- case 30017: //UIA_IsContentElementPropertyId
- retVal->vt = VT_BOOL;
- retVal->boolVal = VARIANT_TRUE;
- break;
- case 30019: //UIA_IsPasswordPropertyId
- retVal->vt = VT_BOOL;
- retVal->boolVal = VARIANT_FALSE;
- break;
- case 30020: //UIA_NativeWindowHandlePropertyId
- retVal->vt = VT_PTR;
- retVal->punkVal = m_screen->coreWindow();
- break;
- }
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::get_HostRawElementProvider(IRawElementProviderSimple **retVal)
-{
- // Return the window's element provider
- IInspectable *hostProvider;
- HRESULT hr = m_screen->coreWindow()->get_AutomationHostProvider(&hostProvider);
- if (SUCCEEDED(hr)) {
- hr = hostProvider->QueryInterface(IID_PPV_ARGS(retVal));
- hostProvider->Release();
- }
- return hr;
-}
-
-// ITextProvider
-HRESULT QWinRTInputContext::GetSelection(SAFEARRAY **)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::GetVisibleRanges(SAFEARRAY **)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::RangeFromChild(IRawElementProviderSimple *,ITextRangeProvider **)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::RangeFromPoint(UiaPoint, ITextRangeProvider **)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::get_DocumentRange(ITextRangeProvider **)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::get_SupportedTextSelection(SupportedTextSelection *)
-{
- // To be useful, requires listening to the focus object for a selection change and raising an event
- return S_OK;
-}
-
-// IValueProvider
-HRESULT QWinRTInputContext::SetValue(LPCWSTR)
-{
- // To be useful, requires listening to the focus object for a value change and raising an event
- // May be useful for inputPanel autocomplete, etc.
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::get_Value(BSTR *)
-{
- // To be useful, requires listening to the focus object for a value change and raising an event
- // May be useful for inputPanel autocomplete, etc.
- return S_OK;
-}
-
-HRESULT QWinRTInputContext::get_IsReadOnly(BOOL *isReadOnly)
-{
- // isReadOnly dictates keyboard opening behavior when view is tapped.
- // We need to decide if the user tapped within a control which is about to receive focus...
- // Since this isn't possible (this function gets called before we receive the touch event),
- // the most platform-aligned option is to show the keyboard if an editable item has focus,
- // and close the keyboard if it is already open.
- *isReadOnly = m_isInputPanelVisible || !inputMethodAccepted();
- return S_OK;
+ QEventDispatcherWinRT::runOnXamlThread([&inputPane]() {
+ HRESULT hr;
+ boolean success;
+ hr = inputPane->TryHide(&success);
+ if (FAILED(hr) || !success)
+ qErrnoWarning(hr, "Failed to hide input panel.");
+ return hr;
+ });
}
-#endif // !Q_OS_WINPHONE
+#endif // Q_OS_WINPHONE
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtinputcontext.h b/src/plugins/platforms/winrt/qwinrtinputcontext.h
index ce7fbabf49..cc3bce435f 100644
--- a/src/plugins/platforms/winrt/qwinrtinputcontext.h
+++ b/src/plugins/platforms/winrt/qwinrtinputcontext.h
@@ -41,9 +41,6 @@
#include <QtCore/QRectF>
#include <wrl.h>
-#ifndef Q_OS_WINPHONE
-# include <UIAutomationCore.h>
-#endif
namespace ABI {
namespace Windows {
@@ -63,11 +60,6 @@ QT_BEGIN_NAMESPACE
class QWinRTScreen;
class QWinRTInputContext : public QPlatformInputContext
-#ifndef Q_OS_WINPHONE
- , public Microsoft::WRL::RuntimeClass<
- Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>,
- IRawElementProviderSimple, ITextProvider, IValueProvider>
-#endif // !Q_OS_WINPHONE
{
public:
explicit QWinRTInputContext(QWinRTScreen *);
@@ -79,26 +71,7 @@ public:
#ifdef Q_OS_WINPHONE
void showInputPanel();
void hideInputPanel();
-#else // Q_OS_WINPHONE
- // IRawElementProviderSimple
- HRESULT __stdcall get_ProviderOptions(ProviderOptions *retVal);
- HRESULT __stdcall GetPatternProvider(PATTERNID, IUnknown **);
- HRESULT __stdcall GetPropertyValue(PROPERTYID idProp, VARIANT *retVal);
- HRESULT __stdcall get_HostRawElementProvider(IRawElementProviderSimple **retVal);
-
- // ITextProvider
- HRESULT __stdcall GetSelection(SAFEARRAY **);
- HRESULT __stdcall GetVisibleRanges(SAFEARRAY **);
- HRESULT __stdcall RangeFromChild(IRawElementProviderSimple *,ITextRangeProvider **);
- HRESULT __stdcall RangeFromPoint(UiaPoint, ITextRangeProvider **);
- HRESULT __stdcall get_DocumentRange(ITextRangeProvider **);
- HRESULT __stdcall get_SupportedTextSelection(SupportedTextSelection *);
-
- // IValueProvider
- HRESULT __stdcall SetValue(LPCWSTR);
- HRESULT __stdcall get_Value(BSTR *);
- HRESULT __stdcall get_IsReadOnly(BOOL *);
-#endif // !Q_OS_WINPHONE
+#endif
private:
HRESULT onShowing(ABI::Windows::UI::ViewManagement::IInputPane *,
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.cpp b/src/plugins/platforms/winrt/qwinrtintegration.cpp
index 70ee6dbe6a..7079d46523 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.cpp
+++ b/src/plugins/platforms/winrt/qwinrtintegration.cpp
@@ -45,37 +45,138 @@
#include "qwinrtfontdatabase.h"
#include "qwinrttheme.h"
+#include <QtCore/QCoreApplication>
+#include <QtGui/QSurface>
#include <QtGui/QOpenGLContext>
+#include <qfunctions_winrt.h>
+#include <functional>
#include <wrl.h>
+#include <windows.ui.xaml.h>
+#include <windows.applicationmodel.h>
+#include <windows.applicationmodel.core.h>
#include <windows.ui.core.h>
#include <windows.ui.viewmanagement.h>
-#include <Windows.ApplicationModel.core.h>
+#include <windows.graphics.display.h>
+#ifdef Q_OS_WINPHONE
+# include <windows.phone.ui.input.h>
+#endif
using namespace Microsoft::WRL;
+using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::ApplicationModel;
+using namespace ABI::Windows::ApplicationModel::Core;
+using namespace ABI::Windows::UI;
using namespace ABI::Windows::UI::Core;
using namespace ABI::Windows::UI::ViewManagement;
+using namespace ABI::Windows::Graphics::Display;
using namespace ABI::Windows::ApplicationModel::Core;
+#ifdef Q_OS_WINPHONE
+using namespace ABI::Windows::Phone::UI::Input;
+#endif
+
+typedef IEventHandler<IInspectable *> ResumeHandler;
+typedef IEventHandler<SuspendingEventArgs *> SuspendHandler;
+#ifdef Q_OS_WINPHONE
+typedef IEventHandler<BackPressedEventArgs*> BackPressedHandler;
+#endif
QT_BEGIN_NAMESPACE
-QWinRTIntegration::QWinRTIntegration()
- : m_success(false)
- , m_fontDatabase(new QWinRTFontDatabase)
- , m_services(new QWinRTServices)
+typedef HRESULT (__stdcall ICoreApplication::*CoreApplicationCallbackRemover)(EventRegistrationToken);
+uint qHash(CoreApplicationCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
+#ifdef Q_OS_WINPHONE
+typedef HRESULT (__stdcall IHardwareButtonsStatics::*HardwareButtonsCallbackRemover)(EventRegistrationToken);
+uint qHash(HardwareButtonsCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
+#endif
+
+class QWinRTIntegrationPrivate
+{
+public:
+ QPlatformFontDatabase *fontDatabase;
+ QPlatformServices *platformServices;
+ QWinRTScreen *mainScreen;
+ QScopedPointer<QWinRTInputContext> inputContext;
+
+ ComPtr<ICoreApplication> application;
+ QHash<CoreApplicationCallbackRemover, EventRegistrationToken> applicationTokens;
+#ifdef Q_OS_WINPHONE
+ ComPtr<IHardwareButtonsStatics> hardwareButtons;
+ QHash<HardwareButtonsCallbackRemover, EventRegistrationToken> buttonsTokens;
+#endif
+};
+
+QWinRTIntegration::QWinRTIntegration() : d_ptr(new QWinRTIntegrationPrivate)
{
- m_screen = new QWinRTScreen;
- screenAdded(m_screen);
+ Q_D(QWinRTIntegration);
+
+ d->fontDatabase = new QWinRTFontDatabase;
+
+ HRESULT hr;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(),
+ IID_PPV_ARGS(&d->application));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = d->application->add_Suspending(Callback<SuspendHandler>(this, &QWinRTIntegration::onSuspended).Get(),
+ &d->applicationTokens[&ICoreApplication::remove_Resuming]);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = d->application->add_Resuming(Callback<ResumeHandler>(this, &QWinRTIntegration::onResume).Get(),
+ &d->applicationTokens[&ICoreApplication::remove_Resuming]);
+ Q_ASSERT_SUCCEEDED(hr);
- m_success = true;
+#ifdef Q_OS_WINPHONE
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
+ IID_PPV_ARGS(&d->hardwareButtons));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = d->hardwareButtons->add_BackPressed(Callback<BackPressedHandler>(this, &QWinRTIntegration::onBackButtonPressed).Get(),
+ &d->buttonsTokens[&IHardwareButtonsStatics::remove_BackPressed]);
+ Q_ASSERT_SUCCEEDED(hr);
+#endif // Q_OS_WINPHONE
+
+ hr = QEventDispatcherWinRT::runOnXamlThread([this, d]() {
+ HRESULT hr;
+ ComPtr<Xaml::IWindowStatics> windowStatics;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Window).Get(),
+ IID_PPV_ARGS(&windowStatics));
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Xaml::IWindow> window;
+ hr = windowStatics->get_Current(&window);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = window->Activate();
+ Q_ASSERT_SUCCEEDED(hr);
+
+ d->mainScreen = new QWinRTScreen(window.Get());
+ d->inputContext.reset(new QWinRTInputContext(d->mainScreen));
+ screenAdded(d->mainScreen);
+ return S_OK;
+ });
+ Q_ASSERT_SUCCEEDED(hr);
}
QWinRTIntegration::~QWinRTIntegration()
{
+ Q_D(QWinRTIntegration);
+ HRESULT hr;
+#ifdef Q_OS_WINPHONE
+ for (QHash<HardwareButtonsCallbackRemover, EventRegistrationToken>::const_iterator i = d->buttonsTokens.begin(); i != d->buttonsTokens.end(); ++i) {
+ hr = (d->hardwareButtons.Get()->*i.key())(i.value());
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+#endif
+ for (QHash<CoreApplicationCallbackRemover, EventRegistrationToken>::const_iterator i = d->applicationTokens.begin(); i != d->applicationTokens.end(); ++i) {
+ hr = (d->application.Get()->*i.key())(i.value());
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+ destroyScreen(d->mainScreen);
Windows::Foundation::Uninitialize();
}
+bool QWinRTIntegration::succeeded() const
+{
+ Q_D(const QWinRTIntegration);
+ return d->mainScreen;
+}
+
QAbstractEventDispatcher *QWinRTIntegration::createEventDispatcher() const
{
return new QWinRTEventDispatcher;
@@ -112,28 +213,31 @@ QPlatformBackingStore *QWinRTIntegration::createPlatformBackingStore(QWindow *wi
QPlatformOpenGLContext *QWinRTIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
{
- QWinRTScreen *screen = static_cast<QWinRTScreen *>(context->screen()->handle());
- return new QWinRTEGLContext(context->format(), context->handle(), screen->eglDisplay(), screen->eglSurface(), screen->eglConfig());
+ return new QWinRTEGLContext(context);
}
QPlatformFontDatabase *QWinRTIntegration::fontDatabase() const
{
- return m_fontDatabase;
+ Q_D(const QWinRTIntegration);
+ return d->fontDatabase;
}
QPlatformInputContext *QWinRTIntegration::inputContext() const
{
- return m_screen->inputContext();
+ Q_D(const QWinRTIntegration);
+ return d->inputContext.data();
}
QPlatformServices *QWinRTIntegration::services() const
{
- return m_services;
+ Q_D(const QWinRTIntegration);
+ return d->platformServices;
}
Qt::KeyboardModifiers QWinRTIntegration::queryKeyboardModifiers() const
{
- return m_screen->keyboardModifiers();
+ Q_D(const QWinRTIntegration);
+ return d->mainScreen->keyboardModifiers();
}
QStringList QWinRTIntegration::themeNames() const
@@ -149,4 +253,45 @@ name) const
return 0;
}
+
+// System-level integration points
+
+#ifdef Q_OS_WINPHONE
+HRESULT QWinRTIntegration::onBackButtonPressed(IInspectable *, IBackPressedEventArgs *args)
+{
+ Q_D(QWinRTIntegration);
+
+ QKeyEvent backPress(QEvent::KeyPress, Qt::Key_Back, Qt::NoModifier);
+ QKeyEvent backRelease(QEvent::KeyRelease, Qt::Key_Back, Qt::NoModifier);
+ backPress.setAccepted(false);
+ backRelease.setAccepted(false);
+
+ QWindow *window = d->mainScreen->topWindow();
+ QObject *receiver = window ? static_cast<QObject *>(window)
+ : static_cast<QObject *>(QCoreApplication::instance());
+
+ // If the event is ignored, the app go to the background
+ QCoreApplication::sendEvent(receiver, &backPress);
+ QCoreApplication::sendEvent(receiver, &backRelease);
+ args->put_Handled(backPress.isAccepted() || backRelease.isAccepted());
+
+ return S_OK;
+}
+#endif // Q_OS_WINPHONE
+
+HRESULT QWinRTIntegration::onSuspended(IInspectable *, ISuspendingEventArgs *)
+{
+ QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationSuspended);
+ QWindowSystemInterface::flushWindowSystemEvents();
+ return S_OK;
+}
+
+HRESULT QWinRTIntegration::onResume(IInspectable *, IInspectable *)
+{
+ // First the system invokes onResume and then changes
+ // the visibility of the screen to be active.
+ QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationHidden);
+ return S_OK;
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.h b/src/plugins/platforms/winrt/qwinrtintegration.h
index bbd6c1e41b..0115e034b5 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.h
+++ b/src/plugins/platforms/winrt/qwinrtintegration.h
@@ -39,11 +39,33 @@
#include <qpa/qplatformintegration.h>
+namespace ABI {
+ namespace Windows {
+ namespace ApplicationModel {
+ struct ISuspendingEventArgs;
+ }
+ namespace Foundation {
+ struct IAsyncAction;
+ }
+#ifdef Q_OS_WINPHONE
+ namespace Phone {
+ namespace UI {
+ namespace Input {
+ struct IBackPressedEventArgs;
+ }
+ }
+ }
+#endif
+ }
+}
+struct IAsyncInfo;
+struct IInspectable;
+
QT_BEGIN_NAMESPACE
class QAbstractEventDispatcher;
-class QWinRTScreen;
+class QWinRTIntegrationPrivate;
class QWinRTIntegration : public QPlatformIntegration
{
private:
@@ -53,10 +75,12 @@ public:
static QWinRTIntegration *create()
{
- QWinRTIntegration *integration = new QWinRTIntegration;
- return integration->m_success ? integration : 0;
+ QScopedPointer<QWinRTIntegration> integration(new QWinRTIntegration);
+ return integration->succeeded() ? integration.take() : nullptr;
}
+ bool succeeded() const;
+
bool hasCapability(QPlatformIntegration::Capability cap) const;
QVariant styleHint(StyleHint hint) const;
@@ -71,11 +95,16 @@ public:
QStringList themeNames() const;
QPlatformTheme *createPlatformTheme(const QString &name) const;
+
private:
- bool m_success;
- QWinRTScreen *m_screen;
- QPlatformFontDatabase *m_fontDatabase;
- QPlatformServices *m_services;
+#ifdef Q_OS_WINPHONE
+ HRESULT onBackButtonPressed(IInspectable *, ABI::Windows::Phone::UI::Input::IBackPressedEventArgs *args);
+#endif
+ HRESULT onSuspended(IInspectable *, ABI::Windows::ApplicationModel::ISuspendingEventArgs *);
+ HRESULT onResume(IInspectable *, IInspectable *);
+
+ QScopedPointer<QWinRTIntegrationPrivate> d_ptr;
+ Q_DECLARE_PRIVATE(QWinRTIntegration)
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.cpp b/src/plugins/platforms/winrt/qwinrtscreen.cpp
index 1d36bb31f6..2a7cbaa159 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.cpp
+++ b/src/plugins/platforms/winrt/qwinrtscreen.cpp
@@ -36,26 +36,18 @@
#include "qwinrtscreen.h"
-#define EGL_EGLEXT_PROTOTYPES
-#include <EGL/eglext.h>
-#include <d3d11.h>
-#include <dxgi1_2.h>
-#ifndef Q_OS_WINPHONE
-#include <dxgi1_3.h>
-#endif
-
#include "qwinrtbackingstore.h"
#include "qwinrtinputcontext.h"
#include "qwinrtcursor.h"
-#include "qwinrteglcontext.h"
+#include <private/qeventdispatcher_winrt_p.h>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QGuiApplication>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <QtCore/qt_windows.h>
#include <QtCore/qfunctions_winrt.h>
+#include <functional>
#include <wrl.h>
#include <windows.system.h>
#include <Windows.Applicationmodel.h>
@@ -64,12 +56,10 @@
#include <windows.ui.h>
#include <windows.ui.core.h>
#include <windows.ui.input.h>
+#include <windows.ui.xaml.h>
#include <windows.ui.viewmanagement.h>
#include <windows.graphics.display.h>
#include <windows.foundation.h>
-#ifdef Q_OS_WINPHONE
-#include <windows.phone.ui.input.h>
-#endif
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
@@ -77,17 +67,13 @@ using namespace ABI::Windows::ApplicationModel;
using namespace ABI::Windows::ApplicationModel::Core;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System;
+using namespace ABI::Windows::UI;
using namespace ABI::Windows::UI::Core;
using namespace ABI::Windows::UI::Input;
using namespace ABI::Windows::UI::ViewManagement;
using namespace ABI::Windows::Devices::Input;
using namespace ABI::Windows::Graphics::Display;
-#ifdef Q_OS_WINPHONE
-using namespace ABI::Windows::Phone::UI::Input;
-#endif
-typedef IEventHandler<IInspectable*> ResumeHandler;
-typedef IEventHandler<SuspendingEventArgs*> SuspendHandler;
typedef ITypedEventHandler<CoreWindow*, WindowActivatedEventArgs*> ActivatedHandler;
typedef ITypedEventHandler<CoreWindow*, CoreWindowEventArgs*> ClosedHandler;
typedef ITypedEventHandler<CoreWindow*, CharacterReceivedEventArgs*> CharacterReceivedHandler;
@@ -96,11 +82,7 @@ typedef ITypedEventHandler<CoreWindow*, KeyEventArgs*> KeyHandler;
typedef ITypedEventHandler<CoreWindow*, PointerEventArgs*> PointerHandler;
typedef ITypedEventHandler<CoreWindow*, WindowSizeChangedEventArgs*> SizeChangedHandler;
typedef ITypedEventHandler<CoreWindow*, VisibilityChangedEventArgs*> VisibilityChangedHandler;
-typedef ITypedEventHandler<CoreWindow*, AutomationProviderRequestedEventArgs*> AutomationProviderRequestedHandler;
typedef ITypedEventHandler<DisplayInformation*, IInspectable*> DisplayInformationHandler;
-#ifdef Q_OS_WINPHONE
-typedef IEventHandler<BackPressedEventArgs*> BackPressedHandler;
-#endif
QT_BEGIN_NAMESPACE
@@ -419,33 +401,26 @@ static inline Qt::Key qKeyFromCode(quint32 code, int mods)
return static_cast<Qt::Key>(code & 0xff);
}
-typedef HRESULT (__stdcall ICoreApplication::*CoreApplicationCallbackRemover)(EventRegistrationToken);
-uint qHash(CoreApplicationCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
typedef HRESULT (__stdcall ICoreWindow::*CoreWindowCallbackRemover)(EventRegistrationToken);
uint qHash(CoreWindowCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
typedef HRESULT (__stdcall IDisplayInformation::*DisplayCallbackRemover)(EventRegistrationToken);
uint qHash(DisplayCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
-#ifdef Q_OS_WINPHONE
-typedef HRESULT (__stdcall IHardwareButtonsStatics::*HardwareButtonsCallbackRemover)(EventRegistrationToken);
-uint qHash(HardwareButtonsCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
-#endif
class QWinRTScreenPrivate
{
public:
- ComPtr<ICoreApplication> application;
+ QTouchDevice *touchDevice;
ComPtr<ICoreWindow> coreWindow;
+ ComPtr<Xaml::IDependencyObject> canvas;
+ ComPtr<IApplicationView> view;
ComPtr<IDisplayInformation> displayInformation;
#ifdef Q_OS_WINPHONE
- ComPtr<IHardwareButtonsStatics> hardwareButtons;
-#endif
+ ComPtr<IStatusBar> statusBar;
+#endif // Q_OS_WINPHONE
QScopedPointer<QWinRTCursor> cursor;
-#ifdef Q_OS_WINPHONE
- QScopedPointer<QWinRTInputContext> inputContext;
-#else
- ComPtr<QWinRTInputContext> inputContext;
-#endif
+
+ QHash<quint32, QWindowSystemInterface::TouchPoint> touchPoints;
QSizeF logicalSize;
QSurfaceFormat surfaceFormat;
@@ -458,68 +433,30 @@ public:
#ifndef Q_OS_WINPHONE
QHash<quint32, QPair<Qt::Key, QString>> activeKeys;
#endif
- QTouchDevice *touchDevice;
- QHash<quint32, QWindowSystemInterface::TouchPoint> touchPoints;
- EGLDisplay eglDisplay;
- EGLSurface eglSurface;
- EGLConfig eglConfig;
-
- QHash<CoreApplicationCallbackRemover, EventRegistrationToken> applicationTokens;
QHash<CoreWindowCallbackRemover, EventRegistrationToken> windowTokens;
QHash<DisplayCallbackRemover, EventRegistrationToken> displayTokens;
-#ifdef Q_OS_WINPHONE
- QHash<HardwareButtonsCallbackRemover, EventRegistrationToken> buttonsTokens;
-#endif
};
-QWinRTScreen::QWinRTScreen()
+// To be called from the XAML thread
+QWinRTScreen::QWinRTScreen(Xaml::IWindow *xamlWindow)
: d_ptr(new QWinRTScreenPrivate)
{
Q_D(QWinRTScreen);
d->orientation = Qt::PrimaryOrientation;
d->touchDevice = Q_NULLPTR;
- d->eglDisplay = EGL_NO_DISPLAY;
- // Obtain the WinRT Application, view, and window
HRESULT hr;
- hr = RoGetActivationFactory(Wrappers::HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(),
- IID_PPV_ARGS(&d->application));
- Q_ASSERT_SUCCEEDED(hr);
- hr = d->application->add_Suspending(Callback<SuspendHandler>(this, &QWinRTScreen::onSuspended).Get(), &d->applicationTokens[&ICoreApplication::remove_Resuming]);
- Q_ASSERT_SUCCEEDED(hr);
- hr = d->application->add_Resuming(Callback<ResumeHandler>(this, &QWinRTScreen::onResume).Get(), &d->applicationTokens[&ICoreApplication::remove_Resuming]);
- Q_ASSERT_SUCCEEDED(hr);
-
- ComPtr<ICoreApplicationView> view;
- hr = d->application->GetCurrentView(&view);
- Q_ASSERT_SUCCEEDED(hr);
- hr = view->get_CoreWindow(&d->coreWindow);
+ hr = xamlWindow->get_CoreWindow(&d->coreWindow);
Q_ASSERT_SUCCEEDED(hr);
hr = d->coreWindow->Activate();
Q_ASSERT_SUCCEEDED(hr);
-#ifdef Q_OS_WINPHONE
- d->inputContext.reset(new QWinRTInputContext(this));
-#else
- d->inputContext = Make<QWinRTInputContext>(this);
-#endif
-
Rect rect;
hr = d->coreWindow->get_Bounds(&rect);
Q_ASSERT_SUCCEEDED(hr);
d->logicalSize = QSizeF(rect.Width, rect.Height);
- d->surfaceFormat.setAlphaBufferSize(0);
- d->surfaceFormat.setRedBufferSize(8);
- d->surfaceFormat.setGreenBufferSize(8);
- d->surfaceFormat.setBlueBufferSize(8);
- d->surfaceFormat.setDepthBufferSize(24);
- d->surfaceFormat.setStencilBufferSize(8);
- d->surfaceFormat.setRenderableType(QSurfaceFormat::OpenGLES);
- d->surfaceFormat.setSamples(1);
- d->surfaceFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
-
hr = d->coreWindow->add_KeyDown(Callback<KeyHandler>(this, &QWinRTScreen::onKeyDown).Get(), &d->windowTokens[&ICoreWindow::remove_KeyDown]);
Q_ASSERT_SUCCEEDED(hr);
hr = d->coreWindow->add_KeyUp(Callback<KeyHandler>(this, &QWinRTScreen::onKeyUp).Get(), &d->windowTokens[&ICoreWindow::remove_KeyUp]);
@@ -538,24 +475,14 @@ QWinRTScreen::QWinRTScreen()
Q_ASSERT_SUCCEEDED(hr);
hr = d->coreWindow->add_PointerWheelChanged(Callback<PointerHandler>(this, &QWinRTScreen::onPointerUpdated).Get(), &d->windowTokens[&ICoreWindow::remove_PointerWheelChanged]);
Q_ASSERT_SUCCEEDED(hr);
-#ifndef Q_OS_WINPHONE
hr = d->coreWindow->add_SizeChanged(Callback<SizeChangedHandler>(this, &QWinRTScreen::onSizeChanged).Get(), &d->windowTokens[&ICoreWindow::remove_SizeChanged]);
Q_ASSERT_SUCCEEDED(hr);
-#endif
hr = d->coreWindow->add_Activated(Callback<ActivatedHandler>(this, &QWinRTScreen::onActivated).Get(), &d->windowTokens[&ICoreWindow::remove_Activated]);
Q_ASSERT_SUCCEEDED(hr);
hr = d->coreWindow->add_Closed(Callback<ClosedHandler>(this, &QWinRTScreen::onClosed).Get(), &d->windowTokens[&ICoreWindow::remove_Closed]);
Q_ASSERT_SUCCEEDED(hr);
hr = d->coreWindow->add_VisibilityChanged(Callback<VisibilityChangedHandler>(this, &QWinRTScreen::onVisibilityChanged).Get(), &d->windowTokens[&ICoreWindow::remove_VisibilityChanged]);
Q_ASSERT_SUCCEEDED(hr);
- hr = d->coreWindow->add_AutomationProviderRequested(Callback<AutomationProviderRequestedHandler>(this, &QWinRTScreen::onAutomationProviderRequested).Get(), &d->windowTokens[&ICoreWindow::remove_AutomationProviderRequested]);
- Q_ASSERT_SUCCEEDED(hr);
-#ifdef Q_OS_WINPHONE
- hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(), IID_PPV_ARGS(&d->hardwareButtons));
- Q_ASSERT_SUCCEEDED(hr);
- hr = d->hardwareButtons->add_BackPressed(Callback<BackPressedHandler>(this, &QWinRTScreen::onBackButtonPressed).Get(), &d->buttonsTokens[&IHardwareButtonsStatics::remove_BackPressed]);
- Q_ASSERT_SUCCEEDED(hr);
-#endif // Q_OS_WINPHONE
// Orientation handling
ComPtr<IDisplayInformationStatics> displayInformationStatics;
@@ -583,45 +510,43 @@ QWinRTScreen::QWinRTScreen()
d->orientation = d->nativeOrientation;
onOrientationChanged(Q_NULLPTR, Q_NULLPTR);
- d->eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
- if (d->eglDisplay == EGL_NO_DISPLAY)
- qCritical("Failed to initialize EGL display: 0x%x", eglGetError());
-
- if (!eglInitialize(d->eglDisplay, NULL, NULL))
- qCritical("Failed to initialize EGL: 0x%x", eglGetError());
-
- // Check that the device properly supports depth/stencil rendering, and disable them if not
- ComPtr<ID3D11Device> d3dDevice;
- const EGLBoolean ok = eglQuerySurfacePointerANGLE(d->eglDisplay, EGL_NO_SURFACE, EGL_DEVICE_EXT, (void **)d3dDevice.GetAddressOf());
- if (ok && d3dDevice) {
- ComPtr<IDXGIDevice> dxgiDevice;
- hr = d3dDevice.As(&dxgiDevice);
- if (SUCCEEDED(hr)) {
- ComPtr<IDXGIAdapter> dxgiAdapter;
- hr = dxgiDevice->GetAdapter(&dxgiAdapter);
- if (SUCCEEDED(hr)) {
- ComPtr<IDXGIAdapter2> dxgiAdapter2;
- hr = dxgiAdapter.As(&dxgiAdapter2);
- if (SUCCEEDED(hr)) {
- DXGI_ADAPTER_DESC2 desc;
- hr = dxgiAdapter2->GetDesc2(&desc);
- if (SUCCEEDED(hr)) {
- // The following GPUs do not render properly with depth/stencil
- if ((desc.VendorId == 0x4d4f4351 && desc.DeviceId == 0x32303032)) { // Qualcomm Adreno 225
- d->surfaceFormat.setDepthBufferSize(-1);
- d->surfaceFormat.setStencilBufferSize(-1);
- }
- }
- }
- }
- }
- }
+ ComPtr<IApplicationViewStatics2> applicationViewStatics;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_ViewManagement_ApplicationView).Get(),
+ IID_PPV_ARGS(&applicationViewStatics));
+ RETURN_VOID_IF_FAILED("Could not get ApplicationViewStatics");
+
+ hr = applicationViewStatics->GetForCurrentView(&d->view);
+ RETURN_VOID_IF_FAILED("Could not access currentView");
+
+ // Create a canvas and set it as the window content. Eventually, this should have its own method so multiple "screens" can be added
+ ComPtr<Xaml::Controls::ICanvas> canvas;
+ hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Controls_Canvas).Get(), &canvas);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Xaml::IFrameworkElement> frameworkElement;
+ hr = canvas.As(&frameworkElement);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = frameworkElement->put_Width(d->logicalSize.width());
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = frameworkElement->put_Height(d->logicalSize.height());
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Xaml::IUIElement> uiElement;
+ hr = canvas.As(&uiElement);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = xamlWindow->put_Content(uiElement.Get());
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = canvas.As(&d->canvas);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ d->cursor.reset(new QWinRTCursor);
- d->eglConfig = q_configFromGLFormat(d->eglDisplay, d->surfaceFormat);
- d->surfaceFormat = q_glFormatFromConfig(d->eglDisplay, d->eglConfig, d->surfaceFormat);
- d->eglSurface = eglCreateWindowSurface(d->eglDisplay, d->eglConfig, d->coreWindow.Get(), NULL);
- if (d->eglSurface == EGL_NO_SURFACE)
- qCritical("Failed to create EGL window surface: 0x%x", eglGetError());
+#ifdef Q_OS_WINPHONE
+ ComPtr<IStatusBarStatics> statusBarStatics;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_ViewManagement_StatusBar).Get(),
+ IID_PPV_ARGS(&statusBarStatics));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = statusBarStatics->GetForCurrentView(&d->statusBar);
+ Q_ASSERT_SUCCEEDED(hr);
+#endif // Q_OS_WINPHONE
}
QWinRTScreen::~QWinRTScreen()
@@ -629,16 +554,20 @@ QWinRTScreen::~QWinRTScreen()
Q_D(QWinRTScreen);
// Unregister callbacks
- for (QHash<CoreApplicationCallbackRemover, EventRegistrationToken>::const_iterator i = d->applicationTokens.begin(); i != d->applicationTokens.end(); ++i)
- (d->application.Get()->*i.key())(i.value());
- for (QHash<CoreWindowCallbackRemover, EventRegistrationToken>::const_iterator i = d->windowTokens.begin(); i != d->windowTokens.end(); ++i)
- (d->coreWindow.Get()->*i.key())(i.value());
- for (QHash<DisplayCallbackRemover, EventRegistrationToken>::const_iterator i = d->displayTokens.begin(); i != d->displayTokens.end(); ++i)
- (d->displayInformation.Get()->*i.key())(i.value());
-#ifdef Q_OS_WINPHONE
- for (QHash<HardwareButtonsCallbackRemover, EventRegistrationToken>::const_iterator i = d->buttonsTokens.begin(); i != d->buttonsTokens.end(); ++i)
- (d->hardwareButtons.Get()->*i.key())(i.value());
-#endif
+ HRESULT hr;
+ hr = QEventDispatcherWinRT::runOnXamlThread([this, d]() {
+ HRESULT hr;
+ for (QHash<CoreWindowCallbackRemover, EventRegistrationToken>::const_iterator i = d->windowTokens.begin(); i != d->windowTokens.end(); ++i) {
+ hr = (d->coreWindow.Get()->*i.key())(i.value());
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+ for (QHash<DisplayCallbackRemover, EventRegistrationToken>::const_iterator i = d->displayTokens.begin(); i != d->displayTokens.end(); ++i) {
+ hr = (d->displayInformation.Get()->*i.key())(i.value());
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+ return hr;
+ });
+ RETURN_VOID_IF_FAILED("Failed to unregister screen event callbacks");
}
QRect QWinRTScreen::geometry() const
@@ -657,12 +586,6 @@ QImage::Format QWinRTScreen::format() const
return QImage::Format_ARGB32_Premultiplied;
}
-QSurfaceFormat QWinRTScreen::surfaceFormat() const
-{
- Q_D(const QWinRTScreen);
- return d->surfaceFormat;
-}
-
QSizeF QWinRTScreen::physicalSize() const
{
Q_D(const QWinRTScreen);
@@ -682,21 +605,9 @@ qreal QWinRTScreen::scaleFactor() const
return d->scaleFactor;
}
-QWinRTInputContext *QWinRTScreen::inputContext() const
-{
- Q_D(const QWinRTScreen);
-#ifdef Q_OS_WINPHONE
- return d->inputContext.data();
-#else
- return d->inputContext.Get();
-#endif
-}
-
QPlatformCursor *QWinRTScreen::cursor() const
{
Q_D(const QWinRTScreen);
- if (!d->cursor)
- const_cast<QWinRTScreenPrivate *>(d)->cursor.reset(new QWinRTCursor);
return d->cursor.data();
}
@@ -744,22 +655,10 @@ ICoreWindow *QWinRTScreen::coreWindow() const
return d->coreWindow.Get();
}
-EGLDisplay QWinRTScreen::eglDisplay() const
+Xaml::IDependencyObject *QWinRTScreen::canvas() const
{
Q_D(const QWinRTScreen);
- return d->eglDisplay;
-}
-
-EGLSurface QWinRTScreen::eglSurface() const
-{
- Q_D(const QWinRTScreen);
- return d->eglSurface;
-}
-
-EGLConfig QWinRTScreen::eglConfig() const
-{
- Q_D(const QWinRTScreen);
- return d->eglConfig;
+ return d->canvas.Get();
}
QWindow *QWinRTScreen::topWindow() const
@@ -773,6 +672,19 @@ void QWinRTScreen::addWindow(QWindow *window)
Q_D(QWinRTScreen);
if (window == topWindow())
return;
+
+#ifdef Q_OS_WINPHONE
+ if (d->statusBar && (window->flags() & Qt::WindowType_Mask) == Qt::Window) {
+ QEventDispatcherWinRT::runOnXamlThread([this, d]() {
+ HRESULT hr;
+ ComPtr<IAsyncAction> op;
+ hr = d->statusBar->HideAsync(&op);
+ Q_ASSERT_SUCCEEDED(hr);
+ return S_OK;
+ });
+ }
+#endif // Q_OS_WINPHONE
+
d->visibleWindows.prepend(window);
QWindowSystemInterface::handleWindowActivated(window, Qt::OtherFocusReason);
handleExpose();
@@ -809,6 +721,20 @@ void QWinRTScreen::lower(QWindow *window)
handleExpose();
}
+void QWinRTScreen::updateWindowTitle()
+{
+ Q_D(QWinRTScreen);
+
+ QWindow *window = topWindow();
+ if (!window)
+ return;
+
+ const QString title = window->title();
+ HStringReference titleRef(reinterpret_cast<LPCWSTR>(title.utf16()), title.length());
+ HRESULT hr = d->view->put_Title(titleRef.Get());
+ RETURN_VOID_IF_FAILED("Unable to set window title");
+}
+
void QWinRTScreen::handleExpose()
{
Q_D(QWinRTScreen);
@@ -1055,17 +981,6 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
return S_OK;
}
-HRESULT QWinRTScreen::onAutomationProviderRequested(ICoreWindow *, IAutomationProviderRequestedEventArgs *args)
-{
-#ifndef Q_OS_WINPHONE
- Q_D(const QWinRTScreen);
- args->put_AutomationProvider(d->inputContext.Get());
-#else
- Q_UNUSED(args)
-#endif
- return S_OK;
-}
-
HRESULT QWinRTScreen::onSizeChanged(ICoreWindow *, IWindowSizeChangedEventArgs *)
{
Q_D(QWinRTScreen);
@@ -1075,18 +990,14 @@ HRESULT QWinRTScreen::onSizeChanged(ICoreWindow *, IWindowSizeChangedEventArgs *
hr = d->coreWindow->get_Bounds(&size);
RETURN_OK_IF_FAILED("Failed to get window bounds");
QSizeF logicalSize = QSizeF(size.Width, size.Height);
-#ifndef Q_OS_WINPHONE // This handler is called from orientation changed, in which case we should always update the size
if (d->logicalSize == logicalSize)
return S_OK;
-#endif
d->logicalSize = logicalSize;
- if (d->eglDisplay) {
- const QRect newGeometry = geometry();
- QWindowSystemInterface::handleScreenGeometryChange(screen(), newGeometry, newGeometry);
- QPlatformScreen::resizeMaximizedWindows();
- handleExpose();
- }
+ const QRect newGeometry = geometry();
+ QWindowSystemInterface::handleScreenGeometryChange(screen(), newGeometry, newGeometry);
+ QPlatformScreen::resizeMaximizedWindows();
+ handleExpose();
return S_OK;
}
@@ -1110,31 +1021,6 @@ HRESULT QWinRTScreen::onActivated(ICoreWindow *, IWindowActivatedEventArgs *args
return S_OK;
}
-HRESULT QWinRTScreen::onSuspended(IInspectable *, ISuspendingEventArgs *)
-{
-#ifndef Q_OS_WINPHONE
- Q_D(QWinRTScreen);
- ComPtr<ID3D11Device> d3dDevice;
- const EGLBoolean ok = eglQuerySurfacePointerANGLE(d->eglDisplay, EGL_NO_SURFACE, EGL_DEVICE_EXT, (void **)d3dDevice.GetAddressOf());
- if (ok && d3dDevice) {
- ComPtr<IDXGIDevice3> dxgiDevice;
- if (SUCCEEDED(d3dDevice.As(&dxgiDevice)))
- dxgiDevice->Trim();
- }
-#endif
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationSuspended);
- QWindowSystemInterface::flushWindowSystemEvents();
- return S_OK;
-}
-
-HRESULT QWinRTScreen::onResume(IInspectable *, IInspectable *)
-{
- // First the system invokes onResume and then changes
- // the visibility of the screen to be active.
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationHidden);
- return S_OK;
-}
-
HRESULT QWinRTScreen::onClosed(ICoreWindow *, ICoreWindowEventArgs *)
{
foreach (QWindow *w, QGuiApplication::topLevelWindows())
@@ -1165,10 +1051,6 @@ HRESULT QWinRTScreen::onOrientationChanged(IDisplayInformation *, IInspectable *
d->orientation = newOrientation;
QWindowSystemInterface::handleScreenOrientationChange(screen(), d->orientation);
}
-
-#ifdef Q_OS_WINPHONE // The size changed handler is ignored in favor of this callback
- onSizeChanged(Q_NULLPTR, Q_NULLPTR);
-#endif
return S_OK;
}
@@ -1205,27 +1087,4 @@ HRESULT QWinRTScreen::onDpiChanged(IDisplayInformation *, IInspectable *)
return S_OK;
}
-#ifdef Q_OS_WINPHONE
-HRESULT QWinRTScreen::onBackButtonPressed(IInspectable *, IBackPressedEventArgs *args)
-{
- Q_D(QWinRTScreen);
-
- QKeyEvent backPress(QEvent::KeyPress, Qt::Key_Back, Qt::NoModifier);
- QKeyEvent backRelease(QEvent::KeyRelease, Qt::Key_Back, Qt::NoModifier);
- backPress.setAccepted(false);
- backRelease.setAccepted(false);
-
- QObject *receiver = d->visibleWindows.isEmpty()
- ? static_cast<QObject *>(QGuiApplication::instance())
- : static_cast<QObject *>(d->visibleWindows.first());
-
- // If the event is ignored, the app will suspend
- QGuiApplication::sendEvent(receiver, &backPress);
- QGuiApplication::sendEvent(receiver, &backRelease);
- args->put_Handled(backPress.isAccepted() || backRelease.isAccepted());
-
- return S_OK;
-}
-#endif // Q_OS_WINPHONE
-
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.h b/src/plugins/platforms/winrt/qwinrtscreen.h
index d34ce75748..796e6abb80 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.h
+++ b/src/plugins/platforms/winrt/qwinrtscreen.h
@@ -40,8 +40,6 @@
#include <qpa/qplatformscreen.h>
#include <qpa/qwindowsysteminterface.h>
-#include <EGL/egl.h>
-
namespace ABI {
namespace Windows {
namespace ApplicationModel {
@@ -59,21 +57,16 @@ namespace ABI {
struct IWindowActivatedEventArgs;
struct IWindowSizeChangedEventArgs;
}
+ namespace Xaml {
+ struct IDependencyObject;
+ struct IWindow;
+ }
}
namespace Graphics {
namespace Display {
struct IDisplayInformation;
}
}
-#ifdef Q_OS_WINPHONE
- namespace Phone {
- namespace UI {
- namespace Input {
- struct IBackPressedEventArgs;
- }
- }
- }
-#endif
}
}
struct IInspectable;
@@ -81,23 +74,20 @@ struct IInspectable;
QT_BEGIN_NAMESPACE
class QTouchDevice;
-class QWinRTEGLContext;
class QWinRTCursor;
class QWinRTInputContext;
class QWinRTScreenPrivate;
class QWinRTScreen : public QPlatformScreen
{
public:
- explicit QWinRTScreen();
+ explicit QWinRTScreen(ABI::Windows::UI::Xaml::IWindow *xamlWindow);
~QWinRTScreen();
QRect geometry() const;
int depth() const;
QImage::Format format() const;
- QSurfaceFormat surfaceFormat() const;
QSizeF physicalSize() const Q_DECL_OVERRIDE;
QDpi logicalDpi() const Q_DECL_OVERRIDE;
qreal scaleFactor() const;
- QWinRTInputContext *inputContext() const;
QPlatformCursor *cursor() const;
Qt::KeyboardModifiers keyboardModifiers() const;
@@ -110,10 +100,10 @@ public:
void raise(QWindow *window);
void lower(QWindow *window);
+ void updateWindowTitle();
+
ABI::Windows::UI::Core::ICoreWindow *coreWindow() const;
- EGLDisplay eglDisplay() const; // To opengl context
- EGLSurface eglSurface() const; // To window
- EGLConfig eglConfig() const;
+ ABI::Windows::UI::Xaml::IDependencyObject *canvas() const;
private:
void handleExpose();
@@ -127,20 +117,13 @@ private:
HRESULT onSizeChanged(ABI::Windows::UI::Core::ICoreWindow *, ABI::Windows::UI::Core::IWindowSizeChangedEventArgs *);
HRESULT onActivated(ABI::Windows::UI::Core::ICoreWindow *, ABI::Windows::UI::Core::IWindowActivatedEventArgs *);
- HRESULT onSuspended(IInspectable *, ABI::Windows::ApplicationModel::ISuspendingEventArgs *);
- HRESULT onResume(IInspectable *, IInspectable *);
HRESULT onClosed(ABI::Windows::UI::Core::ICoreWindow *, ABI::Windows::UI::Core::ICoreWindowEventArgs *);
HRESULT onVisibilityChanged(ABI::Windows::UI::Core::ICoreWindow *, ABI::Windows::UI::Core::IVisibilityChangedEventArgs *);
- HRESULT onAutomationProviderRequested(ABI::Windows::UI::Core::ICoreWindow *, ABI::Windows::UI::Core::IAutomationProviderRequestedEventArgs *);
HRESULT onOrientationChanged(ABI::Windows::Graphics::Display::IDisplayInformation *, IInspectable *);
HRESULT onDpiChanged(ABI::Windows::Graphics::Display::IDisplayInformation *, IInspectable *);
-#ifdef Q_OS_WINPHONE
- HRESULT onBackButtonPressed(IInspectable *, ABI::Windows::Phone::UI::Input::IBackPressedEventArgs *args);
-#endif
-
QScopedPointer<QWinRTScreenPrivate> d_ptr;
Q_DECLARE_PRIVATE(QWinRTScreen)
};
diff --git a/src/plugins/platforms/winrt/qwinrtwindow.cpp b/src/plugins/platforms/winrt/qwinrtwindow.cpp
index adc5dfb776..634d62ef24 100644
--- a/src/plugins/platforms/winrt/qwinrtwindow.cpp
+++ b/src/plugins/platforms/winrt/qwinrtwindow.cpp
@@ -36,47 +36,138 @@
#include "qwinrtwindow.h"
#include "qwinrtscreen.h"
+#include <private/qeventdispatcher_winrt_p.h>
-#include <qpa/qwindowsysteminterface.h>
+#include <EGL/egl.h>
+#define EGL_EGLEXT_PROTOTYPES
+#include <EGL/eglext.h>
+
+#include <qfunctions_winrt.h>
#include <qpa/qplatformscreen.h>
+#include <qpa/qwindowsysteminterface.h>
#include <QtGui/QGuiApplication>
-#include <QtGui/QWindow>
#include <QtGui/QOpenGLContext>
+#include <QtGui/QWindow>
+#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <qfunctions_winrt.h>
-#include <windows.ui.viewmanagement.h>
+#include <functional>
#include <wrl.h>
+#include <windows.foundation.h>
+#include <windows.foundation.collections.h>
+#include <windows.ui.xaml.h>
+#include <windows.ui.xaml.controls.h>
+#include <windows.ui.viewmanagement.h>
using namespace ABI::Windows::UI::ViewManagement;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
+using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::Foundation::Collections;
+using namespace ABI::Windows::UI;
QT_BEGIN_NAMESPACE
+class QWinRTWindowPrivate
+{
+public:
+ QWinRTScreen *screen;
+
+ QSurfaceFormat surfaceFormat;
+ QString windowTitle;
+
+ ComPtr<Xaml::Controls::ISwapChainPanel> swapChainPanel;
+};
+
QWinRTWindow::QWinRTWindow(QWindow *window)
: QPlatformWindow(window)
- , m_screen(static_cast<QWinRTScreen*>(screen()))
+ , d_ptr(new QWinRTWindowPrivate)
{
+ Q_D(QWinRTWindow);
+
+ d->screen = static_cast<QWinRTScreen *>(screen());
setWindowFlags(window->flags());
setWindowState(window->windowState());
setWindowTitle(window->title());
handleContentOrientationChange(window->contentOrientation());
+
+ d->surfaceFormat.setAlphaBufferSize(0);
+ d->surfaceFormat.setRedBufferSize(8);
+ d->surfaceFormat.setGreenBufferSize(8);
+ d->surfaceFormat.setBlueBufferSize(8);
+ d->surfaceFormat.setDepthBufferSize(24);
+ d->surfaceFormat.setStencilBufferSize(8);
+ d->surfaceFormat.setRenderableType(QSurfaceFormat::OpenGLES);
+ d->surfaceFormat.setSamples(1);
+ d->surfaceFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
+
+ HRESULT hr;
+ hr = QEventDispatcherWinRT::runOnXamlThread([this, d]() {
+ // Create a new swapchain and place it inside the canvas
+ HRESULT hr;
+ hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Controls_SwapChainPanel).Get(),
+ &d->swapChainPanel);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Xaml::IUIElement> uiElement;
+ hr = d->swapChainPanel.As(&uiElement);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<Xaml::IDependencyObject> canvas = d->screen->canvas();
+ ComPtr<Xaml::Controls::IPanel> panel;
+ hr = canvas.As(&panel);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IVector<Xaml::UIElement *>> children;
+ hr = panel->get_Children(&children);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = children->Append(uiElement.Get());
+ Q_ASSERT_SUCCEEDED(hr);
+ return S_OK;
+ });
+ Q_ASSERT_SUCCEEDED(hr);
+
setGeometry(window->geometry());
}
QWinRTWindow::~QWinRTWindow()
{
- m_screen->removeWindow(window());
+ Q_D(QWinRTWindow);
+
+ HRESULT hr;
+ hr = QEventDispatcherWinRT::runOnXamlThread([d]() {
+ HRESULT hr;
+ ComPtr<Xaml::IDependencyObject> canvas = d->screen->canvas();
+ ComPtr<Xaml::Controls::IPanel> panel;
+ hr = canvas.As(&panel);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IVector<Xaml::UIElement *>> children;
+ hr = panel->get_Children(&children);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<Xaml::IUIElement> uiElement;
+ hr = d->swapChainPanel.As(&uiElement);
+ Q_ASSERT_SUCCEEDED(hr);
+ quint32 index;
+ boolean found;
+ hr = children->IndexOf(uiElement.Get(), &index, &found);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (found) {
+ hr = children->RemoveAt(index);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+ return S_OK;
+ });
+ RETURN_VOID_IF_FAILED("Failed to completely destroy window resources, likely because the application is shutting down");
}
QSurfaceFormat QWinRTWindow::format() const
{
- return m_screen->surfaceFormat();
+ Q_D(const QWinRTWindow);
+ return d->surfaceFormat;
}
bool QWinRTWindow::isActive() const
{
- return m_screen->topWindow() == window();
+ Q_D(const QWinRTWindow);
+ return d->screen->topWindow() == window();
}
bool QWinRTWindow::isExposed() const
@@ -87,55 +178,70 @@ bool QWinRTWindow::isExposed() const
void QWinRTWindow::setGeometry(const QRect &rect)
{
+ Q_D(QWinRTWindow);
+
if (window()->isTopLevel()) {
- QPlatformWindow::setGeometry(m_screen->geometry());
+ QPlatformWindow::setGeometry(d->screen->geometry());
QWindowSystemInterface::handleGeometryChange(window(), geometry());
} else {
QPlatformWindow::setGeometry(rect);
QWindowSystemInterface::handleGeometryChange(window(), rect);
}
+
+ HRESULT hr;
+ hr = QEventDispatcherWinRT::runOnXamlThread([this, d]() {
+ HRESULT hr;
+ ComPtr<Xaml::IFrameworkElement> frameworkElement;
+ hr = d->swapChainPanel.As(&frameworkElement);
+ Q_ASSERT_SUCCEEDED(hr);
+ const QSizeF size = QSizeF(geometry().size()) / d->screen->scaleFactor();
+ hr = frameworkElement->put_Width(size.width());
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = frameworkElement->put_Height(size.height());
+ Q_ASSERT_SUCCEEDED(hr);
+ return S_OK;
+ });
+ Q_ASSERT_SUCCEEDED(hr);
}
void QWinRTWindow::setVisible(bool visible)
{
+ Q_D(QWinRTWindow);
if (!window()->isTopLevel())
return;
if (visible)
- m_screen->addWindow(window());
+ d->screen->addWindow(window());
else
- m_screen->removeWindow(window());
+ d->screen->removeWindow(window());
}
void QWinRTWindow::setWindowTitle(const QString &title)
{
- ComPtr<IApplicationViewStatics2> statics;
- HRESULT hr;
-
- hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_ViewManagement_ApplicationView).Get(),
- IID_PPV_ARGS(&statics));
- RETURN_VOID_IF_FAILED("Could not get ApplicationViewStatics");
-
- ComPtr<IApplicationView> view;
- hr = statics->GetForCurrentView(&view);
- RETURN_VOID_IF_FAILED("Could not access currentView");
-
- HStringReference str(reinterpret_cast<LPCWSTR>(title.utf16()), title.length());
- hr = view->put_Title(str.Get());
- RETURN_VOID_IF_FAILED("Unable to set window title");
+ Q_D(QWinRTWindow);
+ d->windowTitle = title;
+ d->screen->updateWindowTitle();
}
void QWinRTWindow::raise()
{
+ Q_D(QWinRTWindow);
if (!window()->isTopLevel())
return;
- m_screen->raise(window());
+ d->screen->raise(window());
}
void QWinRTWindow::lower()
{
+ Q_D(QWinRTWindow);
if (!window()->isTopLevel())
return;
- m_screen->lower(window());
+ d->screen->lower(window());
+}
+
+WId QWinRTWindow::winId() const
+{
+ Q_D(const QWinRTWindow);
+ return WId(d->swapChainPanel.Get());
}
qreal QWinRTWindow::devicePixelRatio() const
diff --git a/src/plugins/platforms/winrt/qwinrtwindow.h b/src/plugins/platforms/winrt/qwinrtwindow.h
index 3cfe346ab2..88c149b080 100644
--- a/src/plugins/platforms/winrt/qwinrtwindow.h
+++ b/src/plugins/platforms/winrt/qwinrtwindow.h
@@ -42,8 +42,7 @@
QT_BEGIN_NAMESPACE
-class QWinRTScreen;
-
+class QWinRTWindowPrivate;
class QWinRTWindow : public QPlatformWindow
{
public:
@@ -59,10 +58,13 @@ public:
void raise();
void lower();
+ WId winId() const Q_DECL_OVERRIDE;
+
qreal devicePixelRatio() const Q_DECL_OVERRIDE;
private:
- QWinRTScreen *m_screen;
+ QScopedPointer<QWinRTWindowPrivate> d_ptr;
+ Q_DECLARE_PRIVATE(QWinRTWindow)
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/winrt.pro b/src/plugins/platforms/winrt/winrt.pro
index 80429daeed..2718ea62bb 100644
--- a/src/plugins/platforms/winrt/winrt.pro
+++ b/src/plugins/platforms/winrt/winrt.pro
@@ -1,14 +1,6 @@
TARGET = qwinrt
CONFIG -= precompile_header
-# For Windows Phone 8 we have to deploy fonts together with the application as DirectWrite
-# is not supported here.
-winphone:equals(WINSDK_VER, 8.0): {
- fonts.path = $$[QT_INSTALL_LIBS]/fonts
- fonts.files = $$QT_SOURCE_TREE/lib/fonts/DejaVu*.ttf
- INSTALLS += fonts
-}
-
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QWinRTIntegrationPlugin
!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
@@ -18,13 +10,8 @@ QT += core-private gui-private platformsupport-private
DEFINES *= QT_NO_CAST_FROM_ASCII __WRL_NO_DEFAULT_LIB__ GL_GLEXT_PROTOTYPES
-LIBS += $$QMAKE_LIBS_CORE
-
-!if(winphone:equals(WINSDK_VER, 8.0)) {
- LIBS += -ldwrite
- INCLUDEPATH += $$QT_SOURCE_TREE/src/3rdparty/freetype/include
- DEFINES += QT_WINRT_USE_DWRITE
-}
+LIBS += $$QMAKE_LIBS_CORE -ldwrite
+INCLUDEPATH += $$QT_SOURCE_TREE/src/3rdparty/freetype/include
SOURCES = \
main.cpp \
@@ -60,9 +47,4 @@ HEADERS = \
qwinrttheme.h \
qwinrtwindow.h
-winphone:equals(WINSDK_VER, 8.0): {
- SOURCES -= qwinrtplatformmessagedialoghelper.cpp
- HEADERS -= qwinrtplatformmessagedialoghelper.h
-}
-
OTHER_FILES += winrt.json
diff --git a/src/plugins/platforms/xcb/gl_integrations/qxcbglintegrationfactory.cpp b/src/plugins/platforms/xcb/gl_integrations/qxcbglintegrationfactory.cpp
index 10411e72e2..508f5e82e6 100644
--- a/src/plugins/platforms/xcb/gl_integrations/qxcbglintegrationfactory.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/qxcbglintegrationfactory.cpp
@@ -78,6 +78,7 @@ QStringList QXcbGlIntegrationFactory::keys(const QString &pluginPath)
list.append(loader()->keyMap().values());
return list;
#else
+ Q_UNUSED(pluginPath);
return QStringList();
#endif
}
@@ -93,6 +94,9 @@ QXcbGlIntegration *QXcbGlIntegrationFactory::create(const QString &platform, con
}
if (QXcbGlIntegration *ret = loadIntegration(loader(), platform))
return ret;
+#else
+ Q_UNUSED(platform);
+ Q_UNUSED(pluginPath);
#endif
return Q_NULLPTR;
}
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
index 8b14fc7d70..37f01d4eed 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
@@ -188,16 +188,18 @@ void QGLXContext::init(QXcbScreen *screen, QPlatformOpenGLContext *share)
Window window = 0; // Temporary window used to query OpenGL context
if (config) {
+ const QByteArrayList glxExt = QByteArray(glXQueryExtensionsString(m_display, screen->screenNumber())).split(' ');
+
// Resolve entry point for glXCreateContextAttribsARB
glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
- glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
+ if (glxExt.contains("GLX_ARB_create_context"))
+ glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
- QList<QByteArray> glxExt = QByteArray(glXQueryExtensionsString(m_display, screen->screenNumber())).split(' ');
- bool supportsProfiles = glxExt.contains("GLX_ARB_create_context_profile");
+ const bool supportsProfiles = glxExt.contains("GLX_ARB_create_context_profile");
// Use glXCreateContextAttribsARB if available
// Also, GL ES context creation requires GLX_EXT_create_context_es2_profile
- if (glxExt.contains("GLX_ARB_create_context") && glXCreateContextAttribsARB != 0
+ if (glXCreateContextAttribsARB != 0
&& (m_format.renderableType() != QSurfaceFormat::OpenGLES || (supportsProfiles && glxExt.contains("GLX_EXT_create_context_es2_profile")))) {
// Try to create an OpenGL context for each known OpenGL version in descending
// order from the requested version.
@@ -561,10 +563,12 @@ void (*QGLXContext::getProcAddress(const QByteArray &procName)) ()
if (!glXGetProcAddressARB)
#endif
{
+#ifndef QT_NO_LIBRARY
extern const QString qt_gl_library_name();
// QLibrary lib(qt_gl_library_name());
QLibrary lib(QLatin1String("GL"));
glXGetProcAddressARB = (qt_glXGetProcAddressARB) lib.resolve("glXGetProcAddressARB");
+#endif
}
}
resolved = true;
diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.cpp b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
index c0f5477f82..e62d515b62 100644
--- a/src/plugins/platforms/xcb/qxcbbackingstore.cpp
+++ b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
@@ -49,6 +49,7 @@
#include <qdebug.h>
#include <qpainter.h>
#include <qscreen.h>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <qpa/qplatformgraphicsbuffer.h>
#include <algorithm>
@@ -313,14 +314,7 @@ void QXcbBackingStore::beginPaint(const QRegion &region)
if (!m_image)
return;
- int dpr = int(m_image->image()->devicePixelRatio());
- const int windowDpr = int(window()->devicePixelRatio());
- if (windowDpr != dpr) {
- resize(window()->size(), QRegion());
- dpr = int(m_image->image()->devicePixelRatio());
- }
-
- m_paintRegion = dpr == 1 ? region : QTransform::fromScale(dpr,dpr).map(region);
+ m_paintRegion = region;
m_image->preparePaint(m_paintRegion);
if (m_image->image()->hasAlphaChannel()) {
@@ -369,18 +363,10 @@ void QXcbBackingStore::flush(QWindow *window, const QRegion &region, const QPoin
if (!m_image || m_image->size().isEmpty())
return;
- const int dpr = int(window->devicePixelRatio());
-
-#ifndef QT_NO_DEBUG
- const int imageDpr = int(m_image->image()->devicePixelRatio());
- if (dpr != imageDpr)
- qWarning() << "QXcbBackingStore::flush() wrong devicePixelRatio for backingstore image" << dpr << imageDpr;
-#endif
-
- QSize imageSize = m_image->size() / dpr; //because we multiply with the DPR later
+ QSize imageSize = m_image->size();
QRegion clipped = region;
- clipped &= QRect(0, 0, window->width(), window->height());
+ clipped &= QRect(QPoint(), QHighDpi::toNativePixels(window->size(), window));
clipped &= QRect(0, 0, imageSize.width(), imageSize.height()).translated(-offset);
QRect bounds = clipped.boundingRect();
@@ -398,8 +384,8 @@ void QXcbBackingStore::flush(QWindow *window, const QRegion &region, const QPoin
QVector<QRect> rects = clipped.rects();
for (int i = 0; i < rects.size(); ++i) {
- QRect rect = QRect(rects.at(i).topLeft() * dpr, rects.at(i).size() * dpr);
- m_image->put(platformWindow->xcb_window(), rect.topLeft(), rect.translated(offset * dpr));
+ QRect rect = QRect(rects.at(i).topLeft(), rects.at(i).size());
+ m_image->put(platformWindow->xcb_window(), rect.topLeft(), rect.translated(offset));
}
Q_XCB_NOOP(connection());
@@ -430,9 +416,7 @@ void QXcbBackingStore::composeAndFlush(QWindow *window, const QRegion &region, c
void QXcbBackingStore::resize(const QSize &size, const QRegion &)
{
- const int dpr = int(window()->devicePixelRatio());
- const QSize xSize = size * dpr;
- if (m_image && xSize == m_image->size() && dpr == m_image->image()->devicePixelRatio())
+ if (m_image && size == m_image->size())
return;
Q_XCB_NOOP(connection());
@@ -445,13 +429,11 @@ void QXcbBackingStore::resize(const QSize &size, const QRegion &)
QXcbWindow* win = static_cast<QXcbWindow *>(pw);
delete m_image;
- m_image = new QXcbShmImage(screen, xSize, win->depth(), win->imageFormat());
- m_image->image()->setDevicePixelRatio(dpr);
+ m_image = new QXcbShmImage(screen, size, win->depth(), win->imageFormat());
// Slow path for bgr888 VNC: Create an additional image, paint into that and
// swap R and B while copying to m_image after each paint.
if (win->imageNeedsRgbSwap()) {
- m_rgbImage = QImage(xSize, win->imageFormat());
- m_rgbImage.setDevicePixelRatio(dpr);
+ m_rgbImage = QImage(size, win->imageFormat());
}
Q_XCB_NOOP(connection());
}
@@ -463,14 +445,12 @@ bool QXcbBackingStore::scroll(const QRegion &area, int dx, int dy)
if (!m_image || m_image->image()->isNull())
return false;
- const int dpr = int(m_image->image()->devicePixelRatio());
- QRegion xArea = dpr == 1 ? area : QTransform::fromScale(dpr,dpr).map(area);
m_image->preparePaint(area);
- QPoint delta(dx * dpr, dy * dpr);
- const QVector<QRect> xRects = xArea.rects();
- for (int i = 0; i < xRects.size(); ++i)
- qt_scrollRectInImage(*m_image->image(), xRects.at(i), delta);
+ QPoint delta(dx, dy);
+ const QVector<QRect> rects = area.rects();
+ for (int i = 0; i < rects.size(); ++i)
+ qt_scrollRectInImage(*m_image->image(), rects.at(i), delta);
return true;
}
diff --git a/src/plugins/platforms/xcb/qxcbconnection.cpp b/src/plugins/platforms/xcb/qxcbconnection.cpp
index d2e08aecee..e612cff9a3 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection.cpp
@@ -590,9 +590,6 @@ QXcbConnection::QXcbConnection(QXcbNativeInterface *nativeInterface, bool canGra
qCDebug(QT_XCB_GLINTEGRATION) << "Failed to create xcb gl-integration";
sync();
-
- if (qEnvironmentVariableIsEmpty("QT_IM_MODULE"))
- qputenv("QT_IM_MODULE", QByteArray("compose"));
}
QXcbConnection::~QXcbConnection()
@@ -2074,10 +2071,11 @@ bool QXcbConnection::xi2PrepareXIGenericDeviceEvent(xcb_ge_event_t *ev, int opCo
}
#endif // defined(XCB_USE_XINPUT2)
-QXcbSystemTrayTracker *QXcbConnection::systemTrayTracker()
+QXcbSystemTrayTracker *QXcbConnection::systemTrayTracker() const
{
if (!m_systemTrayTracker) {
- if ( (m_systemTrayTracker = QXcbSystemTrayTracker::create(this)) ) {
+ QXcbConnection *self = const_cast<QXcbConnection *>(this);
+ if ((self->m_systemTrayTracker = QXcbSystemTrayTracker::create(self))) {
connect(m_systemTrayTracker, SIGNAL(systemTrayWindowChanged(QScreen*)),
QGuiApplication::platformNativeInterface(), SIGNAL(systemTrayWindowChanged(QScreen*)));
}
@@ -2085,6 +2083,22 @@ QXcbSystemTrayTracker *QXcbConnection::systemTrayTracker()
return m_systemTrayTracker;
}
+bool QXcbConnection::xEmbedSystemTrayAvailable()
+{
+ if (!QGuiApplicationPrivate::platformIntegration())
+ return false;
+ QXcbConnection *connection = static_cast<QXcbIntegration *>(QGuiApplicationPrivate::platformIntegration())->defaultConnection();
+ return connection->systemTrayTracker();
+}
+
+bool QXcbConnection::xEmbedSystemTrayVisualHasAlphaChannel()
+{
+ if (!QGuiApplicationPrivate::platformIntegration())
+ return false;
+ QXcbConnection *connection = static_cast<QXcbIntegration *>(QGuiApplicationPrivate::platformIntegration())->defaultConnection();
+ return connection->systemTrayTracker() && connection->systemTrayTracker()->visualHasAlphaChannel();
+}
+
bool QXcbConnection::event(QEvent *e)
{
if (e->type() == QEvent::User + 1) {
diff --git a/src/plugins/platforms/xcb/qxcbconnection.h b/src/plugins/platforms/xcb/qxcbconnection.h
index a183a72353..4a0348aa0c 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.h
+++ b/src/plugins/platforms/xcb/qxcbconnection.h
@@ -474,7 +474,9 @@ public:
QXcbNativeInterface *nativeInterface() const { return m_nativeInterface; }
- QXcbSystemTrayTracker *systemTrayTracker();
+ QXcbSystemTrayTracker *systemTrayTracker() const;
+ static bool xEmbedSystemTrayAvailable();
+ static bool xEmbedSystemTrayVisualHasAlphaChannel();
#ifdef XCB_USE_XINPUT2
void handleEnterEvent(const xcb_enter_notify_event_t *);
diff --git a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
index d7688be0ff..7a5480a8a5 100644
--- a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
@@ -562,10 +562,8 @@ void QXcbConnection::xi2ProcessTouch(void *xiDevEvent, QXcbWindow *platformWindo
}
QWindowSystemInterface::TouchPoint &touchPoint = dev->touchPoints[xiDeviceEvent->detail];
QXcbScreen* screen = platformWindow->xcbScreen();
- QPointF pos = screen->mapFromNative(QPointF(fixed1616ToReal(xiDeviceEvent->root_x),
- fixed1616ToReal(xiDeviceEvent->root_y)));
- qreal x = pos.x();
- qreal y = pos.y();
+ qreal x = fixed1616ToReal(xiDeviceEvent->root_x);
+ qreal y = fixed1616ToReal(xiDeviceEvent->root_y);
qreal nx = -1.0, ny = -1.0, d = 0.0;
for (int i = 0; i < dev->xiDeviceInfo->num_classes; ++i) {
XIAnyClassInfo *classinfo = dev->xiDeviceInfo->classes[i];
@@ -872,9 +870,8 @@ void QXcbConnection::xi2HandleScrollEvent(void *event, ScrollingDevice &scrollin
}
}
if (!angleDelta.isNull()) {
- const int dpr = int(platformWindow->devicePixelRatio());
- QPoint local(fixed1616ToReal(xiDeviceEvent->event_x)/dpr, fixed1616ToReal(xiDeviceEvent->event_y)/dpr);
- QPoint global(fixed1616ToReal(xiDeviceEvent->root_x)/dpr, fixed1616ToReal(xiDeviceEvent->root_y)/dpr);
+ QPoint local(fixed1616ToReal(xiDeviceEvent->event_x), fixed1616ToReal(xiDeviceEvent->event_y));
+ QPoint global(fixed1616ToReal(xiDeviceEvent->root_x), fixed1616ToReal(xiDeviceEvent->root_y));
Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(xiDeviceEvent->mods.effective_mods);
if (modifiers & Qt::AltModifier) {
std::swap(angleDelta.rx(), angleDelta.ry());
@@ -900,9 +897,8 @@ void QXcbConnection::xi2HandleScrollEvent(void *event, ScrollingDevice &scrollin
angleDelta.setX(-120);
}
if (!angleDelta.isNull()) {
- const int dpr = int(platformWindow->devicePixelRatio());
- QPoint local(fixed1616ToReal(xiDeviceEvent->event_x)/dpr, fixed1616ToReal(xiDeviceEvent->event_y)/dpr);
- QPoint global(fixed1616ToReal(xiDeviceEvent->root_x)/dpr, fixed1616ToReal(xiDeviceEvent->root_y)/dpr);
+ QPoint local(fixed1616ToReal(xiDeviceEvent->event_x), fixed1616ToReal(xiDeviceEvent->event_y));
+ QPoint global(fixed1616ToReal(xiDeviceEvent->root_x), fixed1616ToReal(xiDeviceEvent->root_y));
Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(xiDeviceEvent->mods.effective_mods);
if (modifiers & Qt::AltModifier)
std::swap(angleDelta.rx(), angleDelta.ry());
@@ -1024,9 +1020,8 @@ bool QXcbConnection::xi2HandleTabletEvent(void *event, TabletData *tabletData, Q
tabletData->inProximity = true;
tabletData->tool = toolIdToTabletDevice(tool);
tabletData->serialId = qint64(ptr[_WACSER_USB_ID]) << 32 | qint64(ptr[_WACSER_TOOL_SERIAL]);
- QWindowSystemInterface::handleTabletEnterProximityEvent(tabletData->tool,
- tabletData->pointerType,
- tabletData->serialId);
+ QWindowSystemInterface::handleTabletEnterProximityEvent(ev->time,
+ tabletData->tool, tabletData->pointerType, tabletData->serialId);
} else {
tabletData->inProximity = false;
tabletData->tool = toolIdToTabletDevice(ptr[_WACSER_LAST_TOOL_ID]);
@@ -1035,9 +1030,8 @@ bool QXcbConnection::xi2HandleTabletEvent(void *event, TabletData *tabletData, Q
if (!tabletData->tool)
tabletData->tool = toolIdToTabletDevice(ptr[_WACSER_LAST_TOOL_SERIAL]);
tabletData->serialId = qint64(ptr[_WACSER_USB_ID]) << 32 | qint64(ptr[_WACSER_LAST_TOOL_SERIAL]);
- QWindowSystemInterface::handleTabletLeaveProximityEvent(tabletData->tool,
- tabletData->pointerType,
- tabletData->serialId);
+ QWindowSystemInterface::handleTabletLeaveProximityEvent(ev->time,
+ tabletData->tool, tabletData->pointerType, tabletData->serialId);
}
// TODO maybe have a hash of tabletData->deviceId to device data so we can
// look up the tablet name here, and distinguish multiple tablets
@@ -1115,13 +1109,14 @@ void QXcbConnection::xi2ReportTabletEvent(TabletData &tabletData, void *event)
}
if (Q_UNLIKELY(lcQpaXInput().isDebugEnabled()))
- qCDebug(lcQpaXInput, "XI2 event on tablet %d with tool %d type %d seq %d detail %d pos %6.1f, %6.1f root pos %6.1f, %6.1f buttons 0x%x pressure %4.2lf tilt %d, %d rotation %6.2lf",
- tabletData.deviceId, tabletData.tool, ev->evtype, ev->sequenceNumber, ev->detail,
+ qCDebug(lcQpaXInput, "XI2 event on tablet %d with tool %d type %d seq %d detail %d time %d "
+ "pos %6.1f, %6.1f root pos %6.1f, %6.1f buttons 0x%x pressure %4.2lf tilt %d, %d rotation %6.2lf",
+ tabletData.deviceId, tabletData.tool, ev->evtype, ev->sequenceNumber, ev->detail, ev->time,
fixed1616ToReal(ev->event_x), fixed1616ToReal(ev->event_y),
fixed1616ToReal(ev->root_x), fixed1616ToReal(ev->root_y),
(int)tabletData.buttons, pressure, xTilt, yTilt, rotation);
- QWindowSystemInterface::handleTabletEvent(window, local, global,
+ QWindowSystemInterface::handleTabletEvent(window, ev->time, local, global,
tabletData.tool, tabletData.pointerType,
tabletData.buttons, pressure,
xTilt, yTilt, tangentialPressure,
diff --git a/src/plugins/platforms/xcb/qxcbcursor.cpp b/src/plugins/platforms/xcb/qxcbcursor.cpp
index bd880698e6..0cd9159052 100644
--- a/src/plugins/platforms/xcb/qxcbcursor.cpp
+++ b/src/plugins/platforms/xcb/qxcbcursor.cpp
@@ -52,7 +52,7 @@ typedef char *(*PtrXcursorLibraryGetTheme)(void *);
typedef int (*PtrXcursorLibrarySetTheme)(void *, const char *);
typedef int (*PtrXcursorLibraryGetDefaultSize)(void *);
-#ifdef XCB_USE_XLIB
+#if defined(XCB_USE_XLIB) && !defined(QT_NO_LIBRARY)
#include <X11/Xlib.h>
enum {
XCursorShape = CursorShape
@@ -300,7 +300,7 @@ QXcbCursor::QXcbCursor(QXcbConnection *conn, QXcbScreen *screen)
const char *cursorStr = "cursor";
xcb_open_font(xcb_connection(), cursorFont, strlen(cursorStr), cursorStr);
-#ifdef XCB_USE_XLIB
+#if defined(XCB_USE_XLIB) && !defined(QT_NO_LIBRARY)
static bool function_ptrs_not_initialized = true;
if (function_ptrs_not_initialized) {
QLibrary xcursorLib(QLatin1String("Xcursor"), 1);
@@ -491,7 +491,7 @@ xcb_cursor_t QXcbCursor::createNonStandardCursor(int cshape)
return cursor;
}
-#ifdef XCB_USE_XLIB
+#if defined(XCB_USE_XLIB) && !defined(QT_NO_LIBRARY)
bool updateCursorTheme(void *dpy, const QByteArray &theme) {
if (!ptrXcursorLibraryGetTheme
|| !ptrXcursorLibrarySetTheme)
@@ -535,7 +535,7 @@ static xcb_cursor_t loadCursor(void *dpy, int cshape)
}
return cursor;
}
-#endif //XCB_USE_XLIB
+#endif //XCB_USE_XLIB / QT_NO_LIBRARY
xcb_cursor_t QXcbCursor::createFontCursor(int cshape)
{
@@ -544,7 +544,7 @@ xcb_cursor_t QXcbCursor::createFontCursor(int cshape)
xcb_cursor_t cursor = XCB_NONE;
// Try Xcursor first
-#ifdef XCB_USE_XLIB
+#if defined(XCB_USE_XLIB) && !defined(QT_NO_LIBRARY)
if (cshape >= 0 && cshape <= Qt::LastCursor) {
void *dpy = connection()->xlib_display();
// special case for non-standard dnd-* cursors
@@ -637,15 +637,14 @@ QPoint QXcbCursor::pos() const
{
QPoint p;
queryPointer(connection(), 0, &p);
- return m_screen->mapFromNative(p);
+ return p;
}
void QXcbCursor::setPos(const QPoint &pos)
{
- const QPoint xPos = m_screen->mapToNative(pos);
xcb_window_t root = 0;
queryPointer(connection(), &root, 0);
- xcb_warp_pointer(xcb_connection(), XCB_NONE, root, 0, 0, 0, 0, xPos.x(), xPos.y());
+ xcb_warp_pointer(xcb_connection(), XCB_NONE, root, 0, 0, 0, 0, pos.x(), pos.y());
xcb_flush(xcb_connection());
}
diff --git a/src/plugins/platforms/xcb/qxcbcursor.h b/src/plugins/platforms/xcb/qxcbcursor.h
index 7e5cdc6870..f4f6e61706 100644
--- a/src/plugins/platforms/xcb/qxcbcursor.h
+++ b/src/plugins/platforms/xcb/qxcbcursor.h
@@ -90,7 +90,7 @@ private:
#ifndef QT_NO_CURSOR
CursorHash m_cursorHash;
#endif
-#ifdef XCB_USE_XLIB
+#if defined(XCB_USE_XLIB) && !defined(QT_NO_LIBRARY)
static void cursorThemePropertyChanged(QXcbVirtualDesktop *screen,
const QByteArray &name,
const QVariant &property,
diff --git a/src/plugins/platforms/xcb/qxcbdrag.cpp b/src/plugins/platforms/xcb/qxcbdrag.cpp
index 1d13adf851..a3e646ed7a 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.cpp
+++ b/src/plugins/platforms/xcb/qxcbdrag.cpp
@@ -51,6 +51,7 @@
#include <private/qshapedpixmapdndwindow_p.h>
#include <private/qsimpledrag_p.h>
+#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
@@ -71,12 +72,16 @@ QT_BEGIN_NAMESPACE
const int xdnd_version = 5;
+static inline xcb_window_t xcb_window(QPlatformWindow *w)
+{
+ return static_cast<QXcbWindow *>(w)->xcb_window();
+}
+
static inline xcb_window_t xcb_window(QWindow *w)
{
return static_cast<QXcbWindow *>(w->handle())->xcb_window();
}
-
static xcb_window_t xdndProxy(QXcbConnection *c, xcb_window_t w)
{
xcb_window_t proxy = XCB_NONE;
@@ -297,15 +302,8 @@ xcb_window_t QXcbDrag::findRealWindow(const QPoint & pos, xcb_window_t w, int md
return 0;
}
-void QXcbDrag::move(const QMouseEvent *me)
+void QXcbDrag::move(const QPoint &globalPos)
{
- // The mouse event is in the coordinate system of the window that started the drag.
- // We do not know which window that was at this point, so we just use the device pixel ratio
- // of the QGuiApplication. This will break once we support screens with different DPR. Fixing
- // this properly requires some redesign of the drag and drop architecture.
- static const int dpr = int(qApp->devicePixelRatio());
- QBasicDrag::move(me);
- QPoint globalPos = me->globalPos();
if (source_sameanswer.contains(globalPos) && source_sameanswer.isValid())
return;
@@ -318,6 +316,9 @@ void QXcbDrag::move(const QMouseEvent *me)
break;
}
}
+
+ QBasicDrag::moveShapedPixmapWindow(QHighDpiScaling::mapPositionFromNative(globalPos, screen));
+
if (screen != current_screen) {
// ### need to recreate the shaped pixmap window?
// int screen = QCursor::x11Screen();
@@ -340,7 +341,7 @@ void QXcbDrag::move(const QMouseEvent *me)
// qt_xdnd_current_screen = screen;
xcb_window_t rootwin = current_screen->root();
xcb_translate_coordinates_reply_t *translate =
- ::translateCoordinates(connection(), rootwin, rootwin, globalPos.x() * dpr, globalPos.y() * dpr);
+ ::translateCoordinates(connection(), rootwin, rootwin, globalPos.x(), globalPos.y());
if (!translate)
return;
@@ -443,7 +444,7 @@ void QXcbDrag::move(const QMouseEvent *me)
DEBUG() << "sending Xdnd enter source=" << enter.data.data32[0];
if (w)
- handleEnter(w->window(), &enter);
+ handleEnter(w, &enter);
else if (target)
xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&enter);
waiting_for_status = false;
@@ -463,7 +464,7 @@ void QXcbDrag::move(const QMouseEvent *me)
move.type = atom(QXcbAtom::XdndPosition);
move.data.data32[0] = connection()->clipboard()->owner();
move.data.data32[1] = 0; // flags
- move.data.data32[2] = (globalPos.x() * dpr << 16) + globalPos.y() * dpr;
+ move.data.data32[2] = (globalPos.x() << 16) + globalPos.y();
move.data.data32[3] = connection()->time();
move.data.data32[4] = toXdndAction(defaultAction(currentDrag()->supportedActions(), QGuiApplication::keyboardModifiers()));
DEBUG() << "sending Xdnd position source=" << move.data.data32[0] << "target=" << move.window;
@@ -471,15 +472,15 @@ void QXcbDrag::move(const QMouseEvent *me)
source_time = connection()->time();
if (w)
- handle_xdnd_position(w->window(), &move);
+ handle_xdnd_position(w, &move);
else
xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&move);
}
}
-void QXcbDrag::drop(const QMouseEvent *event)
+void QXcbDrag::drop(const QPoint &globalPos)
{
- QBasicDrag::drop(event);
+ QBasicDrag::drop(globalPos);
if (!current_target)
return;
@@ -505,7 +506,7 @@ void QXcbDrag::drop(const QMouseEvent *event)
connection()->time(),
current_target,
current_proxy_target,
- (w ? w->window() : 0),
+ w,
// current_embeddig_widget,
currentDrag(),
QTime::currentTime()
@@ -518,7 +519,7 @@ void QXcbDrag::drop(const QMouseEvent *event)
}
if (w) {
- handleDrop(w->window(), &drop);
+ handleDrop(w, &drop);
} else {
xcb_send_event(xcb_connection(), false, current_proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&drop);
}
@@ -664,7 +665,7 @@ static bool checkEmbedded(QWidget* w, const XEvent* xe)
#endif
-void QXcbDrag::handleEnter(QWindow *window, const xcb_client_message_event_t *event)
+void QXcbDrag::handleEnter(QPlatformWindow *window, const xcb_client_message_event_t *event)
{
Q_UNUSED(window);
DEBUG() << "handleEnter" << window;
@@ -689,6 +690,7 @@ void QXcbDrag::handleEnter(QWindow *window, const xcb_client_message_event_t *ev
length = xdnd_max_type;
xcb_atom_t *atoms = (xcb_atom_t *)xcb_get_property_value(reply);
+ xdnd_types.reserve(length);
for (int i = 0; i < length; ++i)
xdnd_types.append(atoms[i]);
}
@@ -704,17 +706,14 @@ void QXcbDrag::handleEnter(QWindow *window, const xcb_client_message_event_t *ev
DEBUG() << " " << connection()->atomName(xdnd_types.at(i));
}
-void QXcbDrag::handle_xdnd_position(QWindow *w, const xcb_client_message_event_t *e)
+void QXcbDrag::handle_xdnd_position(QPlatformWindow *w, const xcb_client_message_event_t *e)
{
QPoint p((e->data.data32[2] & 0xffff0000) >> 16, e->data.data32[2] & 0x0000ffff);
Q_ASSERT(w);
QRect geometry = w->geometry();
- const int dpr = int(w->handle()->devicePixelRatio());
-
- p /= dpr;
p -= geometry.topLeft();
- if (!w || (w->type() == Qt::Desktop))
+ if (!w || !w->window() || (w->window()->type() == Qt::Desktop))
return;
if (e->data.data32[0] != xdnd_dragsource) {
@@ -723,7 +722,7 @@ void QXcbDrag::handle_xdnd_position(QWindow *w, const xcb_client_message_event_t
}
currentPosition = p;
- currentWindow = w;
+ currentWindow = w->window();
// timestamp from the source
if (e->data.data32[3] != XCB_NONE) {
@@ -740,7 +739,7 @@ void QXcbDrag::handle_xdnd_position(QWindow *w, const xcb_client_message_event_t
supported_actions = Qt::DropActions(toDropAction(e->data.data32[4]));
}
- QPlatformDragQtResponse qt_response = QWindowSystemInterface::handleDrag(w,dropData,p,supported_actions);
+ QPlatformDragQtResponse qt_response = QWindowSystemInterface::handleDrag(w->window(),dropData,p,supported_actions);
QRect answerRect(p + geometry.topLeft(), QSize(1,1));
answerRect = qt_response.answerRect().translated(geometry.topLeft()).intersected(geometry);
@@ -796,7 +795,7 @@ namespace
};
}
-void QXcbDrag::handlePosition(QWindow * w, const xcb_client_message_event_t *event)
+void QXcbDrag::handlePosition(QPlatformWindow * w, const xcb_client_message_event_t *event)
{
xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
xcb_generic_event_t *nextEvent;
@@ -830,12 +829,10 @@ void QXcbDrag::handle_xdnd_status(const xcb_client_message_event_t *event)
updateCursor(Qt::IgnoreAction);
}
- static const int dpr = int(qApp->devicePixelRatio());
-
if ((event->data.data32[1] & 2) == 0) {
QPoint p((event->data.data32[2] & 0xffff0000) >> 16, event->data.data32[2] & 0x0000ffff);
QSize s((event->data.data32[3] & 0xffff0000) >> 16, event->data.data32[3] & 0x0000ffff);
- source_sameanswer = QRect(p / dpr, s / dpr);
+ source_sameanswer = QRect(p, s);
} else {
source_sameanswer = QRect();
}
@@ -861,10 +858,10 @@ void QXcbDrag::handleStatus(const xcb_client_message_event_t *event)
DEBUG("xdndHandleStatus end");
}
-void QXcbDrag::handleLeave(QWindow *w, const xcb_client_message_event_t *event)
+void QXcbDrag::handleLeave(QPlatformWindow *w, const xcb_client_message_event_t *event)
{
DEBUG("xdnd leave");
- if (!currentWindow || w != currentWindow.data())
+ if (!currentWindow || w != currentWindow.data()->handle())
return; // sanity
// ###
@@ -879,7 +876,7 @@ void QXcbDrag::handleLeave(QWindow *w, const xcb_client_message_event_t *event)
DEBUG("xdnd drag leave from unexpected source (%x not %x", event->data.data32[0], xdnd_dragsource);
}
- QWindowSystemInterface::handleDrag(w,0,QPoint(),Qt::IgnoreAction);
+ QWindowSystemInterface::handleDrag(w->window(),0,QPoint(),Qt::IgnoreAction);
xdnd_dragsource = 0;
xdnd_types.clear();
@@ -909,7 +906,7 @@ void QXcbDrag::send_leave()
w = 0;
if (w)
- handleLeave(w->window(), (const xcb_client_message_event_t *)&leave);
+ handleLeave(w, (const xcb_client_message_event_t *)&leave);
else
xcb_send_event(xcb_connection(), false,current_proxy_target,
XCB_EVENT_MASK_NO_EVENT, (const char *)&leave);
@@ -920,7 +917,7 @@ void QXcbDrag::send_leave()
waiting_for_status = false;
}
-void QXcbDrag::handleDrop(QWindow *, const xcb_client_message_event_t *event)
+void QXcbDrag::handleDrop(QPlatformWindow *, const xcb_client_message_event_t *event)
{
DEBUG("xdndHandleDrop");
if (!currentWindow) {
diff --git a/src/plugins/platforms/xcb/qxcbdrag.h b/src/plugins/platforms/xcb/qxcbdrag.h
index 95da76b732..699d402ea6 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.h
+++ b/src/plugins/platforms/xcb/qxcbdrag.h
@@ -53,8 +53,8 @@ QT_BEGIN_NAMESPACE
#ifndef QT_NO_DRAGANDDROP
-class QMouseEvent;
class QWindow;
+class QPlatformWindow;
class QXcbConnection;
class QXcbWindow;
class QXcbDropData;
@@ -72,14 +72,14 @@ public:
void startDrag() Q_DECL_OVERRIDE;
void cancel() Q_DECL_OVERRIDE;
- void move(const QMouseEvent *me) Q_DECL_OVERRIDE;
- void drop(const QMouseEvent *me) Q_DECL_OVERRIDE;
+ void move(const QPoint &globalPos) Q_DECL_OVERRIDE;
+ void drop(const QPoint &globalPos) Q_DECL_OVERRIDE;
void endDrag() Q_DECL_OVERRIDE;
- void handleEnter(QWindow *window, const xcb_client_message_event_t *event);
- void handlePosition(QWindow *w, const xcb_client_message_event_t *event);
- void handleLeave(QWindow *w, const xcb_client_message_event_t *event);
- void handleDrop(QWindow *, const xcb_client_message_event_t *event);
+ void handleEnter(QPlatformWindow *window, const xcb_client_message_event_t *event);
+ void handlePosition(QPlatformWindow *w, const xcb_client_message_event_t *event);
+ void handleLeave(QPlatformWindow *w, const xcb_client_message_event_t *event);
+ void handleDrop(QPlatformWindow *, const xcb_client_message_event_t *event);
void handleStatus(const xcb_client_message_event_t *event);
void handleSelectionRequest(const xcb_selection_request_event_t *event);
@@ -99,7 +99,7 @@ private:
void init();
- void handle_xdnd_position(QWindow *w, const xcb_client_message_event_t *event);
+ void handle_xdnd_position(QPlatformWindow *w, const xcb_client_message_event_t *event);
void handle_xdnd_status(const xcb_client_message_event_t *event);
void send_leave();
@@ -146,7 +146,7 @@ private:
xcb_timestamp_t timestamp;
xcb_window_t target;
xcb_window_t proxy_target;
- QWindow *targetWindow;
+ QPlatformWindow *targetWindow;
// QWidget *embedding_widget;
QPointer<QDrag> drag;
QTime time;
diff --git a/src/plugins/platforms/xcb/qxcbintegration.cpp b/src/plugins/platforms/xcb/qxcbintegration.cpp
index fc06f1a7b0..9cedfa77ad 100644
--- a/src/plugins/platforms/xcb/qxcbintegration.cpp
+++ b/src/plugins/platforms/xcb/qxcbintegration.cpp
@@ -268,7 +268,10 @@ void QXcbIntegration::initialize()
{
// Perform everything that may potentially need the event dispatcher (timers, socket
// notifiers) here instead of the constructor.
- m_inputContext.reset(QPlatformInputContextFactory::create());
+ QString icStr = QPlatformInputContextFactory::requested();
+ if (icStr.isNull())
+ icStr = QLatin1String("compose");
+ m_inputContext.reset(QPlatformInputContextFactory::create(icStr));
}
void QXcbIntegration::moveToScreen(QWindow *window, int screen)
diff --git a/src/plugins/platforms/xcb/qxcbkeyboard.cpp b/src/plugins/platforms/xcb/qxcbkeyboard.cpp
index ea541e4556..2e088d3ca5 100644
--- a/src/plugins/platforms/xcb/qxcbkeyboard.cpp
+++ b/src/plugins/platforms/xcb/qxcbkeyboard.cpp
@@ -1545,11 +1545,13 @@ void QXcbKeyboard::handleKeyEvent(xcb_window_t sourceWindow, QEvent::Type type,
QString QXcbKeyboard::lookupString(struct xkb_state *state, xcb_keycode_t code) const
{
- QByteArray chars;
- chars.resize(1 + xkb_state_key_get_utf8(state, code, 0, 0));
- // equivalent of XLookupString
- xkb_state_key_get_utf8(state, code, chars.data(), chars.size());
- return QString::fromUtf8(chars);
+ QVarLengthArray<char, 32> chars(32);
+ const int size = xkb_state_key_get_utf8(state, code, chars.data(), chars.size());
+ if (Q_UNLIKELY(size + 1 > chars.size())) { // +1 for NUL
+ chars.resize(size + 1);
+ xkb_state_key_get_utf8(state, code, chars.data(), chars.size());
+ }
+ return QString::fromUtf8(chars.constData(), size);
}
void QXcbKeyboard::handleKeyPressEvent(const xcb_key_press_event_t *event)
diff --git a/src/plugins/platforms/xcb/qxcbnativeinterface.cpp b/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
index 8bf9003af7..dfb0a125e2 100644
--- a/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
+++ b/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
@@ -47,6 +47,7 @@
#include <QtGui/qscreen.h>
#include <QtPlatformHeaders/qxcbwindowfunctions.h>
+#include <QtPlatformHeaders/qxcbintegrationfunctions.h>
#ifndef QT_NO_DBUS
#include "QtPlatformSupport/private/qdbusmenuconnection_p.h"
@@ -76,7 +77,8 @@ static int resourceType(const QByteArray &key)
QByteArrayLiteral("gettimestamp"), QByteArrayLiteral("x11screen"),
QByteArrayLiteral("rootwindow"),
QByteArrayLiteral("subpixeltype"), QByteArrayLiteral("antialiasingEnabled"),
- QByteArrayLiteral("nofonthinting")
+ QByteArrayLiteral("nofonthinting"),
+ QByteArrayLiteral("atspibus")
};
const QByteArray *end = names + sizeof(names) / sizeof(names[0]);
const QByteArray *result = std::find(names, end, key);
@@ -85,8 +87,7 @@ static int resourceType(const QByteArray &key)
QXcbNativeInterface::QXcbNativeInterface() :
m_genericEventFilterType(QByteArrayLiteral("xcb_generic_event_t")),
- m_sysTraySelectionAtom(XCB_ATOM_NONE),
- m_systrayVisualId(XCB_NONE)
+ m_sysTraySelectionAtom(XCB_ATOM_NONE)
{
}
@@ -117,22 +118,12 @@ bool QXcbNativeInterface::systemTrayAvailable(const QScreen *screen) const
bool QXcbNativeInterface::requestSystemTrayWindowDock(const QWindow *window)
{
- const QPlatformWindow *platformWindow = window->handle();
- if (!platformWindow)
- return false;
- QXcbSystemTrayTracker *trayTracker = systemTrayTracker(window->screen());
- if (!trayTracker)
- return false;
- trayTracker->requestSystemTrayWindowDock(static_cast<const QXcbWindow *>(platformWindow)->xcb_window());
- return true;
+ return QXcbWindow::requestSystemTrayWindowDockStatic(window);
}
QRect QXcbNativeInterface::systemTrayWindowGlobalGeometry(const QWindow *window)
{
- if (const QPlatformWindow *platformWindow = window->handle())
- if (const QXcbSystemTrayTracker *trayTracker = systemTrayTracker(window->screen()))
- return trayTracker->systemTrayWindowGlobalGeometry(static_cast<const QXcbWindow *>(platformWindow)->xcb_window());
- return QRect();
+ return QXcbWindow::systemTrayWindowGlobalGeometryStatic(window);
}
xcb_window_t QXcbNativeInterface::locateSystemTray(xcb_connection_t *conn, const QXcbScreen *screen)
@@ -163,54 +154,14 @@ xcb_window_t QXcbNativeInterface::locateSystemTray(xcb_connection_t *conn, const
return selection_window;
}
-bool QXcbNativeInterface::systrayVisualHasAlphaChannel() {
- const QXcbScreen *screen = static_cast<QXcbScreen *>(QGuiApplication::primaryScreen()->handle());
-
- if (m_systrayVisualId == XCB_NONE) {
- xcb_connection_t *xcb_conn = screen->xcb_connection();
- xcb_atom_t tray_atom = screen->atom(QXcbAtom::_NET_SYSTEM_TRAY_VISUAL);
-
- xcb_window_t systray_window = locateSystemTray(xcb_conn, screen);
- if (systray_window == XCB_WINDOW_NONE)
- return false;
-
- // Get the xcb property for the _NET_SYSTEM_TRAY_VISUAL atom
- xcb_get_property_cookie_t systray_atom_cookie;
- xcb_get_property_reply_t *systray_atom_reply;
-
- systray_atom_cookie = xcb_get_property_unchecked(xcb_conn, false, systray_window,
- tray_atom, XCB_ATOM_VISUALID, 0, 1);
- systray_atom_reply = xcb_get_property_reply(xcb_conn, systray_atom_cookie, 0);
-
- if (!systray_atom_reply)
- return false;
-
- if (systray_atom_reply->value_len > 0 && xcb_get_property_value_length(systray_atom_reply) > 0) {
- xcb_visualid_t * vids = (uint32_t *)xcb_get_property_value(systray_atom_reply);
- m_systrayVisualId = vids[0];
- }
-
- free(systray_atom_reply);
- }
-
- if (m_systrayVisualId != XCB_NONE) {
- quint8 depth = screen->depthOfVisual(m_systrayVisualId);
- return depth == 32;
- } else {
- return false;
- }
+bool QXcbNativeInterface::systrayVisualHasAlphaChannel()
+{
+ return QXcbConnection::xEmbedSystemTrayVisualHasAlphaChannel();
}
-void QXcbNativeInterface::setParentRelativeBackPixmap(const QWindow *qwindow)
+void QXcbNativeInterface::setParentRelativeBackPixmap(QWindow *window)
{
- if (const QPlatformWindow *platformWindow = qwindow->handle()) {
- const QXcbWindow *qxwindow = static_cast<const QXcbWindow *>(platformWindow);
- xcb_connection_t *xcb_conn = qxwindow->xcb_connection();
-
- const quint32 mask = XCB_CW_BACK_PIXMAP;
- const quint32 values[] = { XCB_BACK_PIXMAP_PARENT_RELATIVE };
- Q_XCB_CALL(xcb_change_window_attributes(xcb_conn, qxwindow->xcb_window(), mask, values));
- }
+ QXcbWindow::setParentRelativeBackPixmapStatic(window);
}
void *QXcbNativeInterface::nativeResourceForIntegration(const QByteArray &resourceString)
@@ -233,6 +184,9 @@ void *QXcbNativeInterface::nativeResourceForIntegration(const QByteArray &resour
case Display:
result = display();
break;
+ case AtspiBus:
+ result = atspiBus();
+ break;
case Connection:
result = connection();
break;
@@ -294,6 +248,9 @@ void *QXcbNativeInterface::nativeResourceForScreen(const QByteArray &resourceStr
case NoFontHinting:
result = xcbScreen->noFontHinting() ? this : 0; //qboolptr...
break;
+ case RootWindow:
+ result = reinterpret_cast<void *>(xcbScreen->root());
+ break;
default:
break;
}
@@ -389,9 +346,24 @@ QFunctionPointer QXcbNativeInterface::platformFunction(const QByteArray &functio
return func;
//case sensitive
- if (function == QXcbWindowFunctions::setWmWindowTypeIdentifier()) {
- return QFunctionPointer(QXcbWindow::setWmWindowTypeStatic);
- }
+ if (function == QXcbWindowFunctions::setWmWindowTypeIdentifier())
+ return QFunctionPointer(QXcbWindowFunctions::SetWmWindowType(QXcbWindow::setWmWindowTypeStatic));
+
+ if (function == QXcbWindowFunctions::setWmWindowIconTextIdentifier())
+ return QFunctionPointer(QXcbWindowFunctions::SetWmWindowIconText(QXcbWindow::setWindowIconTextStatic));
+
+ if (function == QXcbWindowFunctions::setParentRelativeBackPixmapIdentifier())
+ return QFunctionPointer(QXcbWindowFunctions::SetParentRelativeBackPixmap(QXcbWindow::setParentRelativeBackPixmapStatic));
+
+ if (function == QXcbWindowFunctions::requestSystemTrayWindowDockIdentifier())
+ return QFunctionPointer(QXcbWindowFunctions::RequestSystemTrayWindowDock(QXcbWindow::requestSystemTrayWindowDockStatic));
+
+ if (function == QXcbWindowFunctions::systemTrayWindowGlobalGeometryIdentifier())
+ return QFunctionPointer(QXcbWindowFunctions::SystemTrayWindowGlobalGeometry(QXcbWindow::systemTrayWindowGlobalGeometryStatic));
+
+ if (function == QXcbIntegrationFunctions::xEmbedSystemTrayVisualHasAlphaChannelIdentifier())
+ return QFunctionPointer(QXcbIntegrationFunctions::XEmbedSystemTrayVisualHasAlphaChannel(QXcbConnection::xEmbedSystemTrayVisualHasAlphaChannel));
+
if (function == QXcbWindowFunctions::visualIdIdentifier()) {
return QFunctionPointer(QXcbWindowFunctions::VisualId(QXcbWindow::visualIdStatic));
}
@@ -466,6 +438,27 @@ void *QXcbNativeInterface::connection()
return integration->defaultConnection()->xcb_connection();
}
+void *QXcbNativeInterface::atspiBus()
+{
+ QXcbIntegration *integration = static_cast<QXcbIntegration *>(QGuiApplicationPrivate::platformIntegration());
+ QXcbConnection *defaultConnection = integration->defaultConnection();
+ if (defaultConnection) {
+ xcb_atom_t atspiBusAtom = defaultConnection->internAtom("AT_SPI_BUS");
+ xcb_get_property_cookie_t cookie = Q_XCB_CALL(xcb_get_property(defaultConnection->xcb_connection(), false,
+ defaultConnection->rootWindow(),
+ atspiBusAtom,
+ XCB_ATOM_STRING, 0, 128));
+ xcb_get_property_reply_t *reply = Q_XCB_CALL(xcb_get_property_reply(defaultConnection->xcb_connection(), cookie, 0));
+ Q_ASSERT(!reply->bytes_after);
+ char *data = (char *)xcb_get_property_value(reply);
+ int length = xcb_get_property_value_length(reply);
+ QByteArray *busAddress = new QByteArray(data, length);
+ free(reply);
+ return busAddress;
+ }
+ return 0;
+}
+
void QXcbNativeInterface::setAppTime(QScreen* screen, xcb_timestamp_t time)
{
if (screen) {
diff --git a/src/plugins/platforms/xcb/qxcbnativeinterface.h b/src/plugins/platforms/xcb/qxcbnativeinterface.h
index 721c6f4b1d..f88b710864 100644
--- a/src/plugins/platforms/xcb/qxcbnativeinterface.h
+++ b/src/plugins/platforms/xcb/qxcbnativeinterface.h
@@ -67,7 +67,8 @@ public:
RootWindow,
ScreenSubpixelType,
ScreenAntialiasingEnabled,
- NoFontHinting
+ NoFontHinting,
+ AtspiBus
};
QXcbNativeInterface();
@@ -98,6 +99,7 @@ public:
void *x11Screen();
void *rootWindow();
void *display();
+ void *atspiBus();
void *connection();
static void setStartupId(const char *);
static void setAppTime(QScreen *screen, xcb_timestamp_t time);
@@ -105,7 +107,7 @@ public:
Q_INVOKABLE void beep();
Q_INVOKABLE bool systemTrayAvailable(const QScreen *screen) const;
- Q_INVOKABLE void setParentRelativeBackPixmap(const QWindow *window);
+ Q_INVOKABLE void setParentRelativeBackPixmap(QWindow *window);
Q_INVOKABLE bool systrayVisualHasAlphaChannel();
Q_INVOKABLE bool requestSystemTrayWindowDock(const QWindow *window);
Q_INVOKABLE QRect systemTrayWindowGlobalGeometry(const QWindow *window);
@@ -121,7 +123,6 @@ private:
const QByteArray m_genericEventFilterType;
xcb_atom_t m_sysTraySelectionAtom;
- xcb_visualid_t m_systrayVisualId;
static QXcbScreen *qPlatformScreenForWindow(QWindow *window);
diff --git a/src/plugins/platforms/xcb/qxcbscreen.cpp b/src/plugins/platforms/xcb/qxcbscreen.cpp
index 3dcd6a713a..c6e48dc8c4 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.cpp
+++ b/src/plugins/platforms/xcb/qxcbscreen.cpp
@@ -44,6 +44,7 @@
#include <qpa/qwindowsysteminterface.h>
#include <private/qmath_p.h>
+#include <QtGui/private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
@@ -86,7 +87,7 @@ QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDe
, m_orientation(Qt::PrimaryOrientation)
, m_refreshRate(60)
, m_forcedDpi(-1)
- , m_devicePixelRatio(1)
+ , m_pixelDensity(1)
, m_hintStyle(QFontEngine::HintStyle(-1))
, m_noFontHinting(false)
, m_subpixelType(QFontEngine::SubpixelAntialiasingType(-1))
@@ -107,9 +108,8 @@ QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDe
updateGeometry(output ? output->timestamp : 0);
}
- const int dpr = int(devicePixelRatio());
if (m_geometry.isEmpty()) {
- m_geometry = QRect(QPoint(), m_virtualSize/dpr);
+ m_geometry = QRect(QPoint(), m_virtualSize);
m_nativeGeometry = QRect(QPoint(), m_virtualSize);
}
if (m_availableGeometry.isEmpty())
@@ -117,12 +117,6 @@ QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDe
readXResources();
- // disable font hinting when we do UI scaling
- static bool dpr_scaling_enabled = (qgetenv("QT_DEVICE_PIXEL_RATIO").toInt() > 1
- || qgetenv("QT_DEVICE_PIXEL_RATIO").toLower() == "auto");
- if (dpr_scaling_enabled)
- m_noFontHinting = true;
-
QScopedPointer<xcb_get_window_attributes_reply_t, QScopedPointerPodDeleter> rootAttribs(
xcb_get_window_attributes_reply(xcb_connection(),
xcb_get_window_attributes_unchecked(xcb_connection(), screen()->root), NULL));
@@ -201,9 +195,8 @@ QWindow *QXcbScreen::topLevelAt(const QPoint &p) const
{
xcb_window_t root = screen()->root;
- int dpr = int(devicePixelRatio());
- int x = p.x() / dpr;
- int y = p.y() / dpr;
+ int x = p.x();
+ int y = p.y();
xcb_window_t parent = root;
xcb_window_t child = root;
@@ -237,43 +230,6 @@ QWindow *QXcbScreen::topLevelAt(const QPoint &p) const
return 0;
}
-
-QPoint QXcbScreen::mapToNative(const QPoint &pos) const
-{
- const int dpr = int(devicePixelRatio());
- return (pos - m_geometry.topLeft()) * dpr + m_nativeGeometry.topLeft();
-}
-
-QPoint QXcbScreen::mapFromNative(const QPoint &pos) const
-{
- const int dpr = int(devicePixelRatio());
- return (pos - m_nativeGeometry.topLeft()) / dpr + m_geometry.topLeft();
-}
-
-QPointF QXcbScreen::mapToNative(const QPointF &pos) const
-{
- const int dpr = int(devicePixelRatio());
- return (pos - m_geometry.topLeft()) * dpr + m_nativeGeometry.topLeft();
-}
-
-QPointF QXcbScreen::mapFromNative(const QPointF &pos) const
-{
- const int dpr = int(devicePixelRatio());
- return (pos - m_nativeGeometry.topLeft()) / dpr + m_geometry.topLeft();
-}
-
-QRect QXcbScreen::mapToNative(const QRect &rect) const
-{
- const int dpr = int(devicePixelRatio());
- return QRect(mapToNative(rect.topLeft()), rect.size() * dpr);
-}
-
-QRect QXcbScreen::mapFromNative(const QRect &rect) const
-{
- const int dpr = int(devicePixelRatio());
- return QRect(mapFromNative(rect.topLeft()), rect.size() / dpr);
-}
-
void QXcbScreen::windowShown(QXcbWindow *window)
{
// Freedesktop.org Startup Notification
@@ -335,29 +291,22 @@ QDpi QXcbScreen::virtualDpi() const
Q_MM_PER_INCH * m_virtualSize.height() / m_virtualSizeMillimeters.height());
}
+
QDpi QXcbScreen::logicalDpi() const
{
static const int overrideDpi = qEnvironmentVariableIntValue("QT_FONT_DPI");
if (overrideDpi)
return QDpi(overrideDpi, overrideDpi);
- int primaryDpr = int(connection()->screens().at(0)->devicePixelRatio());
- if (m_forcedDpi > 0)
- return QDpi(m_forcedDpi/primaryDpr, m_forcedDpi/primaryDpr);
- QDpi vDpi = virtualDpi();
- return QDpi(vDpi.first/primaryDpr, vDpi.second/primaryDpr);
+ if (m_forcedDpi > 0) {
+ return QDpi(m_forcedDpi, m_forcedDpi);
+ }
+ return virtualDpi();
}
-
-qreal QXcbScreen::devicePixelRatio() const
+qreal QXcbScreen::pixelDensity() const
{
- static int override_dpr = qEnvironmentVariableIntValue("QT_DEVICE_PIXEL_RATIO");
- static bool auto_dpr = qgetenv("QT_DEVICE_PIXEL_RATIO").toLower() == "auto";
- if (override_dpr > 0)
- return override_dpr;
- if (auto_dpr)
- return m_devicePixelRatio;
- return 1.0;
+ return m_pixelDensity;
}
QPlatformCursor *QXcbScreen::cursor() const
@@ -516,11 +465,10 @@ void QXcbScreen::updateGeometry(const QRect &geom, uint8_t rotation)
free(workArea);
qreal dpi = xGeometry.width() / physicalSize().width() * qreal(25.4);
- m_devicePixelRatio = qRound(dpi/96);
- const int dpr = int(devicePixelRatio()); // we may override m_devicePixelRatio
- m_geometry = QRect(xGeometry.topLeft(), xGeometry.size()/dpr);
+ m_pixelDensity = qRound(dpi/96);
+ m_geometry = QRect(xGeometry.topLeft(), xGeometry.size());
m_nativeGeometry = QRect(xGeometry.topLeft(), xGeometry.size());
- m_availableGeometry = QRect(mapFromNative(xAvailableGeometry.topLeft()), xAvailableGeometry.size()/dpr);
+ m_availableGeometry = QRect(xAvailableGeometry.topLeft(), xAvailableGeometry.size());
QWindowSystemInterface::handleScreenGeometryChange(QPlatformScreen::screen(), m_geometry, m_availableGeometry);
}
diff --git a/src/plugins/platforms/xcb/qxcbscreen.h b/src/plugins/platforms/xcb/qxcbscreen.h
index ccc30c0b84..cbb6307d6e 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.h
+++ b/src/plugins/platforms/xcb/qxcbscreen.h
@@ -96,7 +96,7 @@ public:
QSizeF physicalVirtualSize() const { return m_virtualSizeMillimeters; }
QDpi virtualDpi() const;
QDpi logicalDpi() const Q_DECL_OVERRIDE;
- qreal devicePixelRatio() const Q_DECL_OVERRIDE;
+ qreal pixelDensity() const Q_DECL_OVERRIDE;
QPlatformCursor *cursor() const Q_DECL_OVERRIDE;
qreal refreshRate() const Q_DECL_OVERRIDE { return m_refreshRate; }
Qt::ScreenOrientation orientation() const Q_DECL_OVERRIDE { return m_orientation; }
@@ -139,13 +139,6 @@ public:
QXcbXSettings *xSettings() const;
- QPoint mapToNative(const QPoint &pos) const;
- QPoint mapFromNative(const QPoint &pos) const;
- QPointF mapToNative(const QPointF &pos) const;
- QPointF mapFromNative(const QPointF &pos) const;
- QRect mapToNative(const QRect &rect) const;
- QRect mapFromNative(const QRect &rect) const;
-
private:
static bool xResource(const QByteArray &identifier,
const QByteArray &expectedIdentifier,
@@ -176,7 +169,7 @@ private:
QXcbCursor *m_cursor;
int m_refreshRate;
int m_forcedDpi;
- int m_devicePixelRatio;
+ int m_pixelDensity;
QFontEngine::HintStyle m_hintStyle;
bool m_noFontHinting;
QFontEngine::SubpixelAntialiasingType m_subpixelType;
diff --git a/src/plugins/platforms/xcb/qxcbsessionmanager.cpp b/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
index 328b72234a..c2101a71c1 100644
--- a/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
+++ b/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
@@ -134,6 +134,7 @@ static void sm_setProperty(const QString &name, const QStringList &value)
SmPropValue *prop = new SmPropValue[value.count()];
int count = 0;
QList<QByteArray> vl;
+ vl.reserve(value.size());
for (QStringList::ConstIterator it = value.begin(); it != value.end(); ++it) {
prop[count].length = (*it).length();
vl.append((*it).toUtf8());
diff --git a/src/plugins/platforms/xcb/qxcbsystemtraytracker.cpp b/src/plugins/platforms/xcb/qxcbsystemtraytracker.cpp
index a4fdd70b79..1f217e8de7 100644
--- a/src/plugins/platforms/xcb/qxcbsystemtraytracker.cpp
+++ b/src/plugins/platforms/xcb/qxcbsystemtraytracker.cpp
@@ -63,14 +63,14 @@ QXcbSystemTrayTracker *QXcbSystemTrayTracker::create(QXcbConnection *connection)
const xcb_atom_t selection = connection->internAtom(netSysTray.constData());
if (!selection)
return 0;
- return new QXcbSystemTrayTracker(connection, trayAtom, selection, connection);
+
+ return new QXcbSystemTrayTracker(connection, trayAtom, selection);
}
QXcbSystemTrayTracker::QXcbSystemTrayTracker(QXcbConnection *connection,
xcb_atom_t trayAtom,
- xcb_atom_t selection,
- QObject *parent)
- : QObject(parent)
+ xcb_atom_t selection)
+ : QObject(connection)
, m_selection(selection)
, m_trayAtom(trayAtom)
, m_connection(connection)
@@ -125,6 +125,7 @@ xcb_window_t QXcbSystemTrayTracker::trayWindow()
// does not work for the QWindow parented on the tray.
QRect QXcbSystemTrayTracker::systemTrayWindowGlobalGeometry(xcb_window_t window) const
{
+
xcb_connection_t *conn = m_connection->xcb_connection();
xcb_get_geometry_reply_t *geomReply =
xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), 0);
@@ -161,9 +162,43 @@ void QXcbSystemTrayTracker::handleDestroyNotifyEvent(const xcb_destroy_notify_ev
{
if (event->window == m_trayWindow) {
m_connection->removeWindowEventListener(m_trayWindow);
- m_trayWindow = 0;
+ m_trayWindow = XCB_WINDOW_NONE;
emitSystemTrayWindowChanged();
}
}
+bool QXcbSystemTrayTracker::visualHasAlphaChannel()
+{
+ if (m_trayWindow == XCB_WINDOW_NONE)
+ return false;
+
+ xcb_atom_t tray_atom = m_connection->atom(QXcbAtom::_NET_SYSTEM_TRAY_VISUAL);
+
+ // Get the xcb property for the _NET_SYSTEM_TRAY_VISUAL atom
+ xcb_get_property_cookie_t systray_atom_cookie;
+ xcb_get_property_reply_t *systray_atom_reply;
+
+ systray_atom_cookie = xcb_get_property_unchecked(m_connection->xcb_connection(), false, m_trayWindow,
+ tray_atom, XCB_ATOM_VISUALID, 0, 1);
+ systray_atom_reply = xcb_get_property_reply(m_connection->xcb_connection(), systray_atom_cookie, 0);
+
+ if (!systray_atom_reply)
+ return false;
+
+ xcb_visualid_t systrayVisualId = XCB_NONE;
+ if (systray_atom_reply->value_len > 0 && xcb_get_property_value_length(systray_atom_reply) > 0) {
+ xcb_visualid_t * vids = (uint32_t *)xcb_get_property_value(systray_atom_reply);
+ systrayVisualId = vids[0];
+ }
+
+ free(systray_atom_reply);
+
+ if (systrayVisualId != XCB_NONE) {
+ quint8 depth = m_connection->primaryScreen()->depthOfVisual(systrayVisualId);
+ return depth == 32;
+ }
+
+ return false;
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/xcb/qxcbsystemtraytracker.h b/src/plugins/platforms/xcb/qxcbsystemtraytracker.h
index 9c20f1729a..b619afb9c4 100644
--- a/src/plugins/platforms/xcb/qxcbsystemtraytracker.h
+++ b/src/plugins/platforms/xcb/qxcbsystemtraytracker.h
@@ -57,14 +57,14 @@ public:
void handleDestroyNotifyEvent(const xcb_destroy_notify_event_t *) Q_DECL_OVERRIDE;
+ bool visualHasAlphaChannel();
signals:
void systemTrayWindowChanged(QScreen *screen);
private:
explicit QXcbSystemTrayTracker(QXcbConnection *connection,
xcb_atom_t trayAtom,
- xcb_atom_t selection,
- QObject *parent = 0);
+ xcb_atom_t selection);
static xcb_window_t locateTrayWindow(const QXcbConnection *connection, xcb_atom_t selection);
void emitSystemTrayWindowChanged();
diff --git a/src/plugins/platforms/xcb/qxcbwindow.cpp b/src/plugins/platforms/xcb/qxcbwindow.cpp
index 4fdebe1ebb..1ff052f2c0 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.cpp
+++ b/src/plugins/platforms/xcb/qxcbwindow.cpp
@@ -37,6 +37,7 @@
#include <QScreen>
#include <QtGui/QIcon>
#include <QtGui/QRegion>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include "qxcbintegration.h"
#include "qxcbconnection.h"
@@ -46,6 +47,7 @@
#include "qxcbwmsupport.h"
#include "qxcbimage.h"
#include "qxcbnativeinterface.h"
+#include "qxcbsystemtraytracker.h"
#include <qpa/qplatformintegration.h>
@@ -139,73 +141,11 @@ enum QX11EmbedMessageType {
const quint32 XEMBED_VERSION = 0;
-static inline QRect mapLocalGeometryToNative(const QRect &qtRect, int dpr)
-{
- return QRect(qtRect.x() * dpr, qtRect.y() * dpr, qtRect.width() * dpr, qtRect.height() * dpr);
-}
-
-// When mapping expose events to Qt rects: round top/left towards the origin and
-// bottom/right away from the origin, making sure that we cover the whole widget
-
-static inline QPoint dpr_floor(const QPoint &p, int dpr)
-{
- return QPoint(p.x()/dpr, p.y()/dpr);
-}
-
-static inline QPoint dpr_ceil(const QPoint &p, int dpr)
-{
- return QPoint((p.x() + dpr - 1) / dpr, (p.y() + dpr - 1) / dpr);
-}
-
-static inline QSize dpr_ceil(const QSize &s, int dpr)
-{
- return QSize((s.width() + dpr - 1) / dpr, (s.height() + dpr - 1) / dpr);
-}
-
-static inline QRect mapExposeFromNative(const QRect &xRect, int dpr)
-{
- return QRect(dpr_floor(xRect.topLeft(), dpr), dpr_ceil(xRect.bottomRight(), dpr));
-}
-
-static inline QRect mapLocalGeometryFromNative(const QRect &xRect, int dpr)
-{
- return QRect(xRect.topLeft() / dpr, dpr_ceil(xRect.size(), dpr));
-}
-
QXcbScreen *QXcbWindow::parentScreen()
{
return parent() ? static_cast<QXcbWindow*>(parent())->parentScreen() : m_xcbScreen;
}
-QPoint QXcbWindow::mapToNative(const QPoint &pos, const QXcbScreen *screen) const
-{
- if (parent())
- return pos * int(screen->devicePixelRatio());
- else
- return screen->mapToNative(pos);
-}
-QPoint QXcbWindow::mapFromNative(const QPoint &pos, const QXcbScreen *screen) const
-{
- if (parent())
- return pos / int(screen->devicePixelRatio());
- else
- return screen->mapFromNative(pos);
-}
-QRect QXcbWindow::mapToNative(const QRect &rect, const QXcbScreen *screen) const
-{
- if (parent())
- return mapLocalGeometryToNative(rect, int(screen->devicePixelRatio()));
- else
- return screen->mapToNative(rect);
-}
-QRect QXcbWindow::mapFromNative(const QRect &rect, const QXcbScreen *screen) const
-{
- if (parent())
- return mapLocalGeometryFromNative(rect, int(screen->devicePixelRatio()));
- else
- return screen->mapFromNative(rect);
-}
-
// Returns \c true if we should set WM_TRANSIENT_FOR on \a w
static inline bool isTransient(const QWindow *w)
{
@@ -381,7 +321,7 @@ void QXcbWindow::create()
Qt::WindowType type = window()->type();
QXcbScreen *currentScreen = xcbScreen();
- QRect rect = window()->geometry();
+ QRect rect = windowGeometry();
QXcbScreen *platformScreen = parent() ? parentScreen() : static_cast<QXcbScreen*>(screenForGeometry(rect));
m_xcbScreen = platformScreen;
@@ -424,17 +364,15 @@ void QXcbWindow::create()
if (platformScreen != currentScreen)
QWindowSystemInterface::handleWindowScreenChanged(window(), platformScreen->QPlatformScreen::screen());
- const int dpr = int(devicePixelRatio());
-
- QSize minimumSize = window()->minimumSize();
+ const QSize minimumSize = windowMinimumSize();
if (rect.width() > 0 || rect.height() > 0) {
- rect.setWidth(qBound(1, rect.width(), XCOORD_MAX/dpr));
- rect.setHeight(qBound(1, rect.height(), XCOORD_MAX/dpr));
+ rect.setWidth(qBound(1, rect.width(), XCOORD_MAX));
+ rect.setHeight(qBound(1, rect.height(), XCOORD_MAX));
} else if (minimumSize.width() > 0 || minimumSize.height() > 0) {
rect.setSize(minimumSize);
} else {
- rect.setWidth(defaultWindowWidth);
- rect.setHeight(defaultWindowHeight);
+ rect.setWidth(QHighDpi::toNativePixels(int(defaultWindowWidth), platformScreen->QPlatformScreen::screen()));
+ rect.setHeight(QHighDpi::toNativePixels(int(defaultWindowHeight), platformScreen->QPlatformScreen::screen()));
}
xcb_window_t xcb_parent_id = platformScreen->root();
@@ -478,9 +416,7 @@ void QXcbWindow::create()
m_visualId = visualInfo->visualid;
- const QRect xRect = mapToNative(rect, platformScreen);
-
- m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, xRect.x(), xRect.y(), xRect.width(), xRect.height(),
+ m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, rect.x(), rect.y(), rect.width(), rect.height(),
0, visualInfo->depth, InputOutput, visualInfo->visual,
CWBackPixel|CWBorderPixel|CWColormap, &a);
@@ -536,16 +472,14 @@ void QXcbWindow::create()
}
m_imageFormat = imageFormatForVisual(m_depth, visual->red_mask, visual->blue_mask, &m_imageRgbSwap);
- const QRect xRect = mapToNative(rect, platformScreen);
-
Q_XCB_CALL(xcb_create_window(xcb_connection(),
m_depth,
m_window, // window id
xcb_parent_id, // parent window id
- xRect.x(),
- xRect.y(),
- xRect.width(),
- xRect.height(),
+ rect.x(),
+ rect.y(),
+ rect.width(),
+ rect.height(),
0, // border width
XCB_WINDOW_CLASS_INPUT_OUTPUT, // window class
m_visualId, // visual
@@ -708,15 +642,14 @@ void QXcbWindow::setGeometry(const QRect &rect)
propagateSizeHints();
- QXcbScreen *currentScreen = xcbScreen();
+ QXcbScreen *currentScreen = m_xcbScreen;
QXcbScreen *newScreen = parent() ? parentScreen() : static_cast<QXcbScreen*>(screenForGeometry(rect));
if (!newScreen)
- newScreen = currentScreen;
+ newScreen = xcbScreen();
m_xcbScreen = newScreen;
- const QRect xRect = mapToNative(rect, newScreen);
- const QRect wmGeometry = windowToWmGeometry(xRect);
+ const QRect wmGeometry = windowToWmGeometry(rect);
if (newScreen != currentScreen)
QWindowSystemInterface::handleWindowScreenChanged(window(), newScreen->QPlatformScreen::screen());
@@ -1328,7 +1261,7 @@ void QXcbWindow::updateMotifWmHintsBeforeMap()
mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
}
- if (window()->minimumSize() == window()->maximumSize()) {
+ if (windowMinimumSize() == windowMaximumSize()) {
// fixed size, remove the resize handle (since mwm/dtwm
// isn't smart enough to do it itself)
mwmhints.flags |= MWM_HINTS_FUNCTIONS;
@@ -1522,10 +1455,22 @@ void QXcbWindow::setWindowTitle(const QString &title)
xcb_flush(xcb_connection());
}
+void QXcbWindow::setWindowIconText(const QString &title)
+{
+ const QByteArray ba = title.toUtf8();
+ Q_XCB_CALL(xcb_change_property(xcb_connection(),
+ XCB_PROP_MODE_REPLACE,
+ m_window,
+ atom(QXcbAtom::_NET_WM_ICON_NAME),
+ atom(QXcbAtom::UTF8_STRING),
+ 8,
+ ba.length(),
+ ba.constData()));
+}
+
void QXcbWindow::setWindowIcon(const QIcon &icon)
{
QVector<quint32> icon_data;
-
if (!icon.isNull()) {
QList<QSize> availableSizes = icon.availableSizes();
if (availableSizes.isEmpty()) {
@@ -1602,8 +1547,7 @@ void QXcbWindow::propagateSizeHints()
xcb_size_hints_t hints;
memset(&hints, 0, sizeof(hints));
- const int dpr = int(devicePixelRatio());
- const QRect xRect = windowToWmGeometry(mapToNative(geometry(), xcbScreen()));
+ const QRect xRect = windowToWmGeometry(geometry());
QWindow *win = window();
@@ -1613,10 +1557,10 @@ void QXcbWindow::propagateSizeHints()
xcb_size_hints_set_size(&hints, true, xRect.width(), xRect.height());
xcb_size_hints_set_win_gravity(&hints, m_gravity);
- QSize minimumSize = win->minimumSize() * dpr;
- QSize maximumSize = win->maximumSize() * dpr;
- QSize baseSize = win->baseSize() * dpr;
- QSize sizeIncrement = win->sizeIncrement() * dpr;
+ QSize minimumSize = windowMinimumSize();
+ QSize maximumSize = windowMaximumSize();
+ QSize baseSize = windowBaseSize();
+ QSize sizeIncrement = windowSizeIncrement();
if (minimumSize.width() > 0 || minimumSize.height() > 0)
xcb_size_hints_set_min_size(&hints,
@@ -1690,6 +1634,12 @@ void QXcbWindow::setWmWindowTypeStatic(QWindow *window, QXcbWindowFunctions::WmW
static_cast<QXcbWindow *>(window->handle())->setWmWindowType(windowTypes, window->flags());
}
+void QXcbWindow::setWindowIconTextStatic(QWindow *window, const QString &text)
+{
+ if (window->handle())
+ static_cast<QXcbWindow *>(window->handle())->setWindowIconText(text);
+}
+
uint QXcbWindow::visualIdStatic(QWindow *window)
{
if (window && window->handle())
@@ -1855,13 +1805,54 @@ void QXcbWindow::setWmWindowType(QXcbWindowFunctions::WmWindowTypes types, Qt::W
xcb_flush(xcb_connection());
}
+void QXcbWindow::setParentRelativeBackPixmapStatic(QWindow *window)
+{
+ if (window->handle())
+ static_cast<QXcbWindow *>(window->handle())->setParentRelativeBackPixmap();
+}
+
+void QXcbWindow::setParentRelativeBackPixmap()
+{
+ const quint32 mask = XCB_CW_BACK_PIXMAP;
+ const quint32 values[] = { XCB_BACK_PIXMAP_PARENT_RELATIVE };
+ Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));
+}
+
+bool QXcbWindow::requestSystemTrayWindowDockStatic(const QWindow *window)
+{
+ if (window->handle())
+ return static_cast<QXcbWindow *>(window->handle())->requestSystemTrayWindowDock();
+ return false;
+}
+
+bool QXcbWindow::requestSystemTrayWindowDock() const
+{
+ if (!connection()->systemTrayTracker())
+ return false;
+ connection()->systemTrayTracker()->requestSystemTrayWindowDock(m_window);
+ return true;
+}
+
+QRect QXcbWindow::systemTrayWindowGlobalGeometryStatic(const QWindow *window)
+{
+ if (window->handle())
+ return static_cast<QXcbWindow *>(window->handle())->systemTrayWindowGlobalGeometry();
+ return QRect();
+}
+
+QRect QXcbWindow::systemTrayWindowGlobalGeometry() const
+{
+ if (!connection()->systemTrayTracker())
+ return QRect();
+ return connection()->systemTrayTracker()->systemTrayWindowGlobalGeometry(m_window);
+}
+
class ExposeCompressor
{
public:
- ExposeCompressor(xcb_window_t window, QRegion *region, int devicePixelRatio)
+ ExposeCompressor(xcb_window_t window, QRegion *region)
: m_window(window)
, m_region(region)
- , m_dpr(devicePixelRatio)
, m_pending(true)
{
}
@@ -1877,7 +1868,7 @@ public:
return false;
if (expose->count == 0)
m_pending = false;
- *m_region |= mapExposeFromNative(QRect(expose->x, expose->y, expose->width, expose->height), m_dpr);
+ *m_region |= QRect(expose->x, expose->y, expose->width, expose->height);
return true;
}
@@ -1889,7 +1880,6 @@ public:
private:
xcb_window_t m_window;
QRegion *m_region;
- int m_dpr;
bool m_pending;
};
@@ -1903,16 +1893,14 @@ bool QXcbWindow::handleGenericEvent(xcb_generic_event_t *event, long *result)
void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
{
- const int dpr = int(devicePixelRatio());
- QRect x_rect(event->x, event->y, event->width, event->height);
- QRect rect = mapExposeFromNative(x_rect, dpr);
+ QRect rect(event->x, event->y, event->width, event->height);
if (m_exposeRegion.isEmpty())
m_exposeRegion = rect;
else
m_exposeRegion |= rect;
- ExposeCompressor compressor(m_window, &m_exposeRegion, dpr);
+ ExposeCompressor compressor(m_window, &m_exposeRegion);
xcb_generic_event_t *filter = 0;
do {
filter = connection()->checkEvent(compressor);
@@ -1964,13 +1952,13 @@ void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *even
}
#ifndef QT_NO_DRAGANDDROP
} else if (event->type == atom(QXcbAtom::XdndEnter)) {
- connection()->drag()->handleEnter(window(), event);
+ connection()->drag()->handleEnter(this, event);
} else if (event->type == atom(QXcbAtom::XdndPosition)) {
- connection()->drag()->handlePosition(window(), event);
+ connection()->drag()->handlePosition(this, event);
} else if (event->type == atom(QXcbAtom::XdndLeave)) {
- connection()->drag()->handleLeave(window(), event);
+ connection()->drag()->handleLeave(this, event);
} else if (event->type == atom(QXcbAtom::XdndDrop)) {
- connection()->drag()->handleDrop(window(), event);
+ connection()->drag()->handleDrop(this, event);
#endif
} else if (event->type == atom(QXcbAtom::_XEMBED)) {
handleXEmbedMessage(event);
@@ -1990,26 +1978,6 @@ void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *even
}
}
-// Temporary workaround for bug in QPlatformScreen::screenForGeometry
-// we need the native geometries to detect our screen, but that's not
-// available in cross-platform code. Will be fixed properly when highDPI
-// support is refactored to expose the native coordinate system.
-
-QXcbScreen *QXcbWindow::screenForNativeGeometry(const QRect &newGeometry) const
-{
- QXcbScreen *currentScreen = xcbScreen();
- if (!currentScreen && QGuiApplication::primaryScreen())
- currentScreen = static_cast<QXcbScreen*>(QGuiApplication::primaryScreen()->handle());
- if (currentScreen && !parent() && !currentScreen->nativeGeometry().intersects(newGeometry)) {
- Q_FOREACH (QPlatformScreen* screen, currentScreen->virtualSiblings()) {
- QXcbScreen *xcbScreen = static_cast<QXcbScreen*>(screen);
- if (xcbScreen->nativeGeometry().intersects(newGeometry))
- return xcbScreen;
- }
- }
- return currentScreen;
-}
-
void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
{
bool fromSendEvent = (event->response_type & 0x80);
@@ -2026,19 +1994,18 @@ void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *
}
}
- const QRect nativeRect = QRect(pos, QSize(event->width, event->height));
- QXcbScreen *newScreen = parent() ? parentScreen() : screenForNativeGeometry(nativeRect);
+ const QRect rect = QRect(pos, QSize(event->width, event->height));
+ QPlatformScreen *newScreen = parent() ? parent()->screen() : screenForGeometry(rect);
QXcbScreen *currentScreen = m_xcbScreen;
- m_xcbScreen = newScreen;
+ m_xcbScreen = static_cast<QXcbScreen*>(newScreen);
if (!newScreen)
return;
- const QRect rect = mapFromNative(nativeRect, newScreen);
QPlatformWindow::setGeometry(rect);
QWindowSystemInterface::handleGeometryChange(window(), rect);
if (newScreen != currentScreen)
- QWindowSystemInterface::handleWindowScreenChanged(window(), newScreen->QPlatformScreen::screen());
+ QWindowSystemInterface::handleWindowScreenChanged(window(), newScreen->screen());
m_configureNotifyPending = false;
@@ -2071,11 +2038,10 @@ QPoint QXcbWindow::mapToGlobal(const QPoint &pos) const
if (!m_embedded)
return pos;
- const int dpr = int(devicePixelRatio());
QPoint ret;
xcb_translate_coordinates_cookie_t cookie =
xcb_translate_coordinates(xcb_connection(), xcb_window(), xcbScreen()->root(),
- pos.x() * dpr, pos.y() * dpr);
+ pos.x(), pos.y());
xcb_translate_coordinates_reply_t *reply =
xcb_translate_coordinates_reply(xcb_connection(), cookie, NULL);
if (reply) {
@@ -2084,7 +2050,7 @@ QPoint QXcbWindow::mapToGlobal(const QPoint &pos) const
free(reply);
}
- return mapFromNative(ret, xcbScreen());
+ return ret;
}
QPoint QXcbWindow::mapFromGlobal(const QPoint &pos) const
@@ -2092,17 +2058,15 @@ QPoint QXcbWindow::mapFromGlobal(const QPoint &pos) const
if (!m_embedded)
return pos;
- const int dpr = int(devicePixelRatio());
QPoint ret;
- QPoint xPos = mapToNative(pos, xcbScreen());
xcb_translate_coordinates_cookie_t cookie =
xcb_translate_coordinates(xcb_connection(), xcbScreen()->root(), xcb_window(),
- xPos.x(), xPos.y());
+ pos.x(), pos.y());
xcb_translate_coordinates_reply_t *reply =
xcb_translate_coordinates_reply(xcb_connection(), cookie, NULL);
if (reply) {
- ret.setX(reply->dst_x / dpr);
- ret.setY(reply->dst_y / dpr);
+ ret.setX(reply->dst_x);
+ ret.setY(reply->dst_y);
free(reply);
}
@@ -2118,7 +2082,7 @@ void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
if (m_configureNotifyPending)
m_deferredExpose = true;
else
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size() * int(devicePixelRatio())));
+ QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
@@ -2150,9 +2114,8 @@ void QXcbWindow::handleButtonPressEvent(int event_x, int event_y, int root_x, in
sendXEmbedMessage(container->xcb_window(), XEMBED_REQUEST_FOCUS);
}
}
- const int dpr = int(devicePixelRatio());
- QPoint local(event_x / dpr, event_y / dpr);
- QPoint global = xcbScreen()->mapFromNative(QPoint(root_x, root_y));
+ QPoint local(event_x, event_y);
+ QPoint global(root_x, root_y);
if (isWheel) {
if (!connection()->isAtLeastXI21()) {
@@ -2174,9 +2137,8 @@ void QXcbWindow::handleButtonPressEvent(int event_x, int event_y, int root_x, in
void QXcbWindow::handleButtonReleaseEvent(int event_x, int event_y, int root_x, int root_y,
int detail, Qt::KeyboardModifiers modifiers, xcb_timestamp_t timestamp)
{
- const int dpr = int(devicePixelRatio());
- QPoint local(event_x / dpr, event_y / dpr);
- QPoint global = xcbScreen()->mapFromNative(QPoint(root_x, root_y));
+ QPoint local(event_x, event_y);
+ QPoint global(root_x, root_y);
if (detail >= 4 && detail <= 7) {
// mouse wheel, handled in handleButtonPressEvent()
@@ -2189,11 +2151,8 @@ void QXcbWindow::handleButtonReleaseEvent(int event_x, int event_y, int root_x,
void QXcbWindow::handleMotionNotifyEvent(int event_x, int event_y, int root_x, int root_y,
Qt::KeyboardModifiers modifiers, xcb_timestamp_t timestamp)
{
- if (!xcbScreen())
- return;
- const int dpr = int(devicePixelRatio());
- QPoint local(event_x / dpr, event_y / dpr);
- QPoint global = xcbScreen()->mapFromNative(QPoint(root_x, root_y));
+ QPoint local(event_x, event_y);
+ QPoint global(root_x, root_y);
handleMouseEvent(timestamp, local, global, modifiers);
}
@@ -2321,11 +2280,10 @@ void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
if (ignoreEnterEvent(event))
return;
- const int dpr = int(devicePixelRatio());
- const QPoint local(event->event_x/dpr, event->event_y/dpr);
+ const QPoint local(event->event_x, event->event_y);
if (!xcbScreen())
return;
- QPoint global = xcbScreen()->mapFromNative(QPoint(event->root_x, event->root_y));
+ QPoint global = QPoint(event->root_x, event->root_y);
QWindowSystemInterface::handleEnterEvent(window(), local, global);
}
@@ -2341,11 +2299,10 @@ void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
QXcbWindow *enterWindow = enter ? connection()->platformWindowFromId(enter->event) : 0;
if (enterWindow) {
- const int dpr = int(devicePixelRatio());
- QPoint local(enter->event_x/dpr, enter->event_y/dpr);
+ QPoint local(enter->event_x, enter->event_y);
if (!xcbScreen())
return;
- QPoint global = xcbScreen()->mapFromNative(QPoint(event->root_x, event->root_y));
+ QPoint global = QPoint(event->root_x, event->root_y);
QWindowSystemInterface::handleEnterLeaveEvent(enterWindow->window(), window(), local, global);
} else {
@@ -2524,7 +2481,7 @@ bool QXcbWindow::startSystemResize(const QPoint &pos, Qt::Corner corner)
xev.type = moveResize;
xev.window = xcb_window();
xev.format = 32;
- const QPoint globalPos = mapToNative(window()->mapToGlobal(pos), xcbScreen());
+ const QPoint globalPos = window()->mapToGlobal(pos);
xev.data.data32[0] = globalPos.x();
xev.data.data32[1] = globalPos.y();
const bool bottom = corner == Qt::BottomRightCorner || corner == Qt::BottomLeftCorner;
@@ -2650,10 +2607,11 @@ void QXcbWindow::setMask(const QRegion &region)
xcb_shape_mask(connection()->xcb_connection(), XCB_SHAPE_SO_SET,
XCB_SHAPE_SK_BOUNDING, xcb_window(), 0, 0, XCB_NONE);
} else {
- const int dpr = devicePixelRatio();
QVector<xcb_rectangle_t> rects;
- foreach (const QRect &r, region.rects())
- rects.push_back(qRectToXCBRectangle(mapLocalGeometryToNative(r, dpr)));
+ const QVector<QRect> regionRects = region.rects();
+ rects.reserve(regionRects.count());
+ foreach (const QRect &r, regionRects)
+ rects.push_back(qRectToXCBRectangle(r));
xcb_shape_rectangles(connection()->xcb_connection(), XCB_SHAPE_SO_SET,
XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
xcb_window(), 0, 0, rects.size(), &rects[0]);
@@ -2691,11 +2649,6 @@ void QXcbWindow::postSyncWindowRequest()
}
}
-qreal QXcbWindow::devicePixelRatio() const
-{
- return xcbScreen() ? xcbScreen()->devicePixelRatio() : 1.0;
-}
-
QXcbScreen *QXcbWindow::xcbScreen() const
{
return static_cast<QXcbScreen *>(screen());
diff --git a/src/plugins/platforms/xcb/qxcbwindow.h b/src/plugins/platforms/xcb/qxcbwindow.h
index a379a6f9db..8968664bad 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.h
+++ b/src/plugins/platforms/xcb/qxcbwindow.h
@@ -86,6 +86,7 @@ public:
QPoint mapFromGlobal(const QPoint &pos) const Q_DECL_OVERRIDE;
void setWindowTitle(const QString &title) Q_DECL_OVERRIDE;
+ void setWindowIconText(const QString &title);
void setWindowIcon(const QIcon &icon) Q_DECL_OVERRIDE;
void raise() Q_DECL_OVERRIDE;
void lower() Q_DECL_OVERRIDE;
@@ -145,6 +146,16 @@ public:
QXcbWindowFunctions::WmWindowTypes wmWindowTypes() const;
void setWmWindowType(QXcbWindowFunctions::WmWindowTypes types, Qt::WindowFlags flags);
+ static void setWindowIconTextStatic(QWindow *window, const QString &text);
+
+ static void setParentRelativeBackPixmapStatic(QWindow *window);
+ void setParentRelativeBackPixmap();
+
+ static bool requestSystemTrayWindowDockStatic(const QWindow *window);
+ bool requestSystemTrayWindowDock() const;
+
+ static QRect systemTrayWindowGlobalGeometryStatic(const QWindow *window);
+ QRect systemTrayWindowGlobalGeometry() const;
uint visualId() const;
bool needsSync() const;
@@ -152,8 +163,6 @@ public:
void postSyncWindowRequest();
void clearSyncWindowRequest() { m_pendingSyncRequest = 0; }
- qreal devicePixelRatio() const Q_DECL_OVERRIDE;
-
QXcbScreen *xcbScreen() const;
virtual void create();
@@ -169,10 +178,6 @@ protected:
virtual void *createVisual() { return Q_NULLPTR; }
virtual bool supportsSyncProtocol() { return !window()->supportsOpenGL(); }
- QPoint mapToNative(const QPoint &pos, const QXcbScreen *screen) const;
- QPoint mapFromNative(const QPoint &pos, const QXcbScreen *screen) const;
- QRect mapToNative(const QRect &rect, const QXcbScreen *screen) const;
- QRect mapFromNative(const QRect &rect, const QXcbScreen *screen) const;
QXcbScreen *parentScreen();
void changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two = 0);
diff --git a/src/plugins/platforms/xcb/qxlibconvenience.cpp b/src/plugins/platforms/xcb/qxlibconvenience.cpp
deleted file mode 100644
index f3c7d2b24e..0000000000
--- a/src/plugins/platforms/xcb/qxlibconvenience.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifdef XCB_USE_XLIB
-
-#include "qxlibconvenience.h"
-
-// Some Xlib headers are heavy macro namespace polluters and conflict with Qt types.
-// This unit makes it easier to deal with them by encapsulating these includes in this .cpp.
-#include <X11/Xutil.h>
-
-QT_BEGIN_NAMESPACE
-
-xcb_keysym_t q_XLookupString(void *display, xcb_window_t window, xcb_window_t root, uint state, xcb_keycode_t code, int type, QByteArray *chars)
-{
- KeySym sym = 0;
- chars->resize(512);
- XKeyEvent event;
- memset(&event, 0, sizeof(event));
- event.type = type;
- event.display = static_cast<Display*>(display);
- event.window = window;
- event.root = root;
- event.state = state;
- event.keycode = code;
- int count = XLookupString(&event, chars->data(), chars->size(), &sym, 0);
- chars->resize(count);
- return sym;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.h b/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.h
index 2ac31bf715..141056637e 100644
--- a/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.h
+++ b/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.h
@@ -34,7 +34,11 @@
#ifndef QGTK2DIALOGHELPERS_P_H
#define QGTK2DIALOGHELPERS_P_H
+#include <QtCore/qhash.h>
+#include <QtCore/qlist.h>
+#include <QtCore/qurl.h>
#include <QtCore/qscopedpointer.h>
+#include <QtCore/qstring.h>
#include <qpa/qplatformdialoghelper.h>
typedef struct _GtkDialog GtkDialog;
@@ -43,6 +47,7 @@ typedef struct _GtkFileFilter GtkFileFilter;
QT_BEGIN_NAMESPACE
class QGtk2Dialog;
+class QColor;
class QGtk2ColorDialogHelper : public QPlatformColorDialogHelper
{
diff --git a/src/plugins/plugins.pro b/src/plugins/plugins.pro
index af4f6fc8fe..dd5345e67e 100644
--- a/src/plugins/plugins.pro
+++ b/src/plugins/plugins.pro
@@ -1,8 +1,15 @@
TEMPLATE = subdirs
+load(qfeatures)
SUBDIRS *= sqldrivers
-!winrt:qtHaveModule(network): SUBDIRS += bearer
-qtHaveModule(gui): SUBDIRS *= imageformats platforms platforminputcontexts platformthemes generic
+!winrt:qtHaveModule(network):!contains(QT_DISABLED_FEATURES, bearermanagement): SUBDIRS += bearer
+qtHaveModule(gui) {
+ SUBDIRS *= platforms platforminputcontexts platformthemes
+ !contains(QT_DISABLED_FEATURES, imageformatplugin): SUBDIRS *= imageformats
+ !contains(QT_DISABLED_FEATURES, library): SUBDIRS *= generic
+}
qtHaveModule(widgets): SUBDIRS *= styles
-!winrt:!wince:qtHaveModule(widgets): SUBDIRS += printsupport
+!winrt:!wince*:qtHaveModule(widgets):!contains(QT_DISABLED_FEATURES, printer) {
+ SUBDIRS += printsupport
+}
diff --git a/src/plugins/printsupport/cocoa/main.cpp b/src/plugins/printsupport/cocoa/main.cpp
index 2037724719..3db7b49ba4 100644
--- a/src/plugins/printsupport/cocoa/main.cpp
+++ b/src/plugins/printsupport/cocoa/main.cpp
@@ -38,8 +38,6 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_PRINTER
-
class QCocoaPrinterSupportPlugin : public QPlatformPrinterSupportPlugin
{
Q_OBJECT
@@ -67,8 +65,6 @@ QPlatformPrinterSupport *QCocoaPrinterSupportPlugin::create(const QString &key)
return platformPrinterSupport;
}
-#endif
-
QT_END_NAMESPACE
#include "main.moc"
diff --git a/src/plugins/printsupport/cups/main.cpp b/src/plugins/printsupport/cups/main.cpp
index 82485114ab..abd24d411a 100644
--- a/src/plugins/printsupport/cups/main.cpp
+++ b/src/plugins/printsupport/cups/main.cpp
@@ -37,8 +37,6 @@
#include <qpa/qplatformprintplugin.h>
#include <QtCore/QStringList>
-#ifndef QT_NO_PRINTER
-
QT_BEGIN_NAMESPACE
class QCupsPrinterSupportPlugin : public QPlatformPrinterSupportPlugin
@@ -65,6 +63,4 @@ QPlatformPrinterSupport *QCupsPrinterSupportPlugin::create(const QString &key)
QT_END_NAMESPACE
-#endif // QT_NO_PRINTER
-
#include "main.moc"
diff --git a/src/plugins/printsupport/cups/qcupsprintengine.cpp b/src/plugins/printsupport/cups/qcupsprintengine.cpp
index c00d7f302c..7ca81986b4 100644
--- a/src/plugins/printsupport/cups/qcupsprintengine.cpp
+++ b/src/plugins/printsupport/cups/qcupsprintengine.cpp
@@ -33,8 +33,6 @@
#include "qcupsprintengine_p.h"
-#ifndef QT_NO_PRINTER
-
#include <qpa/qplatformprintplugin.h>
#include <qpa/qplatformprintersupport.h>
@@ -226,7 +224,9 @@ void QCupsPrintEnginePrivate::closePrintDevice()
it += 2;
}
- for (int c = 0; c < options.size(); ++c) {
+ const int numOptions = options.size();
+ cupsOptStruct.reserve(numOptions);
+ for (int c = 0; c < numOptions; ++c) {
cups_option_t opt;
opt.name = options[c].first.data();
opt.value = options[c].second.data();
@@ -315,5 +315,3 @@ void QCupsPrintEnginePrivate::setPageSize(const QPageSize &pageSize)
}
QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/plugins/printsupport/cups/qcupsprintengine_p.h b/src/plugins/printsupport/cups/qcupsprintengine_p.h
index b589d40b6c..a611740e09 100644
--- a/src/plugins/printsupport/cups/qcupsprintengine_p.h
+++ b/src/plugins/printsupport/cups/qcupsprintengine_p.h
@@ -47,8 +47,6 @@
#include "QtPrintSupport/qprintengine.h"
-#ifndef QT_NO_PRINTER
-
#include <QtCore/qstring.h>
#include <QtGui/qpaintengine.h>
@@ -100,6 +98,4 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_PRINTER
-
#endif // QCUPSPRINTENGINE_P_H
diff --git a/src/plugins/printsupport/cups/qcupsprintersupport.cpp b/src/plugins/printsupport/cups/qcupsprintersupport.cpp
index ea7c116e3c..b257918acf 100644
--- a/src/plugins/printsupport/cups/qcupsprintersupport.cpp
+++ b/src/plugins/printsupport/cups/qcupsprintersupport.cpp
@@ -34,8 +34,6 @@
#include "qcupsprintersupport_p.h"
-#ifndef QT_NO_PRINTER
-
#include "qcupsprintengine_p.h"
#include "qppdprintdevice.h"
#include <private/qprinterinfo_p.h>
@@ -80,6 +78,7 @@ QStringList QCupsPrinterSupport::availablePrintDeviceIds() const
QStringList list;
cups_dest_t *dests;
int count = cupsGetDests(&dests);
+ list.reserve(count);
for (int i = 0; i < count; ++i) {
QString printerId = QString::fromLocal8Bit(dests[i].name);
if (dests[i].instance)
@@ -109,5 +108,3 @@ QString QCupsPrinterSupport::defaultPrintDeviceId() const
}
QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/plugins/printsupport/cups/qcupsprintersupport_p.h b/src/plugins/printsupport/cups/qcupsprintersupport_p.h
index ea913deeaa..6dcaa4e893 100644
--- a/src/plugins/printsupport/cups/qcupsprintersupport_p.h
+++ b/src/plugins/printsupport/cups/qcupsprintersupport_p.h
@@ -48,8 +48,6 @@
#include <qpa/qplatformprintersupport.h>
-#ifndef QT_NO_PRINTER
-
#include <QtCore/qstringlist.h>
QT_BEGIN_NAMESPACE
@@ -73,5 +71,4 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_PRINTER
#endif // QCUPSPRINTERSUPPORT_H
diff --git a/src/plugins/printsupport/cups/qppdprintdevice.cpp b/src/plugins/printsupport/cups/qppdprintdevice.cpp
index 808424b1ed..1b9ff98fca 100644
--- a/src/plugins/printsupport/cups/qppdprintdevice.cpp
+++ b/src/plugins/printsupport/cups/qppdprintdevice.cpp
@@ -42,8 +42,6 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_PRINTER
-
QPpdPrintDevice::QPpdPrintDevice()
: QPlatformPrintDevice(),
m_cupsDest(0),
@@ -269,6 +267,7 @@ void QPpdPrintDevice::loadInputSlots() const
if (m_ppd) {
ppd_option_t *inputSlots = ppdFindOption(m_ppd, "InputSlot");
if (inputSlots) {
+ m_inputSlots.reserve(inputSlots->num_choices);
for (int i = 0; i < inputSlots->num_choices; ++i)
m_inputSlots.append(QPrintUtils::ppdChoiceToInputSlot(inputSlots->choices[i]));
}
@@ -309,6 +308,7 @@ void QPpdPrintDevice::loadOutputBins() const
if (m_ppd) {
ppd_option_t *outputBins = ppdFindOption(m_ppd, "OutputBin");
if (outputBins) {
+ m_outputBins.reserve(outputBins->num_choices);
for (int i = 0; i < outputBins->num_choices; ++i)
m_outputBins.append(QPrintUtils::ppdChoiceToOutputBin(outputBins->choices[i]));
}
@@ -350,6 +350,7 @@ void QPpdPrintDevice::loadDuplexModes() const
if (m_ppd) {
ppd_option_t *duplexModes = ppdFindOption(m_ppd, "Duplex");
if (duplexModes) {
+ m_duplexModes.reserve(duplexModes->num_choices);
for (int i = 0; i < duplexModes->num_choices; ++i)
m_duplexModes.append(QPrintUtils::ppdChoiceToDuplexMode(duplexModes->choices[i].choice));
}
@@ -472,6 +473,4 @@ cups_ptype_e QPpdPrintDevice::printerTypeFlags() const
return static_cast<cups_ptype_e>(printerOption("printer-type").toUInt());
}
-#endif // QT_NO_PRINTER
-
QT_END_NAMESPACE
diff --git a/src/plugins/printsupport/cups/qppdprintdevice.h b/src/plugins/printsupport/cups/qppdprintdevice.h
index 5ebcf39566..a28348eb60 100644
--- a/src/plugins/printsupport/cups/qppdprintdevice.h
+++ b/src/plugins/printsupport/cups/qppdprintdevice.h
@@ -47,7 +47,9 @@
#include <qpa/qplatformprintdevice.h>
-#ifndef QT_NO_PRINTER
+#include <QtCore/qbytearray.h>
+#include <QtCore/qhash.h>
+#include <QtCore/qmargins.h>
#include <cups/cups.h>
#include <cups/ppd.h>
@@ -107,5 +109,4 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_PRINTER
#endif // QPPDPRINTDEVICE_H
diff --git a/src/plugins/printsupport/printsupport.pro b/src/plugins/printsupport/printsupport.pro
index ed201f0744..bd6681f53c 100644
--- a/src/plugins/printsupport/printsupport.pro
+++ b/src/plugins/printsupport/printsupport.pro
@@ -2,4 +2,7 @@ TEMPLATE = subdirs
osx: SUBDIRS += cocoa
win32: SUBDIRS += windows
-unix:!mac:contains(QT_CONFIG, cups): SUBDIRS += cups
+unix:!mac:contains(QT_CONFIG, cups) {
+ load(qfeatures)
+ !contains(QT_DISABLED_FEATURES, cups): SUBDIRS += cups
+}
diff --git a/src/plugins/printsupport/windows/qwindowsprintdevice.cpp b/src/plugins/printsupport/windows/qwindowsprintdevice.cpp
index 505f3138ca..d378ff3130 100644
--- a/src/plugins/printsupport/windows/qwindowsprintdevice.cpp
+++ b/src/plugins/printsupport/windows/qwindowsprintdevice.cpp
@@ -41,8 +41,6 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_PRINTER
-
QT_WARNING_DISABLE_GCC("-Wsign-compare")
extern qreal qt_pointMultiplier(QPageLayout::Unit unit);
@@ -471,6 +469,4 @@ QString QWindowsPrintDevice::defaultPrintDeviceId()
return QString::fromWCharArray(name.data());
}
-#endif // QT_NO_PRINTER
-
QT_END_NAMESPACE
diff --git a/src/plugins/printsupport/windows/qwindowsprintdevice.h b/src/plugins/printsupport/windows/qwindowsprintdevice.h
index 8ab487a59c..2c232d22c5 100644
--- a/src/plugins/printsupport/windows/qwindowsprintdevice.h
+++ b/src/plugins/printsupport/windows/qwindowsprintdevice.h
@@ -47,8 +47,6 @@
#include <qpa/qplatformprintdevice.h>
-#ifndef QT_NO_PRINTER
-
#include <QtCore/qt_windows.h>
QT_BEGIN_NAMESPACE
@@ -95,5 +93,4 @@ private:
QT_END_NAMESPACE
-#endif // QT_NO_PRINTER
#endif // QWINDOWSPRINTDEVICE_H
diff --git a/src/plugins/styles/bb10style/bright/button/core_button_inactive.png b/src/plugins/styles/bb10style/bright/button/core_button_inactive.png
index 7769f15e44..7769f15e44 100755..100644
--- a/src/plugins/styles/bb10style/bright/button/core_button_inactive.png
+++ b/src/plugins/styles/bb10style/bright/button/core_button_inactive.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/button/core_button_pressed.png b/src/plugins/styles/bb10style/bright/button/core_button_pressed.png
index 59b5bfa7c2..59b5bfa7c2 100755..100644
--- a/src/plugins/styles/bb10style/bright/button/core_button_pressed.png
+++ b/src/plugins/styles/bb10style/bright/button/core_button_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/checkbox/core_checkbox_pressed.png b/src/plugins/styles/bb10style/bright/checkbox/core_checkbox_pressed.png
index f1c2ee3bed..f1c2ee3bed 100755..100644
--- a/src/plugins/styles/bb10style/bright/checkbox/core_checkbox_pressed.png
+++ b/src/plugins/styles/bb10style/bright/checkbox/core_checkbox_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg.png b/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg.png
index 07b8ea21bf..07b8ea21bf 100755..100644
--- a/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg.png
+++ b/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg_highlight.png b/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg_highlight.png
index 55f8aee066..55f8aee066 100755..100644
--- a/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg_highlight.png
+++ b/src/plugins/styles/bb10style/bright/lineedit/core_textinput_bg_highlight.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/listitem/core_listitem_active.png b/src/plugins/styles/bb10style/bright/listitem/core_listitem_active.png
index 34daccc27e..34daccc27e 100755..100644
--- a/src/plugins/styles/bb10style/bright/listitem/core_listitem_active.png
+++ b/src/plugins/styles/bb10style/bright/listitem/core_listitem_active.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/listitem/core_listitem_divider.png b/src/plugins/styles/bb10style/bright/listitem/core_listitem_divider.png
index 7a1e22321d..7a1e22321d 100755..100644
--- a/src/plugins/styles/bb10style/bright/listitem/core_listitem_divider.png
+++ b/src/plugins/styles/bb10style/bright/listitem/core_listitem_divider.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/progressbar/core_progressindicator_bg.png b/src/plugins/styles/bb10style/bright/progressbar/core_progressindicator_bg.png
index 3ff930dea7..3ff930dea7 100755..100644
--- a/src/plugins/styles/bb10style/bright/progressbar/core_progressindicator_bg.png
+++ b/src/plugins/styles/bb10style/bright/progressbar/core_progressindicator_bg.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_inactive.png b/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_inactive.png
index cb4c6a8136..cb4c6a8136 100755..100644
--- a/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_inactive.png
+++ b/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_inactive.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_pressed.png b/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_pressed.png
index 88fd1344d2..88fd1344d2 100755..100644
--- a/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_pressed.png
+++ b/src/plugins/styles/bb10style/bright/radiobutton/core_radiobutton_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/scrollbar/core_scrollbar.png b/src/plugins/styles/bb10style/bright/scrollbar/core_scrollbar.png
index 79154e0568..79154e0568 100755..100644
--- a/src/plugins/styles/bb10style/bright/scrollbar/core_scrollbar.png
+++ b/src/plugins/styles/bb10style/bright/scrollbar/core_scrollbar.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/bright/slider/core_slider_handle_pressed.png b/src/plugins/styles/bb10style/bright/slider/core_slider_handle_pressed.png
index 8cb79118b9..8cb79118b9 100755..100644
--- a/src/plugins/styles/bb10style/bright/slider/core_slider_handle_pressed.png
+++ b/src/plugins/styles/bb10style/bright/slider/core_slider_handle_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/button/core_button_inactive.png b/src/plugins/styles/bb10style/dark/button/core_button_inactive.png
index 97842e1ac4..97842e1ac4 100755..100644
--- a/src/plugins/styles/bb10style/dark/button/core_button_inactive.png
+++ b/src/plugins/styles/bb10style/dark/button/core_button_inactive.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/button/core_button_pressed.png b/src/plugins/styles/bb10style/dark/button/core_button_pressed.png
index c149b64a26..c149b64a26 100755..100644
--- a/src/plugins/styles/bb10style/dark/button/core_button_pressed.png
+++ b/src/plugins/styles/bb10style/dark/button/core_button_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/checkbox/core_checkbox_pressed.png b/src/plugins/styles/bb10style/dark/checkbox/core_checkbox_pressed.png
index 507a77b3ea..507a77b3ea 100755..100644
--- a/src/plugins/styles/bb10style/dark/checkbox/core_checkbox_pressed.png
+++ b/src/plugins/styles/bb10style/dark/checkbox/core_checkbox_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg.png b/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg.png
index 07b8ea21bf..07b8ea21bf 100755..100644
--- a/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg.png
+++ b/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg_highlight.png b/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg_highlight.png
index 9b115897e8..9b115897e8 100755..100644
--- a/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg_highlight.png
+++ b/src/plugins/styles/bb10style/dark/lineedit/core_textinput_bg_highlight.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/listitem/core_listitem_active.png b/src/plugins/styles/bb10style/dark/listitem/core_listitem_active.png
index 52aa4e4aa2..52aa4e4aa2 100755..100644
--- a/src/plugins/styles/bb10style/dark/listitem/core_listitem_active.png
+++ b/src/plugins/styles/bb10style/dark/listitem/core_listitem_active.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/listitem/core_listitem_divider.png b/src/plugins/styles/bb10style/dark/listitem/core_listitem_divider.png
index 39e3a8a4f5..39e3a8a4f5 100755..100644
--- a/src/plugins/styles/bb10style/dark/listitem/core_listitem_divider.png
+++ b/src/plugins/styles/bb10style/dark/listitem/core_listitem_divider.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/progressbar/core_progressindicator_bg.png b/src/plugins/styles/bb10style/dark/progressbar/core_progressindicator_bg.png
index 95fcafb437..95fcafb437 100755..100644
--- a/src/plugins/styles/bb10style/dark/progressbar/core_progressindicator_bg.png
+++ b/src/plugins/styles/bb10style/dark/progressbar/core_progressindicator_bg.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_inactive.png b/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_inactive.png
index fd61937d65..fd61937d65 100755..100644
--- a/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_inactive.png
+++ b/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_inactive.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_pressed.png b/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_pressed.png
index 58a1a57b4c..58a1a57b4c 100755..100644
--- a/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_pressed.png
+++ b/src/plugins/styles/bb10style/dark/radiobutton/core_radiobutton_pressed.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/scrollbar/core_scrollbar.png b/src/plugins/styles/bb10style/dark/scrollbar/core_scrollbar.png
index 384f60758a..384f60758a 100755..100644
--- a/src/plugins/styles/bb10style/dark/scrollbar/core_scrollbar.png
+++ b/src/plugins/styles/bb10style/dark/scrollbar/core_scrollbar.png
Binary files differ
diff --git a/src/plugins/styles/bb10style/dark/slider/core_slider_handle_pressed.png b/src/plugins/styles/bb10style/dark/slider/core_slider_handle_pressed.png
index 803c374015..803c374015 100755..100644
--- a/src/plugins/styles/bb10style/dark/slider/core_slider_handle_pressed.png
+++ b/src/plugins/styles/bb10style/dark/slider/core_slider_handle_pressed.png
Binary files differ
diff --git a/src/printsupport/dialogs/qabstractprintdialog.h b/src/printsupport/dialogs/qabstractprintdialog.h
index cf55cfade8..6148502096 100644
--- a/src/printsupport/dialogs/qabstractprintdialog.h
+++ b/src/printsupport/dialogs/qabstractprintdialog.h
@@ -74,7 +74,7 @@ public:
Q_DECLARE_FLAGS(PrintDialogOptions, PrintDialogOption)
#ifndef QT_NO_PRINTDIALOG
- explicit QAbstractPrintDialog(QPrinter *printer, QWidget *parent = 0);
+ explicit QAbstractPrintDialog(QPrinter *printer, QWidget *parent = Q_NULLPTR);
~QAbstractPrintDialog();
virtual int exec() = 0;
@@ -101,7 +101,7 @@ public:
QPrinter *printer() const;
protected:
- QAbstractPrintDialog(QAbstractPrintDialogPrivate &ptr, QPrinter *printer, QWidget *parent = 0);
+ QAbstractPrintDialog(QAbstractPrintDialogPrivate &ptr, QPrinter *printer, QWidget *parent = Q_NULLPTR);
private:
Q_DISABLE_COPY(QAbstractPrintDialog)
diff --git a/src/printsupport/dialogs/qpagesetupdialog.h b/src/printsupport/dialogs/qpagesetupdialog.h
index 43b642b8f1..824d63f2d7 100644
--- a/src/printsupport/dialogs/qpagesetupdialog.h
+++ b/src/printsupport/dialogs/qpagesetupdialog.h
@@ -51,8 +51,8 @@ class Q_PRINTSUPPORT_EXPORT QPageSetupDialog : public QDialog
Q_DECLARE_PRIVATE(QPageSetupDialog)
public:
- explicit QPageSetupDialog(QPrinter *printer, QWidget *parent = 0);
- explicit QPageSetupDialog(QWidget *parent = 0);
+ explicit QPageSetupDialog(QPrinter *printer, QWidget *parent = Q_NULLPTR);
+ explicit QPageSetupDialog(QWidget *parent = Q_NULLPTR);
~QPageSetupDialog();
#if defined(Q_OS_MAC) || defined(Q_OS_WIN)
diff --git a/src/printsupport/dialogs/qpagesetupdialog_mac.mm b/src/printsupport/dialogs/qpagesetupdialog_mac.mm
index 886cbc0152..b86de31883 100644
--- a/src/printsupport/dialogs/qpagesetupdialog_mac.mm
+++ b/src/printsupport/dialogs/qpagesetupdialog_mac.mm
@@ -201,10 +201,9 @@ int QPageSetupDialog::exec()
QDialog::setVisible(true);
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
static_cast <QMacPageSetupDialogPrivate*>(d)->openCocoaPageLayout(Qt::ApplicationModal);
static_cast <QMacPageSetupDialogPrivate*>(d)->closeCocoaPageLayout();
- [pool release];
QDialog::setVisible(false);
diff --git a/src/printsupport/dialogs/qprintdialog.h b/src/printsupport/dialogs/qprintdialog.h
index 1332fcc1fd..cf0115cc28 100644
--- a/src/printsupport/dialogs/qprintdialog.h
+++ b/src/printsupport/dialogs/qprintdialog.h
@@ -53,8 +53,8 @@ class Q_PRINTSUPPORT_EXPORT QPrintDialog : public QAbstractPrintDialog
Q_PROPERTY(PrintDialogOptions options READ options WRITE setOptions)
public:
- explicit QPrintDialog(QPrinter *printer, QWidget *parent = 0);
- explicit QPrintDialog(QWidget *parent = 0);
+ explicit QPrintDialog(QPrinter *printer, QWidget *parent = Q_NULLPTR);
+ explicit QPrintDialog(QWidget *parent = Q_NULLPTR);
~QPrintDialog();
int exec() Q_DECL_OVERRIDE;
diff --git a/src/printsupport/dialogs/qprintdialog_mac.mm b/src/printsupport/dialogs/qprintdialog_mac.mm
index aec1e3babb..030526954d 100644
--- a/src/printsupport/dialogs/qprintdialog_mac.mm
+++ b/src/printsupport/dialogs/qprintdialog_mac.mm
@@ -36,7 +36,6 @@
#include "qprintdialog.h"
#include "qabstractprintdialog_p.h"
-#include <QtCore/qhash.h>
#include <QtCore/private/qcore_mac_p.h>
#include <QtWidgets/private/qapplication_p.h>
#include <QtPrintSupport/qprinter.h>
@@ -302,10 +301,9 @@ int QPrintDialog::exec()
QDialog::setVisible(true);
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
d->openCocoaPrintPanel(Qt::ApplicationModal);
d->closeCocoaPrintPanel();
- [pool release];
QDialog::setVisible(false);
diff --git a/src/printsupport/dialogs/qprintpreviewdialog.h b/src/printsupport/dialogs/qprintpreviewdialog.h
index 15e0271ba0..228cd24f48 100644
--- a/src/printsupport/dialogs/qprintpreviewdialog.h
+++ b/src/printsupport/dialogs/qprintpreviewdialog.h
@@ -52,8 +52,9 @@ class Q_PRINTSUPPORT_EXPORT QPrintPreviewDialog : public QDialog
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);
+ explicit QPrintPreviewDialog(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
+ explicit QPrintPreviewDialog(QPrinter *printer, QWidget *parent = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags());
~QPrintPreviewDialog();
using QDialog::open;
diff --git a/src/printsupport/kernel/qcups.cpp b/src/printsupport/kernel/qcups.cpp
index 8c67b416a9..2f0f1205ca 100644
--- a/src/printsupport/kernel/qcups.cpp
+++ b/src/printsupport/kernel/qcups.cpp
@@ -59,6 +59,16 @@ void QCUPSSupport::setCupsOption(QStringList &cupsOptions, const QString &option
}
}
+void QCUPSSupport::clearCupsOption(QStringList &cupsOptions, const QString &option)
+{
+ // ### use const_iterator once QList::erase takes them
+ const QStringList::iterator it = std::find(cupsOptions.begin(), cupsOptions.end(), option);
+ if (it != cupsOptions.end()) {
+ Q_ASSERT(it + 1 < cupsOptions.end());
+ cupsOptions.erase(it, it+1);
+ }
+}
+
static inline QString jobHoldToString(const QCUPSSupport::JobHoldUntil jobHold, const QTime holdUntilTime)
{
switch (jobHold) {
@@ -94,14 +104,16 @@ static inline QString jobHoldToString(const QCUPSSupport::JobHoldUntil jobHold,
void QCUPSSupport::setJobHold(QPrinter *printer, const JobHoldUntil jobHold, const QTime &holdUntilTime)
{
+ QStringList cupsOptions = cupsOptionsList(printer);
const QString jobHoldUntilArgument = jobHoldToString(jobHold, holdUntilTime);
if (!jobHoldUntilArgument.isEmpty()) {
- QStringList cupsOptions = cupsOptionsList(printer);
setCupsOption(cupsOptions,
QStringLiteral("job-hold-until"),
jobHoldUntilArgument);
- setCupsOptions(printer, cupsOptions);
+ } else {
+ clearCupsOption(cupsOptions, QStringLiteral("job-hold-until"));
}
+ setCupsOptions(printer, cupsOptions);
}
void QCUPSSupport::setJobBilling(QPrinter *printer, const QString &jobBilling)
diff --git a/src/printsupport/kernel/qcups_p.h b/src/printsupport/kernel/qcups_p.h
index afcb2c6f3b..f6ba983e9f 100644
--- a/src/printsupport/kernel/qcups_p.h
+++ b/src/printsupport/kernel/qcups_p.h
@@ -117,6 +117,7 @@ public:
static QStringList cupsOptionsList(QPrinter *printer);
static void setCupsOptions(QPrinter *printer, const QStringList &cupsOptions);
static void setCupsOption(QStringList &cupsOptions, const QString &option, const QString &value);
+ static void clearCupsOption(QStringList &cupsOptions, const QString &option);
static void setJobHold(QPrinter *printer, const JobHoldUntil jobHold = NoHold, const QTime &holdUntilTime = QTime());
static void setJobBilling(QPrinter *printer, const QString &jobBilling = QString());
@@ -127,6 +128,11 @@ public:
const PagesPerSheetLayout pagesPerSheetLayout);
static void setPageRange(QPrinter *printer, int pageFrom, int pageTo);
};
+Q_DECLARE_TYPEINFO(QCUPSSupport::JobHoldUntil, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QCUPSSupport::BannerPage, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QCUPSSupport::PageSet, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QCUPSSupport::PagesPerSheetLayout, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QCUPSSupport::PagesPerSheet, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE
diff --git a/src/printsupport/kernel/qpaintengine_alpha.cpp b/src/printsupport/kernel/qpaintengine_alpha.cpp
index 010a628e4f..710691453a 100644
--- a/src/printsupport/kernel/qpaintengine_alpha.cpp
+++ b/src/printsupport/kernel/qpaintengine_alpha.cpp
@@ -178,7 +178,8 @@ void QAlphaPaintEngine::drawPolygon(const QPointF *points, int pointCount, Polyg
Q_D(QAlphaPaintEngine);
QPolygonF poly;
- for (int i=0; i<pointCount; ++i)
+ poly.reserve(pointCount);
+ for (int i = 0; i < pointCount; ++i)
poly.append(points[i]);
QPainterPath path;
diff --git a/src/printsupport/kernel/qplatformprintplugin.cpp b/src/printsupport/kernel/qplatformprintplugin.cpp
index 091cc6f008..9adf39ffcd 100644
--- a/src/printsupport/kernel/qplatformprintplugin.cpp
+++ b/src/printsupport/kernel/qplatformprintplugin.cpp
@@ -55,6 +55,7 @@ QPlatformPrinterSupportPlugin::~QPlatformPrinterSupportPlugin()
static QPlatformPrinterSupport *printerSupport = 0;
+#ifndef QT_NO_LIBRARY
static void cleanupPrinterSupport()
{
#ifndef QT_NO_PRINTER
@@ -62,6 +63,7 @@ static void cleanupPrinterSupport()
#endif
printerSupport = 0;
}
+#endif // !QT_NO_LIBRARY
/*!
\internal
@@ -73,6 +75,7 @@ static void cleanupPrinterSupport()
*/
QPlatformPrinterSupport *QPlatformPrinterSupportPlugin::get()
{
+#ifndef QT_NO_LIBRARY
if (!printerSupport) {
const QMultiMap<int, QString> keyMap = loader()->keyMap();
if (!keyMap.isEmpty())
@@ -80,6 +83,7 @@ QPlatformPrinterSupport *QPlatformPrinterSupportPlugin::get()
if (printerSupport)
qAddPostRoutine(cleanupPrinterSupport);
}
+#endif // !QT_NO_LIBRARY
return printerSupport;
}
diff --git a/src/printsupport/kernel/qprint_p.h b/src/printsupport/kernel/qprint_p.h
index a097d26a9e..6a05cc1589 100644
--- a/src/printsupport/kernel/qprint_p.h
+++ b/src/printsupport/kernel/qprint_p.h
@@ -245,7 +245,7 @@ public:
// but where would it live? Not in base module as don't want to link to CUPS.
// May have to have two copies in plugins to keep in sync.
- static QPrint::InputSlot ppdChoiceToInputSlot(ppd_choice_t choice)
+ static QPrint::InputSlot ppdChoiceToInputSlot(const ppd_choice_t &choice)
{
QPrint::InputSlot input;
input.key = choice.choice;
@@ -255,7 +255,7 @@ public:
return input;
}
- static QPrint::OutputBin ppdChoiceToOutputBin(ppd_choice_t choice)
+ static QPrint::OutputBin ppdChoiceToOutputBin(const ppd_choice_t &choice)
{
QPrint::OutputBin output;
output.key = choice.choice;
diff --git a/src/printsupport/kernel/qprinter.cpp b/src/printsupport/kernel/qprinter.cpp
index e9009aa2f7..2cecf61573 100644
--- a/src/printsupport/kernel/qprinter.cpp
+++ b/src/printsupport/kernel/qprinter.cpp
@@ -160,7 +160,7 @@ void QPrinterPrivate::changeEngines(QPrinter::OutputFormat format, const QPrinte
initEngines(format, printer);
if (oldPrintEngine) {
- foreach (QPrintEngine::PrintEnginePropertyKey key, m_properties.values()) {
+ foreach (QPrintEngine::PrintEnginePropertyKey key, m_properties) {
QVariant prop;
// PPK_NumberOfCopies need special treatmeant since it in most cases
// will return 1, disregarding the actual value that was set
@@ -1942,7 +1942,9 @@ QList<int> QPrinter::supportedResolutions() const
QList<QVariant> varlist
= d->printEngine->property(QPrintEngine::PPK_SupportedResolutions).toList();
QList<int> intlist;
- for (int i=0; i<varlist.size(); ++i)
+ const int numSupportedResolutions = varlist.size();
+ intlist.reserve(numSupportedResolutions);
+ for (int i = 0; i < numSupportedResolutions; ++i)
intlist << varlist.at(i).toInt();
return intlist;
}
diff --git a/src/printsupport/kernel/qprinterinfo.cpp b/src/printsupport/kernel/qprinterinfo.cpp
index ad488a10ed..1be574891b 100644
--- a/src/printsupport/kernel/qprinterinfo.cpp
+++ b/src/printsupport/kernel/qprinterinfo.cpp
@@ -316,7 +316,9 @@ QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const
{
Q_D(const QPrinterInfo);
QList<QPrinter::PaperSize> list;
- foreach (const QPageSize &pageSize, d->m_printDevice.supportedPageSizes())
+ const QList<QPageSize> supportedPageSizes = d->m_printDevice.supportedPageSizes();
+ list.reserve(supportedPageSizes.size());
+ foreach (const QPageSize &pageSize, supportedPageSizes)
list.append(QPrinter::PaperSize(pageSize.id()));
return list;
}
@@ -336,7 +338,9 @@ QList<QPair<QString, QSizeF> > QPrinterInfo::supportedSizesWithNames() const
{
Q_D(const QPrinterInfo);
QList<QPair<QString, QSizeF> > list;
- foreach (const QPageSize &pageSize, d->m_printDevice.supportedPageSizes())
+ const QList<QPageSize> supportedPageSizes = d->m_printDevice.supportedPageSizes();
+ list.reserve(supportedPageSizes.size());
+ foreach (const QPageSize &pageSize, supportedPageSizes)
list.append(qMakePair(pageSize.name(), pageSize.size(QPageSize::Millimeter)));
return list;
}
@@ -376,7 +380,9 @@ QList<QPrinter::DuplexMode> QPrinterInfo::supportedDuplexModes() const
{
Q_D(const QPrinterInfo);
QList<QPrinter::DuplexMode> list;
- foreach (QPrint::DuplexMode mode, d->m_printDevice.supportedDuplexModes())
+ const QList<QPrint::DuplexMode> supportedDuplexModes = d->m_printDevice.supportedDuplexModes();
+ list.reserve(supportedDuplexModes.size());
+ foreach (QPrint::DuplexMode mode, supportedDuplexModes)
list << QPrinter::DuplexMode(mode);
return list;
}
@@ -416,7 +422,9 @@ QList<QPrinterInfo> QPrinterInfo::availablePrinters()
QList<QPrinterInfo> list;
QPlatformPrinterSupport *ps = QPlatformPrinterSupportPlugin::get();
if (ps) {
- foreach (const QString &id, ps->availablePrintDeviceIds())
+ const QStringList availablePrintDeviceIds = ps->availablePrintDeviceIds();
+ list.reserve(availablePrintDeviceIds.size());
+ foreach (const QString &id, availablePrintDeviceIds)
list.append(QPrinterInfo(id));
}
return list;
diff --git a/src/printsupport/widgets/qcupsjobwidget.cpp b/src/printsupport/widgets/qcupsjobwidget.cpp
index ce8b0d1ed3..43ec37e119 100644
--- a/src/printsupport/widgets/qcupsjobwidget.cpp
+++ b/src/printsupport/widgets/qcupsjobwidget.cpp
@@ -48,7 +48,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_PRINTER
+#if !defined(QT_NO_PRINTER) && !defined(QT_NO_CUPS)
/*!
\internal
@@ -206,6 +206,6 @@ QCUPSSupport::BannerPage QCupsJobWidget::endBannerPage() const
return m_ui.endBannerPageCombo->itemData(m_ui.endBannerPageCombo->currentIndex()).value<QCUPSSupport::BannerPage>();
}
-#endif // QT_NO_PRINTER
+#endif // QT_NO_PRINTER / QT_NO_CUPS
QT_END_NAMESPACE
diff --git a/src/printsupport/widgets/qcupsjobwidget_p.h b/src/printsupport/widgets/qcupsjobwidget_p.h
index dfd2016130..65fea24d2a 100644
--- a/src/printsupport/widgets/qcupsjobwidget_p.h
+++ b/src/printsupport/widgets/qcupsjobwidget_p.h
@@ -52,7 +52,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_PRINTER
+#if !defined(QT_NO_PRINTER) && !defined(QT_NO_CUPS)
class QString;
class QTime;
@@ -100,7 +100,7 @@ private:
Q_DISABLE_COPY(QCupsJobWidget)
};
-#endif // QT_NO_PRINTER
+#endif // QT_NO_PRINTER / QT_NO_CUPS
QT_END_NAMESPACE
diff --git a/src/printsupport/widgets/qprintpreviewwidget.h b/src/printsupport/widgets/qprintpreviewwidget.h
index e88b421ca9..16b388d936 100644
--- a/src/printsupport/widgets/qprintpreviewwidget.h
+++ b/src/printsupport/widgets/qprintpreviewwidget.h
@@ -62,8 +62,9 @@ public:
FitInView
};
- explicit QPrintPreviewWidget(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0);
- explicit QPrintPreviewWidget(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit QPrintPreviewWidget(QPrinter *printer, QWidget *parent = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags());
+ explicit QPrintPreviewWidget(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QPrintPreviewWidget();
qreal zoomFactor() const;
diff --git a/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp b/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
index c3b3b8e817..95422c9e7b 100644
--- a/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
+++ b/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
@@ -80,7 +80,7 @@ if (db.open()) {
//! [4]
...
// MySQL connection
-db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server
+db.setConnectOptions("SSL_KEY=client-key.pem;SSL_CERT=client-cert.pem;SSL_CA=ca-cert.pem;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server
if (!db.open()) {
db.setConnectOptions(); // clears the connect option string
...
diff --git a/src/sql/drivers/mysql/qsql_mysql.cpp b/src/sql/drivers/mysql/qsql_mysql.cpp
index d901008e00..ea8a918dcf 100644
--- a/src/sql/drivers/mysql/qsql_mysql.cpp
+++ b/src/sql/drivers/mysql/qsql_mysql.cpp
@@ -45,6 +45,7 @@
#include <qstringlist.h>
#include <qtextcodec.h>
#include <qvector.h>
+#include <qfile.h>
#include <qdebug.h>
@@ -236,7 +237,11 @@ static QVariant::Type qDecodeMYSQLType(int mysqltype, uint flags)
QVariant::Type type;
switch (mysqltype) {
case FIELD_TYPE_TINY :
+ type = static_cast<QVariant::Type>((flags & UNSIGNED_FLAG) ? QMetaType::UChar : QMetaType::Char);
+ break;
case FIELD_TYPE_SHORT :
+ type = static_cast<QVariant::Type>((flags & UNSIGNED_FLAG) ? QMetaType::UShort : QMetaType::Short);
+ break;
case FIELD_TYPE_LONG :
case FIELD_TYPE_INT24 :
type = (flags & UNSIGNED_FLAG) ? QVariant::UInt : QVariant::Int;
@@ -315,14 +320,12 @@ static bool qIsBlob(int t)
static bool qIsInteger(int t)
{
- return t == MYSQL_TYPE_TINY
- || t == MYSQL_TYPE_SHORT
- || t == MYSQL_TYPE_LONG
- || t == MYSQL_TYPE_LONGLONG
- || t == MYSQL_TYPE_INT24;
+ return t == QMetaType::Char || t == QMetaType::UChar
+ || t == QMetaType::Short || t == QMetaType::UShort
+ || t == QMetaType::Int || t == QMetaType::UInt
+ || t == QMetaType::LongLong || t == QMetaType::ULongLong;
}
-
void QMYSQLResultPrivate::bindBlobs()
{
int i;
@@ -370,14 +373,9 @@ bool QMYSQLResultPrivate::bindInValues()
// after mysql_stmt_exec() in QMYSQLResult::exec()
fieldInfo->length = 0;
hasBlobs = true;
+ } else if (qIsInteger(f.type)) {
+ fieldInfo->length = 8;
} else {
- // fieldInfo->length specifies the display width, which may be too
- // small to hold valid integer values (see
- // http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html ), so
- // always use the MAX_BIGINT_WIDTH for integer types
- if (qIsInteger(fieldInfo->type)) {
- fieldInfo->length = MAX_BIGINT_WIDTH;
- }
fieldInfo->type = MYSQL_TYPE_STRING;
}
bind = &inBinds[i];
@@ -597,6 +595,9 @@ QVariant QMYSQLResult::data(int field)
if (f.nullIndicator)
return QVariant(f.type);
+ if (qIsInteger(f.type))
+ return QVariant(f.type, f.outField);
+
if (f.type != QVariant::ByteArray)
val = toUnicode(d->driver->d_func()->tc, f.outField, f.bufLength);
} else {
@@ -604,18 +605,24 @@ QVariant QMYSQLResult::data(int field)
// NULL value
return QVariant(f.type);
}
+
fieldLength = mysql_fetch_lengths(d->result)[field];
+
if (f.type != QVariant::ByteArray)
val = toUnicode(d->driver->d_func()->tc, d->row[field], fieldLength);
}
- switch(f.type) {
+ switch (static_cast<int>(f.type)) {
case QVariant::LongLong:
return QVariant(val.toLongLong());
case QVariant::ULongLong:
return QVariant(val.toULongLong());
+ case QMetaType::Char:
+ case QMetaType::Short:
case QVariant::Int:
return QVariant(val.toInt());
+ case QMetaType::UChar:
+ case QMetaType::UShort:
case QVariant::UInt:
return QVariant(val.toUInt());
case QVariant::Double: {
@@ -1211,7 +1218,7 @@ static void setOptionFlag(uint &optionFlags, const QString &opt)
else if (opt == QLatin1String("CLIENT_ODBC"))
optionFlags |= CLIENT_ODBC;
else if (opt == QLatin1String("CLIENT_SSL"))
- optionFlags |= CLIENT_SSL;
+ qWarning("QMYSQLDriver: SSL_KEY, SSL_CERT and SSL_CA should be used instead of CLIENT_SSL.");
else
qWarning("QMYSQLDriver::open: Unknown connect option '%s'", opt.toLocal8Bit().constData());
}
@@ -1235,6 +1242,11 @@ bool QMYSQLDriver::open(const QString& db,
unsigned int optionFlags = Q_CLIENT_MULTI_STATEMENTS;
const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
QString unixSocket;
+ QString sslCert;
+ QString sslCA;
+ QString sslKey;
+ QString sslCAPath;
+ QString sslCipher;
#if MYSQL_VERSION_ID >= 50000
my_bool reconnect=false;
uint connectTimeout = 0;
@@ -1263,6 +1275,16 @@ bool QMYSQLDriver::open(const QString& db,
writeTimeout = val.toInt();
}
#endif
+ else if (opt == QLatin1String("SSL_KEY"))
+ sslKey = val;
+ else if (opt == QLatin1String("SSL_CERT"))
+ sslCert = val;
+ else if (opt == QLatin1String("SSL_CA"))
+ sslCA = val;
+ else if (opt == QLatin1String("SSL_CAPATH"))
+ sslCAPath = val;
+ else if (opt == QLatin1String("SSL_CIPHER"))
+ sslCipher = val;
else if (val == QLatin1String("TRUE") || val == QLatin1String("1"))
setOptionFlag(optionFlags, tmp.left(idx).simplified());
else
@@ -1273,39 +1295,60 @@ bool QMYSQLDriver::open(const QString& db,
}
}
- if ((d->mysql = mysql_init((MYSQL*) 0))) {
+ if (!(d->mysql = mysql_init((MYSQL*) 0))) {
+ setLastError(qMakeError(tr("Unable to allocate a MYSQL object"),
+ QSqlError::ConnectionError, d));
+ setOpenError(true);
+ return false;
+ }
+
+ if (!sslKey.isNull() || !sslCert.isNull() || !sslCA.isNull() ||
+ !sslCAPath.isNull() || !sslCipher.isNull()) {
+ mysql_ssl_set(d->mysql,
+ sslKey.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslKey).constData(),
+ sslCert.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCert).constData(),
+ sslCA.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCA).constData(),
+ sslCAPath.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCAPath).constData(),
+ sslCipher.isNull() ? static_cast<const char *>(0)
+ : sslCipher.toLocal8Bit().constData());
+ }
+
#if MYSQL_VERSION_ID >= 50000
- if (connectTimeout != 0)
- mysql_options(d->mysql, MYSQL_OPT_CONNECT_TIMEOUT, &connectTimeout);
- if (readTimeout != 0)
- mysql_options(d->mysql, MYSQL_OPT_READ_TIMEOUT, &readTimeout);
- if (writeTimeout != 0)
- mysql_options(d->mysql, MYSQL_OPT_WRITE_TIMEOUT, &writeTimeout);
+ if (connectTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_CONNECT_TIMEOUT, &connectTimeout);
+ if (readTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_READ_TIMEOUT, &readTimeout);
+ if (writeTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_WRITE_TIMEOUT, &writeTimeout);
#endif
- if (mysql_real_connect(d->mysql,
- host.isNull() ? static_cast<const char *>(0)
- : host.toLocal8Bit().constData(),
- user.isNull() ? static_cast<const char *>(0)
- : user.toLocal8Bit().constData(),
- password.isNull() ? static_cast<const char *>(0)
- : password.toLocal8Bit().constData(),
- db.isNull() ? static_cast<const char *>(0)
- : db.toLocal8Bit().constData(),
- (port > -1) ? port : 0,
- unixSocket.isNull() ? static_cast<const char *>(0)
- : unixSocket.toLocal8Bit().constData(),
- optionFlags)) {
- if (!db.isEmpty() && mysql_select_db(d->mysql, db.toLocal8Bit().constData())) {
- setLastError(qMakeError(tr("Unable to open database '%1'").arg(db), QSqlError::ConnectionError, d));
- mysql_close(d->mysql);
- setOpenError(true);
- return false;
- }
+ if (mysql_real_connect(d->mysql,
+ host.isNull() ? static_cast<const char *>(0)
+ : host.toLocal8Bit().constData(),
+ user.isNull() ? static_cast<const char *>(0)
+ : user.toLocal8Bit().constData(),
+ password.isNull() ? static_cast<const char *>(0)
+ : password.toLocal8Bit().constData(),
+ db.isNull() ? static_cast<const char *>(0)
+ : db.toLocal8Bit().constData(),
+ (port > -1) ? port : 0,
+ unixSocket.isNull() ? static_cast<const char *>(0)
+ : unixSocket.toLocal8Bit().constData(),
+ optionFlags))
+ {
+ if (!db.isEmpty() && mysql_select_db(d->mysql, db.toLocal8Bit().constData())) {
+ setLastError(qMakeError(tr("Unable to open database '%1'").arg(db), QSqlError::ConnectionError, d));
+ mysql_close(d->mysql);
+ setOpenError(true);
+ return false;
+ }
#if MYSQL_VERSION_ID >= 50000
- if (reconnect)
- mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
+ if (reconnect)
+ mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
#endif
- }
} else {
setLastError(qMakeError(tr("Unable to connect"),
QSqlError::ConnectionError, d));
diff --git a/src/sql/kernel/qsqldatabase.cpp b/src/sql/kernel/qsqldatabase.cpp
index 240e19bf20..90c64d7331 100644
--- a/src/sql/kernel/qsqldatabase.cpp
+++ b/src/sql/kernel/qsqldatabase.cpp
@@ -1218,7 +1218,6 @@ QSqlRecord QSqlDatabase::record(const QString& tablename) const
\li CLIENT_COMPRESS
\li CLIENT_FOUND_ROWS
\li CLIENT_IGNORE_SPACE
- \li CLIENT_SSL
\li CLIENT_ODBC
\li CLIENT_NO_SCHEMA
\li CLIENT_INTERACTIVE
@@ -1227,6 +1226,11 @@ QSqlRecord QSqlDatabase::record(const QString& tablename) const
\li MYSQL_OPT_CONNECT_TIMEOUT
\li MYSQL_OPT_READ_TIMEOUT
\li MYSQL_OPT_WRITE_TIMEOUT
+ \li SSL_KEY
+ \li SSL_CERT
+ \li SSL_CA
+ \li SSL_CAPATH
+ \li SSL_CIPHER
\endlist
\li
diff --git a/src/sql/kernel/qsqldriver.h b/src/sql/kernel/qsqldriver.h
index e8375765aa..c53e1b81ee 100644
--- a/src/sql/kernel/qsqldriver.h
+++ b/src/sql/kernel/qsqldriver.h
@@ -83,7 +83,7 @@ public:
DB2
};
- explicit QSqlDriver(QObject *parent=0);
+ explicit QSqlDriver(QObject *parent = Q_NULLPTR);
~QSqlDriver();
virtual bool isOpen() const;
bool isOpenError() const;
@@ -133,7 +133,7 @@ Q_SIGNALS:
void notification(const QString &name, QSqlDriver::NotificationSource source, const QVariant &payload);
protected:
- QSqlDriver(QSqlDriverPrivate &dd, QObject *parent = 0);
+ QSqlDriver(QSqlDriverPrivate &dd, QObject *parent = Q_NULLPTR);
virtual void setOpen(bool o);
virtual void setOpenError(bool e);
virtual void setLastError(const QSqlError& e);
diff --git a/src/sql/kernel/qsqldriverplugin.h b/src/sql/kernel/qsqldriverplugin.h
index 55b8c81878..fd1a6203cb 100644
--- a/src/sql/kernel/qsqldriverplugin.h
+++ b/src/sql/kernel/qsqldriverplugin.h
@@ -49,7 +49,7 @@ class Q_SQL_EXPORT QSqlDriverPlugin : public QObject
{
Q_OBJECT
public:
- explicit QSqlDriverPlugin(QObject *parent = 0);
+ explicit QSqlDriverPlugin(QObject *parent = Q_NULLPTR);
~QSqlDriverPlugin();
virtual QSqlDriver *create(const QString &key) = 0;
diff --git a/src/sql/kernel/qsqlindex.cpp b/src/sql/kernel/qsqlindex.cpp
index 53e13c85e6..bb80cf3e03 100644
--- a/src/sql/kernel/qsqlindex.cpp
+++ b/src/sql/kernel/qsqlindex.cpp
@@ -38,6 +38,9 @@
QT_BEGIN_NAMESPACE
+// ### Qt 6: remove the static assertion, the 'sorts' field was changed from QList to QVector in Qt 5.6
+Q_STATIC_ASSERT((sizeof(QList<bool>) == sizeof(QVector<bool>)));
+
/*!
\class QSqlIndex
\brief The QSqlIndex class provides functions to manipulate and
diff --git a/src/sql/kernel/qsqlindex.h b/src/sql/kernel/qsqlindex.h
index d3d4a7c9aa..4a81d48161 100644
--- a/src/sql/kernel/qsqlindex.h
+++ b/src/sql/kernel/qsqlindex.h
@@ -36,7 +36,10 @@
#include <QtSql/qsqlrecord.h>
#include <QtCore/qstring.h>
+#include <QtCore/qvector.h>
+#if QT_DEPRECATED_SINCE(5,6)
#include <QtCore/qlist.h>
+#endif
QT_BEGIN_NAMESPACE
@@ -63,7 +66,7 @@ private:
QString createField(int i, const QString& prefix, bool verbose) const;
QString cursor;
QString nm;
- QList<bool> sorts;
+ QVector<bool> sorts;
};
QT_END_NAMESPACE
diff --git a/src/sql/models/qsqlquerymodel.h b/src/sql/models/qsqlquerymodel.h
index 2d37b9a482..5c7c22af10 100644
--- a/src/sql/models/qsqlquerymodel.h
+++ b/src/sql/models/qsqlquerymodel.h
@@ -51,7 +51,7 @@ class Q_SQL_EXPORT QSqlQueryModel: public QAbstractTableModel
Q_DECLARE_PRIVATE(QSqlQueryModel)
public:
- explicit QSqlQueryModel(QObject *parent = 0);
+ explicit QSqlQueryModel(QObject *parent = Q_NULLPTR);
virtual ~QSqlQueryModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
@@ -98,7 +98,7 @@ protected:
virtual QModelIndex indexInQuery(const QModelIndex &item) const;
void setLastError(const QSqlError &error);
- QSqlQueryModel(QSqlQueryModelPrivate &dd, QObject *parent = 0);
+ QSqlQueryModel(QSqlQueryModelPrivate &dd, QObject *parent = Q_NULLPTR);
};
QT_END_NAMESPACE
diff --git a/src/sql/models/qsqlrelationaltablemodel.h b/src/sql/models/qsqlrelationaltablemodel.h
index f7470142d6..f2a546dc1a 100644
--- a/src/sql/models/qsqlrelationaltablemodel.h
+++ b/src/sql/models/qsqlrelationaltablemodel.h
@@ -70,7 +70,7 @@ public:
LeftJoin
};
- explicit QSqlRelationalTableModel(QObject *parent = 0,
+ explicit QSqlRelationalTableModel(QObject *parent = Q_NULLPTR,
QSqlDatabase db = QSqlDatabase());
virtual ~QSqlRelationalTableModel();
diff --git a/src/sql/models/qsqltablemodel.h b/src/sql/models/qsqltablemodel.h
index a06abefb1c..5481a777a1 100644
--- a/src/sql/models/qsqltablemodel.h
+++ b/src/sql/models/qsqltablemodel.h
@@ -53,7 +53,7 @@ class Q_SQL_EXPORT QSqlTableModel: public QSqlQueryModel
public:
enum EditStrategy {OnFieldChange, OnRowChange, OnManualSubmit};
- explicit QSqlTableModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase());
+ explicit QSqlTableModel(QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase());
virtual ~QSqlTableModel();
virtual void setTable(const QString &tableName);
@@ -115,7 +115,7 @@ Q_SIGNALS:
void beforeDelete(int row);
protected:
- QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent = 0, QSqlDatabase db = QSqlDatabase());
+ QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase());
virtual bool updateRowInTable(int row, const QSqlRecord &values);
virtual bool insertRowIntoTable(const QSqlRecord &values);
diff --git a/src/src.pro b/src/src.pro
index 61e5ce2d8d..07ace99144 100644
--- a/src/src.pro
+++ b/src/src.pro
@@ -110,7 +110,7 @@ src_platformsupport.depends = src_corelib src_gui src_platformheaders
src_widgets.subdir = $$PWD/widgets
src_widgets.target = sub-widgets
-src_widgets.depends = src_corelib src_gui src_tools_uic
+src_widgets.depends = src_corelib src_gui src_tools_uic src_platformheaders
src_opengl.subdir = $$PWD/opengl
src_opengl.target = sub-opengl
diff --git a/src/testlib/qbenchmark_p.h b/src/testlib/qbenchmark_p.h
index d785f3d4b7..6312a34cb8 100644
--- a/src/testlib/qbenchmark_p.h
+++ b/src/testlib/qbenchmark_p.h
@@ -91,6 +91,7 @@ struct QBenchmarkContext
QBenchmarkContext() : checkpointIndex(-1) {}
};
+Q_DECLARE_TYPEINFO(QBenchmarkContext, Q_MOVABLE_TYPE);
class QBenchmarkResult
{
@@ -126,6 +127,7 @@ public:
return (value / iterations) < (other.value / other.iterations);
}
};
+Q_DECLARE_TYPEINFO(QBenchmarkResult, Q_MOVABLE_TYPE);
/*
The QBenchmarkGlobalData class stores global benchmark-related data.
diff --git a/src/testlib/qsignalspy.h b/src/testlib/qsignalspy.h
index cfde89aec8..1751220059 100644
--- a/src/testlib/qsignalspy.h
+++ b/src/testlib/qsignalspy.h
@@ -82,7 +82,7 @@ public:
}
if (!QMetaObject::connect(obj, sigIndex, this, memberOffset,
- Qt::DirectConnection, 0)) {
+ Qt::DirectConnection, Q_NULLPTR)) {
qWarning("QSignalSpy: QMetaObject::connect returned false. Unable to connect.");
return;
}
diff --git a/src/testlib/qtest.h b/src/testlib/qtest.h
index 994179958b..8da16af91e 100644
--- a/src/testlib/qtest.h
+++ b/src/testlib/qtest.h
@@ -51,6 +51,9 @@
#include <QtCore/qsize.h>
#include <QtCore/qrect.h>
+#ifdef QT_NETWORK_LIB
+# include <QtNetwork/qhostaddress.h>
+#endif
QT_BEGIN_NAMESPACE
@@ -162,6 +165,23 @@ template<> inline char *toString(const QVariant &v)
return qstrdup(vstring.constData());
}
+#ifdef QT_NETWORK_LIB
+template<> inline char *toString(const QHostAddress &addr)
+{
+ switch (addr.protocol()) {
+ case QAbstractSocket::UnknownNetworkLayerProtocol:
+ return qstrdup("<unknown address (parse error)>");
+ case QAbstractSocket::AnyIPProtocol:
+ return qstrdup("QHostAddress::Any");
+ case QAbstractSocket::IPv4Protocol:
+ case QAbstractSocket::IPv6Protocol:
+ break;
+ }
+
+ return qstrdup(addr.toString().toLatin1().constData());
+}
+#endif
+
template<>
inline bool qCompare(QString const &t1, QLatin1String const &t2, const char *actual,
const char *expected, const char *file, int line)
@@ -205,7 +225,7 @@ inline bool qCompare(QList<T> const &t1, QList<T> const &t2, const char *actual,
delete [] val2;
}
}
- return compare_helper(isOk, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(isOk, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
template <>
diff --git a/src/testlib/qtest_gui.h b/src/testlib/qtest_gui.h
index a474758de6..beae9ec065 100644
--- a/src/testlib/qtest_gui.h
+++ b/src/testlib/qtest_gui.h
@@ -86,24 +86,24 @@ inline bool qCompare(QImage const &t1, QImage const &t2,
qsnprintf(msg, 1024, "Compared QImages differ.\n"
" Actual (%s).isNull(): %d\n"
" Expected (%s).isNull(): %d", actual, t1Null, expected, t2Null);
- return compare_helper(false, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(false, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
if (t1Null && t2Null)
- return compare_helper(true, 0, 0, 0, actual, expected, file, line);
+ return compare_helper(true, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
if (t1.width() != t2.width() || t1.height() != t2.height()) {
qsnprintf(msg, 1024, "Compared QImages differ in size.\n"
" Actual (%s): %dx%d\n"
" Expected (%s): %dx%d",
actual, t1.width(), t1.height(),
expected, t2.width(), t2.height());
- return compare_helper(false, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(false, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
if (t1.format() != t2.format()) {
qsnprintf(msg, 1024, "Compared QImages differ in format.\n"
" Actual (%s): %d\n"
" Expected (%s): %d",
actual, t1.format(), expected, t2.format());
- return compare_helper(false, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(false, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
return compare_helper(t1 == t2, "Compared values are not the same",
toString(t1), toString(t2), actual, expected, file, line);
@@ -120,17 +120,17 @@ inline bool qCompare(QPixmap const &t1, QPixmap const &t2, const char *actual, c
qsnprintf(msg, 1024, "Compared QPixmaps differ.\n"
" Actual (%s).isNull(): %d\n"
" Expected (%s).isNull(): %d", actual, t1Null, expected, t2Null);
- return compare_helper(false, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(false, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
if (t1Null && t2Null)
- return compare_helper(true, 0, 0, 0, actual, expected, file, line);
+ return compare_helper(true, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
if (t1.width() != t2.width() || t1.height() != t2.height()) {
qsnprintf(msg, 1024, "Compared QPixmaps differ in size.\n"
" Actual (%s): %dx%d\n"
" Expected (%s): %dx%d",
actual, t1.width(), t1.height(),
expected, t2.width(), t2.height());
- return compare_helper(false, msg, 0, 0, actual, expected, file, line);
+ return compare_helper(false, msg, Q_NULLPTR, Q_NULLPTR, actual, expected, file, line);
}
return qCompare(t1.toImage(), t2.toImage(), actual, expected, file, line);
}
diff --git a/src/testlib/qtestaccessible.h b/src/testlib/qtestaccessible.h
index f1ac625dbd..628145f3b0 100644
--- a/src/testlib/qtestaccessible.h
+++ b/src/testlib/qtestaccessible.h
@@ -126,7 +126,7 @@ public:
static void cleanup()
{
delete instance();
- instance() = 0;
+ instance() = Q_NULLPTR;
}
static void clearEvents() { eventList().clear(); }
static EventList events() { return eventList(); }
@@ -162,8 +162,8 @@ private:
~QTestAccessibility()
{
- QAccessible::installUpdateHandler(0);
- QAccessible::installRootObjectHandler(0);
+ QAccessible::installUpdateHandler(Q_NULLPTR);
+ QAccessible::installRootObjectHandler(Q_NULLPTR);
}
static void rootObjectHandler(QObject *object)
@@ -268,7 +268,7 @@ private:
static QTestAccessibility *&instance()
{
- static QTestAccessibility *ta = 0;
+ static QTestAccessibility *ta = Q_NULLPTR;
return ta;
}
diff --git a/src/testlib/qtestblacklist.cpp b/src/testlib/qtestblacklist.cpp
index 28a2878b32..eb7abdad46 100644
--- a/src/testlib/qtestblacklist.cpp
+++ b/src/testlib/qtestblacklist.cpp
@@ -37,6 +37,9 @@
#include <QtTest/qtest.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qfile.h>
+#include <QtCore/qset.h>
+#include <QtCore/qcoreapplication.h>
+#include <QtCore/qvariant.h>
#include <QtCore/QSysInfo>
#include <set>
@@ -61,83 +64,87 @@ QT_BEGIN_NAMESPACE
The known keys are listed below:
*/
-// this table can be extended with new keywords as required
-const char *matchedConditions[] =
+static QSet<QByteArray> keywords()
{
- "*",
+ // this list can be extended with new keywords as required
+ QSet<QByteArray> set = QSet<QByteArray>()
+ << "*"
#ifdef Q_OS_LINUX
- "linux",
+ << "linux"
#endif
#ifdef Q_OS_OSX
- "osx",
+ << "osx"
#endif
#ifdef Q_OS_WIN
- "windows",
+ << "windows"
#endif
#ifdef Q_OS_IOS
- "ios",
+ << "ios"
#endif
#ifdef Q_OS_ANDROID
- "android",
+ << "android"
#endif
#ifdef Q_OS_QNX
- "qnx",
+ << "qnx"
#endif
#ifdef Q_OS_WINRT
- "winrt",
+ << "winrt"
#endif
#ifdef Q_OS_WINCE
- "wince",
+ << "wince"
#endif
#if QT_POINTER_SIZE == 8
- "64bit",
+ << "64bit"
#else
- "32bit",
+ << "32bit"
#endif
#ifdef Q_CC_GNU
- "gcc",
+ << "gcc"
#endif
#ifdef Q_CC_CLANG
- "clang",
+ << "clang"
#endif
#ifdef Q_CC_MSVC
- "msvc",
+ << "msvc"
#ifdef _MSC_VER
#if _MSC_VER == 1800
- "msvc-2013",
+ << "msvc-2013"
#elif _MSC_VER == 1700
- "msvc-2012",
+ << "msvc-2012"
#elif _MSC_VER == 1600
- "msvc-2010",
+ << "msvc-2010"
#endif
#endif
#endif
#ifdef Q_AUTOTEST_EXPORT
- "developer-build",
+ << "developer-build"
#endif
- 0
-};
+ ;
+ QCoreApplication *app = QCoreApplication::instance();
+ if (app) {
+ const QVariant platformName = app->property("platformName");
+ if (platformName.isValid())
+ set << platformName.toByteArray();
+ }
+
+ return set;
+}
static bool checkCondition(const QByteArray &condition)
{
+ static QSet<QByteArray> matchedConditions = keywords();
QList<QByteArray> conds = condition.split(' ');
- std::set<QByteArray> matches;
- const char **m = matchedConditions;
- while (*m) {
- matches.insert(*m);
- ++m;
- }
QByteArray distributionName = QSysInfo::productType().toLower().toUtf8();
QByteArray distributionRelease = QSysInfo::productVersion().toLower().toUtf8();
if (!distributionName.isEmpty()) {
- if (matches.find(distributionName) == matches.end())
- matches.insert(distributionName);
- matches.insert(distributionName + "-" + distributionRelease);
+ if (matchedConditions.find(distributionName) == matchedConditions.end())
+ matchedConditions.insert(distributionName);
+ matchedConditions.insert(distributionName + "-" + distributionRelease);
}
for (int i = 0; i < conds.size(); ++i) {
@@ -146,7 +153,7 @@ static bool checkCondition(const QByteArray &condition)
if (result)
c = c.mid(1);
- result ^= (matches.find(c) != matches.end());
+ result ^= matchedConditions.contains(c);
if (!result)
return false;
}
@@ -159,6 +166,19 @@ static std::set<QByteArray> *gpuFeatures = 0;
Q_TESTLIB_EXPORT std::set<QByteArray> *(*qgpu_features_ptr)(const QString &) = 0;
+static bool isGPUTestBlacklisted(const char *slot, const char *data = 0)
+{
+ const QByteArray disableKey = QByteArrayLiteral("disable_") + QByteArray(slot);
+ if (gpuFeatures->find(disableKey) != gpuFeatures->end()) {
+ QByteArray msg = QByteArrayLiteral("Skipped due to GPU blacklist: ") + disableKey;
+ if (data)
+ msg += QByteArrayLiteral(":") + QByteArray(data);
+ QTest::qSkip(msg.constData(), __FILE__, __LINE__);
+ return true;
+ }
+ return false;
+}
+
namespace QTestPrivate {
void parseBlackList()
@@ -223,10 +243,12 @@ void checkBlackLists(const char *slot, const char *data)
// Tests blacklisted in GPU_BLACKLIST are to be skipped. Just ignoring the result is
// not sufficient since these are expected to crash or behave in undefined ways.
if (!ignore && gpuFeatures) {
- const QByteArray disableKey = QByteArrayLiteral("disable_") + QByteArray(slot);
- if (gpuFeatures->find(disableKey) != gpuFeatures->end()) {
- const QByteArray msg = QByteArrayLiteral("Skipped due to GPU blacklist: ") + disableKey;
- QTest::qSkip(msg.constData(), __FILE__, __LINE__);
+ QByteArray s_gpu = slot;
+ ignore = isGPUTestBlacklisted(s_gpu, data);
+ if (!ignore && data) {
+ s_gpu += ':';
+ s_gpu += data;
+ isGPUTestBlacklisted(s_gpu);
}
}
}
diff --git a/src/testlib/qtestblacklist_p.h b/src/testlib/qtestblacklist_p.h
index 0107e5d282..87f4dfdb5e 100644
--- a/src/testlib/qtestblacklist_p.h
+++ b/src/testlib/qtestblacklist_p.h
@@ -50,9 +50,10 @@
QT_BEGIN_NAMESPACE
namespace QTestPrivate {
- void parseBlackList();
- void parseGpuBlackList();
- void checkBlackLists(const char *slot, const char *data);
+ // Export functions so they can also be used by QQuickTest
+ Q_TESTLIB_EXPORT void parseBlackList();
+ Q_TESTLIB_EXPORT void parseGpuBlackList();
+ Q_TESTLIB_EXPORT void checkBlackLists(const char *slot, const char *data);
}
QT_END_NAMESPACE
diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp
index efc18180db..1a74bab538 100644
--- a/src/testlib/qtestcase.cpp
+++ b/src/testlib/qtestcase.cpp
@@ -50,6 +50,9 @@
#include <QtCore/private/qtools_p.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qtemporarydir.h>
+#include <QtCore/qthread.h>
+#include <QtCore/qwaitcondition.h>
+#include <QtCore/qmutex.h>
#include <QtTest/private/qtestlog_p.h>
#include <QtTest/private/qtesttable_p.h>
@@ -70,6 +73,12 @@
#include <stdio.h>
#include <stdlib.h>
+#if defined(Q_OS_LINUX)
+#include <sys/types.h>
+#include <unistd.h>
+#include <fcntl.h>
+#endif
+
#ifdef Q_OS_WIN
#ifndef Q_OS_WINCE
# if !defined(Q_CC_MINGW) || (defined(Q_CC_MINGW) && defined(__MINGW64_VERSION_MAJOR))
@@ -93,6 +102,40 @@ QT_BEGIN_NAMESPACE
using QtMiscUtils::toHexUpper;
using QtMiscUtils::fromHex;
+
+static void stackTrace()
+{
+ bool ok = false;
+ const int disableStackDump = qEnvironmentVariableIntValue("QTEST_DISABLE_STACK_DUMP", &ok);
+ if (ok && disableStackDump == 1)
+ return;
+#ifdef Q_OS_LINUX
+ fprintf(stderr, "\n========= Received signal, dumping stack ==============\n");
+ char cmd[512];
+ qsnprintf(cmd, 512, "gdb --pid %d 2>/dev/null <<EOF\n"
+ "set prompt\n"
+ "thread apply all where full\n"
+ "detach\n"
+ "quit\n"
+ "EOF\n",
+ (int)getpid());
+ if (system(cmd) == -1)
+ fprintf(stderr, "calling gdb failed\n");
+ fprintf(stderr, "========= End of stack trace ==============\n");
+#elif defined(Q_OS_OSX)
+ fprintf(stderr, "\n========= Received signal, dumping stack ==============\n");
+ char cmd[512];
+ qsnprintf(cmd, 512, "lldb -p %d 2>/dev/null <<EOF\n"
+ "bt all\n"
+ "quit\n"
+ "EOF\n",
+ (int)getpid());
+ if (system(cmd) == -1)
+ fprintf(stderr, "calling lldb failed\n");
+ fprintf(stderr, "========= End of stack trace ==============\n");
+#endif
+}
+
/*!
\namespace QTest
\inmodule QtTest
@@ -205,7 +248,7 @@ using QtMiscUtils::fromHex;
\note This macro can only be used in a test function that is invoked
by the test framework.
- \sa QTRY_VERIFY(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
+ \sa QTRY_VERIFY(), QTRY_VERIFY2_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
*/
@@ -219,7 +262,47 @@ using QtMiscUtils::fromHex;
\note This macro can only be used in a test function that is invoked
by the test framework.
- \sa QTRY_VERIFY_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
+ \sa QTRY_VERIFY_WITH_TIMEOUT(), QTRY_VERIFY2(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
+*/
+
+/*! \macro QTRY_VERIFY2_WITH_TIMEOUT(condition, message, timeout)
+ \since 5.6
+
+ \relates QTest
+
+ The QTRY_VERIFY2_WITH_TIMEOUT macro is similar to QTRY_VERIFY_WITH_TIMEOUT()
+ except that it outputs a verbose \a message when \a condition is still false
+ after the specified timeout. The \a message is a plain C string.
+
+ Example:
+ \code
+ QTRY_VERIFY2_WITH_TIMEOUT(list.size() > 2, QByteArray::number(list.size()).constData(), 10000);
+ \endcode
+
+ \note This macro can only be used in a test function that is invoked
+ by the test framework.
+
+ \sa QTRY_VERIFY(), QTRY_VERIFY_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
+*/
+
+/*! \macro QTRY_VERIFY2(condition, message)
+ \since 5.6
+
+ \relates QTest
+
+ Checks the \a condition by invoking QTRY_VERIFY2_WITH_TIMEOUT() with a timeout
+ of five seconds. If \a condition is then still false, \a message is output.
+ The \a message is a plain C string.
+
+ Example:
+ \code
+ QTRY_VERIFY2_WITH_TIMEOUT(list.size() > 2, QByteArray::number(list.size()).constData());
+ \endcode
+
+ \note This macro can only be used in a test function that is invoked
+ by the test framework.
+
+ \sa QTRY_VERIFY2_WITH_TIMEOUT(), QTRY_VERIFY2(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
*/
/*! \macro QTRY_COMPARE_WITH_TIMEOUT(actual, expected, timeout)
@@ -1276,7 +1359,7 @@ using QtMiscUtils::fromHex;
*/
/*!
- \fn QTouchEventSequence QTest::touchEvent(QWindow *window, QTouchDevice *device, bool autoCommit = true)
+ \fn QTouchEventSequence QTest::touchEvent(QWindow *window, QTouchDevice *device, bool autoCommit)
\since 5.0
Creates and returns a QTouchEventSequence for the \a device to
@@ -1293,7 +1376,7 @@ using QtMiscUtils::fromHex;
*/
/*!
- \fn QTouchEventSequence QTest::touchEvent(QWidget *widget, QTouchDevice *device, bool autoCommit = true)
+ \fn QTouchEventSequence QTest::touchEvent(QWidget *widget, QTouchDevice *device, bool autoCommit)
Creates and returns a QTouchEventSequence for the \a device to
simulate events for \a widget.
@@ -1883,7 +1966,7 @@ Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, char *argv[], bool qml)
QTestLog::addLogger(logFormat, logFilename);
}
-QBenchmarkResult qMedian(const QList<QBenchmarkResult> &container)
+QBenchmarkResult qMedian(const QVector<QBenchmarkResult> &container)
{
const int count = container.count();
if (count == 0)
@@ -1892,7 +1975,7 @@ QBenchmarkResult qMedian(const QList<QBenchmarkResult> &container)
if (count == 1)
return container.front();
- QList<QBenchmarkResult> containerCopy = container;
+ QVector<QBenchmarkResult> containerCopy = container;
std::sort(containerCopy.begin(), containerCopy.end());
const int middle = count / 2;
@@ -1929,7 +2012,7 @@ static void qInvokeTestMethodDataEntry(char *slot)
bool isBenchmark = false;
int i = (QBenchmarkGlobalData::current->measurer->needsWarmupIteration()) ? -1 : 0;
- QList<QBenchmarkResult> results;
+ QVector<QBenchmarkResult> results;
bool minimumTotalReached = false;
do {
QBenchmarkTestMethodData::current->beginDataRun();
@@ -2011,6 +2094,58 @@ static void qInvokeTestMethodDataEntry(char *slot)
}
}
+class WatchDog : public QThread
+{
+public:
+ WatchDog()
+ {
+ QMutexLocker locker(&mutex);
+ timeout.store(-1);
+ start();
+ waitCondition.wait(&mutex);
+ }
+ ~WatchDog() {
+ {
+ QMutexLocker locker(&mutex);
+ timeout.store(0);
+ waitCondition.wakeAll();
+ }
+ wait();
+ }
+
+ void beginTest() {
+ QMutexLocker locker(&mutex);
+ timeout.store(5*60*1000);
+ waitCondition.wakeAll();
+ }
+
+ void testFinished() {
+ QMutexLocker locker(&mutex);
+ timeout.store(-1);
+ waitCondition.wakeAll();
+ }
+
+ void run() {
+ QMutexLocker locker(&mutex);
+ waitCondition.wakeAll();
+ while (1) {
+ int t = timeout.load();
+ if (!t)
+ break;
+ if (!waitCondition.wait(&mutex, t)) {
+ stackTrace();
+ qFatal("Test function timed out");
+ }
+ }
+ }
+
+private:
+ QBasicAtomicInt timeout;
+ QMutex mutex;
+ QWaitCondition waitCondition;
+};
+
+
/*!
\internal
@@ -2020,7 +2155,7 @@ static void qInvokeTestMethodDataEntry(char *slot)
If the function was successfully called, true is returned, otherwise
false.
*/
-static bool qInvokeTestMethod(const char *slotName, const char *data=0)
+static bool qInvokeTestMethod(const char *slotName, const char *data, WatchDog *watchDog)
{
QTEST_ASSERT(slotName);
@@ -2079,7 +2214,11 @@ static bool qInvokeTestMethod(const char *slotName, const char *data=0)
QTestDataSetter s(curDataIndex >= dataCount ? static_cast<QTestData *>(0)
: table.testData(curDataIndex));
+ if (watchDog)
+ watchDog->beginTest();
qInvokeTestMethodDataEntry(slot);
+ if (watchDog)
+ watchDog->testFinished();
if (data)
break;
@@ -2351,6 +2490,37 @@ char *toPrettyUnicode(const ushort *p, int length)
return buffer.take();
}
+static bool debuggerPresent()
+{
+#if defined(Q_OS_LINUX)
+ int fd = open("/proc/self/status", O_RDONLY);
+ if (fd == -1)
+ return false;
+ char buffer[2048];
+ ssize_t size = read(fd, buffer, sizeof(buffer));
+ if (size == -1) {
+ close(fd);
+ return false;
+ }
+ buffer[size] = 0;
+ const char tracerPidToken[] = "TracerPid:";
+ char *tracerPid = strstr(buffer, tracerPidToken);
+ if (!tracerPid) {
+ close(fd);
+ return false;
+ }
+ tracerPid += sizeof(tracerPidToken);
+ long int pid = strtol(tracerPid, &tracerPid, 10);
+ close(fd);
+ return pid != 0;
+#elif defined(Q_OS_WIN)
+ return IsDebuggerPresent();
+#else
+ // TODO
+ return false;
+#endif
+}
+
static void qInvokeTestMethods(QObject *testObject)
{
const QMetaObject *metaObject = testObject->metaObject();
@@ -2360,6 +2530,10 @@ static void qInvokeTestMethods(QObject *testObject)
QTestTable::globalTestTable();
invokeMethod(testObject, "initTestCase_data()");
+ QScopedPointer<WatchDog> watchDog;
+ if (!debuggerPresent())
+ watchDog.reset(new WatchDog);
+
if (!QTestResult::skipCurrentTest() && !QTest::currentTestFailed()) {
invokeMethod(testObject, "initTestCase()");
@@ -2374,7 +2548,7 @@ static void qInvokeTestMethods(QObject *testObject)
if (QTest::testFuncs) {
for (int i = 0; i != QTest::testFuncCount; i++) {
if (!qInvokeTestMethod(metaObject->method(QTest::testFuncs[i].function()).methodSignature().constData(),
- QTest::testFuncs[i].data())) {
+ QTest::testFuncs[i].data(), watchDog.data())) {
break;
}
}
@@ -2387,7 +2561,7 @@ static void qInvokeTestMethods(QObject *testObject)
for (int i = 0; i != methodCount; i++) {
if (!isValidSlot(testMethods[i]))
continue;
- if (!qInvokeTestMethod(testMethods[i].methodSignature().constData()))
+ if (!qInvokeTestMethod(testMethods[i].methodSignature().constData(), 0, watchDog.data()))
break;
}
delete[] testMethods;
@@ -2423,6 +2597,8 @@ private:
void FatalSignalHandler::signal(int signum)
{
+ if (signum != SIGINT)
+ stackTrace();
qFatal("Received signal %d", signum);
#if defined(Q_OS_INTEGRITY)
{
@@ -2517,13 +2693,137 @@ FatalSignalHandler::~FatalSignalHandler()
} // namespace
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
+
+// Helper class for resolving symbol names by dynamically loading "dbghelp.dll".
+class DebugSymbolResolver
+{
+ Q_DISABLE_COPY(DebugSymbolResolver)
+public:
+ struct Symbol {
+ Symbol() : name(Q_NULLPTR), address(0) {}
+
+ const char *name; // Must be freed by caller.
+ DWORD64 address;
+ };
+
+ explicit DebugSymbolResolver(HANDLE process);
+ ~DebugSymbolResolver() { cleanup(); }
+
+ bool isValid() const { return m_symFromAddr; }
+
+ Symbol resolveSymbol(DWORD64 address) const;
+
+private:
+ // typedefs from DbgHelp.h/.dll
+ struct DBGHELP_SYMBOL_INFO { // SYMBOL_INFO
+ ULONG SizeOfStruct;
+ ULONG TypeIndex; // Type Index of symbol
+ ULONG64 Reserved[2];
+ ULONG Index;
+ ULONG Size;
+ ULONG64 ModBase; // Base Address of module comtaining this symbol
+ ULONG Flags;
+ ULONG64 Value; // Value of symbol, ValuePresent should be 1
+ ULONG64 Address; // Address of symbol including base address of module
+ ULONG Register; // register holding value or pointer to value
+ ULONG Scope; // scope of the symbol
+ ULONG Tag; // pdb classification
+ ULONG NameLen; // Actual length of name
+ ULONG MaxNameLen;
+ CHAR Name[1]; // Name of symbol
+ };
+
+ typedef BOOL (__stdcall *SymInitializeType)(HANDLE, PCSTR, BOOL);
+ typedef BOOL (__stdcall *SymFromAddrType)(HANDLE, DWORD64, PDWORD64, DBGHELP_SYMBOL_INFO *);
+
+ void cleanup();
+
+ const HANDLE m_process;
+ HMODULE m_dbgHelpLib;
+ SymFromAddrType m_symFromAddr;
+};
+
+void DebugSymbolResolver::cleanup()
+{
+ if (m_dbgHelpLib)
+ FreeLibrary(m_dbgHelpLib);
+ m_dbgHelpLib = 0;
+ m_symFromAddr = Q_NULLPTR;
+}
+
+DebugSymbolResolver::DebugSymbolResolver(HANDLE process)
+ : m_process(process), m_dbgHelpLib(0), m_symFromAddr(Q_NULLPTR)
+{
+ bool success = false;
+ m_dbgHelpLib = LoadLibraryW(L"dbghelp.dll");
+ if (m_dbgHelpLib) {
+ SymInitializeType symInitialize = (SymInitializeType)(GetProcAddress(m_dbgHelpLib, "SymInitialize"));
+ m_symFromAddr = (SymFromAddrType)(GetProcAddress(m_dbgHelpLib, "SymFromAddr"));
+ success = symInitialize && m_symFromAddr && symInitialize(process, NULL, TRUE);
+ }
+ if (!success)
+ cleanup();
+}
+
+DebugSymbolResolver::Symbol DebugSymbolResolver::resolveSymbol(DWORD64 address) const
+{
+ // reserve additional buffer where SymFromAddr() will store the name
+ struct NamedSymbolInfo : public DBGHELP_SYMBOL_INFO {
+ enum { symbolNameLength = 255 };
+
+ char name[symbolNameLength + 1];
+ };
+
+ Symbol result;
+ if (!isValid())
+ return result;
+ NamedSymbolInfo symbolBuffer;
+ memset(&symbolBuffer, 0, sizeof(NamedSymbolInfo));
+ symbolBuffer.MaxNameLen = NamedSymbolInfo::symbolNameLength;
+ symbolBuffer.SizeOfStruct = sizeof(DBGHELP_SYMBOL_INFO);
+ if (!m_symFromAddr(m_process, address, 0, &symbolBuffer))
+ return result;
+ result.name = qstrdup(symbolBuffer.Name);
+ result.address = symbolBuffer.Address;
+ return result;
+}
+
static LONG WINAPI windowsFaultHandler(struct _EXCEPTION_POINTERS *exInfo)
{
+ enum { maxStackFrames = 100 };
char appName[MAX_PATH];
if (!GetModuleFileNameA(NULL, appName, MAX_PATH))
appName[0] = 0;
- fprintf(stderr, "A crash occurred in %s (exception code 0x%lx).",
- appName, exInfo->ExceptionRecord->ExceptionCode);
+
+ const void *exceptionAddress = exInfo->ExceptionRecord->ExceptionAddress;
+ fprintf(stderr, "A crash occurred in %s.\n\n"
+ "Exception address: 0x%p\n"
+ "Exception code : 0x%lx\n",
+ appName, exceptionAddress, exInfo->ExceptionRecord->ExceptionCode);
+
+ DebugSymbolResolver resolver(GetCurrentProcess());
+ if (resolver.isValid()) {
+ DebugSymbolResolver::Symbol exceptionSymbol = resolver.resolveSymbol(DWORD64(exceptionAddress));
+ if (exceptionSymbol.name) {
+ fprintf(stderr, "Nearby symbol : %s\n", exceptionSymbol.name);
+ delete [] exceptionSymbol.name;
+ }
+ void *stack[maxStackFrames];
+ fputs("\nStack:\n", stderr);
+ const unsigned frameCount = CaptureStackBackTrace(0, DWORD(maxStackFrames), stack, NULL);
+ for (unsigned f = 0; f < frameCount; ++f) {
+ DebugSymbolResolver::Symbol symbol = resolver.resolveSymbol(DWORD64(stack[f]));
+ if (symbol.name) {
+ fprintf(stderr, "#%3u: %s() - 0x%p\n", f + 1, symbol.name, (const void *)symbol.address);
+ delete [] symbol.name;
+ } else {
+ fprintf(stderr, "#%3u: Unable to obtain symbol\n", f + 1);
+ }
+ }
+ }
+
+ fputc('\n', stderr);
+
return EXCEPTION_EXECUTE_HANDLER;
}
#endif // Q_OS_WIN) && !Q_OS_WINCE && !Q_OS_WINRT
@@ -3237,6 +3537,8 @@ TO_STRING_IMPL(quint64, %llu)
#endif
TO_STRING_IMPL(bool, %d)
TO_STRING_IMPL(char, %c)
+TO_STRING_IMPL(signed char, %hhd)
+TO_STRING_IMPL(unsigned char, %hhu)
TO_STRING_IMPL(float, %g)
TO_STRING_IMPL(double, %lg)
diff --git a/src/testlib/qtestcase.h b/src/testlib/qtestcase.h
index f24283b65e..7d2fd2e701 100644
--- a/src/testlib/qtestcase.h
+++ b/src/testlib/qtestcase.h
@@ -39,6 +39,7 @@
#include <QtCore/qstring.h>
#include <QtCore/qnamespace.h>
#include <QtCore/qmetatype.h>
+#include <QtCore/qmetaobject.h>
#include <QtCore/qtypetraits.h>
#include <QtCore/qsharedpointer.h>
#include <QtCore/qtemporarydir.h>
@@ -157,6 +158,15 @@ do { \
#define QTRY_VERIFY(__expr) QTRY_VERIFY_WITH_TIMEOUT((__expr), 5000)
+// Will try to wait for the expression to become true while allowing event processing
+#define QTRY_VERIFY2_WITH_TIMEOUT(__expr, __messageExpression, __timeout) \
+do { \
+ QTRY_IMPL((__expr), __timeout);\
+ QVERIFY2(__expr, __messageExpression); \
+} while (0)
+
+#define QTRY_VERIFY2(__expr, __messageExpression) QTRY_VERIFY2_WITH_TIMEOUT((__expr), (__messageExpression), 5000)
+
// Will try to wait for the comparison to become successful while allowing event processing
#define QTRY_COMPARE_WITH_TIMEOUT(__expr, __expected, __timeout) \
do { \
@@ -222,12 +232,28 @@ class QTestData;
namespace QTest
{
- template <typename T>
- inline char *toString(const T &)
+ namespace Internal {
+
+ template<typename T> // Output registered enums
+ inline typename QtPrivate::QEnableIf<QtPrivate::IsQEnumHelper<T>::Value, char*>::Type toString(T e)
+ {
+ QMetaEnum me = QMetaEnum::fromType<T>();
+ return qstrdup(me.key(e));
+ }
+
+ template <typename T> // Fallback
+ inline typename QtPrivate::QEnableIf<!QtPrivate::IsQEnumHelper<T>::Value, char*>::Type toString(const T &)
{
- return 0;
+ return Q_NULLPTR;
}
+ } // namespace Internal
+
+ template<typename T>
+ inline char *toString(const T &t)
+ {
+ return Internal::toString(t);
+ }
Q_TESTLIB_EXPORT char *toHexRepresentation(const char *ba, int length);
Q_TESTLIB_EXPORT char *toPrettyCString(const char *unicode, int length);
@@ -235,10 +261,10 @@ namespace QTest
Q_TESTLIB_EXPORT char *toString(const char *);
Q_TESTLIB_EXPORT char *toString(const void *);
- Q_TESTLIB_EXPORT int qExec(QObject *testObject, int argc = 0, char **argv = 0);
+ Q_TESTLIB_EXPORT int qExec(QObject *testObject, int argc = 0, char **argv = Q_NULLPTR);
Q_TESTLIB_EXPORT int qExec(QObject *testObject, const QStringList &arguments);
- Q_TESTLIB_EXPORT void setMainSourcePath(const char *file, const char *builddir = 0);
+ Q_TESTLIB_EXPORT void setMainSourcePath(const char *file, const char *builddir = Q_NULLPTR);
Q_TESTLIB_EXPORT bool qVerify(bool statement, const char *statementStr, const char *description,
const char *file, int line);
@@ -246,15 +272,15 @@ namespace QTest
Q_TESTLIB_EXPORT void qSkip(const char *message, const char *file, int line);
Q_TESTLIB_EXPORT bool qExpectFail(const char *dataIndex, const char *comment, TestFailMode mode,
const char *file, int line);
- Q_TESTLIB_EXPORT void qWarn(const char *message, const char *file = 0, int line = 0);
+ Q_TESTLIB_EXPORT void qWarn(const char *message, const char *file = Q_NULLPTR, int line = 0);
Q_TESTLIB_EXPORT void ignoreMessage(QtMsgType type, const char *message);
#ifndef QT_NO_REGULAREXPRESSION
Q_TESTLIB_EXPORT void ignoreMessage(QtMsgType type, const QRegularExpression &messagePattern);
#endif
Q_TESTLIB_EXPORT QSharedPointer<QTemporaryDir> qExtractTestData(const QString &dirName);
- Q_TESTLIB_EXPORT QString qFindTestData(const char* basepath, const char* file = 0, int line = 0, const char* builddir = 0);
- Q_TESTLIB_EXPORT QString qFindTestData(const QString& basepath, const char* file = 0, int line = 0, const char* builddir = 0);
+ Q_TESTLIB_EXPORT QString qFindTestData(const char* basepath, const char* file = Q_NULLPTR, int line = 0, const char* builddir = Q_NULLPTR);
+ Q_TESTLIB_EXPORT QString qFindTestData(const QString& basepath, const char* file = Q_NULLPTR, int line = 0, const char* builddir = Q_NULLPTR);
Q_TESTLIB_EXPORT void *qData(const char *tagName, int typeId);
Q_TESTLIB_EXPORT void *qGlobalData(const char *tagName, int typeId);
@@ -323,6 +349,8 @@ namespace QTest
QTEST_COMPARE_DECL(float)
QTEST_COMPARE_DECL(double)
QTEST_COMPARE_DECL(char)
+ QTEST_COMPARE_DECL(signed char)
+ QTEST_COMPARE_DECL(unsigned char)
QTEST_COMPARE_DECL(bool)
#endif
@@ -392,14 +420,6 @@ namespace QTest
return compare_string_helper(t1, t2, actual, expected, file, line);
}
- // NokiaX86 and RVCT do not like implicitly comparing bool with int
- inline bool qCompare(bool const &t1, int const &t2,
- const char *actual, const char *expected, const char *file, int line)
- {
- return qCompare(int(t1), t2, actual, expected, file, line);
- }
-
-
template <class T>
inline bool qTest(const T& actual, const char *elementName, const char *actualStr,
const char *expected, const char *file, int line)
diff --git a/src/testlib/qtestevent.h b/src/testlib/qtestevent.h
index a3e5f02ec1..9794b15f4a 100644
--- a/src/testlib/qtestevent.h
+++ b/src/testlib/qtestevent.h
@@ -185,20 +185,20 @@ public:
inline void addKeyEvent(QTest::KeyAction action, char ascii, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ append(new QTestKeyEvent(action, ascii, modifiers, msecs)); }
- inline void addMousePress(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void addMousePress(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MousePress, button, stateKey, pos, delay)); }
- inline void addMouseRelease(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void addMouseRelease(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseRelease, button, stateKey, pos, delay)); }
- inline void addMouseClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void addMouseClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseClick, button, stateKey, pos, delay)); }
- inline void addMouseDClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void addMouseDClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseDClick, button, stateKey, pos, delay)); }
inline void addMouseMove(QPoint pos = QPoint(), int delay=-1)
- { append(new QTestMouseEvent(QTest::MouseMove, Qt::NoButton, 0, pos, delay)); }
+ { append(new QTestMouseEvent(QTest::MouseMove, Qt::NoButton, Qt::KeyboardModifiers(), pos, delay)); }
#endif //QT_GUI_LIB
inline void addDelay(int msecs)
diff --git a/src/testlib/qtesteventloop.h b/src/testlib/qtesteventloop.h
index a9f611f306..a8ce619d4e 100644
--- a/src/testlib/qtesteventloop.h
+++ b/src/testlib/qtesteventloop.h
@@ -50,8 +50,8 @@ class Q_TESTLIB_EXPORT QTestEventLoop : public QObject
Q_OBJECT
public:
- inline QTestEventLoop(QObject *aParent = 0)
- : QObject(aParent), inLoop(false), _timeout(false), timerId(-1), loop(0) {}
+ inline QTestEventLoop(QObject *aParent = Q_NULLPTR)
+ : QObject(aParent), inLoop(false), _timeout(false), timerId(-1), loop(Q_NULLPTR) {}
inline void enterLoopMSecs(int ms);
inline void enterLoop(int secs) { enterLoopMSecs(secs * 1000); }
@@ -97,7 +97,7 @@ inline void QTestEventLoop::enterLoopMSecs(int ms)
loop = &l;
l.exec();
- loop = 0;
+ loop = Q_NULLPTR;
}
inline void QTestEventLoop::exitLoop()
diff --git a/src/testlib/qtestkeyboard.h b/src/testlib/qtestkeyboard.h
index 39520d621f..82dd6fa098 100644
--- a/src/testlib/qtestkeyboard.h
+++ b/src/testlib/qtestkeyboard.h
@@ -97,7 +97,7 @@ namespace QTest
if (action == Press) {
if (modifier & Qt::ShiftModifier)
- simulateEvent(window, true, Qt::Key_Shift, 0, QString(), false, delay);
+ simulateEvent(window, true, Qt::Key_Shift, Qt::KeyboardModifiers(), QString(), false, delay);
if (modifier & Qt::ControlModifier)
simulateEvent(window, true, Qt::Key_Control, modifier & Qt::ShiftModifier, QString(), false, delay);
@@ -220,7 +220,7 @@ namespace QTest
if (action == Press) {
if (modifier & Qt::ShiftModifier)
- simulateEvent(widget, true, Qt::Key_Shift, 0, QString(), false, delay);
+ simulateEvent(widget, true, Qt::Key_Shift, Qt::KeyboardModifiers(), QString(), false, delay);
if (modifier & Qt::ControlModifier)
simulateEvent(widget, true, Qt::Key_Control, modifier & Qt::ShiftModifier, QString(), false, delay);
diff --git a/src/plugins/platforms/xcb/qxlibconvenience.h b/src/testlib/qtestmouse.cpp
index 0e6e1c37ec..99a75744fa 100644
--- a/src/plugins/platforms/xcb/qxlibconvenience.h
+++ b/src/testlib/qtestmouse.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtTest module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@@ -31,19 +31,17 @@
**
****************************************************************************/
-#ifndef XLIBUTILS_H
-#define XLIBUTILS_H
+#include <QtCore/QtGlobal>
+#include <QtCore/qnamespace.h>
+#include <QtTest/qtest_global.h>
-#ifdef XCB_USE_XLIB
+QT_BEGIN_NAMESPACE
-#include <xcb/xcb_keysyms.h>
-#include <QByteArray>
+namespace QTest {
-QT_BEGIN_NAMESPACE
+Q_TESTLIB_EXPORT Qt::MouseButton lastMouseButton = Qt::NoButton;
+Q_TESTLIB_EXPORT int lastMouseTimestamp = 0;
-xcb_keysym_t q_XLookupString(void *display, xcb_window_t window, xcb_window_t root, uint state, xcb_keycode_t code, int type, QByteArray *chars);
+} // namespace QTest
QT_END_NAMESPACE
-
-#endif // XCB_USE_XLIB
-#endif
diff --git a/src/testlib/qtestmouse.h b/src/testlib/qtestmouse.h
index ad6671af02..c422a990ef 100644
--- a/src/testlib/qtestmouse.h
+++ b/src/testlib/qtestmouse.h
@@ -45,6 +45,7 @@
#include <QtTest/qtestspontaneevent.h>
#include <QtCore/qpoint.h>
#include <QtCore/qstring.h>
+#include <QtCore/qpointer.h>
#include <QtGui/qevent.h>
#include <QtGui/qwindow.h>
@@ -57,12 +58,15 @@
QT_BEGIN_NAMESPACE
-Q_GUI_EXPORT void qt_handleMouseEvent(QWindow *w, const QPointF & local, const QPointF & global, Qt::MouseButtons b, Qt::KeyboardModifiers mods = Qt::NoModifier);
+Q_GUI_EXPORT void qt_handleMouseEvent(QWindow *w, const QPointF &local, const QPointF &global, Qt::MouseButtons b, Qt::KeyboardModifiers mods, int timestamp);
namespace QTest
{
enum MouseAction { MousePress, MouseRelease, MouseClick, MouseDClick, MouseMove };
+ extern Q_TESTLIB_EXPORT Qt::MouseButton lastMouseButton;
+ extern Q_TESTLIB_EXPORT int lastMouseTimestamp;
+
static void waitForEvents()
{
#ifdef Q_OS_MAC
@@ -83,76 +87,85 @@ namespace QTest
QTest::qWarn("Mouse event occurs outside of target window.");
}
- static Qt::MouseButton lastButton = Qt::NoButton;
-
if (delay == -1 || delay < defaultMouseDelay())
delay = defaultMouseDelay();
- if (delay > 0)
+ if (delay > 0) {
QTest::qWait(delay);
+ lastMouseTimestamp += delay;
+ }
if (pos.isNull())
pos = window->geometry().center();
- if (action == MouseClick) {
- mouseEvent(MousePress, window, button, stateKey, pos);
- mouseEvent(MouseRelease, window, button, stateKey, pos);
- return;
- }
QTEST_ASSERT(uint(stateKey) == 0 || stateKey & Qt::KeyboardModifierMask);
stateKey &= static_cast<unsigned int>(Qt::KeyboardModifierMask);
+ QPointF global = window->mapToGlobal(pos);
+ QPointer<QWindow> w(window);
switch (action)
{
- case MousePress:
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),button,stateKey);
- lastButton = button;
- break;
- case MouseRelease:
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),Qt::NoButton,stateKey);
- lastButton = Qt::NoButton;
- break;
- case MouseDClick:
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),button,stateKey);
- qWait(10);
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),Qt::NoButton,stateKey);
- qWait(20);
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),button,stateKey);
- qWait(10);
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),Qt::NoButton,stateKey);
- break;
- case MouseMove:
- qt_handleMouseEvent(window,pos,window->mapToGlobal(pos),lastButton,stateKey);
- // No QCursor::setPos() call here. That could potentially result in mouse events sent by the windowing system
- // which is highly undesired here. Tests must avoid relying on QCursor.
+ case MouseDClick:
+ qt_handleMouseEvent(w, pos, global, button, stateKey, ++lastMouseTimestamp);
+ qt_handleMouseEvent(w, pos, global, Qt::NoButton, stateKey, ++lastMouseTimestamp);
+ // fall through
+ case MousePress:
+ case MouseClick:
+ qt_handleMouseEvent(w, pos, global, button, stateKey, ++lastMouseTimestamp);
+ lastMouseButton = button;
+ if (action == MousePress)
break;
- default:
- QTEST_ASSERT(false);
+ // fall through
+ case MouseRelease:
+ qt_handleMouseEvent(w, pos, global, Qt::NoButton, stateKey, ++lastMouseTimestamp);
+ lastMouseTimestamp += 500; // avoid double clicks being generated
+ lastMouseButton = Qt::NoButton;
+ break;
+ case MouseMove:
+ qt_handleMouseEvent(w, pos, global, lastMouseButton, stateKey, ++lastMouseTimestamp);
+ // No QCursor::setPos() call here. That could potentially result in mouse events sent by the windowing system
+ // which is highly undesired here. Tests must avoid relying on QCursor.
+ break;
+ default:
+ QTEST_ASSERT(false);
}
waitForEvents();
}
- inline void mousePress(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mousePress(QWindow *window, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MousePress, window, button, stateKey, pos, delay); }
- inline void mouseRelease(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseRelease(QWindow *window, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseRelease, window, button, stateKey, pos, delay); }
- inline void mouseClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseClick(QWindow *window, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseClick, window, button, stateKey, pos, delay); }
- inline void mouseDClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseDClick(QWindow *window, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseDClick, window, button, stateKey, pos, delay); }
inline void mouseMove(QWindow *window, QPoint pos = QPoint(), int delay=-1)
- { mouseEvent(MouseMove, window, Qt::NoButton, 0, pos, delay); }
+ { mouseEvent(MouseMove, window, Qt::NoButton, Qt::KeyboardModifiers(), pos, delay); }
#ifdef QT_WIDGETS_LIB
static void mouseEvent(MouseAction action, QWidget *widget, Qt::MouseButton button,
Qt::KeyboardModifiers stateKey, QPoint pos, int delay=-1)
{
QTEST_ASSERT(widget);
+
+ if (pos.isNull())
+ pos = widget->rect().center();
+
+#ifdef QTEST_QPA_MOUSE_HANDLING
+ QWindow *w = widget->window()->windowHandle();
+ QTEST_ASSERT(w);
+ mouseEvent(action, w, button, stateKey, w->mapFromGlobal(widget->mapToGlobal(pos)), delay);
+#else
extern int Q_TESTLIB_EXPORT defaultMouseDelay();
if (delay == -1 || delay < defaultMouseDelay())
@@ -160,9 +173,6 @@ namespace QTest
if (delay > 0)
QTest::qWait(delay);
- if (pos.isNull())
- pos = widget->rect().center();
-
if (action == MouseClick) {
mouseEvent(MousePress, widget, button, stateKey, pos);
mouseEvent(MouseRelease, widget, button, stateKey, pos);
@@ -180,7 +190,7 @@ namespace QTest
me = QMouseEvent(QEvent::MouseButtonPress, pos, widget->mapToGlobal(pos), button, button, stateKey);
break;
case MouseRelease:
- me = QMouseEvent(QEvent::MouseButtonRelease, pos, widget->mapToGlobal(pos), button, 0, stateKey);
+ me = QMouseEvent(QEvent::MouseButtonRelease, pos, widget->mapToGlobal(pos), button, Qt::MouseButton(), stateKey);
break;
case MouseDClick:
me = QMouseEvent(QEvent::MouseButtonDblClick, pos, widget->mapToGlobal(pos), button, button, stateKey);
@@ -203,23 +213,27 @@ namespace QTest
QString warning = QString::fromLatin1("Mouse event \"%1\" not accepted by receiving widget");
QTest::qWarn(warning.arg(QString::fromLatin1(mouseActionNames[static_cast<int>(action)])).toLatin1().data());
}
-
+#endif
}
- inline void mousePress(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mousePress(QWidget *widget, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MousePress, widget, button, stateKey, pos, delay); }
- inline void mouseRelease(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseRelease(QWidget *widget, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseRelease, widget, button, stateKey, pos, delay); }
- inline void mouseClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseClick(QWidget *widget, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseClick, widget, button, stateKey, pos, delay); }
- inline void mouseDClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
+ inline void mouseDClick(QWidget *widget, Qt::MouseButton button,
+ Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(),
QPoint pos = QPoint(), int delay=-1)
{ mouseEvent(MouseDClick, widget, button, stateKey, pos, delay); }
inline void mouseMove(QWidget *widget, QPoint pos = QPoint(), int delay=-1)
- { mouseEvent(MouseMove, widget, Qt::NoButton, 0, pos, delay); }
+ { mouseEvent(MouseMove, widget, Qt::NoButton, Qt::KeyboardModifiers(), pos, delay); }
#endif // QT_WIDGETS_LIB
}
diff --git a/src/testlib/qtestsystem.h b/src/testlib/qtestsystem.h
index 50acc6136d..f81ede519c 100644
--- a/src/testlib/qtestsystem.h
+++ b/src/testlib/qtestsystem.h
@@ -56,7 +56,7 @@ namespace QTest
timer.start();
do {
QCoreApplication::processEvents(QEventLoop::AllEvents, ms);
- QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
+ QCoreApplication::sendPostedEvents(Q_NULLPTR, QEvent::DeferredDelete);
QTest::qSleep(10);
} while (timer.elapsed() < ms);
}
@@ -71,7 +71,7 @@ namespace QTest
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
- QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
+ QCoreApplication::sendPostedEvents(Q_NULLPTR, QEvent::DeferredDelete);
QTest::qSleep(10);
}
// Try ensuring the platform window receives the real position.
@@ -100,7 +100,7 @@ namespace QTest
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
- QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
+ QCoreApplication::sendPostedEvents(Q_NULLPTR, QEvent::DeferredDelete);
QTest::qSleep(10);
}
return window->isExposed();
diff --git a/src/testlib/qtesttouch.h b/src/testlib/qtesttouch.h
index 5dcdca808b..8e782d17d7 100644
--- a/src/testlib/qtesttouch.h
+++ b/src/testlib/qtesttouch.h
@@ -68,21 +68,21 @@ namespace QTest
if (commitWhenDestroyed)
commit();
}
- QTouchEventSequence& press(int touchId, const QPoint &pt, QWindow *window = 0)
+ QTouchEventSequence& press(int touchId, const QPoint &pt, QWindow *window = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(window, pt));
p.setState(Qt::TouchPointPressed);
return *this;
}
- QTouchEventSequence& move(int touchId, const QPoint &pt, QWindow *window = 0)
+ QTouchEventSequence& move(int touchId, const QPoint &pt, QWindow *window = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(window, pt));
p.setState(Qt::TouchPointMoved);
return *this;
}
- QTouchEventSequence& release(int touchId, const QPoint &pt, QWindow *window = 0)
+ QTouchEventSequence& release(int touchId, const QPoint &pt, QWindow *window = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(window, pt));
@@ -97,21 +97,21 @@ namespace QTest
}
#ifdef QT_WIDGETS_LIB
- QTouchEventSequence& press(int touchId, const QPoint &pt, QWidget *widget = 0)
+ QTouchEventSequence& press(int touchId, const QPoint &pt, QWidget *widget = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(widget, pt));
p.setState(Qt::TouchPointPressed);
return *this;
}
- QTouchEventSequence& move(int touchId, const QPoint &pt, QWidget *widget = 0)
+ QTouchEventSequence& move(int touchId, const QPoint &pt, QWidget *widget = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(widget, pt));
p.setState(Qt::TouchPointMoved);
return *this;
}
- QTouchEventSequence& release(int touchId, const QPoint &pt, QWidget *widget = 0)
+ QTouchEventSequence& release(int touchId, const QPoint &pt, QWidget *widget = Q_NULLPTR)
{
QTouchEvent::TouchPoint &p = point(touchId);
p.setScreenPos(mapToScreen(widget, pt));
@@ -143,14 +143,14 @@ namespace QTest
private:
#ifdef QT_WIDGETS_LIB
QTouchEventSequence(QWidget *widget, QTouchDevice *aDevice, bool autoCommit)
- : targetWidget(widget), targetWindow(0), device(aDevice), commitWhenDestroyed(autoCommit)
+ : targetWidget(widget), targetWindow(Q_NULLPTR), device(aDevice), commitWhenDestroyed(autoCommit)
{
}
#endif
QTouchEventSequence(QWindow *window, QTouchDevice *aDevice, bool autoCommit)
:
#ifdef QT_WIDGETS_LIB
- targetWidget(0),
+ targetWidget(Q_NULLPTR),
#endif
targetWindow(window), device(aDevice), commitWhenDestroyed(autoCommit)
{
diff --git a/src/testlib/testlib.pro b/src/testlib/testlib.pro
index 79fd342cca..0070cdb271 100644
--- a/src/testlib/testlib.pro
+++ b/src/testlib/testlib.pro
@@ -56,6 +56,7 @@ SOURCES = qtestcase.cpp \
qcsvbenchmarklogger.cpp \
qtestelement.cpp \
qtestelementattribute.cpp \
+ qtestmouse.cpp \
qtestxunitstreamer.cpp \
qxunittestlogger.cpp \
qtestblacklist.cpp
diff --git a/src/tools/bootstrap/bootstrap.pro b/src/tools/bootstrap/bootstrap.pro
index a92e5b8f3d..d5909e68a3 100644
--- a/src/tools/bootstrap/bootstrap.pro
+++ b/src/tools/bootstrap/bootstrap.pro
@@ -4,9 +4,6 @@ TARGET = QtBootstrap
QT =
CONFIG += internal_module force_bootstrap
-# otherwise mingw headers do not declare common functions like putenv
-mingw:QMAKE_CXXFLAGS_CXX11 = -std=gnu++0x
-
MODULE_DEFINES = \
QT_BOOTSTRAPPED \
QT_LITE_UNICODE \
@@ -49,6 +46,9 @@ QMAKE_SYNCQT_OPTIONS += -version $$QT_VERSION
load(qt_module)
+# otherwise mingw headers do not declare common functions like putenv
+mingw: CONFIG -= strict_c++
+
SOURCES += \
../../corelib/codecs/qlatincodec.cpp \
../../corelib/codecs/qtextcodec.cpp \
@@ -97,6 +97,7 @@ SOURCES += \
../../corelib/tools/qlocale_tools.cpp \
../../corelib/tools/qmap.cpp \
../../corelib/tools/qregexp.cpp \
+ ../../corelib/tools/qringbuffer.cpp \
../../corelib/tools/qpoint.cpp \
../../corelib/tools/qrect.cpp \
../../corelib/tools/qsize.cpp \
diff --git a/src/tools/moc/preprocessor.cpp b/src/tools/moc/preprocessor.cpp
index f253c49995..d036c40f35 100644
--- a/src/tools/moc/preprocessor.cpp
+++ b/src/tools/moc/preprocessor.cpp
@@ -529,7 +529,7 @@ Symbols Preprocessor::tokenize(const QByteArray& input, int lineNum, Preprocesso
return symbols;
}
-Symbols Preprocessor::macroExpand(Preprocessor *that, Symbols &toExpand, int &index,
+void Preprocessor::macroExpand(Symbols *into, Preprocessor *that, const Symbols &toExpand, int &index,
int lineNum, bool one, const QSet<QByteArray> &excludeSymbols)
{
SymbolStack symbols;
@@ -539,16 +539,18 @@ Symbols Preprocessor::macroExpand(Preprocessor *that, Symbols &toExpand, int &in
sf.excludedSymbols = excludeSymbols;
symbols.push(sf);
- Symbols result;
if (toExpand.isEmpty())
- return result;
+ return;
for (;;) {
QByteArray macro;
Symbols newSyms = macroExpandIdentifier(that, symbols, lineNum, &macro);
if (macro.isEmpty()) {
- result += newSyms;
+ // not a macro
+ Symbol s = symbols.symbol();
+ s.lineNum = lineNum;
+ *into += s;
} else {
SafeSymbols sf;
sf.symbols = newSyms;
@@ -565,8 +567,6 @@ Symbols Preprocessor::macroExpand(Preprocessor *that, Symbols &toExpand, int &in
index = symbols.top().index;
else
index = toExpand.size();
-
- return result;
}
@@ -576,10 +576,7 @@ Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &sym
// not a macro
if (s.token != PP_IDENTIFIER || !that->macros.contains(s) || symbols.dontReplaceSymbol(s.lexem())) {
- Symbols syms;
- syms += s;
- syms.last().lineNum = lineNum;
- return syms;
+ return Symbols();
}
const Macro &macro = that->macros.value(s);
@@ -600,7 +597,7 @@ Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &sym
syms.last().lineNum = lineNum;
return syms;
}
- QList<Symbols> arguments;
+ QVarLengthArray<Symbols, 5> arguments;
while (symbols.hasNext()) {
Symbols argument;
// strip leading space
@@ -653,7 +650,7 @@ Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &sym
if (i == macro.symbols.size() - 1 || macro.symbols.at(i + 1).token != PP_HASHHASH) {
Symbols arg = arguments.at(index);
int idx = 1;
- expansion += macroExpand(that, arg, idx, lineNum, false, symbols.excludeSymbols());
+ macroExpand(&expansion, that, arg, idx, lineNum, false, symbols.excludeSymbols());
} else {
expansion += arguments.at(index);
}
@@ -726,7 +723,7 @@ void Preprocessor::substituteUntilNewline(Symbols &substituted)
while (hasNext()) {
Token token = next();
if (token == PP_IDENTIFIER) {
- substituted += macroExpand(this, symbols, index, symbol().lineNum, true);
+ macroExpand(&substituted, this, symbols, index, symbol().lineNum, true);
} else if (token == PP_DEFINED) {
bool braces = test(PP_LPAREN);
next(PP_IDENTIFIER);
@@ -1148,7 +1145,7 @@ void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
}
case PP_IDENTIFIER: {
// substitute macros
- preprocessed += macroExpand(this, symbols, index, symbol().lineNum, true);
+ macroExpand(&preprocessed, this, symbols, index, symbol().lineNum, true);
continue;
}
case PP_HASH:
diff --git a/src/tools/moc/preprocessor.h b/src/tools/moc/preprocessor.h
index 28691d316b..9c81f86f9c 100644
--- a/src/tools/moc/preprocessor.h
+++ b/src/tools/moc/preprocessor.h
@@ -76,7 +76,7 @@ public:
void substituteUntilNewline(Symbols &substituted);
static Symbols macroExpandIdentifier(Preprocessor *that, SymbolStack &symbols, int lineNum, QByteArray *macroName);
- static Symbols macroExpand(Preprocessor *that, Symbols &toExpand, int &index, int lineNum, bool one,
+ static void macroExpand(Symbols *into, Preprocessor *that, const Symbols &toExpand, int &index, int lineNum, bool one,
const QSet<QByteArray> &excludeSymbols = QSet<QByteArray>());
int evaluateCondition();
diff --git a/src/tools/moc/symbols.h b/src/tools/moc/symbols.h
index 13f9ada606..5f442e75ed 100644
--- a/src/tools/moc/symbols.h
+++ b/src/tools/moc/symbols.h
@@ -113,8 +113,11 @@ struct Symbol
Token token;
inline QByteArray lexem() const { return lex.mid(from, len); }
inline QByteArray unquotedLexem() const { return lex.mid(from+1, len-2); }
- inline operator QByteArray() const { return lex.mid(from, len); }
inline operator SubArray() const { return SubArray(lex, from, len); }
+ bool operator==(const Symbol& o) const
+ {
+ return SubArray(lex, from, len) == SubArray(o.lex, o.from, o.len);
+ }
QByteArray lex;
int from, len;
@@ -130,6 +133,7 @@ struct SafeSymbols {
QSet<QByteArray> excludedSymbols;
int index;
};
+Q_DECLARE_TYPEINFO(SafeSymbols, Q_MOVABLE_TYPE);
class SymbolStack : public QStack<SafeSymbols>
{
diff --git a/src/tools/qdoc/atom.cpp b/src/tools/qdoc/atom.cpp
index 745da21b30..f50f401c5b 100644
--- a/src/tools/qdoc/atom.cpp
+++ b/src/tools/qdoc/atom.cpp
@@ -64,10 +64,8 @@ QT_BEGIN_NAMESPACE
\also Text
*/
-/*! \enum Atom::Type
+/*! \enum Atom::AtomType
- \value AbstractLeft
- \value AbstractRight
\value AnnotatedList
\value AutoLink
\value BaseName
@@ -149,8 +147,6 @@ static const struct {
const char *english;
int no;
} atms[] = {
- { "AbstractLeft", Atom::AbstractLeft },
- { "AbstractRight", Atom::AbstractRight },
{ "AnnotatedList", Atom::AnnotatedList },
{ "AutoLink", Atom::AutoLink },
{ "BaseName", Atom::BaseName },
@@ -237,27 +233,27 @@ static const struct {
{ 0, 0 }
};
-/*! \fn Atom::Atom(Type type, const QString& string)
+/*! \fn Atom::Atom(AtomType type, const QString& string)
Constructs an atom of the specified \a type with the single
parameter \a string and does not put the new atom in a list.
*/
-/*! \fn Atom::Atom(Type type, const QString& p1, const QString& p2)
+/*! \fn Atom::Atom(AtomType type, const QString& p1, const QString& p2)
Constructs an atom of the specified \a type with the two
parameters \a p1 and \a p2 and does not put the new atom
in a list.
*/
-/*! \fn Atom(Atom *previous, Type type, const QString& string)
+/*! \fn Atom(Atom *previous, AtomType type, const QString& string)
Constructs an atom of the specified \a type with the single
parameter \a string and inserts the new atom into the list
after the \a previous atom.
*/
-/*! \fn Atom::Atom(Atom* previous, Type type, const QString& p1, const QString& p2)
+/*! \fn Atom::Atom(Atom* previous, AtomType type, const QString& p1, const QString& p2)
Constructs an atom of the specified \a type with the two
parameters \a p1 and \a p2 and inserts the new atom into
@@ -289,19 +285,19 @@ static const struct {
*/
/*!
- Return the next Atom in the list if it is of Type \a t.
+ Return the next Atom in the list if it is of AtomType \a t.
Otherwise return 0.
*/
-const Atom* Atom::next(Type t) const
+const Atom* Atom::next(AtomType t) const
{
return (next_ && (next_->type() == t)) ? next_ : 0;
}
/*!
- Return the next Atom in the list if it is of Type \a t
+ Return the next Atom in the list if it is of AtomType \a t
and its string part is \a s. Otherwise return 0.
*/
-const Atom* Atom::next(Type t, const QString& s) const
+const Atom* Atom::next(AtomType t, const QString& s) const
{
return (next_ && (next_->type() == t) && (next_->string() == s)) ? next_ : 0;
}
@@ -311,7 +307,7 @@ const Atom* Atom::next(Type t, const QString& s) const
\also type(), string()
*/
-/*! \fn Type Atom::type() const
+/*! \fn AtomType Atom::type() const
Return the type of this atom.
\also string(), next()
*/
diff --git a/src/tools/qdoc/atom.h b/src/tools/qdoc/atom.h
index ebbba8917e..86b8ba7b3c 100644
--- a/src/tools/qdoc/atom.h
+++ b/src/tools/qdoc/atom.h
@@ -46,9 +46,7 @@ class LinkAtom;
class Atom
{
public:
- enum Type {
- AbstractLeft,
- AbstractRight,
+ enum AtomType {
AnnotatedList,
AutoLink,
BaseName,
@@ -143,13 +141,13 @@ public:
strs << string;
}
- Atom(Type type, const QString& string = "")
+ Atom(AtomType type, const QString& string = "")
: next_(0), type_(type)
{
strs << string;
}
- Atom(Type type, const QString& p1, const QString& p2)
+ Atom(AtomType type, const QString& p1, const QString& p2)
: next_(0), type_(type)
{
strs << p1;
@@ -157,14 +155,14 @@ public:
strs << p2;
}
- Atom(Atom* previous, Type type, const QString& string = "")
+ Atom(Atom* previous, AtomType type, const QString& string = "")
: next_(previous->next_), type_(type)
{
strs << string;
previous->next_ = this;
}
- Atom(Atom* previous, Type type, const QString& p1, const QString& p2)
+ Atom(Atom* previous, AtomType type, const QString& p1, const QString& p2)
: next_(previous->next_), type_(type)
{
strs << p1;
@@ -183,9 +181,9 @@ public:
void setNext(Atom* newNext) { next_ = newNext; }
const Atom* next() const { return next_; }
- const Atom* next(Type t) const;
- const Atom* next(Type t, const QString& s) const;
- Type type() const { return type_; }
+ const Atom* next(AtomType t) const;
+ const Atom* next(AtomType t, const QString& s) const;
+ AtomType type() const { return type_; }
QString typeString() const;
const QString& string() const { return strs[0]; }
const QString& string(int i) const { return strs[i]; }
@@ -197,14 +195,14 @@ public:
virtual Node::Genus genus() { return Node::DontCare; }
virtual bool specifiesDomain() { return false; }
virtual Tree* domain() { return 0; }
- virtual Node::Type goal() { return Node::NoType; }
+ virtual Node::NodeType goal() { return Node::NoType; }
virtual const QString& error() { return noError_; }
virtual void resolveSquareBracketParams() { }
protected:
static QString noError_;
Atom* next_;
- Type type_;
+ AtomType type_;
QStringList strs;
};
@@ -220,14 +218,14 @@ class LinkAtom : public Atom
virtual Node::Genus genus() Q_DECL_OVERRIDE { resolveSquareBracketParams(); return genus_; }
virtual bool specifiesDomain() Q_DECL_OVERRIDE { resolveSquareBracketParams(); return (domain_ != 0); }
virtual Tree* domain() Q_DECL_OVERRIDE { resolveSquareBracketParams(); return domain_; }
- virtual Node::Type goal() Q_DECL_OVERRIDE { resolveSquareBracketParams(); return goal_; }
+ virtual Node::NodeType goal() Q_DECL_OVERRIDE { resolveSquareBracketParams(); return goal_; }
virtual const QString& error() Q_DECL_OVERRIDE { return error_; }
virtual void resolveSquareBracketParams() Q_DECL_OVERRIDE;
protected:
bool resolved_;
Node::Genus genus_;
- Node::Type goal_;
+ Node::NodeType goal_;
Tree* domain_;
QString error_;
QString squareBracketParams_;
diff --git a/src/tools/qdoc/codemarker.cpp b/src/tools/qdoc/codemarker.cpp
index 2253aca183..458799fc27 100644
--- a/src/tools/qdoc/codemarker.cpp
+++ b/src/tools/qdoc/codemarker.cpp
@@ -194,6 +194,22 @@ QString CodeMarker::protect(const QString& str)
return marked;
}
+void CodeMarker::appendProtectedString(QString *output, const QStringRef &str)
+{
+ int n = str.length();
+ output->reserve(output->size() + n * 2 + 30);
+ const QChar *data = str.constData();
+ for (int i = 0; i != n; ++i) {
+ switch (data[i].unicode()) {
+ case '&': *output += samp; break;
+ case '<': *output += slt; break;
+ case '>': *output += sgt; break;
+ case '"': *output += squot; break;
+ default : *output += data[i];
+ }
+ }
+}
+
QString CodeMarker::typified(const QString &string)
{
QString result;
@@ -361,8 +377,7 @@ QString CodeMarker::sortName(const Node *node, const QString* name)
else
sortNo = QLatin1String("E");
}
- return sortNo + nodeName + QLatin1Char(' ')
- + QString::number(func->overloadNumber(), 36);
+ return sortNo + nodeName + QLatin1Char(' ') + QString::number(func->overloadNumber(), 36);
}
if (node->type() == Node::Class)
@@ -390,7 +405,7 @@ void CodeMarker::insert(FastSection &fastSection,
bool irrelevant = false;
bool inheritedMember = false;
if (!node->relates()) {
- InnerNode* p = node->parent();
+ Aggregate* p = node->parent();
if (p->isQmlPropertyGroup())
p = p->parent();
if (p != fastSection.parent_) {
@@ -440,7 +455,7 @@ void CodeMarker::insert(FastSection &fastSection,
if (node->parent()->isClass() || node->parent()->isNamespace()) {
if (fastSection.inherited.isEmpty()
|| fastSection.inherited.last().first != node->parent()) {
- QPair<InnerNode *, int> p(node->parent(), 0);
+ QPair<Aggregate *, int> p(node->parent(), 0);
fastSection.inherited.append(p);
}
fastSection.inherited.last().second++;
diff --git a/src/tools/qdoc/codemarker.h b/src/tools/qdoc/codemarker.h
index 7983aa532c..31a9f3a254 100644
--- a/src/tools/qdoc/codemarker.h
+++ b/src/tools/qdoc/codemarker.h
@@ -64,7 +64,7 @@ struct Section
QStringList keys;
NodeList members;
NodeList reimpMembers;
- QList<QPair<InnerNode *, int> > inherited;
+ QList<QPair<Aggregate *, int> > inherited;
ClassKeysNodesList classKeysNodesList_;
Section() { }
@@ -83,7 +83,7 @@ struct Section
struct FastSection
{
- const InnerNode *parent_;
+ const Aggregate *parent_;
QString name;
QString divClass;
QString singularMember;
@@ -91,9 +91,9 @@ struct FastSection
QMultiMap<QString, Node *> memberMap;
QMultiMap<QString, Node *> reimpMemberMap;
ClassMapList classMapList_;
- QList<QPair<InnerNode *, int> > inherited;
+ QList<QPair<Aggregate *, int> > inherited;
- FastSection(const InnerNode *parent,
+ FastSection(const Aggregate *parent,
const QString& name0,
const QString& divClass0,
const QString& singularMember0,
@@ -127,7 +127,7 @@ public:
virtual bool recognizeCode(const QString& code) = 0;
virtual bool recognizeExtension(const QString& ext) = 0;
virtual bool recognizeLanguage(const QString& lang) = 0;
- virtual Atom::Type atomType() const = 0;
+ virtual Atom::AtomType atomType() const = 0;
virtual QString markedUpCode(const QString& code,
const Node *relative,
const Location &location) = 0;
@@ -143,7 +143,7 @@ public:
virtual QString markedUpIncludes(const QStringList& includes) = 0;
virtual QString functionBeginRegExp(const QString& funcName) = 0;
virtual QString functionEndRegExp(const QString& funcName) = 0;
- virtual QList<Section> sections(const InnerNode *inner,
+ virtual QList<Section> sections(const Aggregate *inner,
SynopsisStyle style,
Status status) = 0;
virtual QList<Section> qmlSections(QmlTypeNode* qmlTypeNode,
@@ -163,7 +163,8 @@ public:
protected:
virtual QString sortName(const Node *node, const QString* name = 0);
- QString protect(const QString &string);
+ static QString protect(const QString &string);
+ static void appendProtectedString(QString *output, const QStringRef &str);
QString taggedNode(const Node* node);
QString taggedQmlNode(const Node* node);
QString linkTag(const Node *node, const QString& body);
diff --git a/src/tools/qdoc/codeparser.cpp b/src/tools/qdoc/codeparser.cpp
index a99a446cc2..92a0d52129 100644
--- a/src/tools/qdoc/codeparser.cpp
+++ b/src/tools/qdoc/codeparser.cpp
@@ -65,6 +65,7 @@ QT_BEGIN_NAMESPACE
#define COMMAND_THREADSAFE Doc::alias(QLatin1String("threadsafe"))
#define COMMAND_TITLE Doc::alias(QLatin1String("title"))
#define COMMAND_WRAPPER Doc::alias(QLatin1String("wrapper"))
+#define COMMAND_NOAUTOLIST Doc::alias(QLatin1String("noautolist"))
QList<CodeParser *> CodeParser::parsers;
bool CodeParser::showInternal_ = false;
@@ -219,8 +220,9 @@ const QSet<QString>& CodeParser::commonMetaCommands()
<< COMMAND_THREADSAFE
<< COMMAND_TITLE
<< COMMAND_WRAPPER
- << COMMAND_INJSMODULE;
- }
+ << COMMAND_INJSMODULE
+ << COMMAND_NOAUTOLIST;
+ }
return commonMetaCommands_;
}
@@ -317,6 +319,9 @@ void CodeParser::processCommonMetaCommand(const Location& location,
location.warning(tr("Command '\\%1' is only meanigfule in '\\module' and '\\qmlmodule'.")
.arg(COMMAND_QTVARIABLE));
}
+ else if (command == COMMAND_NOAUTOLIST) {
+ node->setNoAutoList(true);
+ }
}
/*!
@@ -423,33 +428,6 @@ void CodeParser::checkModuleInclusion(Node* n)
.arg(n->name()).arg(Generator::defaultModuleName()));
}
break;
-#if 0
- case Node::Document:
- if (n->access() != Node::Private && !n->doc().isEmpty()) {
- if (n->subType() == Node::HeaderFile) {
-#if 0
- n->doc().location().warning(tr("Header file with title \"%1\" has no \\inmodule command; "
- "using project name by default: %2")
- .arg(n->title()).arg(Generator::defaultModuleName()));
-#endif
- }
- else if (n->subType() == Node::Page) {
-#if 0
- n->doc().location().warning(tr("Page with title \"%1\" has no \\inmodule command; "
- "using project name by default: %2")
- .arg(n->title()).arg(Generator::defaultModuleName()));
-#endif
- }
- else if (n->subType() == Node::Example) {
-#if 0
- n->doc().location().warning(tr("Example with title \"%1\" has no \\inmodule command; "
- "using project name by default: %2")
- .arg(n->title()).arg(Generator::defaultModuleName()));
-#endif
- }
- }
- break;
-#endif
default:
break;
}
diff --git a/src/tools/qdoc/codeparser.h b/src/tools/qdoc/codeparser.h
index 379deb7e23..9d9e9286ec 100644
--- a/src/tools/qdoc/codeparser.h
+++ b/src/tools/qdoc/codeparser.h
@@ -40,7 +40,6 @@
QT_BEGIN_NAMESPACE
class Config;
-class Node;
class QString;
class QDocDatabase;
diff --git a/src/tools/qdoc/config.cpp b/src/tools/qdoc/config.cpp
index 606bb1c619..beb0bae291 100644
--- a/src/tools/qdoc/config.cpp
+++ b/src/tools/qdoc/config.cpp
@@ -91,6 +91,7 @@ QString ConfigStrings::OUTPUTENCODING = QStringLiteral("outputencoding");
QString ConfigStrings::OUTPUTLANGUAGE = QStringLiteral("outputlanguage");
QString ConfigStrings::OUTPUTFORMATS = QStringLiteral("outputformats");
QString ConfigStrings::OUTPUTPREFIXES = QStringLiteral("outputprefixes");
+QString ConfigStrings::OUTPUTSUFFIXES = QStringLiteral("outputsuffixes");
QString ConfigStrings::PROJECT = QStringLiteral("project");
QString ConfigStrings::REDIRECTDOCUMENTATIONTODEVNULL = QStringLiteral("redirectdocumentationtodevnull");
QString ConfigStrings::QHP = QStringLiteral("qhp");
@@ -134,6 +135,7 @@ public:
QStringList accum;
QStringList next;
};
+Q_DECLARE_TYPEINFO(MetaStackEntry, Q_MOVABLE_TYPE);
/*!
Start accumulating values in a list by appending an empty
@@ -912,8 +914,10 @@ QStringList Config::loadMaster(const QString& fileName)
*/
void Config::load(Location location, const QString& fileName)
{
- pushWorkingDir(QFileInfo(fileName).path());
- QDir::setCurrent(QFileInfo(fileName).path());
+ QFileInfo fileInfo(fileName);
+ QString path = fileInfo.canonicalPath();
+ pushWorkingDir(path);
+ QDir::setCurrent(path);
QRegExp keySyntax(QLatin1String("\\w+(?:\\.\\w+)*"));
#define SKIP_CHAR() \
@@ -935,7 +939,7 @@ void Config::load(Location location, const QString& fileName)
if (location.depth() > 16)
location.fatal(tr("Too many nested includes"));
- QFile fin(fileName);
+ QFile fin(fileInfo.fileName());
if (!fin.open(QFile::ReadOnly | QFile::Text)) {
if (!Config::installDir.isEmpty()) {
int prefix = location.filePath().length() - location.fileName().length();
@@ -1030,7 +1034,7 @@ void Config::load(Location location, const QString& fileName)
/*
Here is the recursive call.
*/
- load(location, QFileInfo(QFileInfo(fileName).dir(), includeFile).filePath());
+ load(location, QFileInfo(QDir(path), includeFile).filePath());
}
else {
/*
diff --git a/src/tools/qdoc/config.h b/src/tools/qdoc/config.h
index 802bcf929d..8d6a124bd1 100644
--- a/src/tools/qdoc/config.h
+++ b/src/tools/qdoc/config.h
@@ -203,6 +203,7 @@ struct ConfigStrings
static QString OUTPUTLANGUAGE;
static QString OUTPUTFORMATS;
static QString OUTPUTPREFIXES;
+ static QString OUTPUTSUFFIXES;
static QString PROJECT;
static QString REDIRECTDOCUMENTATIONTODEVNULL;
static QString QHP;
@@ -278,6 +279,7 @@ struct ConfigStrings
#define CONFIG_OUTPUTLANGUAGE ConfigStrings::OUTPUTLANGUAGE
#define CONFIG_OUTPUTFORMATS ConfigStrings::OUTPUTFORMATS
#define CONFIG_OUTPUTPREFIXES ConfigStrings::OUTPUTPREFIXES
+#define CONFIG_OUTPUTSUFFIXES ConfigStrings::OUTPUTSUFFIXES
#define CONFIG_PROJECT ConfigStrings::PROJECT
#define CONFIG_REDIRECTDOCUMENTATIONTODEVNULL ConfigStrings::REDIRECTDOCUMENTATIONTODEVNULL
#define CONFIG_QHP ConfigStrings::QHP
diff --git a/src/tools/qdoc/cppcodemarker.cpp b/src/tools/qdoc/cppcodemarker.cpp
index 4c1e84fe3c..774ff115b9 100644
--- a/src/tools/qdoc/cppcodemarker.cpp
+++ b/src/tools/qdoc/cppcodemarker.cpp
@@ -103,7 +103,7 @@ bool CppCodeMarker::recognizeLanguage(const QString &lang)
/*!
Returns the type of atom used to represent C++ code in the documentation.
*/
-Atom::Type CppCodeMarker::atomType() const
+Atom::AtomType CppCodeMarker::atomType() const
{
return Atom::Code;
}
@@ -157,11 +157,11 @@ QString CppCodeMarker::markedUpSynopsis(const Node *node,
synopsis += "(";
if (!func->parameters().isEmpty()) {
//synopsis += QLatin1Char(' ');
- QList<Parameter>::ConstIterator p = func->parameters().constBegin();
+ QVector<Parameter>::ConstIterator p = func->parameters().constBegin();
while (p != func->parameters().constEnd()) {
if (p != func->parameters().constBegin())
synopsis += ", ";
- synopsis += typified((*p).leftType());
+ synopsis += typified((*p).dataType());
if (style != Subpage && !(*p).name().isEmpty())
synopsis +=
"<@param>" + protect((*p).name()) + "</@param>";
@@ -328,11 +328,11 @@ QString CppCodeMarker::markedUpQmlItem(const Node* node, bool summary)
synopsis = name;
synopsis += QLatin1Char('(');
if (!func->parameters().isEmpty()) {
- QList<Parameter>::ConstIterator p = func->parameters().constBegin();
+ QVector<Parameter>::ConstIterator p = func->parameters().constBegin();
while (p != func->parameters().constEnd()) {
if (p != func->parameters().constBegin())
synopsis += ", ";
- synopsis += typified((*p).leftType());
+ synopsis += typified((*p).dataType());
if (!(*p).name().isEmpty()) {
if (!synopsis.endsWith(QLatin1Char('(')))
synopsis += QLatin1Char(' ');
@@ -436,7 +436,7 @@ QString CppCodeMarker::functionEndRegExp(const QString& /* funcName */)
return "^\\}$";
}
-QList<Section> CppCodeMarker::sections(const InnerNode *inner,
+QList<Section> CppCodeMarker::sections(const Aggregate *inner,
SynopsisStyle style,
Status status)
{
@@ -522,10 +522,10 @@ QList<Section> CppCodeMarker::sections(const InnerNode *inner,
++r;
}
- QStack<const InnerNode *> stack;
+ QStack<const Aggregate *> stack;
stack.push(inner);
while (!stack.isEmpty()) {
- const InnerNode* ancestor = stack.pop();
+ const Aggregate* ancestor = stack.pop();
NodeList::ConstIterator c = ancestor->childNodes().constBegin();
while (c != ancestor->childNodes().constEnd()) {
@@ -537,11 +537,9 @@ QList<Section> CppCodeMarker::sections(const InnerNode *inner,
isSlot = (func->metaness() == FunctionNode::Slot);
isSignal = (func->metaness() == FunctionNode::Signal);
isStatic = func->isStatic();
- if (func->associatedProperty()) {
- if (func->associatedProperty()->status() == Node::Obsolete) {
- ++c;
- continue;
- }
+ if (func->hasAssociatedProperties() && !func->hasActiveAssociatedProperty()) {
+ ++c;
+ continue;
}
}
else if ((*c)->type() == Node::Variable) {
@@ -685,7 +683,7 @@ QList<Section> CppCodeMarker::sections(const InnerNode *inner,
}
else if ((*c)->type() == Node::Function) {
FunctionNode *function = static_cast<FunctionNode *>(*c);
- if (!function->associatedProperty())
+ if (!function->hasAssociatedProperties() || !function->doc().isEmpty())
insert(memberFunctions, function, style, status);
}
++c;
@@ -701,11 +699,11 @@ QList<Section> CppCodeMarker::sections(const InnerNode *inner,
else {
FastSection all(inner,QString(),QString(),"member","members");
- QStack<const InnerNode*> stack;
+ QStack<const Aggregate*> stack;
stack.push(inner);
while (!stack.isEmpty()) {
- const InnerNode* ancestor = stack.pop();
+ const Aggregate* ancestor = stack.pop();
NodeList::ConstIterator c = ancestor->childNodes().constBegin();
while (c != ancestor->childNodes().constEnd()) {
if ((*c)->access() != Node::Private && (*c)->type() != Node::Property)
@@ -812,8 +810,8 @@ QList<Section> CppCodeMarker::sections(const InnerNode *inner,
if (!ns->orphans().isEmpty()) {
foreach (Node* n, ns->orphans()) {
// Use inner as a temporary parent when inserting orphans
- InnerNode* p = n->parent();
- n->setParent(const_cast<InnerNode*>(inner));
+ Aggregate* p = n->parent();
+ n->setParent(const_cast<Aggregate*>(inner));
if (n->isClass())
insert(classes, n, style, status);
else if (n->isNamespace())
@@ -895,8 +893,8 @@ QString CppCodeMarker::addMarkUp(const QString &in,
ch = (i < (int)code.length()) ? code[i++].cell() : EOF
QString code = in;
- QStringList out;
- QString text;
+ QString out;
+ QStringRef text;
int braceDepth = 0;
int parenDepth = 0;
int i = 0;
@@ -931,8 +929,7 @@ QString CppCodeMarker::addMarkUp(const QString &in,
} else if (keywords.contains(ident)) {
tag = QStringLiteral("keyword");
} else if (braceDepth == 0 && parenDepth == 0) {
- if (QString(code.unicode() + i - 1, code.length() - (i - 1))
- .indexOf(findFunctionRegExp) == 0)
+ if (code.indexOf(findFunctionRegExp, i - 1) == i - 1)
tag = QStringLiteral("func");
target = true;
}
@@ -1071,27 +1068,34 @@ QString CppCodeMarker::addMarkUp(const QString &in,
}
}
- text = code.mid(start, finish - start);
+ text = code.midRef(start, finish - start);
start = finish;
if (!tag.isEmpty()) {
- out << QStringLiteral("<@") << tag;
- if (target)
- out << QStringLiteral(" target=\"") << text << QStringLiteral("()\"");
- out << QStringLiteral(">");
+ out += QStringLiteral("<@");
+ out += tag;
+ if (target) {
+ out += QStringLiteral(" target=\"");
+ out += text;
+ out += QStringLiteral("()\"");
+ }
+ out += QStringLiteral(">");
}
- out << protect(text);
+ appendProtectedString(&out, text);
- if (!tag.isEmpty())
- out << QStringLiteral("</@") << tag << QStringLiteral(">");
+ if (!tag.isEmpty()) {
+ out += QStringLiteral("</@");
+ out += tag;
+ out += QStringLiteral(">");
+ }
}
if (start < code.length()) {
- out << protect(code.mid(start));
+ appendProtectedString(&out, code.midRef(start));
}
- return out.join(QString());
+ return out;
}
/*!
diff --git a/src/tools/qdoc/cppcodemarker.h b/src/tools/qdoc/cppcodemarker.h
index 509d130a27..aa759f2993 100644
--- a/src/tools/qdoc/cppcodemarker.h
+++ b/src/tools/qdoc/cppcodemarker.h
@@ -53,7 +53,7 @@ public:
virtual bool recognizeCode(const QString& code) Q_DECL_OVERRIDE;
virtual bool recognizeExtension(const QString& ext) Q_DECL_OVERRIDE;
virtual bool recognizeLanguage(const QString& lang) Q_DECL_OVERRIDE;
- virtual Atom::Type atomType() const Q_DECL_OVERRIDE;
+ virtual Atom::AtomType atomType() const Q_DECL_OVERRIDE;
virtual QString markedUpCode(const QString& code,
const Node *relative,
const Location &location) Q_DECL_OVERRIDE;
@@ -67,7 +67,7 @@ public:
virtual QString markedUpIncludes(const QStringList& includes) Q_DECL_OVERRIDE;
virtual QString functionBeginRegExp(const QString& funcName) Q_DECL_OVERRIDE;
virtual QString functionEndRegExp(const QString& funcName) Q_DECL_OVERRIDE;
- virtual QList<Section> sections(const InnerNode *innerNode,
+ virtual QList<Section> sections(const Aggregate *innerNode,
SynopsisStyle style,
Status status) Q_DECL_OVERRIDE;
virtual QList<Section> qmlSections(QmlTypeNode* qmlTypeNode,
diff --git a/src/tools/qdoc/cppcodeparser.cpp b/src/tools/qdoc/cppcodeparser.cpp
index f12fb70227..5d2a2c90d0 100644
--- a/src/tools/qdoc/cppcodeparser.cpp
+++ b/src/tools/qdoc/cppcodeparser.cpp
@@ -51,8 +51,10 @@ QT_BEGIN_NAMESPACE
/* qmake ignore Q_OBJECT */
static bool inMacroCommand_ = false;
+static bool parsingHeaderFile_ = false;
QStringList CppCodeParser::exampleFiles;
QStringList CppCodeParser::exampleDirs;
+CppCodeParser* CppCodeParser::cppParser_ = 0;
/*!
The constructor initializes some regular expressions
@@ -62,6 +64,7 @@ CppCodeParser::CppCodeParser()
: varComment("/\\*\\s*([a-zA-Z_0-9]+)\\s*\\*/"), sep("(?:<[^>]+>)?::")
{
reset();
+ cppParser_ = this;
}
/*!
@@ -166,7 +169,9 @@ void CppCodeParser::parseHeaderFile(const Location& location, const QString& fil
Tokenizer fileTokenizer(fileLocation, in);
tokenizer = &fileTokenizer;
readToken();
+ parsingHeaderFile_ = true;
matchDeclList(qdb_->primaryTreeRoot());
+ parsingHeaderFile_ = false;
if (!fileTokenizer.version().isEmpty())
qdb_->setVersion(fileTokenizer.version());
in.close();
@@ -250,16 +255,11 @@ void CppCodeParser::doneParsingHeaderFiles()
/*!
This is called after all the source files (i.e., not the
- header files) have been parsed. It traverses the tree to
- resolve property links, normalize overload signatures, and
- do other housekeeping of the database.
+ header files) have been parsed. Currently nothing to do.
*/
void CppCodeParser::doneParsingSourceFiles()
{
- qdb_->primaryTreeRoot()->normalizeOverloads();
- qdb_->fixInheritance();
- qdb_->resolveProperties();
- qdb_->primaryTreeRoot()->makeUndocumentedChildrenInternal();
+ // contents moved to QdocDatabase::resolveIssues()
}
static QSet<QString> topicCommands_;
@@ -376,12 +376,12 @@ Node* CppCodeParser::processTopicCommand(const Doc& doc,
}
else {
func->setMetaness(FunctionNode::MacroWithParams);
- QList<Parameter> params = func->parameters();
+ QVector<Parameter> params = func->parameters();
for (int i = 0; i < params.size(); ++i) {
Parameter &param = params[i];
- if (param.name().isEmpty() && !param.leftType().isEmpty()
- && param.leftType() != "...")
- param = Parameter("", "", param.leftType());
+ if (param.name().isEmpty() && !param.dataType().isEmpty()
+ && param.dataType() != "...")
+ param = Parameter("", "", param.dataType());
}
func->setParameters(params);
}
@@ -408,7 +408,7 @@ Node* CppCodeParser::processTopicCommand(const Doc& doc,
this way to allow the writer to refer to the entity
without including the namespace qualifier.
*/
- Node::Type type = nodeTypeMap[command];
+ Node::NodeType type = nodeTypeMap[command];
QStringList paths = arg.first.split(QLatin1Char(' '));
QStringList path = paths[0].split("::");
Node *node = 0;
@@ -422,7 +422,7 @@ Node* CppCodeParser::processTopicCommand(const Doc& doc,
lastPath_ = path;
}
- else if (node->isInnerNode()) {
+ else if (node->isAggregate()) {
if (type == Node::Namespace) {
NamespaceNode* ns = static_cast<NamespaceNode*>(node);
ns->markSeen();
@@ -520,16 +520,6 @@ Node* CppCodeParser::processTopicCommand(const Doc& doc,
else if (t == "ditamap")
ptype = Node::DitaMapPage;
}
-
-#if 0
- const Node* n = qdb_->checkForCollision(args[0]);
- if (n) {
- QString other = n->doc().location().fileName();
- doc.location().warning(tr("Name/title collision detected: '%1' in '\\%2'")
- .arg(args[0]).arg(command),
- tr("Also used here: %1").arg(other));
- }
-#endif
DocumentNode* dn = 0;
if (ptype == Node::DitaMapPage)
dn = new DitaMapNode(qdb_->primaryTreeRoot(), args[0]);
@@ -572,7 +562,7 @@ Node* CppCodeParser::processTopicCommand(const Doc& doc,
QmlTypeNode* qmlType = qdb_->findQmlType(module, qmlTypeName);
if (qmlType) {
bool attached = false;
- Node::Type nodeType = Node::QmlMethod;
+ Node::NodeType nodeType = Node::QmlMethod;
if ((command == COMMAND_QMLSIGNAL) ||
(command == COMMAND_JSSIGNAL))
nodeType = Node::QmlSignal;
@@ -697,10 +687,10 @@ bool CppCodeParser::splitQmlPropertyArg(const QString& arg,
<type> <QML-type>::<name>(<param>, <param>, ...)
<type> <QML-module>::<QML-type>::<name>(<param>, <param>, ...)
- This function splits the argument into one of those two
- forms, sets \a module, \a qmlTypeName, and \a name, and returns
- true. If the argument doesn't match either form, an error
- message is emitted and false is returned.
+ This function splits the \a{arg}ument into one of those
+ two forms, sets \a type, \a module, and \a qmlTypeName,
+ and returns true. If the argument doesn't match either
+ form, an error message is emitted and false is returned.
\note The two QML types \e{Component} and \e{QtObject} never
have a module qualifier.
@@ -710,30 +700,29 @@ bool CppCodeParser::splitQmlMethodArg(const QString& arg,
QString& module,
QString& qmlTypeName)
{
- QStringList colonSplit(arg.split("::"));
+ QString name;
+ int leftParen = arg.indexOf(QChar('('));
+ if (leftParen > 0)
+ name = arg.left(leftParen);
+ else
+ name = arg;
+ int firstBlank = name.indexOf(QChar(' '));
+ if (firstBlank > 0) {
+ type = name.left(firstBlank);
+ name = name.right(name.length() - firstBlank - 1);
+ }
+ else
+ type.clear();
+
+ QStringList colonSplit(name.split("::"));
if (colonSplit.size() > 1) {
- QStringList blankSplit = colonSplit[0].split(QLatin1Char(' '));
- if (blankSplit.size() > 1) {
- type = blankSplit[0];
- if (colonSplit.size() > 2) {
- module = blankSplit[1];
- qmlTypeName = colonSplit[1];
- }
- else {
- module.clear();
- qmlTypeName = blankSplit[1];
- }
+ if (colonSplit.size() > 2) {
+ module = colonSplit[0];
+ qmlTypeName = colonSplit[1];
}
else {
- type.clear();
- if (colonSplit.size() > 2) {
- module = colonSplit[0];
- qmlTypeName = colonSplit[1];
- }
- else {
- module.clear();
- qmlTypeName = colonSplit[0];
- }
+ module.clear();
+ qmlTypeName = colonSplit[0];
}
return true;
}
@@ -870,7 +859,8 @@ const QSet<QString>& CppCodeParser::otherMetaCommands()
<< COMMAND_QMLINSTANTIATES
<< COMMAND_QMLDEFAULT
<< COMMAND_QMLREADONLY
- << COMMAND_QMLABSTRACT;
+ << COMMAND_QMLABSTRACT
+ << COMMAND_ABSTRACT;
}
return otherMetaCommands_;
}
@@ -887,22 +877,18 @@ void CppCodeParser::processOtherMetaCommand(const Doc& doc,
{
QString arg = argLocPair.first;
if (command == COMMAND_INHEADERFILE) {
- if (node != 0 && node->isInnerNode()) {
- ((InnerNode *) node)->addInclude(arg);
+ if (node != 0 && node->isAggregate()) {
+ ((Aggregate *) node)->addInclude(arg);
}
else {
- doc.location().warning(tr("Ignored '\\%1'")
- .arg(COMMAND_INHEADERFILE));
+ doc.location().warning(tr("Ignored '\\%1'").arg(COMMAND_INHEADERFILE));
}
}
else if (command == COMMAND_OVERLOAD) {
- if (node != 0 && node->type() == Node::Function) {
- ((FunctionNode *) node)->setOverload(true);
- }
- else {
- doc.location().warning(tr("Ignored '\\%1'")
- .arg(COMMAND_OVERLOAD));
- }
+ if (node && node->isFunction())
+ ((FunctionNode *) node)->setOverloadFlag(true);
+ else
+ doc.location().warning(tr("Ignored '\\%1'").arg(COMMAND_OVERLOAD));
}
else if (command == COMMAND_REIMP) {
if (node != 0 && node->parent() && !node->parent()->isInternal()) {
@@ -928,22 +914,29 @@ void CppCodeParser::processOtherMetaCommand(const Doc& doc,
"because its base function is private "
"or internal").arg(COMMAND_REIMP).arg(node->name()));
}
- func->setReimp(true);
+ func->setReimplemented(true);
}
else {
- doc.location().warning(tr("Ignored '\\%1' in %2")
- .arg(COMMAND_REIMP)
- .arg(node->name()));
+ doc.location().warning(tr("Ignored '\\%1' in %2").arg(COMMAND_REIMP).arg(node->name()));
}
}
}
else if (command == COMMAND_RELATES) {
QStringList path = arg.split("::");
Node* n = qdb_->findRelatesNode(path);
- if (!n)
- doc.location().warning(tr("Cannot find '%1' in '\\%2'").arg(arg).arg(COMMAND_RELATES));
+ if (!n) {
+ // Store just a string to write to the index file
+ if (Generator::preparing())
+ node->setRelates(arg);
+ else
+ doc.location().warning(tr("Cannot find '%1' in '\\%2'").arg(arg).arg(COMMAND_RELATES));
+
+ }
+ else if (node->parent() != n)
+ node->setRelates(static_cast<Aggregate*>(n));
else
- node->setRelates(static_cast<InnerNode*>(n));
+ doc.location().warning(tr("Invalid use of '\\%1' (already a member of '%2')")
+ .arg(COMMAND_RELATES, arg));
}
else if (command == COMMAND_CONTENTSPAGE) {
setLink(node, Node::ContentsLink, arg);
@@ -1014,7 +1007,7 @@ void CppCodeParser::processOtherMetaCommand(const Doc& doc,
}
}
}
- else if (command == COMMAND_QMLABSTRACT) {
+ else if ((command == COMMAND_QMLABSTRACT) || (command == COMMAND_ABSTRACT)) {
if (node->isQmlType() || node->isJsType())
node->setAbstract(true);
}
@@ -1051,7 +1044,7 @@ void CppCodeParser::reset()
tokenizer = 0;
tok = 0;
access = Node::Public;
- metaness = FunctionNode::Plain;
+ metaness_ = FunctionNode::Plain;
lastPath_.clear();
physicalModuleName.clear();
}
@@ -1096,8 +1089,7 @@ bool CppCodeParser::match(int target)
readToken();
return true;
}
- else
- return false;
+ return false;
}
/*!
@@ -1236,8 +1228,9 @@ bool CppCodeParser::matchDataType(CodeChunk *dataType, QString *var)
dataType->append(previousLexeme());
}
else if (match(Tok_void) || match(Tok_int) || match(Tok_char) ||
- match(Tok_double) || match(Tok_Ellipsis))
+ match(Tok_double) || match(Tok_Ellipsis)) {
dataType->append(previousLexeme());
+ }
else {
return false;
}
@@ -1323,37 +1316,72 @@ bool CppCodeParser::matchDataType(CodeChunk *dataType, QString *var)
return true;
}
-bool CppCodeParser::matchParameter(FunctionNode *func)
+/*!
+ Parse the next function parameter, if there is one, and
+ append it to parameter vector \a pvect. Return true if
+ a parameter is parsed and appended to \a pvect.
+ Otherwise return false.
+ */
+bool CppCodeParser::matchParameter(QVector<Parameter>& pvect, bool& isQPrivateSignal)
{
- CodeChunk dataType;
- QString name;
- CodeChunk defaultValue;
-
if (match(Tok_QPrivateSignal)) {
- func->setPrivateSignal();
+ isQPrivateSignal = true;
return true;
}
- if (!matchDataType(&dataType, &name)) {
+ Parameter p;
+ CodeChunk chunk;
+ if (!matchDataType(&chunk, &p.name_)) {
return false;
}
+ p.dataType_ = chunk.toString();
+ chunk.clear();
match(Tok_Comment);
if (match(Tok_Equal)) {
- int parenDepth0 = tokenizer->parenDepth();
-
- while (tokenizer->parenDepth() >= parenDepth0 &&
- (tok != Tok_Comma ||
- tokenizer->parenDepth() > parenDepth0) &&
+ int pdepth = tokenizer->parenDepth();
+ while (tokenizer->parenDepth() >= pdepth &&
+ (tok != Tok_Comma || (tokenizer->parenDepth() > pdepth)) &&
tok != Tok_Eoi) {
- defaultValue.append(lexeme());
+ chunk.append(lexeme());
readToken();
}
}
- func->addParameter(Parameter(dataType.toString(), "", name, defaultValue.toString())); // ###
+ p.defaultValue_ = chunk.toString();
+ pvect.append(p);
return true;
}
-bool CppCodeParser::matchFunctionDecl(InnerNode *parent,
+/*!
+ If the current token is any of several function modifiers,
+ return that token value after reading the next token. If it
+ is not one of the function modieifer tokens, return -1 but
+ don\t read the next token.
+ */
+int CppCodeParser::matchFunctionModifier()
+{
+ switch (tok) {
+ case Tok_friend:
+ case Tok_inline:
+ case Tok_explicit:
+ case Tok_static:
+ case Tok_QT_DEPRECATED:
+ readToken();
+ return tok;
+ case Tok_QT_COMPAT:
+ case Tok_QT_COMPAT_CONSTRUCTOR:
+ case Tok_QT_MOC_COMPAT:
+ case Tok_QT3_SUPPORT:
+ case Tok_QT3_SUPPORT_CONSTRUCTOR:
+ case Tok_QT3_MOC_SUPPORT:
+ readToken();
+ return Tok_QT_COMPAT;
+ default:
+ break;
+ }
+ return -1;
+}
+
+bool CppCodeParser::matchFunctionDecl(Aggregate *parent,
QStringList *parentPathPtr,
FunctionNode **funcPtr,
const QString &templateStuff,
@@ -1362,25 +1390,44 @@ bool CppCodeParser::matchFunctionDecl(InnerNode *parent,
CodeChunk returnType;
QStringList parentPath;
QString name;
- bool compat = false;
- if (match(Tok_friend)) {
- return false;
- }
- match(Tok_explicit);
- if (matchCompat())
- compat = true;
- bool sta = false;
- if (match(Tok_static)) {
- sta = true;
- if (matchCompat())
- compat = true;
+ bool matched_QT_DEPRECATED = false;
+ bool matched_friend = false;
+ bool matched_static = false;
+ bool matched_inline = false;
+ bool matched_explicit = false;
+ bool matched_compat = false;
+
+ int token = tok;
+ while (token != -1) {
+ switch (token) {
+ case Tok_friend:
+ matched_friend = true;
+ break;
+ case Tok_inline:
+ matched_inline = true;
+ break;
+ case Tok_explicit:
+ matched_explicit = true;
+ break;
+ case Tok_static:
+ matched_static = true;
+ break;
+ case Tok_QT_DEPRECATED:
+ // no break here.
+ matched_QT_DEPRECATED = true;
+ case Tok_QT_COMPAT:
+ matched_compat = true;
+ break;
+ }
+ token = matchFunctionModifier();
}
- FunctionNode::Virtualness vir = FunctionNode::NonVirtual;
+
+ FunctionNode::Virtualness virtuality = FunctionNode::NonVirtual;
if (match(Tok_virtual)) {
- vir = FunctionNode::ImpureVirtual;
- if (matchCompat())
- compat = true;
+ virtuality = FunctionNode::NormalVirtual;
+ if (!matched_compat)
+ matched_compat = matchCompat();
}
if (!matchDataType(&returnType)) {
@@ -1397,8 +1444,8 @@ bool CppCodeParser::matchFunctionDecl(InnerNode *parent,
if (returnType.toString() == "QBool")
returnType = CodeChunk("bool");
- if (matchCompat())
- compat = true;
+ if (!matched_compat)
+ matched_compat = matchCompat();
if (tok == Tok_operator &&
(returnType.toString().isEmpty() ||
@@ -1437,12 +1484,10 @@ bool CppCodeParser::matchFunctionDecl(InnerNode *parent,
else {
while (match(Tok_Ident)) {
name = previousLexeme();
-
/*
This is a hack to let QML module identifiers through.
*/
matchModuleQualifier(name);
-
matchTemplateAngles();
if (match(Tok_Gulbrandsen))
@@ -1496,68 +1541,111 @@ bool CppCodeParser::matchFunctionDecl(InnerNode *parent,
var->setLocation(location());
var->setLeftType(returnType.left());
var->setRightType(returnType.right());
- if (compat)
+ if (matched_compat)
var->setStatus(Node::Compat);
- var->setStatic(sta);
+ var->setStatic(matched_static);
return false;
}
- if (tok != Tok_LeftParen) {
+ if (tok != Tok_LeftParen)
return false;
- }
}
readToken();
- FunctionNode *func = new FunctionNode(extra.type, parent, name, extra.isAttached);
- func->setAccess(access);
- func->setLocation(location());
- func->setReturnType(returnType.toString());
- func->setParentPath(parentPath);
- func->setTemplateStuff(templateStuff);
- if (compat)
- func->setStatus(Node::Compat);
-
- func->setMetaness(metaness);
- if (parent) {
- if (name == parent->name()) {
- func->setMetaness(FunctionNode::Ctor);
- } else if (name.startsWith(QLatin1Char('~'))) {
- func->setMetaness(FunctionNode::Dtor);
- }
- }
- func->setStatic(sta);
-
+ // A left paren was seen. Parse the parameters
+ bool isQPrivateSignal = false;
+ QVector<Parameter> pvect;
if (tok != Tok_RightParen) {
do {
- if (!matchParameter(func)) {
+ if (!matchParameter(pvect, isQPrivateSignal))
return false;
- }
} while (match(Tok_Comma));
}
- if (!match(Tok_RightParen)) {
+ // The parameters must end with a right paren
+ if (!match(Tok_RightParen))
return false;
- }
- func->setConst(match(Tok_const));
+ // look for const
+ bool matchedConst = match(Tok_const);
+ // look for 0 indicating pure virtual
if (match(Tok_Equal) && match(Tok_Number))
- vir = FunctionNode::PureVirtual;
- func->setVirtualness(vir);
+ virtuality = FunctionNode::PureVirtual;
+ // look for colon indicating ctors which must be skipped
if (match(Tok_Colon)) {
while (tok != Tok_LeftBrace && tok != Tok_Eoi)
readToken();
}
+ // If no ';' expect a body, which must be skipped.
+ bool body_expected = false;
+ bool body_present = false;
if (!match(Tok_Semicolon) && tok != Tok_Eoi) {
- int braceDepth0 = tokenizer->braceDepth();
-
- if (!match(Tok_LeftBrace)) {
+ body_expected = true;
+ int nesting = tokenizer->braceDepth();
+ if (!match(Tok_LeftBrace))
return false;
- }
- while (tokenizer->braceDepth() >= braceDepth0 && tok != Tok_Eoi)
+ // skip the body
+ while (tokenizer->braceDepth() >= nesting && tok != Tok_Eoi)
readToken();
+ body_present = true;
match(Tok_RightBrace);
}
+
+ FunctionNode *func = 0;
+ bool createFunctionNode = false;
+ if (parsingHeaderFile_) {
+ if (matched_friend) {
+ if (matched_inline) {
+ // nothing yet
+ }
+ if (body_present) {
+ if (body_expected) {
+ // nothing yet
+ }
+ createFunctionNode = true;
+ if (parent && parent->parent())
+ parent = parent->parent();
+ else
+ return false;
+ }
+ }
+ else
+ createFunctionNode = true;
+ }
+ else
+ createFunctionNode = true;
+
+ if (createFunctionNode) {
+ func = new FunctionNode(extra.type, parent, name, extra.isAttached);
+ if (matched_friend)
+ access = Node::Public;
+ func->setAccess(access);
+ func->setLocation(location());
+ func->setReturnType(returnType.toString());
+ func->setParentPath(parentPath);
+ func->setTemplateStuff(templateStuff);
+ if (matched_compat)
+ func->setStatus(Node::Compat);
+ if (matched_QT_DEPRECATED)
+ func->setStatus(Node::Deprecated);
+ if (matched_explicit) { /* What can be done? */ }
+ func->setMetaness(metaness_);
+ if (parent) {
+ if (name == parent->name())
+ func->setMetaness(FunctionNode::Ctor);
+ else if (name.startsWith(QLatin1Char('~')))
+ func->setMetaness(FunctionNode::Dtor);
+ }
+ func->setStatic(matched_static);
+ func->setConst(matchedConst);
+ func->setVirtualness(virtuality);
+ if (isQPrivateSignal)
+ func->setPrivateSignal();
+ if (!pvect.isEmpty()) {
+ func->setParameters(pvect);
+ }
+ }
if (parentPathPtr != 0)
*parentPathPtr = parentPath;
if (funcPtr != 0)
@@ -1616,7 +1704,7 @@ bool CppCodeParser::matchBaseList(ClassNode *classe, bool isClass)
sufficient for Qt because there are no cases of class nesting more
than one level deep.
*/
-bool CppCodeParser::matchClassDecl(InnerNode *parent,
+bool CppCodeParser::matchClassDecl(Aggregate *parent,
const QString &templateStuff)
{
bool isClass = (tok == Tok_class);
@@ -1631,7 +1719,7 @@ bool CppCodeParser::matchClassDecl(InnerNode *parent,
if (tok == Tok_Gulbrandsen) {
Node* n = parent->findChildNode(previousLexeme(),Node::Class);
if (n) {
- parent = static_cast<InnerNode*>(n);
+ parent = static_cast<Aggregate*>(n);
if (parent) {
readToken();
if (tok != Tok_Ident)
@@ -1663,17 +1751,17 @@ bool CppCodeParser::matchClassDecl(InnerNode *parent,
Node::Access outerAccess = access;
access = isClass ? Node::Private : Node::Public;
- FunctionNode::Metaness outerMetaness = metaness;
- metaness = FunctionNode::Plain;
+ FunctionNode::Metaness outerMetaness = metaness_;
+ metaness_ = FunctionNode::Plain;
bool matches = (matchDeclList(classe) && match(Tok_RightBrace) &&
match(Tok_Semicolon));
access = outerAccess;
- metaness = outerMetaness;
+ metaness_ = outerMetaness;
return matches;
}
-bool CppCodeParser::matchNamespaceDecl(InnerNode *parent)
+bool CppCodeParser::matchNamespaceDecl(Aggregate *parent)
{
readToken(); // skip 'namespace'
if (tok != Tok_Ident)
@@ -1712,7 +1800,7 @@ bool CppCodeParser::matchNamespaceDecl(InnerNode *parent)
member function is added to \a parent as an unresolved
\c using clause.
*/
-bool CppCodeParser::matchUsingDecl(InnerNode* parent)
+bool CppCodeParser::matchUsingDecl(Aggregate* parent)
{
bool usingNamespace = false;
readToken(); // skip 'using'
@@ -1774,17 +1862,25 @@ bool CppCodeParser::matchUsingDecl(InnerNode* parent)
return true;
}
-bool CppCodeParser::matchEnumItem(InnerNode *parent, EnumNode *enume)
+bool CppCodeParser::matchEnumItem(Aggregate *parent, EnumNode *enume)
{
if (!match(Tok_Ident))
return false;
QString name = previousLexeme();
CodeChunk val;
+ int parenLevel = 0;
if (match(Tok_Equal)) {
- while (tok != Tok_Comma && tok != Tok_RightBrace &&
- tok != Tok_Eoi) {
+ while (tok != Tok_RightBrace && tok != Tok_Eoi) {
+ if (tok == Tok_LeftParen)
+ parenLevel++;
+ else if (tok == Tok_RightParen)
+ parenLevel--;
+ else if (tok == Tok_Comma) {
+ if (parenLevel <= 0)
+ break;
+ }
val.append(lexeme());
readToken();
}
@@ -1825,7 +1921,7 @@ bool CppCodeParser::matchEnumItem(InnerNode *parent, EnumNode *enume)
return true;
}
-bool CppCodeParser::matchEnumDecl(InnerNode *parent)
+bool CppCodeParser::matchEnumDecl(Aggregate *parent)
{
QString name;
@@ -1856,7 +1952,7 @@ bool CppCodeParser::matchEnumDecl(InnerNode *parent)
return match(Tok_RightBrace) && match(Tok_Semicolon);
}
-bool CppCodeParser::matchTypedefDecl(InnerNode *parent)
+bool CppCodeParser::matchTypedefDecl(Aggregate *parent)
{
CodeChunk dataType;
QString name;
@@ -1876,7 +1972,7 @@ bool CppCodeParser::matchTypedefDecl(InnerNode *parent)
return true;
}
-bool CppCodeParser::matchProperty(InnerNode *parent)
+bool CppCodeParser::matchProperty(Aggregate *parent)
{
int expected_tok = Tok_LeftParen;
if (match(Tok_Q_PRIVATE_PROPERTY)) {
@@ -1989,7 +2085,7 @@ bool CppCodeParser::matchProperty(InnerNode *parent)
/*!
Parse a C++ declaration.
*/
-bool CppCodeParser::matchDeclList(InnerNode *parent)
+bool CppCodeParser::matchDeclList(Aggregate *parent)
{
ExtraFuncData extra;
QString templateStuff;
@@ -2030,28 +2126,28 @@ bool CppCodeParser::matchDeclList(InnerNode *parent)
case Tok_private:
readToken();
access = Node::Private;
- metaness = FunctionNode::Plain;
+ metaness_ = FunctionNode::Plain;
break;
case Tok_protected:
readToken();
access = Node::Protected;
- metaness = FunctionNode::Plain;
+ metaness_ = FunctionNode::Plain;
break;
case Tok_public:
readToken();
access = Node::Public;
- metaness = FunctionNode::Plain;
+ metaness_ = FunctionNode::Plain;
break;
case Tok_signals:
case Tok_Q_SIGNALS:
readToken();
access = Node::Public;
- metaness = FunctionNode::Signal;
+ metaness_ = FunctionNode::Signal;
break;
case Tok_slots:
case Tok_Q_SLOTS:
readToken();
- metaness = FunctionNode::Slot;
+ metaness_ = FunctionNode::Slot;
break;
case Tok_Q_OBJECT:
readToken();
@@ -2069,29 +2165,25 @@ bool CppCodeParser::matchDeclList(InnerNode *parent)
case Tok_Q_DECLARE_SEQUENTIAL_ITERATOR:
readToken();
if (match(Tok_LeftParen) && match(Tok_Ident))
- sequentialIteratorClasses.insert(previousLexeme(),
- location().fileName());
+ sequentialIteratorClasses.insert(previousLexeme(), location().fileName());
match(Tok_RightParen);
break;
case Tok_Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR:
readToken();
if (match(Tok_LeftParen) && match(Tok_Ident))
- mutableSequentialIteratorClasses.insert(previousLexeme(),
- location().fileName());
+ mutableSequentialIteratorClasses.insert(previousLexeme(), location().fileName());
match(Tok_RightParen);
break;
case Tok_Q_DECLARE_ASSOCIATIVE_ITERATOR:
readToken();
if (match(Tok_LeftParen) && match(Tok_Ident))
- associativeIteratorClasses.insert(previousLexeme(),
- location().fileName());
+ associativeIteratorClasses.insert(previousLexeme(), location().fileName());
match(Tok_RightParen);
break;
case Tok_Q_DECLARE_MUTABLE_ASSOCIATIVE_ITERATOR:
readToken();
if (match(Tok_LeftParen) && match(Tok_Ident))
- mutableAssociativeIteratorClasses.insert(previousLexeme(),
- location().fileName());
+ mutableAssociativeIteratorClasses.insert(previousLexeme(), location().fileName());
match(Tok_RightParen);
break;
case Tok_Q_DECLARE_FLAGS:
@@ -2256,15 +2348,15 @@ bool CppCodeParser::matchDocsAndStuff()
processOtherMetaCommands(*d, *n);
(*n)->setDoc(*d);
checkModuleInclusion(*n);
- if ((*n)->isInnerNode() && ((InnerNode *)*n)->includes().isEmpty()) {
- InnerNode *m = static_cast<InnerNode *>(*n);
+ if ((*n)->isAggregate() && ((Aggregate *)*n)->includes().isEmpty()) {
+ Aggregate *m = static_cast<Aggregate *>(*n);
while (m->parent() && m->physicalModuleName().isEmpty()) {
m = m->parent();
}
if (m == *n)
- ((InnerNode *)*n)->addInclude((*n)->name());
+ ((Aggregate *)*n)->addInclude((*n)->name());
else
- ((InnerNode *)*n)->setIncludes(m->includes());
+ ((Aggregate *)*n)->setIncludes(m->includes());
}
++d;
++n;
@@ -2333,6 +2425,34 @@ bool CppCodeParser::makeFunctionNode(const QString& signature,
}
/*!
+ This function uses a Tokenizer to parse the \a parameters of a
+ function into the parameter vector \a {pvect}.
+ */
+bool CppCodeParser::parseParameters(const QString& parameters,
+ QVector<Parameter>& pvect,
+ bool& isQPrivateSignal)
+{
+ Tokenizer* outerTokenizer = tokenizer;
+ int outerTok = tok;
+
+ QByteArray latin1 = parameters.toLatin1();
+ Tokenizer stringTokenizer(Location(), latin1);
+ stringTokenizer.setParsingFnOrMacro(true);
+ tokenizer = &stringTokenizer;
+ readToken();
+
+ inMacroCommand_ = false;
+ do {
+ if (!matchParameter(pvect, isQPrivateSignal))
+ return false;
+ } while (match(Tok_Comma));
+
+ tokenizer = outerTokenizer;
+ tok = outerTok;
+ return true;
+}
+
+/*!
Create a new FunctionNode for a QML method or signal, as
specified by \a type, as a child of \a parent. \a sig is
the complete signature, and if \a attached is true, the
@@ -2346,8 +2466,8 @@ bool CppCodeParser::makeFunctionNode(const QString& signature,
*/
FunctionNode* CppCodeParser::makeFunctionNode(const Doc& doc,
const QString& sig,
- InnerNode* parent,
- Node::Type type,
+ Aggregate* parent,
+ Node::NodeType type,
bool attached,
QString qdoctag)
{
diff --git a/src/tools/qdoc/cppcodeparser.h b/src/tools/qdoc/cppcodeparser.h
index f9ddcab88c..ec04482321 100644
--- a/src/tools/qdoc/cppcodeparser.h
+++ b/src/tools/qdoc/cppcodeparser.h
@@ -44,7 +44,7 @@ class ClassNode;
class CodeChunk;
class CppCodeParserPrivate;
class FunctionNode;
-class InnerNode;
+class Aggregate;
class Tokenizer;
class CppCodeParser : public CodeParser
@@ -52,18 +52,19 @@ class CppCodeParser : public CodeParser
Q_DECLARE_TR_FUNCTIONS(QDoc::CppCodeParser)
struct ExtraFuncData {
- InnerNode* root; // Used as the parent.
- Node::Type type; // The node type: Function, etc.
+ Aggregate* root; // Used as the parent.
+ Node::NodeType type; // The node type: Function, etc.
bool isAttached; // If true, the method is attached.
bool isMacro; // If true, we are parsing a macro signature.
ExtraFuncData() : root(0), type(Node::Function), isAttached(false), isMacro(false) { }
- ExtraFuncData(InnerNode* r, Node::Type t, bool a)
+ ExtraFuncData(Aggregate* r, Node::NodeType t, bool a)
: root(r), type(t), isAttached(a), isMacro(false) { }
};
public:
CppCodeParser();
~CppCodeParser();
+ static CppCodeParser* cppParser() { return cppParser_; }
virtual void initializeParser(const Config& config) Q_DECL_OVERRIDE;
virtual void terminateParser() Q_DECL_OVERRIDE;
@@ -74,6 +75,7 @@ public:
virtual void parseSourceFile(const Location& location, const QString& filePath) Q_DECL_OVERRIDE;
virtual void doneParsingHeaderFiles() Q_DECL_OVERRIDE;
virtual void doneParsingSourceFiles() Q_DECL_OVERRIDE;
+ bool parseParameters(const QString& parameters, QVector<Parameter>& pvect, bool& isQPrivateSignal);
protected:
const QSet<QString>& topicCommands();
@@ -116,23 +118,23 @@ protected:
bool matchTemplateAngles(CodeChunk *type = 0);
bool matchTemplateHeader();
bool matchDataType(CodeChunk *type, QString *var = 0);
- bool matchParameter(FunctionNode *func);
- bool matchFunctionDecl(InnerNode *parent,
+ bool matchParameter(QVector<Parameter>& pvect, bool& isQPrivateSignal);
+ bool matchFunctionDecl(Aggregate *parent,
QStringList *parentPathPtr,
FunctionNode **funcPtr,
const QString &templateStuff,
ExtraFuncData& extra);
bool matchBaseSpecifier(ClassNode *classe, bool isClass);
bool matchBaseList(ClassNode *classe, bool isClass);
- bool matchClassDecl(InnerNode *parent,
+ bool matchClassDecl(Aggregate *parent,
const QString &templateStuff = QString());
- bool matchNamespaceDecl(InnerNode *parent);
- bool matchUsingDecl(InnerNode* parent);
- bool matchEnumItem(InnerNode *parent, EnumNode *enume);
- bool matchEnumDecl(InnerNode *parent);
- bool matchTypedefDecl(InnerNode *parent);
- bool matchProperty(InnerNode *parent);
- bool matchDeclList(InnerNode *parent);
+ bool matchNamespaceDecl(Aggregate *parent);
+ bool matchUsingDecl(Aggregate* parent);
+ bool matchEnumItem(Aggregate *parent, EnumNode *enume);
+ bool matchEnumDecl(Aggregate *parent);
+ bool matchTypedefDecl(Aggregate *parent);
+ bool matchProperty(Aggregate *parent);
+ bool matchDeclList(Aggregate *parent);
bool matchDocsAndStuff();
bool makeFunctionNode(const QString &synopsis,
QStringList *parentPathPtr,
@@ -140,8 +142,8 @@ protected:
ExtraFuncData& params);
FunctionNode* makeFunctionNode(const Doc& doc,
const QString& sig,
- InnerNode* parent,
- Node::Type type,
+ Aggregate* parent,
+ Node::NodeType type,
bool attached,
QString qdoctag);
void parseQiteratorDotH(const Location &location, const QString &filePath);
@@ -149,13 +151,14 @@ protected:
const QString &includeFile,
const QString &macroDef);
void createExampleFileNodes(DocumentNode *dn);
+ int matchFunctionModifier();
protected:
- QMap<QString, Node::Type> nodeTypeMap;
+ QMap<QString, Node::NodeType> nodeTypeMap;
Tokenizer *tokenizer;
int tok;
Node::Access access;
- FunctionNode::Metaness metaness;
+ FunctionNode::Metaness metaness_;
QString physicalModuleName;
QStringList lastPath_;
QRegExp varComment;
@@ -173,10 +176,12 @@ protected:
static QStringList exampleFiles;
static QStringList exampleDirs;
+ static CppCodeParser* cppParser_;
QString exampleNameFilter;
QString exampleImageFilter;
};
+#define COMMAND_ABSTRACT Doc::alias("abstract")
#define COMMAND_CLASS Doc::alias("class")
#define COMMAND_CONTENTSPAGE Doc::alias("contentspage")
#define COMMAND_DITAMAP Doc::alias("ditamap")
diff --git a/src/tools/qdoc/doc.cpp b/src/tools/qdoc/doc.cpp
index 92c6d405de..4ed5894543 100644
--- a/src/tools/qdoc/doc.cpp
+++ b/src/tools/qdoc/doc.cpp
@@ -69,7 +69,6 @@ struct Macro
enum {
CMD_A,
- CMD_ABSTRACT,
CMD_ANNOTATEDLIST,
CMD_B,
CMD_BADCODE,
@@ -85,7 +84,6 @@ enum {
CMD_DOTS,
CMD_E,
CMD_ELSE,
- CMD_ENDABSTRACT,
CMD_ENDCHAPTER,
CMD_ENDCODE,
CMD_ENDDIV,
@@ -187,7 +185,6 @@ static struct {
QString *alias;
} cmds[] = {
{ "a", CMD_A, 0 },
- { "abstract", CMD_ABSTRACT, 0 },
{ "annotatedlist", CMD_ANNOTATEDLIST, 0 },
{ "b", CMD_B, 0 },
{ "badcode", CMD_BADCODE, 0 },
@@ -203,7 +200,6 @@ static struct {
{ "dots", CMD_DOTS, 0 },
{ "e", CMD_E, 0 },
{ "else", CMD_ELSE, 0 },
- { "endabstract", CMD_ENDABSTRACT, 0 },
{ "endchapter", CMD_ENDCHAPTER, 0 },
{ "endcode", CMD_ENDCODE, 0 },
{ "enddiv", CMD_ENDDIV, 0 },
@@ -312,7 +308,7 @@ public:
Doc::Sections granularity_;
Doc::Sections section_; // ###
QList<Atom*> tableOfContents_;
- QList<int> tableOfContentsLevels_;
+ QVector<int> tableOfContentsLevels_;
QList<Atom*> keywords_;
QList<Atom*> targets_;
QStringMultiMap metaMap_;
@@ -469,16 +465,16 @@ private:
void endSection(int unit, int endCmd);
void parseAlso();
void append(const QString &string);
- void append(Atom::Type type, const QString& string = QString());
- void append(Atom::Type type, const QString& p1, const QString& p2);
+ void append(Atom::AtomType type, const QString& string = QString());
+ void append(Atom::AtomType type, const QString& p1, const QString& p2);
void append(const QString& p1, const QString& p2);
void appendChar(QChar ch);
void appendWord(const QString &word);
void appendToCode(const QString &code);
- void appendToCode(const QString &code, Atom::Type defaultType);
+ void appendToCode(const QString &code, Atom::AtomType defaultType);
void startNewPara();
- void enterPara(Atom::Type leftType = Atom::ParaLeft,
- Atom::Type rightType = Atom::ParaRight,
+ void enterPara(Atom::AtomType leftType = Atom::ParaLeft,
+ Atom::AtomType rightType = Atom::ParaRight,
const QString& string = QString());
void leavePara();
void leaveValue();
@@ -525,8 +521,8 @@ private:
bool inTableRow;
bool inTableItem;
bool indexStartedPara; // ### rename
- Atom::Type pendingParaLeftType;
- Atom::Type pendingParaRightType;
+ Atom::AtomType pendingParaLeftType;
+ Atom::AtomType pendingParaRightType;
QString pendingParaString;
int braceDepth;
@@ -631,12 +627,6 @@ void DocParser::parse(const QString& source,
append(Atom::FormattingRight,ATOM_FORMATTING_PARAMETER);
priv->params.insert(p1);
break;
- case CMD_ABSTRACT:
- if (openCommand(cmd)) {
- leavePara();
- append(Atom::AbstractLeft);
- }
- break;
case CMD_BADCODE:
leavePara();
append(Atom::CodeBad,getCode(CMD_BADCODE, marker));
@@ -748,12 +738,6 @@ void DocParser::parse(const QString& source,
location().warning(tr("Unexpected '\\%1'").arg(cmdName(CMD_ELSE)));
}
break;
- case CMD_ENDABSTRACT:
- if (closeCommand(cmd)) {
- leavePara();
- append(Atom::AbstractRight);
- }
- break;
case CMD_ENDCHAPTER:
endSection(Doc::Chapter, cmd);
break;
@@ -1830,11 +1814,6 @@ bool DocParser::openCommand(int cmd)
if (outer == CMD_LIST) {
ok = (cmd == CMD_FOOTNOTE || cmd == CMD_LIST);
}
- else if (outer == CMD_ABSTRACT) {
- ok = (cmd == CMD_LIST ||
- cmd == CMD_QUOTATION ||
- cmd == CMD_TABLE);
- }
else if (outer == CMD_SIDEBAR) {
ok = (cmd == CMD_LIST ||
cmd == CMD_QUOTATION ||
@@ -1984,9 +1963,9 @@ void DocParser::parseAlso()
}
}
-void DocParser::append(Atom::Type type, const QString &string)
+void DocParser::append(Atom::AtomType type, const QString &string)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if ((lastType == Atom::Code) && priv->text.lastAtom()->string().endsWith(QLatin1String("\n\n")))
priv->text.lastAtom()->chopString();
priv->text << Atom(type, string);
@@ -1994,15 +1973,15 @@ void DocParser::append(Atom::Type type, const QString &string)
void DocParser::append(const QString &string)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if ((lastType == Atom::Code) && priv->text.lastAtom()->string().endsWith(QLatin1String("\n\n")))
priv->text.lastAtom()->chopString();
priv->text << Atom(string); // The Atom type is Link.
}
-void DocParser::append(Atom::Type type, const QString& p1, const QString& p2)
+void DocParser::append(Atom::AtomType type, const QString& p1, const QString& p2)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if ((lastType == Atom::Code) && priv->text.lastAtom()->string().endsWith(QLatin1String("\n\n")))
priv->text.lastAtom()->chopString();
priv->text << Atom(type, p1, p2);
@@ -2010,7 +1989,7 @@ void DocParser::append(Atom::Type type, const QString& p1, const QString& p2)
void DocParser::append(const QString& p1, const QString& p2)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if ((lastType == Atom::Code) && priv->text.lastAtom()->string().endsWith(QLatin1String("\n\n")))
priv->text.lastAtom()->chopString();
if (p2.isEmpty())
@@ -2043,15 +2022,15 @@ void DocParser::appendWord(const QString &word)
void DocParser::appendToCode(const QString& markedCode)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if (lastType != Atom::Qml && lastType != Atom::Code && lastType != Atom::JavaScript)
append(Atom::Qml);
priv->text.lastAtom()->appendString(markedCode);
}
-void DocParser::appendToCode(const QString &markedCode, Atom::Type defaultType)
+void DocParser::appendToCode(const QString &markedCode, Atom::AtomType defaultType)
{
- Atom::Type lastType = priv->text.lastAtom()->type();
+ Atom::AtomType lastType = priv->text.lastAtom()->type();
if (lastType != Atom::Qml && lastType != Atom::Code && lastType != Atom::JavaScript)
append(defaultType, markedCode);
else
@@ -2064,8 +2043,8 @@ void DocParser::startNewPara()
enterPara();
}
-void DocParser::enterPara(Atom::Type leftType,
- Atom::Type rightType,
+void DocParser::enterPara(Atom::AtomType leftType,
+ Atom::AtomType rightType,
const QString& string)
{
if (paraState == OutsideParagraph) {
@@ -2674,8 +2653,6 @@ void DocParser::skipToNextPreprocessorCommand()
int DocParser::endCmdFor(int cmd)
{
switch (cmd) {
- case CMD_ABSTRACT:
- return CMD_ENDABSTRACT;
case CMD_BADCODE:
return CMD_ENDCODE;
case CMD_CHAPTER:
@@ -3110,7 +3087,7 @@ const QList<Atom *> &Doc::tableOfContents() const
return priv->extra->tableOfContents_;
}
-const QList<int> &Doc::tableOfContentsLevels() const
+const QVector<int> &Doc::tableOfContentsLevels() const
{
priv->constructExtra();
return priv->extra->tableOfContentsLevels_;
diff --git a/src/tools/qdoc/doc.h b/src/tools/qdoc/doc.h
index 80d47287bb..b064b5878e 100644
--- a/src/tools/qdoc/doc.h
+++ b/src/tools/qdoc/doc.h
@@ -168,7 +168,7 @@ public:
bool hasKeywords() const;
bool hasTargets() const;
const QList<Atom *> &tableOfContents() const;
- const QList<int> &tableOfContentsLevels() const;
+ const QVector<int> &tableOfContentsLevels() const;
const QList<Atom *> &keywords() const;
const QList<Atom *> &targets() const;
const QStringMultiMap &metaTagMap() const;
@@ -188,6 +188,7 @@ private:
DocPrivate *priv;
static const Config* config_;
};
+Q_DECLARE_TYPEINFO(Doc, Q_MOVABLE_TYPE);
typedef QList<Doc> DocList;
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/doc/examples/examples.qdoc b/src/tools/qdoc/doc/examples/examples.qdoc
index 777c869c65..ce67dea20e 100644
--- a/src/tools/qdoc/doc/examples/examples.qdoc
+++ b/src/tools/qdoc/doc/examples/examples.qdoc
@@ -89,10 +89,9 @@
\title UI Components
\brief Basic set of UI components
- This is a listing of a list of UI components implemented by QML types. These
-
- files are available for general import and they are based off the \l{Qt
- Quick Code Samples}.
+ This is a listing of a list of UI components implemented by QML types.
+ These files are available for general import and they are based off the
+ \e {Qt Quick Code Samples}.
This module is part of the \l{componentset}{UIComponents} example.
*/
diff --git a/src/tools/qdoc/doc/qdoc-guide/qdoc-guide.qdoc b/src/tools/qdoc/doc/qdoc-guide/qdoc-guide.qdoc
index a8c9c73b5c..af1fa1ba14 100644
--- a/src/tools/qdoc/doc/qdoc-guide/qdoc-guide.qdoc
+++ b/src/tools/qdoc/doc/qdoc-guide/qdoc-guide.qdoc
@@ -112,7 +112,7 @@
Specifying the path to the source directories allow QDoc to find sources and
generate documentation.
- \code
+ \badcode
sourcedirs = <path to source code>
exampledirs = <path to examples directory>
imagedirs = <path to image directory>
@@ -129,7 +129,7 @@
Likewise, QDoc needs the path to the output directory. The \c outputformats
variable determines the type of documentation. These variables should be
in separate configuration files to modularize the documentation build.
- \code
+ \badcode
outputdir = $SAMPLE_PROJECT/doc/html
outputformats = HTML
\endcode
@@ -144,8 +144,8 @@
the \l{Input and Output Directories}{output} directory. It is also possible
to specify extra files that QDoc should export.
- \code
- extraimages.HTML = extraImage.png \
+ \badcode
+ HTML.extraimages = extraImage.png \
extraImage2.png
\endcode
@@ -169,7 +169,7 @@
generated documentation into the directory specified by the \c outputdir
variable.
- \code
+ \badcode
outputformats = HTML
outputdir = <path to output directory>
\endcode
@@ -178,12 +178,12 @@
are located. Typically, the templates directory contains a \c scripts,
\c images, and a \c style directory, containing scripts and CSS files.
- \code
+ \badcode
HTML.templatedir = <path to templates>
\endcode
The main configuration variables are:
- \code
+ \badcode
HTML.postheader
HTML.postpostheader
HTML.postheader
@@ -210,7 +210,7 @@
documentation, QDoc does not need HTML style templates for generating
documentation in DITA XML format.
- \code
+ \badcode
outputformats = DITAXML
outputdir
\endcode
@@ -222,7 +222,7 @@
the articles. Other projects can use the links in the index file so that
they can link to other articles and API documentation within Qt.
- \code
+ \badcode
indexes = $QT_INSTALL_DOCS/html/qt.index $OTHER_PROJECT/html/qt.index
\endcode
It is possible to specify multiple index files from several projects.
@@ -232,7 +232,7 @@
Macros for substituting HTML characters exist and are helpful for generating
specific HTML-valid characters.
- \code
+ \badcode
macro.pi.HTML = "&Pi;"
\endcode
The snippet code will replace any instances of \c{\\pi} with \c &Pi; in the
@@ -245,18 +245,17 @@
with the QML extension, \c{.qml}, if the extension type is included in the
\l{Input and Output Directories}{fileextensions} variable.
- Also, the generated HTML files can have a prefix, specified in the QDoc
- configuration file.
- \code
+ Also, the generated HTML files can have a prefix and a suffix following the
+ QML module name, specified in the QDoc configuration file.
+ \badcode
outputprefixes = QML
outputprefixes.QML = uicomponents-
+ outputsuffixes = QML
+ outputsuffixes.QML = -tp
\endcode
- The outputprefixes will, for example, prefix QML type HTML filenames.
- \code
- files:
- uicomponents-button.html
- uicomponents-scrollbar.html
- \endcode
+
+ \b {See also}: \l {outputprefixes-variable}{outputprefixes},
+ \l {outputsuffixes-variable}{outputsuffixes}.
*/
diff --git a/src/tools/qdoc/doc/qdoc-manual-cmdindex.qdoc b/src/tools/qdoc/doc/qdoc-manual-cmdindex.qdoc
index 87416fcd14..d3f188c265 100644
--- a/src/tools/qdoc/doc/qdoc-manual-cmdindex.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual-cmdindex.qdoc
@@ -89,6 +89,7 @@
\li \l {namespace-command} {\\namespace}
\li \l {nextpage-command} {\\nextpage}
\li \l {newcode-command} {\\newcode}
+ \li \l {noautolist-command} {\\noautolist}
\li \l {nonreentrant-command} {\\nonreentrant}
\li \l {note-command} {\\note}
\li \l {li-command} {\\o} \span {class="newStuff"} {(deprecated, use \\li)}
@@ -106,6 +107,7 @@
\li \l {printto-command} {\\printto}
\li \l {printuntil-command} {\\printuntil}
\li \l {property-command} {\\property}
+ \li \l {qmlabstract-command} {\\qmlabstract}
\li \l {qmlattachedproperty-command} {\\qmlattachedproperty}
\li \l {qmlattachedsignal-command} {\\qmlattachedsignal}
\li \l {qmlbasictype-command} {\\qmlbasictype}
diff --git a/src/tools/qdoc/doc/qdoc-manual-contextcmds.qdoc b/src/tools/qdoc/doc/qdoc-manual-contextcmds.qdoc
index 77987d6d95..a2e851293c 100644
--- a/src/tools/qdoc/doc/qdoc-manual-contextcmds.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual-contextcmds.qdoc
@@ -46,6 +46,7 @@
below the \l {Topic Commands} {topic} command.
\list
+ \li \l {abstract-command} {\\abstract}
\li \l {compat-command}{\\compat},
\li \l {contentspage-command}{\\contentspage},
\li \l {indexpage-command}{\\indexpage},
@@ -59,6 +60,7 @@
\li \l {overload-command}{\\overload},
\li \l {preliminary-command}{\\preliminary},
\li \l {previouspage-command}{\\previouspage},
+ \li \l {qmlabstract-command} {\\qmlabstract}
\li \l {reentrant-command}{\\reentrant},
\li \l {reimp-command}{\\reimp},
\li \l {relates-command}{\\relates},
@@ -75,7 +77,7 @@
\page 15-qdoc-commands-navigation.html
\previouspage Context Commands
\contentspage QDoc Manual
- \nextpage Reporting Status
+ \nextpage Status
\title Document Navigation
@@ -199,21 +201,41 @@
index page of the collection.
*/
-
/*!
\page 16-qdoc-commands-status.html
\previouspage Document Navigation
\contentspage QDoc Manual
\nextpage Thread Support
- \title Reporting Status
-
- These commands are for indicating that a documented element is
- still under development, is becoming obsolete, is provided for
- compatibility reasons, or is simply not to be included in the
- public interface. The \l {since-command}{\\since} command is for
- including information about the version when a function or class
- first appeared.
+ \title Status
+
+ These commands are for indicating that a documented element has
+ some special status. The element could be marked as about to be
+ made obsolete, or that it is provided for compatibility with an
+ earlier version, or is simply not to be included in the public
+ interface. The \l {since-command}{\\since} command is for
+ specifying the version number in which a function or class first
+ appeared. The \l {qmlabstract-command} {\\qmlabstract} command is
+ for marking a QML type as an abstract base class.
+
+ \target abstract-command
+ \target qmlabstract-command
+ \section1 \\abstract and \\qmlabstract
+
+ \\abstract is a synonym for the \\qmlabstract command. Add this
+ command to the \l {qmltype-command} {\\qmltype} comment for a QML
+ type when that type is meant to be used \e {only} as an abstract
+ base type. When a QML type is abstract, it means that the QML type
+ that can't be instantiated. Instead, the properties in its public
+ API are included in the public properties list on the reference
+ page for each QML type that inherits the abstract QML type. The
+ properties are documented as if they are properties of the
+ inheriting QML type.
+
+ Normally, when a QML type is marked with \e{\\qmlabstract}, it is
+ also marked with \e{\\internal} so that its reference page is not
+ generated. It the abstract QML type is not marked internal, it
+ will have a reference page in the documentation.
\target compat-command
\section1 \\compat
@@ -412,13 +434,14 @@
/ *!
\preliminary
- Returns information about the joining properties of the
- character (needed for certain languages such as
- Arabic).
+ Returns information about the joining type attributes of the
+ character (needed for certain languages such as Arabic or
+ Syriac).
+
* /
- QChar::Joining QChar::joining() const
+ QChar::JoiningType QChar::joiningType() const
{
- return ::joining(*this);
+ return QChar::joiningType(ucs);
}
\endcode
@@ -427,28 +450,25 @@
\quotation
\raw HTML
<h3>
- <a href="http://doc.qt.io/qt-5/qchar.html#JoiningType-enum">Joining</a>
- QChar::joining () const</h3>
+ <a href="http://doc.qt.io/qt-5/qchar.html#JoiningType-enum">JoiningType</a>
+ QChar::joiningType() const</h3>
\endraw
\b {This function is under development and
subject to change.}
- Returns information about the joining properties of the
- character (needed for certain languages such as
- Arabic).
+ Returns information about the joining type attributes of the
+ character (needed for certain languages such as Arabic or
+ Syriac).
\endquotation
- And the function's entry in QChar's list of functions will be
+ And the function's entry in QChar's list of public functions will be
rendered as:
\quotation
\list
\li ...
- \li Joining
- \l {Joining-enum}
- {joining}()
- const \c (preliminary)
+ \li JoiningType \l {QChar::joiningType()} {joiningType}() const \c (preliminary)
\li ...
\endlist
\endquotation
@@ -502,7 +522,7 @@
/*!
\page 17-qdoc-commands-thread.html
- \previouspage Reporting Status
+ \previouspage Status
\contentspage QDoc Manual
\nextpage Relating Things
@@ -680,8 +700,6 @@
\l{threadsafe-command} {\\threadsafe}.
*/
- / *!
-
/*!
\page 18-qdoc-commands-relating.html
\previouspage Thread Support
@@ -791,7 +809,7 @@
</h3>
\endraw
- This function overloads \l {addAction} {addAction()}
+ This function overloads \l {QMenu::addAction()} {addAction()}
This convenience function creates a new action with an
\e icon and some \e text. The function adds the newly
@@ -799,8 +817,7 @@
returns it.
See also
- \l {addAction}
- {QWidget::addAction}().
+ \l {QWidget::addAction()} {QWidget::addAction}().
\endquotation
If you don't include the function name with the \b{\\overload}
diff --git a/src/tools/qdoc/doc/qdoc-manual-markupcmds.qdoc b/src/tools/qdoc/doc/qdoc-manual-markupcmds.qdoc
index d764cde89d..49cbfc0654 100644
--- a/src/tools/qdoc/doc/qdoc-manual-markupcmds.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual-markupcmds.qdoc
@@ -38,7 +38,6 @@
\list
\li \l {a-command} {\\a}
- \li \l {abstract-command} {\\abstract}
\li \l {annotatedlist-command} {\\annotatedlist}
\li \l {b-command} {\\b} \span {class="newStuff"}
\li \l {b-command} {\\bold} {(deprecated, use \\b)}
@@ -68,6 +67,7 @@
\li \l {li-command} {\\li} \span {class="newStuff"}
\li \l {list-command} {\\list}
\li \l {meta-command} {\\meta}
+ \li \l {noautolist-command} {\\noautolist}
\li \l {newcode-command} {\\newcode}
\li \l {li-command} {\\o} \span {class="newStuff"} {(deprecated, use \\li)}
\li \l {note-command} {\\note}
@@ -1839,8 +1839,13 @@
\li \c {\l QWidget} - The name of a class documented with the \l
{class-command} {\\class} command.
- \li \c {\l QWidget::sizeHint()} - The name of a member function,
- documented with or without an \l {fn-command} {\\fn} command.
+ \li \c {\l QWidget::sizeHint()} - The signature of a function without
+ parameters. If a matching function without parameters can't be found,
+ the link is satisfied with the first matching function found.
+
+ \li \c {\l QWidget::removeAction(QAction* action)} - The signature
+ of a function with parameters. If an exact match is not found, the
+ link is not satisfied and qdoc reports a \e {Can't link to...} error.
\li \c {\l <QtGlobal>} - The subject of a \l {headerfile-command}
{\\headerfile} command.
@@ -2092,8 +2097,11 @@
{sa-command} {\\sa (see also)} commands.
The \\keyword command is like the \l {target-command} {\\target}
- command, but stronger. A keyword can be linked from anywhere using
- a simple syntax.
+ command, except when linking to keyword the link goes to the top of
+ the QDoc comment where the \\keyword appears in. If you want to
+ create a link target to a \c section unit within a \\page, use
+ \\target instead. A keyword can be linked from anywhere using a
+ simple syntax.
Keywords must be unique over all the documents processed during
the QDoc run. The command uses the rest of the line as its
@@ -2886,19 +2894,6 @@
parts with a special rendering, conceptual meaning or
function.
- \target abstract-command
- \section1 \\abstract
-
- The \\abstract and \\endabstract commands delimit a
- document's abstract section.
-
- The abstract section is rendered as an indented italicized
- paragraph.
-
- \warning The \b{\\abstract} and \b{\\endabstract} commands
- have not been implemented. The abstract section is rendered as a
- regular HTML paragraph.
-
\target quotation-command
\section1 \\quotation
@@ -3465,6 +3460,20 @@
with the \l {inmodule-command} {\\inmodule} command in its \\class
comment.
+ \section2 \c qmltypesbymodule
+
+ Similar to \c classesbymodule argument, but used for listing the
+ QML types from the QML module specified with the second argument.
+
+ \note Support for this argument was introduced in QDoc 5.6.
+
+ \section2 \c jstypesbymodule
+
+ Similar to \c classesbymodule argument, but used for listing the
+ JavaScript types from the module specified with the second argument.
+
+ \note Support for this argument was introduced in QDoc 5.6.
+
\section2 \c compatclasses
The \c compatclasses argument generates a list in alphabetical
@@ -3895,6 +3904,28 @@
values obtained from the QDoc configuration file. See \l
{Generating DITA XML Output} for details.
+ \target noautolist-command
+ \section1 \\noautolist
+
+ The \\noautolist command indicates that the annotated list of C++
+ classes or QML types, which is automatically generated at the
+ bottom of the C++ or QML module page should be omitted, because
+ the classes or types have been listed manually. This command can
+ also be used with the \l {group-command}{\\group} command to omit
+ the list of group members, when they are listed manually.
+
+ The command must stand on its own line. See \l {Qt Sensors QML Types} for
+ an example. The page is generated from \c {qtsensors5.qdoc}. There you will
+ find a qdoc comment containing the \c{\qmlmodule} command for the QtSensors
+ module. The same qdoc comment contains two \c {\annotated-list} commands to
+ list the QML types in two separate groups. The QML types have been divided
+ into these two groups because it makes more sense to list them this way than
+ it does to list them in a single alphabetical list. At the bottom of the
+ comment, \c {\noautolist} has been used to tell qdoc not to generate the
+ automatic annotated list.
+
+ This command was introduced in QDoc 5.6.
+
\target omit-command
\section1 \\omit
diff --git a/src/tools/qdoc/doc/qdoc-manual-qdocconf.qdoc b/src/tools/qdoc/doc/qdoc-manual-qdocconf.qdoc
index 226c107e3a..2472b0f4fb 100644
--- a/src/tools/qdoc/doc/qdoc-manual-qdocconf.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual-qdocconf.qdoc
@@ -69,14 +69,14 @@
you to use special characters like '=' and ' \" ' within the value
string, for example:
- \code
+ \badcode
HTML.postheader = "<a href=\"index.html\">Home</a>"
\endcode
If an entry spans many lines, use a backslash at the end of every
line but the last:
- \code
+ \badcode
sourcedirs = kernel \
tools \
widgets
@@ -113,6 +113,8 @@
\li \l {manifestmeta-variable} {manifestmeta}
\li \l {outputdir-variable} {outputdir}
\li \l {outputformats-variable} {outputformats}
+ \li \l {outputprefixes-variable} {outputprefixes}
+ \li \l {outputsuffixes-variable} {outputsuffixes}
\li \l {sourcedirs-variable} {sourcedirs}
\li \l {sources-variable} {sources}
\li \l {sources.fileextensions-variable} {sources.fileextensions}
@@ -161,7 +163,7 @@
The general syntax is \tt {alias.\e{original-command-name} = \e
temporary-command-name}.
- \code
+ \badcode
alias.e = i
\endcode
@@ -198,7 +200,7 @@
for details). By default, no symbol is defined, meaning that code
protected with #ifdef...#endif will be ignored.
- \code
+ \badcode
defines = Q_QDOC \
QT_.*_SUPPORT \
QT_.*_LIB \
@@ -226,7 +228,7 @@
You can also define preprocessor symbols manually on the command
line using the -D option. For example:
- \code
+ \badcode
currentdirectory$ qdoc -Dconsoleedition qtgui.qdocconf
\endcode
@@ -249,7 +251,7 @@
The \c edition variable is always used with a particular edition
name to define the modules for that edition:
- \code
+ \badcode
edition.Console = QtCore QtNetwork QtSql QtXml
edition.Desktop = QtCore QtGui QtNetwork QtOpenGL QtSql QtXml \
QtDesigner QtAssistant Qt3Support QAxContainer \
@@ -263,7 +265,7 @@
{generatelist} command is used to generate a list of classes for
this edition:
- \code
+ \badcode
\generatelist{classesbyedition Console}
\endcode
@@ -286,7 +288,7 @@
and accept the first matching file it finds. It will only search
in the specified directories, \e not in subdirectories.
- \code
+ \badcode
exampledirs = $QTDIR/doc/src \
$QTDIR/examples \
$QTDIR \
@@ -297,7 +299,7 @@
When processing
- \code
+ \badcode
\quotefromfile widgets/calculator/calculator.cpp
\endcode
@@ -306,13 +308,13 @@
there isn't, it will search in the \c exampledirs variable, and
first see if there exists a file called
- \code
+ \badcode
$QTDIR/doc/src/widgets/calculator/calculator.cpp
\endcode
If it doesn't, QDoc will continue looking for a file called
- \code
+ \badcode
$QTDIR/examples/widgets/calculator/calculator.cpp
\endcode
@@ -343,7 +345,7 @@
exampledirs} command. But note that if you know the file is listed
in the \c examples variable, you don't need to specify its path:
- \code
+ \badcode
\quotefromfile calculator.cpp
\endcode
@@ -362,7 +364,7 @@
The extensions are given as standard wildcard expressions. You
can add a file extension to the filter using '+='. For example:
- \code
+ \badcode
examples.fileextensions += *.qrc
\endcode
@@ -378,7 +380,7 @@
For example:
- \code
+ \badcode
sourcedirs = src/corelib
excludedirs = src/corelib/tmp
\endcode
@@ -395,7 +397,7 @@
The \c excludefiles variable allows you to specify individual files
that should \e{not} be processed by qdoc.
- \code
+ \badcode
excludefiles += $QT_CORE_SOURCES/../../src/widgets/kernel/qwidget.h \
$QT_CORE_SOURCES/../../src/widgets/kernel/qwidget.cpp
\endcode
@@ -427,7 +429,7 @@
reason, these images are specified using the \c extraimages
variable:
- \code
+ \badcode
extraimages.HTML = qt-logo
\endcode
@@ -468,7 +470,7 @@
preprocessor symbol is specified within the \c falsehoods variable
entry:
- \code
+ \badcode
falsehoods = NOTYET
\endcode
@@ -494,7 +496,7 @@
the header files associated with the \c .cpp source files used in
the documentation.
- \code
+ \badcode
headerdirs = $QTDIR/src \
$QTDIR/extensions/activeqt \
$QTDIR/extensions/motif \
@@ -536,7 +538,7 @@
files in addition to those located in the directories specified by
the \l {headerdirs} {\c headerdirs} variable.
- \code
+ \badcode
headers = $QTDIR/src/gui/widgets/qlineedit.h \
$QTDIR/src/gui/widgets/qpushbutton.h
\endcode
@@ -566,7 +568,7 @@
The extensions are given as standard wildcard expressions. You
can add a file extension to the filter using '+='. For example:
- \code
+ \badcode
header.fileextensions += *.H
\endcode
@@ -590,7 +592,7 @@
and accept the first matching file it finds. It will only search
in the specified directories, \e not in subdirectories.
- \code
+ \badcode
imagedirs = $QTDIR/doc/src/images \
$QTDIR/examples
@@ -599,7 +601,7 @@
When processing
- \code
+ \badcode
\image calculator-example.png
\endcode
@@ -608,13 +610,13 @@
variable. If there isn't, it will search in the \c imagedirs
variable for:
- \code
+ \badcode
$QTDIR/doc/src/images/calculator-example.png
\endcode
If the file doesn't exist, QDoc will look for a file called
- \code
+ \badcode
$QTDIR/examples/calculator-example.png
\endcode
@@ -636,7 +638,7 @@
files in addition to those located in the directories specified by
the \l {imagedirs} {\c imagedirs} variable.
- \code
+ \badcode
images = $QTDIR/doc/src/images/calculator-example.png
\endcode
@@ -660,7 +662,7 @@
The idea is to enable different image format for different output
format.
- \code
+ \badcode
images.fileextensions.HTML = *.png
images.fileextensions.LOUT = *.eps
\endcode
@@ -679,7 +681,7 @@
You can add a file extension to the filter using '+='. For
example:
- \code
+ \badcode
images.fileextensions.HTML += *.eps
\endcode
@@ -696,7 +698,7 @@
specified. However, a possible example of a language variable
statement:
- \code
+ \badcode
language = Cpp
\endcode
@@ -715,7 +717,7 @@
appending \c {.DITAXML} to the macro name, the macro is only used
when generating DITA XML.
- \code
+ \badcode
macro.gui = "\\b"
macro.raisedaster.HTML = "<sup>*</sup>"
\endcode
@@ -741,7 +743,7 @@
The \c naturallanguage variable specifies the natural language
used for the documentation generated by qdoc.
- \code
+ \badcode
naturallanguage = zh-Hans
\endcode
@@ -764,7 +766,7 @@
The \c outputdir variable specifies the directory where QDoc will
put the generated documentation.
- \code
+ \badcode
outputdir = $QTDIR/doc/html
\endcode
@@ -772,7 +774,7 @@
$QTDIR/doc/html. For example, the documentation of the QWidget
class is located in
- \code
+ \badcode
$QTDIR/doc/html/qwidget.html
\endcode
@@ -787,7 +789,7 @@
The \c outputencoding variable specifies the encoding used for the
documentation generated by qdoc.
- \code
+ \badcode
outputencoding = UTF-8
\endcode
@@ -814,21 +816,48 @@
Currently, QDoc only supports the HTML format. It is also
the default format, and doesn't need to be specified.
- \target outputprefixes
+ \target outputprefixes-variable
\section1 outputprefixes
The \c outputprefixes variable specifies a mapping between types of files
and the prefixes to prepend to the HTML file names in the generated
documentation.
- \code
- outputprefixes = QML
+ \badcode
+ outputprefixes = QML JS
outputprefixes.QML = uicomponents-
+ outputprefixes.JS = uicomponents-
\endcode
By default, files containing the API documentation for QML types
- are prefixed with "qml-". In the above example, the
- prefix \c "uicomponents" is used instead.
+ are prefixed with "qml-", and javaScript types with "js-". In the
+ above example, the prefix \c "uicomponents" is used instead for
+ both.
+
+ The output prefix is applied to file names for documentation on
+ QML and JS types.
+
+ \target outputsuffixes-variable
+ \section1 outputsuffixes
+
+ The \c outputsuffixes variable specifies a mapping between types of
+ files and module name suffixes to append to the HTML file names.
+
+ \badcode
+ outputsuffixes = QML
+ outputsuffixes.QML = -tp
+ \endcode
+
+ Given a QML module name \e FooBar and the default
+ \l {outputprefixes-variable}{output prefix} ("qml-"), the file name of
+ the generated HTML page for a QML type \e FooWidget would be
+ \c qml-foobar-tp-foowidget.html.
+
+ By default, no suffix is used. The output suffix, if defined, is applied
+ to file names for documentation on QML and JS types, and their respective
+ module pages.
+
+ The \c outputsuffixes variable was introduced in QDoc 5.6.
\target qhp-variable
\section1 qhp
@@ -845,7 +874,7 @@
The \c sourcedirs variable specifies the directories containing
the \c .cpp or \c .qdoc files used in the documentation.
- \code
+ \badcode
sourcedirs += .. \
../../../examples/gui/doc/src
\endcode
@@ -881,7 +910,7 @@
The \c sourceencoding variable specifies the encoding used for the
source code and documentation.
- \code
+ \badcode
sourceencoding = UTF-8
\endcode
@@ -906,7 +935,7 @@
files in addition to those located in the directories specified by
the \l {sourcedirs-variable} {sourcedirs} variable.
- \code
+ \badcode
sources = $QTDIR/src/gui/widgets/qlineedit.cpp \
$QTDIR/src/gui/widgets/qpushbutton.cpp
\endcode
@@ -935,7 +964,7 @@
The extensions are given as standard wildcard expressions. You
can add a file extension to the filter using '+='. For example:
- \code
+ \badcode
sources.fileextensions += *.CC
\endcode
@@ -952,7 +981,7 @@
output. The warnings are specified using standard wildcard
expressions.
- \code
+ \badcode
spurious = "Cannot find .*" \
"Missing .*"
\endcode
@@ -961,8 +990,8 @@
will not be part of the output when running QDoc. For example
would the following warning be omitted from the output:
- \code
- qt-4.0/src/opengl/qgl_mac.cpp:156: Missing parameter name
+ \badcode
+ src/opengl/qgl_mac.cpp:156: Missing parameter name
\endcode
\target syntaxhighlighting
@@ -972,7 +1001,7 @@
perform syntax highlighting on source code quoted in the
documentation it generates.
- \code
+ \badcode
syntaxhighlighting = true
\endcode
@@ -984,7 +1013,7 @@
The \c tabsize variable defines the size of a tab character.
- \code
+ \badcode
tabsize = 4
\endcode
@@ -1003,8 +1032,8 @@
The \c version variable specifies the version number of the
documented software.
- \code
- version = 4.0.1
+ \badcode
+ version = 5.6.0
\endcode
When a version number is specified (using the \tt{\l version} or
@@ -1023,13 +1052,13 @@
The \c versionsym variable specifies a C++ preprocessor symbol
that defines the version number of the documented software.
- \code
+ \badcode
versionsym = QT_VERSION_STR
\endcode
QT_VERSION_STR is defined in qglobal.h as follows
- \code
+ \badcode
#define QT_VERSION_STR "4.0.1"
\endcode
@@ -1054,42 +1083,106 @@
\section1 Overview
- Starting with Qt 4.4, Qt Assistant uses a different system for managing
- Qt documentation that requires QDoc to generate inventories of files in a
- format that is similar to the old style DCF format, but with additional
- features.
+ Qt Assistant uses a system for managing Qt documentation that requires
+ QDoc to generate inventories of files in a format that is similar to the
+ old style DCF format, but with additional features.
- Instead of hard-coding information about the documentation sets for Qt,
QDoc allows configuration variables to be used to specify which pages are
to be used in each documentation set it generates. These are specified as
- subvariables of the \c qch variable with each set declared using a unique
+ subvariables of the \c qhp variable with each set declared using a unique
identifier as a subvariable.
- For example, the configuration file for the Qt documentation defines a
- \c Qt documentation set by specifying information about the set as
- subvariables with the \c{qhp.Qt} prefix:
-
- \code
- qhp.Qt.file = qt.qhp
- qhp.Qt.namespace = org.qt-project.qtcore.$QT_VERSION_TAG
- qhp.Qt.virtualFolder = qdoc
- qhp.Qt.indexTitle = Qt Reference Documentation
- qhp.Qt.indexRoot =
- qhp.Qt.extraFiles = classic.css images/qt-logo.png
- qhp.Qt.filterAttributes = qt 4.4.0 qtrefdoc
- qhp.Qt.customFilters.Qt.name = Qt 4.4.0
- qhp.Qt.customFilters.Qt.filterAttributes = qt 4.4.0
- qhp.Qt.subprojects = classes overviews examples
- qhp.Qt.subprojects.classes.title = Classes
- qhp.Qt.subprojects.classes.indexTitle = Qt's Classes
- qhp.Qt.subprojects.classes.selectors = class
- qhp.Qt.subprojects.overviews.title = Overviews
- qhp.Qt.subprojects.overviews.indexTitle = All Overviews and HOWTOs
- qhp.Qt.subprojects.overviews.selectors = fake:page,group,module
- qhp.Qt.subprojects.examples.title = Tutorials and Examples
- qhp.Qt.subprojects.examples.indexTitle = Qt Examples
- qhp.Qt.subprojects.examples.selectors = fake:example
- \endcode
+ For example, the configuration file for the Qt Quick documentation set
+ specifies information about the set as subvariables with the
+ \c{qhp.QtQuick} prefix:
+
+ \badcode
+ qhp.projects = QtQuick
+
+ qhp.QtQuick.file = qtquick.qhp
+ qhp.QtQuick.namespace = org.qt-project.qtquick.$QT_VERSION_TAG
+ qhp.QtQuick.virtualFolder = qtquick
+ qhp.QtQuick.indexTitle = Qt Quick
+ qhp.QtQuick.indexRoot =
+
+ qhp.QtQuick.filterAttributes = qtquick $QT_VERSION qtrefdoc
+ qhp.QtQuick.customFilters.Qt.name = QtQuick $QT_VERSION
+ qhp.QtQuick.customFilters.Qt.filterAttributes = qtquick $QT_VERSION
+
+ qhp.QtQuick.subprojects = qmltypes classes examples
+
+ qhp.QtQuick.subprojects.qmltypes.title = QML Types
+ qhp.QtQuick.subprojects.qmltypes.indexTitle = Qt Quick QML Types
+ qhp.QtQuick.subprojects.qmltypes.selectors = qmlclass
+ qhp.QtQuick.subprojects.qmltypes.sortPages = true
+
+ qhp.QtQuick.subprojects.classes.title = Classes
+ qhp.QtQuick.subprojects.classes.title = C++ Classes
+ qhp.QtQuick.subprojects.classes.indexTitle = Qt Quick C++ Classes
+ qhp.QtQuick.subprojects.classes.selectors = class fake:headerfile
+ qhp.QtQuick.subprojects.classes.sortPages = true
+
+ qhp.QtQuick.subprojects.examples.title = Examples
+ qhp.QtQuick.subprojects.examples.indexTitle = Qt Quick Examples and Tutorials
+ qhp.QtQuick.subprojects.examples.selectors = fake:example
+ \endcode
+
+ The documentation set may include one or more subprojects, which are added
+ to the table of contents under the name specified by \c title. The page
+ in the documentation referred to by the \c indexTitle acts as the index page
+ for the subproject. The page types to list under the subproject are specified
+ by \c selectors. The entries are alphabetically sorted if \c sortPages is set
+ to \c true.
+
+ \section2 Using Selectors
+
+ The \c selectors property specifies which page types are listed under the
+ table of contents entry for a subproject. Multiple selectors can be listed,
+ separated by whitespace.
+
+ \table
+ \header \li Selector \li Description
+ \row \li \c namespace \li Namespaces
+ \row \li \c class \li Classes
+ \row \li \c qmltype \li QML Types
+ \row \li \c qmlclass \li Alias for \c qmltype.
+ \row \li \c module \li C++ Modules
+ \row \li \c qmlmodule \li QML Modules
+ \row \li \c doc[:subtype] \li Documentation pages with a specified
+ \c subtype. Multiple subtypes can be
+ listed as a comma-separated list.
+ \row \li \c fake \li Alias for \c doc.
+ \row \li \c group[:groupname] \li Documentation pages for members of a
+ specified group, as added using the
+ \l {ingroup-command}
+ {\\ingroup} groupname command.
+ Multiple group names can be listed as
+ a comma-separated list.
+ (Introduced in QDoc 5.6).
+ \endtable
+
+ Available subtypes for the \c doc selector:
+
+ \table
+ \header \li Subtype \li Description
+ \row \li \c example \li Examples
+ \row \li \c headerfile \li Header files
+ \row \li \c page \li Documentation pages defined with the
+ \l {page-command} {\\page} command.
+ \endtable
+
+ For example, the following configuration would select example pages and
+ pages that include the \c {\ingroup tutorials} command:
+
+ \badcode
+ qhp.QtQuickControls.subprojects = examples
+ qhp.QtQuickControls.subprojects.examples.title = Examples and Tutorials
+ qhp.QtQuickControls.subprojects.examples.indexTitle = Qt Quick Controls Examples
+ qhp.QtQuickControls.subprojects.examples.selectors = doc:example group:tutorials
+ qhp.QtQuickControls.subprojects.examples.sortPages = true
+ \endcode
+
+ \section2 Adding Table of Contents
To create a table of contents for a manual, create a subproject with
a \c{type} property and set it to \c{manual}. The page in the documentation
@@ -1101,7 +1194,7 @@
subproject for its documentation, including all the documentation in a
single manual:
- \code
+ \badcode
qhp.QtCreator.subprojects = manual
qhp.QtCreator.subprojects.manual.title = Qt Creator Manual
qhp.QtCreator.subprojects.manual.indexTitle = Qt Creator Manual
@@ -1133,7 +1226,7 @@
Cpp.ignoredirectives} variables, non-standard constructs
(typically macros) can result in erroneous documentation.
- \code
+ \badcode
Cpp.ignoredirectives = Q_DECLARE_INTERFACE \
Q_DECLARE_OPERATORS_FOR_FLAGS \
Q_DECLARE_PRIVATE \
@@ -1187,7 +1280,7 @@
In \l qtgui.qdocconf:
- \code
+ \badcode
Cpp.ignoretokens = QAXFACTORY_EXPORT \
QM_EXPORT_CANVAS \
...
@@ -1250,15 +1343,12 @@
quotation marks. Note that if the value spans several lines, each
line needs to be enclosed by quotation marks.
- \code
+ \badcode
HTML.footer = "<p /><address><hr /><div align=\"center\">\n" \
...
"</tr></table></div></address>"
\endcode
- The complete variable entry provides the standard footer of the
- \l {http://doc.qt.digia.com/4.0/index.html} {Qt Reference Documentation}.
-
\target HTML.postheader-variable
\section1 HTML.postheader
@@ -1272,7 +1362,7 @@
marks. Note that if the value spans several lines, each line needs
to be enclosed by quotation marks.
- \code
+ \badcode
HTML.postheader = "<table border=\"0\"..." \
...
"<img src=\"images/qt-logo.png\" \
@@ -1296,7 +1386,7 @@
marks. Note that if the value spans several lines, each line needs
to be enclosed by quotation marks.
- \code
+ \badcode
HTML.style = "h3.fn,span.fn" \
"{ margin-left: 1cm; text-indent: -1cm; }\n" \
"a:link { color: #004faf; text-decoration: none }\n" \
@@ -1307,10 +1397,6 @@
"body { background: #ffffff; color: black; }"
\endcode
- provides the HTML style for the \l
- {http://doc.qt.digia.com/4.0/index.html} {Qt Reference
- Documentation}.
-
\target HTML.stylesheets-variable
\section1 HTML.stylesheets
@@ -1322,7 +1408,7 @@
has been generated. Typically, it is only necessary to define a
single stylesheet for any set of documentation; for example:
- \code
+ \badcode
HTML.stylesheets = classic.css
\endcode
@@ -1371,7 +1457,7 @@
Reference documentation, you need to specify the associated index
file:
- \code
+ \badcode
indexes = $QTDIR/doc/html/qt.index
\endcode
@@ -1386,7 +1472,7 @@
The project's name is used to form a file name for the associated
project's \e index file.
- \code
+ \badcode
project = QtCreator
\endcode
@@ -1406,7 +1492,7 @@
the base URL when constructing links to classes, functions, and
other things listed in the index.
- \code
+ \badcode
project = Qt
description = Qt Reference Documentation
url = http://doc.qt.io/qt-4.8/
@@ -1429,7 +1515,7 @@
For example, \l qtgui.qdocconf (the configuration file for Qt)
contains the following variable definitions:
- \code
+ \badcode
project = Qt
description = Qt Reference Documentation
url = http://doc.qt.io/qt-4.8/
@@ -1461,7 +1547,7 @@
A manifest file has the following structure:
- \code
+ \badcode
<?xml version="1.0" encoding="UTF-8"?>
<instructionals module="QtGui">
<examples>
@@ -1503,7 +1589,7 @@
Example:
- \code
+ \badcode
manifestmeta.filters = highlighted sql webkit global
manifestmeta.highlighted.names = "QtGui/Analog Clock Window Example" \
@@ -1539,7 +1625,7 @@
In your configuration file, set your \c {outputformats} variable
to \c {DITAXML}, and send the output to an appropriate directory:
- \code
+ \badcode
outputdir = $QTDIR/doc/ditaxml
outputformats = DITAXML
\endcode
@@ -1547,7 +1633,7 @@
And include these macros in your configuration file to prevent
QDoc from doing some escaping that doesn't validate in XML:
- \code
+ \badcode
macro.aacute.DITAXML = "&aacute;"
macro.Aring.DITAXML = "&Aring;"
macro.aring.DITAXML = "&aring;"
@@ -1571,7 +1657,7 @@
You can also set default values for some of the tags in the DITA
\c {<prolog>} and \c {<metadata>} elements:
- \code
+ \badcode
dita.metadata.default.author = Qt Development Frameworks
dita.metadata.default.permissions = all
dita.metadata.default.publisher = Qt Project
diff --git a/src/tools/qdoc/doc/qdoc-manual-topiccmds.qdoc b/src/tools/qdoc/doc/qdoc-manual-topiccmds.qdoc
index f5351b851c..306fc40cb8 100644
--- a/src/tools/qdoc/doc/qdoc-manual-topiccmds.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual-topiccmds.qdoc
@@ -851,6 +851,9 @@
\endquotation
+ The \l {noautolist-command} {\\noautolist} command can be used here
+ to omit the automatically generated list of classes at the end.
+
See also \l {inmodule-command} {\\inmodule}
\target namespace-command
@@ -1372,6 +1375,9 @@
The \l{componentset}{UIComponents} example demonstrates proper usage of
QDoc commands to document QML types and QML modules.
+ The \l {noautolist-command} {\\noautolist} command can be used here
+ to omit the automatically generated list of types at the end.
+
\target instantiates-command
\section1 \\instantiates
diff --git a/src/tools/qdoc/doc/qdoc-manual.qdoc b/src/tools/qdoc/doc/qdoc-manual.qdoc
index c0a1afaa52..a0e35c2e9c 100644
--- a/src/tools/qdoc/doc/qdoc-manual.qdoc
+++ b/src/tools/qdoc/doc/qdoc-manual.qdoc
@@ -39,7 +39,7 @@
\li \l {Context Commands}
\list
\li \l {Document Navigation}
- \li \l {Reporting Status}
+ \li \l {Status}
\li \l {Thread Support}
\li \l {Relating Things}
\li \l {Grouping Things}
diff --git a/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc b/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc
index 77d252b24c..66ceed4a3d 100644
--- a/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc
+++ b/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc
@@ -27,7 +27,7 @@
/*!
\page qdoc-minimum-qdocconf.html
\target minimal-qdocconf
-\title A minimal qdocconf file
+\title A Minimal qdocconf File
\brief Describes a minimal .qdocconf file
@@ -37,8 +37,8 @@ will discuss every statement in the qdocconf file.
Each line from the qdocconf file is first quoted. Below each statement you will
find the meaning.
-\code
- #include(compat.qdocconf)
+\badcode
+ include(compat.qdocconf)
outputdir = html
headerdirs = .
sourcedirs = .
@@ -46,10 +46,10 @@ find the meaning.
imagedirs = ./images
\endcode
-\title Notes
+\b Notes:
-\code
- #include(compat.qdocconf)
+\badcode
+ include(compat.qdocconf)
\endcode
For compatibility with older versions of Qt, it is recommended
@@ -61,32 +61,29 @@ to include compat.qdocconf.
QDoc will put the documentation generated in the html directory.
-\code
+\badcode
headerdirs = .
\endcode
The header file associated with the \e .cpp source files can be found in the
current directory.
-\code
+\badcode
sourcedirs = .
\endcode
The current directory is the directory containing the source files: the \e .cpp
and \e .qdoc files used in the documentation.
-\code
+\badcode
exampledirs = .
\endcode
The source code of the example files can be found in the current directory.
-\code
+\badcode
imagedirs = ./images
\endcode
-The image files can be found in the underlying directory "images".
-
-\note Please take care with this minimal qdocconf file. Using it in the wrong directory
-could cause qdoc to include a large number of files.
+The image files can be found in the underlying directory \c images.
*/
diff --git a/src/tools/qdoc/doc/qtgui-qdocconf.qdoc b/src/tools/qdoc/doc/qtgui-qdocconf.qdoc
index 3dcd2482d6..d90584ff42 100644
--- a/src/tools/qdoc/doc/qtgui-qdocconf.qdoc
+++ b/src/tools/qdoc/doc/qtgui-qdocconf.qdoc
@@ -30,20 +30,20 @@
\page qtgui-qdocconf.html
\title qtgui.qdocconf with Comments
-\brief A walkthrough of a typical qdocconf file
+\brief A walkthrough of a typical qdocconf file.
This document goes through a typical Qt 5 qdocconf file. The contents is taken from
Qt GUI's \e qtgui.qdocconf file.
-Below you will find the full contents of qtgui.qdocconf. The subsequent section will discuss
+Below you will find the full contents of \c qtgui.qdocconf. The subsequent section will discuss
every statement in the qdocconf file.
-\code
+\badcode
include($QT_INSTALL_DOCS/global/qt-module-defaults.qdocconf)
project = QtGui
description = Qt GUI Reference Documentation
- url = http://doc.qt.io/qt-$QT_VER/qtgui-index.html
+ url = http://doc.qt.io/qt-5
version = $QT_VERSION
examplesinstallpath = gui
@@ -95,20 +95,20 @@ every statement in the qdocconf file.
\title Qtgui.qdocconf with notes
-\code
+\badcode
include($QT_INSTALL_DOCS/global/qt-module-defaults.qdocconf)
\endcode
QDoc inherits the default templates, macros, and settings from the directory
specified from the \c $QT_INSTALL_DOCS variable. \c qmake prints the value of
the variable.
-\code
+\badcode
qmake -query
\endcode
-\sa include
+\b {See also}: \l {include}.
-\code
+\badcode
project = QtGui
\endcode
@@ -116,22 +116,22 @@ The \c project variable sets the name of the QDoc build. This name is also
used to form the index file, which, in this case, will be \e qtgui.index. The
name of the index file doesn't adopt the uppercase letters of the project name.
-\sa project
+\b {See also}: \l {project}.
-\code
+\badcode
description = Qt GUI Reference Documentation
\endcode
A short description of the project concerned.
-\code
- url = http://doc.qt.io/qt-$QT_VER/qtgui-index.html
+\badcode
+ url = http://doc.qt.io/qt-5
\endcode
The \c url variable holds the base url of the project.
The URL is stored in the generated index file for the project.
-QDoc will use this as the base URL when constructing links
+QDoc will use this as the base URL when constructing external links
to content listed in the index.
\note QDoc omits this value when the -installdir argument
@@ -139,27 +139,29 @@ is specified when running QDoc.
\keyword examplesinstallpath
-\code
+\badcode
examplesinstallpath = gui
\endcode
-This \e examplesinstallpath variable indicates that the examples will be installed
-in the \e gui directory under the parent examples directory (for Qt, this is
-$QT_INSTALL_EXAMPLES).
+This \c examplesinstallpath variable indicates that the examples will be
+installed in the \e gui directory under the parent examples directory
+(for Qt, this is $QT_INSTALL_EXAMPLES).
-\note The examplepath variable has to match the example directory specified in exampledirs.
-\sa exampledirs
+\note The examplepath variable has to match the example directory specified in
+ \c exampledirs.
-\code
+\b {See also}: \l {exampledirs}.
+
+\badcode
qhp.projects = QtGui
qhp.QtGui.file = qtgui.qhp
\endcode
-The following parameters are for creating a QHP file (\e .qhp). The qhelpgenerator
-program can convert the QHP file into a QCH file (\e .qch), which can be opened in
-Qt Assistant or Qt Creator.
+The following parameters are for creating a QHP file (\e .qhp). The
+\e qhelpgenerator program can convert the QHP file into a QCH file (\e .qch),
+which can be opened in Qt Assistant or Qt Creator.
-\code
+\badcode
qhp.QtGui.namespace = org.qt-project.qtgui.$QT_VERSION_TAG
\endcode
@@ -167,32 +169,32 @@ A unique identifier which enables QHelpEngine to retrieve the helpfile
from a given link. This namespace is also used as a base url for links
to the helpfile.
-\code
+\badcode
qhp.QtGui.virtualFolder = qtgui
\endcode
Virtual folders group documentation together into a single location. A
-virtual folder will become the root directory of all files referenced in a
-compressed help file.
+virtual folder will become the root directory of all files referenced in
+a compressed help file.
-When two manuals are located in the same virtual folder, it is possible to refer
- to sections of the other manual using relative paths.
-The virtual folder tag is mandatory and the folder must not contain any '/'.
+When two manuals are located in the same virtual folder, it is possible to
+refer to sections of the other manual using relative paths. The virtual
+folder tag is mandatory and the folder must not contain any '/'.
-\code
- qhp.QtGui.indexTitle = Qt GUI the title of the page that has the contents
+\badcode
+ qhp.QtGui.indexTitle = Qt GUI
\endcode
This is the title of the page that has the contents.
-\code
- qhp.QtGui.indexRoot = to be checked
+\badcode
+ qhp.QtGui.indexRoot =
\endcode
Specifies the title of the root (namespace) page to generate the documentation for.
Typically defined as an empty string.
-\code
+\badcode
qhp.QtGui.filterAttributes = qtgui $QT_VERSION qtrefdoc
qhp.QtGui.customFilters.Qt.name = QtGui $QT_VERSION
qhp.QtGui.customFilters.Qt.filterAttributes = qtgui $QT_VERSION
@@ -206,7 +208,7 @@ filter in its \gui{Filtered by} drop-down list. Only the documentation sets
that have their filter attributes match the attributes of the selected
custom filter will be shown.
-\code
+\badcode
qhp.QtGui.subprojects = classes
qhp.QtGui.subprojects.classes.title = C++ Classes
qhp.QtGui.subprojects.classes.indexTitle = Qt GUI C++ Classes
@@ -216,34 +218,22 @@ for this project. In this example, the subproject, which is displayed in
the Assistant's sidebar, is named "C++ Classes" and its index is the page
titled "QT GUI C++ Classes".
-\code
+\badcode
qhp.QtGui.subprojects.classes.selectors = class fake:headerfile
\endcode
-Lists all headerfiles.
-
-A ‘fake’ type specifies a generic documentation node, and is followed by
-a c\ : and a \e subtype specifier.
-
-Possible values:
-\code
- example
- headerfile
- file
- group
- module
- page
- externalpage
- qmlclass
- qmlpropertygroup
- qmlbasictype
+Lists all C++ classes and header files.
+
+See \l {Creating Help Project Files} for more information.
+
+\badcode
+ tagfile = ../../../doc/qtgui/qtgui.tags
\endcode
-tagfile = ../../../doc/qtgui/qtgui.tags
This specifies the Doxygen tag file that needs to be written when the html is generated
by QDoc.
-\code
+\badcode
depends += \
qtcore \
qtnetwork \
@@ -259,14 +249,14 @@ Specifies the modules QDoc needs to load for generating output for Qt GUI.
QDoc loads the index files for all modules listed in the depends statement in
order to enable linking to pages in these modules.
-\code
+\badcode
headerdirs += ..
\endcode
Add the parent directory to the list of directories containing the header files
associated with the \e .cpp source files.
-\code
+\badcode
sourcedirs += .. \
../../../examples/gui/doc/src
\endcode
@@ -274,7 +264,7 @@ associated with the \e .cpp source files.
Add the specified directories to the list of directories containing the \e .cpp and
\e .qdoc files used in the documentation.
-\code
+\badcode
excludedirs = ../../../examples/gui/doc/src/tmp
\endcode
@@ -283,14 +273,13 @@ by qdoc, even if the same directories are included by the \c sourcedirs or \c he
variables.
When executed, QDoc will ignore the directories listed.
-\sa excludefiles
+\b {See also}: \l {excludefiles}.
-\code
+\badcode
exampledirs += ../../../examples/gui \
snippets
\endcode
-\sa {examples-variable}{examples}
-\sa examplesinstallpath
+\b {See also}: \l {examples-variable}{examples}, \l {examplesinstallpath}.
Add the two directories specified to the list of directories containing the source
code of the example files.
@@ -299,7 +288,7 @@ If QDoc encounters both \c exampledirs and \c examples, it will look first in th
\c examples directory. QDoc will accept the first matching file it finds. QDoc will
search in the directories specified, not in their subdirectories.
-\code
+\badcode
imagedirs += images \
../../../examples/gui/doc/images \
../../../doc/src/images \
diff --git a/src/tools/qdoc/generator.cpp b/src/tools/qdoc/generator.cpp
index 7f0d4b48b9..dc731f0121 100644
--- a/src/tools/qdoc/generator.cpp
+++ b/src/tools/qdoc/generator.cpp
@@ -63,6 +63,7 @@ QString Generator::outSubdir_;
QStringList Generator::outFileNames_;
QSet<QString> Generator::outputFormats;
QHash<QString, QString> Generator::outputPrefixes;
+QHash<QString, QString> Generator::outputSuffixes;
QString Generator::project_;
QStringList Generator::scriptDirs;
QStringList Generator::scriptFiles;
@@ -259,7 +260,7 @@ void Generator::writeOutFileNames()
Attaches a QTextStream to the created file, which is written
to all over the place using out().
*/
-void Generator::beginSubPage(const InnerNode* node, const QString& fileName)
+void Generator::beginSubPage(const Aggregate* node, const QString& fileName)
{
QString path = outputDir() + QLatin1Char('/');
if (Generator::useOutputSubdirs() && !node->outputSubdirectory().isEmpty() &&
@@ -281,7 +282,7 @@ void Generator::beginSubPage(const InnerNode* node, const QString& fileName)
out->setCodec(outputCodec);
#endif
outStreamStack.push(out);
- const_cast<InnerNode*>(node)->setOutputFileName(fileName);
+ const_cast<Aggregate*>(node)->setOutputFileName(fileName);
}
/*!
@@ -300,7 +301,7 @@ QString Generator::fileBase(const Node *node) const
{
if (node->relates())
node = node->relates();
- else if (!node->isInnerNode())
+ else if (!node->isAggregate())
node = node->parent();
if (node->type() == Node::QmlPropertyGroup) {
node = node->parent();
@@ -329,21 +330,21 @@ QString Generator::fileBase(const Node *node) const
else if (node->isQmlType() || node->isQmlBasicType() ||
node->isJsType() || node->isJsBasicType()) {
base = node->name();
- if (!node->logicalModuleName().isEmpty()) {
- base.prepend(node->logicalModuleName() + QLatin1Char('-'));
- }
/*
To avoid file name conflicts in the html directory,
- we prepend a prefix (by default, "qml-") to the file name of QML
- element doc files.
+ we prepend a prefix (by default, "qml-") and an optional suffix
+ to the file name. The suffix, if one exists, is appended to the
+ module name.
*/
- if (node->isQmlType() || node->isQmlBasicType())
- base.prepend(outputPrefix(QLatin1String("QML")));
- else
- base.prepend(outputPrefix(QLatin1String("JS")));
+ if (!node->logicalModuleName().isEmpty()) {
+ base.prepend(node->logicalModuleName()
+ + outputSuffix(node)
+ + QLatin1Char('-'));
+ }
+ base.prepend(outputPrefix(node));
}
else if (node->isCollectionNode()) {
- base = node->name();
+ base = node->name() + outputSuffix(node);
if (base.endsWith(".html"))
base.truncate(base.length() - 5);
@@ -356,7 +357,7 @@ QString Generator::fileBase(const Node *node) const
else if (node->isModule()) {
base.append("-module");
}
- // Why not add "-group" for gropup pages?
+ // Why not add "-group" for group pages?
}
else {
const Node *p = node;
@@ -519,9 +520,7 @@ QString Generator::fullDocumentLocation(const Node *node, bool useSubdir)
else if (node->isQmlType() || node->isQmlBasicType() ||
node->isJsType() || node->isJsBasicType()) {
QString fb = fileBase(node);
- if (fb.startsWith(Generator::outputPrefix(QLatin1String("QML"))))
- return fb + QLatin1Char('.') + currentGenerator()->fileExtension();
- else if (fb.startsWith(Generator::outputPrefix(QLatin1String("JS"))))
+ if (fb.startsWith(outputPrefix(node)))
return fb + QLatin1Char('.') + currentGenerator()->fileExtension();
else {
QString mq;
@@ -529,10 +528,7 @@ QString Generator::fullDocumentLocation(const Node *node, bool useSubdir)
mq = node->logicalModuleName().replace(QChar('.'),QChar('-'));
mq = mq.toLower() + QLatin1Char('-');
}
- QLatin1String prefix = QLatin1String("QML");
- if (node->isJsType() || node->isJsBasicType())
- prefix = QLatin1String("JS");
- return fdl+ Generator::outputPrefix(prefix) + mq + fileBase(node) +
+ return fdl + outputPrefix(node) + mq + fileBase(node) +
QLatin1Char('.') + currentGenerator()->fileExtension();
}
}
@@ -564,20 +560,19 @@ QString Generator::fullDocumentLocation(const Node *node, bool useSubdir)
break;
case Node::Function:
{
- const FunctionNode *functionNode =
- static_cast<const FunctionNode *>(node);
+ const FunctionNode *fn = static_cast<const FunctionNode *>(node);
- if (functionNode->metaness() == FunctionNode::Dtor)
- anchorRef = "#dtor." + functionNode->name().mid(1);
+ if (fn->metaness() == FunctionNode::Dtor)
+ anchorRef = "#dtor." + fn->name().mid(1);
- else if (functionNode->associatedProperty())
- return fullDocumentLocation(functionNode->associatedProperty());
+ else if (fn->hasOneAssociatedProperty() && fn->doc().isEmpty())
+ return fullDocumentLocation(fn->firstAssociatedProperty());
- else if (functionNode->overloadNumber() > 1)
- anchorRef = QLatin1Char('#') + cleanRef(functionNode->name())
- + QLatin1Char('-') + QString::number(functionNode->overloadNumber());
+ else if (fn->overloadNumber() > 0)
+ anchorRef = QLatin1Char('#') + cleanRef(fn->name())
+ + QLatin1Char('-') + QString::number(fn->overloadNumber());
else
- anchorRef = QLatin1Char('#') + cleanRef(functionNode->name());
+ anchorRef = QLatin1Char('#') + cleanRef(fn->name());
break;
}
/*
@@ -750,12 +745,12 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
if (node->type() == Node::Document) {
const DocumentNode *dn = static_cast<const DocumentNode *>(node);
- if ((dn->subType() == Node::File) || (dn->subType() == Node::Image)) {
+ if ((dn->docSubtype() == Node::File) || (dn->docSubtype() == Node::Image)) {
quiet = true;
}
}
if (node->doc().isEmpty()) {
- if (!node->isWrapper() && !quiet && !node->isReimp()) { // ### might be unnecessary
+ if (!node->isWrapper() && !quiet && !node->isReimplemented()) { // ### might be unnecessary
node->location().warning(tr("No documentation for '%1'").arg(node->plainFullName()));
}
}
@@ -767,7 +762,7 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
}
if (!generateText(node->doc().body(), node, marker)) {
- if (node->isReimp())
+ if (node->isReimplemented())
return;
}
@@ -809,9 +804,10 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
else if (node->type() == Node::Function) {
const FunctionNode *func = static_cast<const FunctionNode *>(node);
QSet<QString> definedParams;
- QList<Parameter>::ConstIterator p = func->parameters().constBegin();
+ QVector<Parameter>::ConstIterator p = func->parameters().constBegin();
while (p != func->parameters().constEnd()) {
- if ((*p).name().isEmpty() && (*p).leftType() != QLatin1String("...")
+ if ((*p).name().isEmpty() && (*p).dataType() != QLatin1String("...")
+ && (*p).dataType() != QLatin1String("void")
&& func->name() != QLatin1String("operator++")
&& func->name() != QLatin1String("operator--")) {
node->doc().location().warning(tr("Missing parameter name"));
@@ -840,9 +836,8 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
}
else if (!(*a).isEmpty() && !documentedParams.contains(*a)) {
bool needWarning = (func->status() > Node::Obsolete);
- if (func->overloadNumber() > 1) {
- FunctionNode *primaryFunc =
- func->parent()->findFunctionNode(func->name());
+ if (func->overloadNumber() > 0) {
+ FunctionNode *primaryFunc = func->parent()->findFunctionNode(func->name(), QString());
if (primaryFunc) {
foreach (const Parameter &param,
primaryFunc->parameters()) {
@@ -853,7 +848,7 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
}
}
}
- if (needWarning && !func->isReimp())
+ if (needWarning && !func->isReimplemented())
node->doc().location().warning(
tr("Undocumented parameter '%1' in %2")
.arg(*a).arg(node->plainFullName()));
@@ -879,7 +874,7 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
if (dn->isExample()) {
generateExampleFiles(dn, marker);
}
- else if (dn->subType() == Node::File) {
+ else if (dn->docSubtype() == Node::File) {
Text text;
Quoter quoter;
Doc::quoteFromFile(dn->doc().location(), quoter, dn->name());
@@ -891,7 +886,7 @@ void Generator::generateBody(const Node *node, CodeMarker *marker)
}
}
-void Generator::generateClassLikeNode(InnerNode* /* classe */, CodeMarker* /* marker */)
+void Generator::generateClassLikeNode(Aggregate* /* classe */, CodeMarker* /* marker */)
{
}
@@ -920,7 +915,7 @@ void Generator::generateCollectionNode(CollectionNode* , CodeMarker* )
*/
void Generator::generateFileList(const DocumentNode* dn,
CodeMarker* marker,
- Node::SubType subtype,
+ Node::DocSubtype subtype,
const QString& tag)
{
int count = 0;
@@ -931,7 +926,7 @@ void Generator::generateFileList(const DocumentNode* dn,
<< Atom(Atom::ListLeft, openedList.styleString());
foreach (const Node* child, dn->childNodes()) {
- if (child->subType() == subtype) {
+ if (child->docSubtype() == subtype) {
++count;
QString file = child->name();
if (subtype == Node::Image) {
@@ -947,16 +942,10 @@ void Generator::generateFileList(const DocumentNode* dn,
userFriendlyFilePath);
outFileNames_ << prefix.mid(1) + userFriendlyFilePath;
userFriendlyFilePath.truncate(userFriendlyFilePath.lastIndexOf('/'));
-
QString imgOutDir = outDir_ + prefix + userFriendlyFilePath;
if (!dirInfo.mkpath(imgOutDir))
- dn->location().fatal(tr("Cannot create output directory '%1'")
- .arg(imgOutDir));
-
- QString imgOutName = Config::copyFile(dn->location(),
- srcPath,
- file,
- imgOutDir);
+ dn->location().fatal(tr("Cannot create output directory '%1'").arg(imgOutDir));
+ Config::copyFile(dn->location(), srcPath, file, imgOutDir);
}
}
@@ -1032,7 +1021,7 @@ void Generator::generateInherits(const ClassNode *classe, CodeMarker *marker)
/*!
Recursive writing of HTML files from the root \a node.
*/
-void Generator::generateInnerNode(InnerNode* node)
+void Generator::generateAggregate(Aggregate* node)
{
if (!node->url().isNull())
return;
@@ -1043,11 +1032,11 @@ void Generator::generateInnerNode(InnerNode* node)
if (node->isDocumentNode()) {
DocumentNode* docNode = static_cast<DocumentNode*>(node);
- if (docNode->subType() == Node::ExternalPage)
+ if (docNode->docSubtype() == Node::ExternalPage)
return;
- if (docNode->subType() == Node::Image)
+ if (docNode->docSubtype() == Node::Image)
return;
- if (docNode->subType() == Node::Page) {
+ if (docNode->docSubtype() == Node::Page) {
if (node->count() > 0)
qDebug("PAGE %s HAS CHILDREN", qPrintable(docNode->title()));
}
@@ -1117,8 +1106,8 @@ void Generator::generateInnerNode(InnerNode* node)
int i = 0;
while (i < node->childNodes().count()) {
Node *c = node->childNodes().at(i);
- if (c->isInnerNode() && c->access() != Node::Private) {
- generateInnerNode((InnerNode*)c);
+ if (c->isAggregate() && c->access() != Node::Private) {
+ generateAggregate((Aggregate*)c);
}
++i;
}
@@ -1127,7 +1116,7 @@ void Generator::generateInnerNode(InnerNode* node)
/*!
Generate a list of maintainers in the output
*/
-void Generator::generateMaintainerList(const InnerNode* node, CodeMarker* marker)
+void Generator::generateMaintainerList(const Aggregate* node, CodeMarker* marker)
{
QStringList sl = getMetadataElements(node,"maintainer");
@@ -1252,7 +1241,8 @@ void Generator::generateStatus(const Node *node, CodeMarker *marker)
Text text;
switch (node->status()) {
- case Node::Commendable:
+ case Node::Active:
+ // Do nothing.
break;
case Node::Preliminary:
text << Atom::ParaLeft
@@ -1265,19 +1255,19 @@ void Generator::generateStatus(const Node *node, CodeMarker *marker)
break;
case Node::Deprecated:
text << Atom::ParaLeft;
- if (node->isInnerNode())
+ if (node->isAggregate())
text << Atom(Atom::FormattingLeft, ATOM_FORMATTING_BOLD);
text << "This " << typeString(node) << " is deprecated.";
- if (node->isInnerNode())
+ if (node->isAggregate())
text << Atom(Atom::FormattingRight, ATOM_FORMATTING_BOLD);
text << Atom::ParaRight;
break;
case Node::Obsolete:
text << Atom::ParaLeft;
- if (node->isInnerNode())
+ if (node->isAggregate())
text << Atom(Atom::FormattingLeft, ATOM_FORMATTING_BOLD);
text << "This " << typeString(node) << " is obsolete.";
- if (node->isInnerNode())
+ if (node->isAggregate())
text << Atom(Atom::FormattingRight, ATOM_FORMATTING_BOLD);
text << " It is provided to keep old source code working. "
<< "We strongly advise against "
@@ -1285,7 +1275,7 @@ void Generator::generateStatus(const Node *node, CodeMarker *marker)
break;
case Node::Compat:
// reimplemented in HtmlGenerator subclass
- if (node->isInnerNode()) {
+ if (node->isAggregate()) {
text << Atom::ParaLeft
<< Atom(Atom::FormattingLeft, ATOM_FORMATTING_BOLD)
<< "This "
@@ -1384,8 +1374,8 @@ void Generator::generateThreadSafeness(const Node *node, CodeMarker *marker)
<< Atom(Atom::FormattingRight,ATOM_FORMATTING_BOLD)
<< " ";
- if (node->isInnerNode()) {
- const InnerNode* innerNode = static_cast<const InnerNode*>(node);
+ if (node->isAggregate()) {
+ const Aggregate* innerNode = static_cast<const Aggregate*>(node);
text << "All functions in this "
<< typeString(node)
<< " are ";
@@ -1485,11 +1475,80 @@ void Generator::generateThreadSafeness(const Node *node, CodeMarker *marker)
}
/*!
- Traverses the current tree to generate all the documentation.
+ If the node is an overloaded signal, and a node with an example on how to connect to it
+ */
+void Generator::generateOverloadedSignal(const Node* node, CodeMarker* marker)
+{
+ if (node->type() != Node::Function)
+ return;
+ const FunctionNode *func = static_cast<const FunctionNode *>(node);
+ if (func->metaness() != FunctionNode::Signal)
+ return;
+ if (node->parent()->overloads(node->name()).count() <= 1)
+ return;
+
+
+ // Compute a friendly name for the object of that instance.
+ // e.g: "QAbstractSocket" -> "abstractSocket"
+ QString objectName = node->parent()->name();
+ if (objectName.size() >= 2) {
+ if (objectName[0] == 'Q')
+ objectName = objectName.mid(1);
+ objectName[0] = objectName[0].toLower();
+ }
+
+
+ // We have an overloaded signal, show an example
+ QString code = "connect(" + objectName + ", static_cast<" + func->returnType()
+ + "(" + func->parent()->name() + "::*)(";
+ for (int i = 0; i < func->parameters().size(); ++i) {
+ if (i != 0)
+ code += ", ";
+ const Parameter &p = func->parameters().at(i);
+ code += p.dataType() + p.rightType();
+ }
+
+ code += ")";
+ if (func->isConst())
+ code += " const";
+ code += ">(&" + func->parent()->name() + "::" + func->name() + "),\n [=](";
+
+ for (int i = 0; i < func->parameters().size(); ++i) {
+ if (i != 0)
+ code += ", ";
+ const Parameter &p = func->parameters().at(i);
+ code += p.dataType();
+ if (code[code.size()-1].isLetterOrNumber())
+ code += " ";
+ code += p.name() + p.rightType();
+ }
+
+ code += "){ /* ... */ });";
+
+ Text text;
+ text << Atom::ParaLeft
+ << Atom(Atom::FormattingLeft,ATOM_FORMATTING_BOLD)
+ << "Note:"
+ << Atom(Atom::FormattingRight,ATOM_FORMATTING_BOLD)
+ << "Signal "
+ << Atom(Atom::FormattingLeft,ATOM_FORMATTING_ITALIC)
+ << node->name()
+ << Atom(Atom::FormattingRight,ATOM_FORMATTING_ITALIC)
+ << " is overloaded in this class. "
+ "To connect to this one using the function pointer syntax, you must "
+ "specify the signal type in a static cast, as shown in this example:"
+ << Atom(Atom::Code, marker->markedUpCode(code, node, func->location()));
+
+ generateText(text, node, marker);
+}
+
+
+/*!
+ Traverses the database recursivly to generate all the documentation.
*/
void Generator::generateDocs()
{
- generateInnerNode(qdb_->primaryTreeRoot());
+ generateAggregate(qdb_->primaryTreeRoot());
}
Generator *Generator::generatorForFormat(const QString& format)
@@ -1512,7 +1571,7 @@ Generator *Generator::generatorForFormat(const QString& format)
i.e. Once you call this function for a particular \a t,
you consume \a t.
*/
-QString Generator::getMetadataElement(const InnerNode* inner, const QString& t)
+QString Generator::getMetadataElement(const Aggregate* inner, const QString& t)
{
QString s;
QStringMultiMap& metaTagMap = const_cast<QStringMultiMap&>(inner->doc().metaTagMap());
@@ -1533,7 +1592,7 @@ QString Generator::getMetadataElement(const InnerNode* inner, const QString& t)
having the key \a t are erased. i.e. Once you call this
function for a particular \a t, you consume \a t.
*/
-QStringList Generator::getMetadataElements(const InnerNode* inner, const QString& t)
+QStringList Generator::getMetadataElements(const Aggregate* inner, const QString& t)
{
QStringList s;
QStringMultiMap& metaTagMap = const_cast<QStringMultiMap&>(inner->doc().metaTagMap());
@@ -1628,12 +1687,6 @@ void Generator::initialize(const Config &config)
if (!dirInfo.exists(outDir_ + "/images") && !dirInfo.mkdir(outDir_ + "/images"))
config.lastLocation().fatal(tr("Cannot create images directory '%1'").arg(outDir_ + "/images"));
- if (!dirInfo.exists(outDir_ + "/images/used-in-examples") && !dirInfo.mkdir(outDir_ + "/images/used-in-examples"))
- config.lastLocation().fatal(tr("Cannot create images used in examples directory '%1'").arg(outDir_ + "/images/used-in-examples"));
- if (!dirInfo.exists(outDir_ + "/scripts") && !dirInfo.mkdir(outDir_ + "/scripts"))
- config.lastLocation().fatal(tr("Cannot create scripts directory '%1'").arg(outDir_ + "/scripts"));
- if (!dirInfo.exists(outDir_ + "/style") && !dirInfo.mkdir(outDir_ + "/style"))
- config.lastLocation().fatal(tr("Cannot create style directory '%1'").arg(outDir_ + "/style"));
}
imageFiles = config.getCanonicalPathList(CONFIG_IMAGES);
@@ -1672,23 +1725,41 @@ void Generator::initialize(const Config &config)
// Documentation template handling
QStringList scripts = config.getCanonicalPathList((*g)->format()+Config::dot+CONFIG_SCRIPTS, true);
- e = scripts.constBegin();
- while (e != scripts.constEnd()) {
- QString filePath = *e;
- if (!filePath.isEmpty())
- Config::copyFile(config.lastLocation(), filePath, filePath,
- (*g)->outputDir() + "/scripts");
- ++e;
+ if (!scripts.isEmpty()) {
+ QDir dirInfo;
+ if (!dirInfo.exists(outDir_ + "/scripts") && !dirInfo.mkdir(outDir_ + "/scripts")) {
+ config.lastLocation().fatal(tr("Cannot create scripts directory '%1'")
+ .arg(outDir_ + "/scripts"));
+ }
+ else {
+ e = scripts.constBegin();
+ while (e != scripts.constEnd()) {
+ QString filePath = *e;
+ if (!filePath.isEmpty())
+ Config::copyFile(config.lastLocation(), filePath, filePath,
+ (*g)->outputDir() + "/scripts");
+ ++e;
+ }
+ }
}
QStringList styles = config.getCanonicalPathList((*g)->format()+Config::dot+CONFIG_STYLESHEETS, true);
- e = styles.constBegin();
- while (e != styles.constEnd()) {
- QString filePath = *e;
- if (!filePath.isEmpty())
- Config::copyFile(config.lastLocation(), filePath, filePath,
- (*g)->outputDir() + "/style");
- ++e;
+ if (!styles.isEmpty()) {
+ QDir dirInfo;
+ if (!dirInfo.exists(outDir_ + "/style") && !dirInfo.mkdir(outDir_ + "/style")) {
+ config.lastLocation().fatal(tr("Cannot create style directory '%1'")
+ .arg(outDir_ + "/style"));
+ }
+ else {
+ e = styles.constBegin();
+ while (e != styles.constEnd()) {
+ QString filePath = *e;
+ if (!filePath.isEmpty())
+ Config::copyFile(config.lastLocation(), filePath, filePath,
+ (*g)->outputDir() + "/style");
+ ++e;
+ }
+ }
}
}
++g;
@@ -1732,15 +1803,24 @@ void Generator::initialize(const Config &config)
project_ = config.getString(CONFIG_PROJECT);
- QStringList prefixes = config.getStringList(CONFIG_OUTPUTPREFIXES);
- if (!prefixes.isEmpty()) {
- foreach (const QString &prefix, prefixes)
+ outputPrefixes.clear();
+ QStringList items = config.getStringList(CONFIG_OUTPUTPREFIXES);
+ if (!items.isEmpty()) {
+ foreach (const QString &prefix, items)
outputPrefixes[prefix] = config.getString(CONFIG_OUTPUTPREFIXES + Config::dot + prefix);
}
else {
outputPrefixes[QLatin1String("QML")] = QLatin1String("qml-");
outputPrefixes[QLatin1String("JS")] = QLatin1String("js-");
}
+
+ outputSuffixes.clear();
+ items = config.getStringList(CONFIG_OUTPUTSUFFIXES);
+ if (!items.isEmpty()) {
+ foreach (const QString &suffix, items)
+ outputSuffixes[suffix] = config.getString(CONFIG_OUTPUTSUFFIXES + Config::dot + suffix);
+ }
+
noLinkErrors_ = config.getBool(CONFIG_NOLINKERRORS);
autolinkErrors_ = config.getBool(CONFIG_AUTOLINKERRORS);
}
@@ -1770,7 +1850,7 @@ void Generator::initializeGenerator(const Config& config)
singleExec_ = config.getBool(CONFIG_SINGLEEXEC);
}
-bool Generator::matchAhead(const Atom *atom, Atom::Type expectedAtomType)
+bool Generator::matchAhead(const Atom *atom, Atom::AtomType expectedAtomType)
{
return atom->next() != 0 && atom->next()->type() == expectedAtomType;
}
@@ -1790,9 +1870,25 @@ QString Generator::outFileName()
return QFileInfo(static_cast<QFile*>(out().device())->fileName()).fileName();
}
-QString Generator::outputPrefix(const QString &nodeType)
+QString Generator::outputPrefix(const Node *node)
+{
+ // Prefix is applied to QML and JS types
+ if (node->isQmlType() || node->isQmlBasicType())
+ return outputPrefixes[QLatin1String("QML")];
+ if (node->isJsType() || node->isJsBasicType())
+ return outputPrefixes[QLatin1String("JS")];
+ return QString();
+}
+
+QString Generator::outputSuffix(const Node *node)
{
- return outputPrefixes[nodeType];
+ // Suffix is applied to QML and JS types, as
+ // well as module pages.
+ if (node->isQmlModule() || node->isQmlType() || node->isQmlBasicType())
+ return outputSuffixes[QLatin1String("QML")];
+ if (node->isJsModule() || node->isJsType() || node->isJsBasicType())
+ return outputSuffixes[QLatin1String("JS")];
+ return QString();
}
bool Generator::parseArg(const QString& src,
@@ -1917,7 +2013,7 @@ void Generator::singularPlural(Text& text, const NodeList& nodes)
text << " are";
}
-int Generator::skipAtoms(const Atom *atom, Atom::Type type) const
+int Generator::skipAtoms(const Atom *atom, Atom::AtomType type) const
{
int skipAhead = 0;
atom = atom->next();
@@ -1947,21 +2043,21 @@ void Generator::supplementAlsoList(const Node *node, QList<Text> &alsoList)
{
if (node->type() == Node::Function) {
const FunctionNode *func = static_cast<const FunctionNode *>(node);
- if (func->overloadNumber() == 1) {
+ if (func->overloadNumber() == 0) {
QString alternateName;
const FunctionNode *alternateFunc = 0;
if (func->name().startsWith("set") && func->name().size() >= 4) {
alternateName = func->name()[3].toLower();
alternateName += func->name().mid(4);
- alternateFunc = func->parent()->findFunctionNode(alternateName);
+ alternateFunc = func->parent()->findFunctionNode(alternateName, QString());
if (!alternateFunc) {
alternateName = "is" + func->name().mid(3);
- alternateFunc = func->parent()->findFunctionNode(alternateName);
+ alternateFunc = func->parent()->findFunctionNode(alternateName, QString());
if (!alternateFunc) {
alternateName = "has" + func->name().mid(3);
- alternateFunc = func->parent()->findFunctionNode(alternateName);
+ alternateFunc = func->parent()->findFunctionNode(alternateName, QString());
}
}
}
@@ -1969,7 +2065,7 @@ void Generator::supplementAlsoList(const Node *node, QList<Text> &alsoList)
alternateName = "set";
alternateName += func->name()[0].toUpper();
alternateName += func->name().mid(1);
- alternateFunc = func->parent()->findFunctionNode(alternateName);
+ alternateFunc = func->parent()->findFunctionNode(alternateName, QString());
}
if (alternateFunc && alternateFunc->access() != Node::Private) {
diff --git a/src/tools/qdoc/generator.h b/src/tools/qdoc/generator.h
index 9a1672dac4..6c44cd189c 100644
--- a/src/tools/qdoc/generator.h
+++ b/src/tools/qdoc/generator.h
@@ -106,7 +106,7 @@ public:
static QString cleanRef(const QString& ref);
protected:
- virtual void beginSubPage(const InnerNode* node, const QString& fileName);
+ virtual void beginSubPage(const Aggregate* node, const QString& fileName);
virtual void endSubPage();
virtual QString fileBase(const Node* node) const;
virtual QString fileExtension() const = 0;
@@ -114,15 +114,15 @@ protected:
virtual void generateAlsoList(const Node *node, CodeMarker *marker);
virtual int generateAtom(const Atom *atom, const Node *relative, CodeMarker *marker);
virtual void generateBody(const Node *node, CodeMarker *marker);
- virtual void generateClassLikeNode(InnerNode* inner, CodeMarker* marker);
+ virtual void generateClassLikeNode(Aggregate* inner, CodeMarker* marker);
virtual void generateQmlTypePage(QmlTypeNode* , CodeMarker* ) { }
virtual void generateQmlBasicTypePage(QmlBasicTypeNode* , CodeMarker* ) { }
virtual void generateDocumentNode(DocumentNode* dn, CodeMarker* marker);
virtual void generateCollectionNode(CollectionNode* cn, CodeMarker* marker);
virtual void generateInheritedBy(const ClassNode *classe, CodeMarker *marker);
virtual void generateInherits(const ClassNode *classe, CodeMarker *marker);
- virtual void generateInnerNode(InnerNode* node);
- virtual void generateMaintainerList(const InnerNode* node, CodeMarker* marker);
+ virtual void generateAggregate(Aggregate* node);
+ virtual void generateMaintainerList(const Aggregate* node, CodeMarker* marker);
virtual void generateQmlInheritedBy(const QmlTypeNode* qcn, CodeMarker* marker);
virtual void generateQmlInherits(QmlTypeNode* qcn, CodeMarker* marker);
virtual bool generateQmlText(const Text& text,
@@ -131,11 +131,12 @@ protected:
const QString& qmlName);
virtual bool generateText(const Text& text, const Node *relative, CodeMarker *marker);
virtual QString imageFileName(const Node *relative, const QString& fileBase);
- virtual int skipAtoms(const Atom *atom, Atom::Type type) const;
+ virtual int skipAtoms(const Atom *atom, Atom::AtomType type) const;
virtual QString typeString(const Node *node);
- static bool matchAhead(const Atom *atom, Atom::Type expectedAtomType);
- static QString outputPrefix(const QString &nodeType);
+ static bool matchAhead(const Atom *atom, Atom::AtomType expectedAtomType);
+ static QString outputPrefix(const Node* node);
+ static QString outputSuffix(const Node* node);
static void singularPlural(Text& text, const NodeList& nodes);
static void supplementAlsoList(const Node *node, QList<Text> &alsoList);
static QString trimmedTrailing(const QString &string);
@@ -153,14 +154,15 @@ protected:
void generateExampleFiles(const DocumentNode *dn, CodeMarker *marker);
void generateFileList(const DocumentNode* dn,
CodeMarker* marker,
- Node::SubType subtype,
+ Node::DocSubtype subtype,
const QString& tag);
void generateSince(const Node *node, CodeMarker *marker);
void generateStatus(const Node *node, CodeMarker *marker);
void generatePrivateSignalNote(const Node* node, CodeMarker* marker);
void generateThreadSafeness(const Node *node, CodeMarker *marker);
- QString getMetadataElement(const InnerNode* inner, const QString& t);
- QStringList getMetadataElements(const InnerNode* inner, const QString& t);
+ QString getMetadataElement(const Aggregate* inner, const QString& t);
+ QStringList getMetadataElements(const Aggregate* inner, const QString& t);
+ void generateOverloadedSignal(const Node *node, CodeMarker *marker);
QString indent(int level, const QString& markedCode);
QTextStream& out();
QString outFileName();
@@ -213,6 +215,7 @@ private:
static QStringList outFileNames_;
static QSet<QString> outputFormats;
static QHash<QString, QString> outputPrefixes;
+ static QHash<QString, QString> outputSuffixes;
static QStringList scriptDirs;
static QStringList scriptFiles;
static QStringList styleDirs;
diff --git a/src/tools/qdoc/helpprojectwriter.cpp b/src/tools/qdoc/helpprojectwriter.cpp
index d00f75e32d..8161913f1f 100644
--- a/src/tools/qdoc/helpprojectwriter.cpp
+++ b/src/tools/qdoc/helpprojectwriter.cpp
@@ -107,13 +107,13 @@ void HelpProjectWriter::reset(const Config &config,
subproject.sortPages = config.getBool(subprefix + "sortPages");
subproject.type = config.getString(subprefix + "type");
readSelectors(subproject, config.getStringList(subprefix + "selectors"));
- project.subprojects[name] = subproject;
+ project.subprojects.append(subproject);
}
if (project.subprojects.isEmpty()) {
SubProject subproject;
readSelectors(subproject, config.getStringList(prefix + "selectors"));
- project.subprojects.insert(QString(), subproject);
+ project.subprojects.insert(0, subproject);
}
projects.append(project);
@@ -122,10 +122,11 @@ void HelpProjectWriter::reset(const Config &config,
void HelpProjectWriter::readSelectors(SubProject &subproject, const QStringList &selectors)
{
- QHash<QString, Node::Type> typeHash;
+ QHash<QString, Node::NodeType> typeHash;
typeHash["namespace"] = Node::Namespace;
typeHash["class"] = Node::Class;
- typeHash["fake"] = Node::Document;
+ typeHash["doc"] = Node::Document;
+ typeHash["fake"] = Node::Document; // Legacy alias for 'doc'
typeHash["enum"] = Node::Enum;
typeHash["typedef"] = Node::Typedef;
typeHash["function"] = Node::Function;
@@ -139,17 +140,18 @@ void HelpProjectWriter::readSelectors(SubProject &subproject, const QStringList
typeHash["qmlsignalhandler"] = Node::QmlSignalHandler;
typeHash["qmlmethod"] = Node::QmlMethod;
typeHash["qmlpropertygroup"] = Node::QmlPropertyGroup;
- typeHash["qmlclass"] = Node::QmlType;
+ typeHash["qmlclass"] = Node::QmlType; // Legacy alias for 'qmltype'
+ typeHash["qmltype"] = Node::QmlType;
typeHash["qmlbasictype"] = Node::QmlBasicType;
- QHash<QString, Node::SubType> subTypeHash;
- subTypeHash["example"] = Node::Example;
- subTypeHash["headerfile"] = Node::HeaderFile;
- subTypeHash["file"] = Node::File;
- subTypeHash["page"] = Node::Page;
- subTypeHash["externalpage"] = Node::ExternalPage;
+ QHash<QString, Node::DocSubtype> docSubtypeHash;
+ docSubtypeHash["example"] = Node::Example;
+ docSubtypeHash["headerfile"] = Node::HeaderFile;
+ docSubtypeHash["file"] = Node::File;
+ docSubtypeHash["page"] = Node::Page;
+ docSubtypeHash["externalpage"] = Node::ExternalPage;
- QSet<Node::SubType> allSubTypes = QSet<Node::SubType>::fromList(subTypeHash.values());
+ QSet<Node::DocSubtype> allSubTypes = QSet<Node::DocSubtype>::fromList(docSubtypeHash.values());
foreach (const QString &selector, selectors) {
QStringList pieces = selector.split(QLatin1Char(':'));
@@ -158,16 +160,20 @@ void HelpProjectWriter::readSelectors(SubProject &subproject, const QStringList
if (typeHash.contains(lower))
subproject.selectors[typeHash[lower]] = allSubTypes;
} else if (pieces.size() >= 2) {
- QString lower = pieces[0].toLower();
+ QString docType = pieces[0].toLower();
pieces = pieces[1].split(QLatin1Char(','));
- if (typeHash.contains(lower)) {
- QSet<Node::SubType> subTypes;
+ if (typeHash.contains(docType)) {
+ QSet<Node::DocSubtype> docSubtypes;
for (int i = 0; i < pieces.size(); ++i) {
- QString lower = pieces[i].toLower();
- if (subTypeHash.contains(lower))
- subTypes.insert(subTypeHash[lower]);
+ QString piece = pieces[i].toLower();
+ if (typeHash[docType] == Node::Group) {
+ subproject.groups << piece;
+ continue;
+ }
+ if (docSubtypeHash.contains(piece))
+ docSubtypes.insert(docSubtypeHash[piece]);
}
- subproject.selectors[typeHash[lower]] = subTypes;
+ subproject.selectors[typeHash[docType]] = docSubtypes;
}
}
}
@@ -243,36 +249,40 @@ bool HelpProjectWriter::generateSection(HelpProject &project,
if (!docPath.isEmpty() && project.excluded.contains(docPath))
return false;
- QString objName;
- if (node->isDocumentNode()) {
- const DocumentNode *fake = static_cast<const DocumentNode *>(node);
- objName = fake->fullTitle();
- }
- else
- objName = node->fullDocumentName();
-
+ QString objName = node->isDocumentNode() ? node->fullTitle() : node->fullDocumentName();
// Only add nodes to the set for each subproject if they match a selector.
// Those that match will be listed in the table of contents.
- foreach (const QString &name, project.subprojects.keys()) {
- SubProject subproject = project.subprojects[name];
+ for (int i = 0; i < project.subprojects.length(); i++) {
+ SubProject subproject = project.subprojects[i];
// No selectors: accept all nodes.
if (subproject.selectors.isEmpty()) {
- project.subprojects[name].nodes[objName] = node;
+ project.subprojects[i].nodes[objName] = node;
}
else if (subproject.selectors.contains(node->type())) {
+ // Add all group members for 'group:name' selector
+ if (node->isGroup()) {
+ if (project.subprojects[i].groups.contains(node->name())) {
+ const CollectionNode* cn = static_cast<const CollectionNode*>(node);
+ foreach (const Node* m, cn->members()) {
+ QString memberName = m->isDocumentNode()
+ ? m->fullTitle() : m->fullDocumentName();
+ project.subprojects[i].nodes[memberName] = m;
+ }
+ }
+ }
// Accept only the node types in the selectors hash.
- if (node->type() != Node::Document)
- project.subprojects[name].nodes[objName] = node;
+ else if (node->type() != Node::Document)
+ project.subprojects[i].nodes[objName] = node;
else {
- // Accept only fake nodes with subtypes contained in the selector's
+ // Accept only doc nodes with subtypes contained in the selector's
// mask.
const DocumentNode *docNode = static_cast<const DocumentNode *>(node);
- if (subproject.selectors[node->type()].contains(docNode->subType()) &&
- docNode->subType() != Node::ExternalPage &&
+ if (subproject.selectors[node->type()].contains(docNode->docSubtype()) &&
+ docNode->docSubtype() != Node::ExternalPage &&
!docNode->fullTitle().isEmpty()) {
- project.subprojects[name].nodes[objName] = node;
+ project.subprojects[i].nodes[objName] = node;
}
}
}
@@ -291,8 +301,7 @@ bool HelpProjectWriter::generateSection(HelpProject &project,
QStringList details;
details << keyword->string()
<< keyword->string()
- << gen_->fullDocumentLocation(node, false) +
- QLatin1Char('#') + Doc::canonicalTitle(keyword->string());
+ << gen_->fullDocumentLocation(node, false);
project.keywords.append(details);
}
else
@@ -341,8 +350,7 @@ bool HelpProjectWriter::generateSection(HelpProject &project,
QStringList details;
details << keyword->string()
<< keyword->string()
- << gen_->fullDocumentLocation(node, false) +
- QLatin1Char('#') + Doc::canonicalTitle(keyword->string());
+ << gen_->fullDocumentLocation(node, false);
project.keywords.append(details);
}
else
@@ -411,19 +419,18 @@ bool HelpProjectWriter::generateSection(HelpProject &project,
// attributes.
case Node::Document: {
const DocumentNode *docNode = static_cast<const DocumentNode*>(node);
- if (docNode->subType() != Node::ExternalPage &&
- docNode->subType() != Node::Image &&
+ if (docNode->docSubtype() != Node::ExternalPage &&
+ docNode->docSubtype() != Node::Image &&
!docNode->fullTitle().isEmpty()) {
- if (docNode->subType() != Node::File) {
+ if (docNode->docSubtype() != Node::File) {
if (docNode->doc().hasKeywords()) {
foreach (const Atom *keyword, docNode->doc().keywords()) {
if (!keyword->string().isEmpty()) {
QStringList details;
details << keyword->string()
<< keyword->string()
- << gen_->fullDocumentLocation(node, false) +
- QLatin1Char('#') + Doc::canonicalTitle(keyword->string());
+ << gen_->fullDocumentLocation(node, false);
project.keywords.append(details);
} else
docNode->doc().location().warning(
@@ -461,13 +468,13 @@ void HelpProjectWriter::generateSections(HelpProject &project,
/*
Don't include index nodes in the help file. Or DITA map nodes.
*/
- if (node->isIndexNode() || node->subType() == Node::DitaMap)
+ if (node->isIndexNode() || node->docSubtype() == Node::DitaMap)
return;
if (!generateSection(project, writer, node))
return;
- if (node->isInnerNode()) {
- const InnerNode *inner = static_cast<const InnerNode *>(node);
+ if (node->isAggregate()) {
+ const Aggregate *inner = static_cast<const Aggregate *>(node);
// Ensure that we don't visit nodes more than once.
QMap<QString, const Node*> childMap;
@@ -491,7 +498,7 @@ void HelpProjectWriter::generateSections(HelpProject &project,
because The Qml/Js Property Group is
an actual documented thing.
*/
- const InnerNode* inner = static_cast<const InnerNode*>(childNode);
+ const Aggregate* inner = static_cast<const Aggregate*>(childNode);
foreach (const Node* n, inner->childNodes()) {
if (n->access() == Node::Private)
continue;
@@ -620,7 +627,7 @@ void HelpProjectWriter::writeNode(HelpProject &project, QXmlStreamWriter &writer
writer.writeAttribute("ref", href);
writer.writeAttribute("title", docNode->fullTitle());
- if (docNode->subType() == Node::HeaderFile)
+ if (docNode->docSubtype() == Node::HeaderFile)
addMembers(project, writer, node);
writer.writeEndElement(); // section
@@ -707,8 +714,8 @@ void HelpProjectWriter::generateProject(HelpProject &project)
generateSections(project, writer, rootNode);
- foreach (const QString &name, project.subprojects.keys()) {
- SubProject subproject = project.subprojects[name];
+ for (int i = 0; i < project.subprojects.length(); i++) {
+ SubProject subproject = project.subprojects[i];
if (subproject.type == QLatin1String("manual")) {
@@ -763,13 +770,12 @@ void HelpProjectWriter::generateProject(HelpProject &project)
} else {
- if (!name.isEmpty()) {
- writer.writeStartElement("section");
- QString indexPath = gen_->fullDocumentLocation(qdb_->findNodeForTarget(subproject.indexTitle, 0),
+ writer.writeStartElement("section");
+ QString indexPath = gen_->fullDocumentLocation(qdb_->findNodeForTarget(subproject.indexTitle, 0),
false);
- writer.writeAttribute("ref", indexPath);
- writer.writeAttribute("title", subproject.title);
- }
+ writer.writeAttribute("ref", indexPath);
+ writer.writeAttribute("title", subproject.title);
+
if (subproject.sortPages) {
QStringList titles = subproject.nodes.keys();
titles.sort();
@@ -809,8 +815,7 @@ void HelpProjectWriter::generateProject(HelpProject &project)
}
}
- if (!name.isEmpty())
- writer.writeEndElement(); // section
+ writer.writeEndElement(); // section
}
}
diff --git a/src/tools/qdoc/helpprojectwriter.h b/src/tools/qdoc/helpprojectwriter.h
index efc2596296..e4cd1404c7 100644
--- a/src/tools/qdoc/helpprojectwriter.h
+++ b/src/tools/qdoc/helpprojectwriter.h
@@ -50,10 +50,11 @@ struct SubProject
{
QString title;
QString indexTitle;
- QHash<Node::Type, QSet<DocumentNode::SubType> > selectors;
+ QHash<Node::NodeType, QSet<DocumentNode::DocSubtype> > selectors;
bool sortPages;
QString type;
QHash<QString, const Node *> nodes;
+ QStringList groups;
};
struct HelpProject
@@ -70,7 +71,7 @@ struct HelpProject
QSet<QString> filterAttributes;
QHash<QString, QSet<QString> > customFilters;
QSet<QString> excluded;
- QMap<QString, SubProject> subprojects;
+ QList<SubProject> subprojects;
QHash<const Node *, QSet<Node::Status> > memberStatus;
bool includeIndexNodes;
};
diff --git a/src/tools/qdoc/htmlgenerator.cpp b/src/tools/qdoc/htmlgenerator.cpp
index 4aed6085cd..18d2af5810 100644
--- a/src/tools/qdoc/htmlgenerator.cpp
+++ b/src/tools/qdoc/htmlgenerator.cpp
@@ -49,6 +49,7 @@
#include <qiterator.h>
#include <qtextcodec.h>
#include <quuid.h>
+#include <qmap.h>
QT_BEGIN_NAMESPACE
@@ -71,11 +72,11 @@ static void addLink(const QString &linkTarget,
QString *res)
{
if (!linkTarget.isEmpty()) {
- *res += "<a href=\"";
+ *res += QLatin1String("<a href=\"");
*res += linkTarget;
- *res += "\">";
+ *res += QLatin1String("\">");
*res += nestedStuff;
- *res += "</a>";
+ *res += QLatin1String("</a>");
}
else {
*res += nestedStuff;
@@ -139,8 +140,8 @@ void HtmlGenerator::initializeGenerator(const Config &config)
*/
int i = 0;
while (defaults[i].key) {
- formattingLeftMap().insert(defaults[i].key, defaults[i].left);
- formattingRightMap().insert(defaults[i].key, defaults[i].right);
+ formattingLeftMap().insert(QLatin1String(defaults[i].key), QLatin1String(defaults[i].left));
+ formattingRightMap().insert(QLatin1String(defaults[i].key), QLatin1String(defaults[i].right));
i++;
}
@@ -180,7 +181,7 @@ void HtmlGenerator::initializeGenerator(const Config &config)
projectDescription = config.getString(CONFIG_DESCRIPTION);
if (projectDescription.isEmpty() && !project.isEmpty())
- projectDescription = project + " Reference Documentation";
+ projectDescription = project + QLatin1String(" Reference Documentation");
projectUrl = config.getString(CONFIG_URL);
tagFile_ = config.getString(CONFIG_TAGFILE);
@@ -236,8 +237,8 @@ void HtmlGenerator::initializeGenerator(const Config &config)
headerStyles = config.getString(HtmlGenerator::format() + Config::dot + CONFIG_HEADERSTYLES);
QString prefix = CONFIG_QHP + Config::dot + project + Config::dot;
- manifestDir = "qthelp://" + config.getString(prefix + "namespace");
- manifestDir += QLatin1Char('/') + config.getString(prefix + "virtualFolder") + QLatin1Char('/');
+ manifestDir = QLatin1String("qthelp://") + config.getString(prefix + QLatin1String("namespace"));
+ manifestDir += QLatin1Char('/') + config.getString(prefix + QLatin1String("virtualFolder")) + QLatin1Char('/');
readManifestMetaContent(config);
examplesPath = config.getString(CONFIG_EXAMPLESINSTALLPATH);
if (!examplesPath.isEmpty())
@@ -282,12 +283,17 @@ QString HtmlGenerator::format()
*/
void HtmlGenerator::generateKeywordAnchors(const Node* node)
{
+ Q_UNUSED(node);
+ // Disabled: keywords always link to the top of the QDoc
+ // comment they appear in, and do not use a dedicated anchor.
+#if 0
if (!node->doc().isEmpty()) {
const QList<Atom*>& keywords = node->doc().keywords();
foreach (Atom* a, keywords) {
- out() << "<a name=\"" << Doc::canonicalTitle(a->string()) << "\"></a>";
+ out() << QLatin1String("<a name=\"") << Doc::canonicalTitle(a->string()) << QLatin1String("\"></a>");
}
}
+#endif
}
/*!
@@ -470,18 +476,10 @@ QString HtmlGenerator::generateLinksToBrokenLinksPage(CodeMarker* marker, int& c
*/
int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMarker *marker)
{
- int skipAhead = 0;
+ int idx, skipAhead = 0;
static bool in_para = false;
switch (atom->type()) {
- case Atom::AbstractLeft:
- if (relative)
- relative->doc().location().warning(tr("\abstract is not implemented."));
- else
- Location::information(tr("\abstract is not implemented."));
- break;
- case Atom::AbstractRight:
- break;
case Atom::AutoLink:
case Atom::NavAutoLink:
if (!inLink_ && !inContents_ && !inSectionHeading_) {
@@ -547,9 +545,9 @@ int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMark
else
out() << "variable";
QStringList words = str.split(QLatin1Char(' '));
- if (!(words.first() == "contains" || words.first() == "specifies"
- || words.first() == "describes" || words.first() == "defines"
- || words.first() == "holds" || words.first() == "determines"))
+ if (!(words.first() == QLatin1String("contains") || words.first() == QLatin1String("specifies")
+ || words.first() == QLatin1String("describes") || words.first() == QLatin1String("defines")
+ || words.first() == QLatin1String("holds") || words.first() == QLatin1String("determines")))
out() << " holds ";
else
out() << ' ';
@@ -668,74 +666,83 @@ int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMark
break;
case Atom::AnnotatedList:
{
- CollectionNode* cn = qdb_->getCollection(atom->string(), Node::DOC);
+ const CollectionNode* cn = qdb_->getCollectionNode(atom->string(), Node::DOC);
if (cn)
generateList(cn, marker, atom->string());
}
break;
case Atom::GeneratedList:
- if (atom->string() == "annotatedclasses") {
+ if (atom->string() == QLatin1String("annotatedclasses")) {
generateAnnotatedList(relative, marker, qdb_->getCppClasses());
}
- else if (atom->string() == "classes") {
+ else if (atom->string() == QLatin1String("classes")) {
generateCompactList(Generic, relative, qdb_->getCppClasses(), true, QStringLiteral(""));
}
else if (atom->string().contains("classes ")) {
QString rootName = atom->string().mid(atom->string().indexOf("classes") + 7).trimmed();
generateCompactList(Generic, relative, qdb_->getCppClasses(), true, rootName);
}
- else if (atom->string() == "qmlbasictypes") {
+ else if (atom->string() == QLatin1String("qmlbasictypes")) {
generateCompactList(Generic, relative, qdb_->getQmlBasicTypes(), true, QStringLiteral(""));
}
- else if (atom->string() == "qmltypes") {
+ else if (atom->string() == QLatin1String("qmltypes")) {
generateCompactList(Generic, relative, qdb_->getQmlTypes(), true, QStringLiteral(""));
}
- else if (atom->string().contains("classesbymodule")) {
- QString physicalModuleName = atom->string().mid(atom->string().indexOf("classesbymodule") + 15).trimmed();
+ else if ((idx = atom->string().indexOf(QStringLiteral("bymodule"))) != -1) {
+ QString moduleName = atom->string().mid(idx + 8).trimmed();
+ Node::Genus genus = Node::CPP;
+ if (atom->string().startsWith(QLatin1String("qml")))
+ genus = Node::QML;
+ else if (atom->string().startsWith(QLatin1String("js")))
+ genus = Node::JS;
QDocDatabase* qdb = QDocDatabase::qdocDB();
- CollectionNode* cn = qdb->findModule(physicalModuleName);
+ const CollectionNode* cn = qdb->getCollectionNode(moduleName, genus);
if (cn) {
- NodeMap m;
- cn->getMemberClasses(m);
- if (!m.isEmpty()) {
- generateAnnotatedList(relative, marker, m);
+ if (genus == Node::CPP) {
+ NodeMap m;
+ cn->getMemberClasses(m);
+ if (!m.isEmpty()) {
+ generateAnnotatedList(relative, marker, m);
+ }
}
+ else
+ generateAnnotatedList(relative, marker, cn->members());
}
}
- else if (atom->string() == "classhierarchy") {
+ else if (atom->string() == QLatin1String("classhierarchy")) {
generateClassHierarchy(relative, qdb_->getCppClasses());
}
- else if (atom->string() == "obsoleteclasses") {
+ else if (atom->string() == QLatin1String("obsoleteclasses")) {
generateCompactList(Generic, relative, qdb_->getObsoleteClasses(), false, QStringLiteral("Q"));
}
- else if (atom->string() == "obsoleteqmltypes") {
+ else if (atom->string() == QLatin1String("obsoleteqmltypes")) {
generateCompactList(Generic, relative, qdb_->getObsoleteQmlTypes(), false, QStringLiteral(""));
}
- else if (atom->string() == "obsoletecppmembers") {
+ else if (atom->string() == QLatin1String("obsoletecppmembers")) {
generateCompactList(Obsolete, relative, qdb_->getClassesWithObsoleteMembers(), false, QStringLiteral("Q"));
}
- else if (atom->string() == "obsoleteqmlmembers") {
+ else if (atom->string() == QLatin1String("obsoleteqmlmembers")) {
generateCompactList(Obsolete, relative, qdb_->getQmlTypesWithObsoleteMembers(), false, QStringLiteral(""));
}
- else if (atom->string() == "functionindex") {
+ else if (atom->string() == QLatin1String("functionindex")) {
generateFunctionIndex(relative);
}
- else if (atom->string() == "legalese") {
+ else if (atom->string() == QLatin1String("legalese")) {
generateLegaleseList(relative, marker);
}
- else if (atom->string() == "overviews") {
+ else if (atom->string() == QLatin1String("overviews")) {
generateList(relative, marker, "overviews");
}
- else if (atom->string() == "cpp-modules") {
+ else if (atom->string() == QLatin1String("cpp-modules")) {
generateList(relative, marker, "cpp-modules");
}
- else if (atom->string() == "qml-modules") {
+ else if (atom->string() == QLatin1String("qml-modules")) {
generateList(relative, marker, "qml-modules");
}
- else if (atom->string() == "namespaces") {
+ else if (atom->string() == QLatin1String("namespaces")) {
generateAnnotatedList(relative, marker, qdb_->getNamespaces());
}
- else if (atom->string() == "related") {
+ else if (atom->string() == QLatin1String("related")) {
generateList(relative, marker, "related");
}
#if 0
@@ -743,7 +750,7 @@ int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMark
This is not used in Qt5, as of 10/02/2014
Remove permanently if it is not missed.
*/
- else if (atom->string() == "relatedinline") {
+ else if (atom->string() == QLatin1String("relatedinline")) {
const DocumentNode *dn = static_cast<const DocumentNode *>(relative);
if (dn && !dn->members().isEmpty()) {
// Reverse the list into the original scan order.
@@ -1218,13 +1225,13 @@ int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMark
p2 = atom->string(1);
}
if (!p1.isEmpty()) {
- if (p1 == "borderless")
+ if (p1 == QLatin1String("borderless"))
attr = p1;
else if (p1.contains("%"))
width = p1;
}
if (!p2.isEmpty()) {
- if (p2 == "borderless")
+ if (p2 == QLatin1String("borderless"))
attr = p2;
else if (p2.contains("%"))
width = p2;
@@ -1336,7 +1343,7 @@ int HtmlGenerator::generateAtom(const Atom *atom, const Node *relative, CodeMark
/*!
Generate a reference page for a C++ class or a C++ namespace.
*/
-void HtmlGenerator::generateClassLikeNode(InnerNode* inner, CodeMarker* marker)
+void HtmlGenerator::generateClassLikeNode(Aggregate* inner, CodeMarker* marker)
{
QList<Section> sections;
QList<Section>::ConstIterator s;
@@ -1485,7 +1492,7 @@ void HtmlGenerator::generateClassLikeNode(InnerNode* inner, CodeMarker* marker)
const FunctionNode *func = reinterpret_cast<const FunctionNode *>(*m);
if (func->metaness() == FunctionNode::Ctor ||
func->metaness() == FunctionNode::Dtor ||
- func->overloadNumber() != 1)
+ func->overloadNumber() != 0)
names.clear();
}
else if ((*m)->type() == Node::Property) {
@@ -1644,7 +1651,7 @@ void HtmlGenerator::generateDocumentNode(DocumentNode* dn, CodeMarker* marker)
is DITA map page, write the node's contents as a dita
map and return without doing anything else.
*/
- if (dn->subType() == Node::Page && dn->pageType() == Node::DitaMapPage) {
+ if (dn->docSubtype() == Node::Page && dn->pageType() == Node::DitaMapPage) {
const DitaMapNode* dmn = static_cast<const DitaMapNode*>(dn);
writeDitaMap(dmn);
return;
@@ -1660,7 +1667,7 @@ void HtmlGenerator::generateDocumentNode(DocumentNode* dn, CodeMarker* marker)
Generate the TOC for the new doc format.
Don't generate a TOC for the home page.
*/
- if ((dn->name() != QStringLiteral("index.html")))
+ if ((dn->name() != QLatin1String("index.html")))
generateTableOfContents(dn,marker,0);
generateKeywordAnchors(dn);
@@ -1670,7 +1677,7 @@ void HtmlGenerator::generateDocumentNode(DocumentNode* dn, CodeMarker* marker)
dn,
marker);
- if (dn->subType() == Node::HeaderFile) {
+ if (dn->docSubtype() == Node::HeaderFile) {
// Generate brief text and status for modules.
generateBrief(dn, marker);
generateStatus(dn, marker);
@@ -1804,10 +1811,12 @@ void HtmlGenerator::generateCollectionNode(CollectionNode* cn, CodeMarker* marke
generateAlsoList(cn, marker);
generateExtractionMark(cn, EndMark);
- if (cn->isGroup())
- generateAnnotatedList(cn, marker, cn->members());
- else if (cn->isQmlModule() || cn->isJsModule())
- generateAnnotatedList(cn, marker, cn->members());
+ if (!cn->noAutoList()) {
+ if (cn->isGroup())
+ generateAnnotatedList(cn, marker, cn->members());
+ else if (cn->isQmlModule() || cn->isJsModule())
+ generateAnnotatedList(cn, marker, cn->members());
+ }
sections = marker->sections(cn, CodeMarker::Detailed, CodeMarker::Okay);
s = sections.constBegin();
@@ -2087,7 +2096,7 @@ void HtmlGenerator::generateFooter(const Node *node)
Lists the required imports and includes in a table.
The number of rows is known, so this path is simpler than the generateSection() path.
*/
-void HtmlGenerator::generateRequisites(InnerNode *inner, CodeMarker *marker)
+void HtmlGenerator::generateRequisites(Aggregate *inner, CodeMarker *marker)
{
QMap<QString, Text> requisites;
Text text;
@@ -2136,7 +2145,7 @@ void HtmlGenerator::generateRequisites(InnerNode *inner, CodeMarker *marker)
if (inner->type() == Node::Class || inner->type() == Node::Namespace) {
//add the QT variable to the map
if (!inner->physicalModuleName().isEmpty()) {
- CollectionNode* cn = qdb_->findModule(inner->physicalModuleName());
+ const CollectionNode* cn = qdb_->getCollectionNode(inner->physicalModuleName(), Node::CPP);
if (cn && !cn->qtVariable().isEmpty()) {
text.clear();
text << "QT += " + cn->qtVariable();
@@ -2246,11 +2255,7 @@ void HtmlGenerator::generateQmlRequisites(QmlTypeNode *qcn, CodeMarker *marker)
//add the module name and version to the map
QString logicalModuleVersion;
- CollectionNode* collection = 0;
- if (qcn->isJsNode())
- collection = qdb_->findJsModule(qcn->logicalModuleName());
- else
- collection = qdb_->findQmlModule(qcn->logicalModuleName());
+ const CollectionNode* collection = qdb_->getCollectionNode(qcn->logicalModuleName(), qcn->genus());
if (collection)
logicalModuleVersion = collection->logicalModuleVersion();
else
@@ -2359,7 +2364,7 @@ void HtmlGenerator::generateBrief(const Node *node, CodeMarker *marker,
}
}
-void HtmlGenerator::generateIncludes(const InnerNode *inner, CodeMarker *marker)
+void HtmlGenerator::generateIncludes(const Aggregate *inner, CodeMarker *marker)
{
if (!inner->includes().isEmpty()) {
out() << "<pre class=\"cpp\">"
@@ -2518,7 +2523,7 @@ void HtmlGenerator::generateSidebar() {
out() << "</div>\n";
}
-QString HtmlGenerator::generateListOfAllMemberFile(const InnerNode *inner,
+QString HtmlGenerator::generateListOfAllMemberFile(const Aggregate *inner,
CodeMarker *marker)
{
QList<Section> sections;
@@ -2613,7 +2618,7 @@ QString HtmlGenerator::generateAllQmlMembersFile(QmlTypeNode* qml_cn, CodeMarker
return fileName;
}
-QString HtmlGenerator::generateLowStatusMemberFile(InnerNode *inner,
+QString HtmlGenerator::generateLowStatusMemberFile(Aggregate *inner,
CodeMarker *marker,
CodeMarker::Status status)
{
@@ -3164,13 +3169,13 @@ void HtmlGenerator::generateList(const Node* relative, CodeMarker* marker, const
{
CNMap cnm;
Node::Genus genus = Node::DontCare;
- if (selector == "overviews")
+ if (selector == QLatin1String("overviews"))
genus = Node::DOC;
- else if (selector == "cpp-modules")
+ else if (selector == QLatin1String("cpp-modules"))
genus = Node::CPP;
- else if (selector == "qml-modules")
+ else if (selector == QLatin1String("qml-modules"))
genus = Node::QML;
- else if (selector == "js-modules")
+ else if (selector == QLatin1String("js-modules"))
genus = Node::JS;
if (genus != Node::DontCare) {
NodeList nl;
@@ -3345,7 +3350,7 @@ void HtmlGenerator::generateSectionList(const Section& section,
void HtmlGenerator::generateSectionInheritedList(const Section& section, const Node *relative)
{
- QList<QPair<InnerNode *, int> >::ConstIterator p = section.inherited.constBegin();
+ QList<QPair<Aggregate *, int> >::ConstIterator p = section.inherited.constBegin();
while (p != section.inherited.constEnd()) {
out() << "<li class=\"fn\">";
out() << (*p).second << ' ';
@@ -3415,6 +3420,7 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode,
{
QString src = markedCode;
QString html;
+ html.reserve(src.size());
QStringRef arg;
QStringRef par1;
@@ -3427,62 +3433,30 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode,
static const QString linkTag("link");
// replace all <@link> tags: "(<@link node=\"([^\"]+)\">).*(</@link>)"
+ // replace all <@func> tags: "(<@func target=\"([^\"]*)\">)(.*)(</@func>)"
+ // replace all "(<@(type|headerfile)(?: +[^>]*)?>)(.*)(</@\\2>)" tags
bool done = false;
for (int i = 0, srcSize = src.size(); i < srcSize;) {
if (src.at(i) == charLangle && src.at(i + 1) == charAt) {
if (alignNames && !done) {
- html += "</td><td class=\"memItemRight bottomAlign\">";
+ html += QLatin1String("</td><td class=\"memItemRight bottomAlign\">");
done = true;
}
i += 2;
if (parseArg(src, linkTag, &i, srcSize, &arg, &par1)) {
- html += "<b>";
+ html += QLatin1String("<b>");
const Node* n = CodeMarker::nodeForString(par1.toString());
QString link = linkForNode(n, relative);
addLink(link, arg, &html);
- html += "</b>";
- }
- else {
- html += charLangle;
- html += charAt;
+ html += QLatin1String("</b>");
}
- }
- else {
- html += src.at(i++);
- }
- }
-
- // replace all <@func> tags: "(<@func target=\"([^\"]*)\">)(.*)(</@func>)"
- src = html;
- html = QString();
- for (int i = 0, srcSize = src.size(); i < srcSize;) {
- if (src.at(i) == charLangle && src.at(i + 1) == charAt) {
- i += 2;
- if (parseArg(src, funcTag, &i, srcSize, &arg, &par1)) {
+ else if (parseArg(src, funcTag, &i, srcSize, &arg, &par1)) {
const Node* n = qdb_->findFunctionNode(par1.toString(), relative, Node::DontCare);
QString link = linkForNode(n, relative);
addLink(link, arg, &html);
par1 = QStringRef();
}
- else {
- html += charLangle;
- html += charAt;
- }
- }
- else {
- html += src.at(i++);
- }
- }
-
- // replace all "(<@(type|headerfile)(?: +[^>]*)?>)(.*)(</@\\2>)" tags
- src = html;
- html = QString();
-
- for (int i=0, srcSize=src.size(); i<srcSize;) {
- if (src.at(i) == charLangle && src.at(i+1) == charAt) {
- i += 2;
- bool handled = false;
- if (parseArg(src, typeTag, &i, srcSize, &arg, &par1)) {
+ else if (parseArg(src, typeTag, &i, srcSize, &arg, &par1)) {
par1 = QStringRef();
const Node* n = qdb_->findTypeNode(arg.toString(), relative);
html += QLatin1String("<span class=\"type\">");
@@ -3495,7 +3469,6 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode,
else
addLink(linkForNode(n,relative), arg, &html);
html += QLatin1String("</span>");
- handled = true;
}
else if (parseArg(src, headerTag, &i, srcSize, &arg, &par1)) {
par1 = QStringRef();
@@ -3508,9 +3481,8 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode,
else
html += arg;
}
- handled = true;
}
- if (!handled) {
+ else {
html += charLangle;
html += charAt;
}
@@ -3533,59 +3505,68 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode,
// "</@(?:comment|preprocessor|string|char|number|op|type|name|keyword)>" -> "</span>"
src = html;
html = QString();
- static const QString spanTags[] = {
- "<@comment>", "<span class=\"comment\">",
- "<@preprocessor>", "<span class=\"preprocessor\">",
- "<@string>", "<span class=\"string\">",
- "<@char>", "<span class=\"char\">",
- "<@number>", "<span class=\"number\">",
- "<@op>", "<span class=\"operator\">",
- "<@type>", "<span class=\"type\">",
- "<@name>", "<span class=\"name\">",
- "<@keyword>", "<span class=\"keyword\">",
- "</@comment>", "</span>",
- "</@preprocessor>", "</span>",
- "</@string>", "</span>",
- "</@char>", "</span>",
- "</@number>", "</span>",
- "</@op>", "</span>",
- "</@type>", "</span>",
- "</@name>", "</span>",
- "</@keyword>", "</span>",
+ html.reserve(src.size());
+ static const QLatin1String spanTags[] = {
+ QLatin1String("comment>"), QLatin1String("<span class=\"comment\">"),
+ QLatin1String("preprocessor>"), QLatin1String("<span class=\"preprocessor\">"),
+ QLatin1String("string>"), QLatin1String("<span class=\"string\">"),
+ QLatin1String("char>"), QLatin1String("<span class=\"char\">"),
+ QLatin1String("number>"), QLatin1String("<span class=\"number\">"),
+ QLatin1String("op>"), QLatin1String("<span class=\"operator\">"),
+ QLatin1String("type>"), QLatin1String("<span class=\"type\">"),
+ QLatin1String("name>"), QLatin1String("<span class=\"name\">"),
+ QLatin1String("keyword>"), QLatin1String("<span class=\"keyword\">")
};
+ int nTags = 9;
// Update the upper bound of k in the following code to match the length
// of the above array.
for (int i = 0, n = src.size(); i < n;) {
- if (src.at(i) == charLangle) {
- bool handled = false;
- for (int k = 0; k != 18; ++k) {
- const QString & tag = spanTags[2 * k];
- if (tag == QStringRef(&src, i, tag.length())) {
- html += spanTags[2 * k + 1];
- i += tag.length();
- handled = true;
- break;
+ if (src.at(i) == QLatin1Char('<')) {
+ if (src.at(i + 1) == QLatin1Char('@')) {
+ i += 2;
+ bool handled = false;
+ for (int k = 0; k != nTags; ++k) {
+ const QLatin1String& tag = spanTags[2 * k];
+ if (i + tag.size() <= src.length() &&
+ tag == QStringRef(&src, i, tag.size())) {
+ html += spanTags[2 * k + 1];
+ i += tag.size();
+ handled = true;
+ break;
+ }
}
- }
- if (!handled) {
- ++i;
- if (src.at(i) == charAt ||
- (src.at(i) == QLatin1Char('/') && src.at(i + 1) == charAt)) {
+ if (!handled) {
// drop 'our' unknown tags (the ones still containing '@')
while (i < n && src.at(i) != QLatin1Char('>'))
++i;
++i;
}
- else {
- // retain all others
- html += charLangle;
+ continue;
+ }
+ else if (src.at(i + 1) == QLatin1Char('/') && src.at(i + 2) == QLatin1Char('@')) {
+ i += 3;
+ bool handled = false;
+ for (int k = 0; k != nTags; ++k) {
+ const QLatin1String& tag = spanTags[2 * k];
+ if (i + tag.size() <= src.length() &&
+ tag == QStringRef(&src, i, tag.size())) {
+ html += QLatin1String("</span>");
+ i += tag.size();
+ handled = true;
+ break;
+ }
+ }
+ if (!handled) {
+ // drop 'our' unknown tags (the ones still containing '@')
+ while (i < n && src.at(i) != QLatin1Char('>'))
+ ++i;
+ ++i;
}
+ continue;
}
}
- else {
- html += src.at(i);
- ++i;
- }
+ html += src.at(i);
+ ++i;
}
return html;
}
@@ -3660,7 +3641,7 @@ QString HtmlGenerator::protect(const QString &string, const QString &outputEncod
APPEND("&gt;");
} else if (ch == QLatin1Char('"')) {
APPEND("&quot;");
- } else if ((outputEncoding == "ISO-8859-1" && ch.unicode() > 0x007F)
+ } else if ((outputEncoding == QLatin1String("ISO-8859-1") && ch.unicode() > 0x007F)
|| (ch == QLatin1Char('*') && i + 1 < n && string.at(i) == QLatin1Char('/'))
|| (ch == QLatin1Char('.') && i > 2 && string.at(i - 2) == QLatin1Char('.'))) {
// we escape '*/' and the last dot in 'e.g.' and 'i.e.' for the Javadoc generator
@@ -3686,13 +3667,13 @@ QString HtmlGenerator::fileBase(const Node *node) const
result = Generator::fileBase(node);
- if (!node->isInnerNode()) {
+ if (!node->isAggregate()) {
switch (node->status()) {
case Node::Compat:
- result += "-compat";
+ result += QLatin1String("-compat");
break;
case Node::Obsolete:
- result += "-obsolete";
+ result += QLatin1String("-obsolete");
break;
default:
;
@@ -3704,9 +3685,9 @@ QString HtmlGenerator::fileBase(const Node *node) const
QString HtmlGenerator::fileName(const Node *node)
{
if (node->type() == Node::Document) {
- if (static_cast<const DocumentNode *>(node)->subType() == Node::ExternalPage)
+ if (static_cast<const DocumentNode *>(node)->docSubtype() == Node::ExternalPage)
return node->name();
- if (static_cast<const DocumentNode *>(node)->subType() == Node::Image)
+ if (static_cast<const DocumentNode *>(node)->docSubtype() == Node::Image)
return node->name();
}
return Generator::fileName(node);
@@ -3737,12 +3718,12 @@ QString HtmlGenerator::refForNode(const Node *node)
break;
case Node::Function:
func = static_cast<const FunctionNode *>(node);
- if (func->associatedProperty()) {
- return refForNode(func->associatedProperty());
+ if (func->hasOneAssociatedProperty() && func->doc().isEmpty()) {
+ return refForNode(func->firstAssociatedProperty());
}
else {
ref = func->name();
- if (func->overloadNumber() != 1)
+ if (func->overloadNumber() != 0)
ref += QLatin1Char('-') + QString::number(func->overloadNumber());
}
break;
@@ -3767,7 +3748,7 @@ QString HtmlGenerator::refForNode(const Node *node)
case Node::QmlMethod:
func = static_cast<const FunctionNode *>(node);
ref = func->name() + "-method";
- if (func->overloadNumber() != 1)
+ if (func->overloadNumber() != 0)
ref += QLatin1Char('-') + QString::number(func->overloadNumber());
break;
case Node::Variable:
@@ -3831,12 +3812,10 @@ QString HtmlGenerator::getAutoLink(const Atom *atom, const Node *relative, const
QString link = (*node)->url();
if (link.isEmpty()) {
link = linkForNode(*node, relative);
- if ((*node)->subType() == Node::Image)
+ if ((*node)->docSubtype() == Node::Image)
link = "images/used-in-examples/" + link;
- if (!ref.isEmpty())
- link += QLatin1Char('#') + ref;
}
- else if (!ref.isEmpty()) {
+ if (!ref.isEmpty()) {
int hashtag = link.lastIndexOf(QChar('#'));
if (hashtag != -1)
link.truncate(hashtag);
@@ -3872,7 +3851,7 @@ QString HtmlGenerator::linkForNode(const Node *node, const Node *relative)
}
QString link = fn;
- if (!node->isInnerNode() || node->isQmlPropertyGroup() || node->isJsPropertyGroup()) {
+ if (!node->isAggregate() || node->isQmlPropertyGroup() || node->isJsPropertyGroup()) {
QString ref = refForNode(node);
if (relative && fn == fileName(relative) && ref == refForNode(relative))
return QString();
@@ -3923,27 +3902,25 @@ void HtmlGenerator::generateFullName(const Node *apparentNode, const Node *relat
}
void HtmlGenerator::generateDetailedMember(const Node *node,
- const InnerNode *relative,
+ const Aggregate *relative,
CodeMarker *marker)
{
- const EnumNode *enume;
-
+ const EnumNode *etn;
#ifdef GENERATE_MAC_REFS
generateMacRef(node, marker);
#endif
generateExtractionMark(node, MemberMark);
generateKeywordAnchors(node);
QString nodeRef = refForNode(node);
- if (node->type() == Node::Enum
- && (enume = static_cast<const EnumNode *>(node))->flagsType()) {
+ if (node->isEnumType() && (etn = static_cast<const EnumNode *>(node))->flagsType()) {
#ifdef GENERATE_MAC_REFS
- generateMacRef(enume->flagsType(), marker);
+ generateMacRef(etn->flagsType(), marker);
#endif
out() << "<h3 class=\"flags\" id=\"" << nodeRef << "\">";
out() << "<a name=\"" + nodeRef + "\"></a>";
- generateSynopsis(enume, relative, marker, CodeMarker::Detailed);
+ generateSynopsis(etn, relative, marker, CodeMarker::Detailed);
out() << "<br/>";
- generateSynopsis(enume->flagsType(),
+ generateSynopsis(etn->flagsType(),
relative,
marker,
CodeMarker::Detailed);
@@ -3958,10 +3935,11 @@ void HtmlGenerator::generateDetailedMember(const Node *node,
generateStatus(node, marker);
generateBody(node, marker);
+ generateOverloadedSignal(node, marker);
generateThreadSafeness(node, marker);
generateSince(node, marker);
- if (node->type() == Node::Property) {
+ if (node->isProperty()) {
const PropertyNode *property = static_cast<const PropertyNode *>(node);
Section section;
@@ -3987,16 +3965,17 @@ void HtmlGenerator::generateDetailedMember(const Node *node,
const FunctionNode* fn = static_cast<const FunctionNode*>(node);
if (fn->isPrivateSignal())
generatePrivateSignalNote(node, marker);
+ generateAssociatedPropertyNotes(fn);
}
- else if (node->type() == Node::Enum) {
- const EnumNode *enume = static_cast<const EnumNode *>(node);
- if (enume->flagsType()) {
- out() << "<p>The " << protectEnc(enume->flagsType()->name())
+ else if (node->isEnumType()) {
+ const EnumNode *etn = static_cast<const EnumNode *>(node);
+ if (etn->flagsType()) {
+ out() << "<p>The " << protectEnc(etn->flagsType()->name())
<< " type is a typedef for "
<< "<a href=\"" << qflagsHref_ << "\">QFlags</a>&lt;"
- << protectEnc(enume->name())
+ << protectEnc(etn->name())
<< "&gt;. It stores an OR combination of "
- << protectEnc(enume->name())
+ << protectEnc(etn->name())
<< " values.</p>\n";
}
}
@@ -4053,7 +4032,7 @@ void HtmlGenerator::generateStatus(const Node *node, CodeMarker *marker)
switch (node->status()) {
case Node::Obsolete:
- if (node->isInnerNode())
+ if (node->isAggregate())
Generator::generateStatus(node, marker);
break;
case Node::Compat:
@@ -4166,7 +4145,7 @@ void HtmlGenerator::generateQmlSummary(const Section& section,
on a QML element reference page.
*/
void HtmlGenerator::generateDetailedQmlMember(Node *node,
- const InnerNode *relative,
+ const Aggregate *relative,
CodeMarker *marker)
{
QmlPropertyNode* qpn = 0;
@@ -4371,8 +4350,8 @@ void HtmlGenerator::generateExtractionMark(const Node *node, ExtractionMarkType
if (markType == MemberMark) {
if (node->type() == Node::Function) {
const FunctionNode *func = static_cast<const FunctionNode *>(node);
- if (!func->associatedProperty()) {
- if (func->overloadNumber() == 1)
+ if (!func->hasAssociatedProperties()) {
+ if (func->overloadNumber() == 0)
out() << "[overload1]";
out() << "$$$" + func->name() + func->rawParameters().remove(' ');
}
@@ -4428,7 +4407,7 @@ void HtmlGenerator::generateManifestFile(const QString &manifest, const QString
QString fileName = manifest +"-manifest.xml";
QFile file(outputDir() + QLatin1Char('/') + fileName);
bool demos = false;
- if (manifest == "demos")
+ if (manifest == QLatin1String("demos"))
demos = true;
bool proceed = false;
@@ -4481,7 +4460,7 @@ void HtmlGenerator::generateManifestFile(const QString &manifest, const QString
writer.writeAttribute("docUrl", docUrl);
QStringList proFiles;
foreach (const Node* child, en->childNodes()) {
- if (child->subType() == Node::File) {
+ if (child->docSubtype() == Node::File) {
QString file = child->name();
if (file.endsWith(".pro") || file.endsWith(".qmlproject")) {
proFiles << file;
@@ -4578,11 +4557,11 @@ void HtmlGenerator::generateManifestFile(const QString &manifest, const QString
if (s.length() < 2
|| s.at(0).isDigit()
|| s.at(0) == '-'
- || s == QStringLiteral("qt")
- || s == QStringLiteral("the")
- || s == QStringLiteral("and")
- || s.startsWith(QStringLiteral("example"))
- || s.startsWith(QStringLiteral("chapter")))
+ || s == QLatin1String("qt")
+ || s == QLatin1String("the")
+ || s == QLatin1String("and")
+ || s.startsWith(QLatin1String("example"))
+ || s.startsWith(QLatin1String("chapter")))
tag_it = tags.erase(tag_it);
else if (s != *tag_it) {
modified << s;
@@ -4596,7 +4575,7 @@ void HtmlGenerator::generateManifestFile(const QString &manifest, const QString
if (!tags.isEmpty()) {
writer.writeStartElement("tags");
bool wrote_one = false;
- foreach (QString tag, tags) {
+ foreach (const QString &tag, tags) {
if (wrote_one)
writer.writeCharacters(",");
writer.writeCharacters(tag);
@@ -4608,7 +4587,7 @@ void HtmlGenerator::generateManifestFile(const QString &manifest, const QString
QString ename = en->name().mid(en->name().lastIndexOf('/')+1);
QMap<int, const Node*> filesToOpen;
foreach (const Node* child, en->childNodes()) {
- if (child->subType() == Node::File) {
+ if (child->docSubtype() == Node::File) {
QFileInfo fileInfo(child->name());
QString fileName = fileInfo.fileName().toLower();
// open .qml, .cpp and .h files with a
@@ -4693,7 +4672,7 @@ void HtmlGenerator::readManifestMetaContent(const Config &config)
subtype: QML class
subtype: QML module
*/
-void HtmlGenerator::reportOrphans(const InnerNode* parent)
+void HtmlGenerator::reportOrphans(const Aggregate* parent)
{
const NodeList& children = parent->childNodes();
if (children.size() == 0)
@@ -4729,7 +4708,7 @@ void HtmlGenerator::reportOrphans(const InnerNode* parent)
case Node::QmlModule:
break;
case Node::Document:
- switch (child->subType()) {
+ switch (child->docSubtype()) {
case Node::Example:
break;
case Node::HeaderFile:
@@ -4819,7 +4798,7 @@ QXmlStreamWriter& HtmlGenerator::xmlWriter()
It also ensures that a GUID map is created for the output file.
*/
-void HtmlGenerator::beginDitamapPage(const InnerNode* node, const QString& fileName)
+void HtmlGenerator::beginDitamapPage(const Aggregate* node, const QString& fileName)
{
Generator::beginSubPage(node,fileName);
QXmlStreamWriter* writer = new QXmlStreamWriter(out().device());
@@ -4891,4 +4870,37 @@ void HtmlGenerator::writeDitaRefs(const DitaRefList& ditarefs)
}
}
+/*!
+ Generates bold Note lines that explain how function \a fn
+ is associated with each of its associated properties.
+ */
+void HtmlGenerator::generateAssociatedPropertyNotes(const FunctionNode* fn)
+{
+ if (fn->hasAssociatedProperties()) {
+ out() << "<p><b>Note:</b> ";
+ foreach (const PropertyNode* pn, fn->associatedProperties()) {
+ QString msg;
+ switch (pn->role(fn)) {
+ case PropertyNode::Getter:
+ msg = QStringLiteral("Getter function ");
+ break;
+ case PropertyNode::Setter:
+ msg = QStringLiteral("Setter function ");
+ break;
+ case PropertyNode::Resetter:
+ msg = QStringLiteral("Resetter function ");
+ break;
+ case PropertyNode::Notifier:
+ msg = QStringLiteral("Notifier signal ");
+ break;
+ default:
+ break;
+ }
+ QString link = linkForNode(pn, 0);
+ out() << msg << "for property <a href=\"" << link << "\">" << pn->name() << "</a>. ";
+ }
+ out() << "</p>";
+ }
+}
+
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/htmlgenerator.h b/src/tools/qdoc/htmlgenerator.h
index 4a2e158252..d46fc9ebee 100644
--- a/src/tools/qdoc/htmlgenerator.h
+++ b/src/tools/qdoc/htmlgenerator.h
@@ -38,7 +38,7 @@
#ifndef HTMLGENERATOR_H
#define HTMLGENERATOR_H
-#include <qmap.h>
+#include <qhash.h>
#include <qregexp.h>
#include <qxmlstream.h>
#include "codemarker.h"
@@ -94,7 +94,7 @@ protected:
virtual int generateAtom(const Atom *atom,
const Node *relative,
CodeMarker *marker) Q_DECL_OVERRIDE;
- virtual void generateClassLikeNode(InnerNode* inner, CodeMarker* marker) Q_DECL_OVERRIDE;
+ virtual void generateClassLikeNode(Aggregate* inner, CodeMarker* marker) Q_DECL_OVERRIDE;
virtual void generateQmlTypePage(QmlTypeNode* qcn, CodeMarker* marker) Q_DECL_OVERRIDE;
virtual void generateQmlBasicTypePage(QmlBasicTypeNode* qbtn, CodeMarker* marker) Q_DECL_OVERRIDE;
virtual void generateDocumentNode(DocumentNode* dn, CodeMarker* marker) Q_DECL_OVERRIDE;
@@ -106,6 +106,7 @@ protected:
void generateManifestFile(const QString &manifest, const QString &element);
void readManifestMetaContent(const Config &config);
void generateKeywordAnchors(const Node* node);
+ void generateAssociatedPropertyNotes(const FunctionNode* fn);
private:
enum SubTitleSize { SmallSubTitle, LargeSubTitle };
@@ -136,22 +137,22 @@ private:
const Node *relative,
CodeMarker *marker);
void generateFooter(const Node *node = 0);
- void generateRequisites(InnerNode *inner,
+ void generateRequisites(Aggregate *inner,
CodeMarker *marker);
void generateQmlRequisites(QmlTypeNode *qcn,
CodeMarker *marker);
void generateBrief(const Node *node,
CodeMarker *marker,
const Node *relative = 0);
- void generateIncludes(const InnerNode *inner, CodeMarker *marker);
+ void generateIncludes(const Aggregate *inner, CodeMarker *marker);
void generateTableOfContents(const Node *node,
CodeMarker *marker,
QList<Section>* sections = 0);
void generateSidebar();
- QString generateListOfAllMemberFile(const InnerNode *inner,
+ QString generateListOfAllMemberFile(const Aggregate *inner,
CodeMarker *marker);
QString generateAllQmlMembersFile(QmlTypeNode* qml_cn, CodeMarker* marker);
- QString generateLowStatusMemberFile(InnerNode *inner,
+ QString generateLowStatusMemberFile(Aggregate *inner,
CodeMarker *marker,
CodeMarker::Status status);
QString generateQmlMemberFile(QmlTypeNode* qcn,
@@ -180,13 +181,12 @@ private:
CodeMarker *marker,
bool summary);
void generateDetailedQmlMember(Node *node,
- const InnerNode *relative,
+ const Aggregate *relative,
CodeMarker *marker);
void generateQmlInherits(QmlTypeNode* qcn, CodeMarker* marker) Q_DECL_OVERRIDE;
void generateQmlInstantiates(QmlTypeNode* qcn, CodeMarker* marker);
void generateInstantiatedBy(ClassNode* cn, CodeMarker* marker);
- void generateRequisitesTable(const QStringList& requisitesOrder, QMap<QString, Text>& requisites);
void generateSection(const NodeList& nl,
const Node *relative,
CodeMarker *marker,
@@ -204,7 +204,7 @@ private:
void generateFullName(const Node *apparentNode, const Node *relative, const Node *actualNode = 0);
void generateDetailedMember(const Node *node,
- const InnerNode *relative,
+ const Aggregate *relative,
CodeMarker *marker);
void generateLink(const Atom *atom, CodeMarker *marker);
void generateStatus(const Node *node, CodeMarker *marker);
@@ -223,15 +223,15 @@ private:
void beginLink(const QString &link, const Node *node, const Node *relative);
void endLink();
void generateExtractionMark(const Node *node, ExtractionMarkType markType);
- void reportOrphans(const InnerNode* parent);
+ void reportOrphans(const Aggregate* parent);
- void beginDitamapPage(const InnerNode* node, const QString& fileName);
+ void beginDitamapPage(const Aggregate* node, const QString& fileName);
void endDitamapPage();
void writeDitaMap(const DitaMapNode* node);
void writeDitaRefs(const DitaRefList& ditarefs);
QXmlStreamWriter& xmlWriter();
- QMap<QString, QString> refMap;
+ QHash<QString, QString> refMap;
int codeIndent;
HelpProjectWriter *helpProjectWriter;
bool inObsoleteLink;
diff --git a/src/tools/qdoc/jscodemarker.cpp b/src/tools/qdoc/jscodemarker.cpp
index 2538b46433..f6a2c99179 100644
--- a/src/tools/qdoc/jscodemarker.cpp
+++ b/src/tools/qdoc/jscodemarker.cpp
@@ -68,7 +68,7 @@ bool JsCodeMarker::recognizeCode(const QString &code)
QQmlJS::Parser parser(&engine);
QString newCode = code;
- QList<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
+ QVector<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
lexer.setCode(newCode, 1);
return parser.parseProgram();
@@ -95,7 +95,7 @@ bool JsCodeMarker::recognizeLanguage(const QString &language)
/*!
Returns the type of atom used to represent JavaScript code in the documentation.
*/
-Atom::Type JsCodeMarker::atomType() const
+Atom::AtomType JsCodeMarker::atomType() const
{
return Atom::JavaScript;
}
@@ -115,7 +115,7 @@ QString JsCodeMarker::addMarkUp(const QString &code,
QQmlJS::Lexer lexer(&engine);
QString newCode = code;
- QList<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
+ QVector<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
lexer.setCode(newCode, 1);
QQmlJS::Parser parser(&engine);
diff --git a/src/tools/qdoc/jscodemarker.h b/src/tools/qdoc/jscodemarker.h
index d9f6eb5a10..ccba2ca4c7 100644
--- a/src/tools/qdoc/jscodemarker.h
+++ b/src/tools/qdoc/jscodemarker.h
@@ -53,7 +53,7 @@ public:
virtual bool recognizeCode(const QString &code) Q_DECL_OVERRIDE;
virtual bool recognizeExtension(const QString &ext) Q_DECL_OVERRIDE;
virtual bool recognizeLanguage(const QString &language) Q_DECL_OVERRIDE;
- virtual Atom::Type atomType() const Q_DECL_OVERRIDE;
+ virtual Atom::AtomType atomType() const Q_DECL_OVERRIDE;
virtual QString markedUpCode(const QString &code,
const Node *relative,
diff --git a/src/tools/qdoc/location.cpp b/src/tools/qdoc/location.cpp
index 5eba2a69ef..98b63fd035 100644
--- a/src/tools/qdoc/location.cpp
+++ b/src/tools/qdoc/location.cpp
@@ -202,25 +202,34 @@ void Location::pop()
*/
/*! \fn const QString& Location::filePath() const
- Returns the current path and file name.
- Must not be called on an empty Location object.
+ Returns the current path and file name. If the Location is
+ empty, the returned string is null.
\sa lineNo(), columnNo()
*/
/*!
- Returns the file name part of the file path, ie the
- current file. Must not be called on an empty Location
- object.
+ Returns the file name part of the file path, ie the current
+ file. Returns an empty string if the file path is empty.
*/
QString Location::fileName() const
{
QString fp = filePath();
- return fp.mid(fp.lastIndexOf('/') + 1);
+ return (fp.isEmpty() ? fp : fp.mid(fp.lastIndexOf('/') + 1));
}
/*!
+ Returns the suffix of the file name. Returns an empty string
+ if the file path is empty.
+ */
+QString Location::fileSuffix() const
+{
+ QString fp = filePath();
+ return (fp.isEmpty() ? fp : fp.mid(fp.lastIndexOf('.') + 1));
+}
+
+/*!
\brief Returns \a path which is canonicalized and relative to the config file.
QDir::relativeFilePath does not canonicalize the paths, so
diff --git a/src/tools/qdoc/location.h b/src/tools/qdoc/location.h
index 5250e27a47..1cb8e3aec1 100644
--- a/src/tools/qdoc/location.h
+++ b/src/tools/qdoc/location.h
@@ -72,6 +72,7 @@ public:
int depth() const { return stkDepth; }
const QString& filePath() const { return stkTop->filePath; }
QString fileName() const;
+ QString fileSuffix() const;
int lineNo() const { return stkTop->lineNo; }
int columnNo() const { return stkTop->columnNo; }
bool etc() const { return etcetera; }
@@ -104,6 +105,7 @@ private:
int lineNo;
int columnNo;
};
+ friend class QTypeInfo<StackEntry>;
void emitMessage(MessageType type,
const QString& message,
@@ -123,6 +125,8 @@ private:
static QRegExp *spuriousRegExp;
static bool logProgress_;
};
+Q_DECLARE_TYPEINFO(Location::StackEntry, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(Location, Q_COMPLEX_TYPE); // stkTop = &stkBottom
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/main.cpp b/src/tools/qdoc/main.cpp
index 0b156c6bb9..3833cbb5dd 100644
--- a/src/tools/qdoc/main.cpp
+++ b/src/tools/qdoc/main.cpp
@@ -227,6 +227,8 @@ static void processQdocconfFile(const QString &fileName)
config.setStringList(CONFIG_AUTOLINKERRORS, QStringList(autolinkErrors ? "true" : "false"));
config.setStringList(CONFIG_OBSOLETELINKS, QStringList(obsoleteLinks ? "true" : "false"));
+ prevCurrentDir = QDir::currentPath();
+
/*
With the default configuration values in place, load
the qdoc configuration file. Note that the configuration
@@ -236,7 +238,6 @@ static void processQdocconfFile(const QString &fileName)
in the file being processed, mainly for error reporting
purposes.
*/
- currentDir = QFileInfo(fileName).path();
Location::initialize(config);
config.load(fileName);
QString project = config.getString(CONFIG_PROJECT);
@@ -248,7 +249,6 @@ static void processQdocconfFile(const QString &fileName)
config.setStringList(CONFIG_DEFINES,defs);
Location::terminate();
- prevCurrentDir = QDir::currentPath();
currentDir = QFileInfo(fileName).path();
if (!currentDir.isEmpty())
QDir::setCurrent(currentDir);
@@ -342,9 +342,11 @@ static void processQdocconfFile(const QString &fileName)
qdb->clearSearchOrder();
if (!Generator::singleExec()) {
- Generator::debug(" loading index files");
- loadIndexFiles(config);
- Generator::debug(" done loading index files");
+ if (!Generator::preparing()) {
+ Generator::debug(" loading index files");
+ loadIndexFiles(config);
+ Generator::debug(" done loading index files");
+ }
qdb->newPrimaryTree(project);
}
else if (Generator::preparing())
@@ -480,6 +482,9 @@ static void processQdocconfFile(const QString &fileName)
}
Generator::debug(QString("Parsing done."));
+ /*
+ Currently these doneParsingSourceFiles() calls do nothing.
+ */
foreach (CodeParser *codeParser, usedParsers)
codeParser->doneParsingSourceFiles();
diff --git a/src/tools/qdoc/node.cpp b/src/tools/qdoc/node.cpp
index 37bc0c5fef..1fe0af352d 100644
--- a/src/tools/qdoc/node.cpp
+++ b/src/tools/qdoc/node.cpp
@@ -34,26 +34,27 @@
#include "node.h"
#include "tree.h"
#include "codemarker.h"
-#include "codeparser.h"
+#include "cppcodeparser.h"
#include <quuid.h>
#include "qdocdatabase.h"
#include <qdebug.h>
#include "generator.h"
+#include "tokenizer.h"
QT_BEGIN_NAMESPACE
int Node::propertyGroupCount_ = 0;
QStringMap Node::operators_;
-QMap<QString,Node::Type> Node::goals_;
+QMap<QString,Node::NodeType> Node::goals_;
/*!
Initialize the map of search goals. This is called once
by QDocDatabase::initializeDB(). The map key is a string
- representing a value in the enum Node::Type. The map value
+ representing a value in the enum Node::NodeType. The map value
is the enum value.
There should be an entry in the map for each value in the
- Type enum.
+ NodeType enum.
*/
void Node::initialize()
{
@@ -105,7 +106,24 @@ Node::~Node()
{
if (parent_)
parent_->removeChild(this);
+
if (relatesTo_)
+ removeRelates();
+}
+
+/*!
+ Removes this node from the aggregate's list of related
+ nodes, or if this node has created a dummy "relates"
+ aggregate, deletes it.
+*/
+void Node::removeRelates()
+{
+ if (!relatesTo_)
+ return;
+
+ if (relatesTo_->isDocumentNode() && !relatesTo_->parent())
+ delete relatesTo_;
+ else
relatesTo_->removeRelated(this);
}
@@ -160,8 +178,8 @@ QString Node::fullName(const Node* relative) const
match is found, return false.
\a types is a list of type/subtype pairs, where the first
- value in the pair is a Node::Type, and the second value is
- a Node::SubType. The second value is used in the match if
+ value in the pair is a Node::NodeType, and the second value is
+ a Node::DocSubtype. The second value is used in the match if
this node's type is Node::Document.
*/
bool Node::match(const NodeTypeList& types) const
@@ -169,7 +187,7 @@ bool Node::match(const NodeTypeList& types) const
for (int i=0; i<types.size(); ++i) {
if (type() == types.at(i).first) {
if (type() == Node::Document) {
- if (subType() == types.at(i).second)
+ if (docSubtype() == types.at(i).second)
return true;
}
else
@@ -200,12 +218,12 @@ void Node::setDoc(const Doc& doc, bool replace)
given \a parent and \a name. The new node is added to the
parent's child list.
*/
-Node::Node(Type type, InnerNode *parent, const QString& name)
+Node::Node(NodeType type, Aggregate *parent, const QString& name)
: nodeType_((unsigned char) type),
access_((unsigned char) Public),
safeness_((unsigned char) UnspecifiedSafeness),
pageType_((unsigned char) NoPageType),
- status_((unsigned char) Commendable),
+ status_((unsigned char) Active),
indexNodeFlag_(false),
parent_(parent),
relatesTo_(0),
@@ -320,7 +338,7 @@ QString Node::nodeTypeString() const
*/
QString Node::nodeTypeString(unsigned char t)
{
- switch ((Type)t) {
+ switch ((NodeType)t) {
case Namespace:
return "namespace";
case Class:
@@ -370,7 +388,7 @@ QString Node::nodeTypeString(unsigned char t)
*/
QString Node::nodeSubtypeString() const
{
- return nodeSubtypeString(subType());
+ return nodeSubtypeString(docSubtype());
}
/*!
@@ -380,7 +398,7 @@ QString Node::nodeSubtypeString() const
*/
QString Node::nodeSubtypeString(unsigned char t)
{
- switch ((SubType)t) {
+ switch ((DocSubtype)t) {
case Example:
return "example";
case HeaderFile:
@@ -395,7 +413,7 @@ QString Node::nodeSubtypeString(unsigned char t)
return "external page";
case DitaMap:
return "ditamap";
- case NoSubType:
+ case NoSubtype:
default:
break;
}
@@ -460,13 +478,24 @@ bool Node::fromFlagValue(FlagValue fv, bool defaultValue)
/*!
Sets the pointer to the node that this node relates to.
*/
-void Node::setRelates(InnerNode *pseudoParent)
+void Node::setRelates(Aggregate *pseudoParent)
{
- if (relatesTo_) {
- relatesTo_->removeRelated(this);
- }
+ if (pseudoParent == parent())
+ return;
+
+ removeRelates();
relatesTo_ = pseudoParent;
- pseudoParent->related_.append(this);
+ pseudoParent->addRelated(this);
+}
+
+/*!
+ Sets the (unresolved) entity \a name that this node relates to.
+ */
+void Node::setRelates(const QString& name)
+{
+ removeRelates();
+ // Create a dummy aggregate for writing the name into the index
+ relatesTo_ = new DocumentNode(0, name, Node::NoSubtype, Node::NoPageType);
}
/*!
@@ -558,7 +587,7 @@ QString RelatedClass::accessString() const
*/
Node::Status Node::inheritedStatus() const
{
- Status parentStatus = Commendable;
+ Status parentStatus = Active;
if (parent_)
parentStatus = parent_->inheritedStatus();
return (Status)qMin((int)status_, (int)parentStatus);
@@ -606,7 +635,6 @@ QString Node::fileBase() const
base.replace(QLatin1Char(' '), QLatin1Char('-'));
return base.toLower();
}
-#endif
/*!
Returns this node's Universally Unique IDentifier as a
QString. Creates the UUID first, if it has not been created.
@@ -617,6 +645,7 @@ QString Node::guid() const
uuid_ = idForNode();
return uuid_;
}
+#endif
/*!
If this node is a QML or JS type node, return a pointer to
@@ -683,14 +712,32 @@ const Node* Node::root() const
}
/*!
- \class InnerNode
+ Sets the node's declaration location, its definition
+ location, or both, depending on the suffix of the file
+ name from the file path in location \a t.
+ */
+void Node::setLocation(const Location& t)
+{
+ QString suffix = t.fileSuffix();
+ if (suffix == "h")
+ declLocation_ = t;
+ else if (suffix == "cpp")
+ defLocation_ = t;
+ else {
+ declLocation_ = t;
+ defLocation_ = t;
+ }
+}
+
+/*!
+ \class Aggregate
*/
/*!
The inner node destructor deletes the children and removes
this node from its related nodes.
*/
-InnerNode::~InnerNode()
+Aggregate::~Aggregate()
{
deleteChildren();
removeFromRelated();
@@ -706,17 +753,17 @@ InnerNode::~InnerNode()
find all this node's children that have the given \a name,
and return the one that satisfies the \a genus requirement.
*/
-Node *InnerNode::findChildNode(const QString& name, Node::Genus genus) const
+Node *Aggregate::findChildNode(const QString& name, Node::Genus genus) const
{
if (genus == Node::DontCare) {
- Node *node = childMap.value(name);
+ Node *node = childMap_.value(name);
if (node && !node->isQmlPropertyGroup()) // mws asks: Why not property group?
return node;
if (isQmlType() || isJsType()) {
for (int i=0; i<children_.size(); ++i) {
Node* n = children_.at(i);
if (n->isQmlPropertyGroup() || isJsPropertyGroup()) {
- node = static_cast<InnerNode*>(n)->findChildNode(name, genus);
+ node = static_cast<Aggregate*>(n)->findChildNode(name, genus);
if (node)
return node;
}
@@ -724,7 +771,7 @@ Node *InnerNode::findChildNode(const QString& name, Node::Genus genus) const
}
}
else {
- NodeList nodes = childMap.values(name);
+ NodeList nodes = childMap_.values(name);
if (!nodes.isEmpty()) {
for (int i=0; i<nodes.size(); ++i) {
Node* node = nodes.at(i);
@@ -733,20 +780,20 @@ Node *InnerNode::findChildNode(const QString& name, Node::Genus genus) const
}
}
}
- return primaryFunctionMap.value(name);
+ return primaryFunctionMap_.value(name);
}
/*!
Find all the child nodes of this node that are named
\a name and return them in \a nodes.
*/
-void InnerNode::findChildren(const QString& name, NodeList& nodes) const
+void Aggregate::findChildren(const QString& name, NodeList& nodes) const
{
- nodes = childMap.values(name);
- Node* n = primaryFunctionMap.value(name);
+ nodes = childMap_.values(name);
+ Node* n = primaryFunctionMap_.value(name);
if (n) {
nodes.append(n);
- NodeList t = secondaryFunctionMap.value(name);
+ NodeList t = secondaryFunctionMap_.value(name);
if (!t.isEmpty())
nodes.append(t);
}
@@ -756,7 +803,7 @@ void InnerNode::findChildren(const QString& name, NodeList& nodes) const
if (i < 0)
return;
QString qmlPropGroup = name.left(i);
- NodeList t = childMap.values(qmlPropGroup);
+ NodeList t = childMap_.values(qmlPropGroup);
if (t.isEmpty())
return;
foreach (Node* n, t) {
@@ -773,12 +820,12 @@ void InnerNode::findChildren(const QString& name, NodeList& nodes) const
with the specified \a name is found but it is not of the
specified \a type, 0 is returned.
*/
-Node* InnerNode::findChildNode(const QString& name, Type type)
+Node* Aggregate::findChildNode(const QString& name, NodeType type)
{
if (type == Function)
- return primaryFunctionMap.value(name);
+ return primaryFunctionMap_.value(name);
else {
- NodeList nodes = childMap.values(name);
+ NodeList nodes = childMap_.values(name);
for (int i=0; i<nodes.size(); ++i) {
Node* node = nodes.at(i);
if (node->type() == type)
@@ -792,9 +839,56 @@ Node* InnerNode::findChildNode(const QString& name, Type type)
Find a function node that is a child of this nose, such
that the function node has the specified \a name.
*/
-FunctionNode *InnerNode::findFunctionNode(const QString& name) const
-{
- return static_cast<FunctionNode *>(primaryFunctionMap.value(name));
+FunctionNode *Aggregate::findFunctionNode(const QString& name, const QString& params) const
+{
+ FunctionNode* pfn = static_cast<FunctionNode*>(primaryFunctionMap_.value(name));
+ FunctionNode* fn = pfn;
+ if (fn) {
+ const QVector<Parameter>* funcParams = &(fn->parameters());
+ if (params.isEmpty() && funcParams->isEmpty())
+ return fn;
+ bool isQPrivateSignal = false; // Not used in the search
+ QVector<Parameter> testParams;
+ if (!params.isEmpty()) {
+ CppCodeParser* cppParser = CppCodeParser::cppParser();
+ cppParser->parseParameters(params, testParams, isQPrivateSignal);
+ }
+ NodeList funcs = secondaryFunctionMap_.value(name);
+ int i = -1;
+ while (fn) {
+ if (testParams.size() == funcParams->size()) {
+ if (testParams.isEmpty())
+ return fn;
+ bool different = false;
+ for (int j=0; j<testParams.size(); j++) {
+ if (testParams.at(j).dataType() != funcParams->at(j).dataType()) {
+ different = true;
+ break;
+ }
+ }
+ if (!different)
+ return fn;
+ }
+ if (++i < funcs.size()) {
+ fn = static_cast<FunctionNode*>(funcs.at(i));
+ funcParams = &(fn->parameters());
+ }
+ else
+ fn = 0;
+ }
+ if (!fn && !testParams.empty())
+ return 0;
+ }
+ /*
+ Most \l commands that link to functions don't include
+ the parameter declarations in the function signature,
+ so if the \l is meant to go to a function that does
+ have parameters, the algorithm above won't find it.
+ Therefore we must return the pointer to the function
+ in the primary function map in the cases where the
+ parameters should have been specified in the \l command.
+ */
+ return (fn ? fn : pfn);
}
/*!
@@ -802,15 +896,15 @@ FunctionNode *InnerNode::findFunctionNode(const QString& name) const
that the function has the same name and signature as the
\a clone node.
*/
-FunctionNode *InnerNode::findFunctionNode(const FunctionNode *clone) const
+FunctionNode *Aggregate::findFunctionNode(const FunctionNode *clone) const
{
- QMap<QString,Node*>::ConstIterator c = primaryFunctionMap.constFind(clone->name());
- if (c != primaryFunctionMap.constEnd()) {
+ QMap<QString,Node*>::ConstIterator c = primaryFunctionMap_.constFind(clone->name());
+ if (c != primaryFunctionMap_.constEnd()) {
if (isSameSignature(clone, (FunctionNode *) *c)) {
return (FunctionNode *) *c;
}
- else if (secondaryFunctionMap.contains(clone->name())) {
- const NodeList& secs = secondaryFunctionMap[clone->name()];
+ else if (secondaryFunctionMap_.contains(clone->name())) {
+ const NodeList& secs = secondaryFunctionMap_[clone->name()];
NodeList::ConstIterator s = secs.constBegin();
while (s != secs.constEnd()) {
if (isSameSignature(clone, (FunctionNode *) *s))
@@ -825,11 +919,11 @@ FunctionNode *InnerNode::findFunctionNode(const FunctionNode *clone) const
/*!
Returns the list of keys from the primary function map.
*/
-QStringList InnerNode::primaryKeys()
+QStringList Aggregate::primaryKeys()
{
QStringList t;
- QMap<QString, Node*>::iterator i = primaryFunctionMap.begin();
- while (i != primaryFunctionMap.end()) {
+ QMap<QString, Node*>::iterator i = primaryFunctionMap_.begin();
+ while (i != primaryFunctionMap_.end()) {
t.append(i.key());
++i;
}
@@ -839,11 +933,11 @@ QStringList InnerNode::primaryKeys()
/*!
Returns the list of keys from the secondary function map.
*/
-QStringList InnerNode::secondaryKeys()
+QStringList Aggregate::secondaryKeys()
{
QStringList t;
- QMap<QString, NodeList>::iterator i = secondaryFunctionMap.begin();
- while (i != secondaryFunctionMap.end()) {
+ QMap<QString, NodeList>::iterator i = secondaryFunctionMap_.begin();
+ while (i != secondaryFunctionMap_.end()) {
t.append(i.key());
++i;
}
@@ -851,43 +945,13 @@ QStringList InnerNode::secondaryKeys()
}
/*!
- */
-void InnerNode::setOverload(FunctionNode *func, bool overlode)
-{
- Node *node = (Node *) func;
- Node *&primary = primaryFunctionMap[func->name()];
-
- if (secondaryFunctionMap.contains(func->name())) {
- NodeList& secs = secondaryFunctionMap[func->name()];
- if (overlode) {
- if (primary == node) {
- primary = secs.first();
- secs.erase(secs.begin());
- secs.append(node);
- }
- else {
- secs.removeAll(node);
- secs.append(node);
- }
- }
- else {
- if (primary != node) {
- secs.removeAll(node);
- secs.prepend(primary);
- primary = node;
- }
- }
- }
-}
-
-/*!
Mark all child nodes that have no documentation as having
private access and internal status. qdoc will then ignore
them for documentation purposes. Some nodes have an
Intermediate status, meaning that they should be ignored,
but not their children.
*/
-void InnerNode::makeUndocumentedChildrenInternal()
+void Aggregate::makeUndocumentedChildrenInternal()
{
foreach (Node *child, childNodes()) {
if (child->doc().isEmpty() && child->status() != Node::Intermediate) {
@@ -898,68 +962,93 @@ void InnerNode::makeUndocumentedChildrenInternal()
}
/*!
+ This is where we set the overload numbers for function nodes.
+ \note Overload numbers for related non-members are handled
+ separately.
*/
-void InnerNode::normalizeOverloads()
+void Aggregate::normalizeOverloads()
{
- QMap<QString, Node *>::Iterator p1 = primaryFunctionMap.begin();
- while (p1 != primaryFunctionMap.end()) {
+ QMap<QString, Node *>::Iterator p1 = primaryFunctionMap_.begin();
+ while (p1 != primaryFunctionMap_.end()) {
FunctionNode *primaryFunc = (FunctionNode *) *p1;
- if (secondaryFunctionMap.contains(primaryFunc->name()) &&
- (primaryFunc->status() != Commendable ||
- primaryFunc->access() == Private)) {
-
- NodeList& secs = secondaryFunctionMap[primaryFunc->name()];
- NodeList::ConstIterator s = secs.constBegin();
- while (s != secs.constEnd()) {
- FunctionNode *secondaryFunc = (FunctionNode *) *s;
-
- // Any non-obsolete, non-compatibility, non-private functions
- // (i.e, visible functions) are preferable to the primary
- // function.
-
- if (secondaryFunc->status() == Commendable &&
- secondaryFunc->access() != Private) {
-
- *p1 = secondaryFunc;
- int index = secondaryFunctionMap[primaryFunc->name()].indexOf(secondaryFunc);
- secondaryFunctionMap[primaryFunc->name()].replace(index, primaryFunc);
- break;
+ if (primaryFunc->status() != Active || primaryFunc->access() == Private) {
+ if (secondaryFunctionMap_.contains(primaryFunc->name())) {
+ /*
+ Either the primary function is not active or it is private.
+ It therefore can't be the primary function. Search the list
+ of overloads to find one that can be the primary function.
+ */
+ NodeList& overloads = secondaryFunctionMap_[primaryFunc->name()];
+ NodeList::ConstIterator s = overloads.constBegin();
+ while (s != overloads.constEnd()) {
+ FunctionNode *overloadFunc = (FunctionNode *) *s;
+ /*
+ Any non-obsolete, non-private function (i.e., visible function)
+ is preferable to the current primary function. Swap the primary
+ and overload functions.
+ */
+ if (overloadFunc->status() == Active && overloadFunc->access() != Private) {
+ primaryFunc->setOverloadNumber(overloadFunc->overloadNumber());
+ overloads.replace(overloads.indexOf(overloadFunc), primaryFunc);
+ *p1 = overloadFunc;
+ overloadFunc->setOverloadFlag(false);
+ overloadFunc->setOverloadNumber(0);
+ break;
+ }
+ ++s;
}
- ++s;
}
}
++p1;
}
-
- QMap<QString, Node *>::ConstIterator p = primaryFunctionMap.constBegin();
- while (p != primaryFunctionMap.constEnd()) {
+ /*
+ Ensure that none of the primary functions is marked with \overload.
+ */
+ QMap<QString, Node *>::Iterator p = primaryFunctionMap_.begin();
+ while (p != primaryFunctionMap_.end()) {
FunctionNode *primaryFunc = (FunctionNode *) *p;
- if (primaryFunc->isOverload())
- primaryFunc->ove = false;
- if (secondaryFunctionMap.contains(primaryFunc->name())) {
- NodeList& secs = secondaryFunctionMap[primaryFunc->name()];
- NodeList::ConstIterator s = secs.constBegin();
- while (s != secs.constEnd()) {
- FunctionNode *secondaryFunc = (FunctionNode *) *s;
- if (!secondaryFunc->isOverload())
- secondaryFunc->ove = true;
- ++s;
+ if (primaryFunc->isOverload()) {
+ if (secondaryFunctionMap_.contains(primaryFunc->name())) {
+ /*
+ The primary function is marked with \overload. Find an
+ overload in the secondary function map that is not marked
+ with \overload but that is active and not private. Then
+ swap it with the primary function.
+ */
+ NodeList& overloads = secondaryFunctionMap_[primaryFunc->name()];
+ NodeList::ConstIterator s = overloads.constBegin();
+ while (s != overloads.constEnd()) {
+ FunctionNode *overloadFunc = (FunctionNode *) *s;
+ if (!overloadFunc->isOverload()) {
+ if (overloadFunc->status() == Active && overloadFunc->access() != Private) {
+ primaryFunc->setOverloadNumber(overloadFunc->overloadNumber());
+ overloads.replace(overloads.indexOf(overloadFunc), primaryFunc);
+ *p = overloadFunc;
+ overloadFunc->setOverloadFlag(false);
+ overloadFunc->setOverloadNumber(0);
+ break;
+ }
+ }
+ ++s;
+ }
}
}
++p;
}
-
+ /*
+ Recursive part.
+ */
NodeList::ConstIterator c = childNodes().constBegin();
while (c != childNodes().constEnd()) {
- if ((*c)->isInnerNode())
- ((InnerNode *) *c)->normalizeOverloads();
+ if ((*c)->isAggregate())
+ ((Aggregate *) *c)->normalizeOverloads();
++c;
}
}
/*!
*/
-void InnerNode::removeFromRelated()
+void Aggregate::removeFromRelated()
{
while (!related_.isEmpty()) {
Node *p = static_cast<Node *>(related_.takeFirst());
@@ -971,13 +1060,13 @@ void InnerNode::removeFromRelated()
/*!
Deletes all this node's children.
*/
-void InnerNode::deleteChildren()
+void Aggregate::deleteChildren()
{
NodeList childrenCopy = children_; // `children_` will be changed in ~Node()
qDeleteAll(childrenCopy);
}
-/*! \fn bool InnerNode::isInnerNode() const
+/*! \fn bool Aggregate::isAggregate() const
Returns \c true because this is an inner node.
*/
@@ -997,7 +1086,7 @@ bool Node::isWrapper() const
no enum type node is found that has \a enumValue as one
of its values.
*/
-const EnumNode *InnerNode::findEnumNodeForValue(const QString &enumValue) const
+const EnumNode *Aggregate::findEnumNodeForValue(const QString &enumValue) const
{
foreach (const Node *node, enumChildren_) {
const EnumNode *en = static_cast<const EnumNode *>(node);
@@ -1008,32 +1097,16 @@ const EnumNode *InnerNode::findEnumNodeForValue(const QString &enumValue) const
}
/*!
- Returnds the sequence number of the function node \a func
- in the list of overloaded functions for a class, such that
- all the functions have the same name as the \a func.
- */
-int InnerNode::overloadNumber(const FunctionNode *func) const
-{
- Node *node = const_cast<FunctionNode *>(func);
- if (primaryFunctionMap[func->name()] == node) {
- return 1;
- }
- else {
- return secondaryFunctionMap[func->name()].indexOf(node) + 2;
- }
-}
-
-/*!
Returns a node list containing all the member functions of
some class such that the functions overload the name \a funcName.
*/
-NodeList InnerNode::overloads(const QString &funcName) const
+NodeList Aggregate::overloads(const QString &funcName) const
{
NodeList result;
- Node *primary = primaryFunctionMap.value(funcName);
+ Node *primary = primaryFunctionMap_.value(funcName);
if (primary) {
result << primary;
- result += secondaryFunctionMap[funcName];
+ result += secondaryFunctionMap_[funcName];
}
return result;
}
@@ -1042,7 +1115,7 @@ NodeList InnerNode::overloads(const QString &funcName) const
Construct an inner node (i.e., not a leaf node) of the
given \a type and having the given \a parent and \a name.
*/
-InnerNode::InnerNode(Type type, InnerNode *parent, const QString& name)
+Aggregate::Aggregate(NodeType type, Aggregate *parent, const QString& name)
: Node(type, parent, name)
{
switch (type) {
@@ -1059,7 +1132,7 @@ InnerNode::InnerNode(Type type, InnerNode *parent, const QString& name)
/*!
Appends an \a include file to the list of include files.
*/
-void InnerNode::addInclude(const QString& include)
+void Aggregate::addInclude(const QString& include)
{
includes_.append(include);
}
@@ -1067,7 +1140,7 @@ void InnerNode::addInclude(const QString& include)
/*!
Sets the list of include files to \a includes.
*/
-void InnerNode::setIncludes(const QStringList& includes)
+void Aggregate::setIncludes(const QStringList& includes)
{
includes_ = includes;
}
@@ -1075,22 +1148,22 @@ void InnerNode::setIncludes(const QStringList& includes)
/*!
f1 is always the clone
*/
-bool InnerNode::isSameSignature(const FunctionNode *f1, const FunctionNode *f2)
+bool Aggregate::isSameSignature(const FunctionNode *f1, const FunctionNode *f2)
{
- if (f1->parameters().count() != f2->parameters().count())
+ if (f1->parameters().size() != f2->parameters().size())
return false;
if (f1->isConst() != f2->isConst())
return false;
- QList<Parameter>::ConstIterator p1 = f1->parameters().constBegin();
- QList<Parameter>::ConstIterator p2 = f2->parameters().constBegin();
+ QVector<Parameter>::ConstIterator p1 = f1->parameters().constBegin();
+ QVector<Parameter>::ConstIterator p2 = f2->parameters().constBegin();
while (p2 != f2->parameters().constEnd()) {
if ((*p1).hasType() && (*p2).hasType()) {
if ((*p1).rightType() != (*p2).rightType())
return false;
- QString t1 = p1->leftType();
- QString t2 = p2->leftType();
+ QString t1 = p1->dataType();
+ QString t2 = p2->dataType();
if (t1.length() < t2.length())
qSwap(t1, t2);
@@ -1113,23 +1186,26 @@ bool InnerNode::isSameSignature(const FunctionNode *f1, const FunctionNode *f2)
be necessary to update this node's internal collections and
the child's parent pointer and output subdirectory.
*/
-void InnerNode::addChild(Node *child)
+void Aggregate::addChild(Node *child)
{
children_.append(child);
if ((child->type() == Function) || (child->type() == QmlMethod)) {
- FunctionNode *func = (FunctionNode *) child;
- if (!primaryFunctionMap.contains(func->name())) {
- primaryFunctionMap.insert(func->name(), func);
+ FunctionNode *func = static_cast<FunctionNode*>(child);
+ QString name = func->name();
+ if (!primaryFunctionMap_.contains(name)) {
+ primaryFunctionMap_.insert(name, func);
+ func->setOverloadNumber(0);
}
else {
- NodeList &secs = secondaryFunctionMap[func->name()];
- secs.append(func);
+ NodeList &overloads = secondaryFunctionMap_[name];
+ overloads.append(func);
+ func->setOverloadNumber(overloads.size());
}
}
else {
if (child->type() == Enum)
enumChildren_.append(child);
- childMap.insertMulti(child->name(), child);
+ childMap_.insertMulti(child->name(), child);
}
if (child->parent() == 0) {
child->setParent(this);
@@ -1143,9 +1219,9 @@ void InnerNode::addChild(Node *child)
again, because it is presumed to already be there. We just
want to be able to find the child by its \a title.
*/
-void InnerNode::addChild(Node* child, const QString& title)
+void Aggregate::addChild(Node* child, const QString& title)
{
- childMap.insertMulti(title, child);
+ childMap_.insertMulti(title, child);
}
/*!
@@ -1154,40 +1230,38 @@ void InnerNode::addChild(Node* child, const QString& title)
pointer is set to 0, but its output subdirectory is not
changed.
*/
-void InnerNode::removeChild(Node *child)
+void Aggregate::removeChild(Node *child)
{
children_.removeAll(child);
enumChildren_.removeAll(child);
if (child->type() == Function) {
- QMap<QString, Node *>::Iterator prim =
- primaryFunctionMap.find(child->name());
- NodeList& secs = secondaryFunctionMap[child->name()];
- if (prim != primaryFunctionMap.end() && *prim == child) {
- if (secs.isEmpty()) {
- primaryFunctionMap.remove(child->name());
- }
- else {
- primaryFunctionMap.insert(child->name(), secs.takeFirst());
+ QMap<QString, Node *>::Iterator primary = primaryFunctionMap_.find(child->name());
+ NodeList& overloads = secondaryFunctionMap_[child->name()];
+ if (primary != primaryFunctionMap_.end() && *primary == child) {
+ primaryFunctionMap_.erase(primary);
+ if (!overloads.isEmpty()) {
+ FunctionNode* fn = static_cast<FunctionNode*>(overloads.takeFirst());
+ fn->setOverloadNumber(0);
+ primaryFunctionMap_.insert(child->name(), fn);
}
}
- else {
- secs.removeAll(child);
- }
+ else
+ overloads.removeAll(child);
}
- QMap<QString, Node *>::Iterator ent = childMap.find(child->name());
- while (ent != childMap.end() && ent.key() == child->name()) {
+ QMap<QString, Node *>::Iterator ent = childMap_.find(child->name());
+ while (ent != childMap_.end() && ent.key() == child->name()) {
if (*ent == child) {
- childMap.erase(ent);
+ childMap_.erase(ent);
break;
}
++ent;
}
if (child->title().isEmpty())
return;
- ent = childMap.find(child->title());
- while (ent != childMap.end() && ent.key() == child->title()) {
+ ent = childMap_.find(child->title());
+ while (ent != childMap_.end() && ent.key() == child->title()) {
if (*ent == child) {
- childMap.erase(ent);
+ childMap_.erase(ent);
break;
}
++ent;
@@ -1198,7 +1272,7 @@ void InnerNode::removeChild(Node *child)
/*!
Recursively sets the output subdirectory for children
*/
-void InnerNode::setOutputSubdirectory(const QString &t)
+void Aggregate::setOutputSubdirectory(const QString &t)
{
Node::setOutputSubdirectory(t);
for (int i = 0; i < childNodes().size(); ++i)
@@ -1260,17 +1334,56 @@ QString Node::physicalModuleName() const
}
/*!
+ Removes a node from the list of nodes related to this one.
+ If it is a function node, also remove from the primary/
+ secondary function maps.
*/
-void InnerNode::removeRelated(Node *pseudoChild)
+void Aggregate::removeRelated(Node *pseudoChild)
{
related_.removeAll(pseudoChild);
+
+ if (pseudoChild->isFunction()) {
+ QMap<QString, Node *>::Iterator p = primaryFunctionMap_.find(pseudoChild->name());
+ while (p != primaryFunctionMap_.end()) {
+ if (p.value() == pseudoChild) {
+ primaryFunctionMap_.erase(p);
+ break;
+ }
+ ++p;
+ }
+ NodeList& overloads = secondaryFunctionMap_[pseudoChild->name()];
+ overloads.removeAll(pseudoChild);
+ }
+}
+
+/*!
+ Adds \a pseudoChild to the list of nodes related to this one. Resolve a correct
+ overload number for a related non-member function.
+ */
+void Aggregate::addRelated(Node *pseudoChild)
+{
+ related_.append(pseudoChild);
+
+ if (pseudoChild->isFunction()) {
+ FunctionNode* fn = static_cast<FunctionNode*>(pseudoChild);
+ if (primaryFunctionMap_.contains(pseudoChild->name())) {
+ secondaryFunctionMap_[pseudoChild->name()].append(pseudoChild);
+ fn->setOverloadNumber(secondaryFunctionMap_[pseudoChild->name()].size());
+ fn->setOverloadFlag(true);
+ }
+ else {
+ primaryFunctionMap_.insert(pseudoChild->name(), pseudoChild);
+ fn->setOverloadNumber(0);
+ fn->setOverloadFlag(false);
+ }
+ }
}
/*!
If this node has a child that is a QML property named \a n,
return the pointer to that child.
*/
-QmlPropertyNode* InnerNode::hasQmlProperty(const QString& n) const
+QmlPropertyNode* Aggregate::hasQmlProperty(const QString& n) const
{
foreach (Node* child, childNodes()) {
if (child->type() == Node::QmlProperty) {
@@ -1291,7 +1404,7 @@ QmlPropertyNode* InnerNode::hasQmlProperty(const QString& n) const
whose type (attached or normal property) matches \a attached,
return the pointer to that child.
*/
-QmlPropertyNode* InnerNode::hasQmlProperty(const QString& n, bool attached) const
+QmlPropertyNode* Aggregate::hasQmlProperty(const QString& n, bool attached) const
{
foreach (Node* child, childNodes()) {
if (child->type() == Node::QmlProperty) {
@@ -1311,7 +1424,7 @@ QmlPropertyNode* InnerNode::hasQmlProperty(const QString& n, bool attached) cons
\class LeafNode
*/
-/*! \fn bool LeafNode::isInnerNode() const
+/*! \fn bool LeafNode::isAggregate() const
Returns \c false because this is a LeafNode.
*/
@@ -1319,7 +1432,7 @@ QmlPropertyNode* InnerNode::hasQmlProperty(const QString& n, bool attached) cons
Constructs a leaf node named \a name of the specified
\a type. The new leaf node becomes a child of \a parent.
*/
-LeafNode::LeafNode(Type type, InnerNode *parent, const QString& name)
+LeafNode::LeafNode(NodeType type, Aggregate *parent, const QString& name)
: Node(type, parent, name)
{
switch (type) {
@@ -1346,7 +1459,7 @@ LeafNode::LeafNode(Type type, InnerNode *parent, const QString& name)
documentation case where a \e{qmlproperty} command is used
to override the QML definition of a QML property.
*/
-LeafNode::LeafNode(InnerNode* parent, Type type, const QString& name)
+LeafNode::LeafNode(Aggregate* parent, NodeType type, const QString& name)
: Node(type, 0, name)
{
setParent(parent);
@@ -1374,8 +1487,8 @@ LeafNode::LeafNode(InnerNode* parent, Type type, const QString& name)
/*!
Constructs a namespace node.
*/
-NamespaceNode::NamespaceNode(InnerNode *parent, const QString& name)
- : InnerNode(Namespace, parent, name), seen_(false), tree_(0)
+NamespaceNode::NamespaceNode(Aggregate *parent, const QString& name)
+ : Aggregate(Namespace, parent, name), seen_(false), tree_(0)
{
setGenus(Node::CPP);
setPageType(ApiPage);
@@ -1389,8 +1502,8 @@ NamespaceNode::NamespaceNode(InnerNode *parent, const QString& name)
/*!
Constructs a class node. A class node will generate an API page.
*/
-ClassNode::ClassNode(InnerNode *parent, const QString& name)
- : InnerNode(Class, parent, name)
+ClassNode::ClassNode(Aggregate *parent, const QString& name)
+ : Aggregate(Class, parent, name)
{
abstract_ = false;
wrapper_ = false;
@@ -1584,8 +1697,8 @@ QmlTypeNode* ClassNode::findQmlBaseNode()
which specifies the type of DocumentNode. The page type for
the page index is set here.
*/
-DocumentNode::DocumentNode(InnerNode* parent, const QString& name, SubType subtype, Node::PageType ptype)
- : InnerNode(Document, parent, name), nodeSubtype_(subtype)
+DocumentNode::DocumentNode(Aggregate* parent, const QString& name, DocSubtype subtype, Node::PageType ptype)
+ : Aggregate(Document, parent, name), nodeSubtype_(subtype)
{
setGenus(Node::DOC);
switch (subtype) {
@@ -1618,7 +1731,7 @@ void DocumentNode::setTitle(const QString &title)
/*!
Returns the document node's full title, which is usually
- just title(), but for some SubType values is different
+ just title(), but for some DocSubtype values is different
from title()
*/
QString DocumentNode::fullTitle() const
@@ -1669,8 +1782,8 @@ QString DocumentNode::subTitle() const
The constructor for the node representing an enum type
has a \a parent class and an enum type \a name.
*/
-EnumNode::EnumNode(InnerNode *parent, const QString& name)
- : LeafNode(Enum, parent, name), ft(0)
+EnumNode::EnumNode(Aggregate *parent, const QString& name)
+ : LeafNode(Enum, parent, name), flagsType_(0)
{
setGenus(Node::CPP);
}
@@ -1680,8 +1793,8 @@ EnumNode::EnumNode(InnerNode *parent, const QString& name)
*/
void EnumNode::addItem(const EnumItem& item)
{
- itms.append(item);
- names.insert(item.name());
+ items_.append(item);
+ names_.insert(item.name());
}
/*!
@@ -1701,7 +1814,7 @@ Node::Access EnumNode::itemAccess(const QString &name) const
*/
QString EnumNode::itemValue(const QString &name) const
{
- foreach (const EnumItem &item, itms) {
+ foreach (const EnumItem &item, items_) {
if (item.name() == name)
return item.value();
}
@@ -1714,8 +1827,8 @@ QString EnumNode::itemValue(const QString &name) const
/*!
*/
-TypedefNode::TypedefNode(InnerNode *parent, const QString& name)
- : LeafNode(Typedef, parent, name), ae(0)
+TypedefNode::TypedefNode(Aggregate *parent, const QString& name)
+ : LeafNode(Typedef, parent, name), associatedEnum_(0)
{
setGenus(Node::CPP);
}
@@ -1724,7 +1837,7 @@ TypedefNode::TypedefNode(InnerNode *parent, const QString& name)
*/
void TypedefNode::setAssociatedEnum(const EnumNode *enume)
{
- ae = enume;
+ associatedEnum_ = enume;
}
/*!
@@ -1737,36 +1850,43 @@ void TypedefNode::setAssociatedEnum(const EnumNode *enume)
/*!
Constructs this parameter from the left and right types
- \a leftType and rightType, the parameter \a name, and the
+ \a dataType and rightType, the parameter \a name, and the
\a defaultValue. In practice, \a rightType is not used,
and I don't know what is was meant for.
*/
-Parameter::Parameter(const QString& leftType,
+Parameter::Parameter(const QString& dataType,
const QString& rightType,
const QString& name,
const QString& defaultValue)
- : lef(leftType), rig(rightType), nam(name), def(defaultValue)
+ : dataType_(dataType),
+ rightType_(rightType),
+ name_(name),
+ defaultValue_(defaultValue)
{
+ // nothing.
}
/*!
- The standard copy constructor copies the strings from \a p.
+ Standard copy constructor copies \p.
*/
Parameter::Parameter(const Parameter& p)
- : lef(p.lef), rig(p.rig), nam(p.nam), def(p.def)
+ : dataType_(p.dataType_),
+ rightType_(p.rightType_),
+ name_(p.name_),
+ defaultValue_(p.defaultValue_)
{
+ // nothing.
}
/*!
- Assigning Parameter \a p to this Parameter copies the
- strings across.
+ standard assignment operator assigns \p.
*/
Parameter& Parameter::operator=(const Parameter& p)
{
- lef = p.lef;
- rig = p.rig;
- nam = p.nam;
- def = p.def;
+ dataType_ = p.dataType_;
+ rightType_ = p.rightType_;
+ name_ = p.name_;
+ defaultValue_ = p.defaultValue_;
return *this;
}
@@ -1777,12 +1897,12 @@ Parameter& Parameter::operator=(const Parameter& p)
*/
QString Parameter::reconstruct(bool value) const
{
- QString p = lef + rig;
+ QString p = dataType_ + rightType_;
if (!p.endsWith(QChar('*')) && !p.endsWith(QChar('&')) && !p.endsWith(QChar(' ')))
p += QLatin1Char(' ');
- p += nam;
- if (value && !def.isEmpty())
- p += " = " + def;
+ p += name_;
+ if (value && !defaultValue_.isEmpty())
+ p += " = " + defaultValue_;
return p;
}
@@ -1794,19 +1914,21 @@ QString Parameter::reconstruct(bool value) const
/*!
Construct a function node for a C++ function. It's parent
is \a parent, and it's name is \a name.
+
+ Do not set overloadNumber_ in the initializer list because it
+ is set by addChild() in the Node base class.
*/
-FunctionNode::FunctionNode(InnerNode *parent, const QString& name)
+FunctionNode::FunctionNode(Aggregate *parent, const QString& name)
: LeafNode(Function, parent, name),
- met(Plain),
- vir(NonVirtual),
- con(false),
- sta(false),
- ove(false),
- reimp(false),
+ metaness_(Plain),
+ virtualness_(NonVirtual),
+ const_(false),
+ static_(false),
+ reimplemented_(false),
attached_(false),
privateSignal_(false),
- rf(0),
- ap(0)
+ overload_(false),
+ reimplementedFrom_(0)
{
setGenus(Node::CPP);
}
@@ -1815,19 +1937,21 @@ FunctionNode::FunctionNode(InnerNode *parent, const QString& name)
Construct a function node for a QML method or signal, specified
by \a type. It's parent is \a parent, and it's name is \a name.
If \a attached is true, it is an attached method or signal.
+
+ Do not set overloadNumber_ in the initializer list because it
+ is set by addChild() in the Node base class.
*/
-FunctionNode::FunctionNode(Type type, InnerNode *parent, const QString& name, bool attached)
+FunctionNode::FunctionNode(NodeType type, Aggregate *parent, const QString& name, bool attached)
: LeafNode(type, parent, name),
- met(Plain),
- vir(NonVirtual),
- con(false),
- sta(false),
- ove(false),
- reimp(false),
+ metaness_(Plain),
+ virtualness_(NonVirtual),
+ const_(false),
+ static_(false),
+ reimplemented_(false),
attached_(attached),
privateSignal_(false),
- rf(0),
- ap(0)
+ overload_(false),
+ reimplementedFrom_(0)
{
setGenus(Node::QML);
if (type == QmlMethod || type == QmlSignal) {
@@ -1843,32 +1967,33 @@ FunctionNode::FunctionNode(Type type, InnerNode *parent, const QString& name, bo
is PureVirtual, and if the parent() is a ClassNode, set the parent's
\e abstract flag to true.
*/
-void FunctionNode::setVirtualness(Virtualness virtualness)
+void FunctionNode::setVirtualness(Virtualness v)
{
- vir = virtualness;
- if ((virtualness == PureVirtual) && parent() &&
- (parent()->type() == Node::Class))
+ virtualness_ = v;
+ if ((v == PureVirtual) && parent() && (parent()->type() == Node::Class))
parent()->setAbstract(true);
}
-/*!
+/*! \fn void FunctionNode::setOverloadFlag(bool b)
+ Sets this function node's overload flag to \a b.
+ It does not set the overload number.
+ */
+
+/*! \fn void FunctionNode::setOverloadNumber(unsigned char n)
+ Sets this function node's overload number to \a n.
+ It does not set the overload flag.
*/
-void FunctionNode::setOverload(bool overlode)
-{
- parent()->setOverload(this, overlode);
- ove = overlode;
-}
/*!
- Sets the function node's reimplementation flag to \a r.
- When \a r is true, it is supposed to mean that this function
+ Sets the function node's reimplementation flag to \a b.
+ When \a b is true, it is supposed to mean that this function
is a reimplementation of a virtual function in a base class,
- but it really just means the \e reimp command was seen in the
- qdoc comment.
+ but it really just means the \e {\\reimp} command was seen in
+ the qdoc comment.
*/
-void FunctionNode::setReimp(bool r)
+void FunctionNode::setReimplemented(bool b)
{
- reimp = r;
+ reimplemented_ = b;
}
/*!
@@ -1876,16 +2001,16 @@ void FunctionNode::setReimp(bool r)
*/
void FunctionNode::addParameter(const Parameter& parameter)
{
- params.append(parameter);
+ parameters_.append(parameter);
}
/*!
*/
void FunctionNode::borrowParameterNames(const FunctionNode *source)
{
- QList<Parameter>::Iterator t = params.begin();
- QList<Parameter>::ConstIterator s = source->params.constBegin();
- while (s != source->params.constEnd() && t != params.end()) {
+ QVector<Parameter>::Iterator t = parameters_.begin();
+ QVector<Parameter>::ConstIterator s = source->parameters_.constBegin();
+ while (s != source->parameters_.constEnd() && t != parameters_.end()) {
if (!(*s).name().isEmpty())
(*t).setName((*s).name());
++s;
@@ -1897,37 +2022,49 @@ void FunctionNode::borrowParameterNames(const FunctionNode *source)
If this function is a reimplementation, \a from points
to the FunctionNode of the function being reimplemented.
*/
-void FunctionNode::setReimplementedFrom(FunctionNode *from)
+void FunctionNode::setReimplementedFrom(FunctionNode *f)
{
- rf = from;
- from->rb.append(this);
+ reimplementedFrom_ = f;
+ f->reimplementedBy_.append(this);
}
/*!
- Sets the "associated" property to \a property. The function
- might be the setter or getter for a property, for example.
+ Adds the "associated" property \a p to this function node.
+ The function might be the setter or getter for a property,
+ for example.
*/
-void FunctionNode::setAssociatedProperty(PropertyNode *property)
+void FunctionNode::addAssociatedProperty(PropertyNode *p)
{
- ap = property;
+ associatedProperties_.append(p);
}
/*!
- Returns the overload number for this function obtained
- from the parent.
+ Returns true if this function has at least one property
+ that is active, i.e. at least one property that is not
+ obsolete.
*/
-int FunctionNode::overloadNumber() const
+bool FunctionNode::hasActiveAssociatedProperty() const
{
- return parent()->overloadNumber(this);
+ if (associatedProperties_.isEmpty())
+ return false;
+ foreach (const PropertyNode* p, associatedProperties_) {
+ if (!p->isObsolete())
+ return true;
+ }
+ return false;
}
+/*! \fn unsigned char FunctionNode::overloadNumber() const
+ Returns the overload number for this function.
+ */
+
/*!
Returns the list of parameter names.
*/
QStringList FunctionNode::parameterNames() const
{
QStringList names;
- QList<Parameter>::ConstIterator p = parameters().constBegin();
+ QVector<Parameter>::ConstIterator p = parameters().constBegin();
while (p != parameters().constEnd()) {
names << (*p).name();
++p;
@@ -1944,7 +2081,7 @@ QString FunctionNode::rawParameters(bool names, bool values) const
{
QString raw;
foreach (const Parameter &parameter, parameters()) {
- raw += parameter.leftType() + parameter.rightType();
+ raw += parameter.dataType() + parameter.rightType();
if (names)
raw += parameter.name();
if (values)
@@ -1957,15 +2094,15 @@ QString FunctionNode::rawParameters(bool names, bool values) const
Returns the list of reconstructed parameters. If \a values
is true, the default values are included, if any are present.
*/
-QStringList FunctionNode::reconstructParams(bool values) const
+QStringList FunctionNode::reconstructParameters(bool values) const
{
- QStringList params;
- QList<Parameter>::ConstIterator p = parameters().constBegin();
+ QStringList reconstructedParameters;
+ QVector<Parameter>::ConstIterator p = parameters().constBegin();
while (p != parameters().constEnd()) {
- params << (*p).reconstruct(values);
+ reconstructedParameters << (*p).reconstruct(values);
++p;
}
- return params;
+ return reconstructedParameters;
}
/*!
@@ -1979,11 +2116,11 @@ QString FunctionNode::signature(bool values) const
if (!returnType().isEmpty())
s = returnType() + QLatin1Char(' ');
s += name() + QLatin1Char('(');
- QStringList params = reconstructParams(values);
- int p = params.size();
+ QStringList reconstructedParameters = reconstructParameters(values);
+ int p = reconstructedParameters.size();
if (p > 0) {
for (int i=0; i<p; i++) {
- s += params[i];
+ s += reconstructedParameters[i];
if (i < (p-1))
s += ", ";
}
@@ -1993,12 +2130,25 @@ QString FunctionNode::signature(bool values) const
}
/*!
+ Returns true if function \a fn has role \a r for this
+ property.
+ */
+PropertyNode::FunctionRole PropertyNode::role(const FunctionNode* fn) const
+{
+ for (int i=0; i<4; i++) {
+ if (functions_[i].contains(const_cast<FunctionNode*>(fn)))
+ return (FunctionRole) i;
+ }
+ return Notifier;
+}
+
+/*!
Print some debugging stuff.
*/
void FunctionNode::debug() const
{
- qDebug("QML METHOD %s rt %s pp %s",
- qPrintable(name()), qPrintable(rt), qPrintable(pp.join(' ')));
+ qDebug("QML METHOD %s returnType_ %s parentPath_ %s",
+ qPrintable(name()), qPrintable(returnType_), qPrintable(parentPath_.join(' ')));
}
/*!
@@ -2011,17 +2161,17 @@ void FunctionNode::debug() const
The constructor sets the \a parent and the \a name, but
everything else is set to default values.
*/
-PropertyNode::PropertyNode(InnerNode *parent, const QString& name)
+PropertyNode::PropertyNode(Aggregate *parent, const QString& name)
: LeafNode(Property, parent, name),
stored_(FlagValueDefault),
designable_(FlagValueDefault),
scriptable_(FlagValueDefault),
writable_(FlagValueDefault),
user_(FlagValueDefault),
- cst(false),
- fnl(false),
- rev(-1),
- overrides(0)
+ const_(false),
+ final_(false),
+ revision_(-1),
+ overrides_(0)
{
setGenus(Node::CPP);
}
@@ -2039,8 +2189,8 @@ PropertyNode::PropertyNode(InnerNode *parent, const QString& name)
void PropertyNode::setOverriddenFrom(const PropertyNode* baseProperty)
{
for (int i = 0; i < NumFunctionRoles; ++i) {
- if (funcs[i].isEmpty())
- funcs[i] = baseProperty->funcs[i];
+ if (functions_[i].isEmpty())
+ functions_[i] = baseProperty->functions_[i];
}
if (stored_ == FlagValueDefault)
stored_ = baseProperty->stored_;
@@ -2052,7 +2202,7 @@ void PropertyNode::setOverriddenFrom(const PropertyNode* baseProperty)
writable_ = baseProperty->writable_;
if (user_ == FlagValueDefault)
user_ = baseProperty->user_;
- overrides = baseProperty;
+ overrides_ = baseProperty;
}
/*!
@@ -2084,8 +2234,8 @@ QMultiMap<QString,Node*> QmlTypeNode::inheritedBy;
Constructs a Qml class node. The new node has the given
\a parent and \a name.
*/
-QmlTypeNode::QmlTypeNode(InnerNode *parent, const QString& name)
- : InnerNode(QmlType, parent, name),
+QmlTypeNode::QmlTypeNode(Aggregate *parent, const QString& name)
+ : Aggregate(QmlType, parent, name),
abstract_(false),
cnodeRequired_(false),
wrapper_(false),
@@ -2199,9 +2349,9 @@ QString QmlTypeNode::logicalModuleIdentifier() const
Constructs a Qml basic type node. The new node has the given
\a parent and \a name.
*/
-QmlBasicTypeNode::QmlBasicTypeNode(InnerNode *parent,
+QmlBasicTypeNode::QmlBasicTypeNode(Aggregate *parent,
const QString& name)
- : InnerNode(QmlBasicType, parent, name)
+ : Aggregate(QmlBasicType, parent, name)
{
setTitle(name);
setGenus(Node::QML);
@@ -2212,7 +2362,7 @@ QmlBasicTypeNode::QmlBasicTypeNode(InnerNode *parent,
always a QmlTypeNode.
*/
QmlPropertyGroupNode::QmlPropertyGroupNode(QmlTypeNode* parent, const QString& name)
- : InnerNode(QmlPropertyGroup, parent, name)
+ : Aggregate(QmlPropertyGroup, parent, name)
{
idNumber_ = -1;
setGenus(Node::QML);
@@ -2235,7 +2385,7 @@ QString QmlPropertyGroupNode::idNumber()
/*!
Constructor for the QML property node.
*/
-QmlPropertyNode::QmlPropertyNode(InnerNode* parent,
+QmlPropertyNode::QmlPropertyNode(Aggregate* parent,
const QString& name,
const QString& type,
bool attached)
@@ -2281,16 +2431,16 @@ bool QmlPropertyNode::isWritable()
if (pn)
return pn->isWritable();
else
- location().warning(tr("No Q_PROPERTY for QML property %1::%2::%3 "
- "in C++ class documented as QML type: "
- "(property not found in the C++ class or its base classes)")
- .arg(logicalModuleName()).arg(qmlTypeName()).arg(name()));
+ defLocation().warning(tr("No Q_PROPERTY for QML property %1::%2::%3 "
+ "in C++ class documented as QML type: "
+ "(property not found in the C++ class or its base classes)")
+ .arg(logicalModuleName()).arg(qmlTypeName()).arg(name()));
}
else
- location().warning(tr("No Q_PROPERTY for QML property %1::%2::%3 "
- "in C++ class documented as QML type: "
- "(C++ class not specified or not found).")
- .arg(logicalModuleName()).arg(qmlTypeName()).arg(name()));
+ defLocation().warning(tr("No Q_PROPERTY for QML property %1::%2::%3 "
+ "in C++ class documented as QML type: "
+ "(C++ class not specified or not found).")
+ .arg(logicalModuleName()).arg(qmlTypeName()).arg(name()));
}
}
return true;
@@ -2477,6 +2627,7 @@ QString Node::cleanId(const QString &str)
return clean;
}
+#if 0
/*!
Creates a string that can be used as a UUID for the node,
depending on the type and subtype of the node. Uniquenss
@@ -2574,14 +2725,14 @@ QString Node::idForNode() const
str = "js-method-" + parent_->name().toLower() + "-" + func->name();
else if (parent_->type() == Document) {
qDebug() << "qdoc internal error: Node subtype not handled:"
- << parent_->subType() << func->name();
+ << parent_->docSubtype() << func->name();
}
else
qDebug() << "qdoc internal error: Node type not handled:"
<< parent_->type() << func->name();
}
- if (func->overloadNumber() != 1)
+ if (func->overloadNumber() != 0)
str += QLatin1Char('-') + QString::number(func->overloadNumber());
}
break;
@@ -2599,7 +2750,7 @@ QString Node::idForNode() const
break;
case Node::Document:
{
- switch (subType()) {
+ switch (docSubtype()) {
case Node::Page:
case Node::HeaderFile:
str = title();
@@ -2620,7 +2771,7 @@ QString Node::idForNode() const
break;
default:
qDebug() << "ERROR: A case was not handled in Node::idForNode():"
- << "subType():" << subType() << "type():" << type();
+ << "docSubtype():" << docSubtype() << "type():" << type();
break;
}
}
@@ -2682,7 +2833,7 @@ QString Node::idForNode() const
else
str = "js-method-";
str += parent_->name().toLower() + "-" + func->name();
- if (func->overloadNumber() != 1)
+ if (func->overloadNumber() != 0)
str += QLatin1Char('-') + QString::number(func->overloadNumber());
break;
case Node::Variable:
@@ -2690,12 +2841,12 @@ QString Node::idForNode() const
break;
default:
qDebug() << "ERROR: A case was not handled in Node::idForNode():"
- << "type():" << type() << "subType():" << subType();
+ << "type():" << type() << "docSubtype():" << docSubtype();
break;
}
if (str.isEmpty()) {
qDebug() << "ERROR: A link text was empty in Node::idForNode():"
- << "type():" << type() << "subType():" << subType()
+ << "type():" << type() << "docSubtype():" << docSubtype()
<< "name():" << name()
<< "title():" << title();
}
@@ -2704,12 +2855,13 @@ QString Node::idForNode() const
}
return str;
}
+#endif
/*!
Prints the inner node's list of children.
For debugging only.
*/
-void InnerNode::printChildren(const QString& title)
+void Aggregate::printChildren(const QString& title)
{
qDebug() << title << name() << children_.size();
if (children_.size() > 0) {
@@ -2792,7 +2944,7 @@ void CollectionNode::getMemberNamespaces(NodeMap& out)
Loads \a out with all this collection node's members that
are class nodes.
*/
-void CollectionNode::getMemberClasses(NodeMap& out)
+void CollectionNode::getMemberClasses(NodeMap& out) const
{
out.clear();
NodeList::const_iterator i = members_.cbegin();
diff --git a/src/tools/qdoc/node.h b/src/tools/qdoc/node.h
index 2ccd97dbd1..6262cee0ab 100644
--- a/src/tools/qdoc/node.h
+++ b/src/tools/qdoc/node.h
@@ -48,7 +48,7 @@ class Node;
class Tree;
class EnumNode;
class ClassNode;
-class InnerNode;
+class Aggregate;
class ExampleNode;
class TypedefNode;
class QmlTypeNode;
@@ -59,6 +59,7 @@ class CollectionNode;
class QmlPropertyNode;
typedef QList<Node*> NodeList;
+typedef QList<PropertyNode*> PropNodeList;
typedef QMap<QString, Node*> NodeMap;
typedef QMultiMap<QString, Node*> NodeMultiMap;
typedef QPair<int, int> NodeTypePair;
@@ -71,7 +72,7 @@ class Node
Q_DECLARE_TR_FUNCTIONS(QDoc::Node)
public:
- enum Type {
+ enum NodeType {
NoType,
Namespace,
Class,
@@ -94,8 +95,8 @@ public:
LastType
};
- enum SubType {
- NoSubType,
+ enum DocSubtype {
+ NoSubtype,
Example,
HeaderFile,
File,
@@ -115,7 +116,7 @@ public:
Obsolete,
Deprecated,
Preliminary,
- Commendable,
+ Active,
Internal,
Intermediate
}; // don't reorder this enum
@@ -132,13 +133,7 @@ public:
NextLink,
PreviousLink,
ContentsLink,
- IndexLink /*,
- GlossaryLink,
- CopyrightLink,
- ChapterLink,
- SectionLink,
- SubsectionLink,
- AppendixLink */
+ IndexLink
};
enum PageType {
@@ -172,24 +167,25 @@ public:
Node::Genus genus() const { return (Genus) genus_; }
void setGenus(Genus t) { genus_ = (unsigned char) t; }
- void setAccess(Access access) { access_ = (unsigned char) access; }
- void setLocation(const Location& location) { loc_ = location; }
+ void setAccess(Access t) { access_ = (unsigned char) t; }
+ void setLocation(const Location& t);
void setDoc(const Doc& doc, bool replace = false);
- void setStatus(Status status) {
- if (status_ == (unsigned char) Obsolete && status == Deprecated)
+ void setStatus(Status t) {
+ if (status_ == (unsigned char) Obsolete && t == Deprecated)
return;
- status_ = (unsigned char) status;
+ status_ = (unsigned char) t;
}
- void setThreadSafeness(ThreadSafeness safeness) { safeness_ = (unsigned char) safeness; }
+ void setThreadSafeness(ThreadSafeness t) { safeness_ = (unsigned char) t; }
void setSince(const QString &since);
- void setRelates(InnerNode* pseudoParent);
+ void setRelates(Aggregate* pseudoParent);
+ void setRelates(const QString &name);
void setPhysicalModuleName(const QString &name) { physicalModuleName_ = name; }
void setUrl(const QString& url) { url_ = url; }
- void setTemplateStuff(const QString &templateStuff) { templateStuff_ = templateStuff; }
+ void setTemplateStuff(const QString &t) { templateStuff_ = t; }
void setReconstitutedBrief(const QString &t) { reconstitutedBrief_ = t; }
void setPageType(PageType t) { pageType_ = (unsigned char) t; }
void setPageType(const QString& t);
- void setParent(InnerNode* n) { parent_ = n; }
+ void setParent(Aggregate* n) { parent_ = n; }
void setIndexNodeFlag() { indexNodeFlag_ = true; }
virtual void setOutputFileName(const QString& ) { }
@@ -197,7 +193,7 @@ public:
bool isJsNode() const { return genus() == JS; }
bool isCppNode() const { return genus() == CPP; }
- virtual bool isInnerNode() const = 0;
+ virtual bool isAggregate() const = 0;
virtual bool isCollectionNode() const { return false; }
virtual bool isDocumentNode() const { return false; }
virtual bool isGroup() const { return false; }
@@ -208,11 +204,12 @@ public:
virtual bool isJsType() const { return false; }
virtual bool isQmlBasicType() const { return false; }
virtual bool isJsBasicType() const { return false; }
+ virtual bool isEnumType() const { return false; }
virtual bool isExample() const { return false; }
virtual bool isExampleFile() const { return false; }
virtual bool isHeaderFile() const { return false; }
virtual bool isLeaf() const { return false; }
- virtual bool isReimp() const { return false; }
+ virtual bool isReimplemented() const { return false; }
virtual bool isFunction() const { return false; }
virtual bool isNamespace() const { return false; }
virtual bool isClass() const { return false; }
@@ -249,23 +246,24 @@ public:
virtual QmlPropertyNode* hasQmlProperty(const QString& ) const { return 0; }
virtual QmlPropertyNode* hasQmlProperty(const QString&, bool ) const { return 0; }
virtual void getMemberNamespaces(NodeMap& ) { }
- virtual void getMemberClasses(NodeMap& ) { }
+ virtual void getMemberClasses(NodeMap& ) const { }
virtual bool isInternal() const;
virtual void setDataType(const QString& ) { }
virtual void setReadOnly(bool ) { }
- virtual Node* disambiguate(Type , SubType ) { return this; }
+ virtual Node* disambiguate(NodeType , DocSubtype ) { return this; }
virtual bool wasSeen() const { return false; }
virtual void appendGroupName(const QString& ) { }
virtual QString element() const { return QString(); }
virtual Tree* tree() const;
virtual void findChildren(const QString& , NodeList& nodes) const { nodes.clear(); }
+ virtual void setNoAutoList(bool ) { }
bool isIndexNode() const { return indexNodeFlag_; }
- Type type() const { return (Type) nodeType_; }
- virtual SubType subType() const { return NoSubType; }
+ NodeType type() const { return (NodeType) nodeType_; }
+ virtual DocSubtype docSubtype() const { return NoSubtype; }
bool match(const NodeTypeList& types) const;
- InnerNode* parent() const { return parent_; }
+ Aggregate* parent() const { return parent_; }
const Node* root() const;
- InnerNode* relates() const { return relatesTo_; }
+ Aggregate* relates() const { return relatesTo_; }
const QString& name() const { return name_; }
QString physicalModuleName() const;
QString url() const { return url_; }
@@ -282,7 +280,9 @@ public:
Access access() const { return (Access) access_; }
bool isPrivate() const { return (Access) access_ == Private; }
QString accessString() const;
- const Location& location() const { return loc_; }
+ const Location& declLocation() const { return declLocation_; }
+ const Location& defLocation() const { return defLocation_; }
+ const Location& location() const { return (defLocation_.isEmpty() ? declLocation_ : defLocation_); }
const Doc& doc() const { return doc_; }
bool hasDoc() const { return !doc_.isEmpty(); }
Status status() const { return (Status) status_; }
@@ -301,7 +301,7 @@ public:
void clearRelated() { relatesTo_ = 0; }
- QString guid() const;
+ //QString guid() const;
QString extractClassName(const QString &string) const;
virtual QString qmlTypeName() const { return name_; }
virtual QString qmlFullBaseName() const { return QString(); }
@@ -322,7 +322,7 @@ public:
virtual void setOutputSubdirectory(const QString& t) { outSubDir_ = t; }
QString fullDocumentName() const;
static QString cleanId(const QString &str);
- QString idForNode() const;
+ //QString idForNode() const;
static FlagValue toFlagValue(bool b);
static bool fromFlagValue(FlagValue fv, bool defaultValue);
@@ -333,10 +333,11 @@ public:
static int incPropertyGroupCount();
static void clearPropertyGroupCount();
static void initialize();
- static Type goal(const QString& t) { return goals_.value(t); }
+ static NodeType goal(const QString& t) { return goals_.value(t); }
protected:
- Node(Type type, InnerNode* parent, const QString& name);
+ Node(NodeType type, Aggregate* parent, const QString& name);
+ void removeRelates();
private:
@@ -348,10 +349,11 @@ private:
unsigned char status_;
bool indexNodeFlag_;
- InnerNode* parent_;
- InnerNode* relatesTo_;
+ Aggregate* parent_;
+ Aggregate* relatesTo_;
QString name_;
- Location loc_;
+ Location declLocation_;
+ Location defLocation_;
Doc doc_;
QMap<LinkType, QPair<QString, QString> > linkMap_;
QString fileNameBase_;
@@ -360,39 +362,38 @@ private:
QString since_;
QString templateStuff_;
QString reconstitutedBrief_;
- mutable QString uuid_;
+ //mutable QString uuid_;
QString outSubDir_;
static QStringMap operators_;
static int propertyGroupCount_;
- static QMap<QString,Node::Type> goals_;
+ static QMap<QString,Node::NodeType> goals_;
};
+Q_DECLARE_TYPEINFO(Node::DocSubtype, Q_PRIMITIVE_TYPE);
-class InnerNode : public Node
+class Aggregate : public Node
{
public:
- virtual ~InnerNode();
+ virtual ~Aggregate();
Node* findChildNode(const QString& name, Node::Genus genus) const;
- Node* findChildNode(const QString& name, Type type);
+ Node* findChildNode(const QString& name, NodeType type);
virtual void findChildren(const QString& name, NodeList& nodes) const Q_DECL_OVERRIDE;
- FunctionNode* findFunctionNode(const QString& name) const;
+ FunctionNode* findFunctionNode(const QString& name, const QString& params) const;
FunctionNode* findFunctionNode(const FunctionNode* clone) const;
void addInclude(const QString &include);
void setIncludes(const QStringList &includes);
- void setOverload(FunctionNode* func, bool overlode);
void normalizeOverloads();
void makeUndocumentedChildrenInternal();
void deleteChildren();
void removeFromRelated();
- virtual bool isInnerNode() const Q_DECL_OVERRIDE { return true; }
+ virtual bool isAggregate() const Q_DECL_OVERRIDE { return true; }
virtual bool isLeaf() const Q_DECL_OVERRIDE { return false; }
const EnumNode* findEnumNodeForValue(const QString &enumValue) const;
const NodeList & childNodes() const { return children_; }
const NodeList & relatedNodes() const { return related_; }
int count() const { return children_.size(); }
- int overloadNumber(const FunctionNode* func) const;
NodeList overloads(const QString &funcName) const;
const QStringList& includes() const { return includes_; }
@@ -411,15 +412,18 @@ public:
void addChild(Node* child);
void removeChild(Node* child);
void setOutputSubdirectory(const QString& t) Q_DECL_OVERRIDE;
+ const NodeMap& primaryFunctionMap() { return primaryFunctionMap_; }
+ const QMap<QString, NodeList>& secondaryFunctionMap() { return secondaryFunctionMap_; }
protected:
- InnerNode(Type type, InnerNode* parent, const QString& name);
+ Aggregate(NodeType type, Aggregate* parent, const QString& name);
private:
friend class Node;
static bool isSameSignature(const FunctionNode* f1, const FunctionNode* f2);
void removeRelated(Node* pseudoChild);
+ void addRelated(Node* pseudoChild);
QString outputFileName_;
QStringList pageKeywds;
@@ -428,9 +432,9 @@ private:
NodeList children_;
NodeList enumChildren_;
NodeList related_;
- QMap<QString, Node*> childMap;
- QMap<QString, Node*> primaryFunctionMap;
- QMap<QString, NodeList> secondaryFunctionMap;
+ NodeMap childMap_;
+ NodeMap primaryFunctionMap_;
+ QMap<QString, NodeList> secondaryFunctionMap_;
};
class LeafNode : public Node
@@ -439,18 +443,18 @@ public:
LeafNode();
virtual ~LeafNode() { }
- virtual bool isInnerNode() const Q_DECL_OVERRIDE { return false; }
+ virtual bool isAggregate() const Q_DECL_OVERRIDE { return false; }
virtual bool isLeaf() const Q_DECL_OVERRIDE { return true; }
protected:
- LeafNode(Type type, InnerNode* parent, const QString& name);
- LeafNode(InnerNode* parent, Type type, const QString& name);
+ LeafNode(NodeType type, Aggregate* parent, const QString& name);
+ LeafNode(Aggregate* parent, NodeType type, const QString& name);
};
-class NamespaceNode : public InnerNode
+class NamespaceNode : public Aggregate
{
public:
- NamespaceNode(InnerNode* parent, const QString& name);
+ NamespaceNode(Aggregate* parent, const QString& name);
virtual ~NamespaceNode() { }
virtual bool isNamespace() const Q_DECL_OVERRIDE { return true; }
virtual Tree* tree() const Q_DECL_OVERRIDE { return (parent() ? parent()->tree() : tree_); }
@@ -498,10 +502,10 @@ struct UsingClause
QString signature_;
};
-class ClassNode : public InnerNode
+class ClassNode : public Aggregate
{
public:
- ClassNode(InnerNode* parent, const QString& name);
+ ClassNode(Aggregate* parent, const QString& name);
virtual ~ClassNode() { }
virtual bool isClass() const Q_DECL_OVERRIDE { return true; }
virtual bool isWrapper() const Q_DECL_OVERRIDE { return wrapper_; }
@@ -544,13 +548,13 @@ private:
QmlTypeNode* qmlelement;
};
-class DocumentNode : public InnerNode
+class DocumentNode : public Aggregate
{
public:
- DocumentNode(InnerNode* parent,
+ DocumentNode(Aggregate* parent,
const QString& name,
- SubType subType,
+ DocSubtype docSubtype,
PageType ptype);
virtual ~DocumentNode() { }
@@ -558,7 +562,7 @@ public:
virtual void setTitle(const QString &title) Q_DECL_OVERRIDE;
virtual void setSubTitle(const QString &subTitle) Q_DECL_OVERRIDE { subtitle_ = subTitle; }
- SubType subType() const Q_DECL_OVERRIDE { return nodeSubtype_; }
+ DocSubtype docSubtype() const Q_DECL_OVERRIDE { return nodeSubtype_; }
virtual QString title() const Q_DECL_OVERRIDE { return title_; }
virtual QString fullTitle() const Q_DECL_OVERRIDE;
virtual QString subTitle() const Q_DECL_OVERRIDE;
@@ -566,13 +570,13 @@ public:
virtual QString nameForLists() const Q_DECL_OVERRIDE { return title(); }
virtual void setImageFileName(const QString& ) { }
- virtual bool isHeaderFile() const Q_DECL_OVERRIDE { return (subType() == Node::HeaderFile); }
- virtual bool isExample() const Q_DECL_OVERRIDE { return (subType() == Node::Example); }
+ virtual bool isHeaderFile() const Q_DECL_OVERRIDE { return (docSubtype() == Node::HeaderFile); }
+ virtual bool isExample() const Q_DECL_OVERRIDE { return (docSubtype() == Node::Example); }
virtual bool isExampleFile() const Q_DECL_OVERRIDE { return (parent() && parent()->isExample()); }
virtual bool isExternalPage() const Q_DECL_OVERRIDE { return nodeSubtype_ == ExternalPage; }
protected:
- SubType nodeSubtype_;
+ DocSubtype nodeSubtype_;
QString title_;
QString subtitle_;
};
@@ -580,7 +584,7 @@ protected:
class ExampleNode : public DocumentNode
{
public:
- ExampleNode(InnerNode* parent, const QString& name)
+ ExampleNode(Aggregate* parent, const QString& name)
: DocumentNode(parent, name, Node::Example, Node::ExamplePage) { }
virtual ~ExampleNode() { }
virtual QString imageFileName() const Q_DECL_OVERRIDE { return imageFileName_; }
@@ -610,10 +614,10 @@ struct ImportRec {
typedef QList<ImportRec> ImportList;
-class QmlTypeNode : public InnerNode
+class QmlTypeNode : public Aggregate
{
public:
- QmlTypeNode(InnerNode* parent, const QString& name);
+ QmlTypeNode(Aggregate* parent, const QString& name);
virtual ~QmlTypeNode();
virtual bool isQmlType() const Q_DECL_OVERRIDE { return genus() == Node::QML; }
virtual bool isJsType() const Q_DECL_OVERRIDE { return genus() == Node::JS; }
@@ -665,17 +669,17 @@ private:
ImportList importList_;
};
-class QmlBasicTypeNode : public InnerNode
+class QmlBasicTypeNode : public Aggregate
{
public:
- QmlBasicTypeNode(InnerNode* parent,
+ QmlBasicTypeNode(Aggregate* parent,
const QString& name);
virtual ~QmlBasicTypeNode() { }
virtual bool isQmlBasicType() const Q_DECL_OVERRIDE { return (genus() == Node::QML); }
virtual bool isJsBasicType() const Q_DECL_OVERRIDE { return (genus() == Node::JS); }
};
-class QmlPropertyGroupNode : public InnerNode
+class QmlPropertyGroupNode : public Aggregate
{
public:
QmlPropertyGroupNode(QmlTypeNode* parent, const QString& name);
@@ -705,7 +709,7 @@ class QmlPropertyNode : public LeafNode
Q_DECLARE_TR_FUNCTIONS(QDoc::QmlPropertyNode)
public:
- QmlPropertyNode(InnerNode *parent,
+ QmlPropertyNode(Aggregate *parent,
const QString& name,
const QString& type,
bool attached);
@@ -760,65 +764,65 @@ class EnumItem
public:
EnumItem() { }
EnumItem(const QString& name, const QString& value)
- : nam(name), val(value) { }
+ : name_(name), value_(value) { }
- const QString& name() const { return nam; }
- const QString& value() const { return val; }
+ const QString& name() const { return name_; }
+ const QString& value() const { return value_; }
private:
- QString nam;
- QString val;
+ QString name_;
+ QString value_;
};
class EnumNode : public LeafNode
{
public:
- EnumNode(InnerNode* parent, const QString& name);
+ EnumNode(Aggregate* parent, const QString& name);
virtual ~EnumNode() { }
void addItem(const EnumItem& item);
void setFlagsType(TypedefNode* typedeff);
- bool hasItem(const QString &name) const { return names.contains(name); }
+ bool hasItem(const QString &name) const { return names_.contains(name); }
+ virtual bool isEnumType() const Q_DECL_OVERRIDE { return true; }
- const QList<EnumItem>& items() const { return itms; }
+ const QList<EnumItem>& items() const { return items_; }
Access itemAccess(const QString& name) const;
- const TypedefNode* flagsType() const { return ft; }
+ const TypedefNode* flagsType() const { return flagsType_; }
QString itemValue(const QString &name) const;
private:
- QList<EnumItem> itms;
- QSet<QString> names;
- const TypedefNode* ft;
+ QList<EnumItem> items_;
+ QSet<QString> names_;
+ const TypedefNode* flagsType_;
};
class TypedefNode : public LeafNode
{
public:
- TypedefNode(InnerNode* parent, const QString& name);
+ TypedefNode(Aggregate* parent, const QString& name);
virtual ~TypedefNode() { }
- const EnumNode* associatedEnum() const { return ae; }
+ const EnumNode* associatedEnum() const { return associatedEnum_; }
private:
- void setAssociatedEnum(const EnumNode* enume);
+ void setAssociatedEnum(const EnumNode* t);
friend class EnumNode;
- const EnumNode* ae;
+ const EnumNode* associatedEnum_;
};
-inline void EnumNode::setFlagsType(TypedefNode* typedeff)
+inline void EnumNode::setFlagsType(TypedefNode* t)
{
- ft = typedeff;
- typedeff->setAssociatedEnum(this);
+ flagsType_ = t;
+ t->setAssociatedEnum(this);
}
-
class Parameter
{
public:
Parameter() {}
- Parameter(const QString& leftType,
+ Parameter(const QString& dataType,
const QString& rightType = QString(),
const QString& name = QString(),
const QString& defaultValue = QString());
@@ -826,23 +830,26 @@ public:
Parameter& operator=(const Parameter& p);
- void setName(const QString& name) { nam = name; }
+ void setName(const QString& name) { name_ = name; }
- bool hasType() const { return lef.length() + rig.length() > 0; }
- const QString& leftType() const { return lef; }
- const QString& rightType() const { return rig; }
- const QString& name() const { return nam; }
- const QString& defaultValue() const { return def; }
+ bool hasType() const { return dataType_.length() + rightType_.length() > 0; }
+ const QString& dataType() const { return dataType_; }
+ const QString& rightType() const { return rightType_; }
+ const QString& name() const { return name_; }
+ const QString& defaultValue() const { return defaultValue_; }
QString reconstruct(bool value = false) const;
-private:
- QString lef;
- QString rig;
- QString nam;
- QString def;
+ public:
+ QString dataType_;
+ QString rightType_; // mws says remove this 04/08/2015
+ QString name_;
+ QString defaultValue_;
};
+//friend class QTypeInfo<Parameter>;
+//Q_DECLARE_TYPEINFO(Parameter, Q_MOVABLE_TYPE);
+
class FunctionNode : public LeafNode
{
public:
@@ -855,35 +862,37 @@ public:
MacroWithParams,
MacroWithoutParams,
Native };
- enum Virtualness { NonVirtual, ImpureVirtual, PureVirtual };
+ enum Virtualness { NonVirtual, NormalVirtual, PureVirtual };
- FunctionNode(InnerNode* parent, const QString &name);
- FunctionNode(Type type, InnerNode* parent, const QString &name, bool attached);
+ FunctionNode(Aggregate* parent, const QString &name);
+ FunctionNode(NodeType type, Aggregate* parent, const QString &name, bool attached);
virtual ~FunctionNode() { }
- void setReturnType(const QString& returnType) { rt = returnType; }
- void setParentPath(const QStringList& parentPath) { pp = parentPath; }
- void setMetaness(Metaness metaness) { met = metaness; }
- void setVirtualness(Virtualness virtualness);
- void setConst(bool conste) { con = conste; }
- void setStatic(bool statique) { sta = statique; }
- void setOverload(bool overlode);
- void setReimp(bool r);
+ void setReturnType(const QString& t) { returnType_ = t; }
+ void setParentPath(const QStringList& p) { parentPath_ = p; }
+ void setMetaness(Metaness t) { metaness_ = t; }
+ void setVirtualness(Virtualness v);
+ void setConst(bool b) { const_ = b; }
+ void setStatic(bool b) { static_ = b; }
+ unsigned char overloadNumber() const { return overloadNumber_; }
+ void setOverloadFlag(bool b) { overload_ = b; }
+ void setOverloadNumber(unsigned char n) { overloadNumber_ = n; }
+ void setReimplemented(bool b);
void addParameter(const Parameter& parameter);
- inline void setParameters(const QList<Parameter>& parameters);
+ inline void setParameters(const QVector<Parameter>& parameters);
void borrowParameterNames(const FunctionNode* source);
void setReimplementedFrom(FunctionNode* from);
- const QString& returnType() const { return rt; }
- Metaness metaness() const { return met; }
+ const QString& returnType() const { return returnType_; }
+ Metaness metaness() const { return metaness_; }
bool isMacro() const {
- return met == MacroWithParams || met == MacroWithoutParams;
+ return metaness_ == MacroWithParams || metaness_ == MacroWithoutParams;
}
- Virtualness virtualness() const { return vir; }
- bool isConst() const { return con; }
- bool isStatic() const { return sta; }
- bool isOverload() const { return ove; }
- bool isReimp() const Q_DECL_OVERRIDE { return reimp; }
+ Virtualness virtualness() const { return virtualness_; }
+ bool isConst() const { return const_; }
+ bool isStatic() const { return static_; }
+ bool isOverload() const { return overload_; }
+ bool isReimplemented() const Q_DECL_OVERRIDE { return reimplemented_; }
bool isFunction() const Q_DECL_OVERRIDE { return true; }
virtual bool isQmlSignal() const Q_DECL_OVERRIDE {
return (type() == Node::QmlSignal) && (genus() == Node::QML);
@@ -903,17 +912,20 @@ public:
virtual bool isJsMethod() const Q_DECL_OVERRIDE {
return (type() == Node::QmlMethod) && (genus() == Node::JS);
}
- int overloadNumber() const;
- const QList<Parameter>& parameters() const { return params; }
- void clearParams() { params.clear(); }
+ const QVector<Parameter>& parameters() const { return parameters_; }
+ void clearParams() { parameters_.clear(); }
QStringList parameterNames() const;
QString rawParameters(bool names = false, bool values = false) const;
- const FunctionNode* reimplementedFrom() const { return rf; }
- const QList<FunctionNode*> &reimplementedBy() const { return rb; }
- const PropertyNode* associatedProperty() const { return ap; }
- const QStringList& parentPath() const { return pp; }
-
- QStringList reconstructParams(bool values = false) const;
+ const FunctionNode* reimplementedFrom() const { return reimplementedFrom_; }
+ const QList<FunctionNode*> &reimplementedBy() const { return reimplementedBy_; }
+ const PropNodeList& associatedProperties() const { return associatedProperties_; }
+ const QStringList& parentPath() const { return parentPath_; }
+ bool hasAssociatedProperties() const { return !associatedProperties_.isEmpty(); }
+ bool hasOneAssociatedProperty() const { return (associatedProperties_.size() == 1); }
+ PropertyNode* firstAssociatedProperty() const { return associatedProperties_[0]; }
+ bool hasActiveAssociatedProperty() const;
+
+ QStringList reconstructParameters(bool values = false) const;
QString signature(bool values = false) const;
virtual QString element() const Q_DECL_OVERRIDE { return parent()->name(); }
virtual bool isAttached() const Q_DECL_OVERRIDE { return attached_; }
@@ -934,25 +946,26 @@ public:
void debug() const;
private:
- void setAssociatedProperty(PropertyNode* property);
+ void addAssociatedProperty(PropertyNode* property);
- friend class InnerNode;
+ friend class Aggregate;
friend class PropertyNode;
- QString rt;
- QStringList pp;
- Metaness met;
- Virtualness vir;
- bool con : 1;
- bool sta : 1;
- bool ove : 1;
- bool reimp: 1;
+ QString returnType_;
+ QStringList parentPath_;
+ Metaness metaness_;
+ Virtualness virtualness_;
+ bool const_ : 1;
+ bool static_ : 1;
+ bool reimplemented_: 1;
bool attached_: 1;
bool privateSignal_: 1;
- QList<Parameter> params;
- const FunctionNode* rf;
- const PropertyNode* ap;
- QList<FunctionNode*> rb;
+ bool overload_ : 1;
+ unsigned char overloadNumber_;
+ QVector<Parameter> parameters_;
+ const FunctionNode* reimplementedFrom_;
+ PropNodeList associatedProperties_;
+ QList<FunctionNode*> reimplementedBy_;
};
class PropertyNode : public LeafNode
@@ -961,7 +974,7 @@ public:
enum FunctionRole { Getter, Setter, Resetter, Notifier };
enum { NumFunctionRoles = Notifier + 1 };
- PropertyNode(InnerNode* parent, const QString& name);
+ PropertyNode(Aggregate* parent, const QString& name);
virtual ~PropertyNode() { }
virtual void setDataType(const QString& dataType) Q_DECL_OVERRIDE { type_ = dataType; }
@@ -974,30 +987,31 @@ public:
void setWritable(bool writable) { writable_ = toFlagValue(writable); }
void setUser(bool user) { user_ = toFlagValue(user); }
void setOverriddenFrom(const PropertyNode* baseProperty);
- void setRuntimeDesFunc(const QString& rdf) { runtimeDesFunc = rdf; }
- void setRuntimeScrFunc(const QString& scrf) { runtimeScrFunc = scrf; }
- void setConstant() { cst = true; }
- void setFinal() { fnl = true; }
- void setRevision(int revision) { rev = revision; }
+ void setRuntimeDesFunc(const QString& rdf) { runtimeDesFunc_ = rdf; }
+ void setRuntimeScrFunc(const QString& scrf) { runtimeScrFunc_ = scrf; }
+ void setConstant() { const_ = true; }
+ void setFinal() { final_ = true; }
+ void setRevision(int revision) { revision_ = revision; }
const QString &dataType() const { return type_; }
QString qualifiedDataType() const;
NodeList functions() const;
- NodeList functions(FunctionRole role) const { return funcs[(int)role]; }
+ NodeList functions(FunctionRole role) const { return functions_[(int)role]; }
NodeList getters() const { return functions(Getter); }
NodeList setters() const { return functions(Setter); }
NodeList resetters() const { return functions(Resetter); }
NodeList notifiers() const { return functions(Notifier); }
+ FunctionRole role(const FunctionNode* fn) const;
bool isStored() const { return fromFlagValue(stored_, storedDefault()); }
bool isDesignable() const { return fromFlagValue(designable_, designableDefault()); }
bool isScriptable() const { return fromFlagValue(scriptable_, scriptableDefault()); }
- const QString& runtimeDesignabilityFunction() const { return runtimeDesFunc; }
- const QString& runtimeScriptabilityFunction() const { return runtimeScrFunc; }
+ const QString& runtimeDesignabilityFunction() const { return runtimeDesFunc_; }
+ const QString& runtimeScriptabilityFunction() const { return runtimeScrFunc_; }
bool isWritable() const { return fromFlagValue(writable_, writableDefault()); }
bool isUser() const { return fromFlagValue(user_, userDefault()); }
- bool isConstant() const { return cst; }
- bool isFinal() const { return fnl; }
- const PropertyNode* overriddenFrom() const { return overrides; }
+ bool isConstant() const { return const_; }
+ bool isFinal() const { return final_; }
+ const PropertyNode* overriddenFrom() const { return overrides_; }
bool storedDefault() const { return true; }
bool userDefault() const { return false; }
@@ -1007,68 +1021,68 @@ public:
private:
QString type_;
- QString runtimeDesFunc;
- QString runtimeScrFunc;
- NodeList funcs[NumFunctionRoles];
+ QString runtimeDesFunc_;
+ QString runtimeScrFunc_;
+ NodeList functions_[NumFunctionRoles];
FlagValue stored_;
FlagValue designable_;
FlagValue scriptable_;
FlagValue writable_;
FlagValue user_;
- bool cst;
- bool fnl;
- int rev;
- const PropertyNode* overrides;
+ bool const_;
+ bool final_;
+ int revision_;
+ const PropertyNode* overrides_;
};
-inline void FunctionNode::setParameters(const QList<Parameter> &parameters)
+inline void FunctionNode::setParameters(const QVector<Parameter> &p)
{
- params = parameters;
+ parameters_ = p;
}
inline void PropertyNode::addFunction(FunctionNode* function, FunctionRole role)
{
- funcs[(int)role].append(function);
- function->setAssociatedProperty(this);
+ functions_[(int)role].append(function);
+ function->addAssociatedProperty(this);
}
inline void PropertyNode::addSignal(FunctionNode* function, FunctionRole role)
{
- funcs[(int)role].append(function);
- function->setAssociatedProperty(this);
+ functions_[(int)role].append(function);
+ function->addAssociatedProperty(this);
}
inline NodeList PropertyNode::functions() const
{
NodeList list;
for (int i = 0; i < NumFunctionRoles; ++i)
- list += funcs[i];
+ list += functions_[i];
return list;
}
class VariableNode : public LeafNode
{
public:
- VariableNode(InnerNode* parent, const QString &name);
+ VariableNode(Aggregate* parent, const QString &name);
virtual ~VariableNode() { }
- void setLeftType(const QString &leftType) { lt = leftType; }
- void setRightType(const QString &rightType) { rt = rightType; }
- void setStatic(bool statique) { sta = statique; }
+ void setLeftType(const QString &leftType) { lrftType_ = leftType; }
+ void setRightType(const QString &rightType) { rightType_ = rightType; }
+ void setStatic(bool b) { static_ = b; }
- const QString &leftType() const { return lt; }
- const QString &rightType() const { return rt; }
- QString dataType() const { return lt + rt; }
- bool isStatic() const { return sta; }
+ const QString &leftType() const { return lrftType_; }
+ const QString &rightType() const { return rightType_; }
+ QString dataType() const { return lrftType_ + rightType_; }
+ bool isStatic() const { return static_; }
private:
- QString lt;
- QString rt;
- bool sta;
+ QString lrftType_;
+ QString rightType_;
+ bool static_;
};
-inline VariableNode::VariableNode(InnerNode* parent, const QString &name)
- : LeafNode(Variable, parent, name), sta(false)
+inline VariableNode::VariableNode(Aggregate* parent, const QString &name)
+ : LeafNode(Variable, parent, name), static_(false)
{
setGenus(Node::CPP);
}
@@ -1076,20 +1090,21 @@ inline VariableNode::VariableNode(InnerNode* parent, const QString &name)
class DitaMapNode : public DocumentNode
{
public:
- DitaMapNode(InnerNode* parent, const QString& name)
+ DitaMapNode(Aggregate* parent, const QString& name)
: DocumentNode(parent, name, Node::Page, Node::DitaMapPage) { }
virtual ~DitaMapNode() { }
const DitaRefList& map() const { return doc().ditamap(); }
};
-class CollectionNode : public InnerNode
+class CollectionNode : public Aggregate
{
public:
- CollectionNode(Type type,
- InnerNode* parent,
+ CollectionNode(NodeType type,
+ Aggregate* parent,
const QString& name,
- Genus genus) : InnerNode(type, parent, name), seen_(false)
+ Genus genus)
+ : Aggregate(type, parent, name), seen_(false), noAutoList_(false)
{
setPageType(Node::OverviewPage);
setGenus(genus);
@@ -1108,7 +1123,7 @@ class CollectionNode : public InnerNode
virtual bool hasNamespaces() const Q_DECL_OVERRIDE;
virtual bool hasClasses() const Q_DECL_OVERRIDE;
virtual void getMemberNamespaces(NodeMap& out) Q_DECL_OVERRIDE;
- virtual void getMemberClasses(NodeMap& out) Q_DECL_OVERRIDE;
+ virtual void getMemberClasses(NodeMap& out) const Q_DECL_OVERRIDE;
virtual bool wasSeen() const Q_DECL_OVERRIDE { return seen_; }
virtual QString title() const Q_DECL_OVERRIDE { return title_; }
virtual QString subTitle() const Q_DECL_OVERRIDE { return subtitle_; }
@@ -1132,9 +1147,12 @@ class CollectionNode : public InnerNode
void markSeen() { seen_ = true; }
void markNotSeen() { seen_ = false; }
+ bool noAutoList() const { return noAutoList_; }
+ virtual void setNoAutoList(bool b) Q_DECL_OVERRIDE { noAutoList_ = b; }
private:
bool seen_;
+ bool noAutoList_;
QString title_;
QString subtitle_;
NodeList members_;
diff --git a/src/tools/qdoc/openedlist.h b/src/tools/qdoc/openedlist.h
index ee45714cfd..3a564b018d 100644
--- a/src/tools/qdoc/openedlist.h
+++ b/src/tools/qdoc/openedlist.h
@@ -79,6 +79,7 @@ private:
QString pref;
QString suff;
};
+Q_DECLARE_TYPEINFO(OpenedList, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/plaincodemarker.cpp b/src/tools/qdoc/plaincodemarker.cpp
index 94561c3f48..bf2a55b2d5 100644
--- a/src/tools/qdoc/plaincodemarker.cpp
+++ b/src/tools/qdoc/plaincodemarker.cpp
@@ -58,7 +58,7 @@ bool PlainCodeMarker::recognizeLanguage( const QString& /* lang */ )
return false;
}
-Atom::Type PlainCodeMarker::atomType() const
+Atom::AtomType PlainCodeMarker::atomType() const
{
return Atom::Code;
}
@@ -109,7 +109,7 @@ QString PlainCodeMarker::functionEndRegExp( const QString& /* funcName */ )
return QString();
}
-QList<Section> PlainCodeMarker::sections(const InnerNode * /* innerNode */,
+QList<Section> PlainCodeMarker::sections(const Aggregate * /* innerNode */,
SynopsisStyle /* style */,
Status /* status */)
{
diff --git a/src/tools/qdoc/plaincodemarker.h b/src/tools/qdoc/plaincodemarker.h
index 6d41b3dd81..b83a3e4697 100644
--- a/src/tools/qdoc/plaincodemarker.h
+++ b/src/tools/qdoc/plaincodemarker.h
@@ -51,7 +51,7 @@ public:
bool recognizeCode( const QString& code ) Q_DECL_OVERRIDE;
bool recognizeExtension( const QString& ext ) Q_DECL_OVERRIDE;
bool recognizeLanguage( const QString& lang ) Q_DECL_OVERRIDE;
- Atom::Type atomType() const Q_DECL_OVERRIDE;
+ Atom::AtomType atomType() const Q_DECL_OVERRIDE;
QString markedUpCode( const QString& code, const Node *relative, const Location &location ) Q_DECL_OVERRIDE;
QString markedUpSynopsis( const Node *node, const Node *relative,
SynopsisStyle style ) Q_DECL_OVERRIDE;
@@ -61,7 +61,7 @@ public:
QString markedUpIncludes( const QStringList& includes ) Q_DECL_OVERRIDE;
QString functionBeginRegExp( const QString& funcName ) Q_DECL_OVERRIDE;
QString functionEndRegExp( const QString& funcName ) Q_DECL_OVERRIDE;
- QList<Section> sections(const InnerNode *innerNode, SynopsisStyle style, Status status) Q_DECL_OVERRIDE;
+ QList<Section> sections(const Aggregate *innerNode, SynopsisStyle style, Status status) Q_DECL_OVERRIDE;
};
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/puredocparser.cpp b/src/tools/qdoc/puredocparser.cpp
index e47460efb2..80a7ec4bf5 100644
--- a/src/tools/qdoc/puredocparser.cpp
+++ b/src/tools/qdoc/puredocparser.cpp
@@ -149,12 +149,6 @@ bool PureDocParser::processQdocComments()
isJsPropertyTopic = true;
}
}
- if ((isQmlPropertyTopic || isJsPropertyTopic) && topics.size() > 1) {
- qDebug() << "MULTIPLE TOPICS:" << doc.location().fileName() << doc.location().lineNo();
- for (int i=0; i<topics.size(); ++i) {
- qDebug() << " " << topics[i].topic << topics[i].args;
- }
- }
NodeList nodes;
DocList docs;
@@ -207,14 +201,14 @@ bool PureDocParser::processQdocComments()
processOtherMetaCommands(*d, *n);
(*n)->setDoc(*d);
checkModuleInclusion(*n);
- if ((*n)->isInnerNode() && ((InnerNode *)*n)->includes().isEmpty()) {
- InnerNode *m = static_cast<InnerNode *>(*n);
+ if ((*n)->isAggregate() && ((Aggregate *)*n)->includes().isEmpty()) {
+ Aggregate *m = static_cast<Aggregate *>(*n);
while (m->parent() && m->parent() != treeRoot)
m = m->parent();
if (m == *n)
- ((InnerNode *)*n)->addInclude((*n)->name());
+ ((Aggregate *)*n)->addInclude((*n)->name());
else
- ((InnerNode *)*n)->setIncludes(m->includes());
+ ((Aggregate *)*n)->setIncludes(m->includes());
}
++d;
++n;
diff --git a/src/tools/qdoc/qdoc.pro b/src/tools/qdoc/qdoc.pro
index f0df113af8..634d30a9a3 100644
--- a/src/tools/qdoc/qdoc.pro
+++ b/src/tools/qdoc/qdoc.pro
@@ -1,11 +1,10 @@
!force_bootstrap {
load(qfeatures)
requires(!contains(QT_DISABLED_FEATURES, xmlstreamwriter))
- requires(!contains(QT_DISABLED_FEATURES, dom))
}
option(host_build)
-QT = core xml
+QT = core
DEFINES += \
QT_QMLDEVTOOLS_LIB \ # force static exports even if not bootstrapping
diff --git a/src/tools/qdoc/qdocdatabase.cpp b/src/tools/qdoc/qdocdatabase.cpp
index bf84fa8335..5ca8e36ef9 100644
--- a/src/tools/qdoc/qdocdatabase.cpp
+++ b/src/tools/qdoc/qdocdatabase.cpp
@@ -167,7 +167,7 @@ void QDocForest::setSearchOrder(QStringList& t)
forest_.remove(primaryName);
QMap<QString, Tree*>::iterator i;
- foreach (QString m, t) {
+ foreach (const QString &m, t) {
if (primaryName != m) {
i = forest_.find(m);
if (i != forest_.end()) {
@@ -276,7 +276,7 @@ const QVector<Tree*>& QDocForest::indexSearchOrder()
NamespaceNode* QDocForest::newIndexTree(const QString& module)
{
primaryTree_ = new Tree(module, qdb_);
- forest_.insert(module, primaryTree_);
+ forest_.insert(module.toLower(), primaryTree_);
return primaryTree_->root();
}
@@ -380,6 +380,30 @@ QString QDocForest::getLinkCounts(QStringList& strings, QVector<int>& counts)
return depends;
}
+/*!
+ */
+const Node* QDocForest::findFunctionNode(const QString& target,
+ const Node* relative,
+ Node::Genus genus)
+{
+ QString function, params;
+ int length = target.length();
+ if (target.endsWith(QChar(')'))) {
+ int position = target.lastIndexOf(QChar('('));
+ params = target.mid(position+1, length-position-2);
+ function = target.left(position);
+ }
+ else
+ function = target;
+ foreach (Tree* t, searchOrder()) {
+ const Node* n = t->findFunctionNode(function, params, relative, genus);
+ if (n)
+ return n;
+ relative = 0;
+ }
+ return 0;
+}
+
/*! \class QDocDatabase
This class provides exclusive access to the qdoc database,
which consists of a forrest of trees and a lot of maps and
@@ -815,7 +839,7 @@ void QDocDatabase::processForest()
mode, each tree is analyzed in turn, and its classes and
types are added to the appropriate node maps.
*/
-void QDocDatabase::processForest(void (QDocDatabase::*func) (InnerNode*))
+void QDocDatabase::processForest(void (QDocDatabase::*func) (Aggregate*))
{
Tree* t = forest_.firstTree();
while (t) {
@@ -930,7 +954,7 @@ NodeMultiMap& QDocDatabase::getCppClasses()
Finds all the C++ class nodes and QML type nodes and
sorts them into maps.
*/
-void QDocDatabase::findAllClasses(InnerNode* node)
+void QDocDatabase::findAllClasses(Aggregate* node)
{
NodeList::const_iterator c = node->childNodes().constBegin();
while (c != node->childNodes().constEnd()) {
@@ -957,8 +981,8 @@ void QDocDatabase::findAllClasses(InnerNode* node)
if ((*c)->isQmlBasicType() || (*c)->isJsType())
qmlBasicTypes_.insert(qmlTypeName,*c);
}
- else if ((*c)->isInnerNode()) {
- findAllClasses(static_cast<InnerNode*>(*c));
+ else if ((*c)->isAggregate()) {
+ findAllClasses(static_cast<Aggregate*>(*c));
}
}
++c;
@@ -978,13 +1002,13 @@ NodeMapMap& QDocDatabase::getFunctionIndex()
/*!
Finds all the function nodes
*/
-void QDocDatabase::findAllFunctions(InnerNode* node)
+void QDocDatabase::findAllFunctions(Aggregate* node)
{
NodeList::ConstIterator c = node->childNodes().constBegin();
while (c != node->childNodes().constEnd()) {
if ((*c)->access() != Node::Private) {
- if ((*c)->isInnerNode()) {
- findAllFunctions(static_cast<InnerNode*>(*c));
+ if ((*c)->isAggregate()) {
+ findAllFunctions(static_cast<Aggregate*>(*c));
}
else if ((*c)->type() == Node::Function) {
const FunctionNode* func = static_cast<const FunctionNode*>(*c);
@@ -1004,15 +1028,15 @@ void QDocDatabase::findAllFunctions(InnerNode* node)
Finds all the nodes containing legalese text and puts them
in a map.
*/
-void QDocDatabase::findAllLegaleseTexts(InnerNode* node)
+void QDocDatabase::findAllLegaleseTexts(Aggregate* node)
{
NodeList::ConstIterator c = node->childNodes().constBegin();
while (c != node->childNodes().constEnd()) {
if ((*c)->access() != Node::Private) {
if (!(*c)->doc().legaleseText().isEmpty())
legaleseTexts_.insertMulti((*c)->doc().legaleseText(), *c);
- if ((*c)->isInnerNode())
- findAllLegaleseTexts(static_cast<InnerNode *>(*c));
+ if ((*c)->isAggregate())
+ findAllLegaleseTexts(static_cast<Aggregate *>(*c));
}
++c;
}
@@ -1021,13 +1045,13 @@ void QDocDatabase::findAllLegaleseTexts(InnerNode* node)
/*!
Finds all the namespace nodes and puts them in an index.
*/
-void QDocDatabase::findAllNamespaces(InnerNode* node)
+void QDocDatabase::findAllNamespaces(Aggregate* node)
{
NodeList::ConstIterator c = node->childNodes().constBegin();
while (c != node->childNodes().constEnd()) {
if ((*c)->access() != Node::Private || (*c)->isNamespace()) {
- if ((*c)->isInnerNode()) {
- findAllNamespaces(static_cast<InnerNode *>(*c));
+ if ((*c)->isAggregate()) {
+ findAllNamespaces(static_cast<Aggregate *>(*c));
if ((*c)->isNamespace()) {
// Ensure that the namespace's name is not empty (the root
// namespace has no name).
@@ -1046,7 +1070,7 @@ void QDocDatabase::findAllNamespaces(InnerNode* node)
maps. They can be C++ classes, QML types, or they can be
functions, enum types, typedefs, methods, etc.
*/
-void QDocDatabase::findAllObsoleteThings(InnerNode* node)
+void QDocDatabase::findAllObsoleteThings(Aggregate* node)
{
NodeList::const_iterator c = node->childNodes().constBegin();
while (c != node->childNodes().constEnd()) {
@@ -1067,7 +1091,7 @@ void QDocDatabase::findAllObsoleteThings(InnerNode* node)
}
}
else if ((*c)->type() == Node::Class) {
- InnerNode* n = static_cast<InnerNode*>(*c);
+ Aggregate* n = static_cast<Aggregate*>(*c);
bool inserted = false;
NodeList::const_iterator p = n->childNodes().constBegin();
while (p != n->childNodes().constEnd()) {
@@ -1096,7 +1120,7 @@ void QDocDatabase::findAllObsoleteThings(InnerNode* node)
}
}
else if ((*c)->isQmlType() || (*c)->isJsType()) {
- InnerNode* n = static_cast<InnerNode*>(*c);
+ Aggregate* n = static_cast<Aggregate*>(*c);
bool inserted = false;
NodeList::const_iterator p = n->childNodes().constBegin();
while (p != n->childNodes().constEnd()) {
@@ -1127,8 +1151,8 @@ void QDocDatabase::findAllObsoleteThings(InnerNode* node)
++p;
}
}
- else if ((*c)->isInnerNode()) {
- findAllObsoleteThings(static_cast<InnerNode*>(*c));
+ else if ((*c)->isAggregate()) {
+ findAllObsoleteThings(static_cast<Aggregate*>(*c));
}
}
++c;
@@ -1143,7 +1167,7 @@ void QDocDatabase::findAllObsoleteThings(InnerNode* node)
This function is used for generating the "New Classes... in x.y"
section on the \e{What's New in Qt x.y} page.
*/
-void QDocDatabase::findAllSince(InnerNode* node)
+void QDocDatabase::findAllSince(Aggregate* node)
{
NodeList::const_iterator child = node->childNodes().constBegin();
while (child != node->childNodes().constEnd()) {
@@ -1206,8 +1230,8 @@ void QDocDatabase::findAllSince(InnerNode* node)
}
}
// Recursively find child nodes with since commands.
- if ((*child)->isInnerNode())
- findAllSince(static_cast<InnerNode *>(*child));
+ if ((*child)->isAggregate())
+ findAllSince(static_cast<Aggregate *>(*child));
++child;
}
@@ -1264,9 +1288,17 @@ const NodeMap& QDocDatabase::getSinceMap(const QString& key)
to generating documentation.
*/
void QDocDatabase::resolveIssues() {
+ primaryTreeRoot()->normalizeOverloads();
+ fixInheritance();
+ resolveProperties();
+ primaryTreeRoot()->makeUndocumentedChildrenInternal();
resolveQmlInheritance(primaryTreeRoot());
primaryTree()->resolveTargets(primaryTreeRoot());
primaryTree()->resolveCppToQmlLinks();
+ if (!Generator::singleExec()) {
+ QDocIndexFiles::qdocIndexFiles()->resolveRelates();
+ QDocIndexFiles::destroyQDocIndexFiles();
+ }
}
void QDocDatabase::resolveStuff()
@@ -1291,7 +1323,7 @@ void QDocDatabase::resolveNamespaces()
t = forest_.nextTree();
}
QList<QString> keys = nmm_.uniqueKeys();
- foreach (QString s, keys) {
+ foreach (const QString &s, keys) {
NamespaceNode* ns = 0;
QList<Node*> nodes = nmm_.values(s);
int count = nmm_.remove(s);
@@ -1337,8 +1369,16 @@ void QDocDatabase::resolveNamespaces()
}
}
}
-
-
+#if 0
+/*!
+ */
+const Node* QDocDatabase::findFunctionNode(const QString& target,
+ const Node* relative,
+ Node::Genus genus)
+{
+ return forest_.findFunctionNode(target, relative, genus);
+}
+#endif
/*!
This function is called for autolinking to a \a type,
which could be a function return type or a parameter
@@ -1394,7 +1434,7 @@ const Node* QDocDatabase::findNodeForTarget(const QString& target, const Node* r
base type node. If the node is found in the tree, set the
node's QML base type node pointer.
*/
-void QDocDatabase::resolveQmlInheritance(InnerNode* root)
+void QDocDatabase::resolveQmlInheritance(Aggregate* root)
{
NodeMap previousSearches;
// Do we need recursion?
@@ -1458,7 +1498,6 @@ void QDocDatabase::readIndexes(const QStringList& t)
qDebug() << "This index file is already in memory:" << f;
}
QDocIndexFiles::qdocIndexFiles()->readIndexes(indexFiles);
- QDocIndexFiles::destroyQDocIndexFiles();
}
/*!
@@ -1515,7 +1554,7 @@ FunctionNode* QDocDatabase::findNodeInOpenNamespace(const QStringList& parentPat
This function only searches in the current primary tree.
*/
-Node* QDocDatabase::findNodeInOpenNamespace(QStringList& path, Node::Type type)
+Node* QDocDatabase::findNodeInOpenNamespace(QStringList& path, Node::NodeType type)
{
if (path.isEmpty())
return 0;
@@ -1574,6 +1613,13 @@ void QDocDatabase::mergeCollections(Node::Genus genus, CNMap& cnm, const Node* r
if (values.size() > 1) {
foreach (CollectionNode* v, values) {
if (v != n) {
+ // Allow multiple (major) versions of QML/JS modules
+ if (n->type() == Node::QmlModule
+ && n->logicalModuleIdentifier() != v->logicalModuleIdentifier()) {
+ if (v->wasSeen() && v != relative && !v->members().isEmpty())
+ cnm.insert(v->fullTitle().toLower(), v);
+ continue;
+ }
foreach (Node* t, v->members())
n->addMember(t);
}
@@ -1594,12 +1640,19 @@ void QDocDatabase::mergeCollections(Node::Genus genus, CNMap& cnm, const Node* r
Finds all the collection nodes with the same name
and genus as \a c and merges their members into the
members list of \a c.
+
+ For QML and JS modules, the merge is done only if
+ the module identifier matches between the nodes, to avoid
+ merging modules with different (major) versions.
*/
void QDocDatabase::mergeCollections(CollectionNode* c)
{
foreach (Tree* t, searchOrder()) {
CollectionNode* cn = t->getCollection(c->name(), c->genus());
if (cn && cn != c) {
+ if (cn->type() == Node::QmlModule
+ && cn->logicalModuleIdentifier() != c->logicalModuleIdentifier())
+ continue;
foreach (Node* n, cn->members())
c->addMember(n);
}
@@ -1622,11 +1675,13 @@ const Node* QDocDatabase::findNodeForAtom(const Atom* a, const Node* relative, Q
Atom* atom = const_cast<Atom*>(a);
QStringList targetPath = atom->string().split("#");
QString first = targetPath.first().trimmed();
+ if (Generator::debugging())
+ qDebug() << " first:" << first;
Tree* domain = 0;
Node::Genus genus = Node::DontCare;
// Reserved for future use
- //Node::Type goal = Node::NoType;
+ //Node::NodeType goal = Node::NoType;
if (atom->isLinkAtom()) {
domain = atom->domain();
@@ -1640,8 +1695,14 @@ const Node* QDocDatabase::findNodeForAtom(const Atom* a, const Node* relative, Q
else if (domain) {
if (first.endsWith(".html"))
node = domain->findNodeByNameAndType(QStringList(first), Node::Document);
- else if (first.endsWith("()"))
- node = domain->findFunctionNode(first, 0, genus);
+ else if (first.endsWith(QChar(')'))) {
+ QString function, params;
+ int length = first.length();
+ int position = first.lastIndexOf(QChar('('));
+ params = first.mid(position+1, length-position-2);
+ function = first.left(position);
+ node = domain->findFunctionNode(function, params, 0, genus);
+ }
else {
int flags = SearchBaseClasses | SearchEnumValues;
QStringList nodePath = first.split("::");
@@ -1664,8 +1725,11 @@ const Node* QDocDatabase::findNodeForAtom(const Atom* a, const Node* relative, Q
if (!node && first.contains("/"))
return findNodeForTarget(targetPath, relative, genus, ref);
}
- else if (first.endsWith("()"))
+ else if (first.endsWith(QChar(')'))) {
node = findFunctionNode(first, relative, genus);
+ if (Generator::debugging())
+ qDebug() << " node:" << node;
+ }
else {
node = findNodeForTarget(targetPath, relative, genus, ref);
return node;
diff --git a/src/tools/qdoc/qdocdatabase.h b/src/tools/qdoc/qdocdatabase.h
index b8ca8bc32d..80a92af4ed 100644
--- a/src/tools/qdoc/qdocdatabase.h
+++ b/src/tools/qdoc/qdocdatabase.h
@@ -103,7 +103,7 @@ class QDocForest
return 0;
}
- Node* findNodeByNameAndType(const QStringList& path, Node::Type type) {
+ Node* findNodeByNameAndType(const QStringList& path, Node::NodeType type) {
foreach (Tree* t, searchOrder()) {
Node* n = t->findNodeByNameAndType(path, type);
if (n)
@@ -130,9 +130,9 @@ class QDocForest
return 0;
}
- InnerNode* findRelatesNode(const QStringList& path) {
+ Aggregate* findRelatesNode(const QStringList& path) {
foreach (Tree* t, searchOrder()) {
- InnerNode* n = t->findRelatesNode(path);
+ Aggregate* n = t->findRelatesNode(path);
if (n)
return n;
}
@@ -141,15 +141,8 @@ class QDocForest
const Node* findFunctionNode(const QString& target,
const Node* relative,
- Node::Genus genus) {
- foreach (Tree* t, searchOrder()) {
- const Node* n = t->findFunctionNode(target, relative, genus);
- if (n)
- return n;
- relative = 0;
- }
- return 0;
- }
+ Node::Genus genus);
+
const Node* findNodeForTarget(QStringList& targetPath,
const Node* relative,
Node::Genus genus,
@@ -177,6 +170,16 @@ class QDocForest
return 0;
}
+ const CollectionNode* getCollectionNode(const QString& name, Node::Genus genus)
+ {
+ foreach (Tree* t, searchOrder()) {
+ const CollectionNode* cn = t->getCollection(name, genus);
+ if (cn)
+ return cn;
+ }
+ return 0;
+ }
+
QmlTypeNode* lookupQmlType(const QString& name)
{
foreach (Tree* t, searchOrder()) {
@@ -221,19 +224,11 @@ class QDocDatabase
Tree* findTree(const QString& t) { return forest_.findTree(t); }
- CollectionNode* getCollection(const QString& name, Node::Genus genus) {
- return primaryTree()->getCollection(name, genus);
- }
const CNMap& groups() { return primaryTree()->groups(); }
const CNMap& modules() { return primaryTree()->modules(); }
const CNMap& qmlModules() { return primaryTree()->qmlModules(); }
const CNMap& jsModules() { return primaryTree()->jsModules(); }
- CollectionNode* findGroup(const QString& name) { return primaryTree()->findGroup(name); }
- CollectionNode* findModule(const QString& name) { return primaryTree()->findModule(name); }
- CollectionNode* findQmlModule(const QString& name) { return primaryTree()->findQmlModule(name); }
- CollectionNode* findJsModule(const QString& name) { return primaryTree()->findJsModule(name); }
-
CollectionNode* addGroup(const QString& name) { return primaryTree()->addGroup(name); }
CollectionNode* addModule(const QString& name) { return primaryTree()->addModule(name); }
CollectionNode* addQmlModule(const QString& name) { return primaryTree()->addQmlModule(name); }
@@ -260,12 +255,12 @@ class QDocDatabase
QmlTypeNode* findQmlType(const ImportRec& import, const QString& name);
private:
- void findAllClasses(InnerNode *node);
- void findAllFunctions(InnerNode *node);
- void findAllLegaleseTexts(InnerNode *node);
- void findAllNamespaces(InnerNode *node);
- void findAllObsoleteThings(InnerNode* node);
- void findAllSince(InnerNode *node);
+ void findAllClasses(Aggregate *node);
+ void findAllFunctions(Aggregate *node);
+ void findAllLegaleseTexts(Aggregate *node);
+ void findAllNamespaces(Aggregate *node);
+ void findAllObsoleteThings(Aggregate* node);
+ void findAllSince(Aggregate *node);
public:
/*******************************************************************
@@ -289,7 +284,7 @@ class QDocDatabase
Many of these will be either eliminated or replaced.
********************************************************************/
void resolveInheritance() { primaryTree()->resolveInheritance(); }
- void resolveQmlInheritance(InnerNode* root);
+ void resolveQmlInheritance(Aggregate* root);
void resolveIssues();
void resolveStuff();
void fixInheritance() { primaryTree()->fixInheritance(); }
@@ -297,7 +292,7 @@ class QDocDatabase
void insertTarget(const QString& name,
const QString& title,
- TargetRec::Type type,
+ TargetRec::TargetType type,
Node* node,
int priority) {
primaryTree()->insertTarget(name, title, type, node, priority);
@@ -310,7 +305,7 @@ class QDocDatabase
return primaryTree()->findFunctionNode(parentPath, clone);
}
FunctionNode* findNodeInOpenNamespace(const QStringList& parentPath, const FunctionNode* clone);
- Node* findNodeInOpenNamespace(QStringList& path, Node::Type type);
+ Node* findNodeInOpenNamespace(QStringList& path, Node::NodeType type);
const Node* checkForCollision(const QString& name) {
return primaryTree()->checkForCollision(name);
}
@@ -327,7 +322,7 @@ class QDocDatabase
********************************************************************/
ClassNode* findClassNode(const QStringList& path) { return forest_.findClassNode(path); }
Node* findNodeForInclude(const QStringList& path) { return forest_.findNodeForInclude(path); }
- InnerNode* findRelatesNode(const QStringList& path) { return forest_.findRelatesNode(path); }
+ Aggregate* findRelatesNode(const QStringList& path) { return forest_.findRelatesNode(path); }
const Node* findFunctionNode(const QString& target, const Node* relative, Node::Genus genus) {
return forest_.findFunctionNode(target, relative, genus);
}
@@ -336,9 +331,12 @@ class QDocDatabase
const DocumentNode* findDocumentNodeByTitle(const QString& title) {
return forest_.findDocumentNodeByTitle(title);
}
- Node* findNodeByNameAndType(const QStringList& path, Node::Type type) {
+ Node* findNodeByNameAndType(const QStringList& path, Node::NodeType type) {
return forest_.findNodeByNameAndType(path, type);
}
+ const CollectionNode* getCollectionNode(const QString& name, Node::Genus genus) {
+ return forest_.getCollectionNode(name, genus);
+ }
private:
const Node* findNodeForTarget(QStringList& targetPath,
@@ -414,7 +412,7 @@ class QDocDatabase
Node::Genus genus) {
return forest_.findNode(path, relative, findFlags, genus);
}
- void processForest(void (QDocDatabase::*) (InnerNode*));
+ void processForest(void (QDocDatabase::*) (Aggregate*));
bool isLoaded(const QString& t) { return forest_.isLoaded(t); }
static void initializeDB();
diff --git a/src/tools/qdoc/qdocindexfiles.cpp b/src/tools/qdoc/qdocindexfiles.cpp
index 8961ff71ad..fc262d9834 100644
--- a/src/tools/qdoc/qdocindexfiles.cpp
+++ b/src/tools/qdoc/qdocindexfiles.cpp
@@ -31,7 +31,6 @@
**
****************************************************************************/
-#include "qdom.h"
#include "qxmlstream.h"
#include "qdocindexfiles.h"
#include "qdoctagfiles.h"
@@ -101,6 +100,7 @@ void QDocIndexFiles::destroyQDocIndexFiles()
*/
void QDocIndexFiles::readIndexes(const QStringList& indexFiles)
{
+ relatedList_.clear();
foreach (const QString& indexFile, indexFiles) {
QString msg = "Loading index file: " + indexFile;
Location::logToStdErr(msg);
@@ -117,72 +117,81 @@ static bool readingRoot = true;
void QDocIndexFiles::readIndexFile(const QString& path)
{
QFile file(path);
- if (file.open(QFile::ReadOnly)) {
- QDomDocument document;
- document.setContent(&file);
- file.close();
-
- QDomElement indexElement = document.documentElement();
-
- // Generate a relative URL between the install dir and the index file
- // when the -installdir command line option is set.
- QString indexUrl;
- if (Config::installDir.isEmpty()) {
- indexUrl = indexElement.attribute("url", QString());
- }
- else {
- // Use a fake directory, since we will copy the output to a sub directory of
- // installDir when using "make install". This is just for a proper relative path.
- //QDir installDir(path.section('/', 0, -3) + "/outputdir");
- QDir installDir(path.section('/', 0, -3) + '/' + Generator::outputSubdir());
- indexUrl = installDir.relativeFilePath(path).section('/', 0, -2);
- }
- project_ = indexElement.attribute("project", QString());
+ if (!file.open(QFile::ReadOnly)) {
+ qWarning() << "Could not read index file" << path;
+ return;
+ }
- basesList_.clear();
- relatedList_.clear();
+ QXmlStreamReader reader(&file);
+ reader.setNamespaceProcessing(false);
- readingRoot = true;
- NamespaceNode* root = qdb_->newIndexTree(project_);
-
- // Scan all elements in the XML file, constructing a map that contains
- // base classes for each class found.
- QDomElement child = indexElement.firstChildElement();
- while (!child.isNull()) {
- readIndexSection(child, root, indexUrl);
- child = child.nextSiblingElement();
- readingRoot = true;
- }
+ if (!reader.readNextStartElement())
+ return;
- // Now that all the base classes have been found for this index,
- // arrange them into an inheritance hierarchy.
- resolveIndex();
+ if (reader.name() != QLatin1String("INDEX"))
+ return;
+
+ QXmlStreamAttributes attrs = reader.attributes();
+
+ // Generate a relative URL between the install dir and the index file
+ // when the -installdir command line option is set.
+ QString indexUrl;
+ if (Config::installDir.isEmpty()) {
+ indexUrl = attrs.value(QLatin1String("url")).toString();
+ }
+ else {
+ // Use a fake directory, since we will copy the output to a sub directory of
+ // installDir when using "make install". This is just for a proper relative path.
+ //QDir installDir(path.section('/', 0, -3) + "/outputdir");
+ QDir installDir(path.section('/', 0, -3) + '/' + Generator::outputSubdir());
+ indexUrl = installDir.relativeFilePath(path).section('/', 0, -2);
+ }
+ project_ = attrs.value(QLatin1String("project")).toString();
+ basesList_.clear();
+
+ NamespaceNode* root = qdb_->newIndexTree(project_);
+
+ // Scan all elements in the XML file, constructing a map that contains
+ // base classes for each class found.
+ while (reader.readNextStartElement()) {
+ readingRoot = true;
+ readIndexSection(reader, root, indexUrl);
}
+
+ // Now that all the base classes have been found for this index,
+ // arrange them into an inheritance hierarchy.
+ resolveIndex();
}
/*!
Read a <section> element from the index file and create the
appropriate node(s).
*/
-void QDocIndexFiles::readIndexSection(const QDomElement& element,
+void QDocIndexFiles::readIndexSection(QXmlStreamReader& reader,
Node* current,
const QString& indexUrl)
{
- QString name = element.attribute("name");
- QString href = element.attribute("href");
+ QXmlStreamAttributes attributes = reader.attributes();
+ QStringRef elementName = reader.name();
+
+ QString name = attributes.value(QLatin1String("name")).toString();
+ QString href = attributes.value(QLatin1String("href")).toString();
Node* node;
Location location;
- InnerNode* parent = 0;
- if (current->isInnerNode())
- parent = static_cast<InnerNode*>(current);
+ Aggregate* parent = 0;
+
+ bool hasReadChildren = false;
+
+ if (current->isAggregate())
+ parent = static_cast<Aggregate*>(current);
QString filePath;
int lineNo = 0;
- if (element.hasAttribute("filepath")) {
- filePath = element.attribute("filepath", QString());
- lineNo = element.attribute("lineno", QString()).toInt();
+ if (attributes.hasAttribute(QLatin1String("filepath"))) {
+ filePath = attributes.value(QLatin1String("filepath")).toString();
+ lineNo = attributes.value("lineno").toInt();
}
- if (element.nodeName() == "namespace") {
+ if (elementName == QLatin1String("namespace")) {
node = new NamespaceNode(parent, name);
if (!indexUrl.isEmpty())
@@ -191,10 +200,10 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
location = Location(name.toLower() + ".html");
}
- else if (element.nodeName() == "class") {
+ else if (elementName == QLatin1String("class")) {
node = new ClassNode(parent, name);
- if (element.hasAttribute("bases")) {
- QString bases = element.attribute("bases");
+ if (attributes.hasAttribute(QLatin1String("bases"))) {
+ QString bases = attributes.value(QLatin1String("bases")).toString();
if (!bases.isEmpty())
basesList_.append(QPair<ClassNode*,QString>(static_cast<ClassNode*>(node), bases));
}
@@ -203,108 +212,108 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
else if (!indexUrl.isNull())
location = Location(name.toLower() + ".html");
bool abstract = false;
- if (element.attribute("abstract") == "true")
+ if (attributes.value(QLatin1String("abstract")) == QLatin1String("true"))
abstract = true;
node->setAbstract(abstract);
}
- else if (element.nodeName() == "qmlclass") {
+ else if (elementName == QLatin1String("qmlclass")) {
QmlTypeNode* qcn = new QmlTypeNode(parent, name);
- qcn->setTitle(element.attribute("title"));
- QString logicalModuleName = element.attribute("qml-module-name");
+ qcn->setTitle(attributes.value(QLatin1String("title")).toString());
+ QString logicalModuleName = attributes.value(QLatin1String("qml-module-name")).toString();
if (!logicalModuleName.isEmpty())
qdb_->addToQmlModule(logicalModuleName, qcn);
bool abstract = false;
- if (element.attribute("abstract") == "true")
+ if (attributes.value(QLatin1String("abstract")) == QLatin1String("true"))
abstract = true;
qcn->setAbstract(abstract);
- QString qmlFullBaseName = element.attribute("qml-base-type");
+ QString qmlFullBaseName = attributes.value(QLatin1String("qml-base-type")).toString();
if (!qmlFullBaseName.isEmpty()) {
qcn->setQmlBaseName(qmlFullBaseName);
}
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qcn;
}
- else if (element.nodeName() == "jstype") {
+ else if (elementName == QLatin1String("jstype")) {
QmlTypeNode* qcn = new QmlTypeNode(parent, name);
qcn->setGenus(Node::JS);
- qcn->setTitle(element.attribute("title"));
- QString logicalModuleName = element.attribute("js-module-name");
+ qcn->setTitle(attributes.value(QLatin1String("title")).toString());
+ QString logicalModuleName = attributes.value(QLatin1String("js-module-name")).toString();
if (!logicalModuleName.isEmpty())
qdb_->addToQmlModule(logicalModuleName, qcn);
bool abstract = false;
- if (element.attribute("abstract") == "true")
+ if (attributes.value(QLatin1String("abstract")) == QLatin1String("true"))
abstract = true;
qcn->setAbstract(abstract);
- QString qmlFullBaseName = element.attribute("js-base-type");
+ QString qmlFullBaseName = attributes.value(QLatin1String("js-base-type")).toString();
if (!qmlFullBaseName.isEmpty()) {
qcn->setQmlBaseName(qmlFullBaseName);
}
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qcn;
}
- else if (element.nodeName() == "qmlbasictype") {
+ else if (elementName == QLatin1String("qmlbasictype")) {
QmlBasicTypeNode* qbtn = new QmlBasicTypeNode(parent, name);
- qbtn->setTitle(element.attribute("title"));
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ qbtn->setTitle(attributes.value(QLatin1String("title")).toString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qbtn;
}
- else if (element.nodeName() == "jsbasictype") {
+ else if (elementName == QLatin1String("jsbasictype")) {
QmlBasicTypeNode* qbtn = new QmlBasicTypeNode(parent, name);
qbtn->setGenus(Node::JS);
- qbtn->setTitle(element.attribute("title"));
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ qbtn->setTitle(attributes.value(QLatin1String("title")).toString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qbtn;
}
- else if (element.nodeName() == "qmlpropertygroup") {
+ else if (elementName == QLatin1String("qmlpropertygroup")) {
QmlTypeNode* qcn = static_cast<QmlTypeNode*>(parent);
QmlPropertyGroupNode* qpgn = new QmlPropertyGroupNode(qcn, name);
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qpgn;
}
- else if (element.nodeName() == "jspropertygroup") {
+ else if (elementName == QLatin1String("jspropertygroup")) {
QmlTypeNode* qcn = static_cast<QmlTypeNode*>(parent);
QmlPropertyGroupNode* qpgn = new QmlPropertyGroupNode(qcn, name);
qpgn->setGenus(Node::JS);
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value("location").toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
else if (!indexUrl.isNull())
location = Location(name);
node = qpgn;
}
- else if (element.nodeName() == "qmlproperty") {
- QString type = element.attribute("type");
+ else if (elementName == QLatin1String("qmlproperty")) {
+ QString type = attributes.value(QLatin1String("type")).toString();
bool attached = false;
- if (element.attribute("attached") == "true")
+ if (attributes.value(QLatin1String("attached")) == QLatin1String("true"))
attached = true;
bool readonly = false;
- if (element.attribute("writable") == "false")
+ if (attributes.value(QLatin1String("writable")) == QLatin1String("false"))
readonly = true;
QmlPropertyNode* qpn = 0;
if (parent->isQmlType()) {
@@ -318,13 +327,13 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
qpn->setReadOnly(readonly);
node = qpn;
}
- else if (element.nodeName() == "jsproperty") {
- QString type = element.attribute("type");
+ else if (elementName == QLatin1String("jsproperty")) {
+ QString type = attributes.value(QLatin1String("type")).toString();
bool attached = false;
- if (element.attribute("attached") == "true")
+ if (attributes.value(QLatin1String("attached")) == QLatin1String("true"))
attached = true;
bool readonly = false;
- if (element.attribute("writable") == "false")
+ if (attributes.value(QLatin1String("writable")) == QLatin1String("false"))
readonly = true;
QmlPropertyNode* qpn = 0;
if (parent->isJsType()) {
@@ -339,103 +348,103 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
qpn->setReadOnly(readonly);
node = qpn;
}
- else if ((element.nodeName() == "qmlmethod") ||
- (element.nodeName() == "qmlsignal") ||
- (element.nodeName() == "qmlsignalhandler")) {
- Node::Type t = Node::QmlMethod;
- if (element.nodeName() == "qmlsignal")
+ else if ((elementName == QLatin1String("qmlmethod")) ||
+ (elementName == QLatin1String("qmlsignal")) ||
+ (elementName == QLatin1String("qmlsignalhandler"))) {
+ Node::NodeType t = Node::QmlMethod;
+ if (elementName == QLatin1String("qmlsignal"))
t = Node::QmlSignal;
- else if (element.nodeName() == "qmlsignalhandler")
+ else if (elementName == QLatin1String("qmlsignalhandler"))
t = Node::QmlSignalHandler;
bool attached = false;
FunctionNode* fn = new FunctionNode(t, parent, name, attached);
node = fn;
}
- else if ((element.nodeName() == "jsmethod") ||
- (element.nodeName() == "jssignal") ||
- (element.nodeName() == "jssignalhandler")) {
- Node::Type t = Node::QmlMethod;
- if (element.nodeName() == "jssignal")
+ else if ((elementName == QLatin1String("jsmethod")) ||
+ (elementName == QLatin1String("jssignal")) ||
+ (elementName == QLatin1String("jssignalhandler"))) {
+ Node::NodeType t = Node::QmlMethod;
+ if (elementName == QLatin1String("jssignal"))
t = Node::QmlSignal;
- else if (element.nodeName() == "jssignalhandler")
+ else if (elementName == QLatin1String("jssignalhandler"))
t = Node::QmlSignalHandler;
bool attached = false;
FunctionNode* fn = new FunctionNode(t, parent, name, attached);
fn->setGenus(Node::JS);
node = fn;
}
- else if (element.nodeName() == "group") {
+ else if (elementName == QLatin1String("group")) {
CollectionNode* cn = qdb_->addGroup(name);
- cn->setTitle(element.attribute("title"));
- cn->setSubTitle(element.attribute("subtitle"));
- if (element.attribute("seen") == "true")
+ cn->setTitle(attributes.value(QLatin1String("title")).toString());
+ cn->setSubTitle(attributes.value(QLatin1String("subtitle")).toString());
+ if (attributes.value(QLatin1String("seen")) == QLatin1String("true"))
cn->markSeen();
node = cn;
}
- else if (element.nodeName() == "module") {
+ else if (elementName == QLatin1String("module")) {
CollectionNode* cn = qdb_->addModule(name);
- cn->setTitle(element.attribute("title"));
- cn->setSubTitle(element.attribute("subtitle"));
- if (element.attribute("seen") == "true")
+ cn->setTitle(attributes.value(QLatin1String("title")).toString());
+ cn->setSubTitle(attributes.value(QLatin1String("subtitle")).toString());
+ if (attributes.value(QLatin1String("seen")) == QLatin1String("true"))
cn->markSeen();
node = cn;
}
- else if (element.nodeName() == "qmlmodule") {
- QString t = element.attribute("qml-module-name");
+ else if (elementName == QLatin1String("qmlmodule")) {
+ QString t = attributes.value(QLatin1String("qml-module-name")).toString();
CollectionNode* cn = qdb_->addQmlModule(t);
QStringList info;
- info << t << element.attribute("qml-module-version");
+ info << t << attributes.value(QLatin1String("qml-module-version")).toString();
cn->setLogicalModuleInfo(info);
- cn->setTitle(element.attribute("title"));
- cn->setSubTitle(element.attribute("subtitle"));
- if (element.attribute("seen") == "true")
+ cn->setTitle(attributes.value(QLatin1String("title")).toString());
+ cn->setSubTitle(attributes.value(QLatin1String("subtitle")).toString());
+ if (attributes.value(QLatin1String("seen")) == QLatin1String("true"))
cn->markSeen();
node = cn;
}
- else if (element.nodeName() == "jsmodule") {
- QString t = element.attribute("js-module-name");
+ else if (elementName == QLatin1String("jsmodule")) {
+ QString t = attributes.value(QLatin1String("js-module-name")).toString();
CollectionNode* cn = qdb_->addJsModule(t);
QStringList info;
- info << t << element.attribute("js-module-version");
+ info << t << attributes.value(QLatin1String("js-module-version")).toString();
cn->setLogicalModuleInfo(info);
- cn->setTitle(element.attribute("title"));
- cn->setSubTitle(element.attribute("subtitle"));
- if (element.attribute("seen") == "true")
+ cn->setTitle(attributes.value(QLatin1String("title")).toString());
+ cn->setSubTitle(attributes.value(QLatin1String("subtitle")).toString());
+ if (attributes.value(QLatin1String("seen")) == QLatin1String("true"))
cn->markSeen();
node = cn;
}
- else if (element.nodeName() == "page") {
- Node::SubType subtype;
+ else if (elementName == QLatin1String("page")) {
+ Node::DocSubtype subtype;
Node::PageType ptype = Node::NoPageType;
- QString attr = element.attribute("subtype");
- if (attr == "example") {
+ QString attr = attributes.value(QLatin1String("subtype")).toString();
+ if (attr == QLatin1String("example")) {
subtype = Node::Example;
ptype = Node::ExamplePage;
}
- else if (attr == "header") {
+ else if (attr == QLatin1String("header")) {
subtype = Node::HeaderFile;
ptype = Node::ApiPage;
}
- else if (attr == "file") {
+ else if (attr == QLatin1String("file")) {
subtype = Node::File;
ptype = Node::NoPageType;
}
- else if (attr == "page") {
+ else if (attr == QLatin1String("page")) {
subtype = Node::Page;
ptype = Node::ArticlePage;
}
- else if (attr == "externalpage") {
+ else if (attr == QLatin1String("externalpage")) {
subtype = Node::ExternalPage;
ptype = Node::ArticlePage;
}
else
- return;
+ goto done;
DocumentNode* docNode = new DocumentNode(parent, name, subtype, ptype);
- docNode->setTitle(element.attribute("title"));
+ docNode->setTitle(attributes.value(QLatin1String("title")).toString());
- if (element.hasAttribute("location"))
- name = element.attribute("location", QString());
+ if (attributes.hasAttribute(QLatin1String("location")))
+ name = attributes.value(QLatin1String("location")).toString();
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + name);
@@ -445,7 +454,7 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
node = docNode;
}
- else if (element.nodeName() == "enum") {
+ else if (elementName == QLatin1String("enum")) {
EnumNode* enumNode = new EnumNode(parent, name);
if (!indexUrl.isEmpty())
@@ -453,17 +462,20 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
else if (!indexUrl.isNull())
location = Location(parent->name().toLower() + ".html");
- QDomElement child = element.firstChildElement("value");
- while (!child.isNull()) {
- EnumItem item(child.attribute("name"), child.attribute("value"));
- enumNode->addItem(item);
- child = child.nextSiblingElement("value");
+ while (reader.readNextStartElement()) {
+ if (reader.name() == QLatin1String("value")) {
+ QXmlStreamAttributes childAttributes = reader.attributes();
+ EnumItem item(childAttributes.value(QLatin1String("name")).toString(), childAttributes.value(QLatin1String("value")).toString());
+ enumNode->addItem(item);
+ }
+ reader.skipCurrentElement();
}
node = enumNode;
+ hasReadChildren = true;
}
- else if (element.nodeName() == "typedef") {
+ else if (elementName == QLatin1String("typedef")) {
node = new TypedefNode(parent, name);
if (!indexUrl.isEmpty())
@@ -472,7 +484,7 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
location = Location(parent->name().toLower() + ".html");
}
- else if (element.nodeName() == "property") {
+ else if (elementName == QLatin1String("property")) {
node = new PropertyNode(parent, name);
if (!indexUrl.isEmpty())
@@ -481,68 +493,76 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
location = Location(parent->name().toLower() + ".html");
}
- else if (element.nodeName() == "function") {
+ else if (elementName == QLatin1String("function")) {
FunctionNode::Virtualness virt;
- QString t = element.attribute("virtual");
- if (t == "non")
+ QString t = attributes.value(QLatin1String("virtual")).toString();
+ if (t == QLatin1String("non"))
virt = FunctionNode::NonVirtual;
- else if (t == "impure")
- virt = FunctionNode::ImpureVirtual;
- else if (t == "pure")
+ else if (t == QLatin1String("virtual"))
+ virt = FunctionNode::NormalVirtual;
+ else if (t == QLatin1String("pure"))
virt = FunctionNode::PureVirtual;
else
- return;
+ goto done;
- t = element.attribute("meta");
+ t = attributes.value(QLatin1String("meta")).toString();
FunctionNode::Metaness meta;
- if (t == "plain")
+ if (t == QLatin1String("plain"))
meta = FunctionNode::Plain;
- else if (t == "signal")
+ else if (t == QLatin1String("signal"))
meta = FunctionNode::Signal;
- else if (t == "slot")
+ else if (t == QLatin1String("slot"))
meta = FunctionNode::Slot;
- else if (t == "constructor")
+ else if (t == QLatin1String("constructor"))
meta = FunctionNode::Ctor;
- else if (t == "destructor")
+ else if (t == QLatin1String("destructor"))
meta = FunctionNode::Dtor;
- else if (t == "macro")
+ else if (t == QLatin1String("macro"))
meta = FunctionNode::MacroWithParams;
- else if (t == "macrowithparams")
+ else if (t == QLatin1String("macrowithparams"))
meta = FunctionNode::MacroWithParams;
- else if (t == "macrowithoutparams")
+ else if (t == QLatin1String("macrowithoutparams"))
meta = FunctionNode::MacroWithoutParams;
else
- return;
+ goto done;
FunctionNode* functionNode = new FunctionNode(parent, name);
- functionNode->setReturnType(element.attribute("return"));
+ functionNode->setReturnType(attributes.value(QLatin1String("return")).toString());
functionNode->setVirtualness(virt);
functionNode->setMetaness(meta);
- functionNode->setConst(element.attribute("const") == "true");
- functionNode->setStatic(element.attribute("static") == "true");
- functionNode->setOverload(element.attribute("overload") == "true");
-
- if (element.hasAttribute("relates")
- && element.attribute("relates") != parent->name()) {
+ functionNode->setConst(attributes.value(QLatin1String("const")) == QLatin1String("true"));
+ functionNode->setStatic(attributes.value(QLatin1String("static")) == QLatin1String("true"));
+ if (attributes.value(QLatin1String("overload")) == QLatin1String("true")) {
+ functionNode->setOverloadFlag(true);
+ functionNode->setOverloadNumber(attributes.value(QLatin1String("overload-number")).toUInt());
+ }
+ else {
+ functionNode->setOverloadFlag(false);
+ functionNode->setOverloadNumber(0);
+ }
+ if (attributes.hasAttribute(QLatin1String("relates"))
+ && attributes.value(QLatin1String("relates")) != parent->name()) {
relatedList_.append(
QPair<FunctionNode*,QString>(functionNode,
- element.attribute("relates")));
+ attributes.value(QLatin1String("relates")).toString()));
}
/*
Note: The "signature" attribute was written to the
index file, but it is not read back in. Is that ok?
*/
- QDomElement child = element.firstChildElement("parameter");
- while (!child.isNull()) {
- // Do not use the default value for the parameter; it is not
- // required, and has been known to cause problems.
- Parameter parameter(child.attribute("left"),
- child.attribute("right"),
- child.attribute("name"),
- QString()); // child.attribute("default")
- functionNode->addParameter(parameter);
- child = child.nextSiblingElement("parameter");
+ while (reader.readNextStartElement()) {
+ if (reader.name() == QLatin1String("parameter")) {
+ QXmlStreamAttributes childAttributes = reader.attributes();
+ // Do not use the default value for the parameter; it is not
+ // required, and has been known to cause problems.
+ Parameter parameter(childAttributes.value(QLatin1String("left")).toString(),
+ childAttributes.value(QLatin1String("right")).toString(),
+ childAttributes.value(QLatin1String("name")).toString(),
+ QString()); // childAttributes.value(QLatin1String("default"))
+ functionNode->addParameter(parameter);
+ }
+ reader.skipCurrentElement();
}
node = functionNode;
@@ -550,125 +570,134 @@ void QDocIndexFiles::readIndexSection(const QDomElement& element,
location = Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
else if (!indexUrl.isNull())
location = Location(parent->name().toLower() + ".html");
+
+ hasReadChildren = true;
}
- else if (element.nodeName() == "variable") {
+ else if (elementName == QLatin1String("variable")) {
node = new VariableNode(parent, name);
if (!indexUrl.isEmpty())
location = Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
else if (!indexUrl.isNull())
location = Location(parent->name().toLower() + ".html");
}
- else if (element.nodeName() == "keyword") {
- QString title = element.attribute("title");
+ else if (elementName == QLatin1String("keyword")) {
+ QString title = attributes.value(QLatin1String("title")).toString();
qdb_->insertTarget(name, title, TargetRec::Keyword, current, 1);
- return;
+ goto done;
}
- else if (element.nodeName() == "target") {
- QString title = element.attribute("title");
+ else if (elementName == QLatin1String("target")) {
+ QString title = attributes.value(QLatin1String("title")).toString();
qdb_->insertTarget(name, title, TargetRec::Target, current, 2);
- return;
+ goto done;
}
- else if (element.nodeName() == "contents") {
- QString title = element.attribute("title");
+ else if (elementName == QLatin1String("contents")) {
+ QString title = attributes.value(QLatin1String("title")).toString();
qdb_->insertTarget(name, title, TargetRec::Contents, current, 3);
- return;
+ goto done;
}
else
- return;
-
- QString access = element.attribute("access");
- if (access == "public")
- node->setAccess(Node::Public);
- else if (access == "protected")
- node->setAccess(Node::Protected);
- else if ((access == "private") || (access == "internal"))
- node->setAccess(Node::Private);
- else
- node->setAccess(Node::Public);
-
- if ((element.nodeName() != "page") &&
- (element.nodeName() != "qmlclass") &&
- (element.nodeName() != "qmlbasictype") &&
- (element.nodeName() != "jstype") &&
- (element.nodeName() != "jsbasictype")) {
- QString threadSafety = element.attribute("threadsafety");
- if (threadSafety == "non-reentrant")
- node->setThreadSafeness(Node::NonReentrant);
- else if (threadSafety == "reentrant")
- node->setThreadSafeness(Node::Reentrant);
- else if (threadSafety == "thread safe")
- node->setThreadSafeness(Node::ThreadSafe);
+ goto done;
+
+ {
+ QString access = attributes.value(QLatin1String("access")).toString();
+ if (access == "public")
+ node->setAccess(Node::Public);
+ else if (access == "protected")
+ node->setAccess(Node::Protected);
+ else if ((access == "private") || (access == "internal"))
+ node->setAccess(Node::Private);
+ else
+ node->setAccess(Node::Public);
+
+ if ((elementName != QLatin1String("page")) &&
+ (elementName != QLatin1String("qmlclass")) &&
+ (elementName != QLatin1String("qmlbasictype")) &&
+ (elementName != QLatin1String("jstype")) &&
+ (elementName != QLatin1String("jsbasictype"))) {
+ QString threadSafety = attributes.value(QLatin1String("threadsafety")).toString();
+ if (threadSafety == QLatin1String("non-reentrant"))
+ node->setThreadSafeness(Node::NonReentrant);
+ else if (threadSafety == QLatin1String("reentrant"))
+ node->setThreadSafeness(Node::Reentrant);
+ else if (threadSafety == QLatin1String("thread safe"))
+ node->setThreadSafeness(Node::ThreadSafe);
+ else
+ node->setThreadSafeness(Node::UnspecifiedSafeness);
+ }
else
node->setThreadSafeness(Node::UnspecifiedSafeness);
- }
- else
- node->setThreadSafeness(Node::UnspecifiedSafeness);
-
- QString status = element.attribute("status");
- if (status == "compat")
- node->setStatus(Node::Compat);
- else if (status == "obsolete")
- node->setStatus(Node::Obsolete);
- else if (status == "deprecated")
- node->setStatus(Node::Obsolete);
- else if (status == "preliminary")
- node->setStatus(Node::Preliminary);
- else if (status == "commendable")
- node->setStatus(Node::Commendable);
- else if (status == "internal")
- node->setStatus(Node::Internal);
- else
- node->setStatus(Node::Commendable);
-
- QString physicalModuleName = element.attribute("module");
- if (!physicalModuleName.isEmpty())
- qdb_->addToModule(physicalModuleName, node);
- if (!href.isEmpty()) {
- if (node->isExternalPage())
- node->setUrl(href);
- else if (!indexUrl.isEmpty())
- node->setUrl(indexUrl + QLatin1Char('/') + href);
- }
- QString since = element.attribute("since");
- if (!since.isEmpty()) {
- node->setSince(since);
- }
+ QString status = attributes.value(QLatin1String("status")).toString();
+ if (status == QLatin1String("compat"))
+ node->setStatus(Node::Compat);
+ else if (status == QLatin1String("obsolete"))
+ node->setStatus(Node::Obsolete);
+ else if (status == QLatin1String("deprecated"))
+ node->setStatus(Node::Obsolete);
+ else if (status == QLatin1String("preliminary"))
+ node->setStatus(Node::Preliminary);
+ else if (status == QLatin1String("active"))
+ node->setStatus(Node::Active);
+ else if (status == QLatin1String("internal"))
+ node->setStatus(Node::Internal);
+ else
+ node->setStatus(Node::Active);
+
+ QString physicalModuleName = attributes.value(QLatin1String("module")).toString();
+ if (!physicalModuleName.isEmpty())
+ qdb_->addToModule(physicalModuleName, node);
+ if (!href.isEmpty()) {
+ if (node->isExternalPage())
+ node->setUrl(href);
+ else if (!indexUrl.isEmpty())
+ node->setUrl(indexUrl + QLatin1Char('/') + href);
+ }
- QString groupsAttr = element.attribute("groups");
- if (!groupsAttr.isEmpty()) {
- QStringList groupNames = groupsAttr.split(",");
- foreach (const QString &name, groupNames) {
- qdb_->addToGroup(name, node);
+ QString since = attributes.value(QLatin1String("since")).toString();
+ if (!since.isEmpty()) {
+ node->setSince(since);
}
- }
- // Create some content for the node.
- QSet<QString> emptySet;
- Location t(filePath);
- if (!filePath.isEmpty()) {
- t.setLineNo(lineNo);
- node->setLocation(t);
- location = t;
- }
- Doc doc(location, location, " ", emptySet, emptySet); // placeholder
- node->setDoc(doc);
- node->setIndexNodeFlag();
- node->setOutputSubdirectory(project_.toLower());
- QString briefAttr = element.attribute("brief");
- if (!briefAttr.isEmpty()) {
- node->setReconstitutedBrief(briefAttr);
+ QString groupsAttr = attributes.value(QLatin1String("groups")).toString();
+ if (!groupsAttr.isEmpty()) {
+ QStringList groupNames = groupsAttr.split(",");
+ foreach (const QString &name, groupNames) {
+ qdb_->addToGroup(name, node);
+ }
+ }
+
+ // Create some content for the node.
+ QSet<QString> emptySet;
+ Location t(filePath);
+ if (!filePath.isEmpty()) {
+ t.setLineNo(lineNo);
+ node->setLocation(t);
+ location = t;
+ }
+ Doc doc(location, location, " ", emptySet, emptySet); // placeholder
+ node->setDoc(doc);
+ node->setIndexNodeFlag();
+ node->setOutputSubdirectory(project_.toLower());
+ QString briefAttr = attributes.value(QLatin1String("brief")).toString();
+ if (!briefAttr.isEmpty()) {
+ node->setReconstitutedBrief(briefAttr);
+ }
+
+ if (!hasReadChildren) {
+ bool useParent = (elementName == QLatin1String("namespace") && name.isEmpty());
+ while (reader.readNextStartElement()) {
+ if (useParent)
+ readIndexSection(reader, parent, indexUrl);
+ else
+ readIndexSection(reader, node, indexUrl);
+ }
+ }
}
- bool useParent = (element.nodeName() == "namespace" && name.isEmpty());
- if (element.hasChildNodes()) {
- QDomElement child = element.firstChildElement();
- while (!child.isNull()) {
- if (useParent)
- readIndexSection(child, parent, indexUrl);
- else
- readIndexSection(child, node, indexUrl);
- child = child.nextSiblingElement();
+ done:
+ while (!reader.isEndElement()) {
+ if (reader.readNext() == QXmlStreamReader::Invalid) {
+ break;
}
}
}
@@ -700,17 +729,37 @@ void QDocIndexFiles::resolveIndex()
pair.first->addUnresolvedBaseClass(Node::Public, basePath, QString());
}
}
+ // No longer needed.
+ basesList_.clear();
+}
+
+/*
+ Goes though the list of nodes that are related to other aggregates
+ that were read from all index files, and tries to find the aggregate
+ nodes from the database. Calls the node's setRelates() for each
+ aggregate that is found in the local module (primary tree).
+
+ This function is meant to be called before starting the doc generation,
+ after all the index files are read.
+ */
+void QDocIndexFiles::resolveRelates()
+{
+ if (relatedList_.isEmpty())
+ return;
+
+ // Restrict searching only to the local (primary) tree
+ QVector<Tree*> searchOrder = qdb_->searchOrder();
+ qdb_->setLocalSearch();
QPair<FunctionNode*,QString> relatedPair;
foreach (relatedPair, relatedList_) {
QStringList path = relatedPair.second.split("::");
Node* n = qdb_->findRelatesNode(path);
if (n)
- relatedPair.first->setRelates(static_cast<ClassNode*>(n));
+ relatedPair.first->setRelates(static_cast<Aggregate*>(n));
}
-
- // No longer needed.
- basesList_.clear();
+ // Restore original search order
+ qdb_->setSearchOrder(searchOrder);
relatedList_.clear();
}
@@ -726,7 +775,7 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
/*
Don't include index nodes in a new index file. Or DITA map nodes.
*/
- if (node->isIndexNode() || node->subType() == Node::DitaMap)
+ if (node->isIndexNode() || node->docSubtype() == Node::DitaMap)
return false;
QString nodeName;
@@ -885,8 +934,8 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
case Node::Preliminary:
status = "preliminary";
break;
- case Node::Commendable:
- status = "commendable";
+ case Node::Active:
+ status = "active";
break;
case Node::Internal:
status = "internal";
@@ -937,7 +986,7 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
else
href = node->name();
if (node->isQmlNode() || node->isJsNode()) {
- InnerNode* p = node->parent();
+ Aggregate* p = node->parent();
if (p) {
if (p->isQmlPropertyGroup() || p->isJsPropertyGroup())
p = p->parent();
@@ -954,11 +1003,12 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
if (node->isAbstract())
writer.writeAttribute("abstract", "true");
}
- if (!node->location().fileName().isEmpty())
- writer.writeAttribute("location", node->location().fileName());
- if (!node->location().filePath().isEmpty()) {
- writer.writeAttribute("filepath", node->location().filePath());
- writer.writeAttribute("lineno", QString("%1").arg(node->location().lineNo()));
+ const Location& declLocation = node->declLocation();
+ if (!declLocation.fileName().isEmpty())
+ writer.writeAttribute("location", declLocation.fileName());
+ if (!declLocation.filePath().isEmpty()) {
+ writer.writeAttribute("filepath", declLocation.filePath());
+ writer.writeAttribute("lineno", QString("%1").arg(declLocation.lineNo()));
}
if (!node->since().isEmpty()) {
@@ -1019,7 +1069,7 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
*/
bool writeModuleName = false;
const DocumentNode* docNode = static_cast<const DocumentNode*>(node);
- switch (docNode->subType()) {
+ switch (docNode->docSubtype()) {
case Node::Example:
writer.writeAttribute("subtype", "example");
writeModuleName = true;
@@ -1139,8 +1189,8 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
case FunctionNode::NonVirtual:
writer.writeAttribute("virtual", "non");
break;
- case FunctionNode::ImpureVirtual:
- writer.writeAttribute("virtual", "impure");
+ case FunctionNode::NormalVirtual:
+ writer.writeAttribute("virtual", "virtual");
break;
case FunctionNode::PureVirtual:
writer.writeAttribute("virtual", "pure");
@@ -1182,9 +1232,15 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
if (functionNode->relates()) {
writer.writeAttribute("relates", functionNode->relates()->name());
}
- const PropertyNode* propertyNode = functionNode->associatedProperty();
- if (propertyNode)
- writer.writeAttribute("associated-property", propertyNode->name());
+ if (functionNode->hasAssociatedProperties()) {
+ QString associatedProperties;
+ foreach (PropertyNode* pn, functionNode->associatedProperties()) {
+ if (!associatedProperties.isEmpty())
+ associatedProperties += QLatin1String(", ");
+ associatedProperties += pn->name();
+ }
+ writer.writeAttribute("associated-property", associatedProperties);
+ }
writer.writeAttribute("type", functionNode->returnType());
if (!brief.isEmpty())
writer.writeAttribute("brief", brief);
@@ -1201,7 +1257,7 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
for (int i = 0; i < functionNode->parameters().size(); ++i) {
Parameter parameter = functionNode->parameters()[i];
writer.writeStartElement("parameter");
- writer.writeAttribute("left", parameter.leftType());
+ writer.writeAttribute("left", parameter.dataType());
writer.writeAttribute("right", parameter.rightType());
writer.writeAttribute("name", parameter.name());
writer.writeAttribute("default", parameter.defaultValue());
@@ -1316,7 +1372,7 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
bool external = false;
if (node->type() == Node::Document) {
const DocumentNode* docNode = static_cast<const DocumentNode*>(node);
- if (docNode->subType() == Node::ExternalPage)
+ if (docNode->docSubtype() == Node::ExternalPage)
external = true;
}
foreach (const Atom* target, node->doc().targets()) {
@@ -1349,8 +1405,8 @@ bool QDocIndexFiles::generateIndexSection(QXmlStreamWriter& writer,
// opening tag, create child elements, then add a closing tag for the
// element. Elements for all other nodes are closed in the opening tag.
- if (node->isInnerNode()) {
- const InnerNode* inner = static_cast<const InnerNode*>(node);
+ if (node->isAggregate()) {
+ const Aggregate* inner = static_cast<const Aggregate*>(node);
if (inner->doc().hasTableOfContents()) {
for (int i = 0; i < inner->doc().tableOfContents().size(); ++i) {
@@ -1453,8 +1509,8 @@ void QDocIndexFiles::generateIndexSections(QXmlStreamWriter& writer,
return;
if (generateIndexSection(writer, node, generateInternalNodes)) {
- if (node->isInnerNode()) {
- const InnerNode* inner = static_cast<const InnerNode*>(node);
+ if (node->isAggregate()) {
+ const Aggregate* inner = static_cast<const Aggregate*>(node);
NodeList cnodes = inner->childNodes();
std::sort(cnodes.begin(), cnodes.end(), compareNodes);
diff --git a/src/tools/qdoc/qdocindexfiles.h b/src/tools/qdoc/qdocindexfiles.h
index 9a18639251..67a7e7226e 100644
--- a/src/tools/qdoc/qdocindexfiles.h
+++ b/src/tools/qdoc/qdocindexfiles.h
@@ -42,7 +42,6 @@ class Atom;
class Generator;
class QStringList;
class QDocDatabase;
-class QDomElement;
class QXmlStreamWriter;
class QDocIndexFiles
@@ -64,8 +63,9 @@ class QDocIndexFiles
bool generateInternalNodes = false);
void readIndexFile(const QString& path);
- void readIndexSection(const QDomElement& element, Node* current, const QString& indexUrl);
+ void readIndexSection(QXmlStreamReader &reader, Node* current, const QString& indexUrl);
void resolveIndex();
+ void resolveRelates();
bool generateIndexSection(QXmlStreamWriter& writer, Node* node, bool generateInternalNodes = false);
void generateIndexSections(QXmlStreamWriter& writer, Node* node, bool generateInternalNodes = false);
@@ -74,8 +74,8 @@ class QDocIndexFiles
QDocDatabase* qdb_;
Generator* gen_;
QString project_;
- QList<QPair<ClassNode*,QString> > basesList_;
- QList<QPair<FunctionNode*,QString> > relatedList_;
+ QVector<QPair<ClassNode*,QString> > basesList_;
+ QVector<QPair<FunctionNode*,QString> > relatedList_;
};
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/qdoctagfiles.cpp b/src/tools/qdoc/qdoctagfiles.cpp
index 778df33048..1210ac7c36 100644
--- a/src/tools/qdoc/qdoctagfiles.cpp
+++ b/src/tools/qdoc/qdoctagfiles.cpp
@@ -35,7 +35,6 @@
#include "qdoctagfiles.h"
#include "qdocdatabase.h"
-#include "qdom.h"
#include "atom.h"
#include "doc.h"
#include "htmlgenerator.h"
@@ -100,7 +99,7 @@ void QDocTagFiles::destroyQDocTagFiles()
specified, returning true if an element was written; otherwise returns
false.
*/
-void QDocTagFiles::generateTagFileCompounds(QXmlStreamWriter& writer, const InnerNode* inner)
+void QDocTagFiles::generateTagFileCompounds(QXmlStreamWriter& writer, const Aggregate* inner)
{
foreach (const Node* node, inner->childNodes()) {
if (!node->url().isEmpty())
@@ -161,22 +160,22 @@ void QDocTagFiles::generateTagFileCompounds(QXmlStreamWriter& writer, const Inne
}
// Recurse to write all members.
- generateTagFileMembers(writer, static_cast<const InnerNode*>(node));
+ generateTagFileMembers(writer, static_cast<const Aggregate*>(node));
writer.writeEndElement();
// Recurse to write all compounds.
- generateTagFileCompounds(writer, static_cast<const InnerNode*>(node));
+ generateTagFileCompounds(writer, static_cast<const Aggregate*>(node));
}
else {
writer.writeTextElement("name", node->fullDocumentName());
writer.writeTextElement("filename", gen_->fullDocumentLocation(node, false));
// Recurse to write all members.
- generateTagFileMembers(writer, static_cast<const InnerNode*>(node));
+ generateTagFileMembers(writer, static_cast<const Aggregate*>(node));
writer.writeEndElement();
// Recurse to write all compounds.
- generateTagFileCompounds(writer, static_cast<const InnerNode*>(node));
+ generateTagFileCompounds(writer, static_cast<const Aggregate*>(node));
}
}
}
@@ -185,7 +184,7 @@ void QDocTagFiles::generateTagFileCompounds(QXmlStreamWriter& writer, const Inne
Writes all the members of the \a inner node with the \a writer.
The node represents a C++ class, namespace, etc.
*/
-void QDocTagFiles::generateTagFileMembers(QXmlStreamWriter& writer, const InnerNode* inner)
+void QDocTagFiles::generateTagFileMembers(QXmlStreamWriter& writer, const Aggregate* inner)
{
foreach (const Node* node, inner->childNodes()) {
if (!node->url().isEmpty())
@@ -268,7 +267,7 @@ void QDocTagFiles::generateTagFileMembers(QXmlStreamWriter& writer, const InnerN
case FunctionNode::NonVirtual:
writer.writeAttribute("virtualness", "non");
break;
- case FunctionNode::ImpureVirtual:
+ case FunctionNode::NormalVirtual:
writer.writeAttribute("virtualness", "virtual");
break;
case FunctionNode::PureVirtual:
diff --git a/src/tools/qdoc/qdoctagfiles.h b/src/tools/qdoc/qdoctagfiles.h
index 94d3450478..ad1d383bfd 100644
--- a/src/tools/qdoc/qdoctagfiles.h
+++ b/src/tools/qdoc/qdoctagfiles.h
@@ -38,7 +38,7 @@
QT_BEGIN_NAMESPACE
-class InnerNode;
+class Aggregate;
class QDocDatabase;
class Generator;
@@ -53,8 +53,8 @@ class QDocTagFiles
QDocTagFiles();
~QDocTagFiles();
- void generateTagFileCompounds(QXmlStreamWriter& writer, const InnerNode* inner);
- void generateTagFileMembers(QXmlStreamWriter& writer, const InnerNode* inner);
+ void generateTagFileCompounds(QXmlStreamWriter& writer, const Aggregate* inner);
+ void generateTagFileMembers(QXmlStreamWriter& writer, const Aggregate* inner);
void generateTagFile(const QString& fileName, Generator* g);
private:
diff --git a/src/tools/qdoc/qmlcodemarker.cpp b/src/tools/qdoc/qmlcodemarker.cpp
index 86fc79be66..cfb5e16b44 100644
--- a/src/tools/qdoc/qmlcodemarker.cpp
+++ b/src/tools/qdoc/qmlcodemarker.cpp
@@ -96,7 +96,7 @@ bool QmlCodeMarker::recognizeLanguage(const QString &language)
/*!
Returns the type of atom used to represent QML code in the documentation.
*/
-Atom::Type QmlCodeMarker::atomType() const
+Atom::AtomType QmlCodeMarker::atomType() const
{
return Atom::Qml;
}
@@ -166,7 +166,7 @@ QString QmlCodeMarker::addMarkUp(const QString &code,
QQmlJS::Lexer lexer(&engine);
QString newCode = code;
- QList<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
+ QVector<QQmlJS::AST::SourceLocation> pragmas = extractPragmas(newCode);
lexer.setCode(newCode, 1);
QQmlJS::Parser parser(&engine);
@@ -209,11 +209,11 @@ static void replaceWithSpace(QString &str, int idx, int n)
Searches for ".pragma <value>" or ".import <stuff>" declarations
in \a script. Currently supported pragmas are: library
*/
-QList<QQmlJS::AST::SourceLocation> QmlCodeMarker::extractPragmas(QString &script)
+QVector<QQmlJS::AST::SourceLocation> QmlCodeMarker::extractPragmas(QString &script)
{
const QString pragma(QLatin1String("pragma"));
const QString library(QLatin1String("library"));
- QList<QQmlJS::AST::SourceLocation> removed;
+ QVector<QQmlJS::AST::SourceLocation> removed;
QQmlJS::Lexer l(0);
l.setCode(script, 0);
diff --git a/src/tools/qdoc/qmlcodemarker.h b/src/tools/qdoc/qmlcodemarker.h
index 805229e366..b3ec03965f 100644
--- a/src/tools/qdoc/qmlcodemarker.h
+++ b/src/tools/qdoc/qmlcodemarker.h
@@ -54,7 +54,7 @@ public:
virtual bool recognizeCode(const QString &code) Q_DECL_OVERRIDE;
virtual bool recognizeExtension(const QString &ext) Q_DECL_OVERRIDE;
virtual bool recognizeLanguage(const QString &language) Q_DECL_OVERRIDE;
- virtual Atom::Type atomType() const Q_DECL_OVERRIDE;
+ virtual Atom::AtomType atomType() const Q_DECL_OVERRIDE;
virtual QString markedUpCode(const QString &code,
const Node *relative,
const Location &location) Q_DECL_OVERRIDE;
@@ -66,7 +66,7 @@ public:
virtual QString functionEndRegExp(const QString &funcName) Q_DECL_OVERRIDE;
/* Copied from src/declarative/qml/qdeclarativescriptparser.cpp */
- QList<QQmlJS::AST::SourceLocation> extractPragmas(QString &script);
+ QVector<QQmlJS::AST::SourceLocation> extractPragmas(QString &script);
private:
QString addMarkUp(const QString &code, const Node *relative,
diff --git a/src/tools/qdoc/qmlcodeparser.cpp b/src/tools/qdoc/qmlcodeparser.cpp
index 4f5720a94d..bcc0fedc9a 100644
--- a/src/tools/qdoc/qmlcodeparser.cpp
+++ b/src/tools/qdoc/qmlcodeparser.cpp
@@ -56,7 +56,9 @@ QT_BEGIN_NAMESPACE
#define COMMAND_PRELIMINARY Doc::alias("preliminary")
#define COMMAND_SINCE Doc::alias("since")
#define COMMAND_WRAPPER Doc::alias("wrapper")
+#define COMMAND_NOAUTOLIST Doc::alias("noautolist")
+#define COMMAND_ABSTRACT Doc::alias("abstract")
#define COMMAND_QMLABSTRACT Doc::alias("qmlabstract")
#define COMMAND_QMLCLASS Doc::alias("qmlclass")
#define COMMAND_QMLTYPE Doc::alias("qmltype")
@@ -251,10 +253,12 @@ const QSet<QString>& QmlCodeParser::otherMetaCommands()
<< COMMAND_OBSOLETE
<< COMMAND_PRELIMINARY
<< COMMAND_SINCE
+ << COMMAND_ABSTRACT
<< COMMAND_QMLABSTRACT
<< COMMAND_INQMLMODULE
<< COMMAND_INJSMODULE
- << COMMAND_WRAPPER;
+ << COMMAND_WRAPPER
+ << COMMAND_NOAUTOLIST;
}
return otherMetaCommands_;
}
diff --git a/src/tools/qdoc/qmlmarkupvisitor.cpp b/src/tools/qdoc/qmlmarkupvisitor.cpp
index ee86b6de32..3a7635778e 100644
--- a/src/tools/qdoc/qmlmarkupvisitor.cpp
+++ b/src/tools/qdoc/qmlmarkupvisitor.cpp
@@ -42,7 +42,7 @@
QT_BEGIN_NAMESPACE
QmlMarkupVisitor::QmlMarkupVisitor(const QString &source,
- const QList<QQmlJS::AST::SourceLocation> &pragmas,
+ const QVector<QQmlJS::AST::SourceLocation> &pragmas,
QQmlJS::Engine *engine)
{
this->source = source;
@@ -54,21 +54,22 @@ QmlMarkupVisitor::QmlMarkupVisitor(const QString &source,
// Merge the lists of locations of pragmas and comments in the source code.
int i = 0;
int j = 0;
- while (i < engine->comments().length() && j < pragmas.length()) {
- if (engine->comments()[i].offset < pragmas[j].offset) {
+ const QVector<QQmlJS::AST::SourceLocation> comments = engine->comments();
+ while (i < comments.size() && j < pragmas.length()) {
+ if (comments[i].offset < pragmas[j].offset) {
extraTypes.append(Comment);
- extraLocations.append(engine->comments()[i]);
+ extraLocations.append(comments[i]);
++i;
} else {
extraTypes.append(Pragma);
- extraLocations.append(engine->comments()[j]);
+ extraLocations.append(comments[j]);
++j;
}
}
- while (i < engine->comments().length()) {
+ while (i < comments.size()) {
extraTypes.append(Comment);
- extraLocations.append(engine->comments()[i]);
+ extraLocations.append(comments[i]);
++i;
}
diff --git a/src/tools/qdoc/qmlmarkupvisitor.h b/src/tools/qdoc/qmlmarkupvisitor.h
index 04d6a57564..ddd16209ab 100644
--- a/src/tools/qdoc/qmlmarkupvisitor.h
+++ b/src/tools/qdoc/qmlmarkupvisitor.h
@@ -50,7 +50,7 @@ public:
};
QmlMarkupVisitor(const QString &code,
- const QList<QQmlJS::AST::SourceLocation> &pragmas,
+ const QVector<QQmlJS::AST::SourceLocation> &pragmas,
QQmlJS::Engine *engine);
virtual ~QmlMarkupVisitor();
@@ -157,13 +157,14 @@ private:
QString sourceText(QQmlJS::AST::SourceLocation &location);
QQmlJS::Engine *engine;
- QList<ExtraType> extraTypes;
- QList<QQmlJS::AST::SourceLocation> extraLocations;
+ QVector<ExtraType> extraTypes;
+ QVector<QQmlJS::AST::SourceLocation> extraLocations;
QString source;
QString output;
quint32 cursor;
int extraIndex;
};
+Q_DECLARE_TYPEINFO(QmlMarkupVisitor::ExtraType, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/qmlparser/qqmljsastfwd_p.h b/src/tools/qdoc/qmlparser/qqmljsastfwd_p.h
index eae4125ab2..bfaa4401d2 100644
--- a/src/tools/qdoc/qmlparser/qqmljsastfwd_p.h
+++ b/src/tools/qdoc/qmlparser/qqmljsastfwd_p.h
@@ -37,6 +37,7 @@
#include "qqmljsglobal_p.h"
#include <QtCore/qglobal.h>
+#include <QtCore/qtypeinfo.h>
//
// W A R N I N G
@@ -53,27 +54,6 @@ QT_QML_BEGIN_NAMESPACE
namespace QQmlJS { namespace AST {
-class SourceLocation
-{
-public:
- explicit SourceLocation(quint32 offset = 0, quint32 length = 0, quint32 line = 0, quint32 column = 0)
- : offset(offset), length(length),
- startLine(line), startColumn(column)
- { }
-
- bool isValid() const { return length != 0; }
-
- quint32 begin() const { return offset; }
- quint32 end() const { return offset + length; }
-
-// attributes
- // ### encode
- quint32 offset;
- quint32 length;
- quint32 startLine;
- quint32 startColumn;
-};
-
class Visitor;
class Node;
class ExpressionNode;
@@ -176,8 +156,31 @@ class UiQualifiedId;
class UiQualifiedPragmaId;
class UiHeaderItemList;
+class SourceLocation
+{
+public:
+ explicit SourceLocation(quint32 offset = 0, quint32 length = 0, quint32 line = 0, quint32 column = 0)
+ : offset(offset), length(length),
+ startLine(line), startColumn(column)
+ { }
+
+ bool isValid() const { return length != 0; }
+
+ quint32 begin() const { return offset; }
+ quint32 end() const { return offset + length; }
+
+// attributes
+ // ### encode
+ quint32 offset;
+ quint32 length;
+ quint32 startLine;
+ quint32 startColumn;
+};
+
} } // namespace AST
+Q_DECLARE_TYPEINFO(QQmlJS::AST::SourceLocation, Q_PRIMITIVE_TYPE);
+
QT_QML_END_NAMESPACE
#endif
diff --git a/src/tools/qdoc/qmlparser/qqmljsengine_p.cpp b/src/tools/qdoc/qmlparser/qqmljsengine_p.cpp
index 1c0a70a372..2a949b630c 100644
--- a/src/tools/qdoc/qmlparser/qqmljsengine_p.cpp
+++ b/src/tools/qdoc/qmlparser/qqmljsengine_p.cpp
@@ -35,7 +35,6 @@
#include "qqmljsglobal_p.h"
#include <QtCore/qnumeric.h>
-#include <QtCore/qhash.h>
#include <QtCore/qdebug.h>
QT_QML_BEGIN_NAMESPACE
@@ -126,7 +125,7 @@ void Engine::setCode(const QString &code)
void Engine::addComment(int pos, int len, int line, int col)
{ if (len > 0) _comments.append(QQmlJS::AST::SourceLocation(pos, len, line, col)); }
-QList<QQmlJS::AST::SourceLocation> Engine::comments() const
+QVector<QQmlJS::AST::SourceLocation> Engine::comments() const
{ return _comments; }
Lexer *Engine::lexer() const
diff --git a/src/tools/qdoc/qmlparser/qqmljsengine_p.h b/src/tools/qdoc/qmlparser/qqmljsengine_p.h
index fb65d7f028..9ab26f0d0f 100644
--- a/src/tools/qdoc/qmlparser/qqmljsengine_p.h
+++ b/src/tools/qdoc/qmlparser/qqmljsengine_p.h
@@ -50,7 +50,7 @@
#include "qqmljsmemorypool_p.h"
#include <QtCore/qstring.h>
-#include <QtCore/qset.h>
+#include <QtCore/qvector.h>
QT_QML_BEGIN_NAMESPACE
@@ -87,7 +87,7 @@ class QML_PARSER_EXPORT Engine
Lexer *_lexer;
Directives *_directives;
MemoryPool _pool;
- QList<AST::SourceLocation> _comments;
+ QVector<AST::SourceLocation> _comments;
QString _extraCode;
QString _code;
@@ -99,7 +99,7 @@ public:
const QString &code() const { return _code; }
void addComment(int pos, int len, int line, int col);
- QList<AST::SourceLocation> comments() const;
+ QVector<AST::SourceLocation> comments() const;
Lexer *lexer() const;
void setLexer(Lexer *lexer);
diff --git a/src/tools/qdoc/qmlvisitor.cpp b/src/tools/qdoc/qmlvisitor.cpp
index 190c9f0444..155e1de054 100644
--- a/src/tools/qdoc/qmlvisitor.cpp
+++ b/src/tools/qdoc/qmlvisitor.cpp
@@ -54,7 +54,9 @@ QT_BEGIN_NAMESPACE
#define COMMAND_PRELIMINARY Doc::alias(QLatin1String("preliminary"))
#define COMMAND_SINCE Doc::alias(QLatin1String("since"))
#define COMMAND_WRAPPER Doc::alias(QLatin1String("wrapper"))
+#define COMMAND_NOAUTOLIST Doc::alias(QLatin1String("noautolist"))
+#define COMMAND_ABSTRACT Doc::alias(QLatin1String("abstract"))
#define COMMAND_QMLABSTRACT Doc::alias(QLatin1String("qmlabstract"))
#define COMMAND_QMLCLASS Doc::alias(QLatin1String("qmlclass"))
#define COMMAND_QMLTYPE Doc::alias(QLatin1String("qmltype"))
@@ -118,7 +120,7 @@ QmlDocVisitor::~QmlDocVisitor()
*/
QQmlJS::AST::SourceLocation QmlDocVisitor::precedingComment(quint32 offset) const
{
- QListIterator<QQmlJS::AST::SourceLocation> it(engine->comments());
+ QVectorIterator<QQmlJS::AST::SourceLocation> it(engine->comments());
it.toBack();
while (it.hasPrevious()) {
@@ -196,18 +198,11 @@ bool QmlDocVisitor::applyDocumentation(QQmlJS::AST::SourceLocation location, Nod
const TopicList& topicsUsed = doc.topicsUsed();
NodeList nodes;
Node* nodePassedIn = node;
- InnerNode* parent = nodePassedIn->parent();
+ Aggregate* parent = nodePassedIn->parent();
node->setDoc(doc);
nodes.append(node);
if (topicsUsed.size() > 0) {
for (int i=0; i<topicsUsed.size(); ++i) {
- if ((topicsUsed.at(i).topic == COMMAND_QMLPROPERTYGROUP) ||
- (topicsUsed.at(i).topic == COMMAND_JSPROPERTYGROUP)) {
- qDebug() << "PROPERTY GROUP COMMAND SEEN:" << topicsUsed.at(i).args << filePath_;
- break;
- }
- }
- for (int i=0; i<topicsUsed.size(); ++i) {
QString topic = topicsUsed.at(i).topic;
QString args = topicsUsed.at(i).args;
if ((topic == COMMAND_QMLPROPERTY) || (topic == COMMAND_QMLATTACHEDPROPERTY) ||
@@ -497,7 +492,7 @@ void QmlDocVisitor::applyMetacommands(QQmlJS::AST::SourceLocation,
while (i != metacommands.end()) {
QString command = *i;
ArgList args = doc.metaCommandArgs(command);
- if (command == COMMAND_QMLABSTRACT) {
+ if ((command == COMMAND_QMLABSTRACT) || (command == COMMAND_ABSTRACT)) {
if (node->isQmlType() || node->isJsType()) {
node->setAbstract(true);
}
@@ -680,7 +675,7 @@ bool QmlDocVisitor::visit(QQmlJS::AST::UiPublicMember *member)
QString name = member->name.toString();
FunctionNode *qmlSignal = new FunctionNode(Node::QmlSignal, current, name, false);
- QList<Parameter> parameters;
+ QVector<Parameter> parameters;
for (QQmlJS::AST::UiParameterList *it = member->parameters; it; it = it->next) {
if (!it->type.isEmpty() && !it->name.isEmpty())
parameters.append(Parameter(it->type.toString(), QString(), it->name.toString()));
@@ -751,15 +746,15 @@ bool QmlDocVisitor::visit(QQmlJS::AST::FunctionDeclaration* fd)
if (current->isJsType())
qmlMethod->setGenus(Node::JS);
int overloads = 0;
- NodeList::ConstIterator overloadIterator = current->childNodes().constBegin();
- while (overloadIterator != current->childNodes().constEnd()) {
- if ((*overloadIterator)->name() == name)
+ NodeList::ConstIterator i = current->childNodes().constBegin();
+ while (i != current->childNodes().constEnd()) {
+ if ((*i)->name() == name)
overloads++;
- overloadIterator++;
+ i++;
}
if (overloads > 1)
- qmlMethod->setOverload(true);
- QList<Parameter> parameters;
+ qmlMethod->setOverloadFlag(true);
+ QVector<Parameter> parameters;
QQmlJS::AST::FormalParameterList* formals = fd->formals;
if (formals) {
QQmlJS::AST::FormalParameterList* fpl = formals;
diff --git a/src/tools/qdoc/qmlvisitor.h b/src/tools/qdoc/qmlvisitor.h
index cfb167c985..8c5e8c5042 100644
--- a/src/tools/qdoc/qmlvisitor.h
+++ b/src/tools/qdoc/qmlvisitor.h
@@ -111,7 +111,7 @@ private:
QSet<QString> commands_;
QSet<QString> topics_;
QSet<quint32> usedComments;
- InnerNode *current;
+ Aggregate *current;
};
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/quoter.cpp b/src/tools/qdoc/quoter.cpp
index d8a4df33f3..25cf27f731 100644
--- a/src/tools/qdoc/quoter.cpp
+++ b/src/tools/qdoc/quoter.cpp
@@ -39,6 +39,8 @@
QT_BEGIN_NAMESPACE
+QHash<QString,QString> Quoter::commentHash;
+
static void replaceMultipleNewlines(QString &s)
{
const int n = s.size();
@@ -120,14 +122,16 @@ Quoter::Quoter()
* .html, .qrc, .ui, .xq, .xml .dita files:
<!-- [<id>] -->
*/
- commentHash["pro"] = "#!";
- commentHash["py"] = "#!";
- commentHash["html"] = "<!--";
- commentHash["qrc"] = "<!--";
- commentHash["ui"] = "<!--";
- commentHash["xml"] = "<!--";
- commentHash["dita"] = "<!--";
- commentHash["xq"] = "<!--";
+ if (!commentHash.size()) {
+ commentHash["pro"] = "#!";
+ commentHash["py"] = "#!";
+ commentHash["html"] = "<!--";
+ commentHash["qrc"] = "<!--";
+ commentHash["ui"] = "<!--";
+ commentHash["xml"] = "<!--";
+ commentHash["dita"] = "<!--";
+ commentHash["xq"] = "<!--";
+ }
}
void Quoter::reset()
diff --git a/src/tools/qdoc/quoter.h b/src/tools/qdoc/quoter.h
index 2c3fa3980d..7877eda696 100644
--- a/src/tools/qdoc/quoter.h
+++ b/src/tools/qdoc/quoter.h
@@ -78,7 +78,7 @@ private:
QStringList plainLines;
QStringList markedLines;
Location codeLocation;
- QHash<QString,QString> commentHash;
+ static QHash<QString,QString> commentHash;
};
QT_END_NAMESPACE
diff --git a/src/tools/qdoc/text.cpp b/src/tools/qdoc/text.cpp
index b4eebe4c75..fa105a8344 100644
--- a/src/tools/qdoc/text.cpp
+++ b/src/tools/qdoc/text.cpp
@@ -72,7 +72,7 @@ Text& Text::operator=(const Text& text)
return *this;
}
-Text& Text::operator<<(Atom::Type atomType)
+Text& Text::operator<<(Atom::AtomType atomType)
{
return operator<<(Atom(atomType));
}
@@ -177,7 +177,7 @@ QString Text::toString() const
return str;
}
-Text Text::subText(Atom::Type left, Atom::Type right, const Atom* from, bool inclusive) const
+Text Text::subText(Atom::AtomType left, Atom::AtomType right, const Atom* from, bool inclusive) const
{
const Atom* begin = from ? from : firstAtom();
const Atom* end;
diff --git a/src/tools/qdoc/text.h b/src/tools/qdoc/text.h
index 7f4eeb3ec2..40ecf3eddc 100644
--- a/src/tools/qdoc/text.h
+++ b/src/tools/qdoc/text.h
@@ -54,7 +54,7 @@ public:
Atom *firstAtom() { return first; }
Atom *lastAtom() { return last; }
- Text& operator<<(Atom::Type atomType);
+ Text& operator<<(Atom::AtomType atomType);
Text& operator<<(const QString& string);
Text& operator<<(const Atom& atom);
Text& operator<<(const LinkAtom& atom);
@@ -66,7 +66,7 @@ public:
QString toString() const;
const Atom *firstAtom() const { return first; }
const Atom *lastAtom() const { return last; }
- Text subText(Atom::Type left, Atom::Type right, const Atom *from = 0, bool inclusive = false) const;
+ Text subText(Atom::AtomType left, Atom::AtomType right, const Atom *from = 0, bool inclusive = false) const;
void dump() const;
void clear();
diff --git a/src/tools/qdoc/tokenizer.cpp b/src/tools/qdoc/tokenizer.cpp
index 68c6fb7831..987fff548c 100644
--- a/src/tools/qdoc/tokenizer.cpp
+++ b/src/tools/qdoc/tokenizer.cpp
@@ -33,6 +33,7 @@
#include "config.h"
#include "tokenizer.h"
+#include "generator.h"
#include <qfile.h>
#include <qhash.h>
@@ -186,7 +187,7 @@ int Tokenizer::getToken()
}
else if (strcmp(yyLex, kwords[i - 1]) == 0) {
int ret = (int) Tok_FirstKeyword + i - 1;
- if (ret != Tok_explicit && ret != Tok_inline && ret != Tok_typename)
+ if (ret != Tok_typename)
return ret;
break;
}
diff --git a/src/tools/qdoc/tokenizer.h b/src/tools/qdoc/tokenizer.h
index 2b79320567..41a3ffd931 100644
--- a/src/tools/qdoc/tokenizer.h
+++ b/src/tools/qdoc/tokenizer.h
@@ -107,6 +107,7 @@ public:
int braceDepth() const { return yyBraceDepth; }
int parenDepth() const { return yyParenDepth; }
int bracketDepth() const { return yyBracketDepth; }
+ Location& tokenLocation() { return yyTokLoc; }
static void initialize(const Config &config);
static void terminate();
diff --git a/src/tools/qdoc/tree.cpp b/src/tools/qdoc/tree.cpp
index 1b0aba1a0c..d64903e61e 100644
--- a/src/tools/qdoc/tree.cpp
+++ b/src/tools/qdoc/tree.cpp
@@ -181,9 +181,9 @@ FunctionNode* Tree::findFunctionNode(const QStringList& parentPath, const Functi
parent = findClassNode(parentPath, 0);
if (parent == 0)
parent = findNode(parentPath, 0, 0, Node::DontCare);
- if (parent == 0 || !parent->isInnerNode())
+ if (parent == 0 || !parent->isAggregate())
return 0;
- return ((const InnerNode*)parent)->findFunctionNode(clone);
+ return ((const Aggregate*)parent)->findFunctionNode(clone);
}
@@ -220,6 +220,7 @@ QmlTypeNode* Tree::findQmlTypeNode(const QStringList& path)
used as the starting point.
*/
const FunctionNode* Tree::findFunctionNode(const QStringList& path,
+ const QString& params,
const Node* relative,
int findFlags,
Node::Genus genus) const
@@ -234,7 +235,7 @@ const FunctionNode* Tree::findFunctionNode(const QStringList& path,
qcn = static_cast<QmlTypeNode*>(n);
}
if (qcn)
- return static_cast<const FunctionNode*>(qcn->findFunctionNode(path[2]));
+ return static_cast<const FunctionNode*>(qcn->findFunctionNode(path[2], params));
}
if (!relative)
@@ -249,22 +250,22 @@ const FunctionNode* Tree::findFunctionNode(const QStringList& path,
int i;
for (i = 0; i < path.size(); ++i) {
- if (node == 0 || !node->isInnerNode())
+ if (node == 0 || !node->isAggregate())
break;
const Node* next;
if (i == path.size() - 1)
- next = ((const InnerNode*) node)->findFunctionNode(path.at(i));
+ next = ((const Aggregate*) node)->findFunctionNode(path.at(i), params);
else
- next = ((const InnerNode*) node)->findChildNode(path.at(i), genus);
+ next = ((const Aggregate*) node)->findChildNode(path.at(i), genus);
if (!next && node->isClass() && (findFlags & SearchBaseClasses)) {
NodeList baseClasses = allBaseClasses(static_cast<const ClassNode*>(node));
foreach (const Node* baseClass, baseClasses) {
if (i == path.size() - 1)
- next = static_cast<const InnerNode*>(baseClass)->findFunctionNode(path.at(i));
+ next = static_cast<const Aggregate*>(baseClass)->findFunctionNode(path.at(i), params);
else
- next = static_cast<const InnerNode*>(baseClass)->findChildNode(path.at(i), genus);
+ next = static_cast<const Aggregate*>(baseClass)->findChildNode(path.at(i), genus);
if (next)
break;
@@ -301,8 +302,8 @@ static const NodeTypeList& relatesTypes()
{
if (t.isEmpty()) {
t.reserve(3);
- t.append(NodeTypePair(Node::Class, Node::NoSubType));
- t.append(NodeTypePair(Node::Namespace, Node::NoSubType));
+ t.append(NodeTypePair(Node::Class, Node::NoSubtype));
+ t.append(NodeTypePair(Node::Namespace, Node::NoSubtype));
t.append(NodeTypePair(Node::Document, Node::HeaderFile));
}
return t;
@@ -320,13 +321,15 @@ static const NodeTypeList& relatesTypes()
If a matching node is found, a pointer to it is returned.
Otherwise 0 is returned.
*/
-InnerNode* Tree::findRelatesNode(const QStringList& path)
+Aggregate* Tree::findRelatesNode(const QStringList& path)
{
Node* n = findNodeRecursive(path, 0, root(), relatesTypes());
- return ((n && n->isInnerNode()) ? static_cast<InnerNode*>(n) : 0);
+ return ((n && n->isAggregate()) ? static_cast<Aggregate*>(n) : 0);
}
/*!
+ Inserts function name \a funcName and function role \a funcRole into
+ the property function map for the specified \a property.
*/
void Tree::addPropertyFunction(PropertyNode* property,
const QString& funcName,
@@ -344,7 +347,7 @@ void Tree::addPropertyFunction(PropertyNode* property,
This function does not resolve QML inheritance.
*/
-void Tree::resolveInheritance(InnerNode* n)
+void Tree::resolveInheritance(Aggregate* n)
{
if (!n)
n = root();
@@ -399,7 +402,7 @@ void Tree::resolveInheritanceHelper(int pass, ClassNode* cn)
node) using the unqualified base class name.
*/
if (!n) {
- InnerNode* parent = cn->parent();
+ Aggregate* parent = cn->parent();
if (parent)
// Exclude the root namespace
if (parent->isNamespace() && !parent->name().isEmpty())
@@ -422,7 +425,7 @@ void Tree::resolveInheritanceHelper(int pass, ClassNode* cn)
FunctionNode* from = findVirtualFunctionInBaseClasses(cn, func);
if (from != 0) {
if (func->virtualness() == FunctionNode::NonVirtual)
- func->setVirtualness(FunctionNode::ImpureVirtual);
+ func->setVirtualness(FunctionNode::NormalVirtual);
func->setReimplementedFrom(from);
}
}
@@ -442,7 +445,7 @@ void Tree::resolveProperties()
propEntry = unresolvedPropertyMap.constBegin();
while (propEntry != unresolvedPropertyMap.constEnd()) {
PropertyNode* property = propEntry.key();
- InnerNode* parent = property->parent();
+ Aggregate* parent = property->parent();
QString getterName = (*propEntry)[PropertyNode::Getter];
QString setterName = (*propEntry)[PropertyNode::Setter];
QString resetterName = (*propEntry)[PropertyNode::Resetter];
@@ -587,7 +590,7 @@ NodeList Tree::allBaseClasses(const ClassNode* classNode) const
search at the tree root. \a subtype is not used unless
\a type is \c{Document}.
*/
-Node* Tree::findNodeByNameAndType(const QStringList& path, Node::Type type) const
+Node* Tree::findNodeByNameAndType(const QStringList& path, Node::NodeType type) const
{
return findNodeRecursive(path, 0, root(), type);
}
@@ -611,7 +614,7 @@ Node* Tree::findNodeByNameAndType(const QStringList& path, Node::Type type) cons
Node* Tree::findNodeRecursive(const QStringList& path,
int pathIndex,
const Node* start,
- Node::Type type) const
+ Node::NodeType type) const
{
if (!start || path.isEmpty())
return 0; // no place to start, or nothing to search for.
@@ -622,7 +625,7 @@ Node* Tree::findNodeRecursive(const QStringList& path,
return 0; // premature leaf
}
- InnerNode* current = static_cast<InnerNode*>(node);
+ Aggregate* current = static_cast<Aggregate*>(node);
const NodeList& children = current->childNodes();
const QString& name = path.at(pathIndex);
for (int i=0; i<children.size(); ++i) {
@@ -678,7 +681,7 @@ Node* Tree::findNodeRecursive(const QStringList& path,
if (pathIndex >= path.size())
return 0;
- InnerNode* current = static_cast<InnerNode*>(start);
+ Aggregate* current = static_cast<Aggregate*>(start);
const NodeList& children = current->childNodes();
for (int i=0; i<children.size(); ++i) {
Node* n = children.at(i);
@@ -778,7 +781,7 @@ const Node* Tree::findNodeForTarget(const QStringList& path,
}
while (current) {
- if (current->isInnerNode()) {
+ if (current->isAggregate()) {
const Node* node = matchPathAndTarget(path, path_idx, target, current, flags, genus, ref);
if (node)
return node;
@@ -848,8 +851,8 @@ const Node* Tree::matchPathAndTarget(const QStringList& path,
return t;
}
if (target.isEmpty()) {
- if ((idx) == (path.size()-1) && node->isInnerNode() && (flags & SearchEnumValues)) {
- t = static_cast<const InnerNode*>(node)->findEnumNodeForValue(path.at(idx));
+ if ((idx) == (path.size()-1) && node->isAggregate() && (flags & SearchEnumValues)) {
+ t = static_cast<const Aggregate*>(node)->findEnumNodeForValue(path.at(idx));
if (t)
return t;
}
@@ -863,7 +866,7 @@ const Node* Tree::matchPathAndTarget(const QStringList& path,
return t;
if (target.isEmpty()) {
if ((idx) == (path.size()-1) && (flags & SearchEnumValues)) {
- t = static_cast<const InnerNode*>(bc)->findEnumNodeForValue(path.at(idx));
+ t = static_cast<const Aggregate*>(bc)->findEnumNodeForValue(path.at(idx));
if (t)
return t;
}
@@ -915,20 +918,20 @@ const Node* Tree::findNode(const QStringList& path,
}
for (i = start_idx; i < path.size(); ++i) {
- if (node == 0 || !node->isInnerNode())
+ if (node == 0 || !node->isAggregate())
break;
- const Node* next = static_cast<const InnerNode*>(node)->findChildNode(path.at(i), genus);
+ const Node* next = static_cast<const Aggregate*>(node)->findChildNode(path.at(i), genus);
if (!next && (findFlags & SearchEnumValues) && i == path.size()-1) {
- next = static_cast<const InnerNode*>(node)->findEnumNodeForValue(path.at(i));
+ next = static_cast<const Aggregate*>(node)->findEnumNodeForValue(path.at(i));
}
if (!next && ((genus == Node::CPP) || (genus == Node::DontCare)) &&
node->isClass() && (findFlags & SearchBaseClasses)) {
NodeList baseClasses = allBaseClasses(static_cast<const ClassNode*>(node));
foreach (const Node* baseClass, baseClasses) {
- next = static_cast<const InnerNode*>(baseClass)->findChildNode(path.at(i), genus);
+ next = static_cast<const Aggregate*>(baseClass)->findChildNode(path.at(i), genus);
if (!next && (findFlags & SearchEnumValues) && i == path.size() - 1)
- next = static_cast<const InnerNode*>(baseClass)->findEnumNodeForValue(path.at(i));
+ next = static_cast<const Aggregate*>(baseClass)->findEnumNodeForValue(path.at(i));
if (next) {
break;
}
@@ -980,7 +983,7 @@ QString Tree::getRef(const QString& target, const Node* node) const
*/
void Tree::insertTarget(const QString& name,
const QString& title,
- TargetRec::Type type,
+ TargetRec::TargetType type,
Node* node,
int priority)
{
@@ -991,9 +994,8 @@ void Tree::insertTarget(const QString& name,
/*!
*/
-void Tree::resolveTargets(InnerNode* root)
+void Tree::resolveTargets(Aggregate* root)
{
- // need recursion
foreach (Node* child, root->childNodes()) {
if (child->type() == Node::Document) {
DocumentNode* node = static_cast<DocumentNode*>(child);
@@ -1005,7 +1007,7 @@ void Tree::resolveTargets(InnerNode* root)
bool alreadyThere = false;
if (!nodes.empty()) {
for (int i=0; i< nodes.size(); ++i) {
- if (nodes[i]->subType() == Node::ExternalPage) {
+ if (nodes[i]->docSubtype() == Node::ExternalPage) {
if (node->name() == nodes[i]->name()) {
alreadyThere = true;
break;
@@ -1037,9 +1039,8 @@ void Tree::resolveTargets(InnerNode* root)
QString ref = refForAtom(keywords.at(i));
QString title = keywords.at(i)->string();
if (!ref.isEmpty() && !title.isEmpty()) {
- QString key = Doc::canonicalTitle(title);
TargetRec* target = new TargetRec(ref, title, TargetRec::Keyword, child, 1);
- nodesByTargetRef_.insert(key, target);
+ nodesByTargetRef_.insert(Doc::canonicalTitle(title), target);
nodesByTargetTitle_.insert(title, target);
}
}
@@ -1057,6 +1058,8 @@ void Tree::resolveTargets(InnerNode* root)
}
}
}
+ if (child->isAggregate())
+ resolveTargets(static_cast<Aggregate*>(child));
}
}
@@ -1140,18 +1143,15 @@ const DocumentNode* Tree::findDocumentNodeByTitle(const QString& title) const
DocumentNodeMultiMap::const_iterator j = i;
++j;
if (j != docNodesByTitle_.constEnd() && j.key() == i.key()) {
- QList<Location> internalLocations;
while (j != docNodesByTitle_.constEnd()) {
if (j.key() == i.key() && j.value()->url().isEmpty()) {
- internalLocations.append(j.value()->location());
break; // Just report one duplicate for now.
}
++j;
}
- if (internalLocations.size() > 0) {
+ if (j != docNodesByTitle_.cend()) {
i.value()->location().warning("This page title exists in more than one file: " + title);
- foreach (const Location &location, internalLocations)
- location.warning("[It also exists here]");
+ j.value()->location().warning("[It also exists here]");
}
}
return i.value();
@@ -1252,7 +1252,7 @@ CollectionNode* Tree::findCollection(const QString& name, Node::Genus genus)
CNMap::const_iterator i = m->constFind(name);
if (i != m->cend())
return i.value();
- Node::Type t = Node::NoType;
+ Node::NodeType t = Node::NoType;
switch (genus) {
case Node::DOC:
t = Node::Group;
@@ -1453,13 +1453,17 @@ void Tree::insertQmlType(const QString& key, QmlTypeNode* n)
Split \a target on "::" and find the function node with that
path.
*/
-const Node* Tree::findFunctionNode(const QString& target, const Node* relative, Node::Genus genus)
+const Node* Tree::findFunctionNode(const QString& target,
+ const QString& params,
+ const Node* relative,
+ Node::Genus genus) const
{
QString t = target;
- if (t.endsWith("()"))
+ if (t.endsWith("()")) {
t.chop(2);
+ }
QStringList path = t.split("::");
- const FunctionNode* fn = findFunctionNode(path, relative, SearchBaseClasses, genus);
+ const FunctionNode* fn = findFunctionNode(path, params, relative, SearchBaseClasses, genus);
if (fn && fn->metaness() != FunctionNode::MacroWithoutParams)
return fn;
return 0;
diff --git a/src/tools/qdoc/tree.h b/src/tools/qdoc/tree.h
index 1e9612aeec..1fef15bc6d 100644
--- a/src/tools/qdoc/tree.h
+++ b/src/tools/qdoc/tree.h
@@ -49,14 +49,19 @@ class QDocDatabase;
struct TargetRec
{
public:
- enum Type { Unknown, Target, Keyword, Contents, Class, Function, Page, Subtitle };
+ enum TargetType { Unknown, Target, Keyword, Contents, Class, Function, Page, Subtitle };
TargetRec(const QString& name,
const QString& title,
- TargetRec::Type type,
+ TargetRec::TargetType type,
Node* node,
int priority)
- : node_(node), ref_(name), title_(title), priority_(priority), type_(type) { }
+ : node_(node), ref_(name), title_(title), priority_(priority), type_(type) {
+ // Discard the dedicated ref for keywords - they always
+ // link to the top of the QDoc comment they appear in
+ if (type == Keyword)
+ ref_.clear();
+ }
bool isEmpty() const { return ref_.isEmpty(); }
@@ -64,7 +69,7 @@ struct TargetRec
QString ref_;
QString title_;
int priority_;
- Type type_;
+ TargetType type_;
};
struct TargetLoc
@@ -102,12 +107,15 @@ class Tree
ClassNode* findClassNode(const QStringList& path, const Node* start = 0) const;
NamespaceNode* findNamespaceNode(const QStringList& path) const;
FunctionNode* findFunctionNode(const QStringList& parentPath, const FunctionNode* clone);
- const Node* findFunctionNode(const QString& target, const Node* relative, Node::Genus genus);
+ const Node* findFunctionNode(const QString& target,
+ const QString& params,
+ const Node* relative,
+ Node::Genus genus) const;
Node* findNodeRecursive(const QStringList& path,
int pathIndex,
const Node* start,
- Node::Type type) const;
+ Node::NodeType type) const;
Node* findNodeRecursive(const QStringList& path,
int pathIndex,
Node* start,
@@ -134,22 +142,22 @@ class Tree
QmlTypeNode* findQmlTypeNode(const QStringList& path);
- Node* findNodeByNameAndType(const QStringList& path, Node::Type type) const;
- InnerNode* findRelatesNode(const QStringList& path);
+ Node* findNodeByNameAndType(const QStringList& path, Node::NodeType type) const;
+ Aggregate* findRelatesNode(const QStringList& path);
QString getRef(const QString& target, const Node* node) const;
void insertTarget(const QString& name,
const QString& title,
- TargetRec::Type type,
+ TargetRec::TargetType type,
Node* node,
int priority);
- void resolveTargets(InnerNode* root);
+ void resolveTargets(Aggregate* root);
const Node* findUnambiguousTarget(const QString& target, QString& ref) const;
const DocumentNode* findDocumentNodeByTitle(const QString& title) const;
void addPropertyFunction(PropertyNode *property,
const QString &funcName,
PropertyNode::FunctionRole funcRole);
- void resolveInheritance(InnerNode* n = 0);
+ void resolveInheritance(Aggregate* n = 0);
void resolveInheritanceHelper(int pass, ClassNode* cn);
void resolveProperties();
void resolveCppToQmlLinks();
@@ -158,6 +166,7 @@ class Tree
NamespaceNode *root() { return &root_; }
const FunctionNode *findFunctionNode(const QStringList &path,
+ const QString& params,
const Node *relative = 0,
int findFlags = 0,
Node::Genus genus = Node::DontCare) const;
diff --git a/src/tools/qlalr/compress.cpp b/src/tools/qlalr/compress.cpp
index 247b284421..fa67504a08 100644
--- a/src/tools/qlalr/compress.cpp
+++ b/src/tools/qlalr/compress.cpp
@@ -183,7 +183,7 @@ void Compress::operator () (int *table, int row_count, int column_count)
index.fill (-999999, row_count);
- foreach (UncompressedRow row, sortedTable)
+ foreach (const UncompressedRow &row, sortedTable)
{
int first_token = std::distance (row.begin (), row.beginNonZeros ());
QVector<int>::iterator pos = info.begin ();
diff --git a/src/tools/qlalr/cppgenerator.cpp b/src/tools/qlalr/cppgenerator.cpp
index 80f7a4ed2b..3005690e6e 100644
--- a/src/tools/qlalr/cppgenerator.cpp
+++ b/src/tools/qlalr/cppgenerator.cpp
@@ -163,7 +163,7 @@ void CppGenerator::operator () ()
if (item->rule == grammar.goal)
accept_state = q;
- foreach (Name s, lookaheads)
+ foreach (const Name &s, lookaheads)
{
int &u = ACTION (q, aut.id (s));
@@ -616,7 +616,7 @@ void CppGenerator::generateImpl (QTextStream &out)
out << name_ids.value(rule->lhs);
- foreach (Name n, rule->rhs)
+ foreach (const Name &n, rule->rhs)
out << ", " << name_ids.value (n);
}
out << "};" << endl << endl;
diff --git a/src/tools/qlalr/lalr.cpp b/src/tools/qlalr/lalr.cpp
index 3d780cd618..537051956e 100644
--- a/src/tools/qlalr/lalr.cpp
+++ b/src/tools/qlalr/lalr.cpp
@@ -367,7 +367,7 @@ void Automaton::closure (StatePointer state)
if (_M_grammar->isNonTerminal (*item->dot))
{
- foreach (RulePointer rule, _M_grammar->rule_map.values (*item->dot))
+ foreach (const RulePointer &rule, _M_grammar->rule_map.values (*item->dot))
{
Item ii;
ii.rule = rule;
@@ -413,7 +413,7 @@ void Automaton::buildLookbackSets ()
if (! _M_grammar->isNonTerminal (A))
continue;
- foreach (RulePointer rule, _M_grammar->rule_map.values (A))
+ foreach (const RulePointer &rule, _M_grammar->rule_map.values (A))
{
StatePointer q = p;
@@ -606,7 +606,7 @@ void Automaton::buildIncludesDigraph ()
if (! _M_grammar->isNonTerminal (name))
continue;
- foreach (RulePointer rule, _M_grammar->rule_map.values (name))
+ foreach (const RulePointer &rule, _M_grammar->rule_map.values (name))
{
StatePointer p = pp;
@@ -706,7 +706,7 @@ void Automaton::buildLookaheads ()
{
for (ItemPointer item = p->closure.begin (); item != p->closure.end (); ++item)
{
- foreach (Lookback lookback, lookbacks.values (item))
+ foreach (const Lookback &lookback, lookbacks.values (item))
{
StatePointer q = lookback.state;
diff --git a/src/tools/qlalr/lalr.h b/src/tools/qlalr/lalr.h
index 138b1bb876..bdd6609ba6 100644
--- a/src/tools/qlalr/lalr.h
+++ b/src/tools/qlalr/lalr.h
@@ -396,6 +396,9 @@ public:
StatePointer state;
Name nt;
};
+QT_BEGIN_NAMESPACE
+Q_DECLARE_TYPEINFO(OrderedSet<Node<Read> >::const_iterator, Q_PRIMITIVE_TYPE);
+QT_END_NAMESPACE
class Include
{
@@ -417,6 +420,9 @@ public:
StatePointer state;
Name nt;
};
+QT_BEGIN_NAMESPACE
+Q_DECLARE_TYPEINFO(OrderedSet<Node<Include> >::const_iterator, Q_PRIMITIVE_TYPE);
+QT_END_NAMESPACE
class Automaton
{
diff --git a/src/tools/qlalr/parsetable.cpp b/src/tools/qlalr/parsetable.cpp
index 8b62e597ef..77e2219987 100644
--- a/src/tools/qlalr/parsetable.cpp
+++ b/src/tools/qlalr/parsetable.cpp
@@ -91,7 +91,7 @@ void ParseTable::operator () (Automaton *aut)
first = false;
- foreach (Name la, aut->lookaheads.value (item))
+ foreach (const Name &la, aut->lookaheads.value (item))
out << " " << *la << " reduce using rule " << aut->id (item->rule) << " (" << *item->rule->lhs << ")" << endl;
}
diff --git a/src/tools/rcc/rcc.cpp b/src/tools/rcc/rcc.cpp
index 7bd1ac0bc6..40e77c9876 100644
--- a/src/tools/rcc/rcc.cpp
+++ b/src/tools/rcc/rcc.cpp
@@ -366,6 +366,7 @@ enum RCCXmlTag {
ResourceTag,
FileTag
};
+Q_DECLARE_TYPEINFO(RCCXmlTag, Q_PRIMITIVE_TYPE);
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
const QString &fname, QString currentPath, bool ignoreErrors)
@@ -938,10 +939,14 @@ bool RCCResourceLibrary::writeDataNames()
return true;
}
-static bool qt_rcc_compare_hash(const RCCFileInfo *left, const RCCFileInfo *right)
+struct qt_rcc_compare_hash
{
- return qt_hash(left->m_name) < qt_hash(right->m_name);
-}
+ typedef bool result_type;
+ result_type operator()(const RCCFileInfo *left, const RCCFileInfo *right) const
+ {
+ return qt_hash(left->m_name) < qt_hash(right->m_name);
+ }
+};
bool RCCResourceLibrary::writeDataStructure()
{
@@ -963,7 +968,7 @@ bool RCCResourceLibrary::writeDataStructure()
//sort by hash value for binary lookup
QList<RCCFileInfo*> m_children = file->m_children.values();
- std::sort(m_children.begin(), m_children.end(), qt_rcc_compare_hash);
+ std::sort(m_children.begin(), m_children.end(), qt_rcc_compare_hash());
//write out the actual data now
for (int i = 0; i < m_children.size(); ++i) {
@@ -982,7 +987,7 @@ bool RCCResourceLibrary::writeDataStructure()
//sort by hash value for binary lookup
QList<RCCFileInfo*> m_children = file->m_children.values();
- std::sort(m_children.begin(), m_children.end(), qt_rcc_compare_hash);
+ std::sort(m_children.begin(), m_children.end(), qt_rcc_compare_hash());
//write out the actual data now
for (int i = 0; i < m_children.size(); ++i) {
diff --git a/src/tools/uic/cpp/cppwriteincludes.h b/src/tools/uic/cpp/cppwriteincludes.h
index 6e7888c62b..e4f1aedb7e 100644
--- a/src/tools/uic/cpp/cppwriteincludes.h
+++ b/src/tools/uic/cpp/cppwriteincludes.h
@@ -36,7 +36,6 @@
#include "treewalker.h"
-#include <qhash.h>
#include <qmap.h>
#include <qset.h>
#include <qstring.h>
diff --git a/src/tools/uic/uic.h b/src/tools/uic/uic.h
index e88326f0da..b65b662473 100644
--- a/src/tools/uic/uic.h
+++ b/src/tools/uic/uic.h
@@ -38,7 +38,6 @@
#include "customwidgetsinfo.h"
#include <qstring.h>
#include <qstringlist.h>
-#include <qhash.h>
#include <qstack.h>
#include <qxmlstream.h>
diff --git a/src/widgets/accessible/complexwidgets.cpp b/src/widgets/accessible/complexwidgets.cpp
index 60a1329d5e..649a7f4363 100644
--- a/src/widgets/accessible/complexwidgets.cpp
+++ b/src/widgets/accessible/complexwidgets.cpp
@@ -172,7 +172,7 @@ QAccessibleTabBar::QAccessibleTabBar(QWidget *w)
QAccessibleTabBar::~QAccessibleTabBar()
{
- foreach (QAccessible::Id id, m_childInterfaces.values())
+ foreach (QAccessible::Id id, m_childInterfaces)
QAccessible::deleteAccessibleInterface(id);
}
diff --git a/src/widgets/accessible/itemviews.cpp b/src/widgets/accessible/itemviews.cpp
index 4f6cb56060..23a459c7e6 100644
--- a/src/widgets/accessible/itemviews.cpp
+++ b/src/widgets/accessible/itemviews.cpp
@@ -94,7 +94,7 @@ bool QAccessibleTable::isValid() const
QAccessibleTable::~QAccessibleTable()
{
- Q_FOREACH (QAccessible::Id id, childToId.values())
+ Q_FOREACH (QAccessible::Id id, childToId)
QAccessible::deleteAccessibleInterface(id);
}
@@ -198,7 +198,9 @@ QList<QAccessibleInterface *> QAccessibleTable::selectedCells() const
QList<QAccessibleInterface*> cells;
if (!view()->selectionModel())
return cells;
- Q_FOREACH (const QModelIndex &index, view()->selectionModel()->selectedIndexes())
+ const QModelIndexList selectedIndexes = view()->selectionModel()->selectedIndexes();
+ cells.reserve(selectedIndexes.size());
+ Q_FOREACH (const QModelIndex &index, selectedIndexes)
cells.append(child(logicalIndex(index)));
return cells;
}
@@ -208,9 +210,11 @@ QList<int> QAccessibleTable::selectedColumns() const
if (!view()->selectionModel())
return QList<int>();
QList<int> columns;
- Q_FOREACH (const QModelIndex &index, view()->selectionModel()->selectedColumns()) {
+ const QModelIndexList selectedColumns = view()->selectionModel()->selectedColumns();
+ columns.reserve(selectedColumns.size());
+ Q_FOREACH (const QModelIndex &index, selectedColumns)
columns.append(index.column());
- }
+
return columns;
}
@@ -219,9 +223,11 @@ QList<int> QAccessibleTable::selectedRows() const
if (!view()->selectionModel())
return QList<int>();
QList<int> rows;
- Q_FOREACH (const QModelIndex &index, view()->selectionModel()->selectedRows()) {
+ const QModelIndexList selectedRows = view()->selectionModel()->selectedRows();
+ rows.reserve(selectedRows.size());
+ Q_FOREACH (const QModelIndex &index, selectedRows)
rows.append(index.row());
- }
+
return rows;
}
@@ -526,7 +532,7 @@ void QAccessibleTable::modelChange(QAccessibleTableModelChangeEvent *event)
switch (event->modelChangeType()) {
case QAccessibleTableModelChangeEvent::ModelReset:
- Q_FOREACH (QAccessible::Id id, childToId.values())
+ Q_FOREACH (QAccessible::Id id, childToId)
QAccessible::deleteAccessibleInterface(id);
childToId.clear();
break;
@@ -1010,6 +1016,9 @@ QAccessible::Role QAccessibleTableCell::role() const
QAccessible::State QAccessibleTableCell::state() const
{
QAccessible::State st;
+ if (!view)
+ return st;
+
QRect globalRect = view->rect();
globalRect.translate(view->mapToGlobal(QPoint(0,0)));
if (!globalRect.intersects(rect()))
diff --git a/src/widgets/accessible/itemviews.h b/src/widgets/accessible/itemviews.h
index c1bd70a390..33757f168a 100644
--- a/src/widgets/accessible/itemviews.h
+++ b/src/widgets/accessible/itemviews.h
@@ -161,13 +161,13 @@ public:
QAccessibleTableCell(QAbstractItemView *view, const QModelIndex &m_index, QAccessible::Role role);
void *interface_cast(QAccessible::InterfaceType t) Q_DECL_OVERRIDE;
- QObject *object() const Q_DECL_OVERRIDE { return 0; }
+ QObject *object() const Q_DECL_OVERRIDE { return Q_NULLPTR; }
QAccessible::Role role() const Q_DECL_OVERRIDE;
QAccessible::State state() const Q_DECL_OVERRIDE;
QRect rect() const Q_DECL_OVERRIDE;
bool isValid() const Q_DECL_OVERRIDE;
- QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return 0; }
+ QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return Q_NULLPTR; }
int childCount() const Q_DECL_OVERRIDE { return 0; }
int indexOfChild(const QAccessibleInterface *) const Q_DECL_OVERRIDE { return -1; }
@@ -213,13 +213,13 @@ public:
// For header cells, pass the header view in addition
QAccessibleTableHeaderCell(QAbstractItemView *view, int index, Qt::Orientation orientation);
- QObject *object() const Q_DECL_OVERRIDE { return 0; }
+ QObject *object() const Q_DECL_OVERRIDE { return Q_NULLPTR; }
QAccessible::Role role() const Q_DECL_OVERRIDE;
QAccessible::State state() const Q_DECL_OVERRIDE;
QRect rect() const Q_DECL_OVERRIDE;
bool isValid() const Q_DECL_OVERRIDE;
- QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return 0; }
+ QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return Q_NULLPTR; }
int childCount() const Q_DECL_OVERRIDE { return 0; }
int indexOfChild(const QAccessibleInterface *) const Q_DECL_OVERRIDE { return -1; }
@@ -250,13 +250,13 @@ public:
:view(view_)
{}
- QObject *object() const Q_DECL_OVERRIDE { return 0; }
+ QObject *object() const Q_DECL_OVERRIDE { return Q_NULLPTR; }
QAccessible::Role role() const Q_DECL_OVERRIDE { return QAccessible::Pane; }
QAccessible::State state() const Q_DECL_OVERRIDE { return QAccessible::State(); }
QRect rect() const Q_DECL_OVERRIDE { return QRect(); }
bool isValid() const Q_DECL_OVERRIDE { return true; }
- QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return 0; }
+ QAccessibleInterface *childAt(int, int) const Q_DECL_OVERRIDE { return Q_NULLPTR; }
int childCount() const Q_DECL_OVERRIDE { return 0; }
int indexOfChild(const QAccessibleInterface *) const Q_DECL_OVERRIDE { return -1; }
@@ -267,7 +267,7 @@ public:
return QAccessible::queryAccessibleInterface(view);
}
QAccessibleInterface *child(int) const Q_DECL_OVERRIDE {
- return 0;
+ return Q_NULLPTR;
}
private:
diff --git a/src/widgets/accessible/qaccessiblewidgets.cpp b/src/widgets/accessible/qaccessiblewidgets.cpp
index a2bf14b25b..c598a5b4cb 100644
--- a/src/widgets/accessible/qaccessiblewidgets.cpp
+++ b/src/widgets/accessible/qaccessiblewidgets.cpp
@@ -826,6 +826,9 @@ QString QAccessibleTextWidget::attributes(int offset, int *startOffset, int *end
attrs["text-underline-type"] = QStringLiteral("single"); // if underlineStyleValue is set, there is an underline, and Qt does not support other than single ones
} // else both are "none" which is the default - no need to set them
+ if (block.textDirection() == Qt::RightToLeft)
+ attrs["writing-mode"] = QStringLiteral("rl");
+
QTextCharFormat::VerticalAlignment alignment = charFormat.verticalAlignment();
attrs["text-position"] = QString::fromLatin1((alignment == QTextCharFormat::AlignSubScript) ? "sub" : ((alignment == QTextCharFormat::AlignSuperScript) ? "super" : "baseline" ));
diff --git a/src/widgets/dialogs/dialogs.pri b/src/widgets/dialogs/dialogs.pri
index a5b4883db8..4f4a9b1517 100644
--- a/src/widgets/dialogs/dialogs.pri
+++ b/src/widgets/dialogs/dialogs.pri
@@ -2,7 +2,6 @@
HEADERS += \
dialogs/qcolordialog.h \
- dialogs/qcolordialog_p.h \
dialogs/qfscompleter_p.h \
dialogs/qdialog.h \
dialogs/qdialog_p.h \
diff --git a/src/widgets/dialogs/qcolordialog.cpp b/src/widgets/dialogs/qcolordialog.cpp
index 5f3161f39f..2ebbaaee10 100644
--- a/src/widgets/dialogs/qcolordialog.cpp
+++ b/src/widgets/dialogs/qcolordialog.cpp
@@ -31,7 +31,7 @@
**
****************************************************************************/
-#include "qcolordialog_p.h"
+#include "qcolordialog.h"
#ifndef QT_NO_COLORDIALOG
@@ -49,6 +49,7 @@
#include "qpixmap.h"
#include "qpushbutton.h"
#include "qsettings.h"
+#include "qsharedpointer.h"
#include "qstyle.h"
#include "qstyleoption.h"
#include "qvalidator.h"
@@ -58,13 +59,115 @@
#include "qscreen.h"
#include "qcursor.h"
#include "qtimer.h"
+#include "qwindow.h"
+
+#include "private/qdialog_p.h"
#include <algorithm>
QT_BEGIN_NAMESPACE
+namespace {
+class QColorLuminancePicker;
+class QColorPicker;
+class QColorShower;
+class QWellArray;
+class QColorPickingEventFilter;
+} // unnamed namespace
+
+class QColorDialogPrivate : public QDialogPrivate
+{
+ Q_DECLARE_PUBLIC(QColorDialog)
+
+public:
+ enum SetColorMode {
+ ShowColor = 0x1,
+ SelectColor = 0x2,
+ SetColorAll = ShowColor | SelectColor
+ };
+
+ QColorDialogPrivate() : options(new QColorDialogOptions)
+#ifdef Q_OS_WIN32
+ , updateTimer(0)
+#endif
+ {}
+
+ QPlatformColorDialogHelper *platformColorDialogHelper() const
+ { return static_cast<QPlatformColorDialogHelper *>(platformHelper()); }
+
+ void init(const QColor &initial);
+ void initWidgets();
+ QRgb currentColor() const;
+ QColor currentQColor() const;
+ void setCurrentColor(const QColor &color, SetColorMode setColorMode = SetColorAll);
+ void setCurrentRgbColor(QRgb rgb);
+ void setCurrentQColor(const QColor &color);
+ bool selectColor(const QColor &color);
+ QColor grabScreenColor(const QPoint &p);
+
+ 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_nextCustom(int, int);
+ void _q_newCustom(int, int);
+ void _q_newStandard(int, int);
+ void _q_pickScreenColor();
+ void _q_updateColorPicking();
+ void updateColorLabelText(const QPoint &);
+ void updateColorPicking(const QPoint &pos);
+ void releaseColorPicking();
+ bool handleColorPickingMouseMove(QMouseEvent *e);
+ bool handleColorPickingMouseButtonRelease(QMouseEvent *e);
+ bool handleColorPickingKeyPress(QKeyEvent *e);
+
+ bool canBeNativeDialog() const Q_DECL_OVERRIDE;
+
+ QWellArray *custom;
+ QWellArray *standard;
+
+ QDialogButtonBox *buttons;
+ QVBoxLayout *leftLay;
+ QColorPicker *cp;
+ QColorLuminancePicker *lp;
+ QColorShower *cs;
+ QLabel *lblBasicColors;
+ QLabel *lblCustomColors;
+ QLabel *lblScreenColorInfo;
+ QPushButton *ok;
+ QPushButton *cancel;
+ QPushButton *addCusBt;
+ QPushButton *screenColorPickerButton;
+ QColor selectedQColor;
+ int nextCust;
+ bool smallDisplay;
+ bool screenColorPicking;
+ QColorPickingEventFilter *colorPickingEventFilter;
+ QRgb beforeScreenColorPicking;
+ QSharedPointer<QColorDialogOptions> options;
+
+ QPointer<QObject> receiverToDisconnectOnClose;
+ QByteArray memberToDisconnectOnClose;
+#ifdef Q_OS_WIN32
+ QTimer *updateTimer;
+ QWindow dummyTransparentWindow;
+#endif
+
+private:
+ virtual void initHelper(QPlatformDialogHelper *h) Q_DECL_OVERRIDE;
+ virtual void helperPrepareShow(QPlatformDialogHelper *h) Q_DECL_OVERRIDE;
+};
+
//////////// QWellArray BEGIN
+namespace {
+
struct QWellArrayData;
class QWellArray : public QWidget
@@ -446,6 +549,8 @@ private:
QColorDialogPrivate *m_dp;
};
+} // unnamed namespace
+
/*!
Returns the number of custom colors supported by QColorDialog. All
color dialogs share the same custom colors.
@@ -506,6 +611,8 @@ static inline void rgb2hsv(QRgb rgb, int &h, int &s, int &v)
c.getHsv(&h, &s, &v);
}
+namespace {
+
class QColorWell : public QWellArray
{
public:
@@ -975,8 +1082,8 @@ private:
QColorDialog *colorDialog;
QGridLayout *gl;
- friend class QColorDialog;
- friend class QColorDialogPrivate;
+ friend class QT_PREPEND_NAMESPACE(QColorDialog);
+ friend class QT_PREPEND_NAMESPACE(QColorDialogPrivate);
};
class QColorShowLabel : public QFrame
@@ -1265,6 +1372,8 @@ QColorShower::QColorShower(QColorDialog *parent)
retranslateStrings();
}
+} // unnamed namespace
+
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); }
@@ -1605,9 +1714,6 @@ void QColorDialogPrivate::init(const QColor &initial)
if (!nativeDialogInUse)
initWidgets();
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
- delegate = 0;
-#endif
#ifdef Q_OS_WIN32
dummyTransparentWindow.resize(1, 1);
dummyTransparentWindow.setFlags(Qt::Tool | Qt::FramelessWindowHint);
@@ -2009,11 +2115,6 @@ QColorDialog::ColorDialogOptions QColorDialog::options() const
\sa color, colorSelected()
*/
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
-// can only have one Cocoa color panel active
-bool QColorDialogPrivate::sharedColorPanelAvailable = true;
-#endif
-
/*!
\fn void QColorDialog::colorSelected(const QColor &color);
@@ -2040,23 +2141,6 @@ void QColorDialog::setVisible(bool visible)
if (visible)
d->selectedQColor = QColor();
-#if defined(Q_DEAD_CODE_FROM_QT4_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->nativeDialogInUse) {
d->setNativeDialogVisible(visible);
// Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
@@ -2065,7 +2149,6 @@ void QColorDialog::setVisible(bool visible)
} else {
setAttribute(Qt::WA_DontShowOnScreen, false);
}
-#endif
QDialog::setVisible(visible);
}
@@ -2141,13 +2224,7 @@ QRgb QColorDialog::getRgba(QRgb initial, bool *ok, QWidget *parent)
QColorDialog::~QColorDialog()
{
-#if defined(Q_DEAD_CODE_FROM_QT4_MAC)
- Q_D(QColorDialog);
- if (d->delegate) {
- d->releaseCocoaColorPanelDelegate();
- QColorDialogPrivate::sharedColorPanelAvailable = true;
- }
-#endif
+
}
/*!
diff --git a/src/widgets/dialogs/qcolordialog.h b/src/widgets/dialogs/qcolordialog.h
index 16339f56c4..de18e6f9ed 100644
--- a/src/widgets/dialogs/qcolordialog.h
+++ b/src/widgets/dialogs/qcolordialog.h
@@ -61,8 +61,8 @@ public:
Q_DECLARE_FLAGS(ColorDialogOptions, ColorDialogOption)
- explicit QColorDialog(QWidget *parent = 0);
- explicit QColorDialog(const QColor &initial, QWidget *parent = 0);
+ explicit QColorDialog(QWidget *parent = Q_NULLPTR);
+ explicit QColorDialog(const QColor &initial, QWidget *parent = Q_NULLPTR);
~QColorDialog();
void setCurrentColor(const QColor &color);
@@ -81,12 +81,12 @@ public:
void setVisible(bool visible) Q_DECL_OVERRIDE;
static QColor getColor(const QColor &initial = Qt::white,
- QWidget *parent = 0,
+ QWidget *parent = Q_NULLPTR,
const QString &title = QString(),
- ColorDialogOptions options = 0);
+ ColorDialogOptions options = ColorDialogOptions());
// obsolete
- static QRgb getRgba(QRgb rgba = 0xffffffff, bool *ok = 0, QWidget *parent = 0);
+ static QRgb getRgba(QRgb rgba = 0xffffffff, bool *ok = Q_NULLPTR, QWidget *parent = Q_NULLPTR);
static int customCount();
static QColor customColor(int index);
@@ -113,7 +113,6 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_newStandard(int, int))
Q_PRIVATE_SLOT(d_func(), void _q_pickScreenColor())
Q_PRIVATE_SLOT(d_func(), void _q_updateColorPicking())
- friend class QColorShower;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QColorDialog::ColorDialogOptions)
diff --git a/src/widgets/dialogs/qcolordialog_p.h b/src/widgets/dialogs/qcolordialog_p.h
deleted file mode 100644
index 1a881eae70..0000000000
--- a/src/widgets/dialogs/qcolordialog_p.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $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"
-#include "qsharedpointer.h"
-#include "qwindow.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 QColorPickingEventFilter;
-class QTimer;
-
-class QColorDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QColorDialog)
-
-public:
- enum SetColorMode {
- ShowColor = 0x1,
- SelectColor = 0x2,
- SetColorAll = ShowColor | SelectColor
- };
-
- QColorDialogPrivate() : options(new QColorDialogOptions)
-#ifdef Q_OS_WIN32
- , updateTimer(0)
-#endif
- {}
-
- QPlatformColorDialogHelper *platformColorDialogHelper() const
- { return static_cast<QPlatformColorDialogHelper *>(platformHelper()); }
-
- void init(const QColor &initial);
- void initWidgets();
- QRgb currentColor() const;
- QColor currentQColor() const;
- void setCurrentColor(const QColor &color, SetColorMode setColorMode = SetColorAll);
- void setCurrentRgbColor(QRgb rgb);
- void setCurrentQColor(const QColor &color);
- bool selectColor(const QColor &color);
- QColor grabScreenColor(const QPoint &p);
-
- 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_nextCustom(int, int);
- void _q_newCustom(int, int);
- void _q_newStandard(int, int);
- void _q_pickScreenColor();
- void _q_updateColorPicking();
- void updateColorLabelText(const QPoint &);
- void updateColorPicking(const QPoint &pos);
- void releaseColorPicking();
- bool handleColorPickingMouseMove(QMouseEvent *e);
- bool handleColorPickingMouseButtonRelease(QMouseEvent *e);
- bool handleColorPickingKeyPress(QKeyEvent *e);
-
- bool canBeNativeDialog() const Q_DECL_OVERRIDE;
-
- QWellArray *custom;
- QWellArray *standard;
-
- QDialogButtonBox *buttons;
- QVBoxLayout *leftLay;
- QColorPicker *cp;
- QColorLuminancePicker *lp;
- QColorShower *cs;
- QLabel *lblBasicColors;
- QLabel *lblCustomColors;
- QLabel *lblScreenColorInfo;
- QPushButton *ok;
- QPushButton *cancel;
- QPushButton *addCusBt;
- QPushButton *screenColorPickerButton;
- QColor selectedQColor;
- int nextCust;
- bool smallDisplay;
- bool screenColorPicking;
- QColorPickingEventFilter *colorPickingEventFilter;
- QRgb beforeScreenColorPicking;
- QSharedPointer<QColorDialogOptions> options;
-
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-#ifdef Q_OS_WIN32
- QTimer *updateTimer;
- QWindow dummyTransparentWindow;
-#endif
-
-#ifdef Q_DEAD_CODE_FROM_QT4_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
-private:
- virtual void initHelper(QPlatformDialogHelper *h) Q_DECL_OVERRIDE;
- virtual void helperPrepareShow(QPlatformDialogHelper *h) Q_DECL_OVERRIDE;
-};
-
-#endif // QT_NO_COLORDIALOG
-
-QT_END_NAMESPACE
-
-#endif // QCOLORDIALOG_P_H
diff --git a/src/widgets/dialogs/qdialog.h b/src/widgets/dialogs/qdialog.h
index cd53378f9a..5ea5375387 100644
--- a/src/widgets/dialogs/qdialog.h
+++ b/src/widgets/dialogs/qdialog.h
@@ -51,7 +51,7 @@ class Q_WIDGETS_EXPORT QDialog : public QWidget
Q_PROPERTY(bool modal READ isModal WRITE setModal)
public:
- explicit QDialog(QWidget *parent = 0, Qt::WindowFlags f = 0);
+ explicit QDialog(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
~QDialog();
enum DialogCode { Rejected, Accepted };
@@ -90,7 +90,7 @@ public Q_SLOTS:
void showExtension(bool);
protected:
- QDialog(QDialogPrivate &, QWidget *parent, Qt::WindowFlags f = 0);
+ QDialog(QDialogPrivate &, QWidget *parent, Qt::WindowFlags f = Qt::WindowFlags());
#if defined(Q_OS_WINCE)
bool event(QEvent *e);
diff --git a/src/widgets/dialogs/qerrormessage.cpp b/src/widgets/dialogs/qerrormessage.cpp
index 4c3a5497d4..855bae3c9f 100644
--- a/src/widgets/dialogs/qerrormessage.cpp
+++ b/src/widgets/dialogs/qerrormessage.cpp
@@ -47,9 +47,10 @@
#include "qpixmap.h"
#include "qmetaobject.h"
#include "qthread.h"
-#include "qqueue.h"
#include "qset.h"
+#include <queue>
+
#include <stdio.h>
#include <stdlib.h>
@@ -68,16 +69,18 @@ public:
QCheckBox * again;
QTextEdit * errors;
QLabel * icon;
- QQueue<QPair<QString, QString> > pending;
+ std::queue<QPair<QString, QString> > pending;
QSet<QString> doNotShow;
QSet<QString> doNotShowType;
QString currentMessage;
QString currentType;
+ bool isMessageToBeShown(const QString &message, const QString &type) const;
bool nextPending();
void retranslateStrings();
};
+namespace {
class QErrorMessageTextView : public QTextEdit
{
public:
@@ -87,6 +90,7 @@ public:
virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE;
virtual QSize sizeHint() const Q_DECL_OVERRIDE;
};
+} // unnamed namespace
QSize QErrorMessageTextView::minimumSizeHint() const
{
@@ -217,29 +221,32 @@ 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);
+ QGridLayout * grid = new QGridLayout(this);
+
+ connect(d->ok, SIGNAL(clicked()), this, SLOT(accept()));
+ grid->addWidget(d->icon, 0, 0, Qt::AlignTop);
+ grid->addWidget(d->errors, 0, 1);
+ grid->addWidget(d->again, 1, 1, Qt::AlignTop);
+ grid->addWidget(d->ok, 2, 0, 1, 2, Qt::AlignCenter);
+ grid->setColumnStretch(1, 42);
+ grid->setRowStretch(0, 42);
+#ifndef QT_NO_MESSAGEBOX
+ d->icon->setPixmap(QMessageBox::standardIcon(QMessageBox::Information));
+ d->icon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
+#endif
+ d->again->setChecked(true);
#if defined(Q_OS_WINCE)
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();
}
@@ -265,11 +272,13 @@ QErrorMessage::~QErrorMessage()
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);
+ if (!d->again->isChecked()) {
+ if (d->currentType.isEmpty()) {
+ if (!d->currentMessage.isEmpty())
+ d->doNotShow.insert(d->currentMessage);
+ } else {
+ d->doNotShowType.insert(d->currentType);
+ }
}
d->currentMessage.clear();
d->currentType.clear();
@@ -301,20 +310,27 @@ QErrorMessage * QErrorMessage::qtHandler()
/*! \internal */
+bool QErrorMessagePrivate::isMessageToBeShown(const QString &message, const QString &type) const
+{
+ return !message.isEmpty()
+ && (type.isEmpty() ? !doNotShow.contains(message) : !doNotShowType.contains(type));
+}
+
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)))) {
+ while (!pending.empty()) {
+ QPair<QString,QString> &pendingMessage = pending.front();
+ QString message = qMove(pendingMessage.first);
+ QString type = qMove(pendingMessage.second);
+ pending.pop();
+ if (isMessageToBeShown(message, type)) {
#ifndef QT_NO_TEXTHTMLPARSER
errors->setHtml(message);
#else
errors->setPlainText(message);
#endif
- currentMessage = message;
- currentType = type;
+ currentMessage = qMove(message);
+ currentType = qMove(type);
return true;
}
}
@@ -333,12 +349,7 @@ bool QErrorMessagePrivate::nextPending()
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();
+ showMessage(message, QString());
}
/*!
@@ -358,9 +369,9 @@ void QErrorMessage::showMessage(const QString &message)
void QErrorMessage::showMessage(const QString &message, const QString &type)
{
Q_D(QErrorMessage);
- if (d->doNotShow.contains(message) && d->doNotShowType.contains(type))
+ if (!d->isMessageToBeShown(message, type))
return;
- d->pending.push_back(qMakePair(message,type));
+ d->pending.push(qMakePair(message, type));
if (!isVisible() && d->nextPending())
show();
}
diff --git a/src/widgets/dialogs/qerrormessage.h b/src/widgets/dialogs/qerrormessage.h
index 55d0b389b1..1d69515dfb 100644
--- a/src/widgets/dialogs/qerrormessage.h
+++ b/src/widgets/dialogs/qerrormessage.h
@@ -48,7 +48,7 @@ class Q_WIDGETS_EXPORT QErrorMessage: public QDialog
Q_OBJECT
Q_DECLARE_PRIVATE(QErrorMessage)
public:
- explicit QErrorMessage(QWidget* parent = 0);
+ explicit QErrorMessage(QWidget* parent = Q_NULLPTR);
~QErrorMessage();
static QErrorMessage * qtHandler();
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index 64e3f5069e..81beccd5c8 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -330,14 +330,8 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
*/
QT_BEGIN_INCLUDE_NAMESPACE
-#ifdef Q_DEAD_CODE_FROM_QT4_WIN
-#include <qwindowsstyle_p.h>
-#endif
#include <QMetaEnum>
#include <qshortcut.h>
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
-#include <qmacstyle_mac_p.h>
-#endif
QT_END_INCLUDE_NAMESPACE
/*!
@@ -1191,12 +1185,17 @@ QList<QUrl> QFileDialogPrivate::userSelectedFiles() const
if (!usingWidgets())
return addDefaultSuffixToUrls(selectedFiles_sys());
- foreach (const QModelIndex &index, qFileDialogUi->listView->selectionModel()->selectedRows())
+ const QModelIndexList selectedRows = qFileDialogUi->listView->selectionModel()->selectedRows();
+ files.reserve(selectedRows.size());
+ foreach (const QModelIndex &index, selectedRows)
files.append(QUrl::fromLocalFile(index.data(QFileSystemModel::FilePathRole).toString()));
- if (files.isEmpty() && !lineEdit()->text().isEmpty())
- foreach (const QString &path, typedFiles())
+ if (files.isEmpty() && !lineEdit()->text().isEmpty()) {
+ const QStringList typedFilesList = typedFiles();
+ files.reserve(typedFilesList.size());
+ foreach (const QString &path, typedFilesList)
files.append(QUrl::fromLocalFile(path));
+ }
return files;
}
@@ -1230,7 +1229,9 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList &files
QList<QUrl> QFileDialogPrivate::addDefaultSuffixToUrls(const QList<QUrl> &urlsToFix) const
{
QList<QUrl> urls;
- for (int i=0; i<urlsToFix.size(); ++i) {
+ const int numUrlsToFix = urlsToFix.size();
+ urls.reserve(numUrlsToFix);
+ for (int i = 0; i < numUrlsToFix; ++i) {
QUrl url = urlsToFix.at(i);
// if the filename has no suffix, add the default suffix
const QString defaultSuffix = options->defaultSuffix();
@@ -1254,7 +1255,9 @@ QStringList QFileDialog::selectedFiles() const
Q_D(const QFileDialog);
QStringList files;
- foreach (const QUrl &file, d->userSelectedFiles())
+ const QList<QUrl> userSelectedFiles = d->userSelectedFiles();
+ files.reserve(userSelectedFiles.size());
+ foreach (const QUrl &file, userSelectedFiles)
files.append(file.toLocalFile());
if (files.isEmpty() && d->usingWidgets()) {
const FileMode fm = fileMode();
@@ -1279,7 +1282,9 @@ QList<QUrl> QFileDialog::selectedUrls() const
return d->userSelectedFiles();
} else {
QList<QUrl> urls;
- foreach (const QString &file, selectedFiles())
+ const QStringList selectedFileList = selectedFiles();
+ urls.reserve(selectedFileList.size());
+ foreach (const QString &file, selectedFileList)
urls.append(QUrl::fromLocalFile(file));
return urls;
}
@@ -1358,7 +1363,9 @@ QStringList qt_strip_filters(const QStringList &filters)
{
QStringList strippedFilters;
QRegExp r(QString::fromLatin1(QPlatformFileDialogHelper::filterRegExp));
- for (int i = 0; i < filters.count(); ++i) {
+ const int numFilters = filters.count();
+ strippedFilters.reserve(numFilters);
+ for (int i = 0; i < numFilters; ++i) {
QString filterName;
int index = r.indexIn(filters[i]);
if (index >= 0)
@@ -1393,7 +1400,9 @@ 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) {
+ const int numFilters = filters.count();
+ cleanedFilters.reserve(numFilters);
+ for (int i = 0; i < numFilters; ++i) {
cleanedFilters << filters[i].simplified();
}
d->options->setNameFilters(cleanedFilters);
@@ -1693,6 +1702,30 @@ void QFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
d->retranslateWindowTitle();
}
+/*!
+ \property QFileDialog::supportedSchemes
+ \brief the URL schemes that the file dialog should allow navigating to.
+ \since 5.6
+
+ Setting this property allows to restrict the type of URLs the
+ user will be able to select. It is a way for the application to declare
+ the protocols it will support to fetch the file content. An empty list
+ means that no restriction is applied (the default).
+ Supported for local files ("file" scheme) is implicit and always enabled;
+ it is not necessary to include it in the restriction.
+*/
+
+void QFileDialog::setSupportedSchemes(const QStringList &schemes)
+{
+ Q_D(QFileDialog);
+ d->options->setSupportedSchemes(schemes);
+}
+
+QStringList QFileDialog::supportedSchemes() const
+{
+ return d_func()->options->supportedSchemes();
+}
+
/*
Returns the file system model index that is the root index in the
views
@@ -2089,8 +2122,8 @@ QString QFileDialog::getOpenFileName(QWidget *parent,
user will be able to select. It is a way for the application to declare
the protocols it will support to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled.
- it is not necessary to include in the restriction.
+ Supported for local files ("file" scheme) is implicit and always enabled;
+ it is not necessary to include it in the restriction.
When possible, this static function will use the native file dialog and
not a QFileDialog. On platforms which don't support selecting remote
@@ -2107,8 +2140,6 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- Q_UNUSED(supportedSchemes); // TODO
-
QFileDialogArgs args;
args.parent = parent;
args.caption = caption;
@@ -2119,6 +2150,7 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
args.options = options;
QFileDialog dialog(args);
+ dialog.setSupportedSchemes(supportedSchemes);
if (selectedFilter && !selectedFilter->isEmpty())
dialog.selectNameFilter(*selectedFilter);
if (dialog.exec() == QDialog::Accepted) {
@@ -2167,11 +2199,6 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
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 code/src_gui_dialogs_qfiledialog.cpp 10
-
\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.
@@ -2188,6 +2215,7 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
const QStringList schemes = QStringList(QStringLiteral("file"));
const QList<QUrl> selectedUrls = getOpenFileUrls(parent, caption, QUrl::fromLocalFile(dir), filter, selectedFilter, options, schemes);
QStringList fileNames;
+ fileNames.reserve(selectedUrls.size());
foreach (const QUrl &url, selectedUrls)
fileNames << url.toLocalFile();
return fileNames;
@@ -2211,8 +2239,8 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
user will be able to select. It is a way for the application to declare
the protocols it will support to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled.
- it is not necessary to include in the restriction.
+ Supported for local files ("file" scheme) is implicit and always enabled;
+ it is not necessary to include it in the restriction.
When possible, this static function will use the native file dialog and
not a QFileDialog. On platforms which don't support selecting remote
@@ -2229,8 +2257,6 @@ QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- Q_UNUSED(supportedSchemes);
-
QFileDialogArgs args;
args.parent = parent;
args.caption = caption;
@@ -2241,6 +2267,7 @@ QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
args.options = options;
QFileDialog dialog(args);
+ dialog.setSupportedSchemes(supportedSchemes);
if (selectedFilter && !selectedFilter->isEmpty())
dialog.selectNameFilter(*selectedFilter);
if (dialog.exec() == QDialog::Accepted) {
@@ -2330,8 +2357,8 @@ QString QFileDialog::getSaveFileName(QWidget *parent,
user will be able to select. It is a way for the application to declare
the protocols it will support to save the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled.
- it is not necessary to include in the restriction.
+ Supported for local files ("file" scheme) is implicit and always enabled;
+ it is not necessary to include it in the restriction.
When possible, this static function will use the native file dialog and
not a QFileDialog. On platforms which don't support selecting remote
@@ -2348,8 +2375,6 @@ QUrl QFileDialog::getSaveFileUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- Q_UNUSED(supportedSchemes);
-
QFileDialogArgs args;
args.parent = parent;
args.caption = caption;
@@ -2360,6 +2385,7 @@ QUrl QFileDialog::getSaveFileUrl(QWidget *parent,
args.options = options;
QFileDialog dialog(args);
+ dialog.setSupportedSchemes(supportedSchemes);
dialog.setAcceptMode(AcceptSave);
if (selectedFilter && !selectedFilter->isEmpty())
dialog.selectNameFilter(*selectedFilter);
@@ -2440,8 +2466,8 @@ QString QFileDialog::getExistingDirectory(QWidget *parent,
user will be able to select. It is a way for the application to declare
the protocols it will support to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled.
- it is not necessary to include in the restriction.
+ Supported for local files ("file" scheme) is implicit and always enabled;
+ it is not necessary to include it in the restriction.
When possible, this static function will use the native file dialog and
not a QFileDialog. On platforms which don't support selecting remote
@@ -2456,8 +2482,6 @@ QUrl QFileDialog::getExistingDirectoryUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- Q_UNUSED(supportedSchemes);
-
QFileDialogArgs args;
args.parent = parent;
args.caption = caption;
@@ -2466,6 +2490,7 @@ QUrl QFileDialog::getExistingDirectoryUrl(QWidget *parent,
args.options = options;
QFileDialog dialog(args);
+ dialog.setSupportedSchemes(supportedSchemes);
if (dialog.exec() == QDialog::Accepted)
return dialog.selectedUrls().value(0);
return QUrl();
@@ -2667,7 +2692,9 @@ void QFileDialogPrivate::saveSettings()
settings.setValue(QLatin1String("treeViewHeader"), qFileDialogUi->treeView->header()->saveState());
}
QStringList historyUrls;
- foreach (const QString &path, q->history())
+ const QStringList history = q->history();
+ historyUrls.reserve(history.size());
+ foreach (const QString &path, history)
historyUrls << QUrl::fromLocalFile(path).toString();
settings.setValue(QLatin1String("history"), historyUrls);
settings.setValue(QLatin1String("lastVisited"), lastVisitedDir()->toString());
@@ -2959,7 +2986,7 @@ void QFileDialogPrivate::createWidgets()
q->setHistory(options->history());
if (options->initiallySelectedFiles().count() == 1)
q->selectFile(options->initiallySelectedFiles().first().fileName());
- foreach (QUrl url, options->initiallySelectedFiles())
+ foreach (const QUrl &url, options->initiallySelectedFiles())
q->selectUrl(url);
lineEdit()->selectAll();
_q_updateOkButton();
@@ -3779,7 +3806,7 @@ 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()));
+ return QString::fromLocal8Bit(qgetenv(string.mid(1).toLatin1().constData()));
}
#else
if (string.size() > 2 && string.startsWith(QLatin1Char('%')) && string.endsWith(QLatin1Char('%'))) {
diff --git a/src/widgets/dialogs/qfiledialog.h b/src/widgets/dialogs/qfiledialog.h
index 95209bceb5..ffe49a2dd2 100644
--- a/src/widgets/dialogs/qfiledialog.h
+++ b/src/widgets/dialogs/qfiledialog.h
@@ -66,6 +66,7 @@ class Q_WIDGETS_EXPORT QFileDialog : public QDialog
Q_PROPERTY(bool nameFilterDetailsVisible READ isNameFilterDetailsVisible
WRITE setNameFilterDetailsVisible DESIGNABLE false)
Q_PROPERTY(Options options READ options WRITE setOptions)
+ Q_PROPERTY(QStringList supportedSchemes READ supportedSchemes WRITE setSupportedSchemes)
public:
enum ViewMode { Detail, List };
@@ -91,7 +92,7 @@ public:
Q_DECLARE_FLAGS(Options, Option)
QFileDialog(QWidget *parent, Qt::WindowFlags f);
- explicit QFileDialog(QWidget *parent = 0,
+ explicit QFileDialog(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QString &directory = QString(),
const QString &filter = QString());
@@ -167,6 +168,9 @@ public:
void setLabelText(DialogLabel label, const QString &text);
QString labelText(DialogLabel label) const;
+ void setSupportedSchemes(const QStringList &schemes);
+ QStringList supportedSchemes() const;
+
#ifndef QT_NO_PROXYMODEL
void setProxyModel(QAbstractProxyModel *model);
QAbstractProxyModel *proxyModel() const;
@@ -196,60 +200,60 @@ Q_SIGNALS:
public:
- static QString getOpenFileName(QWidget *parent = 0,
+ static QString getOpenFileName(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QString &dir = QString(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options());
- static QUrl getOpenFileUrl(QWidget *parent = 0,
+ static QUrl getOpenFileUrl(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QUrl &dir = QUrl(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0,
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options(),
const QStringList &supportedSchemes = QStringList());
- static QString getSaveFileName(QWidget *parent = 0,
+ static QString getSaveFileName(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QString &dir = QString(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options());
- static QUrl getSaveFileUrl(QWidget *parent = 0,
+ static QUrl getSaveFileUrl(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QUrl &dir = QUrl(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0,
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options(),
const QStringList &supportedSchemes = QStringList());
- static QString getExistingDirectory(QWidget *parent = 0,
+ static QString getExistingDirectory(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QString &dir = QString(),
Options options = ShowDirsOnly);
- static QUrl getExistingDirectoryUrl(QWidget *parent = 0,
+ static QUrl getExistingDirectoryUrl(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QUrl &dir = QUrl(),
Options options = ShowDirsOnly,
const QStringList &supportedSchemes = QStringList());
- static QStringList getOpenFileNames(QWidget *parent = 0,
+ static QStringList getOpenFileNames(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QString &dir = QString(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options());
- static QList<QUrl> getOpenFileUrls(QWidget *parent = 0,
+ static QList<QUrl> getOpenFileUrls(QWidget *parent = Q_NULLPTR,
const QString &caption = QString(),
const QUrl &dir = QUrl(),
const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0,
+ QString *selectedFilter = Q_NULLPTR,
+ Options options = Options(),
const QStringList &supportedSchemes = QStringList());
diff --git a/src/widgets/dialogs/qfilesystemmodel.cpp b/src/widgets/dialogs/qfilesystemmodel.cpp
index 4859231d95..fd49246e9f 100644
--- a/src/widgets/dialogs/qfilesystemmodel.cpp
+++ b/src/widgets/dialogs/qfilesystemmodel.cpp
@@ -259,10 +259,7 @@ 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;
+ return d->index(node, column);
}
/*!
@@ -562,7 +559,7 @@ QModelIndex QFileSystemModel::parent(const QModelIndex &index) const
return the index for node
*/
-QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileSystemNode *node) const
+QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileSystemNode *node, int column) const
{
Q_Q(const QFileSystemModel);
QFileSystemModelPrivate::QFileSystemNode *parentNode = (node ? node->parent : 0);
@@ -575,7 +572,7 @@ QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileS
return QModelIndex();
int visualRow = translateVisibleLocation(parentNode, parentNode->visibleLocation(node->fileName));
- return q->createIndex(visualRow, 0, const_cast<QFileSystemNode*>(node));
+ return q->createIndex(visualRow, column, const_cast<QFileSystemNode*>(node));
}
/*!
@@ -643,7 +640,7 @@ int QFileSystemModel::rowCount(const QModelIndex &parent) const
*/
int QFileSystemModel::columnCount(const QModelIndex &parent) const
{
- return (parent.column() > 0) ? 0 : 4;
+ return (parent.column() > 0) ? 0 : QFileSystemModelPrivate::NumColumns;
}
/*!
@@ -1183,8 +1180,11 @@ void QFileSystemModel::sort(int column, Qt::SortOrder order)
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());
+ const int nodeCount = oldList.count();
+ oldNodes.reserve(nodeCount);
+ for (int i = 0; i < nodeCount; ++i) {
+ const QModelIndex &oldNode = oldList.at(i);
+ QPair<QFileSystemModelPrivate::QFileSystemNode*, int> pair(d->node(oldNode), oldNode.column());
oldNodes.append(pair);
}
@@ -1197,10 +1197,11 @@ void QFileSystemModel::sort(int column, Qt::SortOrder order)
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);
+ const int numOldNodes = oldNodes.size();
+ newList.reserve(numOldNodes);
+ for (int i = 0; i < numOldNodes; ++i) {
+ const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &oldNode = oldNodes.at(i);
+ newList.append(d->index(oldNode.first, oldNode.second));
}
changePersistentIndexList(oldList, newList);
emit layoutChanged();
@@ -1648,7 +1649,9 @@ QStringList QFileSystemModel::nameFilters() const
Q_D(const QFileSystemModel);
QStringList filters;
#ifndef QT_NO_REGEXP
- for (int i = 0; i < d->nameFilters.size(); ++i) {
+ const int numNameFilters = d->nameFilters.size();
+ filters.reserve(numNameFilters);
+ for (int i = 0; i < numNameFilters; ++i) {
filters << d->nameFilters.at(i).pattern();
}
#endif
diff --git a/src/widgets/dialogs/qfilesystemmodel.h b/src/widgets/dialogs/qfilesystemmodel.h
index 7c98a102f3..f749c97bcb 100644
--- a/src/widgets/dialogs/qfilesystemmodel.h
+++ b/src/widgets/dialogs/qfilesystemmodel.h
@@ -69,7 +69,7 @@ public:
FilePermissions = Qt::UserRole + 3
};
- explicit QFileSystemModel(QObject *parent = 0);
+ explicit QFileSystemModel(QObject *parent = Q_NULLPTR);
~QFileSystemModel();
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
@@ -136,7 +136,7 @@ public:
bool remove(const QModelIndex &index);
protected:
- QFileSystemModel(QFileSystemModelPrivate &, QObject *parent = 0);
+ QFileSystemModel(QFileSystemModelPrivate &, QObject *parent = Q_NULLPTR);
void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE;
bool event(QEvent *event) Q_DECL_OVERRIDE;
diff --git a/src/widgets/dialogs/qfilesystemmodel_p.h b/src/widgets/dialogs/qfilesystemmodel_p.h
index dd4b25d59c..57fb457071 100644
--- a/src/widgets/dialogs/qfilesystemmodel_p.h
+++ b/src/widgets/dialogs/qfilesystemmodel_p.h
@@ -70,6 +70,8 @@ class Q_AUTOTEST_EXPORT QFileSystemModelPrivate : public QAbstractItemModelPriva
Q_DECLARE_PUBLIC(QFileSystemModel)
public:
+ enum { NumColumns = 4 };
+
class QFileSystemNode
{
public:
@@ -220,8 +222,8 @@ public:
}
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;
+ inline QModelIndex index(const QString &path, int column = 0) { return index(node(path), column); }
+ QModelIndex index(const QFileSystemNode *node, int column = 0) const;
bool filtersAcceptsNode(const QFileSystemNode *node) const;
bool passNameFilters(const QFileSystemNode *node) const;
void removeNode(QFileSystemNode *parentNode, const QString &name);
@@ -318,6 +320,7 @@ public:
QList<Fetching> toFetch;
};
+Q_DECLARE_TYPEINFO(QFileSystemModelPrivate::Fetching, Q_MOVABLE_TYPE);
#endif // QT_NO_FILESYSTEMMODEL
QT_END_NAMESPACE
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index d47dd3562f..688e8f5c13 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -619,6 +619,7 @@ void QFontDialogPrivate::updateSizes()
int i = 0;
int current = -1;
QStringList str_sizes;
+ str_sizes.reserve(sizes.size());
for(QList<int>::const_iterator it = sizes.constBegin(); it != sizes.constEnd(); ++it) {
str_sizes.append(QString::number(*it));
if (current == -1 && *it == size)
diff --git a/src/widgets/dialogs/qfontdialog.h b/src/widgets/dialogs/qfontdialog.h
index 8ca9bf14dd..c3c3050174 100644
--- a/src/widgets/dialogs/qfontdialog.h
+++ b/src/widgets/dialogs/qfontdialog.h
@@ -65,8 +65,8 @@ public:
Q_DECLARE_FLAGS(FontDialogOptions, FontDialogOption)
- explicit QFontDialog(QWidget *parent = 0);
- explicit QFontDialog(const QFont &initial, QWidget *parent = 0);
+ explicit QFontDialog(QWidget *parent = Q_NULLPTR);
+ explicit QFontDialog(const QFont &initial, QWidget *parent = Q_NULLPTR);
~QFontDialog();
void setCurrentFont(const QFont &font);
@@ -84,9 +84,9 @@ public:
void setVisible(bool visible) Q_DECL_OVERRIDE;
- static QFont getFont(bool *ok, QWidget *parent = 0);
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent = 0, const QString &title = QString(),
- FontDialogOptions options = 0);
+ static QFont getFont(bool *ok, QWidget *parent = Q_NULLPTR);
+ static QFont getFont(bool *ok, const QFont &initial, QWidget *parent = Q_NULLPTR, const QString &title = QString(),
+ FontDialogOptions options = FontDialogOptions());
Q_SIGNALS:
void currentFontChanged(const QFont &font);
diff --git a/src/widgets/dialogs/qinputdialog.cpp b/src/widgets/dialogs/qinputdialog.cpp
index 9c78f5e9ac..fb52fa4651 100644
--- a/src/widgets/dialogs/qinputdialog.cpp
+++ b/src/widgets/dialogs/qinputdialog.cpp
@@ -791,6 +791,7 @@ QStringList QInputDialog::comboBoxItems() const
QStringList result;
if (d->comboBox) {
const int count = d->comboBox->count();
+ result.reserve(count);
for (int i = 0; i < count; ++i)
result.append(d->comboBox->itemText(i));
}
diff --git a/src/widgets/dialogs/qinputdialog.h b/src/widgets/dialogs/qinputdialog.h
index 84130d5f90..600f6c9753 100644
--- a/src/widgets/dialogs/qinputdialog.h
+++ b/src/widgets/dialogs/qinputdialog.h
@@ -83,7 +83,7 @@ public:
DoubleInput
};
- QInputDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ QInputDialog(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QInputDialog();
void setInputMode(InputMode mode);
@@ -153,27 +153,29 @@ public:
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,
+ const QString &text = QString(), bool *ok = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags(),
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
static QString getMultiLineText(QWidget *parent, const QString &title, const QString &label,
- const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
- Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
+ const QString &text = QString(), bool *ok = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags(),
+ 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,
+ bool *ok = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags(),
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
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);
+ int step = 1, bool *ok = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
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);
+ int decimals = 1, bool *ok = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
#if QT_DEPRECATED_SINCE(5, 0)
QT_DEPRECATED static inline 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)
+ int step = 1, bool *ok = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags())
{
return getInt(parent, title, label, value, minValue, maxValue, step, ok, flags);
}
diff --git a/src/widgets/dialogs/qmessagebox.h b/src/widgets/dialogs/qmessagebox.h
index 464bf734dc..b108354466 100644
--- a/src/widgets/dialogs/qmessagebox.h
+++ b/src/widgets/dialogs/qmessagebox.h
@@ -125,9 +125,9 @@ public:
Q_DECLARE_FLAGS(StandardButtons, StandardButton)
- explicit QMessageBox(QWidget *parent = 0);
+ explicit QMessageBox(QWidget *parent = Q_NULLPTR);
QMessageBox(Icon icon, const QString &title, const QString &text,
- StandardButtons buttons = NoButton, QWidget *parent = 0,
+ StandardButtons buttons = NoButton, QWidget *parent = Q_NULLPTR,
Qt::WindowFlags flags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
~QMessageBox();
@@ -198,7 +198,7 @@ public:
QMessageBox(const QString &title, const QString &text, Icon icon,
int button0, int button1, int button2,
- QWidget *parent = 0,
+ QWidget *parent = Q_NULLPTR,
Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
static int information(QWidget *parent, const QString &title,
diff --git a/src/widgets/dialogs/qprogressdialog.cpp b/src/widgets/dialogs/qprogressdialog.cpp
index 4e8e245813..97e9267a9d 100644
--- a/src/widgets/dialogs/qprogressdialog.cpp
+++ b/src/widgets/dialogs/qprogressdialog.cpp
@@ -697,9 +697,6 @@ void QProgressDialog::setValue(int progress)
d->shown_once = true;
}
}
-#ifdef Q_DEAD_CODE_FROM_QT4_MAC
- QApplication::flush();
-#endif
}
if (progress == d->bar->maximum() && d->autoReset)
diff --git a/src/widgets/dialogs/qprogressdialog.h b/src/widgets/dialogs/qprogressdialog.h
index 51c45f5d30..28de623385 100644
--- a/src/widgets/dialogs/qprogressdialog.h
+++ b/src/widgets/dialogs/qprogressdialog.h
@@ -61,9 +61,10 @@ class Q_WIDGETS_EXPORT QProgressDialog : public QDialog
Q_PROPERTY(QString labelText READ labelText WRITE setLabelText)
public:
- explicit QProgressDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit QProgressDialog(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
QProgressDialog(const QString &labelText, const QString &cancelButtonText,
- int minimum, int maximum, QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ int minimum, int maximum, QWidget *parent = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags());
~QProgressDialog();
void setLabel(QLabel *label);
diff --git a/src/widgets/dialogs/qsidebar.cpp b/src/widgets/dialogs/qsidebar.cpp
index 6fbcce801d..be3c060ba1 100644
--- a/src/widgets/dialogs/qsidebar.cpp
+++ b/src/widgets/dialogs/qsidebar.cpp
@@ -274,7 +274,9 @@ void QUrlModel::addUrls(const QList<QUrl> &list, int row, bool move)
QList<QUrl> QUrlModel::urls() const
{
QList<QUrl> list;
- for (int i = 0; i < rowCount(); ++i)
+ const int numRows = rowCount();
+ list.reserve(numRows);
+ for (int i = 0; i < numRows; ++i)
list.append(data(index(i, 0), UrlRole).toUrl());
return list;
}
@@ -334,10 +336,12 @@ void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &botto
void QUrlModel::layoutChanged()
{
QStringList paths;
- for (int i = 0; i < watching.count(); ++i)
+ const int numPaths = watching.count();
+ paths.reserve(numPaths);
+ for (int i = 0; i < numPaths; ++i)
paths.append(watching.at(i).second);
watching.clear();
- for (int i = 0; i < paths.count(); ++i) {
+ for (int i = 0; i < numPaths; ++i) {
QString path = paths.at(i);
QModelIndex newIndex = fileSystemModel->index(path);
watching.append(QPair<QModelIndex, QString>(newIndex, path));
@@ -453,12 +457,14 @@ void QSidebar::removeEntry()
{
QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
QList<QPersistentModelIndex> indexes;
- for (int i = 0; i < idxs.count(); i++)
+ const int numIndexes = idxs.count();
+ for (int i = 0; i < numIndexes; i++)
indexes.append(idxs.at(i));
- for (int i = 0; i < indexes.count(); ++i)
+ for (int i = 0; i < numIndexes; ++i) {
if (!indexes.at(i).data(QUrlModel::UrlRole).toUrl().path().isEmpty())
model()->removeRow(indexes.at(i).row());
+ }
}
/*!
diff --git a/src/widgets/dialogs/qwizard.cpp b/src/widgets/dialogs/qwizard.cpp
index 139fbc3843..6a1c0eb592 100644
--- a/src/widgets/dialogs/qwizard.cpp
+++ b/src/widgets/dialogs/qwizard.cpp
@@ -170,6 +170,7 @@ public:
const char *changedSignal)
: className(className), property(property), changedSignal(changedSignal) {}
};
+Q_DECLARE_TYPEINFO(QWizardDefaultProperty, Q_MOVABLE_TYPE);
class QWizardField
{
@@ -189,6 +190,7 @@ public:
QByteArray changedSignal;
QVariant initialValue;
};
+Q_DECLARE_TYPEINFO(QWizardField, Q_MOVABLE_TYPE);
QWizardField::QWizardField(QWizardPage *page, const QString &spec, QObject *object,
const char *property, const char *changedSignal)
@@ -751,6 +753,7 @@ void QWizardPrivate::init()
updateButtonLayout();
+ defaultPropertyTable.reserve(NFallbackDefaultProperties);
for (uint i = 0; i < NFallbackDefaultProperties; ++i)
defaultPropertyTable.append(QWizardDefaultProperty(fallbackProperties[i].className,
fallbackProperties[i].property,
diff --git a/src/widgets/dialogs/qwizard.h b/src/widgets/dialogs/qwizard.h
index 517edde377..9193f0b659 100644
--- a/src/widgets/dialogs/qwizard.h
+++ b/src/widgets/dialogs/qwizard.h
@@ -114,7 +114,7 @@ public:
Q_DECLARE_FLAGS(WizardOptions, WizardOption)
- explicit QWizard(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit QWizard(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QWizard();
int addPage(QWizardPage *page);
@@ -209,7 +209,7 @@ class Q_WIDGETS_EXPORT QWizardPage : public QWidget
Q_PROPERTY(QString subTitle READ subTitle WRITE setSubTitle)
public:
- explicit QWizardPage(QWidget *parent = 0);
+ explicit QWizardPage(QWidget *parent = Q_NULLPTR);
~QWizardPage();
void setTitle(const QString &title);
@@ -237,8 +237,8 @@ Q_SIGNALS:
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);
+ void registerField(const QString &name, QWidget *widget, const char *property = Q_NULLPTR,
+ const char *changedSignal = Q_NULLPTR);
QWizard *wizard() const;
private:
diff --git a/src/widgets/doc/images/listview.png b/src/widgets/doc/images/listview.png
index fa49c52c62..fa49c52c62 100755..100644
--- a/src/widgets/doc/images/listview.png
+++ b/src/widgets/doc/images/listview.png
Binary files differ
diff --git a/src/widgets/doc/images/modelview-combobox.png b/src/widgets/doc/images/modelview-combobox.png
index d172b413eb..d172b413eb 100755..100644
--- a/src/widgets/doc/images/modelview-combobox.png
+++ b/src/widgets/doc/images/modelview-combobox.png
Binary files differ
diff --git a/src/widgets/doc/images/tableview.png b/src/widgets/doc/images/tableview.png
index 8be1b6ce62..8be1b6ce62 100755..100644
--- a/src/widgets/doc/images/tableview.png
+++ b/src/widgets/doc/images/tableview.png
Binary files differ
diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
index 39dfe32ace..e5c0f5cea1 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
@@ -106,16 +106,6 @@ QStringList files = QFileDialog::getOpenFileNames(
//! [9]
-//! [10]
-QStringList list = files;
-QStringList::Iterator it = list.begin();
-while(it != list.end()) {
- myProcessing(*it);
- ++it;
-}
-//! [10]
-
-
//! [11]
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
"/home/jana/untitled.png",
diff --git a/src/widgets/doc/snippets/macmainwindow.mm b/src/widgets/doc/snippets/macmainwindow.mm
index d0d74631ab..d0d74631ab 100755..100644
--- a/src/widgets/doc/snippets/macmainwindow.mm
+++ b/src/widgets/doc/snippets/macmainwindow.mm
diff --git a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
index 7610174744..0e52944bb0 100644
--- a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
+++ b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
@@ -226,7 +226,11 @@
We create a toolbar as a child of the main window, and add the desired
actions to it:
- \snippet mainwindows/sdi/mainwindow.cpp 0
+ \code
+ fileToolBar = addToolBar(tr("File"));
+ fileToolBar->addAction(newAct);
+ fileToolBar->addAction(openAct);
+ \endcode
\dots
\snippet code/doc_src_qt4-mainwindow.cpp 1
diff --git a/src/widgets/effects/qgraphicseffect.cpp b/src/widgets/effects/qgraphicseffect.cpp
index f53804e494..5a97be3d96 100644
--- a/src/widgets/effects/qgraphicseffect.cpp
+++ b/src/widgets/effects/qgraphicseffect.cpp
@@ -111,6 +111,10 @@
#ifndef QT_NO_GRAPHICSEFFECT
QT_BEGIN_NAMESPACE
+QGraphicsEffectPrivate::~QGraphicsEffectPrivate()
+{
+}
+
/*!
\internal
\class QGraphicsEffectSource
diff --git a/src/widgets/effects/qgraphicseffect.h b/src/widgets/effects/qgraphicseffect.h
index 678ece3dd2..c43b607d39 100644
--- a/src/widgets/effects/qgraphicseffect.h
+++ b/src/widgets/effects/qgraphicseffect.h
@@ -72,7 +72,7 @@ public:
PadToEffectiveBoundingRect
};
- QGraphicsEffect(QObject *parent = 0);
+ QGraphicsEffect(QObject *parent = Q_NULLPTR);
virtual ~QGraphicsEffect();
virtual QRectF boundingRectFor(const QRectF &sourceRect) const;
@@ -88,7 +88,7 @@ Q_SIGNALS:
void enabledChanged(bool enabled);
protected:
- QGraphicsEffect(QGraphicsEffectPrivate &d, QObject *parent = 0);
+ QGraphicsEffect(QGraphicsEffectPrivate &d, QObject *parent = Q_NULLPTR);
virtual void draw(QPainter *painter) = 0;
virtual void sourceChanged(ChangeFlags flags);
void updateBoundingRect();
@@ -97,7 +97,7 @@ protected:
QRectF sourceBoundingRect(Qt::CoordinateSystem system = Qt::LogicalCoordinates) const;
void drawSource(QPainter *painter);
QPixmap sourcePixmap(Qt::CoordinateSystem system = Qt::LogicalCoordinates,
- QPoint *offset = 0,
+ QPoint *offset = Q_NULLPTR,
PixmapPadMode mode = PadToEffectiveBoundingRect) const;
private:
@@ -122,7 +122,7 @@ class Q_WIDGETS_EXPORT QGraphicsColorizeEffect: public QGraphicsEffect
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(QObject *parent = Q_NULLPTR);
~QGraphicsColorizeEffect();
QColor color() const;
@@ -159,7 +159,7 @@ public:
};
Q_DECLARE_FLAGS(BlurHints, BlurHint)
- QGraphicsBlurEffect(QObject *parent = 0);
+ QGraphicsBlurEffect(QObject *parent = Q_NULLPTR);
~QGraphicsBlurEffect();
QRectF boundingRectFor(const QRectF &rect) const Q_DECL_OVERRIDE;
@@ -194,7 +194,7 @@ class Q_WIDGETS_EXPORT QGraphicsDropShadowEffect: public QGraphicsEffect
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(QObject *parent = Q_NULLPTR);
~QGraphicsDropShadowEffect();
QRectF boundingRectFor(const QRectF &rect) const Q_DECL_OVERRIDE;
@@ -247,7 +247,7 @@ class Q_WIDGETS_EXPORT QGraphicsOpacityEffect: public QGraphicsEffect
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(QObject *parent = Q_NULLPTR);
~QGraphicsOpacityEffect();
qreal opacity() const;
diff --git a/src/widgets/effects/qgraphicseffect_p.h b/src/widgets/effects/qgraphicseffect_p.h
index 6e990cc52e..35264c0d30 100644
--- a/src/widgets/effects/qgraphicseffect_p.h
+++ b/src/widgets/effects/qgraphicseffect_p.h
@@ -142,6 +142,7 @@ class Q_WIDGETS_EXPORT QGraphicsEffectPrivate : public QObjectPrivate
Q_DECLARE_PUBLIC(QGraphicsEffect)
public:
QGraphicsEffectPrivate() : source(0), isEnabled(1) {}
+ ~QGraphicsEffectPrivate();
inline void setGraphicsEffectSource(QGraphicsEffectSource *newSource)
{
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout.h b/src/widgets/graphicsview/qgraphicsanchorlayout.h
index 90406fe71f..2fdfe75be9 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout.h
@@ -71,7 +71,7 @@ private:
class Q_WIDGETS_EXPORT QGraphicsAnchorLayout : public QGraphicsLayout
{
public:
- QGraphicsAnchorLayout(QGraphicsLayoutItem *parent = 0);
+ QGraphicsAnchorLayout(QGraphicsLayoutItem *parent = Q_NULLPTR);
virtual ~QGraphicsAnchorLayout();
QGraphicsAnchor *addAnchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
index 8327777217..dac8e61645 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
@@ -751,9 +751,12 @@ static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph,
AnchorVertex *prev = before;
QVector<AnchorData *> edges;
+ edges.reserve(vertices.count() + 1);
+ const int numVertices = vertices.count();
+ edges.reserve(numVertices + 1);
// Take from the graph, the edges that will be simplificated
- for (int i = 0; i < vertices.count(); ++i) {
+ for (int i = 0; i < numVertices; ++i) {
AnchorVertex *next = vertices.at(i);
AnchorData *ad = graph->takeEdge(prev, next);
Q_ASSERT(ad);
@@ -2569,6 +2572,7 @@ QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
if (!remainingConstraints.isEmpty()) {
QList<QSimplexConstraint *> nonTrunkConstraints;
+ nonTrunkConstraints.reserve(remainingConstraints.size());
QLinkedList<QSimplexConstraint *>::iterator it = remainingConstraints.begin();
while (it != remainingConstraints.end()) {
nonTrunkConstraints += *it;
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
index c0bb8ef63a..a5c7f1e2ce 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
@@ -317,6 +317,7 @@ public:
QSet<AnchorData *> positives;
QSet<AnchorData *> negatives;
};
+Q_DECLARE_TYPEINFO(GraphPath, Q_MOVABLE_TYPE);
class QGraphicsAnchorLayoutPrivate;
/*!
diff --git a/src/widgets/graphicsview/qgraphicsgridlayout.h b/src/widgets/graphicsview/qgraphicsgridlayout.h
index 90cc316025..f6aa3af91d 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayout.h
+++ b/src/widgets/graphicsview/qgraphicsgridlayout.h
@@ -47,12 +47,12 @@ class QGraphicsGridLayoutPrivate;
class Q_WIDGETS_EXPORT QGraphicsGridLayout : public QGraphicsLayout
{
public:
- QGraphicsGridLayout(QGraphicsLayoutItem *parent = 0);
+ QGraphicsGridLayout(QGraphicsLayoutItem *parent = Q_NULLPTR);
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);
+ Qt::Alignment alignment = Qt::Alignment());
+ inline void addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment = Qt::Alignment());
void setHorizontalSpacing(qreal spacing);
qreal horizontalSpacing() const;
diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp
index 1332134000..5f5c402a4a 100644
--- a/src/widgets/graphicsview/qgraphicsitem.cpp
+++ b/src/widgets/graphicsview/qgraphicsitem.cpp
@@ -10832,9 +10832,7 @@ void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphic
range.start = 0;
range.length = layout.text().length();
range.format.setTextOutline(d->pen);
- QList<QTextLayout::FormatRange> formats;
- formats.append(range);
- layout.setAdditionalFormats(formats);
+ layout.setFormats(QVector<QTextLayout::FormatRange>(1, range));
}
setupTextLayout(&layout);
diff --git a/src/widgets/graphicsview/qgraphicsitem.h b/src/widgets/graphicsview/qgraphicsitem.h
index d3540beb77..b2f8fcbe74 100644
--- a/src/widgets/graphicsview/qgraphicsitem.h
+++ b/src/widgets/graphicsview/qgraphicsitem.h
@@ -153,7 +153,7 @@ public:
SceneModal
};
- explicit QGraphicsItem(QGraphicsItem *parent = 0);
+ explicit QGraphicsItem(QGraphicsItem *parent = Q_NULLPTR);
virtual ~QGraphicsItem();
QGraphicsScene *scene() const;
@@ -189,7 +189,7 @@ public:
PanelModality panelModality() const;
void setPanelModality(PanelModality panelModality);
- bool isBlockedByModalPanel(QGraphicsItem **blockingPanel = 0) const;
+ bool isBlockedByModalPanel(QGraphicsItem **blockingPanel = Q_NULLPTR) const;
#ifndef QT_NO_TOOLTIP
QString toolTip() const;
@@ -285,7 +285,7 @@ public:
QTransform transform() const;
QTransform sceneTransform() const;
QTransform deviceTransform(const QTransform &viewportTransform) const;
- QTransform itemTransform(const QGraphicsItem *other, bool *ok = 0) const;
+ QTransform itemTransform(const QGraphicsItem *other, bool *ok = Q_NULLPTR) const;
void setTransform(const QTransform &matrix, bool combine = false);
void resetTransform();
#if QT_DEPRECATED_SINCE(5, 0)
@@ -336,7 +336,7 @@ public:
void setBoundingRegionGranularity(qreal granularity);
// Drawing
- virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0;
+ virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) = 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());
@@ -553,7 +553,7 @@ class Q_WIDGETS_EXPORT QGraphicsObject : public QObject, public QGraphicsItem
Q_CLASSINFO("DefaultProperty", "children")
Q_INTERFACES(QGraphicsItem)
public:
- explicit QGraphicsObject(QGraphicsItem *parent = 0);
+ explicit QGraphicsObject(QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsObject();
using QObject::children;
@@ -595,7 +595,7 @@ class QAbstractGraphicsShapeItemPrivate;
class Q_WIDGETS_EXPORT QAbstractGraphicsShapeItem : public QGraphicsItem
{
public:
- explicit QAbstractGraphicsShapeItem(QGraphicsItem *parent = 0);
+ explicit QAbstractGraphicsShapeItem(QGraphicsItem *parent = Q_NULLPTR);
~QAbstractGraphicsShapeItem();
QPen pen() const;
@@ -620,8 +620,8 @@ class QGraphicsPathItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsPathItem : public QAbstractGraphicsShapeItem
{
public:
- explicit QGraphicsPathItem(QGraphicsItem *parent = 0);
- explicit QGraphicsPathItem(const QPainterPath &path, QGraphicsItem *parent = 0);
+ explicit QGraphicsPathItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsPathItem(const QPainterPath &path, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsPathItem();
QPainterPath path() const;
@@ -631,7 +631,7 @@ public:
QPainterPath shape() const Q_DECL_OVERRIDE;
bool contains(const QPointF &point) const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
@@ -653,9 +653,9 @@ class QGraphicsRectItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsRectItem : public QAbstractGraphicsShapeItem
{
public:
- explicit QGraphicsRectItem(QGraphicsItem *parent = 0);
- explicit QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent = 0);
- explicit QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0);
+ explicit QGraphicsRectItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsRectItem();
QRectF rect() const;
@@ -666,7 +666,7 @@ public:
QPainterPath shape() const Q_DECL_OVERRIDE;
bool contains(const QPointF &point) const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
@@ -691,9 +691,9 @@ class QGraphicsEllipseItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsEllipseItem : public QAbstractGraphicsShapeItem
{
public:
- explicit QGraphicsEllipseItem(QGraphicsItem *parent = 0);
- explicit QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent = 0);
- explicit QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0);
+ explicit QGraphicsEllipseItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsEllipseItem();
QRectF rect() const;
@@ -710,7 +710,7 @@ public:
QPainterPath shape() const Q_DECL_OVERRIDE;
bool contains(const QPointF &point) const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
@@ -735,9 +735,9 @@ class QGraphicsPolygonItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsPolygonItem : public QAbstractGraphicsShapeItem
{
public:
- explicit QGraphicsPolygonItem(QGraphicsItem *parent = 0);
+ explicit QGraphicsPolygonItem(QGraphicsItem *parent = Q_NULLPTR);
explicit QGraphicsPolygonItem(const QPolygonF &polygon,
- QGraphicsItem *parent = 0);
+ QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsPolygonItem();
QPolygonF polygon() const;
@@ -750,7 +750,7 @@ public:
QPainterPath shape() const Q_DECL_OVERRIDE;
bool contains(const QPointF &point) const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
@@ -772,9 +772,9 @@ class QGraphicsLineItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsLineItem : public QGraphicsItem
{
public:
- explicit QGraphicsLineItem(QGraphicsItem *parent = 0);
- explicit QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent = 0);
- explicit QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent = 0);
+ explicit QGraphicsLineItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsLineItem();
QPen pen() const;
@@ -789,7 +789,7 @@ public:
QPainterPath shape() const Q_DECL_OVERRIDE;
bool contains(const QPointF &point) const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
@@ -817,8 +817,8 @@ public:
HeuristicMaskShape
};
- explicit QGraphicsPixmapItem(QGraphicsItem *parent = 0);
- explicit QGraphicsPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent = 0);
+ explicit QGraphicsPixmapItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsPixmapItem();
QPixmap pixmap() const;
@@ -869,8 +869,8 @@ class Q_WIDGETS_EXPORT QGraphicsTextItem : public QGraphicsObject
QDOC_PROPERTY(QTextCursor textCursor READ textCursor WRITE setTextCursor)
public:
- explicit QGraphicsTextItem(QGraphicsItem *parent = 0);
- explicit QGraphicsTextItem(const QString &text, QGraphicsItem *parent = 0);
+ explicit QGraphicsTextItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsTextItem(const QString &text, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsTextItem();
QString toHtml() const;
@@ -960,8 +960,8 @@ class QGraphicsSimpleTextItemPrivate;
class Q_WIDGETS_EXPORT QGraphicsSimpleTextItem : public QAbstractGraphicsShapeItem
{
public:
- explicit QGraphicsSimpleTextItem(QGraphicsItem *parent = 0);
- explicit QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent = 0);
+ explicit QGraphicsSimpleTextItem(QGraphicsItem *parent = Q_NULLPTR);
+ explicit QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsSimpleTextItem();
void setText(const QString &text);
@@ -996,14 +996,14 @@ class QGraphicsItemGroupPrivate;
class Q_WIDGETS_EXPORT QGraphicsItemGroup : public QGraphicsItem
{
public:
- explicit QGraphicsItemGroup(QGraphicsItem *parent = 0);
+ explicit QGraphicsItemGroup(QGraphicsItem *parent = Q_NULLPTR);
~QGraphicsItemGroup();
void addToGroup(QGraphicsItem *item);
void removeFromGroup(QGraphicsItem *item);
QRectF boundingRect() const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
bool isObscuredBy(const QGraphicsItem *item) const Q_DECL_OVERRIDE;
QPainterPath opaqueArea() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/graphicsview/qgraphicsitem_p.h b/src/widgets/graphicsview/qgraphicsitem_p.h
index bf788d2c39..fe4bac12bc 100644
--- a/src/widgets/graphicsview/qgraphicsitem_p.h
+++ b/src/widgets/graphicsview/qgraphicsitem_p.h
@@ -353,6 +353,7 @@ public:
}
struct ExtraStruct {
+ ExtraStruct() {} // for QVector, don't use
ExtraStruct(Extra type, QVariant value)
: type(type), value(value)
{ }
@@ -364,7 +365,7 @@ public:
{ return type < extra; }
};
- QList<ExtraStruct> extras;
+ QVector<ExtraStruct> extras;
QGraphicsItemCache *maybeExtraItemCache() const;
QGraphicsItemCache *extraItemCache() const;
@@ -584,6 +585,7 @@ public:
int globalStackingOrder;
QGraphicsItem *q_ptr;
};
+Q_DECLARE_TYPEINFO(QGraphicsItemPrivate::ExtraStruct, Q_MOVABLE_TYPE);
struct QGraphicsItemPrivate::TransformData
{
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.cpp b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
index 0a6fccf559..585539de94 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.cpp
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
@@ -116,7 +116,6 @@ public:
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
@@ -124,21 +123,22 @@ public:
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);
+ QVector<Pair> xPosition;
+ QVector<Pair> yPosition;
+ QVector<Pair> rotation;
+ QVector<Pair> verticalScale;
+ QVector<Pair> horizontalScale;
+ QVector<Pair> verticalShear;
+ QVector<Pair> horizontalShear;
+ QVector<Pair> xTranslation;
+ QVector<Pair> yTranslation;
+
+ qreal linearValueForStep(qreal step, QVector<Pair> *source, qreal defaultValue = 0);
+ void insertUniquePair(qreal step, qreal value, QVector<Pair> *binList, const char* method);
};
+Q_DECLARE_TYPEINFO(QGraphicsItemAnimationPrivate::Pair, Q_PRIMITIVE_TYPE);
-qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, QList<Pair> *source, qreal defaultValue)
+qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, QVector<Pair> *source, qreal defaultValue)
{
if (source->isEmpty())
return defaultValue;
@@ -168,20 +168,18 @@ qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, QList<Pair>
return valueBefore + (valueAfter - valueBefore) * ((step - stepBefore) / (stepAfter - stepBefore));
}
-void QGraphicsItemAnimationPrivate::insertUniquePair(qreal step, qreal value, QList<Pair> *binList, const char* method)
+void QGraphicsItemAnimationPrivate::insertUniquePair(qreal step, qreal value, QVector<Pair> *binList, const char* method)
{
if (!check_step_valid(step, method))
return;
- Pair pair(step, value);
+ const Pair pair = { step, value };
- QList<Pair>::iterator result = std::lower_bound(binList->begin(), binList->end(), pair);
- if ((result != binList->end()) && !(pair < *result))
+ const QVector<Pair>::iterator result = std::lower_bound(binList->begin(), binList->end(), pair);
+ if (result == binList->end() || pair < *result)
+ binList->insert(result, pair);
+ else
result->value = value;
- else {
- *binList << pair;
- std::sort(binList->begin(), binList->end());
- }
}
/*!
@@ -284,7 +282,9 @@ void QGraphicsItemAnimation::setPosAt(qreal step, const QPointF &pos)
QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::posList() const
{
QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->xPosition.size(); ++i)
+ const int xPosCount = d->xPosition.size();
+ list.reserve(xPosCount);
+ for (int i = 0; i < xPosCount; ++i)
list << QPair<qreal, QPointF>(d->xPosition.at(i).step, QPointF(d->xPosition.at(i).value, d->yPosition.at(i).value));
return list;
@@ -338,7 +338,9 @@ void QGraphicsItemAnimation::setRotationAt(qreal step, qreal angle)
QList<QPair<qreal, qreal> > QGraphicsItemAnimation::rotationList() const
{
QList<QPair<qreal, qreal> > list;
- for (int i = 0; i < d->rotation.size(); ++i)
+ const int numRotations = d->rotation.size();
+ list.reserve(numRotations);
+ for (int i = 0; i < numRotations; ++i)
list << QPair<qreal, qreal>(d->rotation.at(i).step, d->rotation.at(i).value);
return list;
@@ -386,7 +388,9 @@ void QGraphicsItemAnimation::setTranslationAt(qreal step, qreal dx, qreal dy)
QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::translationList() const
{
QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->xTranslation.size(); ++i)
+ const int numTranslations = d->xTranslation.size();
+ list.reserve(numTranslations);
+ for (int i = 0; i < numTranslations; ++i)
list << QPair<qreal, QPointF>(d->xTranslation.at(i).step, QPointF(d->xTranslation.at(i).value, d->yTranslation.at(i).value));
return list;
@@ -435,7 +439,9 @@ void QGraphicsItemAnimation::setScaleAt(qreal step, qreal sx, qreal sy)
QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::scaleList() const
{
QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->horizontalScale.size(); ++i)
+ const int numScales = d->horizontalScale.size();
+ list.reserve(numScales);
+ for (int i = 0; i < numScales; ++i)
list << QPair<qreal, QPointF>(d->horizontalScale.at(i).step, QPointF(d->horizontalScale.at(i).value, d->verticalScale.at(i).value));
return list;
@@ -483,7 +489,9 @@ void QGraphicsItemAnimation::setShearAt(qreal step, qreal sh, qreal sv)
QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::shearList() const
{
QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->horizontalShear.size(); ++i)
+ const int numShears = d->horizontalShear.size();
+ list.reserve(numShears);
+ for (int i = 0; i < numShears; ++i)
list << QPair<qreal, QPointF>(d->horizontalShear.at(i).step, QPointF(d->horizontalShear.at(i).value, d->verticalShear.at(i).value));
return list;
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.h b/src/widgets/graphicsview/qgraphicsitemanimation.h
index 02a20f3f01..a54ba3a9e9 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.h
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.h
@@ -52,7 +52,7 @@ class Q_WIDGETS_EXPORT QGraphicsItemAnimation : public QObject
{
Q_OBJECT
public:
- QGraphicsItemAnimation(QObject *parent = 0);
+ QGraphicsItemAnimation(QObject *parent = Q_NULLPTR);
virtual ~QGraphicsItemAnimation();
QGraphicsItem *item() const;
diff --git a/src/widgets/graphicsview/qgraphicslayout.h b/src/widgets/graphicsview/qgraphicslayout.h
index ebd90735f1..84a8d97943 100644
--- a/src/widgets/graphicsview/qgraphicslayout.h
+++ b/src/widgets/graphicsview/qgraphicslayout.h
@@ -48,7 +48,7 @@ class QGraphicsWidget;
class Q_WIDGETS_EXPORT QGraphicsLayout : public QGraphicsLayoutItem
{
public:
- QGraphicsLayout(QGraphicsLayoutItem *parent = 0);
+ QGraphicsLayout(QGraphicsLayoutItem *parent = Q_NULLPTR);
~QGraphicsLayout();
void setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
diff --git a/src/widgets/graphicsview/qgraphicslayoutitem.h b/src/widgets/graphicsview/qgraphicslayoutitem.h
index 85b6d901f2..1608d79836 100644
--- a/src/widgets/graphicsview/qgraphicslayoutitem.h
+++ b/src/widgets/graphicsview/qgraphicslayoutitem.h
@@ -48,7 +48,7 @@ class QGraphicsItem;
class Q_WIDGETS_EXPORT QGraphicsLayoutItem
{
public:
- QGraphicsLayoutItem(QGraphicsLayoutItem *parent = 0, bool isLayout = false);
+ QGraphicsLayoutItem(QGraphicsLayoutItem *parent = Q_NULLPTR, bool isLayout = false);
virtual ~QGraphicsLayoutItem();
void setSizePolicy(const QSizePolicy &policy);
diff --git a/src/widgets/graphicsview/qgraphicslinearlayout.h b/src/widgets/graphicsview/qgraphicslinearlayout.h
index 997bff7da1..3232da22ca 100644
--- a/src/widgets/graphicsview/qgraphicslinearlayout.h
+++ b/src/widgets/graphicsview/qgraphicslinearlayout.h
@@ -47,8 +47,8 @@ class QGraphicsLinearLayoutPrivate;
class Q_WIDGETS_EXPORT QGraphicsLinearLayout : public QGraphicsLayout
{
public:
- QGraphicsLinearLayout(QGraphicsLayoutItem *parent = 0);
- QGraphicsLinearLayout(Qt::Orientation orientation, QGraphicsLayoutItem *parent = 0);
+ QGraphicsLinearLayout(QGraphicsLayoutItem *parent = Q_NULLPTR);
+ QGraphicsLinearLayout(Qt::Orientation orientation, QGraphicsLayoutItem *parent = Q_NULLPTR);
virtual ~QGraphicsLinearLayout();
void setOrientation(Qt::Orientation orientation);
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.cpp b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
index db4d18299b..08ea1ea0e3 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.cpp
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
@@ -269,8 +269,7 @@ void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneMouseEvent
// Send mouse event.
QMouseEvent mouseEvent(type, pos, receiver->mapTo(receiver->topLevelWidget(), pos.toPoint()),
receiver->mapToGlobal(pos.toPoint()),
- event->button(), event->buttons(), event->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&mouseEvent, event->source());
+ event->button(), event->buttons(), event->modifiers(), event->source());
QWidget *embeddedMouseGrabberPtr = (QWidget *)embeddedMouseGrabber;
QApplicationPrivate::sendMouseEvent(receiver, &mouseEvent, alienWidget, widget,
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.h b/src/widgets/graphicsview/qgraphicsproxywidget.h
index ae52f88f16..5a03a8a9dd 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.h
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.h
@@ -47,7 +47,7 @@ class Q_WIDGETS_EXPORT QGraphicsProxyWidget : public QGraphicsWidget
{
Q_OBJECT
public:
- QGraphicsProxyWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
+ QGraphicsProxyWidget(QGraphicsItem *parent = Q_NULLPTR, Qt::WindowFlags wFlags = Qt::WindowFlags());
~QGraphicsProxyWidget();
void setWidget(QWidget *widget);
diff --git a/src/widgets/graphicsview/qgraphicsscene.h b/src/widgets/graphicsview/qgraphicsscene.h
index 68382bf498..c93db20716 100644
--- a/src/widgets/graphicsview/qgraphicsscene.h
+++ b/src/widgets/graphicsview/qgraphicsscene.h
@@ -115,9 +115,9 @@ public:
};
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);
+ QGraphicsScene(QObject *parent = Q_NULLPTR);
+ QGraphicsScene(const QRectF &sceneRect, QObject *parent = Q_NULLPTR);
+ QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent = Q_NULLPTR);
virtual ~QGraphicsScene();
QRectF sceneRect() const;
@@ -192,7 +192,7 @@ public:
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);
+ QGraphicsProxyWidget *addWidget(QWidget *widget, Qt::WindowFlags wFlags = Qt::WindowFlags());
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())
@@ -279,7 +279,7 @@ protected:
virtual void drawItems(QPainter *painter, int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[],
- QWidget *widget = 0);
+ QWidget *widget = Q_NULLPTR);
protected Q_SLOTS:
// ### Qt 6: make unconditional
diff --git a/src/widgets/graphicsview/qgraphicssceneevent.h b/src/widgets/graphicsview/qgraphicssceneevent.h
index 1e3554fa36..ffa708ea23 100644
--- a/src/widgets/graphicsview/qgraphicssceneevent.h
+++ b/src/widgets/graphicsview/qgraphicssceneevent.h
@@ -40,7 +40,9 @@
#include <QtCore/qrect.h>
#include <QtGui/qpolygon.h>
#include <QtCore/qset.h>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/qhash.h>
+#endif
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/graphicsview/qgraphicssceneindex.cpp b/src/widgets/graphicsview/qgraphicssceneindex.cpp
index 8662f73d64..a76f6b6565 100644
--- a/src/widgets/graphicsview/qgraphicssceneindex.cpp
+++ b/src/widgets/graphicsview/qgraphicssceneindex.cpp
@@ -520,7 +520,9 @@ QList<QGraphicsItem *> QGraphicsSceneIndex::estimateTopLevelItems(const QRectF &
scened->ensureSortedTopLevelItems();
if (order == Qt::DescendingOrder) {
QList<QGraphicsItem *> sorted;
- for (int i = scened->topLevelItems.size() - 1; i >= 0; --i)
+ const int numTopLevelItems = scened->topLevelItems.size();
+ sorted.reserve(numTopLevelItems);
+ for (int i = numTopLevelItems - 1; i >= 0; --i)
sorted << scened->topLevelItems.at(i);
return sorted;
}
diff --git a/src/widgets/graphicsview/qgraphicstransform.cpp b/src/widgets/graphicsview/qgraphicstransform.cpp
index 67564b5a8b..fe963fbf3c 100644
--- a/src/widgets/graphicsview/qgraphicstransform.cpp
+++ b/src/widgets/graphicsview/qgraphicstransform.cpp
@@ -89,6 +89,11 @@
#ifndef QT_NO_GRAPHICSVIEW
QT_BEGIN_NAMESPACE
+
+QGraphicsTransformPrivate::~QGraphicsTransformPrivate()
+{
+}
+
void QGraphicsTransformPrivate::setItem(QGraphicsItem *i)
{
if (item == i)
diff --git a/src/widgets/graphicsview/qgraphicstransform.h b/src/widgets/graphicsview/qgraphicstransform.h
index 4a7a3d0c0b..6fa76683f2 100644
--- a/src/widgets/graphicsview/qgraphicstransform.h
+++ b/src/widgets/graphicsview/qgraphicstransform.h
@@ -50,7 +50,7 @@ class Q_WIDGETS_EXPORT QGraphicsTransform : public QObject
{
Q_OBJECT
public:
- QGraphicsTransform(QObject *parent = 0);
+ QGraphicsTransform(QObject *parent = Q_NULLPTR);
~QGraphicsTransform();
virtual void applyTo(QMatrix4x4 *matrix) const = 0;
@@ -78,7 +78,7 @@ class Q_WIDGETS_EXPORT QGraphicsScale : public QGraphicsTransform
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(QObject *parent = Q_NULLPTR);
~QGraphicsScale();
QVector3D origin() const;
@@ -116,7 +116,7 @@ class Q_WIDGETS_EXPORT QGraphicsRotation : public QGraphicsTransform
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(QObject *parent = Q_NULLPTR);
~QGraphicsRotation();
QVector3D origin() const;
diff --git a/src/widgets/graphicsview/qgraphicstransform_p.h b/src/widgets/graphicsview/qgraphicstransform_p.h
index dde085935f..c81a95fd3d 100644
--- a/src/widgets/graphicsview/qgraphicstransform_p.h
+++ b/src/widgets/graphicsview/qgraphicstransform_p.h
@@ -51,12 +51,14 @@ QT_BEGIN_NAMESPACE
class QGraphicsItem;
-class QGraphicsTransformPrivate : public QObjectPrivate {
+// ### Qt 6: unexport again, if QtQuick1's QDeclarativeTranslatePrivate is gone by then
+class Q_WIDGETS_EXPORT QGraphicsTransformPrivate : public QObjectPrivate {
public:
Q_DECLARE_PUBLIC(QGraphicsTransform)
QGraphicsTransformPrivate()
: QObjectPrivate(), item(0) {}
+ ~QGraphicsTransformPrivate();
QGraphicsItem *item;
diff --git a/src/widgets/graphicsview/qgraphicsview.cpp b/src/widgets/graphicsview/qgraphicsview.cpp
index c270c4be88..ac8cd45f9e 100644
--- a/src/widgets/graphicsview/qgraphicsview.cpp
+++ b/src/widgets/graphicsview/qgraphicsview.cpp
@@ -362,6 +362,10 @@ QGraphicsViewPrivate::QGraphicsViewPrivate()
styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS);
}
+QGraphicsViewPrivate::~QGraphicsViewPrivate()
+{
+}
+
/*!
\internal
*/
@@ -2460,6 +2464,7 @@ QPolygonF QGraphicsView::mapToScene(const QRect &rect) const
QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const
{
QPolygonF poly;
+ poly.reserve(polygon.count());
foreach (const QPoint &point, polygon)
poly << mapToScene(point);
return poly;
@@ -2555,6 +2560,7 @@ QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const
QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const
{
QPolygon poly;
+ poly.reserve(polygon.count());
foreach (const QPointF &point, polygon)
poly << mapFromScene(point);
return poly;
@@ -2669,7 +2675,9 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects)
// 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)
+ const int dirtyRectsCount = dirtyRects.size();
+ dirtyViewportRects.reserve(dirtyRectsCount + rects.count());
+ for (int i = 0; i < dirtyRectsCount; ++i)
dirtyViewportRects += dirtyRects.at(i);
d->dirtyRegion = QRegion();
d->dirtyBoundingRect = QRect();
diff --git a/src/widgets/graphicsview/qgraphicsview.h b/src/widgets/graphicsview/qgraphicsview.h
index d426273d97..667fa76fe7 100644
--- a/src/widgets/graphicsview/qgraphicsview.h
+++ b/src/widgets/graphicsview/qgraphicsview.h
@@ -108,8 +108,8 @@ public:
};
Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag)
- QGraphicsView(QWidget *parent = 0);
- QGraphicsView(QGraphicsScene *scene, QWidget *parent = 0);
+ QGraphicsView(QWidget *parent = Q_NULLPTR);
+ QGraphicsView(QGraphicsScene *scene, QWidget *parent = Q_NULLPTR);
~QGraphicsView();
QSize sizeHint() const Q_DECL_OVERRIDE;
@@ -230,7 +230,7 @@ protected Q_SLOTS:
void setupViewport(QWidget *widget) Q_DECL_OVERRIDE;
protected:
- QGraphicsView(QGraphicsViewPrivate &, QWidget *parent = 0);
+ QGraphicsView(QGraphicsViewPrivate &, QWidget *parent = Q_NULLPTR);
bool event(QEvent *event) Q_DECL_OVERRIDE;
bool viewportEvent(QEvent *event) Q_DECL_OVERRIDE;
diff --git a/src/widgets/graphicsview/qgraphicsview_p.h b/src/widgets/graphicsview/qgraphicsview_p.h
index fec8336695..dcbffb1c39 100644
--- a/src/widgets/graphicsview/qgraphicsview_p.h
+++ b/src/widgets/graphicsview/qgraphicsview_p.h
@@ -63,6 +63,7 @@ class Q_WIDGETS_EXPORT QGraphicsViewPrivate : public QAbstractScrollAreaPrivate
Q_DECLARE_PUBLIC(QGraphicsView)
public:
QGraphicsViewPrivate();
+ ~QGraphicsViewPrivate();
void recalculateContentSize();
void centerView(QGraphicsView::ViewportAnchor anchor);
diff --git a/src/widgets/graphicsview/qgraphicswidget.cpp b/src/widgets/graphicsview/qgraphicswidget.cpp
index 6f10e2854c..67311ed2c3 100644
--- a/src/widgets/graphicsview/qgraphicswidget.cpp
+++ b/src/widgets/graphicsview/qgraphicswidget.cpp
@@ -304,6 +304,7 @@ void QGraphicsWidget::resize(const QSizeF &size)
/*!
\fn void QGraphicsWidget::resize(qreal w, qreal h)
+ \overload
This convenience function is equivalent to calling resize(QSizeF(w, h)).
diff --git a/src/widgets/graphicsview/qgraphicswidget.h b/src/widgets/graphicsview/qgraphicswidget.h
index 3ecdeac158..0878e020bc 100644
--- a/src/widgets/graphicsview/qgraphicswidget.h
+++ b/src/widgets/graphicsview/qgraphicswidget.h
@@ -74,7 +74,7 @@ class Q_WIDGETS_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphic
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(QGraphicsItem *parent = Q_NULLPTR, Qt::WindowFlags wFlags = Qt::WindowFlags());
~QGraphicsWidget();
QGraphicsLayout *layout() const;
void setLayout(QGraphicsLayout *layout);
@@ -156,8 +156,8 @@ public:
};
int type() const Q_DECL_OVERRIDE;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) Q_DECL_OVERRIDE;
- virtual void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) Q_DECL_OVERRIDE;
+ virtual void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR);
QRectF boundingRect() const Q_DECL_OVERRIDE;
QPainterPath shape() const Q_DECL_OVERRIDE;
@@ -213,7 +213,7 @@ protected:
virtual void ungrabMouseEvent(QEvent *event);
virtual void grabKeyboardEvent(QEvent *event);
virtual void ungrabKeyboardEvent(QEvent *event);
- QGraphicsWidget(QGraphicsWidgetPrivate &, QGraphicsItem *parent, Qt::WindowFlags wFlags = 0);
+ QGraphicsWidget(QGraphicsWidgetPrivate &, QGraphicsItem *parent, Qt::WindowFlags wFlags = Qt::WindowFlags());
private:
Q_DISABLE_COPY(QGraphicsWidget)
diff --git a/src/widgets/itemviews/itemviews.pri b/src/widgets/itemviews/itemviews.pri
index 2bbf7ac1ff..245962d35f 100644
--- a/src/widgets/itemviews/itemviews.pri
+++ b/src/widgets/itemviews/itemviews.pri
@@ -4,6 +4,7 @@ HEADERS += \
itemviews/qabstractitemview.h \
itemviews/qabstractitemview_p.h \
itemviews/qheaderview.h \
+ itemviews/qheaderview_p.h \
itemviews/qlistview.h \
itemviews/qlistview_p.h \
itemviews/qbsptree_p.h \
diff --git a/src/widgets/itemviews/qabstractitemdelegate.h b/src/widgets/itemviews/qabstractitemdelegate.h
index c250179087..b29717d1e1 100644
--- a/src/widgets/itemviews/qabstractitemdelegate.h
+++ b/src/widgets/itemviews/qabstractitemdelegate.h
@@ -63,7 +63,7 @@ public:
RevertModelCache
};
- explicit QAbstractItemDelegate(QObject *parent = 0);
+ explicit QAbstractItemDelegate(QObject *parent = Q_NULLPTR);
virtual ~QAbstractItemDelegate();
// painting
@@ -113,7 +113,7 @@ Q_SIGNALS:
void sizeHintChanged(const QModelIndex &);
protected:
- QAbstractItemDelegate(QObjectPrivate &, QObject *parent = 0);
+ QAbstractItemDelegate(QObjectPrivate &, QObject *parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QAbstractItemDelegate)
Q_DISABLE_COPY(QAbstractItemDelegate)
diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp
index 2caf5d1eb3..c5601b63b2 100644
--- a/src/widgets/itemviews/qabstractitemview.cpp
+++ b/src/widgets/itemviews/qabstractitemview.cpp
@@ -1882,8 +1882,7 @@ void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
|| (d->pressedIndex != index)) {
QMouseEvent me(QEvent::MouseButtonPress,
event->localPos(), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&me, event->source());
+ event->button(), event->buttons(), event->modifiers(), event->source());
mousePressEvent(&me);
return;
}
@@ -2386,7 +2385,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
}
#endif
break;
-#ifdef Q_OS_MAC
+#ifdef Q_OS_OSX
case Qt::Key_Enter:
case Qt::Key_Return:
// Propagate the enter if you couldn't edit the item and there are no
@@ -2416,7 +2415,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
selectAll();
break;
}
-#ifdef Q_OS_MAC
+#ifdef Q_OS_OSX
if (event->key() == Qt::Key_O && event->modifiers() & Qt::ControlModifier && currentIndex().isValid()) {
emit activated(currentIndex());
break;
@@ -3017,9 +3016,8 @@ int QAbstractItemView::sizeHintForRow(int row) const
QStyleOptionViewItem option = d->viewOptionsV1();
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);
+ const QModelIndex 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();
@@ -3048,9 +3046,8 @@ int QAbstractItemView::sizeHintForColumn(int column) const
QStyleOptionViewItem option = d->viewOptionsV1();
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);
+ const QModelIndex 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();
diff --git a/src/widgets/itemviews/qabstractitemview.h b/src/widgets/itemviews/qabstractitemview.h
index 1be17b6c0e..ff1848b149 100644
--- a/src/widgets/itemviews/qabstractitemview.h
+++ b/src/widgets/itemviews/qabstractitemview.h
@@ -115,7 +115,7 @@ public:
};
Q_ENUM(ScrollMode)
- explicit QAbstractItemView(QWidget *parent = 0);
+ explicit QAbstractItemView(QWidget *parent = Q_NULLPTR);
~QAbstractItemView();
virtual void setModel(QAbstractItemModel *model);
@@ -258,7 +258,7 @@ Q_SIGNALS:
void iconSizeChanged(const QSize &size);
protected:
- QAbstractItemView(QAbstractItemViewPrivate &, QWidget *parent = 0);
+ QAbstractItemView(QAbstractItemViewPrivate &, QWidget *parent = Q_NULLPTR);
void setHorizontalStepsPerItem(int steps);
int horizontalStepsPerItem() const;
@@ -283,7 +283,7 @@ protected:
virtual bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event);
virtual QItemSelectionModel::SelectionFlags selectionCommand(const QModelIndex &index,
- const QEvent *event = 0) const;
+ const QEvent *event = Q_NULLPTR) const;
#ifndef QT_NO_DRAGANDDROP
virtual void startDrag(Qt::DropActions supportedActions);
diff --git a/src/widgets/itemviews/qabstractitemview_p.h b/src/widgets/itemviews/qabstractitemview_p.h
index 016c50436b..bb88b25652 100644
--- a/src/widgets/itemviews/qabstractitemview_p.h
+++ b/src/widgets/itemviews/qabstractitemview_p.h
@@ -74,7 +74,7 @@ typedef QHash<QWidget *, QPersistentModelIndex> QEditorIndexHash;
typedef QHash<QPersistentModelIndex, QEditorInfo> QIndexEditorHash;
typedef QPair<QRect, QModelIndex> QItemViewPaintPair;
-typedef QList<QItemViewPaintPair> QItemViewPaintPairs;
+typedef QVector<QItemViewPaintPair> QItemViewPaintPairs;
class QEmptyModel : public QAbstractItemModel
{
diff --git a/src/widgets/itemviews/qcolumnview.cpp b/src/widgets/itemviews/qcolumnview.cpp
index 5c317bbb0c..92bbdf6b69 100644
--- a/src/widgets/itemviews/qcolumnview.cpp
+++ b/src/widgets/itemviews/qcolumnview.cpp
@@ -861,11 +861,15 @@ void QColumnView::setColumnWidths(const QList<int> &list)
{
Q_D(QColumnView);
int i = 0;
- for (; (i < list.count() && i < d->columns.count()); ++i) {
+ const int listCount = list.count();
+ const int count = qMin(listCount, d->columns.count());
+ for (; i < 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.reserve(listCount);
+ for (; i < listCount; ++i)
d->columnSizes.append(list.at(i));
}
@@ -878,7 +882,9 @@ QList<int> QColumnView::columnWidths() const
{
Q_D(const QColumnView);
QList<int> list;
- for (int i = 0; i < d->columns.count(); ++i)
+ const int columnCount = d->columns.count();
+ list.reserve(columnCount);
+ for (int i = 0; i < columnCount; ++i)
list.append(d->columnSizes.at(i));
return list;
}
diff --git a/src/widgets/itemviews/qcolumnview.h b/src/widgets/itemviews/qcolumnview.h
index 792ae04eb6..58472ddd8e 100644
--- a/src/widgets/itemviews/qcolumnview.h
+++ b/src/widgets/itemviews/qcolumnview.h
@@ -52,7 +52,7 @@ Q_SIGNALS:
void updatePreviewWidget(const QModelIndex &index);
public:
- explicit QColumnView(QWidget *parent = 0);
+ explicit QColumnView(QWidget *parent = Q_NULLPTR);
~QColumnView();
// QAbstractItemView overloads
@@ -76,7 +76,7 @@ public:
QList<int> columnWidths() const;
protected:
- QColumnView(QColumnViewPrivate &dd, QWidget *parent = 0);
+ QColumnView(QColumnViewPrivate &dd, QWidget *parent = Q_NULLPTR);
// QAbstractItemView overloads
bool isIndexHidden(const QModelIndex &index) const Q_DECL_OVERRIDE;
diff --git a/src/widgets/itemviews/qdatawidgetmapper.cpp b/src/widgets/itemviews/qdatawidgetmapper.cpp
index c9fdf9967a..ee7b3613a2 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.cpp
+++ b/src/widgets/itemviews/qdatawidgetmapper.cpp
@@ -756,7 +756,7 @@ void QDataWidgetMapper::clearMapping()
QList<QDataWidgetMapperPrivate::WidgetMapper> copy;
d->widgetMap.swap(copy); // a C++98 move
- for (std::reverse_iterator<QList<QDataWidgetMapperPrivate::WidgetMapper>::const_iterator> it(copy.cend()), end(copy.cbegin()); it != end; ++it) {
+ for (QList<QDataWidgetMapperPrivate::WidgetMapper>::const_reverse_iterator it = copy.crbegin(), end = copy.crend(); it != end; ++it) {
if (it->widget)
it->widget->removeEventFilter(d->delegate);
}
diff --git a/src/widgets/itemviews/qdatawidgetmapper.h b/src/widgets/itemviews/qdatawidgetmapper.h
index 5ccbee4d68..4dd5e0e14c 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.h
+++ b/src/widgets/itemviews/qdatawidgetmapper.h
@@ -55,7 +55,7 @@ class Q_WIDGETS_EXPORT QDataWidgetMapper: public QObject
Q_PROPERTY(SubmitPolicy submitPolicy READ submitPolicy WRITE setSubmitPolicy)
public:
- explicit QDataWidgetMapper(QObject *parent = 0);
+ explicit QDataWidgetMapper(QObject *parent = Q_NULLPTR);
~QDataWidgetMapper();
void setModel(QAbstractItemModel *model);
diff --git a/src/widgets/itemviews/qdirmodel.cpp b/src/widgets/itemviews/qdirmodel.cpp
index 50406b51f4..0c157c940f 100644
--- a/src/widgets/itemviews/qdirmodel.cpp
+++ b/src/widgets/itemviews/qdirmodel.cpp
@@ -66,7 +66,6 @@ public:
struct QDirNode
{
QDirNode() : parent(0), populated(false), stat(false) {}
- ~QDirNode() { children.clear(); }
QDirNode *parent;
QFileInfo info;
QIcon icon; // cache the icon
diff --git a/src/widgets/itemviews/qdirmodel.h b/src/widgets/itemviews/qdirmodel.h
index dcc337244c..536e5299a2 100644
--- a/src/widgets/itemviews/qdirmodel.h
+++ b/src/widgets/itemviews/qdirmodel.h
@@ -60,8 +60,8 @@ public:
};
QDirModel(const QStringList &nameFilters, QDir::Filters filters,
- QDir::SortFlags sort, QObject *parent = 0);
- explicit QDirModel(QObject *parent = 0);
+ QDir::SortFlags sort, QObject *parent = Q_NULLPTR);
+ explicit QDirModel(QObject *parent = Q_NULLPTR);
~QDirModel();
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
@@ -127,7 +127,7 @@ public Q_SLOTS:
void refresh(const QModelIndex &parent = QModelIndex());
protected:
- QDirModel(QDirModelPrivate &, QObject *parent = 0);
+ QDirModel(QDirModelPrivate &, QObject *parent = Q_NULLPTR);
friend class QFileDialogPrivate;
private:
diff --git a/src/widgets/itemviews/qfileiconprovider.cpp b/src/widgets/itemviews/qfileiconprovider.cpp
index 051cb8e7cc..f43bcd5d5a 100644
--- a/src/widgets/itemviews/qfileiconprovider.cpp
+++ b/src/widgets/itemviews/qfileiconprovider.cpp
@@ -117,6 +117,7 @@ public:
if (themeSizes.isEmpty())
return sizes;
+ sizes.reserve(themeSizes.count());
foreach (int size, themeSizes)
sizes << QSize(size, size);
}
diff --git a/src/widgets/itemviews/qheaderview.h b/src/widgets/itemviews/qheaderview.h
index e0f57130c0..d892614a39 100644
--- a/src/widgets/itemviews/qheaderview.h
+++ b/src/widgets/itemviews/qheaderview.h
@@ -68,7 +68,7 @@ public:
};
Q_ENUM(ResizeMode)
- explicit QHeaderView(Qt::Orientation orientation, QWidget *parent = 0);
+ explicit QHeaderView(Qt::Orientation orientation, QWidget *parent = Q_NULLPTR);
virtual ~QHeaderView();
void setModel(QAbstractItemModel *model) Q_DECL_OVERRIDE;
@@ -202,7 +202,7 @@ protected Q_SLOTS:
void sectionsAboutToBeRemoved(const QModelIndex &parent, int logicalFirst, int logicalLast);
protected:
- QHeaderView(QHeaderViewPrivate &dd, Qt::Orientation orientation, QWidget *parent = 0);
+ QHeaderView(QHeaderViewPrivate &dd, Qt::Orientation orientation, QWidget *parent = Q_NULLPTR);
void initialize();
void initializeSections();
diff --git a/src/widgets/itemviews/qheaderview_p.h b/src/widgets/itemviews/qheaderview_p.h
index 621c3c990e..7f92d2a81b 100644
--- a/src/widgets/itemviews/qheaderview_p.h
+++ b/src/widgets/itemviews/qheaderview_p.h
@@ -369,6 +369,7 @@ public:
#endif
};
+Q_DECLARE_TYPEINFO(QHeaderViewPrivate::SectionItem, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qitemdelegate.h b/src/widgets/itemviews/qitemdelegate.h
index edc224b0f3..beba6b90fb 100644
--- a/src/widgets/itemviews/qitemdelegate.h
+++ b/src/widgets/itemviews/qitemdelegate.h
@@ -53,7 +53,7 @@ class Q_WIDGETS_EXPORT QItemDelegate : public QAbstractItemDelegate
Q_PROPERTY(bool clipping READ hasClipping WRITE setClipping)
public:
- explicit QItemDelegate(QObject *parent = 0);
+ explicit QItemDelegate(QObject *parent = Q_NULLPTR);
~QItemDelegate();
bool hasClipping() const;
diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp
index f3fd3e75a1..9b07564db9 100644
--- a/src/widgets/itemviews/qlistview.cpp
+++ b/src/widgets/itemviews/qlistview.cpp
@@ -53,6 +53,8 @@
QT_BEGIN_NAMESPACE
+extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
+
/*!
\class QListView
@@ -796,6 +798,35 @@ void QListView::mouseReleaseEvent(QMouseEvent *e)
}
}
+#ifndef QT_NO_WHEELEVENT
+/*!
+ \reimp
+*/
+void QListView::wheelEvent(QWheelEvent *e)
+{
+ Q_D(QListView);
+ if (e->orientation() == Qt::Vertical) {
+ if (e->angleDelta().x() == 0
+ && ((d->flow == TopToBottom && d->wrap) || (d->flow == LeftToRight && !d->wrap))
+ && d->vbar->minimum() == 0 && d->vbar->maximum() == 0) {
+ QPoint pixelDelta(e->pixelDelta().y(), e->pixelDelta().x());
+ QPoint angleDelta(e->angleDelta().y(), e->angleDelta().x());
+ QWheelEvent hwe(e->pos(), e->globalPos(), pixelDelta, angleDelta, e->delta(),
+ Qt::Horizontal, e->buttons(), e->modifiers(), e->phase());
+ if (e->spontaneous())
+ qt_sendSpontaneousEvent(d->hbar, &hwe);
+ else
+ QApplication::sendEvent(d->hbar, &hwe);
+ e->setAccepted(hwe.isAccepted());
+ } else {
+ QApplication::sendEvent(d->vbar, e);
+ }
+ } else {
+ QApplication::sendEvent(d->hbar, e);
+ }
+}
+#endif // QT_NO_WHEELEVENT
+
/*!
\reimp
*/
diff --git a/src/widgets/itemviews/qlistview.h b/src/widgets/itemviews/qlistview.h
index f62c96067f..433933b500 100644
--- a/src/widgets/itemviews/qlistview.h
+++ b/src/widgets/itemviews/qlistview.h
@@ -72,7 +72,7 @@ public:
enum ViewMode { ListMode, IconMode };
Q_ENUM(ViewMode)
- explicit QListView(QWidget *parent = 0);
+ explicit QListView(QWidget *parent = Q_NULLPTR);
~QListView();
void setMovement(Movement movement);
@@ -131,7 +131,7 @@ Q_SIGNALS:
void indexesMoved(const QModelIndexList &indexes);
protected:
- QListView(QListViewPrivate &, QWidget *parent = 0);
+ QListView(QListViewPrivate &, QWidget *parent = Q_NULLPTR);
bool event(QEvent *e) Q_DECL_OVERRIDE;
@@ -146,6 +146,9 @@ protected:
void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
+#ifndef QT_NO_WHEELEVENT
+ void wheelEvent(QWheelEvent *e) Q_DECL_OVERRIDE;
+#endif
void timerEvent(QTimerEvent *e) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE;
diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h
index fe059d73dd..c1b5b8772c 100644
--- a/src/widgets/itemviews/qlistview_p.h
+++ b/src/widgets/itemviews/qlistview_p.h
@@ -93,6 +93,7 @@ private:
mutable int indexHint;
uint visited;
};
+Q_DECLARE_TYPEINFO(QListViewItem, Q_PRIMITIVE_TYPE);
struct QListViewLayoutInfo
{
@@ -105,6 +106,7 @@ struct QListViewLayoutInfo
QListView::Flow flow;
int max;
};
+Q_DECLARE_TYPEINFO(QListViewLayoutInfo, Q_PRIMITIVE_TYPE);
class QListView;
class QListViewPrivate;
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index 66f965aa54..0e1e56e966 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -299,7 +299,10 @@ void QListModel::sort(int column, Qt::SortOrder order)
std::sort(sorting.begin(), sorting.end(), compare);
QModelIndexList fromIndexes;
QModelIndexList toIndexes;
- for (int r = 0; r < sorting.count(); ++r) {
+ const int sortingCount = sorting.count();
+ fromIndexes.reserve(sortingCount);
+ toIndexes.reserve(sortingCount);
+ for (int r = 0; r < sortingCount; ++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));
@@ -423,7 +426,9 @@ QMimeData *QListModel::internalMimeData() const
QMimeData *QListModel::mimeData(const QModelIndexList &indexes) const
{
QList<QListWidgetItem*> itemlist;
- for (int i = 0; i < indexes.count(); ++i)
+ const int indexesCount = indexes.count();
+ itemlist.reserve(indexesCount);
+ for (int i = 0; i < indexesCount; ++i)
itemlist << at(indexes.at(i).row());
const QListWidget *view = qobject_cast<const QListWidget*>(QObject::parent());
@@ -1694,7 +1699,9 @@ QList<QListWidgetItem*> QListWidget::selectedItems() const
Q_D(const QListWidget);
QModelIndexList indexes = selectionModel()->selectedIndexes();
QList<QListWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i)
+ const int numIndexes = indexes.count();
+ items.reserve(numIndexes);
+ for (int i = 0; i < numIndexes; ++i)
items.append(d->listModel()->at(indexes.at(i).row()));
return items;
}
@@ -1710,7 +1717,9 @@ QList<QListWidgetItem*> QListWidget::findItems(const QString &text, Qt::MatchFla
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)
+ const int indexesSize = indexes.size();
+ items.reserve(indexesSize);
+ for (int i = 0; i < indexesSize; ++i)
items.append(d->listModel()->at(indexes.at(i).row()));
return items;
}
@@ -1795,6 +1804,7 @@ QMimeData *QListWidget::mimeData(const QList<QListWidgetItem*> items) const
// if non empty, it's called from the model's own mimeData
if (cachedIndexes.isEmpty()) {
+ cachedIndexes.reserve(items.count());
foreach (QListWidgetItem *item, items)
cachedIndexes << indexFromItem(item);
@@ -1845,7 +1855,9 @@ void QListWidget::dropEvent(QDropEvent *event) {
if (d->dropOn(event, &row, &col, &topIndex)) {
QList<QModelIndex> selIndexes = selectedIndexes();
QList<QPersistentModelIndex> persIndexes;
- for (int i = 0; i < selIndexes.count(); i++)
+ const int selIndexesCount = selIndexes.count();
+ persIndexes.reserve(selIndexesCount);
+ for (int i = 0; i < selIndexesCount; i++)
persIndexes.append(selIndexes.at(i));
if (persIndexes.contains(topIndex))
diff --git a/src/widgets/itemviews/qlistwidget.h b/src/widgets/itemviews/qlistwidget.h
index 8ab864c930..1fbdc472db 100644
--- a/src/widgets/itemviews/qlistwidget.h
+++ b/src/widgets/itemviews/qlistwidget.h
@@ -55,10 +55,10 @@ class Q_WIDGETS_EXPORT QListWidgetItem
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(QListWidget *view = Q_NULLPTR, int type = Type);
+ explicit QListWidgetItem(const QString &text, QListWidget *view = Q_NULLPTR, int type = Type);
explicit QListWidgetItem(const QIcon &icon, const QString &text,
- QListWidget *view = 0, int type = Type);
+ QListWidget *view = Q_NULLPTR, int type = Type);
QListWidgetItem(const QListWidgetItem &other);
virtual ~QListWidgetItem();
@@ -198,7 +198,7 @@ class Q_WIDGETS_EXPORT QListWidget : public QListView
friend class QListWidgetItem;
friend class QListModel;
public:
- explicit QListWidget(QWidget *parent = 0);
+ explicit QListWidget(QWidget *parent = Q_NULLPTR);
~QListWidget();
QListWidgetItem *item(int row) const;
@@ -299,7 +299,7 @@ private:
};
inline void QListWidget::removeItemWidget(QListWidgetItem *aItem)
-{ setItemWidget(aItem, 0); }
+{ setItemWidget(aItem, Q_NULLPTR); }
inline void QListWidget::addItem(QListWidgetItem *aitem)
{ insertItem(count(), aitem); }
diff --git a/src/widgets/itemviews/qstyleditemdelegate.h b/src/widgets/itemviews/qstyleditemdelegate.h
index 590ddf6614..541830239a 100644
--- a/src/widgets/itemviews/qstyleditemdelegate.h
+++ b/src/widgets/itemviews/qstyleditemdelegate.h
@@ -52,7 +52,7 @@ class Q_WIDGETS_EXPORT QStyledItemDelegate : public QAbstractItemDelegate
Q_OBJECT
public:
- explicit QStyledItemDelegate(QObject *parent = 0);
+ explicit QStyledItemDelegate(QObject *parent = Q_NULLPTR);
~QStyledItemDelegate();
// painting
diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp
index ae31387faf..3e3e3099c8 100644
--- a/src/widgets/itemviews/qtableview.cpp
+++ b/src/widgets/itemviews/qtableview.cpp
@@ -1884,6 +1884,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
break;
}
} while (expanded);
+ selection.reserve((right - left + 1) * (bottom - top + 1));
for (int horizontal = left; horizontal <= right; ++horizontal) {
int column = d->logicalColumn(horizontal);
for (int vertical = top; vertical <= bottom; ++vertical) {
@@ -1897,6 +1898,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
int left = d->visualColumn(tl.column());
int bottom = d->visualRow(br.row());
int right = d->visualColumn(br.column());
+ selection.reserve((right - left + 1) * (bottom - top + 1));
for (int horizontal = left; horizontal <= right; ++horizontal) {
int column = d->logicalColumn(horizontal);
for (int vertical = top; vertical <= bottom; ++vertical) {
@@ -1908,6 +1910,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
} else if (horizontalMoved) {
int left = d->visualColumn(tl.column());
int right = d->visualColumn(br.column());
+ selection.reserve(right - left + 1);
for (int visual = left; visual <= right; ++visual) {
int column = d->logicalColumn(visual);
QModelIndex topLeft = d->model->index(tl.row(), column, d->root);
@@ -1917,6 +1920,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
} else if (verticalMoved) {
int top = d->visualRow(tl.row());
int bottom = d->visualRow(br.row());
+ selection.reserve(bottom - top + 1);
for (int visual = top; visual <= bottom; ++visual) {
int row = d->logicalRow(visual);
QModelIndex topLeft = d->model->index(row, tl.column(), d->root);
@@ -2540,7 +2544,7 @@ void QTableView::setColumnHidden(int column, bool hide)
*/
/*!
- If \a enabled true enables sorting for the table and immediately
+ If \a enable is true, enables sorting for the table and immediately
trigger a call to sortByColumn() with the current sort section and
order
*/
diff --git a/src/widgets/itemviews/qtableview.h b/src/widgets/itemviews/qtableview.h
index d69b78c6fe..1bb23844cc 100644
--- a/src/widgets/itemviews/qtableview.h
+++ b/src/widgets/itemviews/qtableview.h
@@ -54,7 +54,7 @@ class Q_WIDGETS_EXPORT QTableView : public QAbstractItemView
Q_PROPERTY(bool cornerButtonEnabled READ isCornerButtonEnabled WRITE setCornerButtonEnabled)
public:
- explicit QTableView(QWidget *parent = 0);
+ explicit QTableView(QWidget *parent = Q_NULLPTR);
~QTableView();
void setModel(QAbstractItemModel *model) Q_DECL_OVERRIDE;
diff --git a/src/widgets/itemviews/qtablewidget.cpp b/src/widgets/itemviews/qtablewidget.cpp
index 9ebcbc35a7..f0c7ac0d32 100644
--- a/src/widgets/itemviews/qtablewidget.cpp
+++ b/src/widgets/itemviews/qtablewidget.cpp
@@ -507,11 +507,15 @@ void QTableModel::sort(int column, Qt::SortOrder order)
QVector<QTableWidgetItem*> sorted_table(tableItems.count());
QModelIndexList from;
QModelIndexList to;
- for (int i = 0; i < rowCount(); ++i) {
+ const int numRows = rowCount();
+ const int numColumns = columnCount();
+ from.reserve(numRows * numColumns);
+ to.reserve(numRows * numColumns);
+ for (int i = 0; i < numRows; ++i) {
int r = (i < sortable.count()
? sortable.at(i).second
: unsortable.at(i - sortable.count()));
- for (int c = 0; c < columnCount(); ++c) {
+ for (int c = 0; c < numColumns; ++c) {
sorted_table[tableIndex(i, c)] = item(r, c);
from.append(createIndex(r, c));
to.append(createIndex(i, c));
@@ -812,7 +816,9 @@ QMimeData *QTableModel::internalMimeData() const
QMimeData *QTableModel::mimeData(const QModelIndexList &indexes) const
{
QList<QTableWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i)
+ const int indexesCount = indexes.count();
+ items.reserve(indexesCount);
+ for (int i = 0; i < indexesCount; ++i)
items << item(indexes.at(i));
const QTableWidget *view = qobject_cast<const QTableWidget*>(QObject::parent());
@@ -2326,7 +2332,9 @@ QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges() const
{
const QList<QItemSelectionRange> ranges = selectionModel()->selection();
QList<QTableWidgetSelectionRange> result;
- for (int i = 0; i < ranges.count(); ++i)
+ const int rangesCount = ranges.count();
+ result.reserve(rangesCount);
+ for (int i = 0; i < rangesCount; ++i)
result.append(QTableWidgetSelectionRange(ranges.at(i).top(),
ranges.at(i).left(),
ranges.at(i).bottom(),
@@ -2372,7 +2380,9 @@ QList<QTableWidgetItem*> QTableWidget::findItems(const QString &text, Qt::MatchF
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)
+ const int indexCount = indexes.size();
+ items.reserve(indexCount);
+ for (int i = 0; i < indexCount; ++i)
items.append(d->tableModel()->item(indexes.at(i)));
return items;
}
@@ -2565,6 +2575,7 @@ QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem*> items) const
// if non empty, it's called from the model's own mimeData
if (cachedIndexes.isEmpty()) {
+ cachedIndexes.reserve(items.count());
foreach (QTableWidgetItem *item, items)
cachedIndexes << indexFromItem(item);
@@ -2676,7 +2687,9 @@ void QTableWidget::dropEvent(QDropEvent *event) {
}
QList<QTableWidgetItem *> taken;
- for (int i = 0; i < indexes.count(); ++i)
+ const int indexesCount = indexes.count();
+ taken.reserve(indexesCount);
+ for (int i = 0; i < indexesCount; ++i)
taken.append(takeItem(indexes.at(i).row(), indexes.at(i).column()));
for (int i = 0; i < indexes.count(); ++i) {
diff --git a/src/widgets/itemviews/qtablewidget.h b/src/widgets/itemviews/qtablewidget.h
index 93639f0753..9acdc19863 100644
--- a/src/widgets/itemviews/qtablewidget.h
+++ b/src/widgets/itemviews/qtablewidget.h
@@ -214,8 +214,8 @@ class Q_WIDGETS_EXPORT QTableWidget : public QTableView
friend class QTableModel;
public:
- explicit QTableWidget(QWidget *parent = 0);
- QTableWidget(int rows, int columns, QWidget *parent = 0);
+ explicit QTableWidget(QWidget *parent = Q_NULLPTR);
+ QTableWidget(int rows, int columns, QWidget *parent = Q_NULLPTR);
~QTableWidget();
void setRowCount(int rows);
@@ -344,7 +344,7 @@ private:
};
inline void QTableWidget::removeCellWidget(int arow, int acolumn)
-{ setCellWidget(arow, acolumn, 0); }
+{ setCellWidget(arow, acolumn, Q_NULLPTR); }
inline QTableWidgetItem *QTableWidget::itemAt(int ax, int ay) const
{ return itemAt(QPoint(ax, ay)); }
diff --git a/src/widgets/itemviews/qtreeview.h b/src/widgets/itemviews/qtreeview.h
index e9e2e78e17..546cc488cb 100644
--- a/src/widgets/itemviews/qtreeview.h
+++ b/src/widgets/itemviews/qtreeview.h
@@ -60,7 +60,7 @@ class Q_WIDGETS_EXPORT QTreeView : public QAbstractItemView
Q_PROPERTY(bool expandsOnDoubleClick READ expandsOnDoubleClick WRITE setExpandsOnDoubleClick)
public:
- explicit QTreeView(QWidget *parent = 0);
+ explicit QTreeView(QWidget *parent = Q_NULLPTR);
~QTreeView();
void setModel(QAbstractItemModel *model) Q_DECL_OVERRIDE;
@@ -163,7 +163,7 @@ protected Q_SLOTS:
void rowsRemoved(const QModelIndex &parent, int first, int last);
protected:
- QTreeView(QTreeViewPrivate &dd, QWidget *parent = 0);
+ QTreeView(QTreeViewPrivate &dd, QWidget *parent = Q_NULLPTR);
void scrollContentsBy(int dx, int dy) Q_DECL_OVERRIDE;
void rowsInserted(const QModelIndex &parent, int start, int end) Q_DECL_OVERRIDE;
void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) Q_DECL_OVERRIDE;
diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp
index bf736bc387..5970e94292 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -1720,12 +1720,12 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
}
} break;
case Qt::CheckStateRole:
- if ((itemFlags & Qt::ItemIsTristate) && value != Qt::PartiallyChecked) {
+ if ((itemFlags & Qt::ItemIsAutoTristate) && value != Qt::PartiallyChecked) {
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;
+ itemFlags &= ~Qt::ItemIsAutoTristate;
child->setData(column, role, value);
itemFlags = f;
}
@@ -1760,7 +1760,7 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
model->emitDataChanged(this, column);
if (role == Qt::CheckStateRole) {
QTreeWidgetItem *p;
- for (p = par; p && (p->itemFlags & Qt::ItemIsTristate); p = p->par)
+ for (p = par; p && (p->itemFlags & Qt::ItemIsAutoTristate); p = p->par)
model->emitDataChanged(p, column);
}
}
@@ -1779,7 +1779,7 @@ QVariant QTreeWidgetItem::data(int column, int role) const
break;
case Qt::CheckStateRole:
// special case for check state in tristate
- if (children.count() && (itemFlags & Qt::ItemIsTristate))
+ if (children.count() && (itemFlags & Qt::ItemIsAutoTristate))
return childrenCheckState(column);
// fallthrough intended
default:
@@ -3042,7 +3042,9 @@ QList<QTreeWidgetItem*> QTreeWidget::findItems(const QString &text, Qt::MatchFla
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)
+ const int indexesSize = indexes.size();
+ items.reserve(indexesSize);
+ for (int i = 0; i < indexesSize; ++i)
items.append(d->item(indexes.at(i)));
return items;
}
@@ -3371,7 +3373,9 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
if (d->dropOn(event, &row, &col, &topIndex)) {
QList<QModelIndex> idxs = selectedIndexes();
QList<QPersistentModelIndex> indexes;
- for (int i = 0; i < idxs.count(); i++)
+ const int indexesCount = idxs.count();
+ indexes.reserve(indexesCount);
+ for (int i = 0; i < indexesCount; i++)
indexes.append(idxs.at(i));
if (indexes.contains(topIndex))
diff --git a/src/widgets/itemviews/qtreewidget.h b/src/widgets/itemviews/qtreewidget.h
index 564e10ac1a..995528fe37 100644
--- a/src/widgets/itemviews/qtreewidget.h
+++ b/src/widgets/itemviews/qtreewidget.h
@@ -172,7 +172,7 @@ public:
inline QTreeWidgetItem *parent() const { return par; }
inline QTreeWidgetItem *child(int index) const {
if (index < 0 || index >= children.size())
- return 0;
+ return Q_NULLPTR;
executePendingSort();
return children.at(index);
}
@@ -255,7 +255,7 @@ class Q_WIDGETS_EXPORT QTreeWidget : public QTreeView
friend class QTreeModel;
friend class QTreeWidgetItem;
public:
- explicit QTreeWidget(QWidget *parent = 0);
+ explicit QTreeWidget(QWidget *parent = Q_NULLPTR);
~QTreeWidget();
int columnCount() const;
@@ -375,7 +375,7 @@ private:
};
inline void QTreeWidget::removeItemWidget(QTreeWidgetItem *item, int column)
-{ setItemWidget(item, column, 0); }
+{ setItemWidget(item, column, Q_NULLPTR); }
inline QTreeWidgetItem *QTreeWidget::itemAt(int ax, int ay) const
{ return itemAt(QPoint(ax, ay)); }
diff --git a/src/widgets/itemviews/qwidgetitemdata_p.h b/src/widgets/itemviews/qwidgetitemdata_p.h
index 307d228c74..d8c1fc2ff7 100644
--- a/src/widgets/itemviews/qwidgetitemdata_p.h
+++ b/src/widgets/itemviews/qwidgetitemdata_p.h
@@ -58,6 +58,7 @@ public:
QVariant value;
inline bool operator==(const QWidgetItemData &other) const { return role == other.role && value == other.value; }
};
+Q_DECLARE_TYPEINFO(QWidgetItemData, Q_MOVABLE_TYPE);
#ifndef QT_NO_DATASTREAM
diff --git a/src/widgets/kernel/qaction.cpp b/src/widgets/kernel/qaction.cpp
index 4dd10720d6..95c4877eb9 100644
--- a/src/widgets/kernel/qaction.cpp
+++ b/src/widgets/kernel/qaction.cpp
@@ -223,8 +223,9 @@ void QActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map)
\snippet mainwindows/application/mainwindow.cpp 19
\codeline
- \snippet mainwindows/application/mainwindow.cpp 28
- \snippet mainwindows/application/mainwindow.cpp 31
+ \code
+ fileMenu->addAction(openAct);
+ \endcode
We recommend that actions are created as children of the window
they are used in. In most cases actions will be children of
diff --git a/src/widgets/kernel/qaction.h b/src/widgets/kernel/qaction.h
index 1d69694699..8ef26b60bf 100644
--- a/src/widgets/kernel/qaction.h
+++ b/src/widgets/kernel/qaction.h
@@ -153,7 +153,7 @@ public:
enum ActionEvent { Trigger, Hover };
void activate(ActionEvent event);
- bool showStatusText(QWidget *widget=0);
+ bool showStatusText(QWidget *widget = Q_NULLPTR);
void setMenuRole(MenuRole menuRole);
MenuRole menuRole() const;
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index 647484ece1..d8c14de060 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -3249,12 +3249,11 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QPointer<QWidget> pw = w;
while (w) {
- QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(), mouse->button(), mouse->buttons(),
- mouse->modifiers());
+ QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(),
+ mouse->button(), mouse->buttons(), mouse->modifiers(), mouse->source());
me.spont = mouse->spontaneous();
me.setTimestamp(mouse->timestamp());
QGuiApplicationPrivate::setMouseEventFlags(&me, mouse->flags());
- QGuiApplicationPrivate::setMouseEventSource(&me, mouse->source());
// throw away any mouse-tracking-only mouse events
if (!w->hasMouseTracking()
&& mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
@@ -3688,7 +3687,9 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
{
// send to all application event filters
- if (sendThroughApplicationEventFilters(receiver, e))
+ if (threadRequiresCoreApplication()
+ && receiver->d_func()->threadData->thread == mainThread()
+ && sendThroughApplicationEventFilters(receiver, e))
return true;
if (receiver->isWidgetType()) {
diff --git a/src/widgets/kernel/qapplication.h b/src/widgets/kernel/qapplication.h
index d4b2326afd..7aaea2a947 100644
--- a/src/widgets/kernel/qapplication.h
+++ b/src/widgets/kernel/qapplication.h
@@ -104,11 +104,11 @@ public:
using QGuiApplication::palette;
static QPalette palette(const QWidget *);
static QPalette palette(const char *className);
- static void setPalette(const QPalette &, const char* className = 0);
+ static void setPalette(const QPalette &, const char* className = Q_NULLPTR);
static QFont font();
static QFont font(const QWidget*);
static QFont font(const char *className);
- static void setFont(const QFont &, const char* className = 0);
+ static void setFont(const QFont &, const char* className = Q_NULLPTR);
static QFontMetrics fontMetrics();
#if QT_VERSION < 0x060000 // remove these forwarders in Qt 6
diff --git a/src/widgets/kernel/qboxlayout.h b/src/widgets/kernel/qboxlayout.h
index 5ce9ca26f6..10209e05c9 100644
--- a/src/widgets/kernel/qboxlayout.h
+++ b/src/widgets/kernel/qboxlayout.h
@@ -54,7 +54,7 @@ public:
enum Direction { LeftToRight, RightToLeft, TopToBottom, BottomToTop,
Down = TopToBottom, Up = BottomToTop };
- explicit QBoxLayout(Direction, QWidget *parent = 0);
+ explicit QBoxLayout(Direction, QWidget *parent = Q_NULLPTR);
~QBoxLayout();
@@ -64,7 +64,7 @@ public:
void addSpacing(int size);
void addStretch(int stretch = 0);
void addSpacerItem(QSpacerItem *spacerItem);
- void addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = 0);
+ void addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = Qt::Alignment());
void addLayout(QLayout *layout, int stretch = 0);
void addStrut(int);
void addItem(QLayoutItem *) Q_DECL_OVERRIDE;
@@ -72,7 +72,7 @@ public:
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 insertWidget(int index, QWidget *widget, int stretch = 0, Qt::Alignment alignment = Qt::Alignment());
void insertLayout(int index, QLayout *layout, int stretch = 0);
void insertItem(int index, QLayoutItem *);
diff --git a/src/widgets/kernel/qdesktopwidget.h b/src/widgets/kernel/qdesktopwidget.h
index 5412c5bc4a..c0cc4f1b81 100644
--- a/src/widgets/kernel/qdesktopwidget.h
+++ b/src/widgets/kernel/qdesktopwidget.h
@@ -58,7 +58,7 @@ public:
int screenCount() const;
int primaryScreen() const;
- int screenNumber(const QWidget *widget = 0) const;
+ int screenNumber(const QWidget *widget = Q_NULLPTR) const;
int screenNumber(const QPoint &) const;
QWidget *screen(int screen = -1);
diff --git a/src/widgets/kernel/qformlayout.h b/src/widgets/kernel/qformlayout.h
index 18f3c84354..0767d78ce6 100644
--- a/src/widgets/kernel/qformlayout.h
+++ b/src/widgets/kernel/qformlayout.h
@@ -74,7 +74,7 @@ public:
};
Q_ENUM(ItemRole)
- explicit QFormLayout(QWidget *parent = 0);
+ explicit QFormLayout(QWidget *parent = Q_NULLPTR);
~QFormLayout();
void setFieldGrowthPolicy(FieldGrowthPolicy policy);
diff --git a/src/widgets/kernel/qgesture.h b/src/widgets/kernel/qgesture.h
index dfe9450365..bcf583a507 100644
--- a/src/widgets/kernel/qgesture.h
+++ b/src/widgets/kernel/qgesture.h
@@ -63,7 +63,7 @@ class Q_WIDGETS_EXPORT QGesture : public QObject
Q_PROPERTY(bool hasHotSpot READ hasHotSpot)
public:
- explicit QGesture(QObject *parent = 0);
+ explicit QGesture(QObject *parent = Q_NULLPTR);
~QGesture();
Qt::GestureType gestureType() const;
@@ -107,7 +107,7 @@ class Q_WIDGETS_EXPORT QPanGesture : public QGesture
Q_PRIVATE_PROPERTY(QPanGesture::d_func(), qreal verticalVelocity READ verticalVelocity WRITE setVerticalVelocity)
public:
- explicit QPanGesture(QObject *parent = 0);
+ explicit QPanGesture(QObject *parent = Q_NULLPTR);
~QPanGesture();
QPointF lastOffset() const;
@@ -154,7 +154,7 @@ public:
Q_PROPERTY(QPointF centerPoint READ centerPoint WRITE setCenterPoint)
public:
- explicit QPinchGesture(QObject *parent = 0);
+ explicit QPinchGesture(QObject *parent = Q_NULLPTR);
~QPinchGesture();
ChangeFlags totalChangeFlags() const;
@@ -210,7 +210,7 @@ public:
enum SwipeDirection { NoDirection, Left, Right, Up, Down };
Q_ENUM(SwipeDirection)
- explicit QSwipeGesture(QObject *parent = 0);
+ explicit QSwipeGesture(QObject *parent = Q_NULLPTR);
~QSwipeGesture();
SwipeDirection horizontalDirection() const;
@@ -231,7 +231,7 @@ class Q_WIDGETS_EXPORT QTapGesture : public QGesture
Q_PROPERTY(QPointF position READ position WRITE setPosition)
public:
- explicit QTapGesture(QObject *parent = 0);
+ explicit QTapGesture(QObject *parent = Q_NULLPTR);
~QTapGesture();
QPointF position() const;
@@ -249,7 +249,7 @@ class Q_WIDGETS_EXPORT QTapAndHoldGesture : public QGesture
Q_PROPERTY(QPointF position READ position WRITE setPosition)
public:
- explicit QTapAndHoldGesture(QObject *parent = 0);
+ explicit QTapAndHoldGesture(QObject *parent = Q_NULLPTR);
~QTapAndHoldGesture();
QPointF position() const;
diff --git a/src/widgets/kernel/qgesturemanager.cpp b/src/widgets/kernel/qgesturemanager.cpp
index b5d3a56d3f..8cb7c2b560 100644
--- a/src/widgets/kernel/qgesturemanager.cpp
+++ b/src/widgets/kernel/qgesturemanager.cpp
@@ -569,18 +569,19 @@ void QGestureManager::getGestureTargets(const QSet<QGesture*> &gestures,
}
// for each gesture type
- foreach (Qt::GestureType type, gestureByTypes.keys()) {
- QHash<QWidget *, QGesture *> gestures = gestureByTypes.value(type);
- foreach (QWidget *widget, gestures.keys()) {
+ for (GestureByTypes::const_iterator git = gestureByTypes.cbegin(), gend = gestureByTypes.cend(); git != gend; ++git) {
+ const QHash<QWidget *, QGesture *> &gestures = git.value();
+ for (QHash<QWidget *, QGesture *>::const_iterator wit = gestures.cbegin(), wend = gestures.cend(); wit != wend; ++wit) {
+ QWidget *widget = wit.key();
QWidget *w = widget->parentWidget();
while (w) {
QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator it
- = w->d_func()->gestureContext.constFind(type);
+ = w->d_func()->gestureContext.constFind(git.key());
if (it != w->d_func()->gestureContext.constEnd()) {
// i.e. 'w' listens to gesture 'type'
if (!(it.value() & Qt::DontStartGestureOnChildren) && w != widget) {
// conflicting gesture!
- (*conflicts)[widget].append(gestures[widget]);
+ (*conflicts)[widget].append(wit.value());
break;
}
}
@@ -591,7 +592,7 @@ void QGestureManager::getGestureTargets(const QSet<QGesture*> &gestures,
w = w->parentWidget();
}
if (!w)
- (*normal)[widget].append(gestures[widget]);
+ (*normal)[widget].append(wit.value());
}
}
}
diff --git a/src/widgets/kernel/qgridlayout.h b/src/widgets/kernel/qgridlayout.h
index a582d31634..ae3fe125b6 100644
--- a/src/widgets/kernel/qgridlayout.h
+++ b/src/widgets/kernel/qgridlayout.h
@@ -93,10 +93,10 @@ public:
void invalidate() Q_DECL_OVERRIDE;
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 addWidget(QWidget *, int row, int column, Qt::Alignment = Qt::Alignment());
+ void addWidget(QWidget *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = Qt::Alignment());
+ void addLayout(QLayout *, int row, int column, Qt::Alignment = Qt::Alignment());
+ void addLayout(QLayout *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = Qt::Alignment());
void setOriginCorner(Qt::Corner);
Qt::Corner originCorner() const;
@@ -107,7 +107,7 @@ public:
int count() const Q_DECL_OVERRIDE;
void setGeometry(const QRect&) Q_DECL_OVERRIDE;
- void addItem(QLayoutItem *item, int row, int column, int rowSpan = 1, int columnSpan = 1, Qt::Alignment = 0);
+ void addItem(QLayoutItem *item, int row, int column, int rowSpan = 1, int columnSpan = 1, Qt::Alignment = Qt::Alignment());
void setDefaultPositioning(int n, Qt::Orientation orient);
void getItemPosition(int idx, int *row, int *column, int *rowSpan, int *columnSpan) const;
diff --git a/src/widgets/kernel/qlayout.cpp b/src/widgets/kernel/qlayout.cpp
index d3e5986103..e74f17b6f7 100644
--- a/src/widgets/kernel/qlayout.cpp
+++ b/src/widgets/kernel/qlayout.cpp
@@ -1175,13 +1175,12 @@ QLayoutItem *QLayout::replaceWidget(QWidget *from, QWidget *to, Qt::FindChildOpt
if (index == -1)
return 0;
+ addChildWidget(to);
QLayoutItem *newitem = new QWidgetItem(to);
newitem->setAlignment(item->alignment());
QLayoutItem *r = d->replaceAt(index, newitem);
if (!r)
delete newitem;
- else
- addChildWidget(to);
return r;
}
diff --git a/src/widgets/kernel/qlayoutitem.h b/src/widgets/kernel/qlayoutitem.h
index 650e114c76..cdb612728f 100644
--- a/src/widgets/kernel/qlayoutitem.h
+++ b/src/widgets/kernel/qlayoutitem.h
@@ -53,7 +53,7 @@ class QSize;
class Q_WIDGETS_EXPORT QLayoutItem
{
public:
- inline explicit QLayoutItem(Qt::Alignment alignment = 0);
+ inline explicit QLayoutItem(Qt::Alignment alignment = Qt::Alignment());
virtual ~QLayoutItem();
virtual QSize sizeHint() const = 0;
virtual QSize minimumSize() const = 0;
diff --git a/src/widgets/kernel/qopenglwidget.cpp b/src/widgets/kernel/qopenglwidget.cpp
index 1ee28f2e9a..b98e8a6a66 100644
--- a/src/widgets/kernel/qopenglwidget.cpp
+++ b/src/widgets/kernel/qopenglwidget.cpp
@@ -553,7 +553,8 @@ public:
hasBeenComposed(false),
flushPending(false),
paintDevice(0),
- updateBehavior(QOpenGLWidget::NoPartialUpdate)
+ updateBehavior(QOpenGLWidget::NoPartialUpdate),
+ requestedSamples(0)
{
requestedFormat = QSurfaceFormat::defaultFormat();
}
@@ -595,6 +596,7 @@ public:
QOpenGLPaintDevice *paintDevice;
QSurfaceFormat requestedFormat;
QOpenGLWidget::UpdateBehavior updateBehavior;
+ int requestedSamples;
};
void QOpenGLWidgetPaintDevicePrivate::beginPaint()
@@ -686,7 +688,7 @@ void QOpenGLWidgetPrivate::recreateFbo()
delete resolvedFbo;
resolvedFbo = 0;
- int samples = context->format().samples();
+ int samples = requestedSamples;
QOpenGLExtensions *extfuncs = static_cast<QOpenGLExtensions *>(context->functions());
if (!extfuncs->hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample))
samples = 0;
@@ -695,7 +697,7 @@ void QOpenGLWidgetPrivate::recreateFbo()
format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
format.setSamples(samples);
- const QSize deviceSize = q->size() * q->devicePixelRatio();
+ const QSize deviceSize = q->size() * q->devicePixelRatioF();
fbo = new QOpenGLFramebufferObject(deviceSize, format);
if (samples > 0)
resolvedFbo = new QOpenGLFramebufferObject(deviceSize);
@@ -704,7 +706,7 @@ void QOpenGLWidgetPrivate::recreateFbo()
context->functions()->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
paintDevice->setSize(deviceSize);
- paintDevice->setDevicePixelRatio(q->devicePixelRatio());
+ paintDevice->setDevicePixelRatio(q->devicePixelRatioF());
emit q->resized();
}
@@ -742,6 +744,13 @@ void QOpenGLWidgetPrivate::initialize()
return;
}
+ // Do not include the sample count. Requesting a multisampled context is not necessary
+ // since we render into an FBO, never to an actual surface. What's more, attempting to
+ // create a pbuffer with a multisampled config crashes certain implementations. Just
+ // avoid the entire hassle, the result is the same.
+ requestedSamples = requestedFormat.samples();
+ requestedFormat.setSamples(0);
+
QScopedPointer<QOpenGLContext> ctx(new QOpenGLContext);
ctx->setShareContext(shareContext);
ctx->setFormat(requestedFormat);
@@ -778,8 +787,8 @@ void QOpenGLWidgetPrivate::initialize()
}
paintDevice = new QOpenGLWidgetPaintDevice(q);
- paintDevice->setSize(q->size() * q->devicePixelRatio());
- paintDevice->setDevicePixelRatio(q->devicePixelRatio());
+ paintDevice->setSize(q->size() * q->devicePixelRatioF());
+ paintDevice->setDevicePixelRatio(q->devicePixelRatioF());
context = ctx.take();
initialized = true;
@@ -808,7 +817,7 @@ void QOpenGLWidgetPrivate::invokeUserPaint()
QOpenGLFunctions *f = ctx->functions();
QOpenGLContextPrivate::get(ctx)->defaultFboRedirect = fbo->handle();
- f->glViewport(0, 0, q->width() * q->devicePixelRatio(), q->height() * q->devicePixelRatio());
+ f->glViewport(0, 0, q->width() * q->devicePixelRatioF(), q->height() * q->devicePixelRatioF());
q->paintGL();
flushPending = true;
@@ -859,8 +868,8 @@ QImage QOpenGLWidgetPrivate::grabFramebuffer()
render();
resolveSamples();
q->makeCurrent();
- QImage res = qt_gl_read_framebuffer(q->size() * q->devicePixelRatio(), false, false);
- res.setDevicePixelRatio(q->devicePixelRatio());
+ QImage res = qt_gl_read_framebuffer(q->size() * q->devicePixelRatioF(), false, false);
+ res.setDevicePixelRatio(q->devicePixelRatioF());
return res;
}
@@ -879,7 +888,7 @@ void QOpenGLWidgetPrivate::resizeViewportFramebuffer()
if (!initialized)
return;
- if (!fbo || q->size() * q->devicePixelRatio() != fbo->size())
+ if (!fbo || q->size() * q->devicePixelRatioF() != fbo->size())
recreateFbo();
}
@@ -1196,6 +1205,7 @@ int QOpenGLWidget::metric(QPaintDevice::PaintDeviceMetric metric) const
return QWidget::metric(metric);
QWidget *tlw = window();
+ QWindow *window = tlw ? tlw->windowHandle() : 0;
QScreen *screen = tlw && tlw->windowHandle() ? tlw->windowHandle()->screen() : 0;
if (!screen && QGuiApplication::primaryScreen())
screen = QGuiApplication::primaryScreen();
@@ -1243,8 +1253,13 @@ int QOpenGLWidget::metric(QPaintDevice::PaintDeviceMetric metric) const
else
return qRound(dpmy * 0.0254);
case PdmDevicePixelRatio:
- if (screen)
- return screen->devicePixelRatio();
+ if (window)
+ return int(window->devicePixelRatio());
+ else
+ return 1.0;
+ case PdmDevicePixelRatioScaled:
+ if (window)
+ return int(window->devicePixelRatio() * devicePixelRatioFScale());
else
return 1.0;
default:
@@ -1304,7 +1319,7 @@ bool QOpenGLWidget::event(QEvent *e)
}
break;
case QEvent::ScreenChangeInternal:
- if (d->initialized && d->paintDevice->devicePixelRatio() != devicePixelRatio())
+ if (d->initialized && d->paintDevice->devicePixelRatioF() != devicePixelRatioF())
d->recreateFbo();
break;
default:
diff --git a/src/widgets/kernel/qopenglwidget.h b/src/widgets/kernel/qopenglwidget.h
index 4a9edb8180..ca65d75ca8 100644
--- a/src/widgets/kernel/qopenglwidget.h
+++ b/src/widgets/kernel/qopenglwidget.h
@@ -57,7 +57,7 @@ public:
PartialUpdate
};
- explicit QOpenGLWidget(QWidget* parent = 0, Qt::WindowFlags f = 0);
+ explicit QOpenGLWidget(QWidget* parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
~QOpenGLWidget();
void setUpdateBehavior(UpdateBehavior updateBehavior);
diff --git a/src/widgets/kernel/qshortcut.h b/src/widgets/kernel/qshortcut.h
index 9171f855ba..e816bbe06d 100644
--- a/src/widgets/kernel/qshortcut.h
+++ b/src/widgets/kernel/qshortcut.h
@@ -55,7 +55,7 @@ class Q_WIDGETS_EXPORT QShortcut : public QObject
public:
explicit QShortcut(QWidget *parent);
QShortcut(const QKeySequence& key, QWidget *parent,
- const char *member = 0, const char *ambiguousMember = 0,
+ const char *member = Q_NULLPTR, const char *ambiguousMember = Q_NULLPTR,
Qt::ShortcutContext context = Qt::WindowShortcut);
~QShortcut();
diff --git a/src/widgets/kernel/qsizepolicy.cpp b/src/widgets/kernel/qsizepolicy.cpp
index 1476b4c5d7..3c28f5ccf7 100644
--- a/src/widgets/kernel/qsizepolicy.cpp
+++ b/src/widgets/kernel/qsizepolicy.cpp
@@ -332,6 +332,15 @@ void QSizePolicy::setControlType(ControlType type)
*/
/*!
+ \fn uint qHash(QSizePolicy key, uint seed = 0)
+ \since 5.6
+ \relates QSizePolicy
+
+ Returns the hash value for \a key, using
+ \a seed to seed the calculation.
+*/
+
+/*!
\fn int QSizePolicy::horizontalStretch() const
Returns the horizontal stretch factor of the size policy.
diff --git a/src/widgets/kernel/qsizepolicy.h b/src/widgets/kernel/qsizepolicy.h
index 6cd511f513..7c9a356973 100644
--- a/src/widgets/kernel/qsizepolicy.h
+++ b/src/widgets/kernel/qsizepolicy.h
@@ -40,6 +40,9 @@ QT_BEGIN_NAMESPACE
class QVariant;
+class QSizePolicy;
+
+Q_DECL_CONST_FUNCTION inline uint qHash(QSizePolicy key, uint seed = 0) Q_DECL_NOTHROW;
class Q_WIDGETS_EXPORT QSizePolicy
{
@@ -112,6 +115,9 @@ public:
bool operator==(const QSizePolicy& s) const { return data == s.data; }
bool operator!=(const QSizePolicy& s) const { return data != s.data; }
+
+ friend Q_DECL_CONST_FUNCTION uint qHash(QSizePolicy key, uint seed) Q_DECL_NOTHROW { return qHash(key.data, seed); }
+
operator QVariant() const;
int horizontalStretch() const { return static_cast<int>(bits.horStretch); }
diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp
index 8a800ab9d0..51bf6e4684 100644
--- a/src/widgets/kernel/qtooltip.cpp
+++ b/src/widgets/kernel/qtooltip.cpp
@@ -37,7 +37,6 @@
#include <qapplication.h>
#include <qdesktopwidget.h>
#include <qevent.h>
-#include <qhash.h>
#include <qlabel.h>
#include <qpointer.h>
#include <qstyle.h>
diff --git a/src/widgets/kernel/qtooltip.h b/src/widgets/kernel/qtooltip.h
index 286d8fb327..54cf71d2f0 100644
--- a/src/widgets/kernel/qtooltip.h
+++ b/src/widgets/kernel/qtooltip.h
@@ -46,7 +46,7 @@ class Q_WIDGETS_EXPORT QToolTip
QToolTip() Q_DECL_EQ_DELETE;
public:
// ### Qt 6 - merge the three showText functions below
- static void showText(const QPoint &pos, const QString &text, QWidget *w = 0);
+ static void showText(const QPoint &pos, const QString &text, QWidget *w = Q_NULLPTR);
static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect);
static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecShowTime);
static inline void hideText() { showText(QPoint(), QString()); }
diff --git a/src/widgets/kernel/qwhatsthis.cpp b/src/widgets/kernel/qwhatsthis.cpp
index 5fb4695687..1e437c4fb7 100644
--- a/src/widgets/kernel/qwhatsthis.cpp
+++ b/src/widgets/kernel/qwhatsthis.cpp
@@ -42,7 +42,6 @@
#include "qscreen.h"
#include "qpainter.h"
#include "qtimer.h"
-#include "qhash.h"
#include "qaction.h"
#include "qcursor.h"
#include "qbitmap.h"
diff --git a/src/widgets/kernel/qwhatsthis.h b/src/widgets/kernel/qwhatsthis.h
index 999c66486c..367b8aab3c 100644
--- a/src/widgets/kernel/qwhatsthis.h
+++ b/src/widgets/kernel/qwhatsthis.h
@@ -53,10 +53,10 @@ public:
static bool inWhatsThisMode();
static void leaveWhatsThisMode();
- static void showText(const QPoint &pos, const QString &text, QWidget *w = 0);
+ static void showText(const QPoint &pos, const QString &text, QWidget *w = Q_NULLPTR);
static void hideText();
- static QAction *createAction(QObject *parent = 0);
+ static QAction *createAction(QObject *parent = Q_NULLPTR);
};
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index ba0fcf75d0..32c52ade56 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -37,7 +37,6 @@
#include "qcursor.h"
#include "qdesktopwidget_p.h"
#include "qevent.h"
-#include "qhash.h"
#include "qlayout.h"
#include "qmenu.h"
#include "qmetaobject.h"
@@ -69,6 +68,7 @@
#include "private/qstylesheetstyle_p.h"
#include "private/qstyle_p.h"
#include "qfileinfo.h"
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qinputmethod.h>
#include <QtGui/qopenglcontext.h>
#include <QtGui/private/qopenglcontext_p.h>
@@ -100,6 +100,7 @@
#include "qwindowcontainer_p.h"
+#include <QtPlatformHeaders/qxcbwindowfunctions.h>
// widget/widget data creation count
//#define QWIDGET_EXTRA_DEBUG
@@ -711,7 +712,7 @@ void QWidget::setAutoFillBackground(bool enabled)
close().
\row \li Top-level windows \li
- \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
+ \l windowModified, \l windowTitle, \l windowIcon,
\l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
\l maximized, showMaximized(), \l fullScreen, showFullScreen(),
showNormal().
@@ -2038,7 +2039,7 @@ void QWidgetPrivate::setSystemClip(QPaintDevice *paintDevice, const QRegion &reg
// Transform the system clip region from device-independent pixels to device pixels
QPaintEngine *paintEngine = paintDevice->paintEngine();
QTransform scaleTransform;
- const qreal devicePixelRatio = paintDevice->devicePixelRatio();
+ const qreal devicePixelRatio = paintDevice->devicePixelRatioF();
scaleTransform.scale(devicePixelRatio, devicePixelRatio);
paintEngine->d_func()->systemClip = scaleTransform.map(region);
}
@@ -5364,7 +5365,7 @@ void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset
if (size.isNull())
return;
- const qreal pixmapDevicePixelRatio = qreal(painter->device()->devicePixelRatio());
+ const qreal pixmapDevicePixelRatio = painter->device()->devicePixelRatioF();
QPixmap pixmap(size * pixmapDevicePixelRatio);
pixmap.setDevicePixelRatio(pixmapDevicePixelRatio);
@@ -5949,7 +5950,7 @@ void QWidget::unsetLocale()
window title, if set. This is done by the QPA plugin, so it is shown to the
user, but isn't part of the windowTitle string.
- \sa windowIcon, windowIconText, windowModified, windowFilePath
+ \sa windowIcon, windowModified, windowFilePath
*/
QString QWidget::windowTitle() const
{
@@ -6044,7 +6045,11 @@ void QWidgetPrivate::setWindowIconText_helper(const QString &title)
void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
{
- Q_UNUSED(iconText);
+ Q_Q(QWidget);
+ // ### The QWidget property is deprecated, but the XCB window function is not.
+ // It should remain available for the rare application that needs it.
+ if (QWindow *window = q->windowHandle())
+ QXcbWindowFunctions::setWmWindowIconText(window, iconText);
}
/*!
@@ -6054,6 +6059,9 @@ void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
new \a iconText as an argument.
\since 5.2
+ \obsolete
+
+ This signal is deprecated.
*/
void QWidget::setWindowIconText(const QString &iconText)
@@ -6104,7 +6112,7 @@ void QWidget::setWindowTitle(const QString &title)
has been set, windowIcon() returns the application icon
(QApplication::windowIcon()).
- \sa windowIconText, windowTitle
+ \sa windowTitle
*/
QIcon QWidget::windowIcon() const
{
@@ -6120,8 +6128,15 @@ QIcon QWidget::windowIcon() const
void QWidgetPrivate::setWindowIcon_helper()
{
+ Q_Q(QWidget);
QEvent e(QEvent::WindowIconChange);
- QApplication::sendEvent(q_func(), &e);
+
+ // Do not send the event if the widget is a top level.
+ // In that case, setWindowIcon_sys does it, and event propagation from
+ // QWidgetWindow to the top level QWidget ensures that the event reaches
+ // the top level anyhow
+ if (!q->windowHandle())
+ QApplication::sendEvent(q, &e);
for (int i = 0; i < children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(children.at(i));
if (w && !w->isWindow())
@@ -6164,10 +6179,15 @@ void QWidgetPrivate::setWindowIcon_sys()
/*!
\property QWidget::windowIconText
- \brief the widget's icon text
+ \brief the text to be displayed on the icon of a minimized window
This property only makes sense for windows. If no icon
- text has been set, this functions returns an empty string.
+ text has been set, this accessor returns an empty string.
+ It is only implemented on the X11 platform, and only certain
+ window managers use this window property.
+
+ \obsolete
+ This property is deprecated.
\sa windowIcon, windowTitle
*/
@@ -9721,6 +9741,8 @@ void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
d->imHints = hints;
if (this == QGuiApplication::focusObject())
QGuiApplication::inputMethod()->update(Qt::ImHints);
+#else
+ Q_UNUSED(hints);
#endif //QT_NO_IM
}
@@ -11815,13 +11837,11 @@ void QWidgetPrivate::updateFrameStrut()
Q_Q(QWidget);
if (q->data->fstrut_dirty) {
if (QTLWExtra *te = maybeTopData()) {
- if (te->window) {
- if (const QPlatformWindow *pw = te->window->handle()) {
- const QMargins margins = pw->frameMargins();
- if (!margins.isNull()) {
- te->frameStrut.setCoords(margins.left(), margins.top(), margins.right(), margins.bottom());
- q->data->fstrut_dirty = false;
- }
+ if (te->window && te->window->handle()) {
+ const QMargins margins = te->window->frameMargins();
+ if (!margins.isNull()) {
+ te->frameStrut.setCoords(margins.left(), margins.top(), margins.right(), margins.bottom());
+ q->data->fstrut_dirty = false;
}
}
}
@@ -12640,6 +12660,9 @@ int QWidget::metric(PaintDeviceMetric m) const
return qRound(screen->physicalDotsPerInchY());
} else if (m == PdmDevicePixelRatio) {
return topLevelWindow ? topLevelWindow->devicePixelRatio() : qApp->devicePixelRatio();
+ } else if (m == PdmDevicePixelRatioScaled) {
+ return (QPaintDevice::devicePixelRatioFScale() *
+ (topLevelWindow ? topLevelWindow->devicePixelRatio() : qApp->devicePixelRatio()));
} else {
val = QPaintDevice::metric(m);// XXX
}
@@ -12765,7 +12788,7 @@ void QWidgetPrivate::setMask_sys(const QRegion &region)
Q_Q(QWidget);
if (const QWindow *window = q->windowHandle())
if (QPlatformWindow *platformWindow = window->handle())
- platformWindow->setMask(region);
+ platformWindow->setMask(QHighDpi::toNativeLocalRegion(region, window));
}
/*!
@@ -12818,6 +12841,65 @@ void QWidgetPrivate::setWidgetParentHelper(QObject *widgetAsObject, QObject *new
widget->setParent(static_cast<QWidget*>(newParent));
}
+#ifndef QT_NO_DEBUG_STREAM
+
+static inline void formatWidgetAttributes(QDebug debug, const QWidget *widget)
+{
+ const QMetaObject *qtMo = qt_getEnumMetaObject(Qt::WA_AttributeCount);
+ const QMetaEnum me = qtMo->enumerator(qtMo->indexOfEnumerator("WidgetAttribute"));
+ debug << ", attributes=[";
+ int count = 0;
+ for (int a = 0; a < Qt::WA_AttributeCount; ++a) {
+ if (widget->testAttribute(static_cast<Qt::WidgetAttribute>(a))) {
+ if (count++)
+ debug << ',';
+ debug << me.valueToKey(a);
+ }
+ }
+ debug << ']';
+}
+
+QDebug operator<<(QDebug debug, const QWidget *widget)
+{
+ const QDebugStateSaver saver(debug);
+ debug.nospace();
+ if (widget) {
+ debug << widget->metaObject()->className() << '(' << (const void *)widget;
+ if (!widget->objectName().isEmpty())
+ debug << ", name=" << widget->objectName();
+ if (debug.verbosity() > 2) {
+ const QRect geometry = widget->geometry();
+ const QRect frameGeometry = widget->frameGeometry();
+ if (widget->isVisible())
+ debug << ", visible";
+ if (!widget->isEnabled())
+ debug << ", disabled";
+ debug << ", states=" << widget->windowState()
+ << ", type=" << widget->windowType() << ", flags=" << widget->windowFlags();
+ formatWidgetAttributes(debug, widget);
+ if (widget->isWindow())
+ debug << ", window";
+ debug << ", " << geometry.width() << 'x' << geometry.height()
+ << forcesign << geometry.x() << geometry.y() << noforcesign;
+ if (frameGeometry != geometry) {
+ const QMargins margins(geometry.x() - frameGeometry.x(),
+ geometry.y() - frameGeometry.y(),
+ frameGeometry.right() - geometry.right(),
+ frameGeometry.bottom() - geometry.bottom());
+ debug << ", margins=" << margins;
+ }
+ debug << ", devicePixelRatio=" << widget->devicePixelRatioF();
+ if (const WId wid = widget->internalWinId())
+ debug << ", winId=0x" << hex << wid << dec;
+ }
+ debug << ')';
+ } else {
+ debug << "QWidget(0x0)";
+ }
+ return debug;
+}
+#endif // !QT_NO_DEBUG_STREAM
+
/*! \fn Qt::HANDLE QWidget::macCGHandle() const
\internal
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index c3913e9d45..a56f6e1133 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -89,6 +89,9 @@ class QGraphicsEffect;
class QRasterWindowSurface;
class QUnifiedToolbarSurface;
class QPixmap;
+#ifndef QT_NO_DEBUG_STREAM
+class QDebug;
+#endif
class QWidgetData
{
@@ -165,7 +168,7 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
Q_PROPERTY(bool acceptDrops READ acceptDrops WRITE setAcceptDrops)
Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle NOTIFY windowTitleChanged DESIGNABLE isWindow)
Q_PROPERTY(QIcon windowIcon READ windowIcon WRITE setWindowIcon NOTIFY windowIconChanged DESIGNABLE isWindow)
- Q_PROPERTY(QString windowIconText READ windowIconText WRITE setWindowIconText NOTIFY windowIconTextChanged DESIGNABLE isWindow)
+ Q_PROPERTY(QString windowIconText READ windowIconText WRITE setWindowIconText NOTIFY windowIconTextChanged DESIGNABLE isWindow) // deprecated
Q_PROPERTY(double windowOpacity READ windowOpacity WRITE setWindowOpacity DESIGNABLE isWindow)
Q_PROPERTY(bool windowModified READ isWindowModified WRITE setWindowModified DESIGNABLE isWindow)
#ifndef QT_NO_TOOLTIP
@@ -200,7 +203,7 @@ public:
};
Q_DECLARE_FLAGS(RenderFlags, RenderFlag)
- explicit QWidget(QWidget* parent = 0, Qt::WindowFlags f = 0);
+ explicit QWidget(QWidget* parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
~QWidget();
int devType() const Q_DECL_OVERRIDE;
@@ -590,7 +593,7 @@ public:
QWindow *windowHandle() const;
- static QWidget *createWindowContainer(QWindow *window, QWidget *parent=0, Qt::WindowFlags flags=0);
+ static QWidget *createWindowContainer(QWindow *window, QWidget *parent=Q_NULLPTR, Qt::WindowFlags flags=Qt::WindowFlags());
friend class QDesktopScreenWidget;
@@ -731,12 +734,12 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QWidget::RenderFlags)
#ifndef Q_QDOC
template <> inline QWidget *qobject_cast<QWidget*>(QObject *o)
{
- if (!o || !o->isWidgetType()) return 0;
+ if (!o || !o->isWidgetType()) return Q_NULLPTR;
return static_cast<QWidget*>(o);
}
template <> inline const QWidget *qobject_cast<const QWidget*>(const QObject *o)
{
- if (!o || !o->isWidgetType()) return 0;
+ if (!o || !o->isWidgetType()) return Q_NULLPTR;
return static_cast<const QWidget*>(o);
}
#endif // !Q_QDOC
@@ -858,6 +861,10 @@ inline bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
#define QWIDGETSIZE_MAX ((1<<24)-1)
+#ifndef QT_NO_DEBUG_STREAM
+Q_WIDGETS_EXPORT QDebug operator<<(QDebug, const QWidget *);
+#endif
+
QT_END_NAMESPACE
#endif // QWIDGET_H
diff --git a/src/widgets/kernel/qwidgetbackingstore.cpp b/src/widgets/kernel/qwidgetbackingstore.cpp
index 2a339cda4c..69958636fd 100644
--- a/src/widgets/kernel/qwidgetbackingstore.cpp
+++ b/src/widgets/kernel/qwidgetbackingstore.cpp
@@ -763,9 +763,8 @@ QWidgetBackingStore::~QWidgetBackingStore()
#ifndef QT_NO_OPENGL
delete widgetTextures;
- delete dirtyOnScreenWidgets;
#endif
- dirtyOnScreenWidgets = 0;
+ delete dirtyOnScreenWidgets;
}
//parent's coordinates; move whole rect; update parent and widget
diff --git a/src/widgets/kernel/qwidgetbackingstore_p.h b/src/widgets/kernel/qwidgetbackingstore_p.h
index bcffa3be79..b7ee7e4168 100644
--- a/src/widgets/kernel/qwidgetbackingstore_p.h
+++ b/src/widgets/kernel/qwidgetbackingstore_p.h
@@ -301,6 +301,8 @@ private:
friend class QWidgetPrivate;
friend class QWidget;
friend class QBackingStore;
+
+ Q_DISABLE_COPY(QWidgetBackingStore)
};
QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 24ef7de1cf..deaac4e263 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -45,13 +45,13 @@
#include <qpa/qplatformtheme.h>
#include <qpa/qplatformwindow.h>
#include <private/qgesturemanager_p.h>
+#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
Q_WIDGETS_EXPORT extern bool qt_tab_all_widgets();
QWidget *qt_button_down = 0; // widget got last button-down
-static QPointer<QWidget> qt_tablet_target = 0;
// popup control
QWidget *qt_popup_down = 0; // popup that contains the pressed widget
@@ -161,7 +161,7 @@ bool QWidgetWindow::event(QEvent *event)
if (m_widget->testAttribute(Qt::WA_DontShowOnScreen)) {
// \a event is uninteresting for QWidgetWindow, the event was probably
// generated before WA_DontShowOnScreen was set
- return m_widget->event(event);
+ return QCoreApplication::sendEvent(m_widget, event);
}
switch (event->type()) {
@@ -303,7 +303,7 @@ bool QWidgetWindow::event(QEvent *event)
break;
}
- if (m_widget->event(event) && event->type() != QEvent::Timer)
+ if (QCoreApplication::sendEvent(m_widget, event) && event->type() != QEvent::Timer)
return true;
return QWindow::event(event);
@@ -446,8 +446,8 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
if (receiver != popup)
widgetPos = receiver->mapFromGlobal(event->globalPos());
QWidget *alien = receiver->childAt(receiver->mapFromGlobal(event->globalPos()));
- QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(), event->button(), event->buttons(), event->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&e, QGuiApplicationPrivate::mouseEventSource(event));
+ QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(),
+ event->button(), event->buttons(), event->modifiers(), event->source());
e.setTimestamp(event->timestamp());
QApplicationPrivate::sendMouseEvent(receiver, &e, alien, receiver->window(), &qt_button_down, qt_last_mouse_receiver);
qt_last_mouse_receiver = receiver;
@@ -489,9 +489,9 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
if (globalGeometry.contains(event->globalPos())) {
// Use postEvent() to ensure the local QEventLoop terminates when called from QMenu::exec()
const QPoint localPos = win->mapFromGlobal(event->globalPos());
- QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPos(), event->button(), event->buttons(), event->modifiers());
+ QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPos(),
+ event->button(), event->buttons(), event->modifiers(), event->source());
QCoreApplicationPrivate::setEventSpontaneous(e, true);
- QGuiApplicationPrivate::setMouseEventSource(e, QGuiApplicationPrivate::mouseEventSource(event));
e->setTimestamp(event->timestamp());
QCoreApplication::postEvent(win, e);
}
@@ -548,8 +548,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
// The preceding statement excludes MouseButtonPress events which caused
// creation of a MouseButtonDblClick event. QTBUG-25831
QMouseEvent translated(event->type(), mapped, event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&translated, QGuiApplicationPrivate::mouseEventSource(event));
+ event->button(), event->buttons(), event->modifiers(), event->source());
translated.setTimestamp(event->timestamp());
QApplicationPrivate::sendMouseEvent(receiver, &translated, widget, m_widget,
&qt_button_down, qt_last_mouse_receiver);
@@ -673,7 +672,7 @@ void QWidgetWindow::updateNormalGeometry()
// Ask platform window, default to widget geometry.
QRect normalGeometry;
if (const QPlatformWindow *pw = handle())
- normalGeometry = pw->normalGeometry();
+ normalGeometry = QHighDpi::fromNativePixels(pw->normalGeometry(), this);
if (!normalGeometry.isValid() && effectiveState(m_widget->windowState()) == Qt::WindowNoState)
normalGeometry = m_widget->geometry();
if (normalGeometry.isValid())
@@ -874,6 +873,7 @@ bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, long
#ifndef QT_NO_TABLETEVENT
void QWidgetWindow::handleTabletEvent(QTabletEvent *event)
{
+ static QPointer<QWidget> qt_tablet_target = 0;
if (event->type() == QEvent::TabletPress) {
QWidget *widget = m_widget->childAt(event->pos());
if (!widget)
diff --git a/src/widgets/statemachine/qkeyeventtransition.cpp b/src/widgets/statemachine/qkeyeventtransition.cpp
index 3283003e2e..67af85dd27 100644
--- a/src/widgets/statemachine/qkeyeventtransition.cpp
+++ b/src/widgets/statemachine/qkeyeventtransition.cpp
@@ -117,7 +117,7 @@ int QKeyEventTransition::key() const
}
/*!
- Sets the key that this key event transition will check for.
+ Sets the \a key that this key event transition will check for.
*/
void QKeyEventTransition::setKey(int key)
{
diff --git a/src/widgets/statemachine/qkeyeventtransition.h b/src/widgets/statemachine/qkeyeventtransition.h
index 5dd0685d0b..ad159eaa22 100644
--- a/src/widgets/statemachine/qkeyeventtransition.h
+++ b/src/widgets/statemachine/qkeyeventtransition.h
@@ -48,9 +48,9 @@ class Q_WIDGETS_EXPORT QKeyEventTransition : public QEventTransition
Q_PROPERTY(int key READ key WRITE setKey)
Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
public:
- QKeyEventTransition(QState *sourceState = 0);
+ QKeyEventTransition(QState *sourceState = Q_NULLPTR);
QKeyEventTransition(QObject *object, QEvent::Type type, int key,
- QState *sourceState = 0);
+ QState *sourceState = Q_NULLPTR);
~QKeyEventTransition();
int key() const;
diff --git a/src/widgets/statemachine/qmouseeventtransition.h b/src/widgets/statemachine/qmouseeventtransition.h
index d9bac9e1a0..b4db61279d 100644
--- a/src/widgets/statemachine/qmouseeventtransition.h
+++ b/src/widgets/statemachine/qmouseeventtransition.h
@@ -49,9 +49,9 @@ class Q_WIDGETS_EXPORT QMouseEventTransition : public QEventTransition
Q_PROPERTY(Qt::MouseButton button READ button WRITE setButton)
Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
public:
- QMouseEventTransition(QState *sourceState = 0);
+ QMouseEventTransition(QState *sourceState = Q_NULLPTR);
QMouseEventTransition(QObject *object, QEvent::Type type,
- Qt::MouseButton button, QState *sourceState = 0);
+ Qt::MouseButton button, QState *sourceState = Q_NULLPTR);
~QMouseEventTransition();
Qt::MouseButton button() const;
diff --git a/src/widgets/styles/qcommonstyle.h b/src/widgets/styles/qcommonstyle.h
index 06fd755fa1..0d040f1b3e 100644
--- a/src/widgets/styles/qcommonstyle.h
+++ b/src/widgets/styles/qcommonstyle.h
@@ -49,34 +49,34 @@ public:
~QCommonStyle();
void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const Q_DECL_OVERRIDE;
+ const QWidget *w = Q_NULLPTR) const Q_DECL_OVERRIDE;
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const Q_DECL_OVERRIDE;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ const QWidget *w = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const Q_DECL_OVERRIDE;
+ const QWidget *w = Q_NULLPTR) const Q_DECL_OVERRIDE;
SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const Q_DECL_OVERRIDE;
+ const QPoint &pt, const QWidget *w = Q_NULLPTR) const Q_DECL_OVERRIDE;
QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w = 0) const Q_DECL_OVERRIDE;
+ const QWidget *w = Q_NULLPTR) const Q_DECL_OVERRIDE;
QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ const QSize &contentsSize, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
- int pixelMetric(PixelMetric m, const QStyleOption *opt = 0, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ int pixelMetric(PixelMetric m, const QStyleOption *opt = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
- int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const Q_DECL_OVERRIDE;
+ int styleHint(StyleHint sh, const QStyleOption *opt = Q_NULLPTR, const QWidget *w = Q_NULLPTR,
+ QStyleHintReturn *shret = Q_NULLPTR) const Q_DECL_OVERRIDE;
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const Q_DECL_OVERRIDE;
- QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *opt = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
const QStyleOption *opt) const Q_DECL_OVERRIDE;
int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option = 0,
- const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ Qt::Orientation orientation, const QStyleOption *option = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
void polish(QPalette &) Q_DECL_OVERRIDE;
void polish(QApplication *app) Q_DECL_OVERRIDE;
diff --git a/src/widgets/styles/qdrawutil.h b/src/widgets/styles/qdrawutil.h
index 1f2078a931..f34a2857a7 100644
--- a/src/widgets/styles/qdrawutil.h
+++ b/src/widgets/styles/qdrawutil.h
@@ -63,42 +63,42 @@ Q_WIDGETS_EXPORT void qDrawShadeLine(QPainter *p, const QPoint &p1, const QPoint
Q_WIDGETS_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);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawShadeRect(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken = false,
int lineWidth = 1, int midLineWidth = 0,
- const QBrush *fill = 0);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_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);
+ int lineWidth = 1, const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawShadePanel(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken = false,
- int lineWidth = 1, const QBrush *fill = 0);
+ int lineWidth = 1, const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawWinButton(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawWinButton(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawWinPanel(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawWinPanel(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
+ const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &,
- int lineWidth = 1, const QBrush *fill = 0);
+ int lineWidth = 1, const QBrush *fill = Q_NULLPTR);
Q_WIDGETS_EXPORT void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &,
- int lineWidth = 1, const QBrush *fill = 0);
+ int lineWidth = 1, const QBrush *fill = Q_NULLPTR);
@@ -145,7 +145,7 @@ Q_WIDGETS_EXPORT void qDrawBorderPixmap(QPainter *painter,
const QMargins &sourceMargins,
const QTileRules &rules = QTileRules()
#ifndef Q_QDOC
- , QDrawBorderPixmap::DrawingHints hints = 0
+ , QDrawBorderPixmap::DrawingHints hints = QDrawBorderPixmap::DrawingHints()
#endif
);
diff --git a/src/widgets/styles/qfusionstyle.cpp b/src/widgets/styles/qfusionstyle.cpp
index 6d722c680b..f87542ffa8 100644
--- a/src/widgets/styles/qfusionstyle.cpp
+++ b/src/widgets/styles/qfusionstyle.cpp
@@ -40,7 +40,6 @@
#include <qpushbutton.h>
#include <qpainter.h>
#include <qdir.h>
-#include <qhash.h>
#include <qstyleoption.h>
#include <qapplication.h>
#include <qmainwindow.h>
diff --git a/src/widgets/styles/qgtk2painter.cpp b/src/widgets/styles/qgtk2painter.cpp
index 489d456617..ea8afbc93c 100644
--- a/src/widgets/styles/qgtk2painter.cpp
+++ b/src/widgets/styles/qgtk2painter.cpp
@@ -93,6 +93,7 @@ namespace QGtk2PainterPrivate {
static void initGtk()
{
+#ifndef QT_NO_LIBRARY
static bool initialized = false;
if (!initialized) {
// enforce the "0" suffix, so we'll open libgtk-x11-2.0.so.0
@@ -123,6 +124,7 @@ static void initGtk()
initialized = true;
}
+#endif // !QT_NO_LIBRARY
}
// To recover alpha we apply the gtk painting function two times to
diff --git a/src/widgets/styles/qgtkstyle_p.cpp b/src/widgets/styles/qgtkstyle_p.cpp
index 0e119a11ae..00682c1c0f 100644
--- a/src/widgets/styles/qgtkstyle_p.cpp
+++ b/src/widgets/styles/qgtkstyle_p.cpp
@@ -326,6 +326,7 @@ void QGtkStylePrivate::gtkWidgetSetFocus(GtkWidget *widget, bool focus)
*/
void QGtkStylePrivate::resolveGtk() const
{
+#ifndef QT_NO_LIBRARY
// enforce the "0" suffix, so we'll open libgtk-x11-2.0.so.0
QLibrary libgtk(QLS("gtk-x11-2.0"), 0, 0);
@@ -427,6 +428,7 @@ void QGtkStylePrivate::resolveGtk() const
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");
+#endif // !QT_NO_LIBRARY
}
/* \internal
@@ -593,11 +595,13 @@ void QGtkStylePrivate::cleanupGtkWidgets()
static bool resolveGConf()
{
+#ifndef QT_NO_LIBRARY
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");
}
+#endif // !QT_NO_LIBRARY
return (QGtkStylePrivate::gconf_client_get_default !=0);
}
diff --git a/src/widgets/styles/qmacstyle_mac.mm b/src/widgets/styles/qmacstyle_mac.mm
index d13754b36b..3219952f7f 100644
--- a/src/widgets/styles/qmacstyle_mac.mm
+++ b/src/widgets/styles/qmacstyle_mac.mm
@@ -93,18 +93,6 @@
QT_USE_NAMESPACE
-namespace {
-class AutoReleasePool
-{
-public:
- AutoReleasePool(): pool([[NSAutoreleasePool alloc] init]) {}
- ~AutoReleasePool() { [pool release]; }
-
-private:
- NSAutoreleasePool *pool;
-};
-}
-
@interface QT_MANGLE_NAMESPACE(NotificationReceiver) : NSObject {
QMacStylePrivate *mPrivate;
}
@@ -126,7 +114,7 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(NotificationReceiver);
{
Q_UNUSED(notification);
QEvent event(QEvent::StyleChange);
- QMutableSetIterator<QPointer<QObject> > it(QMacStylePrivate::scrollBars);
+ QMutableVectorIterator<QPointer<QObject> > it(QMacStylePrivate::scrollBars);
while (it.hasNext()) {
if (!it.next())
it.remove();
@@ -150,12 +138,7 @@ const int QMacStylePrivate::BevelButtonW = 50;
const int QMacStylePrivate::BevelButtonH = 22;
const int QMacStylePrivate::PushButtonContentPadding = 6;
-QSet<QPointer<QObject> > QMacStylePrivate::scrollBars;
-
-static uint qHash(const QPointer<QObject> &ptr)
-{
- return qHash(ptr.data());
-}
+QVector<QPointer<QObject> > QMacStylePrivate::scrollBars;
// Title bar gradient colors for Lion were determined by inspecting PSDs exported
// using CoreUI's CoreThemeDocument; there is no public API to retrieve them
@@ -1753,7 +1736,7 @@ QMacStylePrivate::QMacStylePrivate()
QMacStylePrivate::~QMacStylePrivate()
{
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
Q_FOREACH (NSView *b, cocoaControls)
[b release];
}
@@ -1989,7 +1972,7 @@ void QMacStylePrivate::drawColorlessButton(const HIRect &macRect, HIThemeButtonD
}
}
- int devicePixelRatio = p->device()->devicePixelRatio();
+ int devicePixelRatio = p->device()->devicePixelRatioF();
int width = devicePixelRatio * (int(macRect.size.width) + extraWidth);
int height = devicePixelRatio * (int(macRect.size.height) + extraHeight);
@@ -2135,7 +2118,7 @@ QMacStyle::QMacStyle()
: QCommonStyle(*new QMacStylePrivate)
{
Q_D(QMacStyle);
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
d->receiver = [[NotificationReceiver alloc] initWithPrivate:d];
NotificationReceiver *receiver = static_cast<NotificationReceiver *>(d->receiver);
@@ -2152,7 +2135,7 @@ QMacStyle::QMacStyle()
QMacStyle::~QMacStyle()
{
Q_D(QMacStyle);
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
[reinterpret_cast<NSScroller*>(d->nsscroller) release];
@@ -2169,7 +2152,7 @@ QMacStyle::~QMacStyle()
*/
QPixmap QMacStylePrivate::generateBackgroundPattern() const
{
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
QPixmap px(4, 4);
QMacCGContext cg(&px);
HIThemeSetFill(kThemeBrushDialogBackgroundActive, 0, cg, kHIThemeOrientationNormal);
@@ -2767,7 +2750,7 @@ QPalette QMacStyle::standardPalette() const
int QMacStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
QStyleHintReturn *hret) const
{
- AutoReleasePool pool;
+ QMacAutoReleasePool pool;
SInt32 ret = 0;
switch (sh) {
@@ -5380,7 +5363,7 @@ void QMacStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex
// there is not enough space for them.
if (cc == CC_ScrollBar) {
if (opt && opt->styleObject && !QMacStylePrivate::scrollBars.contains(opt->styleObject))
- QMacStylePrivate::scrollBars.insert(QPointer<QObject>(opt->styleObject));
+ QMacStylePrivate::scrollBars.append(QPointer<QObject>(opt->styleObject));
const int scrollBarLength = (slider->orientation == Qt::Horizontal)
? slider->rect.width() : slider->rect.height();
const QMacStyle::WidgetSizePolicy sizePolicy = widgetSizePolicy(widget, opt);
@@ -7217,7 +7200,7 @@ CGContextRef qt_mac_cg_context(const QPaintDevice *pdev)
}
CGContextTranslateCTM(ret, 0, pm->height());
- int devicePixelRatio = pdev->devicePixelRatio();
+ qreal devicePixelRatio = pdev->devicePixelRatioF();
CGContextScaleCTM(ret, devicePixelRatio, devicePixelRatio);
CGContextScaleCTM(ret, 1, -1);
return ret;
diff --git a/src/widgets/styles/qmacstyle_mac_p_p.h b/src/widgets/styles/qmacstyle_mac_p_p.h
index b09e81d595..33818568ec 100644
--- a/src/widgets/styles/qmacstyle_mac_p_p.h
+++ b/src/widgets/styles/qmacstyle_mac_p_p.h
@@ -86,7 +86,7 @@
#include <qdatetimeedit.h>
#include <qmath.h>
#include <qpair.h>
-#include <qset.h>
+#include <qvector.h>
#include <QtWidgets/qgraphicsproxywidget.h>
#include <QtWidgets/qgraphicsview.h>
@@ -213,7 +213,7 @@ public:
mutable QPointer<QObject> pressedButton;
mutable QPointer<QObject> defaultButton;
mutable QPointer<QObject> autoDefaultButton;
- static QSet<QPointer<QObject> > scrollBars;
+ static QVector<QPointer<QObject> > scrollBars;
struct ButtonState {
int frame;
diff --git a/src/widgets/styles/qproxystyle.h b/src/widgets/styles/qproxystyle.h
index cac4cde0f2..072965bbd7 100644
--- a/src/widgets/styles/qproxystyle.h
+++ b/src/widgets/styles/qproxystyle.h
@@ -47,16 +47,16 @@ class Q_WIDGETS_EXPORT QProxyStyle : public QCommonStyle
Q_OBJECT
public:
- QProxyStyle(QStyle *style = 0);
+ QProxyStyle(QStyle *style = Q_NULLPTR);
QProxyStyle(const QString &key);
~QProxyStyle();
QStyle *baseStyle() const;
void setBaseStyle(QStyle *style);
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
- void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
void drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled,
const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const Q_DECL_OVERRIDE;
virtual void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const Q_DECL_OVERRIDE;
@@ -68,14 +68,14 @@ public:
QRect itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const Q_DECL_OVERRIDE;
QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const Q_DECL_OVERRIDE;
- SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const Q_DECL_OVERRIDE;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ int styleHint(StyleHint hint, const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR, QStyleHintReturn *returnData = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ int pixelMetric(PixelMetric metric, const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option = 0, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ Qt::Orientation orientation, const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget = 0) const Q_DECL_OVERRIDE;
+ QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
+ QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget = Q_NULLPTR) const Q_DECL_OVERRIDE;
QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const Q_DECL_OVERRIDE;
QPalette standardPalette() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index b41762795d..1e9d15c993 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -192,7 +192,7 @@ public:
Q_ENUM(PrimitiveElement)
virtual void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const = 0;
+ const QWidget *w = Q_NULLPTR) const = 0;
enum ControlElement {
CE_PushButton,
CE_PushButtonBevel,
@@ -263,7 +263,7 @@ public:
Q_ENUM(ControlElement)
virtual void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const = 0;
+ const QWidget *w = Q_NULLPTR) const = 0;
enum SubElement {
SE_PushButtonContents,
@@ -347,7 +347,7 @@ public:
Q_ENUM(SubElement)
virtual QRect subElementRect(SubElement subElement, const QStyleOption *option,
- const QWidget *widget = 0) const = 0;
+ const QWidget *widget = Q_NULLPTR) const = 0;
enum ComplexControl {
@@ -426,11 +426,11 @@ public:
virtual void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *widget = 0) const = 0;
+ const QWidget *widget = Q_NULLPTR) const = 0;
virtual SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *widget = 0) const = 0;
+ const QPoint &pt, const QWidget *widget = Q_NULLPTR) const = 0;
virtual QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget = 0) const = 0;
+ SubControl sc, const QWidget *widget = Q_NULLPTR) const = 0;
enum PixelMetric {
PM_ButtonMargin,
@@ -561,8 +561,8 @@ public:
};
Q_ENUM(PixelMetric)
- virtual int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
- const QWidget *widget = 0) const = 0;
+ virtual int pixelMetric(PixelMetric metric, const QStyleOption *option = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const = 0;
enum ContentsType {
CT_PushButton,
@@ -594,7 +594,7 @@ public:
Q_ENUM(ContentsType)
virtual QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *w = 0) const = 0;
+ const QSize &contentsSize, const QWidget *w = Q_NULLPTR) const = 0;
enum RequestSoftwareInputPanel {
RSIP_OnMouseClickAndAlreadyFocused,
@@ -724,8 +724,8 @@ public:
};
Q_ENUM(StyleHint)
- virtual int styleHint(StyleHint stylehint, const QStyleOption *opt = 0,
- const QWidget *widget = 0, QStyleHintReturn* returnData = 0) const = 0;
+ virtual int styleHint(StyleHint stylehint, const QStyleOption *opt = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR, QStyleHintReturn* returnData = Q_NULLPTR) const = 0;
enum StandardPixmap {
SP_TitleBarMenuButton,
@@ -804,11 +804,11 @@ public:
};
Q_ENUM(StandardPixmap)
- virtual QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const = 0;
+ virtual QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const = 0;
- virtual QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0,
- const QWidget *widget = 0) const = 0;
+ virtual QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = Q_NULLPTR,
+ const QWidget *widget = Q_NULLPTR) const = 0;
virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
const QStyleOption *opt) const = 0;
@@ -827,10 +827,10 @@ public:
virtual int layoutSpacing(QSizePolicy::ControlType control1,
QSizePolicy::ControlType control2, Qt::Orientation orientation,
- const QStyleOption *option = 0, const QWidget *widget = 0) const = 0;
+ const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const = 0;
int combinedLayoutSpacing(QSizePolicy::ControlTypes controls1,
QSizePolicy::ControlTypes controls2, Qt::Orientation orientation,
- QStyleOption *option = 0, QWidget *widget = 0) const;
+ QStyleOption *option = Q_NULLPTR, QWidget *widget = Q_NULLPTR) const;
const QStyle * proxy() const;
diff --git a/src/widgets/styles/qstylepainter.h b/src/widgets/styles/qstylepainter.h
index 33d17d42b9..8492d231ae 100644
--- a/src/widgets/styles/qstylepainter.h
+++ b/src/widgets/styles/qstylepainter.h
@@ -44,7 +44,7 @@ QT_BEGIN_NAMESPACE
class QStylePainter : public QPainter
{
public:
- inline QStylePainter() : QPainter(), widget(0), wstyle(0) {}
+ inline QStylePainter() : QPainter(), widget(Q_NULLPTR), wstyle(Q_NULLPTR) {}
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); }
diff --git a/src/widgets/styles/qstyleplugin.h b/src/widgets/styles/qstyleplugin.h
index b83774a39d..c8f6344758 100644
--- a/src/widgets/styles/qstyleplugin.h
+++ b/src/widgets/styles/qstyleplugin.h
@@ -48,7 +48,7 @@ class Q_WIDGETS_EXPORT QStylePlugin : public QObject
{
Q_OBJECT
public:
- explicit QStylePlugin(QObject *parent = 0);
+ explicit QStylePlugin(QObject *parent = Q_NULLPTR);
~QStylePlugin();
virtual QStyle *create(const QString &key) = 0;
diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp
index ce10b92d85..380b2b3939 100644
--- a/src/widgets/styles/qstylesheetstyle.cpp
+++ b/src/widgets/styles/qstylesheetstyle.cpp
@@ -460,7 +460,6 @@ 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 QObject *);
- ~QRenderRule() { }
QRect borderRect(const QRect &r) const;
QRect outlineRect(const QRect &r) const;
@@ -558,16 +557,22 @@ public:
return csz;
}
+ bool hasStyleHint(const QString &sh) const { return styleHints.contains(sh); }
+ QVariant styleHint(const QString &sh) const { return styleHints.value(sh); }
+
+ void fixupBorder(int);
+
+ // Shouldn't be here
+ void setClip(QPainter *p, const QRect &rect);
+ void unsetClip(QPainter *);
+
+public:
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;
@@ -578,12 +583,10 @@ public:
QSharedDataPointer<QStyleSheetPositionData> p;
QSharedDataPointer<QStyleSheetImageData> img;
- // Shouldn't be here
- void setClip(QPainter *p, const QRect &rect);
- void unsetClip(QPainter *);
int clipset;
QPainterPath clipPath;
};
+Q_DECLARE_TYPEINFO(QRenderRule, Q_MOVABLE_TYPE);
///////////////////////////////////////////////////////////////////////////////////////////
static const char *const knownStyleHints[] = {
@@ -728,6 +731,7 @@ namespace {
int width;
};
}
+template <> class QTypeInfo<ButtonInfo> : public QTypeInfoMerger<ButtonInfo, QRenderRule, int> {};
QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const
{
@@ -742,16 +746,19 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
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 == '(') {
+ QVector<ButtonInfo> infos;
+ const int numLayouts = layout.size();
+ infos.reserve(numLayouts);
+ for (int i = 0; i < numLayouts; i++) {
+ const int element = layout[i].toInt();
+ if (element == '(') {
where = Center;
- } else if (info.element == ')') {
+ } else if (element == ')') {
where = Right;
} else {
- switch (info.element) {
+ ButtonInfo info;
+ info.element = element;
+ switch (element) {
case PseudoElement_TitleBar:
if (!(tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)))
continue;
@@ -796,14 +803,14 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
info.rule = subRule;
info.offset = offsets[where];
info.where = where;
- infos.append(info);
+ infos.append(qMove(info));
offsets[where] += info.width;
}
}
- for (int i = 0; i < infos.count(); i++) {
- ButtonInfo info = infos[i];
+ for (int i = 0; i < infos.size(); i++) {
+ const ButtonInfo &info = infos[i];
QRect lr = cr;
switch (info.where) {
case Center: {
@@ -2393,6 +2400,13 @@ static bool unstylable(const QWidget *w)
return true;
}
#endif
+
+#ifndef QT_NO_TABBAR
+ if (w->metaObject() == &QWidget::staticMetaObject
+ && qobject_cast<const QTabBar*>(w->parentWidget()))
+ return true; // The moving tab of a QTabBar
+#endif
+
return false;
}
diff --git a/src/widgets/styles/qwindowsstyle.cpp b/src/widgets/styles/qwindowsstyle.cpp
index 14af5ede39..db8a649931 100644
--- a/src/widgets/styles/qwindowsstyle.cpp
+++ b/src/widgets/styles/qwindowsstyle.cpp
@@ -1796,7 +1796,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
QColor left, right;
//Titlebar gradient
- if (widget && widget->isWindow()) {
+ if (opt->state & QStyle::State_Window) {
floating = true;
if (active) {
left = d->activeCaptionColor;
diff --git a/src/widgets/styles/qwindowsstyle_p_p.h b/src/widgets/styles/qwindowsstyle_p_p.h
index f1a4a390e1..c8778cc914 100644
--- a/src/widgets/styles/qwindowsstyle_p_p.h
+++ b/src/widgets/styles/qwindowsstyle_p_p.h
@@ -50,7 +50,6 @@
#ifndef QT_NO_STYLE_WINDOWS
#include <qlist.h>
-#include <qhash.h>
QT_BEGIN_NAMESPACE
@@ -66,7 +65,7 @@ public:
static int pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *option = 0, const QWidget *widget = 0);
static int fixedPixelMetric(QStyle::PixelMetric pm);
static int devicePixelRatio(const QWidget *widget = 0)
- { return widget ? widget->devicePixelRatio() : QWindowsStylePrivate::appDevicePixelRatio(); }
+ { return widget ? int(widget->devicePixelRatioF()) : QWindowsStylePrivate::appDevicePixelRatio(); }
bool hasSeenAlt(const QWidget *widget) const;
bool altDown() const { return alt_down; }
diff --git a/src/widgets/util/qcompleter.h b/src/widgets/util/qcompleter.h
index 22230fc39e..32ee6296ca 100644
--- a/src/widgets/util/qcompleter.h
+++ b/src/widgets/util/qcompleter.h
@@ -76,10 +76,10 @@ public:
CaseInsensitivelySortedModel
};
- QCompleter(QObject *parent = 0);
- QCompleter(QAbstractItemModel *model, QObject *parent = 0);
+ QCompleter(QObject *parent = Q_NULLPTR);
+ QCompleter(QAbstractItemModel *model, QObject *parent = Q_NULLPTR);
#ifndef QT_NO_STRINGLISTMODEL
- QCompleter(const QStringList& completions, QObject *parent = 0);
+ QCompleter(const QStringList& completions, QObject *parent = Q_NULLPTR);
#endif
~QCompleter();
diff --git a/src/widgets/util/qflickgesture.cpp b/src/widgets/util/qflickgesture.cpp
index 0e598717c8..8eadc42625 100644
--- a/src/widgets/util/qflickgesture.cpp
+++ b/src/widgets/util/qflickgesture.cpp
@@ -66,8 +66,8 @@ static QMouseEvent *copyMouseEvent(QEvent *e)
case QEvent::MouseButtonRelease:
case QEvent::MouseMove: {
QMouseEvent *me = static_cast<QMouseEvent *>(e);
- QMouseEvent *cme = new QMouseEvent(me->type(), QPoint(0, 0), me->windowPos(), me->screenPos(), me->button(), me->buttons(), me->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(cme, me->source());
+ QMouseEvent *cme = new QMouseEvent(me->type(), QPoint(0, 0), me->windowPos(), me->screenPos(),
+ me->button(), me->buttons(), me->modifiers(), me->source());
return cme;
}
#ifndef QT_NO_GRAPHICSVIEW
@@ -78,8 +78,8 @@ static QMouseEvent *copyMouseEvent(QEvent *e)
#if 1
QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress :
(me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove);
- QMouseEvent *cme = new QMouseEvent(met, QPoint(0, 0), QPoint(0, 0), me->screenPos(), me->button(), me->buttons(), me->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(cme, me->source());
+ QMouseEvent *cme = new QMouseEvent(met, QPoint(0, 0), QPoint(0, 0), me->screenPos(),
+ me->button(), me->buttons(), me->modifiers(), me->source());
return cme;
#else
QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type());
@@ -240,8 +240,7 @@ public:
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, farFarAway,
mouseButton, QApplication::mouseButtons() & ~mouseButton,
- QApplication::keyboardModifiers());
- QGuiApplicationPrivate::setMouseEventSource(&re, mouseEventSource);
+ QApplication::keyboardModifiers(), mouseEventSource);
sendMouseEvent(&re, RegrabMouseAfterwards);
// don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release!
}
@@ -291,8 +290,7 @@ protected:
if (me) {
QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPos()),
mouseTarget->topLevelWidget()->mapFromGlobal(me->globalPos()), me->screenPos(),
- me->button(), me->buttons(), me->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&copy, me->source());
+ me->button(), me->buttons(), me->modifiers(), me->source());
qt_sendSpontaneousEvent(mouseTarget, &copy);
}
diff --git a/src/widgets/util/qscroller_mac.mm b/src/widgets/util/qscroller_mac.mm
index 9120c43075..07de07de52 100644
--- a/src/widgets/util/qscroller_mac.mm
+++ b/src/widgets/util/qscroller_mac.mm
@@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE
QPointF QScrollerPrivate::realDpi(int screen)
{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
NSArray *nsscreens = [NSScreen screens];
if (screen < 0 || screen >= int([nsscreens count]))
@@ -59,7 +59,6 @@ QPointF QScrollerPrivate::realDpi(int screen)
} else {
return QPointF();
}
- [pool release];
}
QT_END_NAMESPACE
diff --git a/src/widgets/util/qscroller_p.h b/src/widgets/util/qscroller_p.h
index bb00c12905..d09f78d130 100644
--- a/src/widgets/util/qscroller_p.h
+++ b/src/widgets/util/qscroller_p.h
@@ -196,6 +196,9 @@ public:
QScroller *q_ptr;
};
+template <>
+class QTypeInfo<QScrollerPrivate::ScrollSegment>
+ : public QTypeInfoMerger<QScrollerPrivate::ScrollSegment, QEasingCurve> {};
QT_END_NAMESPACE
diff --git a/src/widgets/util/qsystemtrayicon.h b/src/widgets/util/qsystemtrayicon.h
index a4da0861e9..aba126b4fc 100644
--- a/src/widgets/util/qsystemtrayicon.h
+++ b/src/widgets/util/qsystemtrayicon.h
@@ -59,8 +59,8 @@ class Q_WIDGETS_EXPORT QSystemTrayIcon : public QObject
Q_PROPERTY(bool visible READ isVisible WRITE setVisible DESIGNABLE false)
public:
- QSystemTrayIcon(QObject *parent = 0);
- QSystemTrayIcon(const QIcon &icon, QObject *parent = 0);
+ QSystemTrayIcon(QObject *parent = Q_NULLPTR);
+ QSystemTrayIcon(const QIcon &icon, QObject *parent = Q_NULLPTR);
~QSystemTrayIcon();
enum ActivationReason {
diff --git a/src/widgets/util/qsystemtrayicon_x11.cpp b/src/widgets/util/qsystemtrayicon_x11.cpp
index 4060655d45..9a69db1bc8 100644
--- a/src/widgets/util/qsystemtrayicon_x11.cpp
+++ b/src/widgets/util/qsystemtrayicon_x11.cpp
@@ -52,6 +52,8 @@
#include <private/qguiapplication_p.h>
#include <qdebug.h>
+#include <QtPlatformHeaders/qxcbwindowfunctions.h>
+#include <QtPlatformHeaders/qxcbintegrationfunctions.h>
#ifndef QT_NO_SYSTEMTRAYICON
QT_BEGIN_NAMESPACE
@@ -112,17 +114,11 @@ QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *qIn)
// window to ParentRelative (so that it inherits the background of its X11 parent window), call
// xcb_clear_region before painting (so that the inherited background is visible) and then grab
// the just-drawn background from the X11 server.
- bool hasAlphaChannel = false;
- QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
- "systrayVisualHasAlphaChannel", Qt::DirectConnection,
- Q_RETURN_ARG(bool, hasAlphaChannel));
+ bool hasAlphaChannel = QXcbIntegrationFunctions::xEmbedSystemTrayVisualHasAlphaChannel();
setAttribute(Qt::WA_TranslucentBackground, hasAlphaChannel);
if (!hasAlphaChannel) {
createWinId();
- QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
- "setParentRelativeBackPixmap", Qt::DirectConnection,
- Q_ARG(const QWindow *, windowHandle())
- );
+ QXcbWindowFunctions::setParentRelativeBackPixmap(windowHandle());
// XXX: This is actually required, but breaks things ("QWidget::paintEngine: Should no
// longer be called"). Why is this needed? When the widget is drawn, we use tricks to grab
@@ -143,15 +139,9 @@ bool QSystemTrayIconSys::addToTray()
createWinId();
setMouseTracking(true);
- bool requestResult = false;
- if (!QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
- "requestSystemTrayWindowDock", Qt::DirectConnection,
- Q_RETURN_ARG(bool, requestResult),
- Q_ARG(const QWindow *, windowHandle()))
- || !requestResult) {
- qWarning("requestSystemTrayWindowDock failed.");
+ if (!QXcbWindowFunctions::requestSystemTrayWindowDock(windowHandle()))
return false;
- }
+
if (!background.isNull())
background = QPixmap();
show();
@@ -171,15 +161,7 @@ void QSystemTrayIconSys::systemTrayWindowChanged(QScreen *)
QRect QSystemTrayIconSys::globalGeometry() const
{
- QRect result;
- if (!QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
- "systemTrayWindowGlobalGeometry", Qt::DirectConnection,
- Q_RETURN_ARG(QRect, result),
- Q_ARG(const QWindow *, windowHandle()))
- || !result.isValid()) {
- qWarning("systemTrayWindowGlobalGeometry failed.");
- }
- return result;
+ return QXcbWindowFunctions::systemTrayWindowGlobalGeometry(windowHandle());
}
void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev)
diff --git a/src/widgets/util/qundogroup.h b/src/widgets/util/qundogroup.h
index ea4b226a18..ec6e67f4d3 100644
--- a/src/widgets/util/qundogroup.h
+++ b/src/widgets/util/qundogroup.h
@@ -52,7 +52,7 @@ class Q_WIDGETS_EXPORT QUndoGroup : public QObject
Q_DECLARE_PRIVATE(QUndoGroup)
public:
- explicit QUndoGroup(QObject *parent = 0);
+ explicit QUndoGroup(QObject *parent = Q_NULLPTR);
~QUndoGroup();
void addStack(QUndoStack *stack);
diff --git a/src/widgets/util/qundostack.h b/src/widgets/util/qundostack.h
index f6589da4ec..0b14a442c2 100644
--- a/src/widgets/util/qundostack.h
+++ b/src/widgets/util/qundostack.h
@@ -51,8 +51,8 @@ class Q_WIDGETS_EXPORT QUndoCommand
QUndoCommandPrivate *d;
public:
- explicit QUndoCommand(QUndoCommand *parent = 0);
- explicit QUndoCommand(const QString &text, QUndoCommand *parent = 0);
+ explicit QUndoCommand(QUndoCommand *parent = Q_NULLPTR);
+ explicit QUndoCommand(const QString &text, QUndoCommand *parent = Q_NULLPTR);
virtual ~QUndoCommand();
virtual void undo();
@@ -85,7 +85,7 @@ class Q_WIDGETS_EXPORT QUndoStack : public QObject
Q_PROPERTY(int undoLimit READ undoLimit WRITE setUndoLimit)
public:
- explicit QUndoStack(QObject *parent = 0);
+ explicit QUndoStack(QObject *parent = Q_NULLPTR);
~QUndoStack();
void clear();
diff --git a/src/widgets/util/qundoview.h b/src/widgets/util/qundoview.h
index a239d9b38e..2a15207ca5 100644
--- a/src/widgets/util/qundoview.h
+++ b/src/widgets/util/qundoview.h
@@ -55,10 +55,10 @@ class Q_WIDGETS_EXPORT QUndoView : public QListView
Q_PROPERTY(QIcon cleanIcon READ cleanIcon WRITE setCleanIcon)
public:
- explicit QUndoView(QWidget *parent = 0);
- explicit QUndoView(QUndoStack *stack, QWidget *parent = 0);
+ explicit QUndoView(QWidget *parent = Q_NULLPTR);
+ explicit QUndoView(QUndoStack *stack, QWidget *parent = Q_NULLPTR);
#ifndef QT_NO_UNDOGROUP
- explicit QUndoView(QUndoGroup *group, QWidget *parent = 0);
+ explicit QUndoView(QUndoGroup *group, QWidget *parent = Q_NULLPTR);
#endif
~QUndoView();
diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp
index e413b3b87a..292bbc3325 100644
--- a/src/widgets/widgets/qabstractbutton.cpp
+++ b/src/widgets/widgets/qabstractbutton.cpp
@@ -221,13 +221,12 @@ void QButtonGroup::addButton(QAbstractButton *button, int id)
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 {
- std::sort(ids.begin(), ids.end());
- d->mapping[button] = ids.first()-1;
- }
+ const QHash<QAbstractButton*, int>::const_iterator it
+ = std::min_element(d->mapping.cbegin(), d->mapping.cend());
+ if (it == d->mapping.cend())
+ d->mapping[button] = -2;
+ else
+ d->mapping[button] = *it - 1;
} else {
d->mapping[button] = id;
}
diff --git a/src/widgets/widgets/qabstractbutton.h b/src/widgets/widgets/qabstractbutton.h
index 4b397e2396..5f3e82a2e6 100644
--- a/src/widgets/widgets/qabstractbutton.h
+++ b/src/widgets/widgets/qabstractbutton.h
@@ -63,7 +63,7 @@ class Q_WIDGETS_EXPORT QAbstractButton : public QWidget
Q_PROPERTY(bool down READ isDown WRITE setDown DESIGNABLE false)
public:
- explicit QAbstractButton(QWidget* parent=0);
+ explicit QAbstractButton(QWidget *parent = Q_NULLPTR);
~QAbstractButton();
void setText(const QString &text);
@@ -135,7 +135,7 @@ protected:
protected:
- QAbstractButton(QAbstractButtonPrivate &dd, QWidget* parent = 0);
+ QAbstractButton(QAbstractButtonPrivate &dd, QWidget* parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QAbstractButton)
diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp
index 2e1caedde7..65d06eafc5 100644
--- a/src/widgets/widgets/qabstractscrollarea.cpp
+++ b/src/widgets/widgets/qabstractscrollarea.cpp
@@ -168,6 +168,10 @@ QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate()
{
}
+QAbstractScrollAreaPrivate::~QAbstractScrollAreaPrivate()
+{
+}
+
QAbstractScrollAreaScrollBarContainer::QAbstractScrollAreaScrollBarContainer(Qt::Orientation orientation, QWidget *parent)
:QWidget(parent), scrollBar(new QScrollBar(orientation, this)),
layout(new QBoxLayout(orientation == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom)),
@@ -206,10 +210,12 @@ QWidgetList QAbstractScrollAreaScrollBarContainer::widgets(LogicalPosition posit
QWidgetList list;
const int scrollBarIndex = scrollBarLayoutIndex();
if (position == LogicalLeft) {
+ list.reserve(scrollBarIndex);
for (int i = 0; i < scrollBarIndex; ++i)
list.append(layout->itemAt(i)->widget());
} else if (position == LogicalRight) {
const int layoutItemCount = layout->count();
+ list.reserve(layoutItemCount - (scrollBarIndex + 1));
for (int i = scrollBarIndex + 1; i < layoutItemCount; ++i)
list.append(layout->itemAt(i)->widget());
}
diff --git a/src/widgets/widgets/qabstractscrollarea.h b/src/widgets/widgets/qabstractscrollarea.h
index 13dafd547b..8bc32b1c78 100644
--- a/src/widgets/widgets/qabstractscrollarea.h
+++ b/src/widgets/widgets/qabstractscrollarea.h
@@ -54,7 +54,7 @@ class Q_WIDGETS_EXPORT QAbstractScrollArea : public QFrame
Q_PROPERTY(SizeAdjustPolicy sizeAdjustPolicy READ sizeAdjustPolicy WRITE setSizeAdjustPolicy)
public:
- explicit QAbstractScrollArea(QWidget* parent=0);
+ explicit QAbstractScrollArea(QWidget *parent = Q_NULLPTR);
~QAbstractScrollArea();
enum SizeAdjustPolicy {
@@ -94,7 +94,7 @@ public:
void setSizeAdjustPolicy(SizeAdjustPolicy policy);
protected:
- QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent = 0);
+ QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent = Q_NULLPTR);
void setViewportMargins(int left, int top, int right, int bottom);
void setViewportMargins(const QMargins &margins);
QMargins viewportMargins() const;
diff --git a/src/widgets/widgets/qabstractscrollarea_p.h b/src/widgets/widgets/qabstractscrollarea_p.h
index f770bb69f8..33222573f4 100644
--- a/src/widgets/widgets/qabstractscrollarea_p.h
+++ b/src/widgets/widgets/qabstractscrollarea_p.h
@@ -54,12 +54,15 @@ QT_BEGIN_NAMESPACE
class QScrollBar;
class QAbstractScrollAreaScrollBarContainer;
+
+// ### Qt 6: is the export still needed? If not, unexport QFramePrivate, too.
class Q_WIDGETS_EXPORT QAbstractScrollAreaPrivate: public QFramePrivate
{
Q_DECLARE_PUBLIC(QAbstractScrollArea)
public:
QAbstractScrollAreaPrivate();
+ ~QAbstractScrollAreaPrivate();
void replaceScrollBar(QScrollBar *scrollBar, Qt::Orientation orientation);
diff --git a/src/widgets/widgets/qabstractslider.h b/src/widgets/widgets/qabstractslider.h
index 2f649e3d3d..6faca5ea3c 100644
--- a/src/widgets/widgets/qabstractslider.h
+++ b/src/widgets/widgets/qabstractslider.h
@@ -58,7 +58,7 @@ class Q_WIDGETS_EXPORT QAbstractSlider : public QWidget
Q_PROPERTY(bool sliderDown READ isSliderDown WRITE setSliderDown DESIGNABLE false)
public:
- explicit QAbstractSlider(QWidget *parent=0);
+ explicit QAbstractSlider(QWidget *parent = Q_NULLPTR);
~QAbstractSlider();
Qt::Orientation orientation() const;
@@ -144,7 +144,7 @@ protected:
protected:
- QAbstractSlider(QAbstractSliderPrivate &dd, QWidget *parent=0);
+ QAbstractSlider(QAbstractSliderPrivate &dd, QWidget *parent = Q_NULLPTR);
private:
Q_DISABLE_COPY(QAbstractSlider)
diff --git a/src/widgets/widgets/qabstractspinbox.h b/src/widgets/widgets/qabstractspinbox.h
index a80a89c894..046036b9a8 100644
--- a/src/widgets/widgets/qabstractspinbox.h
+++ b/src/widgets/widgets/qabstractspinbox.h
@@ -64,7 +64,7 @@ class Q_WIDGETS_EXPORT QAbstractSpinBox : public QWidget
Q_PROPERTY(bool keyboardTracking READ keyboardTracking WRITE setKeyboardTracking)
Q_PROPERTY(bool showGroupSeparator READ isGroupSeparatorShown WRITE setGroupSeparatorShown)
public:
- explicit QAbstractSpinBox(QWidget *parent = 0);
+ explicit QAbstractSpinBox(QWidget *parent = Q_NULLPTR);
~QAbstractSpinBox();
enum StepEnabledFlag { StepNone = 0x00, StepUpEnabled = 0x01,
@@ -154,7 +154,7 @@ protected:
Q_SIGNALS:
void editingFinished();
protected:
- QAbstractSpinBox(QAbstractSpinBoxPrivate &dd, QWidget *parent = 0);
+ QAbstractSpinBox(QAbstractSpinBoxPrivate &dd, QWidget *parent = Q_NULLPTR);
private:
Q_PRIVATE_SLOT(d_func(), void _q_editorTextChanged(const QString &))
diff --git a/src/widgets/widgets/qbuttongroup.h b/src/widgets/widgets/qbuttongroup.h
index 01de03ac84..ba4f8e26c1 100644
--- a/src/widgets/widgets/qbuttongroup.h
+++ b/src/widgets/widgets/qbuttongroup.h
@@ -51,7 +51,7 @@ class Q_WIDGETS_EXPORT QButtonGroup : public QObject
Q_PROPERTY(bool exclusive READ exclusive WRITE setExclusive)
public:
- explicit QButtonGroup(QObject *parent = 0);
+ explicit QButtonGroup(QObject *parent = Q_NULLPTR);
~QButtonGroup();
void setExclusive(bool);
diff --git a/src/widgets/widgets/qcalendarwidget.h b/src/widgets/widgets/qcalendarwidget.h
index c456cc2161..df54985351 100644
--- a/src/widgets/widgets/qcalendarwidget.h
+++ b/src/widgets/widgets/qcalendarwidget.h
@@ -83,7 +83,7 @@ public:
};
Q_ENUM(SelectionMode)
- explicit QCalendarWidget(QWidget *parent = 0);
+ explicit QCalendarWidget(QWidget *parent = Q_NULLPTR);
~QCalendarWidget();
virtual QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qcheckbox.h b/src/widgets/widgets/qcheckbox.h
index b614659f02..61d03eb8e6 100644
--- a/src/widgets/widgets/qcheckbox.h
+++ b/src/widgets/widgets/qcheckbox.h
@@ -49,8 +49,8 @@ class Q_WIDGETS_EXPORT QCheckBox : public QAbstractButton
Q_PROPERTY(bool tristate READ isTristate WRITE setTristate)
public:
- explicit QCheckBox(QWidget *parent=0);
- explicit QCheckBox(const QString &text, QWidget *parent=0);
+ explicit QCheckBox(QWidget *parent = Q_NULLPTR);
+ explicit QCheckBox(const QString &text, QWidget *parent = Q_NULLPTR);
~QCheckBox();
QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index 4840b75c1b..af2a66a838 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -546,7 +546,8 @@ void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
disconnect(view, SIGNAL(destroyed()),
this, SLOT(viewDestroyed()));
- delete view;
+ if (isAncestorOf(view))
+ delete view;
view = 0;
}
@@ -2268,6 +2269,7 @@ void QComboBox::insertItems(int index, const QStringList &list)
// construct a QStandardItem, reducing the number of expensive signals from the model
if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(d->model)) {
QList<QStandardItem *> items;
+ items.reserve(insertCount);
QStandardItem *hiddenRoot = m->invisibleRootItem();
for (int i = 0; i < insertCount; ++i)
items.append(new QStandardItem(list.at(i)));
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index ae35f7a89a..3182a0a3aa 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -74,7 +74,7 @@ class Q_WIDGETS_EXPORT QComboBox : public QWidget
Q_PROPERTY(int modelColumn READ modelColumn WRITE setModelColumn)
public:
- explicit QComboBox(QWidget *parent = 0);
+ explicit QComboBox(QWidget *parent = Q_NULLPTR);
~QComboBox();
int maxVisibleItems() const;
diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h
index 3fdfdcc22f..b69b94f3b9 100644
--- a/src/widgets/widgets/qcombobox_p.h
+++ b/src/widgets/widgets/qcombobox_p.h
@@ -57,7 +57,6 @@
#include "QtGui/qpainter.h"
#include "QtWidgets/qstyle.h"
#include "QtWidgets/qstyleoption.h"
-#include "QtCore/qhash.h"
#include "QtCore/qpair.h"
#include "QtCore/qtimer.h"
#include "private/qwidget_p.h"
diff --git a/src/widgets/widgets/qcommandlinkbutton.h b/src/widgets/widgets/qcommandlinkbutton.h
index 486c48af5d..9ddb14270d 100644
--- a/src/widgets/widgets/qcommandlinkbutton.h
+++ b/src/widgets/widgets/qcommandlinkbutton.h
@@ -49,9 +49,9 @@ class Q_WIDGETS_EXPORT QCommandLinkButton: public QPushButton
Q_PROPERTY(bool flat READ isFlat WRITE setFlat DESIGNABLE false)
public:
- explicit QCommandLinkButton(QWidget *parent=0);
- explicit QCommandLinkButton(const QString &text, QWidget *parent=0);
- explicit QCommandLinkButton(const QString &text, const QString &description, QWidget *parent=0);
+ explicit QCommandLinkButton(QWidget *parent = Q_NULLPTR);
+ explicit QCommandLinkButton(const QString &text, QWidget *parent = Q_NULLPTR);
+ explicit QCommandLinkButton(const QString &text, const QString &description, QWidget *parent = Q_NULLPTR);
~QCommandLinkButton();
QString description() const;
diff --git a/src/widgets/widgets/qdatetimeedit.h b/src/widgets/widgets/qdatetimeedit.h
index 4e77713fd0..829ce205be 100644
--- a/src/widgets/widgets/qdatetimeedit.h
+++ b/src/widgets/widgets/qdatetimeedit.h
@@ -86,10 +86,10 @@ public:
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);
+ explicit QDateTimeEdit(QWidget *parent = Q_NULLPTR);
+ explicit QDateTimeEdit(const QDateTime &dt, QWidget *parent = Q_NULLPTR);
+ explicit QDateTimeEdit(const QDate &d, QWidget *parent = Q_NULLPTR);
+ explicit QDateTimeEdit(const QTime &t, QWidget *parent = Q_NULLPTR);
~QDateTimeEdit();
QDateTime dateTime() const;
@@ -185,7 +185,7 @@ protected:
virtual void paintEvent(QPaintEvent *event);
void initStyleOption(QStyleOptionSpinBox *option) const;
- QDateTimeEdit(const QVariant &val, QVariant::Type parserType, QWidget *parent = 0);
+ QDateTimeEdit(const QVariant &val, QVariant::Type parserType, QWidget *parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QDateTimeEdit)
Q_DISABLE_COPY(QDateTimeEdit)
@@ -198,8 +198,8 @@ class Q_WIDGETS_EXPORT QTimeEdit : public QDateTimeEdit
Q_OBJECT
Q_PROPERTY(QTime time READ time WRITE setTime NOTIFY userTimeChanged USER true)
public:
- explicit QTimeEdit(QWidget *parent = 0);
- explicit QTimeEdit(const QTime &time, QWidget *parent = 0);
+ explicit QTimeEdit(QWidget *parent = Q_NULLPTR);
+ explicit QTimeEdit(const QTime &time, QWidget *parent = Q_NULLPTR);
~QTimeEdit();
Q_SIGNALS:
@@ -211,8 +211,8 @@ class Q_WIDGETS_EXPORT QDateEdit : public QDateTimeEdit
Q_OBJECT
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY userDateChanged USER true)
public:
- explicit QDateEdit(QWidget *parent = 0);
- explicit QDateEdit(const QDate &date, QWidget *parent = 0);
+ explicit QDateEdit(QWidget *parent = Q_NULLPTR);
+ explicit QDateEdit(const QDate &date, QWidget *parent = Q_NULLPTR);
~QDateEdit();
Q_SIGNALS:
diff --git a/src/widgets/widgets/qdial.h b/src/widgets/widgets/qdial.h
index 7e01aefce3..cb69e02301 100644
--- a/src/widgets/widgets/qdial.h
+++ b/src/widgets/widgets/qdial.h
@@ -54,7 +54,7 @@ class Q_WIDGETS_EXPORT QDial: public QAbstractSlider
Q_PROPERTY(qreal notchTarget READ notchTarget WRITE setNotchTarget)
Q_PROPERTY(bool notchesVisible READ notchesVisible WRITE setNotchesVisible)
public:
- explicit QDial(QWidget *parent = 0);
+ explicit QDial(QWidget *parent = Q_NULLPTR);
~QDial();
diff --git a/src/widgets/widgets/qdialogbuttonbox.h b/src/widgets/widgets/qdialogbuttonbox.h
index 02960b5b79..83c1fd66fd 100644
--- a/src/widgets/widgets/qdialogbuttonbox.h
+++ b/src/widgets/widgets/qdialogbuttonbox.h
@@ -106,11 +106,11 @@ public:
GnomeLayout
};
- QDialogButtonBox(QWidget *parent = 0);
- QDialogButtonBox(Qt::Orientation orientation, QWidget *parent = 0);
- explicit QDialogButtonBox(StandardButtons buttons, QWidget *parent = 0);
+ QDialogButtonBox(QWidget *parent = Q_NULLPTR);
+ QDialogButtonBox(Qt::Orientation orientation, QWidget *parent = Q_NULLPTR);
+ explicit QDialogButtonBox(StandardButtons buttons, QWidget *parent = Q_NULLPTR);
QDialogButtonBox(StandardButtons buttons, Qt::Orientation orientation,
- QWidget *parent = 0);
+ QWidget *parent = Q_NULLPTR);
~QDialogButtonBox();
void setOrientation(Qt::Orientation orientation);
diff --git a/src/widgets/widgets/qdockarealayout.cpp b/src/widgets/widgets/qdockarealayout.cpp
index e71b9616fc..0a00086138 100644
--- a/src/widgets/widgets/qdockarealayout.cpp
+++ b/src/widgets/widgets/qdockarealayout.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -1017,7 +1018,7 @@ QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path)
index = -index - 1;
if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
+ QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != 0);
return item.subinfo->plug(path.mid(1));
}
@@ -1063,7 +1064,7 @@ QLayoutItem *QDockAreaLayoutInfo::unplug(const QList<int> &path)
const int index = path.first();
if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
+ QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != 0);
return item.subinfo->unplug(path.mid(1));
}
@@ -1854,20 +1855,6 @@ static Qt::DockWidgetArea toDockWidgetArea(QInternal::DockPosition pos)
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;
@@ -1958,11 +1945,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
#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));
+ r = QDockAreaLayout::constrainedRect(r, widget);
widget->move(r.topLeft());
widget->resize(r.size());
}
@@ -2075,6 +2058,36 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
#endif //QT_NO_TABBAR
#ifndef QT_NO_TABBAR
+/*! \internal
+ reparent all the widgets contained in this layout portion to the
+ specified parent. This is used to reparent dock widgets and tabbars
+ to the floating window or the main window
+ */
+void QDockAreaLayoutInfo::reparentWidgets(QWidget *parent)
+{
+ if (tabBar)
+ tabBar->setParent(parent);
+
+ for (int i = 0; i < item_list.count(); ++i) {
+ const QDockAreaLayoutItem &item = item_list.at(i);
+ if (item.flags & QDockAreaLayoutItem::GapItem)
+ continue;
+ if (item.skip())
+ continue;
+ if (item.subinfo)
+ item.subinfo->reparentWidgets(parent);
+ if (item.widgetItem) {
+ QWidget *w = item.widgetItem->widget();
+ if (w->parent() != parent) {
+ bool hidden = w->isHidden();
+ w->setParent(parent);
+ if (!hidden)
+ w->show();
+ }
+ }
+ }
+}
+
//returns whether the tabbar is visible or not
bool QDockAreaLayoutInfo::updateTabBar() const
{
@@ -2198,8 +2211,10 @@ QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const
QSet<QWidget*> QDockAreaLayoutInfo::usedSeparatorWidgets() const
{
QSet<QWidget*> result;
+ const int numSeparatorWidgets = separatorWidgets.count();
+ result.reserve(numSeparatorWidgets);
- for (int i = 0; i < separatorWidgets.count(); ++i)
+ for (int i = 0; i < numSeparatorWidgets; ++i)
result << separatorWidgets.at(i);
for (int i = 0; i < item_list.count(); ++i) {
@@ -2244,6 +2259,22 @@ QRect QDockAreaLayoutInfo::tabContentRect() const
return result;
}
+
+int QDockAreaLayoutInfo::tabIndexToListIndex(int tabIndex) const
+{
+ Q_ASSERT(tabbed && tabBar);
+ quintptr data = qvariant_cast<quintptr>(tabBar->tabData(tabIndex));
+ for (int i = 0; i < item_list.count(); ++i) {
+ if (tabId(item_list.at(i)) == data)
+ return i;
+ }
+ return -1;
+}
+
+void QDockAreaLayoutInfo::moveTab(int from, int to)
+{
+ item_list.move(tabIndexToListIndex(from), tabIndexToListIndex(to));
+}
#endif // QT_NO_TABBAR
/******************************************************************************
@@ -2965,6 +2996,33 @@ QSize QDockAreaLayout::minimumSize() const
return QSize(qMax(row1, row2, row3), qMax(col1, col2, col3));
}
+/*! \internal
+ Try to fit the given rectangle \a rect on the screen which contains
+ the window \a widget.
+ Used to compute the geometry of a dragged a dock widget that should
+ be shown with \a rect, but needs to be visible on the screen
+ */
+QRect QDockAreaLayout::constrainedRect(QRect rect, QWidget* widget)
+{
+ QRect desktop;
+ QDesktopWidget *desktopW = QApplication::desktop();
+ if (desktopW->isVirtualDesktop())
+ desktop = desktopW->screenGeometry(rect.topLeft());
+ else
+ desktop = desktopW->screenGeometry(widget);
+
+ 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 QDockAreaLayout::restoreDockWidget(QDockWidget *dockWidget)
{
QList<int> index = indexOfPlaceHolder(dockWidget->objectName());
@@ -2978,9 +3036,7 @@ bool QDockAreaLayout::restoreDockWidget(QDockWidget *dockWidget)
item.widgetItem = new QDockWidgetItem(dockWidget);
if (placeHolder->window) {
- const QRect screenGeometry =
- QApplication::desktop()->screenGeometry(placeHolder->topLevelRect.center());
- const QRect r = constrainedRect(placeHolder->topLevelRect, screenGeometry);
+ const QRect r = constrainedRect(placeHolder->topLevelRect, dockWidget);
dockWidget->d_func()->setWindowState(true, true, r);
}
dockWidget->setVisible(!placeHolder->hidden);
@@ -3045,6 +3101,53 @@ void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
remove(index);
}
+void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks,
+ const QList<int> &sizes, Qt::Orientation o)
+{
+ if (docks.count() != sizes.count()) {
+ qWarning("QMainWidget::resizeDocks: size of the lists are not the same");
+ return;
+ }
+ int count = docks.count();
+ fallbackToSizeHints = false;
+ for (int i = 0; i < count; ++i) {
+ QList<int> path = indexOf(docks[i]);
+ if (path.isEmpty()) {
+ qWarning("QMainWidget::resizeDocks: one QDockWidget is not part of the layout");
+ continue;
+ }
+ int size = sizes[i];
+ if (size <= 0) {
+ qWarning("QMainWidget::resizeDocks: all sizes need to be larger than 0");
+ size = 1;
+ }
+
+ while (path.size() > 1) {
+ QDockAreaLayoutInfo *info = this->info(path);
+ if (!info->tabbed && info->o == o) {
+ info->item_list[path.last()].size = size;
+ int totalSize = 0;
+ foreach (const QDockAreaLayoutItem &item, info->item_list) {
+ if (!item.skip()) {
+ if (totalSize != 0)
+ totalSize += sep;
+ totalSize += item.size == -1 ? pick(o, item.sizeHint()) : item.size;
+ }
+ }
+ size = totalSize;
+ }
+ path.removeLast();
+ }
+
+ const int dockNum = path.first();
+ Q_ASSERT(dockNum < QInternal::DockCount);
+ QRect &r = this->docks[dockNum].rect;
+ QSize s = r.size();
+ rpick(o, s) = size;
+ r.setSize(s);
+ }
+}
+
void QDockAreaLayout::splitDockWidget(QDockWidget *after,
QDockWidget *dockWidget,
Qt::Orientation orientation)
diff --git a/src/widgets/widgets/qdockarealayout_p.h b/src/widgets/widgets/qdockarealayout_p.h
index 7c67466c7b..5d352f0124 100644
--- a/src/widgets/widgets/qdockarealayout_p.h
+++ b/src/widgets/widgets/qdockarealayout_p.h
@@ -202,12 +202,16 @@ public:
QTabBar *tabBar;
int tabBarShape;
+ void reparentWidgets(QWidget *p);
bool updateTabBar() const;
void setTabBarShape(int shape);
QSize tabBarMinimumSize() const;
QSize tabBarSizeHint() const;
QSet<QTabBar*> usedTabBars() const;
+
+ int tabIndexToListIndex(int) const;
+ void moveTab(int from, int to);
#endif // QT_NO_TABBAR
};
@@ -229,7 +233,8 @@ public:
bool isValid() const;
- enum { DockWidgetStateMarker = 0xfd };
+ enum { DockWidgetStateMarker = 0xfd, FloatingDockWidgetTabMarker = 0xf9 };
+ static QRect constrainedRect(QRect rect, QWidget *widget);
void saveState(QDataStream &stream) const;
bool restoreState(QDataStream &stream, const QList<QDockWidget*> &widgets, bool testing = false);
@@ -263,6 +268,7 @@ public:
void splitDockWidget(QDockWidget *after, QDockWidget *dockWidget,
Qt::Orientation orientation);
void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
+ void resizeDocks(const QList<QDockWidget *> &docks, const QList<int> &sizes, Qt::Orientation o);
void apply(bool animate);
diff --git a/src/widgets/widgets/qdockwidget.cpp b/src/widgets/widgets/qdockwidget.cpp
index 21b0904cc0..8b0263fc0c 100644
--- a/src/widgets/widgets/qdockwidget.cpp
+++ b/src/widgets/widgets/qdockwidget.cpp
@@ -65,6 +65,18 @@ extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*); /
// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
+static inline QMainWindowLayout *qt_mainwindow_layout_from_dock(const QDockWidget *dock)
+{
+ const QWidget *p = dock->parentWidget();
+ while (p) {
+ const QMainWindow *window = qobject_cast<const QMainWindow*>(p);
+ if (window)
+ return qt_mainwindow_layout(window);
+ p = p->parentWidget();
+ }
+ return Q_NULLPTR;
+}
+
static inline bool hasFeature(const QDockWidgetPrivate *priv, QDockWidget::DockWidgetFeature feature)
{ return (priv->features & feature) == feature; }
@@ -194,25 +206,40 @@ QDockWidgetLayout::~QDockWidgetLayout()
qDeleteAll(item_list);
}
+/*! \internal
+ Returns true if the dock widget managed by this layout should have a native
+ window decoration or if Qt needs to draw it.
+ */
bool QDockWidgetLayout::nativeWindowDeco() const
{
- return nativeWindowDeco(parentWidget()->isWindow());
+ bool floating = parentWidget()->isWindow();
+ if (!floating && qobject_cast<QDockWidgetGroupWindow*>(parentWidget()->parentWidget()))
+ return wmSupportsNativeWindowDeco();
+ return nativeWindowDeco(floating);
}
-static bool isXcb()
+/*! \internal
+ Returns true if the window manager can draw natively the windows decoration
+ of a dock widget
+ */
+bool QDockWidgetLayout::wmSupportsNativeWindowDeco()
{
+#if defined(Q_OS_WINCE) || defined(Q_OS_ANDROID)
+ return false;
+#else
static const bool xcb = !QGuiApplication::platformName().compare(QLatin1String("xcb"), Qt::CaseInsensitive);
- return xcb;
+ return !xcb;
+#endif
}
+/*! \internal
+ Returns true if the dock widget managed by this layout should have a native
+ window decoration or if Qt needs to draw it. The \a floating parameter
+ overrides the floating current state of the dock widget.
+ */
bool QDockWidgetLayout::nativeWindowDeco(bool floating) const
{
-#if defined(Q_OS_WINCE) || defined(Q_OS_ANDROID)
- Q_UNUSED(floating)
- return false;
-#else
- return !isXcb() && (floating && item_list[QDockWidgetLayout::TitleBar] == 0);
-#endif
+ return wmSupportsNativeWindowDeco() && floating && item_list.at(QDockWidgetLayout::TitleBar) == 0;
}
@@ -587,6 +614,7 @@ void QDockWidgetPrivate::init()
#ifndef QT_NO_ACTION
toggleViewAction = new QAction(q);
toggleViewAction->setCheckable(true);
+ toggleViewAction->setMenuRole(QAction::NoRole);
fixedWindowTitle = qt_setWindowTitle_helperHelper(q->windowTitle(), q);
toggleViewAction->setText(fixedWindowTitle);
QObject::connect(toggleViewAction, SIGNAL(triggered(bool)),
@@ -611,7 +639,10 @@ void QDockWidget::initStyleOption(QStyleOptionDockWidget *option) const
return;
QDockWidgetLayout *dwlayout = qobject_cast<QDockWidgetLayout*>(layout());
- option->initFrom(this);
+ QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent());
+ // If we are in a floating tab, init from the parent because the attributes and the geometry
+ // of the title bar should be taken from the floating window.
+ option->initFrom(floatingTab && !isFloating() ? parentWidget() : this);
option->rect = dwlayout->titleArea();
option->title = d->fixedWindowTitle;
option->closable = hasFeature(this, QDockWidget::DockWidgetClosable);
@@ -681,14 +712,20 @@ void QDockWidgetPrivate::_q_toggleTopLevel()
q->setFloating(!q->isFloating());
}
+/*! \internal
+ Initialize the drag state structure and remember the position of the click.
+ This is called when the mouse is pressed, but the dock is not yet dragged out.
+
+ \a nca specify that the event comes from NonClientAreaMouseButtonPress
+ */
void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca)
{
+ Q_Q(QDockWidget);
+
if (state != 0)
return;
- QMainWindow *win = qobject_cast<QMainWindow*>(parent);
- Q_ASSERT(win != 0);
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
+ QMainWindowLayout *layout = qt_mainwindow_layout_from_dock(q);
Q_ASSERT(layout != 0);
if (layout->pluggingWidget != 0) // the main window is animating a docking operation
return;
@@ -702,23 +739,33 @@ void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca)
state->ctrlDrag = false;
}
-void QDockWidgetPrivate::startDrag()
+/*! \internal
+ Actually start the drag and detach the dockwidget.
+ The \a group parameter is true when we should potentially drag a group of
+ tabbed widgets, and false if the dock widget should always be dragged
+ alone.
+ */
+void QDockWidgetPrivate::startDrag(bool group)
{
Q_Q(QDockWidget);
if (state == 0 || state->dragging)
return;
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
+ QMainWindowLayout *layout = qt_mainwindow_layout_from_dock(q);
Q_ASSERT(layout != 0);
- state->widgetItem = layout->unplug(q);
+ state->widgetItem = layout->unplug(q, group);
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);
+ QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
+ if (floatingTab && !q->isFloating())
+ state->widgetItem = new QDockWidgetGroupWindowItem(floatingTab);
+ else
+ state->widgetItem = new QDockWidgetItem(q);
state->ownWidgetItem = true;
}
@@ -728,6 +775,11 @@ void QDockWidgetPrivate::startDrag()
state->dragging = true;
}
+/*! \internal
+ Ends the drag end drop operation of the QDockWidget.
+ The \a abort parameter specifies that it ends because of programmatic state
+ reset rather than mouse release event.
+ */
void QDockWidgetPrivate::endDrag(bool abort)
{
Q_Q(QDockWidget);
@@ -736,29 +788,31 @@ void QDockWidgetPrivate::endDrag(bool abort)
q->releaseMouse();
if (state->dragging) {
- QMainWindowLayout *mwLayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
+ QMainWindowLayout *mwLayout = qt_mainwindow_layout_from_dock(q);
Q_ASSERT(mwLayout != 0);
if (abort || !mwLayout->plug(state->widgetItem)) {
if (hasFeature(this, QDockWidget::DockWidgetFloatable)) {
+ // This QDockWidget will now stay in the floating state.
if (state->ownWidgetItem)
delete state->widgetItem;
mwLayout->restore();
- if (isXcb()) {
+ QDockWidgetLayout *dwLayout = qobject_cast<QDockWidgetLayout*>(layout);
+ if (!dwLayout->nativeWindowDeco()) {
// get rid of the X11BypassWindowManager window flag and activate the resizer
Qt::WindowFlags flags = q->windowFlags();
flags &= ~Qt::X11BypassWindowManagerHint;
q->setWindowFlags(flags);
- setResizerActive(true);
+ setResizerActive(q->isFloating());
q->show();
} else {
- QDockWidgetLayout *myLayout
- = qobject_cast<QDockWidgetLayout*>(layout);
- setResizerActive(myLayout->widgetForRole(QDockWidgetLayout::TitleBar) != 0);
+ setResizerActive(false);
}
undockedGeometry = q->geometry();
q->activateWindow();
} else {
+ // The tab was not plugged back in the QMainWindow but the QDockWidget cannot
+ // stay floating, revert to the previous state.
mwLayout->revert(state->widgetItem);
}
}
@@ -782,11 +836,7 @@ 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);
+ QMainWindowLayout *mainWinLayout = qt_mainwindow_layout_from_dock(q);
if (mainWinLayout == 0)
return false;
@@ -804,12 +854,14 @@ bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event)
if (!dwLayout->nativeWindowDeco()) {
QRect titleArea = dwLayout->titleArea();
+ QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
+
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 ||
+ (qobject_cast<QMainWindow*>(parent) == 0 && !floatingTab) ||
isAnimating() || state != 0) {
return false;
}
@@ -853,7 +905,7 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
QDockWidgetLayout *dwlayout
= qobject_cast<QDockWidgetLayout *>(layout);
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
+ QMainWindowLayout *mwlayout = qt_mainwindow_layout_from_dock(q);
if (!dwlayout->nativeWindowDeco()) {
if (!state->dragging
&& mwlayout->pluggingWidget == 0
@@ -871,7 +923,12 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
if (state->dragging && !state->nca) {
QPoint pos = event->globalPos() - state->pressPos;
- q->move(pos);
+
+ QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
+ if (floatingTab && !q->isFloating())
+ floatingTab->move(pos);
+ else
+ q->move(pos);
if (state && !state->ctrlDrag)
mwlayout->hover(state->widgetItem, event->globalPos());
@@ -902,8 +959,9 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
int fw = q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q);
- QRect geo = q->geometry();
- QRect titleRect = q->frameGeometry();
+ QWidget *tl = q->topLevelWidget();
+ QRect geo = tl->geometry();
+ QRect titleRect = tl->frameGeometry();
#ifdef Q_DEAD_CODE_FROM_QT4_MAC
if ((features & QDockWidget::DockWidgetVerticalTitleBar)) {
titleRect.setTop(geo.top());
@@ -924,7 +982,7 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
break;
if (state != 0)
break;
- if (qobject_cast<QMainWindow*>(parent) == 0)
+ if (qobject_cast<QMainWindow*>(parent) == 0 && qobject_cast<QDockWidgetGroupWindow*>(parent) == 0)
break;
if (isAnimating())
break;
@@ -958,11 +1016,17 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
}
}
+/*! \internal
+ Called when the QDockWidget or the QDockWidgetGroupWindow is moved
+ */
void QDockWidgetPrivate::moveEvent(QMoveEvent *event)
{
Q_Q(QDockWidget);
- if (state == 0 || !state->dragging || !state->nca || !q->isWindow())
+ if (state == 0 || !state->dragging || !state->nca)
+ return;
+
+ if (!q->isWindow() && qobject_cast<QDockWidgetGroupWindow*>(parent) == 0)
return;
// When the native window frame is being dragged, all we get is these mouse
@@ -971,7 +1035,7 @@ void QDockWidgetPrivate::moveEvent(QMoveEvent *event)
if (state->ctrlDrag)
return;
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
+ QMainWindowLayout *layout = qt_mainwindow_layout_from_dock(q);
Q_ASSERT(layout != 0);
QPoint globalMousePos = event->pos() + state->pressPos;
@@ -999,8 +1063,9 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
Q_Q(QDockWidget);
if (!floating && parent) {
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- if (mwlayout && mwlayout->dockWidgetArea(q) == Qt::NoDockWidgetArea)
+ QMainWindowLayout *mwlayout = qt_mainwindow_layout_from_dock(q);
+ if (mwlayout && mwlayout->dockWidgetArea(q) == Qt::NoDockWidgetArea
+ && !qobject_cast<QDockWidgetGroupWindow *>(parent))
return; // this dockwidget can't be redocked
}
@@ -1048,7 +1113,7 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
if (floating != wasFloating) {
emit q->topLevelChanged(floating);
if (!floating && parent) {
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
+ QMainWindowLayout *mwlayout = qt_mainwindow_layout_from_dock(q);
if (mwlayout)
emit q->dockLocationChanged(mwlayout->dockWidgetArea(q));
}
@@ -1230,8 +1295,11 @@ void QDockWidget::setFeatures(QDockWidget::DockWidgetFeatures features)
emit featuresChanged(d->features);
update();
if (closableChanged && layout->nativeWindowDeco()) {
- //this ensures the native decoration is drawn
- d->setWindowState(true /*floating*/, true /*unplug*/);
+ QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow *>(parent());
+ if (floatingTab && !isFloating())
+ floatingTab->adjustFlags();
+ else
+ d->setWindowState(true /*floating*/, true /*unplug*/); //this ensures the native decoration is drawn
}
}
@@ -1323,11 +1391,12 @@ void QDockWidget::changeEvent(QEvent *event)
#endif
#ifndef QT_NO_TABBAR
{
- QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget());
- if (QMainWindowLayout *winLayout = qt_mainwindow_layout(win)) {
+ if (QMainWindowLayout *winLayout = qt_mainwindow_layout_from_dock(this)) {
if (QDockAreaLayoutInfo *info = winLayout->layoutState.dockAreaLayout.info(this))
info->updateTabBar();
}
+ if (QDockWidgetGroupWindow *p = qobject_cast<QDockWidgetGroupWindow *>(parent()))
+ p->adjustFlags();
}
#endif // QT_NO_TABBAR
break;
@@ -1380,7 +1449,7 @@ bool QDockWidget::event(QEvent *event)
Q_D(QDockWidget);
QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget());
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
+ QMainWindowLayout *layout = qt_mainwindow_layout_from_dock(this);
switch (event->type()) {
#ifndef QT_NO_ACTION
@@ -1417,6 +1486,9 @@ bool QDockWidget::event(QEvent *event)
}
if (!isFloating() && layout != 0 && onTop)
layout->raise(this);
+ if (QDockWidgetGroupWindow *p = qobject_cast<QDockWidgetGroupWindow *>(parent()))
+ p->adjustFlags();
+
break;
}
case QEvent::WindowActivate:
diff --git a/src/widgets/widgets/qdockwidget.h b/src/widgets/widgets/qdockwidget.h
index af4a5521bf..25e4d4d0a4 100644
--- a/src/widgets/widgets/qdockwidget.h
+++ b/src/widgets/widgets/qdockwidget.h
@@ -58,8 +58,9 @@ class Q_WIDGETS_EXPORT QDockWidget : public QWidget
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);
+ explicit QDockWidget(const QString &title, QWidget *parent = Q_NULLPTR,
+ Qt::WindowFlags flags = Qt::WindowFlags());
+ explicit QDockWidget(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QDockWidget();
QWidget *widget() const;
diff --git a/src/widgets/widgets/qdockwidget_p.h b/src/widgets/widgets/qdockwidget_p.h
index 752d6519e5..9c68bc5fb1 100644
--- a/src/widgets/widgets/qdockwidget_p.h
+++ b/src/widgets/widgets/qdockwidget_p.h
@@ -108,7 +108,7 @@ public:
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 startDrag(bool group = true);
void endDrag(bool abort = false);
void moveEvent(QMoveEvent *event);
@@ -151,6 +151,7 @@ public:
int minimumTitleWidth() const;
int titleHeight() const;
void updateMaxSize();
+ static bool wmSupportsNativeWindowDeco();
bool nativeWindowDeco() const;
bool nativeWindowDeco(bool floating) const;
diff --git a/src/widgets/widgets/qfocusframe.h b/src/widgets/widgets/qfocusframe.h
index f976ba9827..bbd639c2f9 100644
--- a/src/widgets/widgets/qfocusframe.h
+++ b/src/widgets/widgets/qfocusframe.h
@@ -46,7 +46,7 @@ class Q_WIDGETS_EXPORT QFocusFrame : public QWidget
{
Q_OBJECT
public:
- QFocusFrame(QWidget *parent=0);
+ QFocusFrame(QWidget *parent = Q_NULLPTR);
~QFocusFrame();
void setWidget(QWidget *widget);
diff --git a/src/widgets/widgets/qfontcombobox.cpp b/src/widgets/widgets/qfontcombobox.cpp
index faa2f41a51..957d148c74 100644
--- a/src/widgets/widgets/qfontcombobox.cpp
+++ b/src/widgets/widgets/qfontcombobox.cpp
@@ -401,14 +401,6 @@ void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
*/
/*!
- \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)
diff --git a/src/widgets/widgets/qfontcombobox.h b/src/widgets/widgets/qfontcombobox.h
index 0c8cf5d58d..412acd041e 100644
--- a/src/widgets/widgets/qfontcombobox.h
+++ b/src/widgets/widgets/qfontcombobox.h
@@ -53,7 +53,7 @@ class Q_WIDGETS_EXPORT QFontComboBox : public QComboBox
Q_PROPERTY(QFont currentFont READ currentFont WRITE setCurrentFont NOTIFY currentFontChanged)
public:
- explicit QFontComboBox(QWidget *parent = 0);
+ explicit QFontComboBox(QWidget *parent = Q_NULLPTR);
~QFontComboBox();
void setWritingSystem(QFontDatabase::WritingSystem);
diff --git a/src/widgets/widgets/qframe.cpp b/src/widgets/widgets/qframe.cpp
index 0861ea70b5..755b03a4ca 100644
--- a/src/widgets/widgets/qframe.cpp
+++ b/src/widgets/widgets/qframe.cpp
@@ -45,7 +45,7 @@
QT_BEGIN_NAMESPACE
QFramePrivate::QFramePrivate()
- : frect(QRect(0, 0, 0, 0)),
+ : frect(0, 0, 0, 0),
frameStyle(QFrame::NoFrame | QFrame::Plain),
lineWidth(1),
midLineWidth(0),
@@ -55,6 +55,10 @@ QFramePrivate::QFramePrivate()
{
}
+QFramePrivate::~QFramePrivate()
+{
+}
+
inline void QFramePrivate::init()
{
setLayoutItemMargins(QStyle::SE_FrameLayoutItem);
diff --git a/src/widgets/widgets/qframe.h b/src/widgets/widgets/qframe.h
index c32e38f311..eb4d74c72a 100644
--- a/src/widgets/widgets/qframe.h
+++ b/src/widgets/widgets/qframe.h
@@ -54,7 +54,7 @@ class Q_WIDGETS_EXPORT QFrame : public QWidget
Q_PROPERTY(QRect frameRect READ frameRect WRITE setFrameRect DESIGNABLE false)
public:
- explicit QFrame(QWidget* parent = 0, Qt::WindowFlags f = 0);
+ explicit QFrame(QWidget* parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
~QFrame();
int frameStyle() const;
@@ -108,7 +108,7 @@ protected:
protected:
- QFrame(QFramePrivate &dd, QWidget* parent = 0, Qt::WindowFlags f = 0);
+ QFrame(QFramePrivate &dd, QWidget* parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
void initStyleOption(QStyleOptionFrame *option) const;
private:
diff --git a/src/widgets/widgets/qframe_p.h b/src/widgets/widgets/qframe_p.h
index 2b80e9abbe..eb04bbed4a 100644
--- a/src/widgets/widgets/qframe_p.h
+++ b/src/widgets/widgets/qframe_p.h
@@ -50,11 +50,13 @@
QT_BEGIN_NAMESPACE
-class QFramePrivate : public QWidgetPrivate
+// ### unexport this class when and if QAbstractScrollAreaPrivate is unexported
+class Q_WIDGETS_EXPORT QFramePrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QFrame)
public:
QFramePrivate();
+ ~QFramePrivate();
void updateFrameWidth();
void updateStyledFrameWidths();
diff --git a/src/widgets/widgets/qgroupbox.h b/src/widgets/widgets/qgroupbox.h
index 8100fadff4..57ebdce8dd 100644
--- a/src/widgets/widgets/qgroupbox.h
+++ b/src/widgets/widgets/qgroupbox.h
@@ -53,8 +53,8 @@ class Q_WIDGETS_EXPORT QGroupBox : public QWidget
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);
+ explicit QGroupBox(QWidget *parent = Q_NULLPTR);
+ explicit QGroupBox(const QString &title, QWidget *parent = Q_NULLPTR);
~QGroupBox();
QString title() const;
diff --git a/src/widgets/widgets/qkeysequenceedit.h b/src/widgets/widgets/qkeysequenceedit.h
index 1887a40bfc..ad60bcc513 100644
--- a/src/widgets/widgets/qkeysequenceedit.h
+++ b/src/widgets/widgets/qkeysequenceedit.h
@@ -48,8 +48,8 @@ class Q_WIDGETS_EXPORT QKeySequenceEdit : public QWidget
Q_PROPERTY(QKeySequence keySequence READ keySequence WRITE setKeySequence NOTIFY keySequenceChanged USER true)
public:
- explicit QKeySequenceEdit(QWidget *parent = 0);
- explicit QKeySequenceEdit(const QKeySequence &keySequence, QWidget *parent = 0);
+ explicit QKeySequenceEdit(QWidget *parent = Q_NULLPTR);
+ explicit QKeySequenceEdit(const QKeySequence &keySequence, QWidget *parent = Q_NULLPTR);
~QKeySequenceEdit();
QKeySequence keySequence() const;
diff --git a/src/widgets/widgets/qlabel.cpp b/src/widgets/widgets/qlabel.cpp
index 83e94c4128..55e277026c 100644
--- a/src/widgets/widgets/qlabel.cpp
+++ b/src/widgets/widgets/qlabel.cpp
@@ -53,6 +53,54 @@
QT_BEGIN_NAMESPACE
+QLabelPrivate::QLabelPrivate()
+ : QFramePrivate(),
+ sh(),
+ msh(),
+ text(),
+ pixmap(Q_NULLPTR),
+ scaledpixmap(Q_NULLPTR),
+ cachedimage(Q_NULLPTR),
+#ifndef QT_NO_PICTURE
+ picture(Q_NULLPTR),
+#endif
+#ifndef QT_NO_MOVIE
+ movie(),
+#endif
+ control(Q_NULLPTR),
+ shortcutCursor(),
+#ifndef QT_NO_CURSOR
+ cursor(),
+#endif
+#ifndef QT_NO_SHORTCUT
+ buddy(),
+ shortcutId(0),
+#endif
+ textformat(Qt::AutoText),
+ textInteractionFlags(Qt::LinksAccessibleByMouse),
+ sizePolicy(),
+ margin(0),
+ align(Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs),
+ indent(-1),
+ valid_hints(false),
+ scaledcontents(false),
+ textLayoutDirty(false),
+ textDirty(false),
+ isRichText(false),
+ isTextLabel(false),
+ hasShortcut(/*???*/),
+#ifndef QT_NO_CURSOR
+ validCursor(false),
+ onAnchor(false),
+#endif
+ openExternalLinks(false)
+{
+}
+
+QLabelPrivate::~QLabelPrivate()
+{
+}
+
/*!
\class QLabel
\brief The QLabel widget provides a text or image display.
@@ -202,41 +250,8 @@ 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);
}
@@ -1081,7 +1096,7 @@ void QLabel::paintEvent(QPaintEvent *)
d->cachedimage = new QImage(d->pixmap->toImage());
delete d->scaledpixmap;
QImage scaledImage =
- d->cachedimage->scaled(cr.size() * devicePixelRatio(),
+ d->cachedimage->scaled(cr.size() * devicePixelRatioF(),
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
d->scaledpixmap = new QPixmap(QPixmap::fromImage(scaledImage));
}
diff --git a/src/widgets/widgets/qlabel.h b/src/widgets/widgets/qlabel.h
index 330626a9c5..1a3a68db60 100644
--- a/src/widgets/widgets/qlabel.h
+++ b/src/widgets/widgets/qlabel.h
@@ -58,8 +58,8 @@ class Q_WIDGETS_EXPORT QLabel : public QFrame
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);
+ explicit QLabel(QWidget *parent=Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags());
+ explicit QLabel(const QString &text, QWidget *parent=Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags());
~QLabel();
QString text() const;
diff --git a/src/widgets/widgets/qlabel_p.h b/src/widgets/widgets/qlabel_p.h
index 3778cb9d47..bd7a9d1e8f 100644
--- a/src/widgets/widgets/qlabel_p.h
+++ b/src/widgets/widgets/qlabel_p.h
@@ -64,50 +64,21 @@ class QLabelPrivate : public QFramePrivate
{
Q_DECLARE_PUBLIC(QLabel)
public:
- QLabelPrivate() {}
+ QLabelPrivate();
+ ~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 QWidgetTextControl *control;
- mutable QTextCursor shortcutCursor;
- Qt::TextInteractionFlags textInteractionFlags;
-
inline bool needTextControl() const {
return isTextLabel
&& (isRichText
@@ -129,13 +100,46 @@ public:
QMenu *createStandardContextMenu(const QPoint &pos);
#endif
- bool openExternalLinks;
-
+ mutable QSize sh;
+ mutable QSize msh;
+ QString text;
+ QPixmap *pixmap;
+ QPixmap *scaledpixmap;
+ QImage *cachedimage;
+#ifndef QT_NO_PICTURE
+ QPicture *picture;
+#endif
+#ifndef QT_NO_MOVIE
+ QPointer<QMovie> movie;
+#endif
+ mutable QWidgetTextControl *control;
+ mutable QTextCursor shortcutCursor;
+#ifndef QT_NO_CURSOR
+ QCursor cursor;
+#endif
+#ifndef QT_NO_SHORTCUT
+ QPointer<QWidget> buddy;
+ int shortcutId;
+#endif
+ Qt::TextFormat textformat;
+ Qt::TextInteractionFlags textInteractionFlags;
+ mutable QSizePolicy sizePolicy;
+ int margin;
+ ushort align;
+ short indent;
+ mutable uint valid_hints : 1;
+ uint scaledcontents : 1;
+ mutable uint textLayoutDirty : 1;
+ mutable uint textDirty : 1;
+ mutable uint isRichText : 1;
+ mutable uint isTextLabel : 1;
+ mutable uint hasShortcut : 1;
#ifndef QT_NO_CURSOR
uint validCursor : 1;
uint onAnchor : 1;
- QCursor cursor;
#endif
+ uint openExternalLinks : 1;
+ // <-- space for more bit field values here
friend class QMessageBoxPrivate;
};
diff --git a/src/widgets/widgets/qlcdnumber.h b/src/widgets/widgets/qlcdnumber.h
index d93edc75ca..9a7904a8bb 100644
--- a/src/widgets/widgets/qlcdnumber.h
+++ b/src/widgets/widgets/qlcdnumber.h
@@ -53,8 +53,8 @@ class Q_WIDGETS_EXPORT QLCDNumber : public QFrame // LCD number widget
Q_PROPERTY(int intValue READ intValue WRITE display)
public:
- explicit QLCDNumber(QWidget* parent = 0);
- explicit QLCDNumber(uint numDigits, QWidget* parent = 0);
+ explicit QLCDNumber(QWidget* parent = Q_NULLPTR);
+ explicit QLCDNumber(uint numDigits, QWidget* parent = Q_NULLPTR);
~QLCDNumber();
enum Mode {
diff --git a/src/widgets/widgets/qlineedit.h b/src/widgets/widgets/qlineedit.h
index e006f1c0d8..ac192f0da8 100644
--- a/src/widgets/widgets/qlineedit.h
+++ b/src/widgets/widgets/qlineedit.h
@@ -84,8 +84,8 @@ public:
};
Q_ENUM(ActionPosition)
- explicit QLineEdit(QWidget* parent=0);
- explicit QLineEdit(const QString &, QWidget* parent=0);
+ explicit QLineEdit(QWidget *parent = Q_NULLPTR);
+ explicit QLineEdit(const QString &, QWidget *parent = Q_NULLPTR);
~QLineEdit();
QString text() const;
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index 6645a375a7..a68f5a41ed 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -364,7 +364,7 @@ void QLineEditIconButton::startOpacityAnimation(qreal endValue)
void QLineEditIconButton::updateCursor()
{
#ifndef QT_NO_CURSOR
- setCursor(qFuzzyCompare(m_opacity, 1.0) || !parentWidget() ? QCursor(Qt::ArrowCursor) : parentWidget()->cursor());
+ setCursor(qFuzzyCompare(m_opacity, qreal(1.0)) || !parentWidget() ? QCursor(Qt::ArrowCursor) : parentWidget()->cursor());
#endif
}
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 5a22285149..b47866b827 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -114,7 +114,7 @@ public:
QAction *action;
int flags;
};
- typedef QList<SideWidgetEntry> SideWidgetEntryList;
+ typedef QVector<SideWidgetEntry> SideWidgetEntryList;
QLineEditPrivate()
: control(0), frame(1), contextMenuEnabled(1), cursorVisible(0),
@@ -228,6 +228,7 @@ private:
int lastTextSize;
mutable QSize m_iconSize;
};
+Q_DECLARE_TYPEINFO(QLineEditPrivate::SideWidgetEntry, Q_PRIMITIVE_TYPE);
static bool isSideWidgetVisible(const QLineEditPrivate::SideWidgetEntry &e)
{
diff --git a/src/widgets/widgets/qmaccocoaviewcontainer_mac.h b/src/widgets/widgets/qmaccocoaviewcontainer_mac.h
index 5920c1f8bf..a27d8f8690 100644
--- a/src/widgets/widgets/qmaccocoaviewcontainer_mac.h
+++ b/src/widgets/widgets/qmaccocoaviewcontainer_mac.h
@@ -45,7 +45,7 @@ class Q_WIDGETS_EXPORT QMacCocoaViewContainer : public QWidget
{
Q_OBJECT
public:
- QMacCocoaViewContainer(NSView *cocoaViewToWrap, QWidget *parent = 0);
+ QMacCocoaViewContainer(NSView *cocoaViewToWrap, QWidget *parent = Q_NULLPTR);
virtual ~QMacCocoaViewContainer();
void setCocoaView(NSView *view);
diff --git a/src/widgets/widgets/qmacnativewidget_mac.h b/src/widgets/widgets/qmacnativewidget_mac.h
index 761e55656b..5e82872faa 100644
--- a/src/widgets/widgets/qmacnativewidget_mac.h
+++ b/src/widgets/widgets/qmacnativewidget_mac.h
@@ -45,7 +45,7 @@ class Q_WIDGETS_EXPORT QMacNativeWidget : public QWidget
{
Q_OBJECT
public:
- QMacNativeWidget(NSView *parentView = 0);
+ QMacNativeWidget(NSView *parentView = Q_NULLPTR);
~QMacNativeWidget();
QSize sizeHint() const;
diff --git a/src/widgets/widgets/qmainwindow.cpp b/src/widgets/widgets/qmainwindow.cpp
index 4d5d3e5ec1..ff4bb3cc98 100644
--- a/src/widgets/widgets/qmainwindow.cpp
+++ b/src/widgets/widgets/qmainwindow.cpp
@@ -263,7 +263,14 @@ void QMainWindowPrivate::init()
An example of how to create menus follows:
- \snippet mainwindows/application/mainwindow.cpp 26
+ \code
+ void MainWindow::createMenus()
+ {
+ fileMenu = menuBar()->addMenu(tr("&File"));
+ fileMenu->addAction(newAct);
+ fileMenu->addAction(openAct);
+ fileMenu->addAction(saveAct);
+ \endcode
The \c createPopupMenu() function creates popup menus when the
main window receives context menu events. The default
@@ -290,7 +297,12 @@ void QMainWindowPrivate::init()
An example of toolbar creation follows:
- \snippet mainwindows/application/mainwindow.cpp 29
+ \code
+ void MainWindow::createToolBars()
+ {
+ fileToolBar = addToolBar(tr("File"));
+ fileToolBar->addAction(newAct);
+ \endcode
\section2 Creating Dock Widgets
@@ -420,6 +432,13 @@ QMainWindow::~QMainWindow()
at the bottom. Implies AllowTabbedDocks. See also
\l setTabPosition().
+ \value GroupedDragging When dragging the titlebar of a dock, all the tabs
+ that are tabbed with it are going to be dragged.
+ Implies AllowTabbedDocks. Does not work well if
+ some QDockWidgets have restrictions in which area
+ they are allowed. (This enum value was added in Qt
+ 5.6.)
+
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
@@ -1080,7 +1099,7 @@ void QMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget
addDockWidget(area, dockwidget, orientation);
#ifdef Q_DEAD_CODE_FROM_QT4_MAC //drawer support
- QMacCocoaAutoReleasePool pool;
+ QMacAutoReleasePool 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
@@ -1218,6 +1237,35 @@ void QMainWindow::removeDockWidget(QDockWidget *dockwidget)
Qt::DockWidgetArea QMainWindow::dockWidgetArea(QDockWidget *dockwidget) const
{ return d_func()->layout->dockWidgetArea(dockwidget); }
+
+/*!
+ \since 5.6
+ Resizes the dock widgets in the list \a docks to the corresponding size in
+ pixels from the list \a sizes. If \a orientation is Qt::Horizontal, adjusts
+ the width, otherwise adjusts the height of the dock widgets.
+ The sizes will be adjusted such that the maximum and the minimum sizes are
+ respected and the QMainWindow itself will not be resized.
+ Any additional/missing space is distributed amongst the widgets according
+ to the relative weight of the sizes.
+
+ Example:
+ \code
+ resizeDocks({blueWidget, yellowWidget}, {20 , 40}, Qt::Horizontal);
+ \endcode
+ If the blue and the yellow widget are nested on the same level they will be
+ resized such that the yellowWidget is twice as big as the blueWidget
+
+ If some widgets are grouped in tabs, only one widget per group should be
+ specified. Widgets not in the list might be changed to repect the constraints.
+*/
+void QMainWindow::resizeDocks(const QList<QDockWidget *> &docks,
+ const QList<int> &sizes, Qt::Orientation orientation)
+{
+ d_func()->layout->layoutState.dockAreaLayout.resizeDocks(docks, sizes, orientation);
+ d_func()->layout->invalidate();
+}
+
+
#endif // QT_NO_DOCKWIDGET
/*!
diff --git a/src/widgets/widgets/qmainwindow.h b/src/widgets/widgets/qmainwindow.h
index cbbea74b9b..70d78a7904 100644
--- a/src/widgets/widgets/qmainwindow.h
+++ b/src/widgets/widgets/qmainwindow.h
@@ -77,12 +77,13 @@ public:
AllowNestedDocks = 0x02,
AllowTabbedDocks = 0x04,
ForceTabbedDocks = 0x08, // implies AllowTabbedDocks, !AllowNestedDocks
- VerticalTabs = 0x10 // implies AllowTabbedDocks
+ VerticalTabs = 0x10, // implies AllowTabbedDocks
+ GroupedDragging = 0x20 // implies AllowTabbedDocks
};
Q_ENUM(DockOption)
Q_DECLARE_FLAGS(DockOptions, DockOption)
- explicit QMainWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit QMainWindow(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QMainWindow();
QSize iconSize() const;
@@ -164,6 +165,9 @@ public:
bool restoreDockWidget(QDockWidget *dockwidget);
Qt::DockWidgetArea dockWidgetArea(QDockWidget *dockwidget) const;
+
+ void resizeDocks(const QList<QDockWidget *> &docks,
+ const QList<int> &sizes, Qt::Orientation orientation);
#endif // QT_NO_DOCKWIDGET
QByteArray saveState(int version = 0) const;
diff --git a/src/widgets/widgets/qmainwindowlayout.cpp b/src/widgets/widgets/qmainwindowlayout.cpp
index 046666f571..54e956c4cf 100644
--- a/src/widgets/widgets/qmainwindowlayout.cpp
+++ b/src/widgets/widgets/qmainwindowlayout.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -49,6 +50,7 @@
#include <qstatusbar.h>
#include <qstring.h>
#include <qstyle.h>
+#include <qstylepainter.h>
#include <qvarlengtharray.h>
#include <qstack.h>
#include <qmap.h>
@@ -61,6 +63,7 @@
#include <private/qapplication_p.h>
#include <private/qlayoutengine_p.h>
+#include <private/qwidgetresizehandler_p.h>
#ifdef Q_DEAD_CODE_FROM_QT4_MAC
# include <private/qcore_mac_p.h>
# include <private/qt_cocoa_helpers_mac_p.h>
@@ -68,9 +71,7 @@
QT_BEGIN_NAMESPACE
-#ifdef QT_NO_DOCKWIDGET
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-#endif
/******************************************************************************
** debug
@@ -165,6 +166,228 @@ QDebug operator<<(QDebug debug, const QMainWindowLayout *layout)
#endif // !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_DEBUG)
/******************************************************************************
+ ** QDockWidgetGroupWindow
+ */
+// QDockWidgetGroupWindow is the floating window containing the tabbed dockwidgets in case several
+// dockwidgets are dragged together (QMainWindow::GroupedDragging feature).
+// QDockWidgetGroupLayout is the layout of that window and use a QDockAreaLayoutInfo to layout
+// the tabs inside it.
+#ifndef QT_NO_DOCKWIDGET
+class QDockWidgetGroupLayout : public QLayout {
+ QDockAreaLayoutInfo info;
+ QWidgetResizeHandler *resizer;
+public:
+ QDockWidgetGroupLayout(QWidget* parent) : QLayout(parent) {
+ setSizeConstraint(QLayout::SetMinAndMaxSize);
+ resizer = new QWidgetResizeHandler(parent);
+ resizer->setMovingEnabled(false);
+ }
+ ~QDockWidgetGroupLayout() {
+ info.deleteAllLayoutItems();
+ }
+
+ void addItem(QLayoutItem*) Q_DECL_OVERRIDE { Q_UNREACHABLE(); }
+ int count() const Q_DECL_OVERRIDE { return 0; }
+ QLayoutItem* itemAt(int index) const Q_DECL_OVERRIDE
+ {
+ int x = 0;
+ return info.itemAt(&x, index);
+ }
+ QLayoutItem* takeAt(int index) Q_DECL_OVERRIDE
+ {
+ int x = 0;
+ return info.takeAt(&x, index);
+ }
+ QSize sizeHint() const Q_DECL_OVERRIDE
+ {
+ int fw = frameWidth();
+ return info.sizeHint() + QSize(fw, fw);
+ }
+ QSize minimumSize() const Q_DECL_OVERRIDE
+ {
+ int fw = frameWidth();
+ return info.minimumSize() + QSize(fw, fw);
+ }
+ QSize maximumSize() const Q_DECL_OVERRIDE
+ {
+ int fw = frameWidth();
+ return info.maximumSize() + QSize(fw, fw);
+ }
+ void setGeometry(const QRect&r) Q_DECL_OVERRIDE
+ {
+ QDockAreaLayoutInfo *li = layoutInfo();
+ if (li->isEmpty()) {
+ static_cast<QDockWidgetGroupWindow *>(parent())->destroyIfEmpty();
+ return;
+ }
+ int fw = frameWidth();
+ li->reparentWidgets(parentWidget());
+ li->rect = r.adjusted(fw, fw, -fw, -fw);
+ li->fitItems();
+ li->apply(false);
+ resizer->setActive(QWidgetResizeHandler::Resize, !nativeWindowDeco());
+ }
+
+ QDockAreaLayoutInfo *layoutInfo() {
+ return &info;
+ }
+
+ bool nativeWindowDeco() const
+ {
+ return QDockWidgetLayout::wmSupportsNativeWindowDeco();
+ }
+
+ int frameWidth() const
+ {
+ return nativeWindowDeco() ? 0 :
+ parentWidget()->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, parentWidget());
+ }
+};
+
+bool QDockWidgetGroupWindow::event(QEvent *e)
+{
+ switch (e->type()) {
+ case QEvent::Close:
+ // Forward the close to the QDockWidget just as if its close button was pressed
+ if (QDockWidget *dw = topDockWidget()) {
+ e->ignore();
+ dw->close();
+ adjustFlags();
+ }
+ return true;
+ case QEvent::Move:
+ // Let QDockWidgetPrivate::moseEvent handle the dragging
+ if (QDockWidget *dw = topDockWidget())
+ static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->moveEvent(static_cast<QMoveEvent*>(e));
+ return true;
+ case QEvent::NonClientAreaMouseMove:
+ case QEvent::NonClientAreaMouseButtonPress:
+ case QEvent::NonClientAreaMouseButtonRelease:
+ case QEvent::NonClientAreaMouseButtonDblClick:
+ // Let the QDockWidgetPrivate of the currently visible dock widget handle the drag and drop
+ if (QDockWidget *dw = topDockWidget())
+ static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->nonClientAreaMouseEvent(static_cast<QMouseEvent*>(e));
+ return true;
+ case QEvent::ChildAdded:
+ if (qobject_cast<QDockWidget *>(static_cast<QChildEvent*>(e)->child()))
+ adjustFlags();
+ break;
+ default:
+ break;
+ }
+ return QWidget::event(e);
+}
+
+void QDockWidgetGroupWindow::paintEvent(QPaintEvent *)
+{
+ QDockWidgetGroupLayout *lay = static_cast<QDockWidgetGroupLayout *>(layout());
+ bool nativeDeco = lay->nativeWindowDeco();
+
+ if (!nativeDeco) {
+ QStyleOptionFrame framOpt;
+ framOpt.init(this);
+ QStylePainter p(this);
+ p.drawPrimitive(QStyle::PE_FrameDockWidget, framOpt);
+ }
+}
+
+QDockAreaLayoutInfo *QDockWidgetGroupWindow::layoutInfo() const
+{
+ return static_cast<QDockWidgetGroupLayout*>(layout())->layoutInfo();
+}
+
+/*! \internal
+ Returns the currently active QDockWidget.
+ */
+QDockWidget *QDockWidgetGroupWindow::topDockWidget() const
+{
+ QDockAreaLayoutInfo *info = layoutInfo();
+ QDockWidget *dw = 0;
+ if (info->tabBar && info->tabBar->currentIndex() >= 0) {
+ int i = info->tabIndexToListIndex(info->tabBar->currentIndex());
+ if (i >= 0) {
+ const QDockAreaLayoutItem &item = info->item_list.at(i);
+ if (item.widgetItem)
+ dw = qobject_cast<QDockWidget *>(item.widgetItem->widget());
+ }
+ }
+ if (!dw) {
+ for (int i = 0; !dw && i < info->item_list.count(); ++i) {
+ const QDockAreaLayoutItem &item = info->item_list.at(i);
+ if (item.skip())
+ continue;
+ if (!item.widgetItem)
+ continue;
+ dw = qobject_cast<QDockWidget *>(item.widgetItem->widget());
+ }
+ }
+ return dw;
+}
+
+/*! \internal
+ Destroy this window if there is no more QDockWidget in it.
+ */
+void QDockWidgetGroupWindow::destroyIfEmpty()
+{
+ if (layoutInfo()->isEmpty()) {
+ // Make sure to reparent the possibly floating or hidden QDockWidgets to the parent
+ foreach (QDockWidget *dw,
+ findChildren<QDockWidget *>(QString(), Qt::FindDirectChildrenOnly)) {
+ bool wasFloating = dw->isFloating();
+ bool wasHidden = dw->isHidden();
+ dw->setParent(parentWidget());
+ if (wasFloating) {
+ dw->setFloating(true);
+ } else {
+ // maybe it was hidden, we still have to put it back in the main layout.
+ QMainWindowLayout *ml = qt_mainwindow_layout(static_cast<QMainWindow*>(parentWidget()));
+ Qt::DockWidgetArea area = ml->dockWidgetArea(this);
+ if (area == Qt::NoDockWidgetArea)
+ area = Qt::LeftDockWidgetArea;
+ static_cast<QMainWindow*>(parentWidget())->addDockWidget(area, dw);
+ }
+ if (!wasHidden)
+ dw->show();
+ }
+ foreach (QTabBar *tb, findChildren<QTabBar *>(QString(), Qt::FindDirectChildrenOnly))
+ tb->setParent(parentWidget());
+ deleteLater();
+ }
+}
+
+/*! \internal
+ Sets the flags of this window in accordence to the capabilities of the dock widgets
+ */
+void QDockWidgetGroupWindow::adjustFlags()
+{
+ QDockWidget *top = topDockWidget();
+ if (!top)
+ return;
+ const bool nativeDeco = static_cast<QDockWidgetGroupLayout *>(layout())->nativeWindowDeco();
+
+ Qt::WindowFlags oldFlags = windowFlags();
+ Qt::WindowFlags flags = oldFlags;
+ if (nativeDeco) {
+ flags |= Qt::CustomizeWindowHint | Qt::WindowTitleHint;
+ if (top->features() & QDockWidget::DockWidgetClosable)
+ flags |= Qt::WindowCloseButtonHint;
+ else
+ flags &= ~Qt::WindowCloseButtonHint;
+ flags &= ~Qt::FramelessWindowHint;
+ } else {
+ flags |= Qt::FramelessWindowHint;
+ }
+ if (oldFlags != flags) {
+ setWindowFlags(flags);
+ show(); // setWindowFlags hides the window
+ }
+
+ setWindowTitle(top->windowTitle());
+ setWindowIcon(top->windowIcon());
+}
+#endif
+
+/******************************************************************************
** QMainWindowLayoutState
*/
@@ -335,8 +558,8 @@ QList<int> QMainWindowLayoutState::indexOf(QWidget *widget) const
#ifndef QT_NO_DOCKWIDGET
// is it a dock widget?
- if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(widget)) {
- result = dockAreaLayout.indexOf(dockWidget);
+ if (qobject_cast<QDockWidget *>(widget) || qobject_cast<QDockWidgetGroupWindow *>(widget)) {
+ result = dockAreaLayout.indexOf(widget);
if (!result.isEmpty())
result.prepend(1);
return result;
@@ -413,7 +636,8 @@ QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget,
#ifndef QT_NO_DOCKWIDGET
// is it a dock widget?
- if (qobject_cast<QDockWidget *>(widget) != 0) {
+ if (qobject_cast<QDockWidget *>(widget) != 0
+ || qobject_cast<QDockWidgetGroupWindow *>(widget)) {
result = dockAreaLayout.gapIndex(pos);
if (!result.isEmpty())
result.prepend(1);
@@ -440,7 +664,7 @@ bool QMainWindowLayoutState::insertGap(const QList<int> &path, QLayoutItem *item
#ifndef QT_NO_DOCKWIDGET
if (i == 1) {
- Q_ASSERT(qobject_cast<QDockWidget*>(item->widget()) != 0);
+ Q_ASSERT(qobject_cast<QDockWidget*>(item->widget()) || qobject_cast<QDockWidgetGroupWindow*>(item->widget()));
return dockAreaLayout.insertGap(path.mid(1), item);
}
#endif //QT_NO_DOCKWIDGET
@@ -593,6 +817,17 @@ void QMainWindowLayoutState::saveState(QDataStream &stream) const
{
#ifndef QT_NO_DOCKWIDGET
dockAreaLayout.saveState(stream);
+#ifndef QT_NO_TABBAR
+ QList<QDockWidgetGroupWindow *> floatingTabs =
+ mainWindow->findChildren<QDockWidgetGroupWindow *>(QString(), Qt::FindDirectChildrenOnly);
+
+ foreach (QDockWidgetGroupWindow *floating, floatingTabs) {
+ if (floating->layoutInfo()->isEmpty())
+ continue;
+ stream << uchar(QDockAreaLayout::FloatingDockWidgetTabMarker) << floating->geometry();
+ floating->layoutInfo()->saveState(stream);
+ }
+#endif
#endif
#ifndef QT_NO_TOOLBAR
toolBarAreaLayout.saveState(stream);
@@ -638,12 +873,28 @@ bool QMainWindowLayoutState::checkFormat(QDataStream &stream)
case QDockAreaLayout::DockWidgetStateMarker:
{
QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
+ foreach (QDockWidgetGroupWindow *floating, findChildrenHelper<QDockWidgetGroupWindow*>(mainWindow))
+ dockWidgets += findChildrenHelper<QDockWidget*>(floating);
if (!dockAreaLayout.restoreState(stream, dockWidgets, true /*testing*/)) {
return false;
}
}
break;
-#endif
+#ifndef QT_NO_TABBAR
+ case QDockAreaLayout::FloatingDockWidgetTabMarker:
+ {
+ QRect geom;
+ stream >> geom;
+ QDockAreaLayoutInfo info;
+ QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
+ foreach (QDockWidgetGroupWindow *floating, findChildrenHelper<QDockWidgetGroupWindow*>(mainWindow))
+ dockWidgets += findChildrenHelper<QDockWidget*>(floating);
+ if (!info.restoreState(stream, dockWidgets, true /* testing*/))
+ return false;
+ }
+ break;
+#endif // QT_NO_TABBAR
+#endif // QT_NO_DOCKWIDGET
default:
//there was an error during the parsing
return false;
@@ -682,6 +933,8 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
case QDockAreaLayout::DockWidgetStateMarker:
{
QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
+ foreach (QDockWidgetGroupWindow *floating, findChildrenHelper<QDockWidgetGroupWindow*>(mainWindow))
+ dockWidgets += findChildrenHelper<QDockWidget*>(floating);
if (!dockAreaLayout.restoreState(stream, dockWidgets))
return false;
@@ -702,6 +955,26 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
}
}
break;
+#ifndef QT_NO_TABBAR
+ case QDockAreaLayout::FloatingDockWidgetTabMarker:
+ {
+ QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
+ foreach (QDockWidgetGroupWindow *floating, findChildrenHelper<QDockWidgetGroupWindow*>(mainWindow))
+ dockWidgets += findChildrenHelper<QDockWidget*>(floating);
+ QDockWidgetGroupWindow* floatingTab = qt_mainwindow_layout(mainWindow)->createTabbedDockWindow();
+ *floatingTab->layoutInfo() = QDockAreaLayoutInfo(&dockAreaLayout.sep, QInternal::LeftDock,
+ Qt::Horizontal, QTabBar::RoundedSouth, mainWindow);
+ QRect geometry;
+ stream >> geometry;
+ if (!floatingTab->layoutInfo()->restoreState(stream, dockWidgets, false))
+ return false;
+ geometry = QDockAreaLayout::constrainedRect(geometry, floatingTab);
+ floatingTab->move(geometry.topLeft());
+ floatingTab->resize(geometry.size());
+ floatingTab->show();
+ }
+ break;
+#endif // QT_NO_TABBAR
#endif // QT_NO_DOCKWIDGET
#ifndef QT_NO_TOOLBAR
@@ -1223,7 +1496,7 @@ void QMainWindowLayout::splitDockWidget(QDockWidget *after,
invalidate();
}
-Qt::DockWidgetArea QMainWindowLayout::dockWidgetArea(QDockWidget *widget) const
+Qt::DockWidgetArea QMainWindowLayout::dockWidgetArea(QWidget *widget) const
{
QList<int> pathToWidget = layoutState.dockAreaLayout.indexOf(widget);
if (pathToWidget.isEmpty())
@@ -1238,20 +1511,88 @@ void QMainWindowLayout::keepSize(QDockWidget *w)
#ifndef QT_NO_TABBAR
+// Handle custom tooltip, and allow to drag tabs away.
class QMainWindowTabBar : public QTabBar
{
+ QMainWindow *mainWindow;
+ QDockWidget *draggingDock; // Currently dragging (detached) dock widget
public:
- QMainWindowTabBar(QWidget *parent);
+ QMainWindowTabBar(QMainWindow *parent);
protected:
bool event(QEvent *e) Q_DECL_OVERRIDE;
+ void mouseReleaseEvent(QMouseEvent*) Q_DECL_OVERRIDE;
+ void mouseMoveEvent(QMouseEvent*) Q_DECL_OVERRIDE;
+
};
-QMainWindowTabBar::QMainWindowTabBar(QWidget *parent)
- : QTabBar(parent)
+QMainWindowTabBar::QMainWindowTabBar(QMainWindow *parent)
+ : QTabBar(parent), mainWindow(parent), draggingDock(0)
{
setExpanding(false);
}
+void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
+{
+ // The QTabBar handles the moving (reordering) of tabs.
+ // When QTabBarPrivate::dragInProgress is true, and that the mouse is outside of a region
+ // around the QTabBar, we will consider the user wants to drag that QDockWidget away from this
+ // tab area.
+
+ QTabBarPrivate *d = static_cast<QTabBarPrivate*>(d_ptr.data());
+ if (!draggingDock && (mainWindow->dockOptions() & QMainWindow::GroupedDragging)) {
+ int offset = QApplication::startDragDistance() + 1;
+ offset *= 3;
+ QRect r = rect().adjusted(-offset, -offset, offset, offset);
+ if (d->dragInProgress && !r.contains(e->pos()) && d->validIndex(d->pressedIndex)) {
+ QMainWindowLayout* mlayout = qt_mainwindow_layout(mainWindow);
+ QDockAreaLayoutInfo *info = mlayout->dockInfo(this);
+ Q_ASSERT(info);
+ int idx = info->tabIndexToListIndex(d->pressedIndex);
+ const QDockAreaLayoutItem &item = info->item_list.at(idx);
+ if (item.widgetItem
+ && (draggingDock = qobject_cast<QDockWidget *>(item.widgetItem->widget()))) {
+ // We should drag this QDockWidget away by unpluging it.
+ // First cancel the QTabBar's internal move
+ d->moveTabFinished(d->pressedIndex);
+ d->pressedIndex = -1;
+ if (d->movingTab)
+ d->movingTab->setVisible(false);
+ d->dragStartPosition = QPoint();
+
+ // Then starts the drag using QDockWidgetPrivate's API
+ QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
+ QDockWidgetLayout *dwlayout = static_cast<QDockWidgetLayout *>(draggingDock->layout());
+ dockPriv->initDrag(dwlayout->titleArea().center(), true);
+ dockPriv->startDrag(false);
+ if (dockPriv->state)
+ dockPriv->state->ctrlDrag = e->modifiers() & Qt::ControlModifier;
+ }
+ }
+ }
+
+ if (draggingDock) {
+ QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
+ if (dockPriv->state && dockPriv->state->dragging) {
+ QPoint pos = e->globalPos() - dockPriv->state->pressPos;
+ draggingDock->move(pos);
+ // move will call QMainWindowLayout::hover
+ }
+ }
+ QTabBar::mouseMoveEvent(e);
+}
+
+void QMainWindowTabBar::mouseReleaseEvent(QMouseEvent *e)
+{
+ if (draggingDock && e->button() == Qt::LeftButton) {
+ QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
+ if (dockPriv->state && dockPriv->state->dragging) {
+ dockPriv->endDrag();
+ }
+ draggingDock = 0;
+ }
+ QTabBar::mouseReleaseEvent(e);
+}
+
bool QMainWindowTabBar::event(QEvent *e)
{
// show the tooltip if tab is too small to fit label
@@ -1276,11 +1617,13 @@ QTabBar *QMainWindowLayout::getTabBar()
if (!unusedTabBars.isEmpty()) {
result = unusedTabBars.takeLast();
} else {
- result = new QMainWindowTabBar(parentWidget());
+ result = new QMainWindowTabBar(static_cast<QMainWindow *>(parentWidget()));
result->setDrawBase(true);
result->setElideMode(Qt::ElideRight);
result->setDocumentMode(_documentMode);
+ result->setMovable(true);
connect(result, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()));
+ connect(result, &QTabBar::tabMoved, this, &QMainWindowLayout::tabMoved);
}
usedTabBars.insert(result);
@@ -1303,12 +1646,30 @@ QWidget *QMainWindowLayout::getSeparatorWidget()
return result;
}
+/*! \internal
+ Returns a pointer QDockAreaLayoutInfo which contains this \a widget directly
+ (in its internal list)
+ */
+QDockAreaLayoutInfo *QMainWindowLayout::dockInfo(QWidget *widget)
+{
+ QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(widget);
+ if (info)
+ return info;
+ foreach (QDockWidgetGroupWindow *dwgw,
+ parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly)) {
+ info = dwgw->layoutInfo()->info(widget);
+ if (info)
+ return info;
+ }
+ return 0;
+}
+
void QMainWindowLayout::tabChanged()
{
QTabBar *tb = qobject_cast<QTabBar*>(sender());
if (tb == 0)
return;
- QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(tb);
+ QDockAreaLayoutInfo *info = dockInfo(tb);
if (info == 0)
return;
info->apply(false);
@@ -1316,6 +1677,16 @@ void QMainWindowLayout::tabChanged()
if (QWidget *w = centralWidget())
w->raise();
}
+
+void QMainWindowLayout::tabMoved(int from, int to)
+{
+ QTabBar *tb = qobject_cast<QTabBar*>(sender());
+ Q_ASSERT(tb);
+ QDockAreaLayoutInfo *info = dockInfo(tb);
+ Q_ASSERT(info);
+
+ info->moveTab(from, to);
+}
#endif // QT_NO_TABBAR
bool QMainWindowLayout::startSeparatorMove(const QPoint &pos)
@@ -1353,7 +1724,7 @@ bool QMainWindowLayout::endSeparatorMove(const QPoint&)
void QMainWindowLayout::raise(QDockWidget *widget)
{
- QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(widget);
+ QDockAreaLayoutInfo *info = dockInfo(widget);
if (info == 0)
return;
#ifndef QT_NO_TABBAR
@@ -1537,6 +1908,8 @@ void QMainWindowLayout::revert(QLayoutItem *widgetItem)
QWidget *widget = widgetItem->widget();
layoutState = savedState;
currentGapPos = layoutState.indexOf(widget);
+ if (currentGapPos.isEmpty())
+ return;
fixToolBarOrientation(widgetItem, currentGapPos.at(1));
layoutState.unplug(currentGapPos);
layoutState.fitLayout();
@@ -1547,6 +1920,54 @@ void QMainWindowLayout::revert(QLayoutItem *widgetItem)
bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
{
+#ifndef QT_NO_DOCKWIDGET
+ if (currentHoveredFloat) {
+ QWidget *widget = widgetItem->widget();
+ QList<int> previousPath = layoutState.indexOf(widget);
+ if (!previousPath.isEmpty())
+ layoutState.remove(previousPath);
+ // Let's remove the widget from any possible group window
+ foreach (QDockWidgetGroupWindow *dwgw,
+ parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly)) {
+ QList<int> path = dwgw->layoutInfo()->indexOf(widget);
+ if (!path.isEmpty())
+ dwgw->layoutInfo()->remove(path);
+ }
+ currentGapRect = QRect();
+
+ if (QDockWidget *dropTo = qobject_cast<QDockWidget*>(currentHoveredFloat)) {
+ //dropping to a normal widget, we mutate it in a QDockWidgetGroupWindow with two tabs
+ QDockWidgetGroupWindow *floatingTabs = createTabbedDockWindow();
+ floatingTabs->setGeometry(dropTo->geometry());
+ QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
+ *info = QDockAreaLayoutInfo(&layoutState.dockAreaLayout.sep, QInternal::LeftDock,
+ Qt::Horizontal, QTabBar::RoundedSouth,
+ static_cast<QMainWindow*>(parentWidget()));
+ info->tabbed = true;
+ QLayout *parentLayout = currentHoveredFloat->parentWidget()->layout();
+ info->item_list.append(parentLayout->takeAt(parentLayout->indexOf(currentHoveredFloat)));
+
+ dropTo->setParent(floatingTabs);
+ dropTo->show();
+ dropTo->d_func()->plug(QRect());
+ currentHoveredFloat = floatingTabs;
+ }
+
+ QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(currentHoveredFloat);
+ Q_ASSERT(dwgw);
+ Q_ASSERT(dwgw->layoutInfo()->tabbed); // because floating group should always be tabbed
+ previousPath = dwgw->layoutInfo()->indexOf(widget);
+ if (!previousPath.isEmpty())
+ dwgw->layoutInfo()->remove(previousPath);
+ dwgw->layoutInfo()->tab(0, widgetItem);
+ QRect globalRect = dwgw->layoutInfo()->tabContentRect();
+ globalRect.moveTopLeft(dwgw->mapToGlobal(globalRect.topLeft()));
+ pluggingWidget = widget;
+ widgetAnimator.animate(widget, globalRect, dockOptions & QMainWindow::AnimatedDocks);
+ return true;
+ }
+#endif
+
if (!parentWidget()->isVisible() || parentWidget()->isMinimized() || currentGapPos.isEmpty())
return false;
@@ -1554,6 +1975,16 @@ bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
QWidget *widget = widgetItem->widget();
+#ifndef QT_NO_DOCKWIDGET
+ // Let's remove the widget from any possible group window
+ foreach (QDockWidgetGroupWindow *dwgw,
+ parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly)) {
+ QList<int> path = dwgw->layoutInfo()->indexOf(widget);
+ if (!path.isEmpty())
+ dwgw->layoutInfo()->remove(path);
+ }
+#endif
+
QList<int> previousPath = layoutState.indexOf(widget);
const QLayoutItem *it = layoutState.plug(currentGapPos);
@@ -1601,8 +2032,59 @@ void QMainWindowLayout::animationFinished(QWidget *widget)
if (widget == pluggingWidget) {
#ifndef QT_NO_DOCKWIDGET
- if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget))
+ if (QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
+ // When the animated widget was a QDockWidgetGroupWindow, it means each of the
+ // embedded QDockWidget needs to be plugged back into the QMainWindow layout.
+ savedState.clear();
+ QDockAreaLayoutInfo* info = dwgw->layoutInfo();
+ QDockAreaLayoutInfo* parentInfo;
+ QList<int> path;
+
+ if (QDockWidgetGroupWindow *dropTo = qobject_cast<QDockWidgetGroupWindow *>(currentHoveredFloat)) {
+ parentInfo = dropTo->layoutInfo();
+ Q_ASSERT(parentInfo->tabbed);
+ path = parentInfo->indexOf(widget);
+ Q_ASSERT(path.size() == 1);
+ } else {
+ path = layoutState.dockAreaLayout.indexOf(widget);
+ Q_ASSERT(path.size() >= 2);
+ parentInfo = layoutState.dockAreaLayout.info(path);
+ Q_ASSERT(parentInfo);
+ }
+
+ if (parentInfo->tabbed) {
+ // merge the two tab widgets
+ int idx = path.last();
+ Q_ASSERT(parentInfo->item_list[idx].widgetItem->widget() == dwgw);
+ delete parentInfo->item_list[idx].widgetItem;
+ parentInfo->item_list.removeAt(idx);
+ std::copy(info->item_list.cbegin(), info->item_list.cend(),
+ std::inserter(parentInfo->item_list, parentInfo->item_list.begin() + idx));
+ quintptr currentId = info->currentTabId();
+ *info = QDockAreaLayoutInfo();
+ parentInfo->reparentWidgets(currentHoveredFloat ? currentHoveredFloat.data() : parentWidget());
+ parentInfo->updateTabBar();
+ parentInfo->setCurrentTabId(currentId);
+ } else {
+ QDockAreaLayoutItem &item = layoutState.dockAreaLayout.item(path);
+ Q_ASSERT(item.widgetItem->widget() == dwgw);
+ delete item.widgetItem;
+ item.widgetItem = 0;
+ item.subinfo = new QDockAreaLayoutInfo(qMove(*info));
+ *info = QDockAreaLayoutInfo();
+ item.subinfo->reparentWidgets(parentWidget());
+ item.subinfo->setTabBarShape(parentInfo->tabBarShape);
+ }
+ dwgw->destroyIfEmpty();
+ }
+
+ if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
+ if (currentHoveredFloat) {
+ dw->setParent(currentHoveredFloat);
+ dw->show();
+ }
dw->d_func()->plug(currentGapRect);
+ }
#endif
#ifndef QT_NO_TOOLBAR
if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
@@ -1612,6 +2094,7 @@ void QMainWindowLayout::animationFinished(QWidget *widget)
savedState.clear();
currentGapPos.clear();
pluggingWidget = 0;
+ currentHoveredFloat = Q_NULLPTR;
//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);
@@ -1621,7 +2104,7 @@ void QMainWindowLayout::animationFinished(QWidget *widget)
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))
+ if (QDockAreaLayoutInfo *info = dockInfo(widget))
info->setCurrentTab(widget);
}
#endif
@@ -1673,9 +2156,6 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLay
#endif // QT_NO_DOCKWIDGET
, widgetAnimator(this)
, pluggingWidget(0)
-#ifndef QT_NO_RUBBERBAND
- , gapIndicator(new QRubberBand(QRubberBand::Rectangle, mainwindow))
-#endif //QT_NO_RUBBERBAND
#ifdef Q_DEAD_CODE_FROM_QT4_MAC
, blockVisiblityCheck(false)
#endif
@@ -1693,12 +2173,6 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLay
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"));
@@ -1765,8 +2239,33 @@ void QMainWindowLayout::setCentralWidget(QWidget *widget)
invalidate();
}
-QLayoutItem *QMainWindowLayout::unplug(QWidget *widget)
-{
+/*! \internal
+ Unplug \a widget (QDockWidget or QToolBar) from it's parent container.
+
+ If \a group is true we might actually unplug the group of tabs this
+ widget is part if QMainWindow::GroupedDragging is set. When \a group
+ is false, the widget itself is always unplugged alone
+
+ Returns the QLayoutItem of the dragged element.
+ The layout item is kept in the layout but set as a gap item.
+ */
+QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
+{
+#if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_TABBAR)
+ QDockWidgetGroupWindow *floatingParent = qobject_cast<QDockWidgetGroupWindow *>(widget->parentWidget());
+ if (group && floatingParent && !widget->isWindow()) {
+ // We are just dragging a floating window as it, not need to do anything, we just have to
+ // look up the corresponding QWidgetItem* if it exists
+ QList<int> tabbedWindowPath = layoutState.indexOf(widget->parentWidget());
+ return tabbedWindowPath.isEmpty() ? 0 : layoutState.item(tabbedWindowPath);
+ } else if (floatingParent) {
+ // We are unplugging a dock widget from a floating window.
+ if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
+ dw->d_func()->unplug(widget->geometry());
+ return 0;
+ }
+ }
+#endif
QList<int> path = layoutState.indexOf(widget);
if (path.isEmpty())
return 0;
@@ -1780,9 +2279,35 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget)
#ifndef QT_NO_DOCKWIDGET
if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
- dw->d_func()->unplug(r);
+ Q_ASSERT(path.first() == 1);
+ bool actualGroup = false;
+#ifndef QT_NO_TABBAR
+ if (group && (dockOptions & QMainWindow::GroupedDragging) && path.size() > 3) {
+ QDockAreaLayoutItem &parentItem = layoutState.dockAreaLayout.item(path.mid(1, path.size() - 2));
+ if (parentItem.subinfo && parentItem.subinfo->tabbed) {
+ // The QDockWidget is part of a group of tab and we need to unplug them all.
+ actualGroup = true;
+ path.removeLast();
+
+ QDockWidgetGroupWindow* floatingTabs = createTabbedDockWindow();
+ QDockAreaLayoutInfo* info = floatingTabs->layoutInfo();
+ *info = qMove(*parentItem.subinfo);
+ delete parentItem.subinfo;
+ parentItem.subinfo = 0;
+ floatingTabs->setGeometry(info->rect.translated(parentWidget()->pos()));
+ floatingTabs->show();
+ floatingTabs->raise();
+ item = new QDockWidgetGroupWindowItem(floatingTabs);
+ parentItem.widgetItem = item;
+ savedState = layoutState;
+ }
+ }
+#endif // QT_NO_TABBAR
+ if (!actualGroup) {
+ dw->d_func()->unplug(r);
+ }
}
-#endif
+#endif // QT_NO_DOCKWIDGET
#ifndef QT_NO_TOOLBAR
if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) {
tb->d_func()->unplug(r);
@@ -1804,18 +2329,75 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget)
void QMainWindowLayout::updateGapIndicator()
{
#ifndef QT_NO_RUBBERBAND
- gapIndicator->setVisible(!widgetAnimator.animating() && !currentGapPos.isEmpty());
- gapIndicator->setGeometry(currentGapRect);
-#endif
+ if ((!widgetAnimator.animating() && !currentGapPos.isEmpty()) || currentHoveredFloat) {
+ QWidget *expectedParent = currentHoveredFloat ? currentHoveredFloat.data() : parentWidget();
+ if (!gapIndicator) {
+ gapIndicator = new QRubberBand(QRubberBand::Rectangle, expectedParent);
+ // For accessibility to identify this special widget.
+ gapIndicator->setObjectName(QLatin1String("qt_rubberband"));
+ } else if (gapIndicator->parent() != expectedParent) {
+ gapIndicator->setParent(expectedParent);
+ }
+ gapIndicator->setGeometry(currentHoveredFloat ? currentHoveredFloat->rect() : currentGapRect);
+ gapIndicator->show();
+ gapIndicator->raise();
+ } else if (gapIndicator) {
+ gapIndicator->hide();
+ }
+#endif //QT_NO_RUBBERBAND
}
-QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
+void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
{
if (!parentWidget()->isVisible() || parentWidget()->isMinimized()
|| pluggingWidget != 0 || widgetItem == 0)
- return QList<int>();
+ return;
QWidget *widget = widgetItem->widget();
+
+#ifndef QT_NO_DOCKWIDGET
+ if ((dockOptions & QMainWindow::GroupedDragging) && (qobject_cast<QDockWidget*>(widget)
+ || qobject_cast<QDockWidgetGroupWindow *>(widget))) {
+
+ // Check if we are over another floating dock widget
+ QVarLengthArray<QWidget *, 10> candidates;
+ foreach (QObject *c, parentWidget()->children()) {
+ QWidget *w = qobject_cast<QWidget*>(c);
+ if (!w)
+ continue;
+ if (w == widget)
+ continue;
+ if (!w->isTopLevel() || !w->isVisible() || w->isMinimized())
+ continue;
+ if (!qobject_cast<QDockWidget*>(w) && !qobject_cast<QDockWidgetGroupWindow *>(w))
+ continue;
+ candidates << w;
+ if (QDockWidgetGroupWindow *group = qobject_cast<QDockWidgetGroupWindow *>(w)) {
+ // Sometimes, there are floating QDockWidget that have a QDockWidgetGroupWindow as a parent.
+ foreach (QObject *c, group->children()) {
+ if (QDockWidget *dw = qobject_cast<QDockWidget*>(c)) {
+ if (dw != widget && dw->isFloating() && dw->isVisible() && !dw->isMinimized())
+ candidates << dw;
+ }
+ }
+ }
+ }
+ foreach (QWidget *w, candidates) {
+ QWindow *handle1 = widget->windowHandle();
+ QWindow *handle2 = w->windowHandle();
+ if (handle1 && handle2 && handle1->screen() != handle2->screen())
+ continue;
+ if (!w->geometry().contains(mousePos))
+ continue;
+
+ currentHoveredFloat = w;
+ restore(true);
+ return;
+ }
+ }
+ currentHoveredFloat = Q_NULLPTR;
+#endif //QT_NO_DOCKWIDGET
+
QPoint pos = parentWidget()->mapFromGlobal(mousePos);
if (!savedState.isValid())
@@ -1829,6 +2411,9 @@ QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mouse
#ifndef QT_NO_DOCKWIDGET
if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget))
allowed = dw->isAreaAllowed(toDockWidgetArea(path.at(1)));
+
+ if (qobject_cast<QDockWidgetGroupWindow *>(widget))
+ allowed = true;
#endif
#ifndef QT_NO_TOOLBAR
if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
@@ -1840,13 +2425,13 @@ QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mouse
}
if (path == currentGapPos)
- return currentGapPos; // the gap is already there
+ return; // the gap is already there
currentGapPos = path;
if (path.isEmpty()) {
fixToolBarOrientation(widgetItem, 2); // 2 = top dock, ie. horizontal
restore(true);
- return QList<int>();
+ return;
}
fixToolBarOrientation(widgetItem, currentGapPos.at(1));
@@ -1855,7 +2440,7 @@ QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mouse
if (!newState.insertGap(path, widgetItem)) {
restore(true); // not enough space
- return QList<int>();
+ return;
}
QSize min = newState.minimumSize();
@@ -1863,7 +2448,7 @@ QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mouse
if (min.width() > size.width() || min.height() > size.height()) {
restore(true);
- return QList<int>();
+ return;
}
newState.fitLayout();
@@ -1877,8 +2462,13 @@ QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mouse
applyState(layoutState);
updateGapIndicator();
+}
- return path;
+QDockWidgetGroupWindow *QMainWindowLayout::createTabbedDockWindow()
+{
+ QDockWidgetGroupWindow* f = new QDockWidgetGroupWindow(parentWidget(), Qt::Tool);
+ new QDockWidgetGroupLayout(f);
+ return f;
}
void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animate)
@@ -1886,6 +2476,11 @@ void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animat
#ifndef QT_NO_DOCKWIDGET
#ifndef QT_NO_TABBAR
QSet<QTabBar*> used = newState.dockAreaLayout.usedTabBars();
+ foreach (QDockWidgetGroupWindow *dwgw,
+ parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly)) {
+ used += dwgw->layoutInfo()->usedTabBars();
+ }
+
QSet<QTabBar*> retired = usedTabBars - used;
usedTabBars = used;
foreach (QTabBar *tab_bar, retired) {
@@ -1904,6 +2499,8 @@ void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animat
}
}
+ for (int i = 0; i < QInternal::DockCount; ++i)
+ newState.dockAreaLayout.docks[i].reparentWidgets(parentWidget());
#endif // QT_NO_TABBAR
#endif // QT_NO_DOCKWIDGET
diff --git a/src/widgets/widgets/qmainwindowlayout_p.h b/src/widgets/widgets/qmainwindowlayout_p.h
index 9f84ee95db..9a13e5f5ce 100644
--- a/src/widgets/widgets/qmainwindowlayout_p.h
+++ b/src/widgets/widgets/qmainwindowlayout_p.h
@@ -77,6 +77,37 @@ QT_BEGIN_NAMESPACE
class QToolBar;
class QRubberBand;
+#ifndef QT_NO_DOCKWIDGET
+class QDockWidgetGroupWindow : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit QDockWidgetGroupWindow(QWidget* parent = 0, Qt::WindowFlags f = 0)
+ : QWidget(parent, f) {}
+ QDockAreaLayoutInfo *layoutInfo() const;
+ QDockWidget *topDockWidget() const;
+ void destroyIfEmpty();
+ void adjustFlags();
+protected:
+ bool event(QEvent *) Q_DECL_OVERRIDE;
+ void paintEvent(QPaintEvent*) Q_DECL_OVERRIDE;
+};
+
+// This item will be used in the layout for the gap item. We cannot use QWidgetItem directly
+// because QWidgetItem functions return an empty size for widgets that are are floating.
+class QDockWidgetGroupWindowItem : public QWidgetItem
+{
+public:
+ explicit QDockWidgetGroupWindowItem(QDockWidgetGroupWindow *parent) : QWidgetItem(parent) {}
+ QSize minimumSize() const Q_DECL_OVERRIDE { return lay()->minimumSize(); }
+ QSize maximumSize() const Q_DECL_OVERRIDE { return lay()->maximumSize(); }
+ QSize sizeHint() const Q_DECL_OVERRIDE { return lay()->sizeHint(); }
+
+private:
+ QLayout *lay() const { return const_cast<QDockWidgetGroupWindowItem *>(this)->widget()->layout(); }
+};
+#endif
+
/* 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
@@ -196,10 +227,11 @@ public:
QDockWidget *dockwidget,
Qt::Orientation orientation);
void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
- Qt::DockWidgetArea dockWidgetArea(QDockWidget *dockwidget) const;
+ Qt::DockWidgetArea dockWidgetArea(QWidget* widget) const;
void raise(QDockWidget *widget);
void setVerticalTabsEnabled(bool enabled);
bool restoreDockWidget(QDockWidget *dockwidget);
+ QDockAreaLayoutInfo *dockInfo(QWidget *w);
#ifndef QT_NO_TABBAR
bool _documentMode;
@@ -224,6 +256,8 @@ public:
void setTabShape(QTabWidget::TabShape tabShape);
QTabWidget::TabPosition tabPosition(Qt::DockWidgetArea area) const;
void setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition);
+
+ QDockWidgetGroupWindow *createTabbedDockWindow();
#endif // QT_NO_TABWIDGET
#endif // QT_NO_TABBAR
@@ -268,12 +302,15 @@ public:
QRect currentGapRect;
QWidget *pluggingWidget;
#ifndef QT_NO_RUBBERBAND
- QRubberBand *gapIndicator;
+ QPointer<QRubberBand> gapIndicator;
+#endif
+#ifndef QT_NO_DOCKWIDGET
+ QPointer<QWidget> currentHoveredFloat; // set when dragging over a floating dock widget
#endif
- QList<int> hover(QLayoutItem *widgetItem, const QPoint &mousePos);
+ void hover(QLayoutItem *widgetItem, const QPoint &mousePos);
bool plug(QLayoutItem *widgetItem);
- QLayoutItem *unplug(QWidget *widget);
+ QLayoutItem *unplug(QWidget *widget, bool group = false);
void revert(QLayoutItem *widgetItem);
void updateGapIndicator();
void paintDropIndicator(QPainter *p, QWidget *widget, const QRegion &clip);
@@ -286,6 +323,7 @@ private Q_SLOTS:
#ifndef QT_NO_DOCKWIDGET
#ifndef QT_NO_TABBAR
void tabChanged();
+ void tabMoved(int from, int to);
#endif
#endif
private:
diff --git a/src/widgets/widgets/qmdiarea.h b/src/widgets/widgets/qmdiarea.h
index 461282f8a8..e05535b2af 100644
--- a/src/widgets/widgets/qmdiarea.h
+++ b/src/widgets/widgets/qmdiarea.h
@@ -79,7 +79,7 @@ public:
};
Q_ENUM(ViewMode)
- QMdiArea(QWidget *parent = 0);
+ QMdiArea(QWidget *parent = Q_NULLPTR);
~QMdiArea();
QSize sizeHint() const Q_DECL_OVERRIDE;
@@ -89,7 +89,7 @@ public:
QMdiSubWindow *activeSubWindow() const;
QList<QMdiSubWindow *> subWindowList(WindowOrder order = CreationOrder) const;
- QMdiSubWindow *addSubWindow(QWidget *widget, Qt::WindowFlags flags = 0);
+ QMdiSubWindow *addSubWindow(QWidget *widget, Qt::WindowFlags flags = Qt::WindowFlags());
void removeSubWindow(QWidget *widget);
QBrush background() const;
diff --git a/src/widgets/widgets/qmdiarea_p.h b/src/widgets/widgets/qmdiarea_p.h
index 7f28879f8d..f6bdf61492 100644
--- a/src/widgets/widgets/qmdiarea_p.h
+++ b/src/widgets/widgets/qmdiarea_p.h
@@ -142,8 +142,8 @@ public:
#endif
QMdiAreaTabBar *tabBar;
QList<QMdi::Rearranger *> pendingRearrangements;
- QList< QPointer<QMdiSubWindow> > pendingPlacements;
- QList< QPointer<QMdiSubWindow> > childWindows;
+ QVector< QPointer<QMdiSubWindow> > pendingPlacements;
+ QVector< QPointer<QMdiSubWindow> > childWindows;
QList<int> indicesToActivatedChildren;
QPointer<QMdiSubWindow> active;
QPointer<QMdiSubWindow> aboutToBecomeActive;
diff --git a/src/widgets/widgets/qmdisubwindow.cpp b/src/widgets/widgets/qmdisubwindow.cpp
index 1808030639..c3b31ea5a4 100644
--- a/src/widgets/widgets/qmdisubwindow.cpp
+++ b/src/widgets/widgets/qmdisubwindow.cpp
@@ -1091,8 +1091,8 @@ void QMdiSubWindowPrivate::updateDirtyRegions()
if (!parent)
return;
- foreach (Operation operation, operationMap.keys())
- operationMap.find(operation).value().region = getRegion(operation);
+ for (OperationInfoMap::iterator it = operationMap.begin(), end = operationMap.end(); it != end; ++it)
+ it.value().region = getRegion(it.key());
}
/*!
diff --git a/src/widgets/widgets/qmdisubwindow.h b/src/widgets/widgets/qmdisubwindow.h
index 693477c894..e7d0ca4e44 100644
--- a/src/widgets/widgets/qmdisubwindow.h
+++ b/src/widgets/widgets/qmdisubwindow.h
@@ -60,7 +60,7 @@ public:
};
Q_DECLARE_FLAGS(SubWindowOptions, SubWindowOption)
- QMdiSubWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ QMdiSubWindow(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags());
~QMdiSubWindow();
QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index e81359feac..a7c58ab332 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -102,9 +102,9 @@ class QTornOffMenu : public QMenu
causedPopup.action = ((QTornOffMenu*)p)->d_func()->causedPopup.action;
causedStack = ((QTornOffMenu*)p)->d_func()->calcCausedStack();
}
- QList<QPointer<QWidget> > calcCausedStack() const Q_DECL_OVERRIDE { return causedStack; }
+ QVector<QPointer<QWidget> > calcCausedStack() const Q_DECL_OVERRIDE { return causedStack; }
QPointer<QMenu> causedMenu;
- QList<QPointer<QWidget> > causedStack;
+ QVector<QPointer<QWidget> > causedStack;
};
public:
QTornOffMenu(QMenu *p) : QMenu(*(new QTornOffMenuPrivate(p)))
@@ -236,9 +236,9 @@ QRect QMenuPrivate::popupGeometry(int screen) const
}
}
-QList<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const
+QVector<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const
{
- QList<QPointer<QWidget> > ret;
+ QVector<QPointer<QWidget> > ret;
for(QWidget *widget = causedPopup.widget; widget; ) {
ret.append(widget);
if (QTornOffMenu *qtmenu = qobject_cast<QTornOffMenu*>(widget))
@@ -1110,8 +1110,7 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
handleEnterLeaveEvents(&previousMouseMenu,qobject_cast<QMenu *>(caused));
if(e->type() != QEvent::MouseButtonRelease || mouseDown == caused) {
QMouseEvent new_e(e->type(), cpos, caused->mapTo(caused->topLevelWidget(), cpos), e->screenPos(),
- e->button(), e->buttons(), e->modifiers());
- QGuiApplicationPrivate::setMouseEventSource(&new_e, e->source());
+ e->button(), e->buttons(), e->modifiers(), e->source());
QApplication::sendEvent(caused, &new_e);
return true;
}
@@ -1123,7 +1122,7 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
return false;
}
-void QMenuPrivate::activateCausedStack(const QList<QPointer<QWidget> > &causedStack, QAction *action, QAction::ActionEvent action_e, bool self)
+void QMenuPrivate::activateCausedStack(const QVector<QPointer<QWidget> > &causedStack, QAction *action, QAction::ActionEvent action_e, bool self)
{
QBoolBlocker guard(activationRecursionGuard);
if(self)
@@ -1171,7 +1170,7 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e
/* 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();
+ const QVector<QPointer<QWidget> > causedStack = calcCausedStack();
if (action_e == QAction::Trigger) {
#ifndef QT_NO_WHATSTHIS
if (!inWhatsThisMode)
@@ -1233,7 +1232,7 @@ void QMenuPrivate::_q_actionTriggered()
if (!activationRecursionGuard && actionGuard) {
//in case the action has not been activated by the mouse
//we check the parent hierarchy
- QList< QPointer<QWidget> > list;
+ QVector< QPointer<QWidget> > list;
for(QWidget *widget = q->parentWidget(); widget; ) {
if (qobject_cast<QMenu*>(widget)
#ifndef QT_NO_MENUBAR
@@ -1572,6 +1571,100 @@ QAction *QMenu::addAction(const QString &text, const QObject *receiver, const ch
return action;
}
+/*!\fn QAction *QMenu::addAction(const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 method of the \a receiver. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
+/*!\fn QAction *QMenu::addAction(const QString &text, Functor functor, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 functor. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
+/*!\fn QAction *QMenu::addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 functor. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ If \a context is destroyed, the functor will not be called.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
+/*!\fn QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 method of the \a receiver. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
+/*!\fn QAction *QMenu::addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 functor. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
+/*!\fn QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0)
+
+ \since 5.6
+
+ \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 functor. The function adds the newly created
+ action to the menu's list of actions and returns it.
+
+ If \a context is destroyed, the functor will not be called.
+
+ QMenu takes ownership of the returned QAction.
+*/
+
/*!
\overload
diff --git a/src/widgets/widgets/qmenu.h b/src/widgets/widgets/qmenu.h
index 5dda8b2370..6bbe54186e 100644
--- a/src/widgets/widgets/qmenu.h
+++ b/src/widgets/widgets/qmenu.h
@@ -68,8 +68,8 @@ private:
Q_PROPERTY(bool toolTipsVisible READ toolTipsVisible WRITE setToolTipsVisible)
public:
- explicit QMenu(QWidget *parent = 0);
- explicit QMenu(const QString &title, QWidget *parent = 0);
+ explicit QMenu(QWidget *parent = Q_NULLPTR);
+ explicit QMenu(const QString &title, QWidget *parent = Q_NULLPTR);
~QMenu();
using QWidget::addAction;
@@ -78,6 +78,72 @@ public:
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);
+#ifdef Q_QDOC
+ QAction *addAction(const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QString &text, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0);
+#else
+ // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
+ template<class Obj, typename Func1>
+ inline typename QtPrivate::QEnableIf<!QtPrivate::is_same<const char*, Func1>::value
+ && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::Type
+ addAction(const QString &text, const Obj *object, Func1 slot, const QKeySequence &shortcut = 0)
+ {
+ QAction *result = addAction(text);
+#ifdef QT_NO_SHORTCUT
+ Q_UNUSED(shortcut)
+#else
+ result->setShortcut(shortcut);
+#endif
+ connect(result, &QAction::triggered, object, slot);
+ return result;
+ }
+ // addAction(QString): Connect to a functor or function pointer (without context)
+ template <typename Func1>
+ inline QAction *addAction(const QString &text, Func1 slot, const QKeySequence &shortcut = 0)
+ {
+ QAction *result = addAction(text);
+#ifdef QT_NO_SHORTCUT
+ Q_UNUSED(shortcut)
+#else
+ result->setShortcut(shortcut);
+#endif
+ connect(result, &QAction::triggered, slot);
+ return result;
+ }
+ // addAction(QIcon, QString): Connect to a QObject slot / functor or function pointer (with context)
+ template<class Obj, typename Func1>
+ inline typename QtPrivate::QEnableIf<!QtPrivate::is_same<const char*, Func1>::value
+ && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::Type
+ addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot, const QKeySequence &shortcut = 0)
+ {
+ QAction *result = addAction(actionIcon, text);
+#ifdef QT_NO_SHORTCUT
+ Q_UNUSED(shortcut)
+#else
+ result->setShortcut(shortcut);
+#endif
+ connect(result, &QAction::triggered, object, slot);
+ return result;
+ }
+ // addAction(QIcon, QString): Connect to a functor or function pointer (without context)
+ template <typename Func1>
+ inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot, const QKeySequence &shortcut = 0)
+ {
+ QAction *result = addAction(actionIcon, text);
+#ifdef QT_NO_SHORTCUT
+ Q_UNUSED(shortcut)
+#else
+ result->setShortcut(shortcut);
+#endif
+ connect(result, &QAction::triggered, slot);
+ return result;
+ }
+#endif // !Q_QDOC
+
QAction *addMenu(QMenu *menu);
QMenu *addMenu(const QString &title);
QMenu *addMenu(const QIcon &icon, const QString &title);
@@ -107,14 +173,14 @@ public:
void setActiveAction(QAction *act);
QAction *activeAction() const;
- void popup(const QPoint &pos, QAction *at=0);
+ void popup(const QPoint &pos, QAction *at = Q_NULLPTR);
QAction *exec();
- QAction *exec(const QPoint &pos, QAction *at=0);
+ QAction *exec(const QPoint &pos, QAction *at = Q_NULLPTR);
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
- static QAction *exec(const QList<QAction *> &actions, const QPoint &pos, QAction *at = 0, QWidget *parent = 0);
+ static QAction *exec(const QList<QAction *> &actions, const QPoint &pos, QAction *at = Q_NULLPTR, QWidget *parent = Q_NULLPTR);
#else
- static QAction *exec(QList<QAction*> actions, const QPoint &pos, QAction *at=0, QWidget *parent=0);
+ static QAction *exec(QList<QAction*> actions, const QPoint &pos, QAction *at = Q_NULLPTR, QWidget *parent = Q_NULLPTR);
#endif
QSize sizeHint() const Q_DECL_OVERRIDE;
@@ -189,7 +255,7 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_platformMenuAboutToShow())
protected:
- QMenu(QMenuPrivate &dd, QWidget* parent = 0);
+ QMenu(QMenuPrivate &dd, QWidget* parent = Q_NULLPTR);
private:
Q_DISABLE_COPY(QMenu)
diff --git a/src/widgets/widgets/qmenu_p.h b/src/widgets/widgets/qmenu_p.h
index ab6ca068fb..3acf73af90 100644
--- a/src/widgets/widgets/qmenu_p.h
+++ b/src/widgets/widgets/qmenu_p.h
@@ -422,7 +422,7 @@ public:
QPointer<QWidget> widget;
QPointer<QAction> action;
};
- virtual QList<QPointer<QWidget> > calcCausedStack() const;
+ virtual QVector<QPointer<QWidget> > calcCausedStack() const;
QMenuCaused causedPopup;
void hideUpToMenuBar();
void hideMenu(QMenu *menu);
@@ -450,7 +450,7 @@ public:
//firing of events
void activateAction(QAction *, QAction::ActionEvent, bool self=true);
- void activateCausedStack(const QList<QPointer<QWidget> > &, QAction *, QAction::ActionEvent, bool);
+ void activateCausedStack(const QVector<QPointer<QWidget> > &, QAction *, QAction::ActionEvent, bool);
void _q_actionTriggered();
void _q_actionHovered();
diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp
index 883fd3a945..91775e3862 100644
--- a/src/widgets/widgets/qmenubar.cpp
+++ b/src/widgets/widgets/qmenubar.cpp
@@ -195,7 +195,9 @@ void QMenuBarPrivate::updateGeometries()
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++)
+ const int actionsCount = actions.count();
+ shortcutIndexMap.reserve(actionsCount);
+ for (int i = 0; i < actionsCount; i++)
shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actions.at(i)->text())));
}
#endif
diff --git a/src/widgets/widgets/qmenubar.h b/src/widgets/widgets/qmenubar.h
index 461dec8a94..3b3980c860 100644
--- a/src/widgets/widgets/qmenubar.h
+++ b/src/widgets/widgets/qmenubar.h
@@ -54,7 +54,7 @@ class Q_WIDGETS_EXPORT QMenuBar : public QWidget
Q_PROPERTY(bool nativeMenuBar READ isNativeMenuBar WRITE setNativeMenuBar)
public:
- explicit QMenuBar(QWidget *parent = 0);
+ explicit QMenuBar(QWidget *parent = Q_NULLPTR);
~QMenuBar();
using QWidget::addAction;
diff --git a/src/widgets/widgets/qplaintextedit.cpp b/src/widgets/widgets/qplaintextedit.cpp
index 93c9ddc285..91788a3383 100644
--- a/src/widgets/widgets/qplaintextedit.cpp
+++ b/src/widgets/widgets/qplaintextedit.cpp
@@ -1615,7 +1615,7 @@ void QPlainTextEdit::timerEvent(QTimerEvent *e)
Note that the undo/redo history is cleared by this function.
- \sa toText()
+ \sa toPlainText()
*/
void QPlainTextEdit::setPlainText(const QString &text)
diff --git a/src/widgets/widgets/qplaintextedit.h b/src/widgets/widgets/qplaintextedit.h
index 69bd2ab647..60f1d6e984 100644
--- a/src/widgets/widgets/qplaintextedit.h
+++ b/src/widgets/widgets/qplaintextedit.h
@@ -82,8 +82,8 @@ public:
};
Q_ENUM(LineWrapMode)
- explicit QPlainTextEdit(QWidget *parent = 0);
- explicit QPlainTextEdit(const QString &text, QWidget *parent = 0);
+ explicit QPlainTextEdit(QWidget *parent = Q_NULLPTR);
+ explicit QPlainTextEdit(const QString &text, QWidget *parent = Q_NULLPTR);
virtual ~QPlainTextEdit();
void setDocument(QTextDocument *document);
@@ -136,9 +136,9 @@ public:
void setCenterOnScroll(bool enabled);
bool centerOnScroll() const;
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QRegExp &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif
inline QString toPlainText() const
diff --git a/src/widgets/widgets/qprogressbar.h b/src/widgets/widgets/qprogressbar.h
index 0c3200f82c..e17e01c17b 100644
--- a/src/widgets/widgets/qprogressbar.h
+++ b/src/widgets/widgets/qprogressbar.h
@@ -62,7 +62,7 @@ public:
enum Direction { TopToBottom, BottomToTop };
Q_ENUM(Direction)
- explicit QProgressBar(QWidget *parent = 0);
+ explicit QProgressBar(QWidget *parent = Q_NULLPTR);
~QProgressBar();
int minimum() const;
diff --git a/src/widgets/widgets/qpushbutton.h b/src/widgets/widgets/qpushbutton.h
index 2521c0982e..3db12be380 100644
--- a/src/widgets/widgets/qpushbutton.h
+++ b/src/widgets/widgets/qpushbutton.h
@@ -52,9 +52,9 @@ class Q_WIDGETS_EXPORT QPushButton : public QAbstractButton
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);
+ explicit QPushButton(QWidget *parent = Q_NULLPTR);
+ explicit QPushButton(const QString &text, QWidget *parent = Q_NULLPTR);
+ QPushButton(const QIcon& icon, const QString &text, QWidget *parent = Q_NULLPTR);
~QPushButton();
QSize sizeHint() const Q_DECL_OVERRIDE;
@@ -88,7 +88,7 @@ protected:
void focusInEvent(QFocusEvent *) Q_DECL_OVERRIDE;
void focusOutEvent(QFocusEvent *) Q_DECL_OVERRIDE;
void initStyleOption(QStyleOptionButton *option) const;
- QPushButton(QPushButtonPrivate &dd, QWidget* parent = 0);
+ QPushButton(QPushButtonPrivate &dd, QWidget* parent = Q_NULLPTR);
public:
diff --git a/src/widgets/widgets/qradiobutton.h b/src/widgets/widgets/qradiobutton.h
index f323f5af99..df0b1051bf 100644
--- a/src/widgets/widgets/qradiobutton.h
+++ b/src/widgets/widgets/qradiobutton.h
@@ -47,8 +47,8 @@ class Q_WIDGETS_EXPORT QRadioButton : public QAbstractButton
Q_OBJECT
public:
- explicit QRadioButton(QWidget *parent=0);
- explicit QRadioButton(const QString &text, QWidget *parent=0);
+ explicit QRadioButton(QWidget *parent = Q_NULLPTR);
+ explicit QRadioButton(const QString &text, QWidget *parent = Q_NULLPTR);
~QRadioButton();
QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qrubberband.h b/src/widgets/widgets/qrubberband.h
index 3ff6eb47fa..b0dc14ed98 100644
--- a/src/widgets/widgets/qrubberband.h
+++ b/src/widgets/widgets/qrubberband.h
@@ -50,7 +50,7 @@ class Q_WIDGETS_EXPORT QRubberBand : public QWidget
public:
enum Shape { Line, Rectangle };
- explicit QRubberBand(Shape, QWidget * =0);
+ explicit QRubberBand(Shape, QWidget * = Q_NULLPTR);
~QRubberBand();
Shape shape() const;
diff --git a/src/widgets/widgets/qscrollarea.h b/src/widgets/widgets/qscrollarea.h
index cafb1ec6de..1658236034 100644
--- a/src/widgets/widgets/qscrollarea.h
+++ b/src/widgets/widgets/qscrollarea.h
@@ -50,7 +50,7 @@ class Q_WIDGETS_EXPORT QScrollArea : public QAbstractScrollArea
Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
public:
- explicit QScrollArea(QWidget* parent=0);
+ explicit QScrollArea(QWidget *parent = Q_NULLPTR);
~QScrollArea();
QWidget *widget() const;
@@ -71,7 +71,7 @@ public:
void ensureWidgetVisible(QWidget *childWidget, int xmargin = 50, int ymargin = 50);
protected:
- QScrollArea(QScrollAreaPrivate &dd, QWidget *parent = 0);
+ QScrollArea(QScrollAreaPrivate &dd, QWidget *parent = Q_NULLPTR);
bool event(QEvent *) Q_DECL_OVERRIDE;
bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qscrollbar.h b/src/widgets/widgets/qscrollbar.h
index 5934469045..4af5fb4a55 100644
--- a/src/widgets/widgets/qscrollbar.h
+++ b/src/widgets/widgets/qscrollbar.h
@@ -49,8 +49,8 @@ class Q_WIDGETS_EXPORT QScrollBar : public QAbstractSlider
{
Q_OBJECT
public:
- explicit QScrollBar(QWidget *parent=0);
- explicit QScrollBar(Qt::Orientation, QWidget *parent=0);
+ explicit QScrollBar(QWidget *parent = Q_NULLPTR);
+ explicit QScrollBar(Qt::Orientation, QWidget *parent = Q_NULLPTR);
~QScrollBar();
QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qslider.h b/src/widgets/widgets/qslider.h
index 3a528382a7..801a684fdf 100644
--- a/src/widgets/widgets/qslider.h
+++ b/src/widgets/widgets/qslider.h
@@ -61,8 +61,8 @@ public:
};
Q_ENUM(TickPosition)
- explicit QSlider(QWidget *parent = 0);
- explicit QSlider(Qt::Orientation orientation, QWidget *parent = 0);
+ explicit QSlider(QWidget *parent = Q_NULLPTR);
+ explicit QSlider(Qt::Orientation orientation, QWidget *parent = Q_NULLPTR);
~QSlider();
diff --git a/src/widgets/widgets/qspinbox.h b/src/widgets/widgets/qspinbox.h
index 606206d4f0..066fe88562 100644
--- a/src/widgets/widgets/qspinbox.h
+++ b/src/widgets/widgets/qspinbox.h
@@ -56,7 +56,7 @@ class Q_WIDGETS_EXPORT QSpinBox : public QAbstractSpinBox
Q_PROPERTY(int displayIntegerBase READ displayIntegerBase WRITE setDisplayIntegerBase)
public:
- explicit QSpinBox(QWidget *parent = 0);
+ explicit QSpinBox(QWidget *parent = Q_NULLPTR);
~QSpinBox();
int value() const;
@@ -117,7 +117,7 @@ class Q_WIDGETS_EXPORT QDoubleSpinBox : public QAbstractSpinBox
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);
+ explicit QDoubleSpinBox(QWidget *parent = Q_NULLPTR);
~QDoubleSpinBox();
double value() const;
diff --git a/src/widgets/widgets/qsplashscreen.h b/src/widgets/widgets/qsplashscreen.h
index 58b8484f4c..dec24a5608 100644
--- a/src/widgets/widgets/qsplashscreen.h
+++ b/src/widgets/widgets/qsplashscreen.h
@@ -47,8 +47,8 @@ class Q_WIDGETS_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);
+ explicit QSplashScreen(const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = Qt::WindowFlags());
+ QSplashScreen(QWidget *parent, const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = Qt::WindowFlags());
virtual ~QSplashScreen();
void setPixmap(const QPixmap &pixmap);
diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp
index de6e45234c..c2081c15f8 100644
--- a/src/widgets/widgets/qsplitter.cpp
+++ b/src/widgets/widgets/qsplitter.cpp
@@ -58,6 +58,10 @@ QT_BEGIN_NAMESPACE
//#define QSPLITTER_DEBUG
+QSplitterPrivate::~QSplitterPrivate()
+{
+}
+
/*!
\class QSplitterHandle
\brief The QSplitterHandle class provides handle functionality for the splitter.
@@ -1498,8 +1502,11 @@ QList<int> QSplitter::sizes() const
Q_D(const QSplitter);
ensurePolished();
+ const int numSizes = d->list.size();
QList<int> list;
- for (int i = 0; i < d->list.size(); ++i) {
+ list.reserve(numSizes);
+
+ for (int i = 0; i < numSizes; ++i) {
QSplitterLayoutStruct *s = d->list.at(i);
list.append(d->pick(s->rect.size()));
}
@@ -1594,8 +1601,10 @@ QByteArray QSplitter::saveState() const
stream << qint32(SplitterMagic);
stream << qint32(version);
+ const int numSizes = d->list.size();
QList<int> list;
- for (int i = 0; i < d->list.size(); ++i) {
+ list.reserve(numSizes);
+ for (int i = 0; i < numSizes; ++i) {
QSplitterLayoutStruct *s = d->list.at(i);
list.append(s->sizer);
}
diff --git a/src/widgets/widgets/qsplitter.h b/src/widgets/widgets/qsplitter.h
index 4da92acd22..84010c236b 100644
--- a/src/widgets/widgets/qsplitter.h
+++ b/src/widgets/widgets/qsplitter.h
@@ -58,8 +58,8 @@ class Q_WIDGETS_EXPORT QSplitter : public QFrame
Q_PROPERTY(bool childrenCollapsible READ childrenCollapsible WRITE setChildrenCollapsible)
public:
- explicit QSplitter(QWidget* parent = 0);
- explicit QSplitter(Qt::Orientation, QWidget* parent = 0);
+ explicit QSplitter(QWidget* parent = Q_NULLPTR);
+ explicit QSplitter(Qt::Orientation, QWidget* parent = Q_NULLPTR);
~QSplitter();
void addWidget(QWidget *widget);
diff --git a/src/widgets/widgets/qsplitter_p.h b/src/widgets/widgets/qsplitter_p.h
index a45f776da1..890bd535ec 100644
--- a/src/widgets/widgets/qsplitter_p.h
+++ b/src/widgets/widgets/qsplitter_p.h
@@ -76,6 +76,7 @@ class QSplitterPrivate : public QFramePrivate
public:
QSplitterPrivate() : rubberBand(0), opaque(true), firstShow(true),
childrenCollapsible(true), compatMode(false), handleWidth(-1), blockChildAdd(false), opaqueResizeSet(false) {}
+ ~QSplitterPrivate();
QPointer<QRubberBand> rubberBand;
mutable QList<QSplitterLayoutStruct *> list;
diff --git a/src/widgets/widgets/qstackedwidget.h b/src/widgets/widgets/qstackedwidget.h
index 4267d8241f..9fcdf80833 100644
--- a/src/widgets/widgets/qstackedwidget.h
+++ b/src/widgets/widgets/qstackedwidget.h
@@ -50,7 +50,7 @@ class Q_WIDGETS_EXPORT QStackedWidget : public QFrame
Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
Q_PROPERTY(int count READ count)
public:
- explicit QStackedWidget(QWidget *parent=0);
+ explicit QStackedWidget(QWidget *parent = Q_NULLPTR);
~QStackedWidget();
int addWidget(QWidget *w);
diff --git a/src/widgets/widgets/qstatusbar.h b/src/widgets/widgets/qstatusbar.h
index 42248d7958..92785aa4c4 100644
--- a/src/widgets/widgets/qstatusbar.h
+++ b/src/widgets/widgets/qstatusbar.h
@@ -50,7 +50,7 @@ class Q_WIDGETS_EXPORT QStatusBar: public QWidget
Q_PROPERTY(bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled)
public:
- explicit QStatusBar(QWidget* parent=0);
+ explicit QStatusBar(QWidget *parent = Q_NULLPTR);
virtual ~QStatusBar();
void addWidget(QWidget *widget, int stretch = 0);
diff --git a/src/widgets/widgets/qtabbar.h b/src/widgets/widgets/qtabbar.h
index 6d8bdb0c86..94a83142b0 100644
--- a/src/widgets/widgets/qtabbar.h
+++ b/src/widgets/widgets/qtabbar.h
@@ -65,7 +65,7 @@ class Q_WIDGETS_EXPORT QTabBar: public QWidget
Q_PROPERTY(bool changeCurrentOnDrag READ changeCurrentOnDrag WRITE setChangeCurrentOnDrag)
public:
- explicit QTabBar(QWidget* parent=0);
+ explicit QTabBar(QWidget *parent = Q_NULLPTR);
~QTabBar();
enum Shape { RoundedNorth, RoundedSouth, RoundedWest, RoundedEast,
diff --git a/src/widgets/widgets/qtabwidget.h b/src/widgets/widgets/qtabwidget.h
index 702563127d..f12d584475 100644
--- a/src/widgets/widgets/qtabwidget.h
+++ b/src/widgets/widgets/qtabwidget.h
@@ -62,7 +62,7 @@ class Q_WIDGETS_EXPORT QTabWidget : public QWidget
Q_PROPERTY(bool tabBarAutoHide READ tabBarAutoHide WRITE setTabBarAutoHide)
public:
- explicit QTabWidget(QWidget *parent = 0);
+ explicit QTabWidget(QWidget *parent = Q_NULLPTR);
~QTabWidget();
int addTab(QWidget *widget, const QString &);
diff --git a/src/widgets/widgets/qtextbrowser.cpp b/src/widgets/widgets/qtextbrowser.cpp
index 9bf305a055..2c073342b0 100644
--- a/src/widgets/widgets/qtextbrowser.cpp
+++ b/src/widgets/widgets/qtextbrowser.cpp
@@ -139,6 +139,7 @@ public:
int lastKeypadScrollValue;
#endif
};
+Q_DECLARE_TYPEINFO(QTextBrowserPrivate::HistoryEntry, Q_MOVABLE_TYPE);
QString QTextBrowserPrivate::findFile(const QUrl &name) const
{
diff --git a/src/widgets/widgets/qtextbrowser.h b/src/widgets/widgets/qtextbrowser.h
index 4d4d9f4880..339814e948 100644
--- a/src/widgets/widgets/qtextbrowser.h
+++ b/src/widgets/widgets/qtextbrowser.h
@@ -57,7 +57,7 @@ class Q_WIDGETS_EXPORT QTextBrowser : public QTextEdit
Q_PROPERTY(bool openLinks READ openLinks WRITE setOpenLinks)
public:
- explicit QTextBrowser(QWidget* parent = 0);
+ explicit QTextBrowser(QWidget* parent = Q_NULLPTR);
virtual ~QTextBrowser();
QUrl source() const;
diff --git a/src/widgets/widgets/qtextedit.h b/src/widgets/widgets/qtextedit.h
index 689f45bea9..88b7444daa 100644
--- a/src/widgets/widgets/qtextedit.h
+++ b/src/widgets/widgets/qtextedit.h
@@ -94,8 +94,8 @@ public:
Q_DECLARE_FLAGS(AutoFormatting, AutoFormattingFlag)
- explicit QTextEdit(QWidget *parent = 0);
- explicit QTextEdit(const QString &text, QWidget *parent = 0);
+ explicit QTextEdit(QWidget *parent = Q_NULLPTR);
+ explicit QTextEdit(const QString &text, QWidget *parent = Q_NULLPTR);
virtual ~QTextEdit();
void setDocument(QTextDocument *document);
@@ -153,9 +153,9 @@ public:
QTextOption::WrapMode wordWrapMode() const;
void setWordWrapMode(QTextOption::WrapMode policy);
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QRegExp &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif
QString toPlainText() const;
diff --git a/src/widgets/widgets/qtoolbar.cpp b/src/widgets/widgets/qtoolbar.cpp
index ecba6f1974..1e4a39088c 100644
--- a/src/widgets/widgets/qtoolbar.cpp
+++ b/src/widgets/widgets/qtoolbar.cpp
@@ -793,6 +793,82 @@ QAction *QToolBar::addAction(const QIcon &icon, const QString &text,
return action;
}
+/*!\fn QAction *QToolBar::addAction(const QString &text, const QObject *receiver, PointerToMemberFunction method)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a text. This action is added to
+ the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a method of the \a receiver.
+*/
+
+/*!\fn QAction *QToolBar::addAction(const QString &text, Functor functor)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a text. This action is added to
+ the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a functor.
+*/
+
+/*!\fn QAction *QToolBar::addAction(const QString &text, const QObject *context, Functor functor)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a text. This action is added to
+ the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a functor.
+
+ If \a context is destroyed, the functor will not be called.
+*/
+
+/*!\fn QAction *QToolBar::addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a icon and \a text. This
+ action is added to the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a method of the \a receiver.
+*/
+
+/*!\fn QAction *QToolBar::addAction(const QIcon &icon, const QString &text, Functor functor)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a icon and \a text. This
+ action is added to the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a functor.
+*/
+
+/*!\fn QAction *QToolBar::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor)
+
+ \since 5.6
+
+ \overload
+
+ Creates a new action with the given \a icon and \a text. This
+ action is added to the end of the toolbar. The action's
+ \l{QAction::triggered()}{triggered()} signal is connected to the
+ \a functor.
+
+ If \a context is destroyed, the functor will not be called.
+*/
+
/*!
Adds a separator to the end of the toolbar.
diff --git a/src/widgets/widgets/qtoolbar.h b/src/widgets/widgets/qtoolbar.h
index f925577646..9eeb7ccd71 100644
--- a/src/widgets/widgets/qtoolbar.h
+++ b/src/widgets/widgets/qtoolbar.h
@@ -34,6 +34,7 @@
#ifndef QDYNAMICTOOLBAR_H
#define QDYNAMICTOOLBAR_H
+#include <QtWidgets/qaction.h>
#include <QtWidgets/qwidget.h>
QT_BEGIN_NAMESPACE
@@ -68,8 +69,8 @@ class Q_WIDGETS_EXPORT QToolBar : public QWidget
Q_PROPERTY(bool floatable READ isFloatable WRITE setFloatable)
public:
- explicit QToolBar(const QString &title, QWidget *parent = 0);
- explicit QToolBar(QWidget *parent = 0);
+ explicit QToolBar(const QString &title, QWidget *parent = Q_NULLPTR);
+ explicit QToolBar(QWidget *parent = Q_NULLPTR);
~QToolBar();
void setMovable(bool movable);
@@ -92,6 +93,51 @@ public:
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);
+#ifdef Q_QDOC
+ QAction *addAction(const QString &text, const QObject *receiver, PointerToMemberFunction method);
+ QAction *addAction(const QString &text, Functor functor);
+ QAction *addAction(const QString &text, const QObject *context, Functor functor);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method);
+ QAction *addAction(const QIcon &icon, const QString &text, Functor functor);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor);
+#else
+ // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
+ template<class Obj, typename Func1>
+ inline typename QtPrivate::QEnableIf<!QtPrivate::is_same<const char*, Func1>::value
+ && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::Type
+ addAction(const QString &text, const Obj *object, Func1 slot)
+ {
+ QAction *result = addAction(text);
+ connect(result, &QAction::triggered, object, slot);
+ return result;
+ }
+ // addAction(QString): Connect to a functor or function pointer (without context)
+ template <typename Func1>
+ inline QAction *addAction(const QString &text, Func1 slot)
+ {
+ QAction *result = addAction(text);
+ connect(result, &QAction::triggered, slot);
+ return result;
+ }
+ // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
+ template<class Obj, typename Func1>
+ inline typename QtPrivate::QEnableIf<!QtPrivate::is_same<const char*, Func1>::value
+ && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::Type
+ addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot)
+ {
+ QAction *result = addAction(actionIcon, text);
+ connect(result, &QAction::triggered, object, slot);
+ return result;
+ }
+ // addAction(QIcon, QString): Connect to a functor or function pointer (without context)
+ template <typename Func1>
+ inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot)
+ {
+ QAction *result = addAction(actionIcon, text);
+ connect(result, &QAction::triggered, slot);
+ return result;
+ }
+#endif // !Q_QDOC
QAction *addSeparator();
QAction *insertSeparator(QAction *before);
diff --git a/src/widgets/widgets/qtoolbox.h b/src/widgets/widgets/qtoolbox.h
index cff5ae09ae..42b06e205c 100644
--- a/src/widgets/widgets/qtoolbox.h
+++ b/src/widgets/widgets/qtoolbox.h
@@ -51,7 +51,7 @@ class Q_WIDGETS_EXPORT QToolBox : public QFrame
Q_PROPERTY(int count READ count)
public:
- explicit QToolBox(QWidget *parent = 0, Qt::WindowFlags f = 0);
+ explicit QToolBox(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
~QToolBox();
int addItem(QWidget *widget, const QString &text);
diff --git a/src/widgets/widgets/qtoolbutton.h b/src/widgets/widgets/qtoolbutton.h
index 69ad032324..c76f58577b 100644
--- a/src/widgets/widgets/qtoolbutton.h
+++ b/src/widgets/widgets/qtoolbutton.h
@@ -64,7 +64,7 @@ public:
};
Q_ENUM(ToolButtonPopupMode)
- explicit QToolButton(QWidget * parent=0);
+ explicit QToolButton(QWidget *parent = Q_NULLPTR);
~QToolButton();
QSize sizeHint() const Q_DECL_OVERRIDE;
diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp
index 759e41a5fa..436937be72 100644
--- a/src/widgets/widgets/qwidgetlinecontrol.cpp
+++ b/src/widgets/widgets/qwidgetlinecontrol.cpp
@@ -189,7 +189,7 @@ void QWidgetLineControl::commitPreedit()
m_preeditCursor = 0;
setPreeditArea(-1, QString());
- m_textLayout.clearAdditionalFormats();
+ m_textLayout.clearFormats();
updateDisplayText(/*force*/ true);
#endif
}
@@ -557,7 +557,8 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
const int oldPreeditCursor = m_preeditCursor;
m_preeditCursor = event->preeditString().length();
m_hideCursor = false;
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
+ formats.reserve(event->attributes().size());
for (int i = 0; i < event->attributes().size(); ++i) {
const QInputMethodEvent::Attribute &a = event->attributes().at(i);
if (a.type == QInputMethodEvent::Cursor) {
@@ -574,7 +575,7 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
}
}
}
- m_textLayout.setAdditionalFormats(formats);
+ m_textLayout.setFormats(formats);
updateDisplayText(/*force*/ true);
if (cursorPositionChanged)
emitCursorPositionChanged();
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index 72007ac3e8..deca002bf5 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -883,7 +883,8 @@ void QWidgetTextControl::setTextCursor(const QTextCursor &cursor)
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->cursorOn = d->hasFocus
+ && (d->interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
d->_q_updateCurrentCharFormatAndSelection();
ensureCursorVisible();
d->repaintOldAndNewSelection(oldSelection);
@@ -2028,7 +2029,8 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
QTextLayout *layout = block.layout();
if (isGettingInput)
layout->setPreeditArea(cursor.position() - block.position(), e->preeditString());
- QList<QTextLayout::FormatRange> overrides;
+ QVector<QTextLayout::FormatRange> overrides;
+ overrides.reserve(e->attributes().size());
const int oldPreeditCursor = preeditCursor;
preeditCursor = e->preeditString().length();
hideCursor = false;
@@ -2048,7 +2050,7 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
}
}
}
- layout->setAdditionalFormats(overrides);
+ layout->setFormats(overrides);
cursor.endEditBlock();
@@ -2138,7 +2140,7 @@ void QWidgetTextControlPrivate::focusEvent(QFocusEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
if (!QApplication::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason))) {
#endif
- cursorOn = (interactionFlags & Qt::TextSelectableByKeyboard);
+ cursorOn = (interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
if (interactionFlags & Qt::TextEditable) {
setBlinkingCursorEnabled(true);
}
@@ -2437,10 +2439,13 @@ QList<QTextEdit::ExtraSelection> QWidgetTextControl::extraSelections() const
{
Q_D(const QWidgetTextControl);
QList<QTextEdit::ExtraSelection> selections;
- for (int i = 0; i < d->extraSelections.count(); ++i) {
+ const int numExtraSelections = d->extraSelections.count();
+ selections.reserve(numExtraSelections);
+ for (int i = 0; i < numExtraSelections; ++i) {
QTextEdit::ExtraSelection sel;
- sel.cursor = d->extraSelections.at(i).cursor;
- sel.format = d->extraSelections.at(i).format;
+ const QAbstractTextDocumentLayout::Selection &sel2 = d->extraSelections.at(i);
+ sel.cursor = sel2.cursor;
+ sel.format = sel2.format;
selections.append(sel);
}
return selections;
@@ -2877,7 +2882,7 @@ void QWidgetTextControlPrivate::commitPreedit()
QTextBlock block = cursor.block();
QTextLayout *layout = block.layout();
layout->setPreeditArea(-1, QString());
- layout->clearAdditionalFormats();
+ layout->clearFormats();
cursor.endEditBlock();
}
diff --git a/src/winmain/qtmain_winrt.cpp b/src/winmain/qtmain_winrt.cpp
index 141e3ed135..d9f8c8f991 100644
--- a/src/winmain/qtmain_winrt.cpp
+++ b/src/winmain/qtmain_winrt.cpp
@@ -49,38 +49,44 @@
entry point within the newly created GUI thread.
*/
+#if _MSC_VER < 1900
#include <new.h>
typedef struct
{
int newmode;
} _startupinfo;
+#endif // _MSC_VER < 1900
extern "C" {
+#if _MSC_VER < 1900
int __getmainargs(int *argc, char ***argv, char ***env, int expandWildcards, _startupinfo *info);
+#endif
int main(int, char **);
}
#include <qbytearray.h>
#include <qstring.h>
-#include <qlist.h>
-#include <qvector.h>
#include <qdir.h>
#include <qstandardpaths.h>
+#include <qfunctions_winrt.h>
#include <wrl.h>
#include <Windows.ApplicationModel.core.h>
+#include <windows.ui.xaml.h>
+#include <windows.ui.xaml.controls.h>
using namespace ABI::Windows::ApplicationModel;
+using namespace ABI::Windows::ApplicationModel::Activation;
+using namespace ABI::Windows::ApplicationModel::Core;
using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::UI;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
#define qHString(x) Wrappers::HString::MakeReference(x).Get()
#define CoreApplicationClass RuntimeClass_Windows_ApplicationModel_Core_CoreApplication
-typedef ITypedEventHandler<Core::CoreApplicationView *, Activation::IActivatedEventArgs *> ActivatedHandler;
-
-static int g_mainExitCode;
+typedef ITypedEventHandler<CoreApplicationView *, Activation::IActivatedEventArgs *> ActivatedHandler;
static QtMessageHandler defaultMessageHandler;
static void devMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
@@ -103,53 +109,112 @@ static void devMessageHandler(QtMsgType type, const QMessageLogContext &context,
defaultMessageHandler(type, context, message);
}
-class AppContainer : public Microsoft::WRL::RuntimeClass<Core::IFrameworkView>
+class AppContainer : public RuntimeClass<Xaml::IApplicationOverrides>
{
public:
- AppContainer(int argc, char *argv[]) : m_argc(argc), m_deleteArgv0(false)
+ AppContainer()
{
- m_argv.reserve(argc);
- for (int i = 0; i < argc; ++i) {
- // Workaround for empty argv[0] which occurs when WMAppManifest's ImageParams is used
- // The second argument is taken to be the executable
- if (i == 0 && argc >= 2 && !qstrlen(argv[0])) {
- const QByteArray argv0 = QDir::current()
- .absoluteFilePath(QString::fromLatin1(argv[1])).toUtf8();
- m_argv.append(qstrdup(argv0.constData()));
- m_argc -= 1;
- m_deleteArgv0 = true;
- ++i;
- continue;
- }
- m_argv.append(argv[i]);
- }
+ ComPtr<Xaml::IApplicationFactory> applicationFactory;
+ HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Application).Get(),
+ IID_PPV_ARGS(&applicationFactory));
+ Q_ASSERT_SUCCEEDED(hr);
+
+ hr = applicationFactory->CreateInstance(this, &base, &core);
+ RETURN_VOID_IF_FAILED("Failed to create application container instance");
}
~AppContainer()
{
- if (m_deleteArgv0)
- delete[] m_argv[0];
- for (int i = m_argc; i < m_argv.size(); ++i)
- delete[] m_argv[i];
}
- // IFrameworkView Methods
- HRESULT __stdcall Initialize(Core::ICoreApplicationView *view)
+ int exec(int argc, char **argv)
{
- view->add_Activated(Callback<ActivatedHandler>(this, &AppContainer::onActivated).Get(),
- &m_activationToken);
- return S_OK;
+ args.reserve(argc);
+ for (int i = 0; i < argc; ++i)
+ args.append(argv[i]);
+
+ mainThread = CreateThread(NULL, 0, [](void *param) -> DWORD {
+ AppContainer *app = reinterpret_cast<AppContainer *>(param);
+ int argc = app->args.count();
+ char **argv = app->args.data();
+ return main(argc, argv);
+ }, this, CREATE_SUSPENDED, nullptr);
+
+ HRESULT hr;
+ ComPtr<Xaml::IApplicationStatics> appStatics;
+ hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Application).Get(),
+ IID_PPV_ARGS(&appStatics));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = appStatics->Start(Callback<Xaml::IApplicationInitializationCallback>([](Xaml::IApplicationInitializationCallbackParams *) {
+ return S_OK;
+ }).Get());
+ Q_ASSERT_SUCCEEDED(hr);
+
+ DWORD exitCode;
+ GetExitCodeThread(mainThread, &exitCode);
+ return exitCode;
+ }
+
+private:
+ HRESULT __stdcall OnActivated(IActivatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ return base->OnActivated(args);
}
- HRESULT __stdcall SetWindow(ABI::Windows::UI::Core::ICoreWindow *) { return S_OK; }
- HRESULT __stdcall Load(HSTRING) { return S_OK; }
- HRESULT __stdcall Run()
+
+ HRESULT __stdcall OnLaunched(ILaunchActivatedEventArgs *launchArgs) Q_DECL_OVERRIDE
{
+#if _MSC_VER >= 1900
+ commandLine = QString::fromWCharArray(GetCommandLine()).toUtf8();
+#endif
+ HString launchCommandLine;
+ launchArgs->get_Arguments(launchCommandLine.GetAddressOf());
+ if (launchCommandLine.IsValid()) {
+ quint32 launchCommandLineLength;
+ const wchar_t *launchCommandLineBuffer = launchCommandLine.GetRawBuffer(&launchCommandLineLength);
+ if (!commandLine.isEmpty() && launchCommandLineLength)
+ commandLine += ' ';
+ if (launchCommandLineLength)
+ commandLine += QString::fromWCharArray(launchCommandLineBuffer, launchCommandLineLength).toUtf8();
+ }
+ if (!commandLine.isEmpty())
+ args.append(commandLine.data());
+
+ bool quote = false;
+ bool escape = false;
+ for (int i = 0; i < commandLine.size(); ++i) {
+ switch (commandLine.at(i)) {
+ case '\\':
+ escape = true;
+ break;
+ case '"':
+ if (escape) {
+ escape = false;
+ break;
+ }
+ quote = !quote;
+ commandLine[i] = '\0';
+ break;
+ case ' ':
+ if (quote)
+ break;
+ commandLine[i] = '\0';
+ if (args.last()[0] != '\0')
+ args.append(commandLine.data() + i + 1);
+ // fall through
+ default:
+ if (args.last()[0] == '\0')
+ args.last() = commandLine.data() + i;
+ escape = false; // only quotes are escaped
+ break;
+ }
+ }
+
bool develMode = false;
bool debugWait = false;
- foreach (const QByteArray &arg, m_argv) {
- if (arg == "-qdevel")
+ foreach (const char *arg, args) {
+ if (strcmp(arg, "-qdevel") == 0)
develMode = true;
- if (arg == "-qdebug")
+ if (strcmp(arg, "-qdebug") == 0)
debugWait = true;
}
if (develMode) {
@@ -173,98 +238,70 @@ public:
while (!IsDebuggerPresent())
WaitForSingleObjectEx(GetCurrentThread(), 1, true);
}
- g_mainExitCode = main(m_argv.count(), m_argv.data());
+
+ ResumeThread(mainThread);
return S_OK;
}
- HRESULT __stdcall Uninitialize() { return S_OK; }
-private:
- // Activation handler
- HRESULT onActivated(Core::ICoreApplicationView *, Activation::IActivatedEventArgs *args)
+ HRESULT __stdcall OnFileActivated(IFileActivatedEventArgs *args) Q_DECL_OVERRIDE
{
- Activation::ILaunchActivatedEventArgs *launchArgs;
- if (SUCCEEDED(args->QueryInterface(&launchArgs))) {
- for (int i = m_argc; i < m_argv.size(); ++i)
- delete[] m_argv[i];
- m_argv.resize(m_argc);
- HString arguments;
- launchArgs->get_Arguments(arguments.GetAddressOf());
- if (arguments.IsValid()) {
- foreach (const QByteArray &arg, QString::fromWCharArray(
- arguments.GetRawBuffer(nullptr)).toLocal8Bit().split(' ')) {
- m_argv.append(qstrdup(arg.constData()));
- }
- }
- }
+ Q_UNUSED(args);
return S_OK;
}
- int m_argc;
- QVector<char *> m_argv;
- bool m_deleteArgv0;
- EventRegistrationToken m_activationToken;
-};
+ HRESULT __stdcall OnSearchActivated(ISearchActivatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ Q_UNUSED(args);
+ return S_OK;
+ }
-class AppViewSource : public Microsoft::WRL::RuntimeClass<Core::IFrameworkViewSource>
-{
-public:
- AppViewSource(int argc, char **argv) : m_argc(argc), m_argv(argv) { }
- HRESULT __stdcall CreateView(Core::IFrameworkView **frameworkView)
+ HRESULT __stdcall OnShareTargetActivated(IShareTargetActivatedEventArgs *args) Q_DECL_OVERRIDE
{
- return (*frameworkView = Make<AppContainer>(m_argc, m_argv).Detach()) ? S_OK : E_OUTOFMEMORY;
+ Q_UNUSED(args);
+ return S_OK;
}
-private:
- int m_argc;
- char **m_argv;
+
+ HRESULT __stdcall OnFileOpenPickerActivated(IFileOpenPickerActivatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ Q_UNUSED(args);
+ return S_OK;
+ }
+
+ HRESULT __stdcall OnFileSavePickerActivated(IFileSavePickerActivatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ Q_UNUSED(args);
+ return S_OK;
+ }
+
+ HRESULT __stdcall OnCachedFileUpdaterActivated(ICachedFileUpdaterActivatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ Q_UNUSED(args);
+ return S_OK;
+ }
+
+ HRESULT __stdcall OnWindowCreated(Xaml::IWindowCreatedEventArgs *args) Q_DECL_OVERRIDE
+ {
+ Q_UNUSED(args);
+ return S_OK;
+ }
+
+ ComPtr<Xaml::IApplicationOverrides> base;
+ ComPtr<Xaml::IApplication> core;
+ QByteArray commandLine;
+ QVarLengthArray<char *> args;
+ HANDLE mainThread;
};
// Main entry point for Appx containers
int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
-#if _MSC_VER < 1900
int argc = 0;
- char **argv, **env;
+ char **argv = 0, **env = 0;
+#if _MSC_VER < 1900
_startupinfo info = { _query_new_mode() };
if (int init = __getmainargs(&argc, &argv, &env, false, &info))
return init;
-#else
- QByteArray commandLine = QString::fromWCharArray(GetCommandLine()).toUtf8();
- QVarLengthArray<char *> args;
- args.append(commandLine.data());
- bool quote = false;
- bool escape = false;
- for (int i = 0; i < commandLine.size(); ++i) {
- switch (commandLine.at(i)) {
- case '\\':
- escape = true;
- break;
- case '"':
- if (escape) {
- escape = false;
- break;
- }
- quote = !quote;
- commandLine[i] = '\0';
- break;
- case ' ':
- if (quote)
- break;
- commandLine[i] = '\0';
- if (args.last()[0] != '\0')
- args.append(commandLine.data() + i + 1);
- // fall through
- default:
- if (args.last()[0] == '\0')
- args.last() = commandLine.data() + i;
- escape = false; // only quotes are escaped
- break;
- }
- }
- int argc = args.size();
- char **argv = args.data();
- char **env = Q_NULLPTR;
#endif // _MSC_VER >= 1900
-
for (int i = 0; env && env[i]; ++i) {
QByteArray var(env[i]);
int split = var.indexOf('=');
@@ -275,10 +312,6 @@ int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
if (FAILED(RoInitialize(RO_INIT_MULTITHREADED)))
return 1;
- Core::ICoreApplication *appFactory;
- if (FAILED(RoGetActivationFactory(qHString(CoreApplicationClass), IID_PPV_ARGS(&appFactory))))
- return 2;
-
- appFactory->Run(Make<AppViewSource>(argc, argv).Get());
- return g_mainExitCode;
+ ComPtr<AppContainer> app = Make<AppContainer>();
+ return app->exec(argc, argv);
}
diff --git a/src/xml/dom/qdom.h b/src/xml/dom/qdom.h
index 5a83659e5c..f2bcf83e2b 100644
--- a/src/xml/dom/qdom.h
+++ b/src/xml/dom/qdom.h
@@ -329,14 +329,14 @@ public:
inline QDomNode::NodeType nodeType() const { return DocumentNode; }
// Qt extensions
- bool setContent(const QByteArray& text, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(const QString& text, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(QIODevice* dev, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(QXmlInputSource *source, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(const QByteArray& text, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(const QString& text, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(QIODevice* dev, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
- bool setContent(QXmlInputSource *source, QXmlReader *reader, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
+ bool setContent(const QByteArray& text, bool namespaceProcessing, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(const QString& text, bool namespaceProcessing, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(QIODevice* dev, bool namespaceProcessing, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(QXmlInputSource *source, bool namespaceProcessing, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(const QByteArray& text, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(const QString& text, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(QIODevice* dev, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
+ bool setContent(QXmlInputSource *source, QXmlReader *reader, QString *errorMsg=Q_NULLPTR, int *errorLine=Q_NULLPTR, int *errorColumn=Q_NULLPTR );
// Qt extensions
QString toString(int = 1) const;
diff --git a/src/xml/sax/qxml.h b/src/xml/sax/qxml.h
index d7285fc289..6bb9bfbe9c 100644
--- a/src/xml/sax/qxml.h
+++ b/src/xml/sax/qxml.h
@@ -201,10 +201,10 @@ class Q_XML_EXPORT QXmlReader
{
public:
virtual ~QXmlReader() {}
- virtual bool feature(const QString& name, bool *ok = 0) const = 0;
+ virtual bool feature(const QString& name, bool *ok = Q_NULLPTR) const = 0;
virtual void setFeature(const QString& name, bool value) = 0;
virtual bool hasFeature(const QString& name) const = 0;
- virtual void* property(const QString& name, bool *ok = 0) const = 0;
+ virtual void* property(const QString& name, bool *ok = Q_NULLPTR) const = 0;
virtual void setProperty(const QString& name, void* value) = 0;
virtual bool hasProperty(const QString& name) const = 0;
virtual void setEntityResolver(QXmlEntityResolver* handler) = 0;
@@ -229,11 +229,11 @@ public:
QXmlSimpleReader();
virtual ~QXmlSimpleReader();
- bool feature(const QString& name, bool *ok = 0) const Q_DECL_OVERRIDE;
+ bool feature(const QString& name, bool *ok = Q_NULLPTR) const Q_DECL_OVERRIDE;
void setFeature(const QString& name, bool value) Q_DECL_OVERRIDE;
bool hasFeature(const QString& name) const Q_DECL_OVERRIDE;
- void* property(const QString& name, bool *ok = 0) const Q_DECL_OVERRIDE;
+ void* property(const QString& name, bool *ok = Q_NULLPTR) const Q_DECL_OVERRIDE;
void setProperty(const QString& name, void* value) Q_DECL_OVERRIDE;
bool hasProperty(const QString& name) const Q_DECL_OVERRIDE;
diff --git a/src/xml/sax/qxml_p.h b/src/xml/sax/qxml_p.h
index 7712b5760c..013c2618a3 100644
--- a/src/xml/sax/qxml_p.h
+++ b/src/xml/sax/qxml_p.h
@@ -104,6 +104,7 @@ private:
QString value;
int index;
};
+ friend class QTypeInfo<XmlRef>;
QStack<XmlRef> xmlRefStack;
// used for standalone declaration
@@ -166,6 +167,7 @@ private:
ParseFunction function;
int state;
};
+ friend class QTypeInfo<ParseState>;
QStack<ParseState> *parseStack;
// used in parseProlog()
@@ -294,6 +296,8 @@ private:
friend class QXmlSimpleReaderLocator;
friend class QDomHandler;
};
+Q_DECLARE_TYPEINFO(QXmlSimpleReaderPrivate::ParseState, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QXmlSimpleReaderPrivate::XmlRef, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
diff --git a/sync.profile b/sync.profile
index bf29ca6e26..1700d94fff 100644
--- a/sync.profile
+++ b/sync.profile
@@ -50,7 +50,7 @@
}
);
-@qpa_headers = ( qr/^qplatform/, qr/^qwindowsystem/ );
+@qpa_headers = ( qr/^(?!qplatformheaderhelper)qplatform/, qr/^qwindowsystem/ );
my @angle_headers = ('egl.h', 'eglext.h', 'eglplatform.h', 'gl2.h', 'gl2ext.h', 'gl2platform.h', 'ShaderLang.h', 'khrplatform.h');
my @internal_zlib_headers = ( "crc32.h", "deflate.h", "gzguts.h", "inffast.h", "inffixed.h", "inflate.h", "inftrees.h", "trees.h", "zutil.h" );
my @zlib_headers = ( "zconf.h", "zlib.h" );
diff --git a/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp b/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
index b5e3dee9a6..cadd4e82cd 100644
--- a/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
+++ b/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
@@ -1443,45 +1443,45 @@ void tst_QtConcurrentFilter::noDetach()
QVERIFY(l.isDetached());
QList<int> ll = l;
- QVERIFY(l.isDetached() == false);
+ QVERIFY(!l.isDetached());
QtConcurrent::filtered(l, waitFilterfn).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::blockingFiltered(l, waitFilterfn);
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::filteredReduced(l, waitFilterfn, intSumReduce).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::filter(l, waitFilterfn).waitForFinished();
if (!l.isDetached())
QEXPECT_FAIL("", "QTBUG-20688: Known unstable failure", Abort);
- QVERIFY(l.isDetached() == true);
- QVERIFY(ll.isDetached() == true);
+ QVERIFY(l.isDetached());
+ QVERIFY(ll.isDetached());
}
{
const QList<int> l = QList<int>() << 1;
QVERIFY(l.isDetached());
const QList<int> ll = l;
- QVERIFY(l.isDetached() == false);
+ QVERIFY(!l.isDetached());
QtConcurrent::filtered(l, waitFilterfn).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::filteredReduced(l, waitFilterfn, intSumReduce).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
}
}
diff --git a/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp b/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
index 4e19124ca8..33941d8e90 100644
--- a/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
+++ b/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
@@ -2250,38 +2250,38 @@ void tst_QtConcurrentMap::noDetach()
QVERIFY(l.isDetached());
QList<int> ll = l;
- QVERIFY(l.isDetached() == false);
+ QVERIFY(!l.isDetached());
QtConcurrent::mapped(l, mapper).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::mappedReduced(l, mapper, intSumReduce).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::map(l, multiplyBy2Immutable).waitForFinished();
- QVERIFY(l.isDetached() == true);
- QVERIFY(ll.isDetached() == true);
+ QVERIFY(l.isDetached());
+ QVERIFY(ll.isDetached());
}
{
const QList<int> l = QList<int>() << 1;
QVERIFY(l.isDetached());
const QList<int> ll = l;
- QVERIFY(l.isDetached() == false);
+ QVERIFY(!l.isDetached());
QtConcurrent::mapped(l, mapper).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
QtConcurrent::mappedReduced(l, mapper, intSumReduce).waitForFinished();
- QVERIFY(l.isDetached() == false);
- QVERIFY(ll.isDetached() == false);
+ QVERIFY(!l.isDetached());
+ QVERIFY(!ll.isDetached());
}
}
diff --git a/tests/auto/corelib/animation/qpauseanimation/BLACKLIST b/tests/auto/corelib/animation/qpauseanimation/BLACKLIST
new file mode 100644
index 0000000000..3b2cd84749
--- /dev/null
+++ b/tests/auto/corelib/animation/qpauseanimation/BLACKLIST
@@ -0,0 +1,4 @@
+[multiplePauseAnimations]
+osx-10.9
+[pauseAndPropertyAnimations]
+*
diff --git a/tests/auto/corelib/animation/qpropertyanimation/BLACKLIST b/tests/auto/corelib/animation/qpropertyanimation/BLACKLIST
new file mode 100644
index 0000000000..a7e95b1e97
--- /dev/null
+++ b/tests/auto/corelib/animation/qpropertyanimation/BLACKLIST
@@ -0,0 +1,4 @@
+[statesAndSignals:normal animation]
+windows
+[startBackwardWithoutEndValue]
+windows
diff --git a/tests/auto/corelib/animation/qsequentialanimationgroup/BLACKLIST b/tests/auto/corelib/animation/qsequentialanimationgroup/BLACKLIST
new file mode 100644
index 0000000000..e11e4ae6fb
--- /dev/null
+++ b/tests/auto/corelib/animation/qsequentialanimationgroup/BLACKLIST
@@ -0,0 +1,4 @@
+[startGroupWithRunningChild]
+windows
+[finishWithUncontrolledAnimation]
+windows
diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
index 69bf7598fc..00f70f5380 100644
--- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
+++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
@@ -457,7 +457,7 @@ void tst_QGlobal::isEnum()
// fallback type traits implementation. Any compiler
// supported by Qt that supports C++0x class enums
// should also support the __is_enum intrinsic.
- QVERIFY(Q_IS_ENUM(isEnum_G) == true);
+ QVERIFY(Q_IS_ENUM(isEnum_G));
#endif
#undef IS_ENUM_TRUE
diff --git a/tests/auto/corelib/global/qglobalstatic/tst_qglobalstatic.cpp b/tests/auto/corelib/global/qglobalstatic/tst_qglobalstatic.cpp
index a1cfff7e85..e9fd999e9f 100644
--- a/tests/auto/corelib/global/qglobalstatic/tst_qglobalstatic.cpp
+++ b/tests/auto/corelib/global/qglobalstatic/tst_qglobalstatic.cpp
@@ -41,10 +41,17 @@
#include <QtCore/QThread>
#include <QtTest/QtTest>
+#if defined(Q_OS_UNIX)
+#include <sys/resource.h>
+#endif
+
class tst_QGlobalStatic : public QObject
{
Q_OBJECT
+public Q_SLOTS:
+ void initTestCase();
+
private Q_SLOTS:
void beforeInitialization();
void api();
@@ -55,6 +62,20 @@ private Q_SLOTS:
void afterDestruction();
};
+void tst_QGlobalStatic::initTestCase()
+{
+#if defined(Q_OS_UNIX)
+ // The tests create a lot of threads, which require file descriptors. On systems like
+ // OS X low defaults such as 256 as the limit for the number of simultaneously
+ // open files is not sufficient.
+ struct rlimit numFiles;
+ if (getrlimit(RLIMIT_NOFILE, &numFiles) == 0 && numFiles.rlim_cur < 1024) {
+ numFiles.rlim_cur = qMin(rlim_t(1024), numFiles.rlim_max);
+ setrlimit(RLIMIT_NOFILE, &numFiles);
+ }
+#endif
+}
+
Q_GLOBAL_STATIC_WITH_ARGS(const int, constInt, (42))
Q_GLOBAL_STATIC_WITH_ARGS(volatile int, volatileInt, (-47))
diff --git a/tests/auto/corelib/io/qdebug/tst_qdebug.cpp b/tests/auto/corelib/io/qdebug/tst_qdebug.cpp
index 3e19e816c9..db2805ebf0 100644
--- a/tests/auto/corelib/io/qdebug/tst_qdebug.cpp
+++ b/tests/auto/corelib/io/qdebug/tst_qdebug.cpp
@@ -49,6 +49,7 @@ private slots:
void debugWithBool() const;
void debugSpaceHandling() const;
void debugNoQuotes() const;
+ void verbosity() const;
void stateSaver() const;
void veryLongWarningMessage() const;
void qDebugQChar() const;
@@ -192,7 +193,11 @@ public:
QDebug operator<< (QDebug s, const MyLine& line)
{
const QDebugStateSaver saver(s);
- s.nospace() << "MyLine(" << line.p1 << ", " << line.p2 << ")";
+ s.nospace();
+ s << "MyLine(" << line.p1 << ", "<< line.p2;
+ if (s.verbosity() > 2)
+ s << ", Manhattan length=" << (qAbs(line.p2.v1 - line.p1.v1) + qAbs(line.p2.v2 - line.p1.v2));
+ s << ')';
return s;
}
@@ -255,6 +260,33 @@ void tst_QDebug::debugNoQuotes() const
QCOMPARE(s_msg, QString::fromLatin1("'H' \"Hello\" \"Hello\" H Hello Hello"));
}
+void tst_QDebug::verbosity() const
+{
+ MyLine line(MyPoint(10, 11), MyPoint (12, 13));
+ QString output;
+ QDebug d(&output);
+ d.nospace();
+ d << line << '\n';
+ const int oldVerbosity = d.verbosity();
+ d.setVerbosity(0);
+ QCOMPARE(d.verbosity(), 0);
+ d.setVerbosity(7);
+ QCOMPARE(d.verbosity(), 7);
+ const int newVerbosity = oldVerbosity + 2;
+ d.setVerbosity(newVerbosity);
+ QCOMPARE(d.verbosity(), newVerbosity);
+ d << line << '\n';
+ d.setVerbosity(oldVerbosity );
+ QCOMPARE(d.verbosity(), oldVerbosity );
+ d << line;
+ const QStringList lines = output.split(QLatin1Char('\n'));
+ QCOMPARE(lines.size(), 3);
+ // Verbose should be longer
+ QVERIFY2(lines.at(1).size() > lines.at(0).size(), qPrintable(lines.join(QLatin1Char(','))));
+ // Switching back to brief produces same output
+ QCOMPARE(lines.at(0).size(), lines.at(2).size());
+}
+
void tst_QDebug::stateSaver() const
{
MessageHandlerSetter mhs(myMessageHandler);
diff --git a/tests/auto/corelib/io/qdir/qdir.pro b/tests/auto/corelib/io/qdir/qdir.pro
index d3e954bd32..0adc7e0450 100644
--- a/tests/auto/corelib/io/qdir/qdir.pro
+++ b/tests/auto/corelib/io/qdir/qdir.pro
@@ -10,3 +10,5 @@ DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
android:!android-no-sdk {
RESOURCES += android_testdata.qrc
}
+
+win32: CONFIG += insignificant_test # Crashes on Windows in release builds
diff --git a/tests/auto/corelib/io/qdiriterator/qdiriterator.pro b/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
index 3b5d2bd931..a2429bf2f0 100644
--- a/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
+++ b/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
@@ -8,3 +8,5 @@ TESTDATA += entrylist
wince*mips*|wincewm50smart-msvc200*: DEFINES += WINCE_BROKEN_ITERATE=1
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
+
+win32: CONFIG += insignificant_test # Crashes on Windows in release builds
diff --git a/tests/auto/corelib/io/qfileinfo/qfileinfo.pro b/tests/auto/corelib/io/qfileinfo/qfileinfo.pro
index de99447404..571637be37 100644
--- a/tests/auto/corelib/io/qfileinfo/qfileinfo.pro
+++ b/tests/auto/corelib/io/qfileinfo/qfileinfo.pro
@@ -7,3 +7,5 @@ RESOURCES += qfileinfo.qrc \
win32:!wince:!winrt:LIBS += -ladvapi32 -lnetapi32
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
+
+win32: CONFIG += insignificant_test # Crashes on Windows in release builds
diff --git a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
index 96ad78a666..8d276b3616 100644
--- a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
+++ b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
@@ -287,7 +287,8 @@ void tst_QFileInfo::initTestCase()
m_resourcesDir = dataPath + QLatin1String("/resources");
m_proFile = dataPath + QLatin1String("/tst_qfileinfo.pro");
- QVERIFY(m_dir.isValid());
+ QVERIFY2(m_dir.isValid(),
+ ("Failed to create temporary dir: " + m_dir.errorString()).toUtf8());
QVERIFY(QDir::setCurrent(m_dir.path()));
}
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+haiku/test b/tests/auto/corelib/io/qfileselector/platforms/+haiku/test
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/auto/corelib/io/qfileselector/platforms/+haiku/test
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+haiku/test2 b/tests/auto/corelib/io/qfileselector/platforms/+haiku/test2
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/auto/corelib/io/qfileselector/platforms/+haiku/test2
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+haiku/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+haiku/test
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+haiku/test
diff --git a/tests/auto/corelib/io/qfileselector/qfileselector.qrc b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
index 661647f933..6e2699774d 100644
--- a/tests/auto/corelib/io/qfileselector/qfileselector.qrc
+++ b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
@@ -19,6 +19,7 @@
<file>platforms/+unix/+darwin/+mac/+osx/test</file>
<file>platforms/+unix/+darwin/+mac/test</file>
<file>platforms/+unix/+darwin/test</file>
+ <file>platforms/+unix/+haiku/test</file>
<file>platforms/+unix/+linux/test</file>
<file>platforms/+unix/test</file>
<file>platforms/+windows/+wince/test</file>
@@ -30,6 +31,7 @@
<file>platforms/+osx/test</file>
<file>platforms/+darwin/test</file>
<file>platforms/+mac/test</file>
+ <file>platforms/+haiku/test</file>
<file>platforms/+linux/test</file>
<file>platforms/+wince/test</file>
@@ -39,6 +41,7 @@
<file>platforms/+blackberry/test2</file>
<file>platforms/+ios/test2</file>
<file>platforms/+osx/test2</file>
+ <file>platforms/+haiku/test2</file>
<file>platforms/+linux/test2</file>
<file>platforms/+wince/test2</file>
<file>platforms/+winnt/test2</file>
diff --git a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
index b3767b4887..87381f4c4e 100644
--- a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
+++ b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
@@ -89,7 +89,7 @@ void tst_QFileSelector::basicTest_data()
QString expectedPlatform2File(""); //Only the last selector
QString expectedPlatform3File; // Only the first selector (the family)
#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID) && !defined(Q_OS_BLACKBERRY) && \
- !defined(Q_OS_DARWIN) && !defined(Q_OS_LINUX)
+ !defined(Q_OS_DARWIN) && !defined(Q_OS_LINUX) && !defined(Q_OS_HAIKU)
/* We are only aware of specific unixes, and do not have test files for any of the others.
However those unixes can get a selector added from the result of a uname call, so this will
lead to a case where we don't have that file so we can't expect the concatenation of platform
diff --git a/tests/auto/corelib/io/qfilesystemwatcher/BLACKLIST b/tests/auto/corelib/io/qfilesystemwatcher/BLACKLIST
index 3ac0b9dff4..10a4ba069e 100644
--- a/tests/auto/corelib/io/qfilesystemwatcher/BLACKLIST
+++ b/tests/auto/corelib/io/qfilesystemwatcher/BLACKLIST
@@ -6,3 +6,4 @@ windows 64bit msvc
osx
[watchFileAndItsDirectory:native backend-specialchars]
osx
+windows
diff --git a/tests/auto/corelib/io/qfilesystemwatcher/tst_qfilesystemwatcher.cpp b/tests/auto/corelib/io/qfilesystemwatcher/tst_qfilesystemwatcher.cpp
index 7e56ecaab3..a0434aa8ee 100644
--- a/tests/auto/corelib/io/qfilesystemwatcher/tst_qfilesystemwatcher.cpp
+++ b/tests/auto/corelib/io/qfilesystemwatcher/tst_qfilesystemwatcher.cpp
@@ -553,7 +553,7 @@ void tst_QFileSystemWatcher::watchFileAndItsDirectory()
timer.start(3000);
eventLoop.exec();
int fileChangedSpyCount = fileChangedSpy.count();
-#ifdef Q_OS_WIN64
+#ifdef Q_OS_WIN
if (fileChangedSpyCount != 0)
QEXPECT_FAIL("", "See QTBUG-30943", Continue);
#endif
diff --git a/tests/auto/corelib/io/qiodevice/BLACKLIST b/tests/auto/corelib/io/qiodevice/BLACKLIST
new file mode 100644
index 0000000000..b8a61d3ca9
--- /dev/null
+++ b/tests/auto/corelib/io/qiodevice/BLACKLIST
@@ -0,0 +1,2 @@
+[unget]
+redhatenterpriselinuxworkstation-6.6
diff --git a/tests/auto/corelib/io/qprocess/BLACKLIST b/tests/auto/corelib/io/qprocess/BLACKLIST
new file mode 100644
index 0000000000..dcd913ca49
--- /dev/null
+++ b/tests/auto/corelib/io/qprocess/BLACKLIST
@@ -0,0 +1,2 @@
+[lockupsInStartDetached]
+redhatenterpriselinuxworkstation-6.6
diff --git a/tests/auto/corelib/io/qprocess/tst_qprocess.cpp b/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
index 0995f764b7..caefc3fc21 100644
--- a/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
+++ b/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
@@ -124,9 +124,9 @@ private slots:
void removeFileWhileProcessIsRunning();
void fileWriterProcess();
void switchReadChannels();
-#ifdef Q_OS_WIN
+ void discardUnwantedOutput();
void setWorkingDirectory();
-#endif // Q_OS_WIN
+ void setNonExistentWorkingDirectory();
#endif // not Q_OS_WINCE
void exitStatus_data();
@@ -220,7 +220,6 @@ void tst_QProcess::getSetCheck()
QCOMPARE(QProcess::ProcessChannel(QProcess::StandardError), obj1.readChannel());
}
-//-----------------------------------------------------------------------------
void tst_QProcess::constructing()
{
QProcess process;
@@ -282,7 +281,6 @@ void tst_QProcess::simpleStart()
QCOMPARE(qvariant_cast<QProcess::ProcessState>(spy.at(2).at(0)), QProcess::NotRunning);
}
-//-----------------------------------------------------------------------------
void tst_QProcess::startWithOpen()
{
QProcess p;
@@ -300,7 +298,6 @@ void tst_QProcess::startWithOpen()
QVERIFY(p.waitForFinished(5000));
}
-//-----------------------------------------------------------------------------
void tst_QProcess::startWithOldOpen()
{
// similar to the above, but we start with start() actually
@@ -319,7 +316,6 @@ void tst_QProcess::startWithOldOpen()
QVERIFY(p.waitForFinished(5000));
}
-//-----------------------------------------------------------------------------
void tst_QProcess::execute()
{
QCOMPARE(QProcess::execute("testProcessNormal/testProcessNormal",
@@ -327,7 +323,6 @@ void tst_QProcess::execute()
QCOMPARE(QProcess::execute("nonexistingexe"), -2);
}
-//-----------------------------------------------------------------------------
void tst_QProcess::startDetached()
{
QProcess proc;
@@ -339,7 +334,6 @@ void tst_QProcess::startDetached()
QCOMPARE(QProcess::startDetached("nonexistingexe"), false);
}
-//-----------------------------------------------------------------------------
void tst_QProcess::readFromProcess()
{
int lines = 0;
@@ -349,7 +343,6 @@ void tst_QProcess::readFromProcess()
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::crashTest()
{
qRegisterMetaType<QProcess::ProcessState>("QProcess::ProcessState");
@@ -362,11 +355,13 @@ void tst_QProcess::crashTest()
qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
- QSignalSpy spy(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
- QSignalSpy spy2(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
+ QSignalSpy spy(process, &QProcess::errorOccurred);
+ QSignalSpy spy2(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy spy3(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(spy.isValid());
QVERIFY(spy2.isValid());
+ QVERIFY(spy3.isValid());
QVERIFY(process->waitForFinished(30000));
@@ -374,7 +369,10 @@ void tst_QProcess::crashTest()
QCOMPARE(*static_cast<const QProcess::ProcessError *>(spy.at(0).at(0).constData()), QProcess::Crashed);
QCOMPARE(spy2.count(), 1);
- QCOMPARE(*static_cast<const QProcess::ExitStatus *>(spy2.at(0).at(1).constData()), QProcess::CrashExit);
+ QCOMPARE(*static_cast<const QProcess::ProcessError *>(spy2.at(0).at(0).constData()), QProcess::Crashed);
+
+ QCOMPARE(spy3.count(), 1);
+ QCOMPARE(*static_cast<const QProcess::ExitStatus *>(spy3.at(0).at(1).constData()), QProcess::CrashExit);
QCOMPARE(process->exitStatus(), QProcess::CrashExit);
@@ -387,7 +385,6 @@ void tst_QProcess::crashTest()
QCOMPARE(qvariant_cast<QProcess::ProcessState>(stateSpy.at(2).at(0)), QProcess::NotRunning);
}
-//-----------------------------------------------------------------------------
void tst_QProcess::crashTest2()
{
process = new QProcess;
@@ -397,7 +394,7 @@ void tst_QProcess::crashTest2()
qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
- QSignalSpy spy(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy spy(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::errorOccurred));
QSignalSpy spy2(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(spy.isValid());
@@ -423,7 +420,6 @@ void tst_QProcess::crashTest2()
#ifndef Q_OS_WINCE
//Reading and writing to a process is not supported on Qt/CE
-//-----------------------------------------------------------------------------
void tst_QProcess::echoTest_data()
{
QTest::addColumn<QByteArray>("input");
@@ -438,8 +434,6 @@ void tst_QProcess::echoTest_data()
QTest::newRow("10000 bytes") << QByteArray(10000, '@');
}
-//-----------------------------------------------------------------------------
-
void tst_QProcess::echoTest()
{
QFETCH(QByteArray, input);
@@ -484,14 +478,11 @@ void tst_QProcess::echoTest()
}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::exitLoopSlot()
{
QTestEventLoop::instance().exitLoop();
}
-//-----------------------------------------------------------------------------
-
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::echoTest2()
@@ -543,7 +534,6 @@ void tst_QProcess::echoTest2()
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
// Reading and writing to a process is not supported on Qt/CE
-//-----------------------------------------------------------------------------
void tst_QProcess::echoTestGui()
{
QProcess process;
@@ -572,7 +562,6 @@ void tst_QProcess::testSetNamedPipeHandleState()
}
#endif // !Q_OS_WINCE && Q_OS_WIN
-//-----------------------------------------------------------------------------
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
// Batch files are not supported on Windows CE
void tst_QProcess::batFiles_data()
@@ -601,7 +590,6 @@ void tst_QProcess::batFiles()
}
#endif // !Q_OS_WINCE && Q_OS_WIN
-//-----------------------------------------------------------------------------
void tst_QProcess::exitStatus_data()
{
QTest::addColumn<QStringList>("processList");
@@ -644,7 +632,7 @@ void tst_QProcess::exitStatus()
process->deleteLater();
process = 0;
}
-//-----------------------------------------------------------------------------
+
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::loopBackTest()
@@ -670,7 +658,6 @@ void tst_QProcess::loopBackTest()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::readTimeoutAndThenCrash()
@@ -688,8 +675,10 @@ void tst_QProcess::readTimeoutAndThenCrash()
QCOMPARE(process->error(), QProcess::Timedout);
qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
- QSignalSpy spy(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy spy(process, &QProcess::errorOccurred);
+ QSignalSpy spy2(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QVERIFY(spy.isValid());
+ QVERIFY(spy2.isValid());
process->kill();
@@ -698,6 +687,8 @@ void tst_QProcess::readTimeoutAndThenCrash()
QCOMPARE(spy.count(), 1);
QCOMPARE(*static_cast<const QProcess::ProcessError *>(spy.at(0).at(0).constData()), QProcess::Crashed);
+ QCOMPARE(spy2.count(), 1);
+ QCOMPARE(*static_cast<const QProcess::ProcessError *>(spy2.at(0).at(0).constData()), QProcess::Crashed);
delete process;
process = 0;
@@ -750,7 +741,6 @@ void tst_QProcess::deadWhileReading()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::restartProcessDeadlock()
@@ -780,7 +770,6 @@ void tst_QProcess::restartProcess()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::closeWriteChannel()
@@ -808,7 +797,6 @@ void tst_QProcess::closeWriteChannel()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE"
void tst_QProcess::closeReadChannel()
@@ -840,7 +828,6 @@ void tst_QProcess::closeReadChannel()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::openModes()
@@ -885,7 +872,6 @@ void tst_QProcess::openModes()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::emitReadyReadOnlyWhenNewDataArrives()
@@ -921,7 +907,6 @@ void tst_QProcess::emitReadyReadOnlyWhenNewDataArrives()
}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::hardExit()
{
QProcess proc;
@@ -945,7 +930,6 @@ void tst_QProcess::hardExit()
QCOMPARE(int(proc.error()), int(QProcess::Crashed));
}
-//-----------------------------------------------------------------------------
void tst_QProcess::softExit()
{
QProcess proc;
@@ -1055,7 +1039,6 @@ private:
QByteArray dataToWrite;
};
-//-----------------------------------------------------------------------------
void tst_QProcess::softExitInSlots_data()
{
QTest::addColumn<QString>("appName");
@@ -1065,7 +1048,6 @@ void tst_QProcess::softExitInSlots_data()
#endif
QTest::newRow("console app") << "testProcessEcho2/testProcessEcho2";
}
-//-----------------------------------------------------------------------------
void tst_QProcess::softExitInSlots()
{
@@ -1081,7 +1063,6 @@ void tst_QProcess::softExitInSlots()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::mergedChannels()
@@ -1106,7 +1087,6 @@ void tst_QProcess::mergedChannels()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
@@ -1161,7 +1141,6 @@ void tst_QProcess::forwardedChannels()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::atEnd()
@@ -1222,7 +1201,6 @@ private:
int exitCode;
};
-//-----------------------------------------------------------------------------
void tst_QProcess::processInAThread()
{
for (int i = 0; i < 10; ++i) {
@@ -1233,7 +1211,6 @@ void tst_QProcess::processInAThread()
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::processesInMultipleThreads()
{
for (int i = 0; i < 10; ++i) {
@@ -1258,7 +1235,6 @@ void tst_QProcess::processesInMultipleThreads()
}
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::waitForFinishedWithTimeout()
@@ -1279,7 +1255,6 @@ void tst_QProcess::waitForFinishedWithTimeout()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::waitForReadyReadInAReadyReadSlot()
@@ -1308,7 +1283,6 @@ void tst_QProcess::waitForReadyReadInAReadyReadSlot()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::waitForReadyReadInAReadyReadSlotSlot()
@@ -1320,7 +1294,6 @@ void tst_QProcess::waitForReadyReadInAReadyReadSlotSlot()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::waitForBytesWrittenInABytesWrittenSlot()
@@ -1347,7 +1320,6 @@ void tst_QProcess::waitForBytesWrittenInABytesWrittenSlot()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::waitForBytesWrittenInABytesWrittenSlotSlot()
@@ -1357,7 +1329,7 @@ void tst_QProcess::waitForBytesWrittenInABytesWrittenSlotSlot()
QTestEventLoop::instance().exitLoop();
}
#endif
-//-----------------------------------------------------------------------------
+
void tst_QProcess::spaceArgsTest_data()
{
QTest::addColumn<QStringList>("args");
@@ -1410,7 +1382,6 @@ static QByteArray startFailMessage(const QString &program, const QProcess &proce
return result;
}
-//-----------------------------------------------------------------------------
void tst_QProcess::spaceArgsTest()
{
QFETCH(QStringList, args);
@@ -1483,7 +1454,6 @@ void tst_QProcess::spaceArgsTest()
#if defined(Q_OS_WIN)
-//-----------------------------------------------------------------------------
void tst_QProcess::nativeArguments()
{
QProcess proc;
@@ -1527,7 +1497,6 @@ void tst_QProcess::nativeArguments()
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::exitCodeTest()
{
for (int i = 0; i < 255; ++i) {
@@ -1544,7 +1513,6 @@ void tst_QProcess::exitCodeTest()
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::failToStart()
{
#if defined(QPROCESS_USE_SPAWN) && !defined(Q_OS_QNX)
@@ -1556,12 +1524,14 @@ void tst_QProcess::failToStart()
QProcess process;
QSignalSpy stateSpy(&process, &QProcess::stateChanged);
- QSignalSpy errorSpy(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy errorSpy(&process, &QProcess::errorOccurred);
+ QSignalSpy errorSpy2(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QSignalSpy finishedSpy(&process, static_cast<void (QProcess::*)(int)>(&QProcess::finished));
QSignalSpy finishedSpy2(&process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(stateSpy.isValid());
QVERIFY(errorSpy.isValid());
+ QVERIFY(errorSpy2.isValid());
QVERIFY(finishedSpy.isValid());
QVERIFY(finishedSpy2.isValid());
@@ -1578,6 +1548,7 @@ void tst_QProcess::failToStart()
for (int j = 0; j < 8; ++j) {
for (int i = 0; i < attempts; ++i) {
QCOMPARE(errorSpy.count(), j * attempts + i);
+ QCOMPARE(errorSpy2.count(), j * attempts + i);
process.start("/blurp");
switch (j) {
@@ -1602,6 +1573,7 @@ void tst_QProcess::failToStart()
QCOMPARE(process.error(), QProcess::FailedToStart);
QCOMPARE(errorSpy.count(), j * attempts + i + 1);
+ QCOMPARE(errorSpy2.count(), j * attempts + i + 1);
QCOMPARE(finishedSpy.count(), 0);
QCOMPARE(finishedSpy2.count(), 0);
@@ -1614,7 +1586,6 @@ void tst_QProcess::failToStart()
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::failToStartWithWait()
{
#if defined(QPROCESS_USE_SPAWN) && !defined(Q_OS_QNX)
@@ -1625,11 +1596,13 @@ void tst_QProcess::failToStartWithWait()
QProcess process;
QEventLoop loop;
- QSignalSpy errorSpy(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy errorSpy(&process, &QProcess::errorOccurred);
+ QSignalSpy errorSpy2(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QSignalSpy finishedSpy(&process, static_cast<void (QProcess::*)(int)>(&QProcess::finished));
QSignalSpy finishedSpy2(&process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(errorSpy.isValid());
+ QVERIFY(errorSpy2.isValid());
QVERIFY(finishedSpy.isValid());
QVERIFY(finishedSpy2.isValid());
@@ -1639,12 +1612,12 @@ void tst_QProcess::failToStartWithWait()
QCOMPARE(process.error(), QProcess::FailedToStart);
QCOMPARE(errorSpy.count(), i + 1);
+ QCOMPARE(errorSpy2.count(), i + 1);
QCOMPARE(finishedSpy.count(), 0);
QCOMPARE(finishedSpy2.count(), 0);
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::failToStartWithEventLoop()
{
#if defined(QPROCESS_USE_SPAWN) && !defined(Q_OS_QNX)
@@ -1655,16 +1628,18 @@ void tst_QProcess::failToStartWithEventLoop()
QProcess process;
QEventLoop loop;
- QSignalSpy errorSpy(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy errorSpy(&process, &QProcess::errorOccurred);
+ QSignalSpy errorSpy2(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QSignalSpy finishedSpy(&process, static_cast<void (QProcess::*)(int)>(&QProcess::finished));
QSignalSpy finishedSpy2(&process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(errorSpy.isValid());
+ QVERIFY(errorSpy2.isValid());
QVERIFY(finishedSpy.isValid());
QVERIFY(finishedSpy2.isValid());
// The error signal may be emitted before start() returns
- connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()), Qt::QueuedConnection);
+ connect(&process, &QProcess::errorOccurred, &loop, &QEventLoop::quit, Qt::QueuedConnection);
for (int i = 0; i < 50; ++i) {
@@ -1674,6 +1649,7 @@ void tst_QProcess::failToStartWithEventLoop()
QCOMPARE(process.error(), QProcess::FailedToStart);
QCOMPARE(errorSpy.count(), i + 1);
+ QCOMPARE(errorSpy2.count(), i + 1);
QCOMPARE(finishedSpy.count(), 0);
QCOMPARE(finishedSpy2.count(), 0);
}
@@ -1715,7 +1691,6 @@ void tst_QProcess::failToStartEmptyArgs()
QCOMPARE(process.error(), QProcess::FailedToStart);
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::removeFileWhileProcessIsRunning()
@@ -1734,7 +1709,6 @@ void tst_QProcess::removeFileWhileProcessIsRunning()
QVERIFY(process.waitForFinished(5000));
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// OS doesn't support environment variables
void tst_QProcess::setEnvironment_data()
@@ -1812,7 +1786,6 @@ void tst_QProcess::setEnvironment()
}
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// OS doesn't support environment variables
void tst_QProcess::setProcessEnvironment_data()
@@ -1853,7 +1826,7 @@ void tst_QProcess::setProcessEnvironment()
}
}
#endif
-//-----------------------------------------------------------------------------
+
void tst_QProcess::systemEnvironment()
{
#if defined (Q_OS_WINCE)
@@ -1869,7 +1842,6 @@ void tst_QProcess::systemEnvironment()
#endif
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::spaceInName()
@@ -1882,7 +1854,6 @@ void tst_QProcess::spaceInName()
}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::lockupsInStartDetached()
{
// Check that QProcess doesn't cause a lock up at this program's
@@ -1896,7 +1867,6 @@ void tst_QProcess::lockupsInStartDetached()
QProcess::startDetached("yjhbrty");
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::atEnd2()
@@ -1915,7 +1885,6 @@ void tst_QProcess::atEnd2()
}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::waitForReadyReadForNonexistantProcess()
{
// Start a program that doesn't exist, process events and then try to waitForReadyRead
@@ -1923,11 +1892,13 @@ void tst_QProcess::waitForReadyReadForNonexistantProcess()
qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
QProcess process;
- QSignalSpy errorSpy(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy errorSpy(&process, &QProcess::errorOccurred);
+ QSignalSpy errorSpy2(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QSignalSpy finishedSpy1(&process, static_cast<void (QProcess::*)(int)>(&QProcess::finished));
QSignalSpy finishedSpy2(&process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished));
QVERIFY(errorSpy.isValid());
+ QVERIFY(errorSpy2.isValid());
QVERIFY(finishedSpy1.isValid());
QVERIFY(finishedSpy2.isValid());
@@ -1939,11 +1910,12 @@ void tst_QProcess::waitForReadyReadForNonexistantProcess()
#endif
QCOMPARE(errorSpy.count(), 1);
QCOMPARE(errorSpy.at(0).at(0).toInt(), 0);
+ QCOMPARE(errorSpy2.count(), 1);
+ QCOMPARE(errorSpy2.at(0).at(0).toInt(), 0);
QCOMPARE(finishedSpy1.count(), 0);
QCOMPARE(finishedSpy2.count(), 0);
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::setStandardInputFile()
@@ -1973,7 +1945,6 @@ void tst_QProcess::setStandardInputFile()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::setStandardOutputFile_data()
@@ -2004,7 +1975,6 @@ void tst_QProcess::setStandardOutputFile_data()
<< true;
}
-//-----------------------------------------------------------------------------
void tst_QProcess::setStandardOutputFile()
{
static const char data[] = "Original data. ";
@@ -2089,7 +2059,6 @@ void tst_QProcess::setStandardOutputFileAndWaitForBytesWritten()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::setStandardOutputProcess_data()
@@ -2130,7 +2099,6 @@ void tst_QProcess::setStandardOutputProcess()
}
#endif
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::fileWriterProcess()
@@ -2158,7 +2126,6 @@ void tst_QProcess::fileWriterProcess()
}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::detachedWorkingDirectoryAndPid()
{
qint64 pid;
@@ -2202,7 +2169,6 @@ void tst_QProcess::detachedWorkingDirectoryAndPid()
QCOMPARE(actualPid, pid);
}
-//-----------------------------------------------------------------------------
#ifndef Q_OS_WINCE
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::switchReadChannels()
@@ -2233,16 +2199,38 @@ void tst_QProcess::switchReadChannels()
}
#endif
-//-----------------------------------------------------------------------------
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+#ifndef Q_OS_WINCE
+// Reading and writing to a process is not supported on Qt/CE
+void tst_QProcess::discardUnwantedOutput()
+{
+ QProcess process;
+
+ process.setProgram("testProcessEcho2/testProcessEcho2");
+ process.start(QIODevice::WriteOnly);
+ process.write("Hello, World");
+ process.closeWriteChannel();
+ QVERIFY(process.waitForFinished(5000));
+
+ process.setReadChannel(QProcess::StandardOutput);
+ QCOMPARE(process.bytesAvailable(), Q_INT64_C(0));
+ process.setReadChannel(QProcess::StandardError);
+ QCOMPARE(process.bytesAvailable(), Q_INT64_C(0));
+}
+#endif
+
+#ifndef Q_OS_WINCE
// Q_OS_WIN - setWorkingDirectory will chdir before starting the process on unices
// Windows CE does not support working directory logic
void tst_QProcess::setWorkingDirectory()
{
process = new QProcess;
process->setWorkingDirectory("test");
- process->start("testSetWorkingDirectory/testSetWorkingDirectory");
- QVERIFY(process->waitForFinished());
+
+ // use absolute path because on Windows, the executable is relative to the parent's CWD
+ // while on Unix with fork it's relative to the child's (with posix_spawn, it could be either).
+ process->start(QFileInfo("testSetWorkingDirectory/testSetWorkingDirectory").absoluteFilePath());
+
+ QVERIFY2(process->waitForFinished(), process->errorString().toLocal8Bit());
QByteArray workingDir = process->readAllStandardOutput();
QCOMPARE(QDir("test").canonicalPath(), QDir(workingDir.constData()).canonicalPath());
@@ -2250,9 +2238,26 @@ void tst_QProcess::setWorkingDirectory()
delete process;
process = 0;
}
+
+void tst_QProcess::setNonExistentWorkingDirectory()
+{
+ process = new QProcess;
+ process->setWorkingDirectory("this/directory/should/not/exist/for/sure");
+
+ // use absolute path because on Windows, the executable is relative to the parent's CWD
+ // while on Unix with fork it's relative to the child's (with posix_spawn, it could be either).
+ process->start(QFileInfo("testSetWorkingDirectory/testSetWorkingDirectory").absoluteFilePath());
+ QVERIFY(!process->waitForFinished());
+#ifdef QPROCESS_USE_SPAWN
+ QEXPECT_FAIL("", "QProcess cannot detect failure to start when using posix_spawn()", Continue);
+#endif
+ QCOMPARE(int(process->error()), int(QProcess::FailedToStart));
+
+ delete process;
+ process = 0;
+}
#endif
-//-----------------------------------------------------------------------------
void tst_QProcess::startFinishStartFinish()
{
QProcess process;
@@ -2271,7 +2276,6 @@ void tst_QProcess::startFinishStartFinish()
}
}
-//-----------------------------------------------------------------------------
void tst_QProcess::invalidProgramString_data()
{
QTest::addColumn<QString>("programString");
@@ -2286,17 +2290,19 @@ void tst_QProcess::invalidProgramString()
QProcess process;
qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
- QSignalSpy spy(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
+ QSignalSpy spy(&process, &QProcess::errorOccurred);
+ QSignalSpy spy2(&process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error));
QVERIFY(spy.isValid());
+ QVERIFY(spy2.isValid());
process.start(programString);
QCOMPARE(process.error(), QProcess::FailedToStart);
QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy2.count(), 1);
QVERIFY(!QProcess::startDetached(programString));
}
-//-----------------------------------------------------------------------------
void tst_QProcess::onlyOneStartedSignal()
{
qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
@@ -2323,8 +2329,6 @@ void tst_QProcess::onlyOneStartedSignal()
QCOMPARE(spyFinished.count(), 1);
}
-//-----------------------------------------------------------------------------
-
class BlockOnReadStdOut : public QObject
{
Q_OBJECT
diff --git a/tests/auto/corelib/io/qprocessenvironment/tst_qprocessenvironment.cpp b/tests/auto/corelib/io/qprocessenvironment/tst_qprocessenvironment.cpp
index be9a38c499..2099101a91 100644
--- a/tests/auto/corelib/io/qprocessenvironment/tst_qprocessenvironment.cpp
+++ b/tests/auto/corelib/io/qprocessenvironment/tst_qprocessenvironment.cpp
@@ -66,11 +66,19 @@ void tst_QProcessEnvironment::operator_eq()
QVERIFY(e1 == e2);
e1.clear();
- QVERIFY(e1 != e2);
+ QVERIFY(e1 == e2);
e2.clear();
+ QVERIFY(e1 == e2);
+
+ e1.insert("FOO", "bar");
+ QVERIFY(e1 != e2);
+ e2.insert("FOO", "bar");
QVERIFY(e1 == e2);
+
+ e2.insert("FOO", "baz");
+ QVERIFY(e1 != e2);
}
void tst_QProcessEnvironment::clearAndIsEmpty()
@@ -196,6 +204,15 @@ void tst_QProcessEnvironment::insertEnv()
QCOMPARE(e.value("Hello"), QString("Another World"));
QCOMPARE(e.value("FOO2"), QString("bar2"));
QCOMPARE(e.value("A2"), QString("bc2"));
+
+ QProcessEnvironment e3;
+ e3.insert("FOO2", "bar2");
+ e3.insert("A2", "bc2");
+ e3.insert("Hello", "Another World");
+
+ e3.insert(e3); // mustn't deadlock
+
+ QVERIFY(e3 == e2);
}
void tst_QProcessEnvironment::caseSensitivity()
diff --git a/tests/auto/corelib/io/qsettings/BLACKLIST b/tests/auto/corelib/io/qsettings/BLACKLIST
new file mode 100644
index 0000000000..1cba99b66c
--- /dev/null
+++ b/tests/auto/corelib/io/qsettings/BLACKLIST
@@ -0,0 +1,2 @@
+[isWritable:native]
+osx-10.10
diff --git a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
index 3e98a369ce..58a3db9615 100644
--- a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
+++ b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
@@ -93,6 +93,7 @@ void tst_QTemporaryDir::construction()
QCOMPARE(dir.path().left(tmp.size()), tmp);
QVERIFY(dir.path().contains("tst_qtemporarydir"));
QVERIFY(QFileInfo(dir.path()).isDir());
+ QCOMPARE(dir.errorString(), QString());
}
// Testing get/set functions
@@ -251,6 +252,7 @@ void tst_QTemporaryDir::nonWritableCurrentDir()
QTemporaryDir dir("tempXXXXXX");
dir.setAutoRemove(true);
QVERIFY(!dir.isValid());
+ QVERIFY(!dir.errorString().isEmpty());
QVERIFY(dir.path().isEmpty());
#endif
}
@@ -287,7 +289,11 @@ void tst_QTemporaryDir::stressTest()
for (int i = 0; i < iterations; ++i) {
QTemporaryDir dir(pattern);
dir.setAutoRemove(false);
- QVERIFY2(dir.isValid(), qPrintable(QString::fromLatin1("Failed to create #%1 under %2.").arg(i).arg(QDir::toNativeSeparators(pattern))));
+ QVERIFY2(dir.isValid(),
+ qPrintable(QString::fromLatin1("Failed to create #%1 under %2: %3.")
+ .arg(i)
+ .arg(QDir::toNativeSeparators(pattern))
+ .arg(dir.errorString())));
QVERIFY(!names.contains(dir.path()));
names.insert(dir.path());
}
diff --git a/tests/auto/corelib/io/qtextstream/BLACKLIST b/tests/auto/corelib/io/qtextstream/BLACKLIST
new file mode 100644
index 0000000000..bc3f118b33
--- /dev/null
+++ b/tests/auto/corelib/io/qtextstream/BLACKLIST
@@ -0,0 +1,2 @@
+[stillOpenWhenAtEnd]
+windows
diff --git a/tests/auto/corelib/io/qurlquery/tst_qurlquery.cpp b/tests/auto/corelib/io/qurlquery/tst_qurlquery.cpp
index db0136dd20..769a96ac64 100644
--- a/tests/auto/corelib/io/qurlquery/tst_qurlquery.cpp
+++ b/tests/auto/corelib/io/qurlquery/tst_qurlquery.cpp
@@ -177,6 +177,7 @@ void tst_QUrlQuery::constructing()
QVERIFY(copy.isEmpty());
QVERIFY(!copy.isDetached());
QVERIFY(copy == empty);
+ QCOMPARE(qHash(copy), qHash(empty));
QVERIFY(!(copy != empty));
copy = empty;
@@ -184,6 +185,7 @@ void tst_QUrlQuery::constructing()
copy = QUrlQuery();
QVERIFY(copy == empty);
+ QCOMPARE(qHash(copy), qHash(empty));
}
{
QUrlQuery copy(emptyQuery());
@@ -298,6 +300,7 @@ void tst_QUrlQuery::addRemove()
QVERIFY(query == original);
QVERIFY(!(query != original));
+ QCOMPARE(qHash(query), qHash(original));
}
{
diff --git a/tests/auto/corelib/itemmodels/qabstractitemmodel/tst_qabstractitemmodel.cpp b/tests/auto/corelib/itemmodels/qabstractitemmodel/tst_qabstractitemmodel.cpp
index 64170b15dd..c4d2df7c3e 100644
--- a/tests/auto/corelib/itemmodels/qabstractitemmodel/tst_qabstractitemmodel.cpp
+++ b/tests/auto/corelib/itemmodels/qabstractitemmodel/tst_qabstractitemmodel.cpp
@@ -379,7 +379,7 @@ void tst_QAbstractItemModel::hasChildren()
{
QtTestModel model(1, 1);
QModelIndex idx = model.index(0, 0, QModelIndex());
- QVERIFY(model.hasChildren(idx) == false);
+ QVERIFY(!model.hasChildren(idx));
}
void tst_QAbstractItemModel::data()
diff --git a/tests/auto/corelib/itemmodels/qitemselectionmodel/tst_qitemselectionmodel.cpp b/tests/auto/corelib/itemmodels/qitemselectionmodel/tst_qitemselectionmodel.cpp
index 8d331389f5..23cd254477 100644
--- a/tests/auto/corelib/itemmodels/qitemselectionmodel/tst_qitemselectionmodel.cpp
+++ b/tests/auto/corelib/itemmodels/qitemselectionmodel/tst_qitemselectionmodel.cpp
@@ -1530,7 +1530,7 @@ void tst_QItemSelectionModel::resetModel()
model.reset();
QVERIFY(selectionModel->selection().isEmpty());
- QVERIFY(selectionModel->hasSelection() == false);
+ QVERIFY(!selectionModel->hasSelection());
selectionModel->select(QItemSelection(model.index(0, 0), model.index(5, 5)), QItemSelectionModel::Select);
diff --git a/tests/auto/corelib/itemmodels/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp b/tests/auto/corelib/itemmodels/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp
index 1c30adc8de..0302ae5cbf 100644
--- a/tests/auto/corelib/itemmodels/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp
+++ b/tests/auto/corelib/itemmodels/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp
@@ -87,6 +87,7 @@ private slots:
void filter_qtbug30662();
void changeSourceLayout();
+ void changeSourceLayoutFilteredOut();
void removeSourceRows_data();
void removeSourceRows();
void insertSourceRows_data();
@@ -1533,6 +1534,32 @@ void tst_QSortFilterProxyModel::changeSourceLayout()
}
}
+void tst_QSortFilterProxyModel::changeSourceLayoutFilteredOut()
+{
+ QStandardItemModel model(2, 1);
+ model.setData(model.index(0, 0), QString("b"));
+ model.setData(model.index(1, 0), QString("a"));
+ QSortFilterProxyModel proxy;
+ proxy.setSourceModel(&model);
+
+ int beforeSortFilter = proxy.rowCount();
+
+ QSignalSpy removeSpy(&proxy, &QSortFilterProxyModel::rowsRemoved);
+ // Filter everything out
+ proxy.setFilterRegExp(QRegExp("c"));
+ QCOMPARE(removeSpy.count(), 1);
+ QCOMPARE(0, proxy.rowCount());
+
+ // change layout of source model
+ model.sort(0, Qt::AscendingOrder);
+
+ QSignalSpy insertSpy(&proxy, &QSortFilterProxyModel::rowsInserted);
+ // Remove filter; we expect an insert
+ proxy.setFilterRegExp(QRegExp(""));
+ QCOMPARE(insertSpy.count(), 1);
+ QCOMPARE(beforeSortFilter, proxy.rowCount());
+}
+
void tst_QSortFilterProxyModel::removeSourceRows_data()
{
QTest::addColumn<QStringList>("sourceItems");
diff --git a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro b/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro
index 0602b9fc38..1039f2c08d 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro
+++ b/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro
@@ -3,3 +3,4 @@ TARGET = tst_qcoreapplication
QT = core testlib core-private
SOURCES = tst_qcoreapplication.cpp
HEADERS = tst_qcoreapplication.h
+requires(contains(QT_CONFIG,private_tests))
diff --git a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
index efecf31d66..060ef99d65 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
+++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
@@ -78,6 +78,21 @@ public:
}
};
+class Thread : public QDaemonThread
+{
+ void run() Q_DECL_OVERRIDE
+ {
+ QThreadData *data = QThreadData::current();
+ QVERIFY(!data->requiresCoreApplication); // daemon thread
+ data->requiresCoreApplication = requiresCoreApplication;
+ QThread::run();
+ }
+
+public:
+ Thread() : requiresCoreApplication(true) {}
+ bool requiresCoreApplication;
+};
+
void tst_QCoreApplication::sendEventsOnProcessEvents()
{
int argc = 1;
@@ -853,6 +868,68 @@ void tst_QCoreApplication::applicationEventFilters_auxThread()
QVERIFY(!spy.recordedEvents.contains(QEvent::User + 1));
}
+void tst_QCoreApplication::threadedEventDelivery_data()
+{
+ QTest::addColumn<bool>("requiresCoreApplication");
+ QTest::addColumn<bool>("createCoreApplication");
+ QTest::addColumn<bool>("eventsReceived");
+
+ // invalid combination:
+ //QTest::newRow("default-without-coreapp") << true << false << false;
+ QTest::newRow("default") << true << true << true;
+ QTest::newRow("independent-without-coreapp") << false << false << true;
+ QTest::newRow("independent-with-coreapp") << false << true << true;
+}
+
+// posts the event before the QCoreApplication is destroyed, starts thread after
+void tst_QCoreApplication::threadedEventDelivery()
+{
+ QFETCH(bool, requiresCoreApplication);
+ QFETCH(bool, createCoreApplication);
+ QFETCH(bool, eventsReceived);
+
+ int argc = 1;
+ char *argv[] = { const_cast<char*>(QTest::currentAppName()) };
+ QScopedPointer<TestApplication> app(createCoreApplication ? new TestApplication(argc, argv) : 0);
+
+ Thread thread;
+ thread.requiresCoreApplication = requiresCoreApplication;
+ ThreadedEventReceiver receiver;
+ receiver.moveToThread(&thread);
+ QCoreApplication::postEvent(&receiver, new QEvent(QEvent::Type(QEvent::User + 1)));
+
+ thread.start();
+ QVERIFY(thread.wait(1000));
+ QCOMPARE(receiver.recordedEvents.contains(QEvent::User + 1), eventsReceived);
+}
+
+void tst_QCoreApplication::addRemoveLibPaths()
+{
+ QStringList paths = QCoreApplication::libraryPaths();
+ if (paths.isEmpty())
+ QSKIP("Cannot add/remove library paths if there are none.");
+
+ QString currentDir = QDir().absolutePath();
+ QCoreApplication::addLibraryPath(currentDir);
+ QVERIFY(QCoreApplication::libraryPaths().contains(currentDir));
+
+ QCoreApplication::removeLibraryPath(paths[0]);
+ QVERIFY(!QCoreApplication::libraryPaths().contains(paths[0]));
+
+ int argc = 1;
+ char *argv[] = { const_cast<char*>(QTest::currentAppName()) };
+ TestApplication app(argc, argv);
+
+ // Check that modifications stay alive across the creation of an application.
+ QVERIFY(QCoreApplication::libraryPaths().contains(currentDir));
+ QVERIFY(!QCoreApplication::libraryPaths().contains(paths[0]));
+
+ QStringList replace;
+ replace << currentDir << paths[0];
+ QCoreApplication::setLibraryPaths(replace);
+ QVERIFY(QCoreApplication::libraryPaths() == replace);
+}
+
static void createQObjectOnDestruction()
{
// Make sure that we can create a QObject after the last QObject has been
diff --git a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
index 09e15723ac..d9296b3846 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
+++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
@@ -61,6 +61,9 @@ private slots:
void QTBUG31606_QEventDestructorDeadLock();
void applicationEventFilters_mainThread();
void applicationEventFilters_auxThread();
+ void threadedEventDelivery_data();
+ void threadedEventDelivery();
+ void addRemoveLibPaths();
};
#endif // TST_QCOREAPPLICATION_H
diff --git a/tests/auto/corelib/kernel/qeventdispatcher/BLACKLIST b/tests/auto/corelib/kernel/qeventdispatcher/BLACKLIST
new file mode 100644
index 0000000000..00be65751b
--- /dev/null
+++ b/tests/auto/corelib/kernel/qeventdispatcher/BLACKLIST
@@ -0,0 +1,4 @@
+[sendPostedEvents]
+windows
+[registerTimer]
+windows
diff --git a/tests/auto/corelib/kernel/qeventloop/BLACKLIST b/tests/auto/corelib/kernel/qeventloop/BLACKLIST
new file mode 100644
index 0000000000..6ea6314b0a
--- /dev/null
+++ b/tests/auto/corelib/kernel/qeventloop/BLACKLIST
@@ -0,0 +1,2 @@
+[testQuitLock]
+windows
diff --git a/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp b/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
index a18c9eb370..4d54aa4dc8 100644
--- a/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
+++ b/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
@@ -46,6 +46,7 @@ class tst_QMetaProperty : public QObject
Q_PROPERTY(int value8 READ value8)
Q_PROPERTY(int value9 READ value9 CONSTANT)
Q_PROPERTY(int value10 READ value10 FINAL)
+ Q_PROPERTY(QMap<int, int> map MEMBER map)
private slots:
void hasStdCppSet();
@@ -53,6 +54,7 @@ private slots:
void isFinal();
void gadget();
void readAndWriteWithLazyRegistration();
+ void mapProperty();
public:
enum EnumType { EnumType1 };
@@ -65,6 +67,8 @@ public:
int value8() const { return 1; }
int value9() const { return 1; }
int value10() const { return 1; }
+
+ QMap<int, int> map;
};
void tst_QMetaProperty::hasStdCppSet()
@@ -182,6 +186,14 @@ void tst_QMetaProperty::readAndWriteWithLazyRegistration()
QCOMPARE(o.property("write").value<CustomWriteObjectChild*>(), &data);
}
+void tst_QMetaProperty::mapProperty()
+{
+ map.insert(5, 9);
+ QVariant v1 = QVariant::fromValue(map);
+ QVariant v = property("map");
+ QVERIFY(v.isValid());
+ QCOMPARE(map, (v.value<QMap<int,int> >()));
+}
QTEST_MAIN(tst_QMetaProperty)
#include "tst_qmetaproperty.moc"
diff --git a/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp b/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
index 01bf16c295..d368d9961b 100644
--- a/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
+++ b/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
@@ -70,7 +70,7 @@ void tst_QMimeData::clear() const
mimeData.setData("text/plain", "pirates");
QVERIFY(mimeData.hasText());
mimeData.clear();
- QVERIFY(mimeData.hasText() == false);
+ QVERIFY(!mimeData.hasText());
// repopulate, verify not empty
mimeData.setData("text/plain", "pirates");
@@ -136,7 +136,7 @@ void tst_QMimeData::hasColor() const
QMimeData mimeData;
// initial state
- QVERIFY(mimeData.hasColor() == false);
+ QVERIFY(!mimeData.hasColor());
// set, verify
mimeData.setColorData(QColor(Qt::red));
@@ -144,11 +144,11 @@ void tst_QMimeData::hasColor() const
// clear, verify
mimeData.clear();
- QVERIFY(mimeData.hasColor() == false);
+ QVERIFY(!mimeData.hasColor());
// set something else, verify
mimeData.setData("text/plain", "pirates");
- QVERIFY(mimeData.hasColor() == false);
+ QVERIFY(!mimeData.hasColor());
}
void tst_QMimeData::hasFormat() const
@@ -156,17 +156,17 @@ void tst_QMimeData::hasFormat() const
QMimeData mimeData;
// initial state
- QVERIFY(mimeData.hasFormat("text/plain") == false);
+ QVERIFY(!mimeData.hasFormat("text/plain"));
// add, verify
mimeData.setData("text/plain", "pirates");
QVERIFY(mimeData.hasFormat("text/plain"));
- QVERIFY(mimeData.hasFormat("text/html") == false);
+ QVERIFY(!mimeData.hasFormat("text/html"));
// clear, verify
mimeData.clear();
- QVERIFY(mimeData.hasFormat("text/plain") == false);
- QVERIFY(mimeData.hasFormat("text/html") == false);
+ QVERIFY(!mimeData.hasFormat("text/plain"));
+ QVERIFY(!mimeData.hasFormat("text/html"));
}
void tst_QMimeData::hasHtml() const
@@ -174,11 +174,11 @@ void tst_QMimeData::hasHtml() const
QMimeData mimeData;
// initial state
- QVERIFY(mimeData.hasHtml() == false);
+ QVERIFY(!mimeData.hasHtml());
// add plain, verify false
mimeData.setData("text/plain", "pirates");
- QVERIFY(mimeData.hasHtml() == false);
+ QVERIFY(!mimeData.hasHtml());
// add html, verify
mimeData.setData("text/html", "ninjas");
@@ -186,7 +186,7 @@ void tst_QMimeData::hasHtml() const
// clear, verify
mimeData.clear();
- QVERIFY(mimeData.hasHtml() == false);
+ QVERIFY(!mimeData.hasHtml());
// readd, verify
mimeData.setData("text/html", "ninjas");
@@ -198,11 +198,11 @@ void tst_QMimeData::hasImage() const
QMimeData mimeData;
// initial state
- QVERIFY(mimeData.hasImage() == false);
+ QVERIFY(!mimeData.hasImage());
// add text, verify false
mimeData.setData("text/plain", "pirates");
- QVERIFY(mimeData.hasImage() == false);
+ QVERIFY(!mimeData.hasImage());
// add image
mimeData.setImageData(QImage());
@@ -210,7 +210,7 @@ void tst_QMimeData::hasImage() const
// clear, verify
mimeData.clear();
- QVERIFY(mimeData.hasImage() == false);
+ QVERIFY(!mimeData.hasImage());
}
void tst_QMimeData::imageData() const
@@ -244,13 +244,13 @@ void tst_QMimeData::removeFormat() const
// remove, verify
mimeData.removeFormat("text/plain");
- QVERIFY(mimeData.hasFormat("text/plain") == false);
+ QVERIFY(!mimeData.hasFormat("text/plain"));
QVERIFY(mimeData.hasFormat("text/html"));
// remove, verify
mimeData.removeFormat("text/html");
- QVERIFY(mimeData.hasFormat("text/plain") == false);
- QVERIFY(mimeData.hasFormat("text/html") == false);
+ QVERIFY(!mimeData.hasFormat("text/plain"));
+ QVERIFY(!mimeData.hasFormat("text/html"));
}
void tst_QMimeData::setHtml() const
@@ -258,7 +258,7 @@ void tst_QMimeData::setHtml() const
QMimeData mimeData;
// initial state
- QVERIFY(mimeData.hasHtml() == false);
+ QVERIFY(!mimeData.hasHtml());
// add html, verify
mimeData.setHtml("ninjas");
@@ -277,7 +277,7 @@ void tst_QMimeData::setText() const
// verify initial state
QCOMPARE(mimeData.text(), QLatin1String(""));
- QVERIFY(mimeData.hasText() == false);
+ QVERIFY(!mimeData.hasText());
// set, verify
mimeData.setText("pirates");
@@ -294,7 +294,7 @@ void tst_QMimeData::setText() const
// clear, verify
mimeData.clear();
QCOMPARE(mimeData.text(), QLatin1String(""));
- QVERIFY(mimeData.hasText() == false);
+ QVERIFY(!mimeData.hasText());
}
// Publish retrieveData for verifying content validity
diff --git a/tests/auto/corelib/kernel/qobject/BLACKLIST b/tests/auto/corelib/kernel/qobject/BLACKLIST
new file mode 100644
index 0000000000..0887a73b4c
--- /dev/null
+++ b/tests/auto/corelib/kernel/qobject/BLACKLIST
@@ -0,0 +1,2 @@
+[moveToThread]
+windows
diff --git a/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp b/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
index 814c4bb691..d7cce4ada4 100644
--- a/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
+++ b/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
@@ -50,6 +50,7 @@ private slots:
void destructor();
void assignment_operators();
void equality_operators();
+ void swap();
void isNull();
void dereference_operators();
void disconnect();
@@ -169,6 +170,22 @@ void tst_QPointer::equality_operators()
#endif
}
+void tst_QPointer::swap()
+{
+ QPointer<QObject> c1, c2;
+ {
+ QObject o;
+ c1 = &o;
+ QVERIFY(c2.isNull());
+ QCOMPARE(c1.data(), &o);
+ c1.swap(c2);
+ QVERIFY(c1.isNull());
+ QCOMPARE(c2.data(), &o);
+ }
+ QVERIFY(c1.isNull());
+ QVERIFY(c2.isNull());
+}
+
void tst_QPointer::isNull()
{
QPointer<QObject> p1;
diff --git a/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST b/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST
new file mode 100644
index 0000000000..e68bf84268
--- /dev/null
+++ b/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST
@@ -0,0 +1,3 @@
+[unexpectedDisconnection]
+windows
+osx
diff --git a/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp b/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
index 1d1432f600..1dc358bd97 100644
--- a/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
+++ b/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
@@ -440,6 +440,9 @@ void tst_QTimer::deleteLaterOnQTimer()
void tst_QTimer::moveToThread()
{
+#if defined(Q_OS_WIN32)
+ QSKIP("Does not work reliably on Windows :(");
+#endif
QTimer ti1;
QTimer ti2;
ti1.start(MOVETOTHREAD_TIMEOUT);
diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
index a192ccde59..6da8f55e61 100644
--- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
+++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
@@ -3357,9 +3357,6 @@ void tst_QVariant::numericalConvert_data()
void tst_QVariant::numericalConvert()
{
-#if defined(Q_OS_LINUX) && defined(Q_CC_GNU) && !defined(__x86_64__)
- QSKIP("Known to fail due to a GCC bug on at least Ubuntu 10.04 32-bit - check QTBUG-8959");
-#endif
QFETCH(QVariant, v);
QFETCH(bool, isInteger);
double num = isInteger ? 5 : 5.3;
diff --git a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
index 8bc90d917e..dd04849f87 100644
--- a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
+++ b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
@@ -35,6 +35,7 @@
#include "qstandardpaths.h"
+#include <QtCore/QElapsedTimer>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QStandardPaths>
@@ -129,7 +130,8 @@ void tst_QMimeDatabase::initTestCase()
#ifdef USE_XDG_DATA_DIRS
// Create a temporary "global" XDG data dir for later use
// It will initially contain a copy of freedesktop.org.xml
- QVERIFY(m_temporaryDir.isValid());
+ QVERIFY2(m_temporaryDir.isValid(),
+ ("Could not create temporary subdir: " + m_temporaryDir.errorString()).toUtf8());
const QDir here = QDir(m_temporaryDir.path());
m_globalXdgDir = m_temporaryDir.path() + QStringLiteral("/global");
const QString globalPackageDir = m_globalXdgDir + QStringLiteral("/mime/packages");
@@ -818,16 +820,20 @@ static bool runUpdateMimeDatabase(const QString &path) // TODO make it a QMimeDa
return false;
}
+ QElapsedTimer timer;
QProcess proc;
proc.setProcessChannelMode(QProcess::MergedChannels); // silence output
+ qDebug().noquote() << "runUpdateMimeDatabase: running" << umd << path << "...";
+ timer.start();
proc.start(umd, QStringList(path));
if (!proc.waitForStarted()) {
qWarning("Cannot start %s: %s",
qPrintable(umd), qPrintable(proc.errorString()));
return false;
}
- proc.waitForFinished();
- //qDebug() << "runUpdateMimeDatabase" << path;
+ const bool success = proc.waitForFinished();
+ qDebug().noquote() << "runUpdateMimeDatabase: done,"
+ << success << timer.elapsed() << "ms";
return true;
}
diff --git a/tests/auto/corelib/plugin/qpluginloader/tst_qpluginloader.cpp b/tests/auto/corelib/plugin/qpluginloader/tst_qpluginloader.cpp
index bdbb291d7f..72bd38d116 100644
--- a/tests/auto/corelib/plugin/qpluginloader/tst_qpluginloader.cpp
+++ b/tests/auto/corelib/plugin/qpluginloader/tst_qpluginloader.cpp
@@ -120,6 +120,7 @@ private slots:
void loadGarbage();
#endif
void relativePath();
+ void absolutePath();
void reloadPlugin();
void preloadedPlugin_data();
void preloadedPlugin();
@@ -311,7 +312,7 @@ void tst_QPluginLoader::loadCorruptElf()
void tst_QPluginLoader::loadMachO_data()
{
-#ifdef Q_OF_MACH_O
+#if defined(QT_BUILD_INTERNAL) && defined(Q_OF_MACH_O)
QTest::addColumn<int>("parseResult");
QTest::newRow("/dev/null") << int(QMachOParser::NotSuitable);
@@ -347,7 +348,7 @@ void tst_QPluginLoader::loadMachO_data()
void tst_QPluginLoader::loadMachO()
{
-#ifdef Q_OF_MACH_O
+#if defined(QT_BUILD_INTERNAL) && defined(Q_OF_MACH_O)
QFile f(QFINDTESTDATA(QTest::currentDataTag()));
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray data = f.readAll();
@@ -406,6 +407,20 @@ void tst_QPluginLoader::relativePath()
QVERIFY(loader.unload());
}
+void tst_QPluginLoader::absolutePath()
+{
+ // Windows binaries run from release and debug subdirs, so we can't rely on the current dir.
+ const QString binDir = QFINDTESTDATA("bin");
+ QVERIFY(!binDir.isEmpty());
+ QVERIFY(QDir::isAbsolutePath(binDir));
+ QPluginLoader loader(binDir + "/theplugin");
+ loader.load(); // not recommended, instance() should do the job.
+ PluginInterface *instance = qobject_cast<PluginInterface*>(loader.instance());
+ QVERIFY(instance);
+ QCOMPARE(instance->pluginName(), QLatin1String("Plugin ok"));
+ QVERIFY(loader.unload());
+}
+
void tst_QPluginLoader::reloadPlugin()
{
QPluginLoader loader;
diff --git a/tests/auto/corelib/statemachine/qstate/tst_qstate.cpp b/tests/auto/corelib/statemachine/qstate/tst_qstate.cpp
index ac3374b6a3..c64d55671a 100644
--- a/tests/auto/corelib/statemachine/qstate/tst_qstate.cpp
+++ b/tests/auto/corelib/statemachine/qstate/tst_qstate.cpp
@@ -47,6 +47,7 @@ private slots:
void historyInitialState();
void transitions();
void privateSignals();
+ void parallelStateAndInitialState();
};
class TestClass: public QObject
@@ -344,5 +345,35 @@ void tst_QState::privateSignals()
}
+void tst_QState::parallelStateAndInitialState()
+{
+ QStateMachine machine;
+
+ { // setting an initial state on a parallel state:
+ QState a(QState::ParallelStates, &machine);
+ QState b(&a);
+ QVERIFY(!a.initialState());
+ const QString warning
+ = QString::asprintf("QState::setInitialState: ignoring attempt to set initial state of parallel state group %p", &a);
+ QTest::ignoreMessage(QtWarningMsg, qPrintable(warning));
+ a.setInitialState(&b); // should produce a warning and do nothing.
+ QVERIFY(!a.initialState());
+ }
+
+ { // setting the child-mode from ExclusiveStates to ParallelStates should remove the initial state:
+ QState a(QState::ExclusiveStates, &machine);
+ QState b(&a);
+ a.setInitialState(&b);
+ QCOMPARE(a.initialState(), &b);
+ const QString warning
+ = QString::asprintf("QState::setChildMode: setting the child-mode of state %p to "
+ "parallel removes the initial state", &a);
+ QTest::ignoreMessage(QtWarningMsg, qPrintable(warning));
+ a.setChildMode(QState::ParallelStates); // should produce a warning and remove the initial state
+ QVERIFY(!a.initialState());
+ QCOMPARE(a.childMode(), QState::ParallelStates);
+ }
+}
+
QTEST_MAIN(tst_QState)
#include "tst_qstate.moc"
diff --git a/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp b/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
index 1292c3b98f..28df7cce7b 100644
--- a/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
+++ b/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
@@ -250,6 +250,7 @@ private slots:
void internalTransition();
void conflictingTransition();
void qtbug_46059();
+ void qtbug_46703();
};
class TestState : public QState
@@ -265,7 +266,7 @@ public:
TestState(ChildMode mode, const QString &objectName = QString())
: QState(mode)
{ setObjectName(objectName); }
- QList<QPair<int, Event> > events;
+ QVector<QPair<int, Event> > events;
protected:
virtual void onEntry(QEvent *) {
events.append(qMakePair(globalTick++, Entry));
@@ -281,7 +282,7 @@ public:
TestTransition(QAbstractState *target, const QString &objectName = QString())
: QAbstractTransition()
{ setTargetState(target); setObjectName(objectName); }
- QList<int> triggers;
+ QVector<int> triggers;
protected:
virtual bool eventTest(QEvent *) {
return true;
@@ -4860,7 +4861,7 @@ public:
signalList.append(signal);
}
- QList<QMetaMethod> signalList;
+ QVector<QMetaMethod> signalList;
};
void tst_QStateMachine::testIncrementReceivers()
@@ -6485,5 +6486,59 @@ void tst_QStateMachine::qtbug_46059()
QVERIFY(machine.isRunning());
}
+void tst_QStateMachine::qtbug_46703()
+{
+ QStateMachine machine;
+ QState root(&machine);
+ QHistoryState h(&root);
+ QState p(QState::ParallelStates, &root);
+ QState a(&p);
+ QState a1(&a);
+ QState a2(&a);
+ QState a3(&a);
+ QState b(&p);
+ QState b1(&b);
+ QState b2(&b);
+
+ machine.setObjectName("machine");
+ root.setObjectName("root");
+ h.setObjectName("h");
+ p.setObjectName("p");
+ a.setObjectName("a");
+ a1.setObjectName("a1");
+ a2.setObjectName("a2");
+ a3.setObjectName("a3");
+ b.setObjectName("b");
+ b1.setObjectName("b1");
+ b2.setObjectName("b2");
+
+ machine.setInitialState(&root);
+ root.setInitialState(&h);
+ a.setInitialState(&a3);
+ b.setInitialState(&b1);
+ struct : public QAbstractTransition {
+ virtual bool eventTest(QEvent *) { return false; }
+ virtual void onTransition(QEvent *) {}
+ } defaultTransition;
+ defaultTransition.setTargetStates(QList<QAbstractState*>() << &a2 << &b2);
+ h.setDefaultTransition(&defaultTransition);
+
+ machine.start();
+ QCoreApplication::processEvents();
+
+ QTRY_COMPARE(machine.configuration().contains(&root), true);
+ QTRY_COMPARE(machine.configuration().contains(&h), false);
+ QTRY_COMPARE(machine.configuration().contains(&p), true);
+ QTRY_COMPARE(machine.configuration().contains(&a), true);
+ QTRY_COMPARE(machine.configuration().contains(&a1), false);
+ QTRY_COMPARE(machine.configuration().contains(&a2), true);
+ QTRY_COMPARE(machine.configuration().contains(&a3), false);
+ QTRY_COMPARE(machine.configuration().contains(&b), true);
+ QTRY_COMPARE(machine.configuration().contains(&b1), false);
+ QTRY_COMPARE(machine.configuration().contains(&b2), true);
+
+ QVERIFY(machine.isRunning());
+}
+
QTEST_MAIN(tst_QStateMachine)
#include "tst_qstatemachine.moc"
diff --git a/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp b/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
index e8c58a9fa5..72ae68f81a 100644
--- a/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
+++ b/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
@@ -479,34 +479,34 @@ void tst_QAtomicInt::testAndSet_data()
QTest::addColumn<int>("value");
QTest::addColumn<int>("expected");
QTest::addColumn<int>("newval");
- QTest::addColumn<int>("result");
+ QTest::addColumn<bool>("result");
// these should succeed
- QTest::newRow("success0") << 0 << 0 << 0 << 1;
- QTest::newRow("success1") << 0 << 0 << 1 << 1;
- QTest::newRow("success2") << 0 << 0 << -1 << 1;
- QTest::newRow("success3") << 1 << 1 << 0 << 1;
- QTest::newRow("success4") << 1 << 1 << 1 << 1;
- QTest::newRow("success5") << 1 << 1 << -1 << 1;
- QTest::newRow("success6") << -1 << -1 << 0 << 1;
- QTest::newRow("success7") << -1 << -1 << 1 << 1;
- QTest::newRow("success8") << -1 << -1 << -1 << 1;
- QTest::newRow("success9") << INT_MIN+1 << INT_MIN+1 << INT_MIN+1 << 1;
- QTest::newRow("successA") << INT_MIN+1 << INT_MIN+1 << 1 << 1;
- QTest::newRow("successB") << INT_MIN+1 << INT_MIN+1 << -1 << 1;
- QTest::newRow("successC") << INT_MAX << INT_MAX << INT_MAX << 1;
- QTest::newRow("successD") << INT_MAX << INT_MAX << 1 << 1;
- QTest::newRow("successE") << INT_MAX << INT_MAX << -1 << 1;
+ QTest::newRow("success0") << 0 << 0 << 0 << true;
+ QTest::newRow("success1") << 0 << 0 << 1 << true;
+ QTest::newRow("success2") << 0 << 0 << -1 << true;
+ QTest::newRow("success3") << 1 << 1 << 0 << true;
+ QTest::newRow("success4") << 1 << 1 << 1 << true;
+ QTest::newRow("success5") << 1 << 1 << -1 << true;
+ QTest::newRow("success6") << -1 << -1 << 0 << true;
+ QTest::newRow("success7") << -1 << -1 << 1 << true;
+ QTest::newRow("success8") << -1 << -1 << -1 << true;
+ QTest::newRow("success9") << INT_MIN+1 << INT_MIN+1 << INT_MIN+1 << true;
+ QTest::newRow("successA") << INT_MIN+1 << INT_MIN+1 << 1 << true;
+ QTest::newRow("successB") << INT_MIN+1 << INT_MIN+1 << -1 << true;
+ QTest::newRow("successC") << INT_MAX << INT_MAX << INT_MAX << true;
+ QTest::newRow("successD") << INT_MAX << INT_MAX << 1 << true;
+ QTest::newRow("successE") << INT_MAX << INT_MAX << -1 << true;
// these should fail
- QTest::newRow("failure0") << 0 << 1 << ~0 << 0;
- QTest::newRow("failure1") << 0 << -1 << ~0 << 0;
- QTest::newRow("failure2") << 1 << 0 << ~0 << 0;
- QTest::newRow("failure3") << -1 << 0 << ~0 << 0;
- QTest::newRow("failure4") << 1 << -1 << ~0 << 0;
- QTest::newRow("failure5") << -1 << 1 << ~0 << 0;
- QTest::newRow("failure6") << INT_MIN+1 << INT_MAX << ~0 << 0;
- QTest::newRow("failure7") << INT_MAX << INT_MIN+1 << ~0 << 0;
+ QTest::newRow("failure0") << 0 << 1 << ~0 << false;
+ QTest::newRow("failure1") << 0 << -1 << ~0 << false;
+ QTest::newRow("failure2") << 1 << 0 << ~0 << false;
+ QTest::newRow("failure3") << -1 << 0 << ~0 << false;
+ QTest::newRow("failure4") << 1 << -1 << ~0 << false;
+ QTest::newRow("failure5") << -1 << 1 << ~0 << false;
+ QTest::newRow("failure6") << INT_MIN+1 << INT_MAX << ~0 << false;
+ QTest::newRow("failure7") << INT_MAX << INT_MIN+1 << ~0 << false;
}
void tst_QAtomicInt::testAndSet()
@@ -517,26 +517,26 @@ void tst_QAtomicInt::testAndSet()
{
QAtomicInt atomic = value;
- QTEST(atomic.testAndSetRelaxed(expected, newval) ? 1 : 0, "result");
+ QTEST(atomic.testAndSetRelaxed(expected, newval), "result");
}
{
QAtomicInt atomic = value;
- QTEST(atomic.testAndSetAcquire(expected, newval) ? 1 : 0, "result");
+ QTEST(atomic.testAndSetAcquire(expected, newval), "result");
}
{
QAtomicInt atomic = value;
- QTEST(atomic.testAndSetRelease(expected, newval) ? 1 : 0, "result");
+ QTEST(atomic.testAndSetRelease(expected, newval), "result");
}
{
QAtomicInt atomic = value;
- QTEST(atomic.testAndSetOrdered(expected, newval) ? 1 : 0, "result");
+ QTEST(atomic.testAndSetOrdered(expected, newval), "result");
}
#ifdef Q_ATOMIC_INT32_IS_SUPPORTED
- QFETCH(int, result);
+ QFETCH(bool, result);
// the new implementation has the version that loads the current value
{
diff --git a/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp b/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp
index 99978a9923..ad690a094b 100644
--- a/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp
+++ b/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp
@@ -648,7 +648,7 @@ void tst_QFuture::cancel()
result.reportStarted();
f = result.future();
- QVERIFY(f.isCanceled() == false);
+ QVERIFY(!f.isCanceled());
result.reportCanceled();
QVERIFY(f.isCanceled());
result.reportFinished();
@@ -663,14 +663,14 @@ void tst_QFuture::cancel()
QFutureInterface<void> result;
QFuture<void> f;
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
result.reportStarted();
f = result.future();
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
- QVERIFY(result.isCanceled() == false);
+ QVERIFY(!result.isCanceled());
f.cancel();
QVERIFY(result.isCanceled());
@@ -683,12 +683,12 @@ void tst_QFuture::cancel()
QFutureInterface<void> result;
QFuture<void> f;
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
result.reportStarted();
f = result.future();
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
result.reportFinished();
@@ -805,12 +805,12 @@ void tst_QFuture::indexedResults()
{
QFutureInterface<QChar> Interface;
QFuture<QChar> f;
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
Interface.reportStarted();
f = Interface.future();
- QVERIFY(f.isStarted() == true);
+ QVERIFY(f.isStarted());
QChar result;
@@ -1126,14 +1126,14 @@ void tst_QFuture::iterators()
QVERIFY(it.hasNext());
QCOMPARE(it.peekNext(), resultCount - 1);
QCOMPARE(it.next(), resultCount - 1);
- QVERIFY(it.hasNext() == false);
+ QVERIFY(!it.hasNext());
}
{
QFutureIterator<int> it(f);
QVERIFY(it.hasNext());
it.toBack();
- QVERIFY(it.hasNext() == false);
+ QVERIFY(!it.hasNext());
it.toFront();
QVERIFY(it.hasNext());
}
@@ -1192,15 +1192,15 @@ void tst_QFuture::pause()
Interface.reportStarted();
QFuture<void> f = Interface.future();
- QVERIFY(Interface.isPaused() == false);
+ QVERIFY(!Interface.isPaused());
f.pause();
- QVERIFY(Interface.isPaused() == true);
+ QVERIFY(Interface.isPaused());
f.resume();
- QVERIFY(Interface.isPaused() == false);
+ QVERIFY(!Interface.isPaused());
f.togglePaused();
- QVERIFY(Interface.isPaused() == true);
+ QVERIFY(Interface.isPaused());
f.togglePaused();
- QVERIFY(Interface.isPaused() == false);
+ QVERIFY(!Interface.isPaused());
Interface.reportFinished();
}
@@ -1228,13 +1228,13 @@ void tst_QFuture::throttling()
i.reportStarted();
QFuture<void> f = i.future();
- QVERIFY(i.isThrottled() == false);
+ QVERIFY(!i.isThrottled());
i.setThrottled(true);
QVERIFY(i.isThrottled());
i.setThrottled(false);
- QVERIFY(i.isThrottled() == false);
+ QVERIFY(!i.isThrottled());
i.setThrottled(true);
QVERIFY(i.isThrottled());
diff --git a/tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp b/tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp
index 8831345ad7..60a4d749c9 100644
--- a/tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp
+++ b/tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp
@@ -743,7 +743,7 @@ void tst_QFutureWatcher::finishedState()
iface.reportFinished();
QVERIFY(future.isFinished());
- QVERIFY(watcher.isFinished() == false);
+ QVERIFY(!watcher.isFinished());
QTest::qWait(10);
QVERIFY(watcher.isFinished());
@@ -761,18 +761,18 @@ void tst_QFutureWatcher::throttling()
QFutureWatcher<int> watcher;
watcher.setFuture(future);
- QVERIFY(iface.isThrottled() == false);
+ QVERIFY(!iface.isThrottled());
for (int i = 0; i < 1000; ++i) {
int result = 0;
iface.reportResult(result);
}
- QVERIFY(iface.isThrottled() == true);
+ QVERIFY(iface.isThrottled());
QTest::qWait(100); // process events.
- QVERIFY(iface.isThrottled() == false);
+ QVERIFY(!iface.isThrottled());
iface.reportFinished();
}
diff --git a/tests/auto/corelib/thread/qsemaphore/BLACKLIST b/tests/auto/corelib/thread/qsemaphore/BLACKLIST
new file mode 100644
index 0000000000..9f6f6e3ba6
--- /dev/null
+++ b/tests/auto/corelib/thread/qsemaphore/BLACKLIST
@@ -0,0 +1,3 @@
+# Times out randomly on linux, windows, osx
+[tryAcquireWithTimeout]
+*
diff --git a/tests/auto/corelib/thread/qthread/BLACKLIST b/tests/auto/corelib/thread/qthread/BLACKLIST
new file mode 100644
index 0000000000..d75249454f
--- /dev/null
+++ b/tests/auto/corelib/thread/qthread/BLACKLIST
@@ -0,0 +1,2 @@
+[wait3_slowDestructor]
+windows
diff --git a/tests/auto/corelib/thread/qthreadpool/BLACKLIST b/tests/auto/corelib/thread/qthreadpool/BLACKLIST
new file mode 100644
index 0000000000..684f650a72
--- /dev/null
+++ b/tests/auto/corelib/thread/qthreadpool/BLACKLIST
@@ -0,0 +1,5 @@
+[expiryTimeoutRace]
+osx
+[tryStartCount]
+windows msvc-2012
+linux
diff --git a/tests/auto/corelib/tools/collections/tst_collections.cpp b/tests/auto/corelib/tools/collections/tst_collections.cpp
index 7eedd5bcf7..ae8ffe48be 100644
--- a/tests/auto/corelib/tools/collections/tst_collections.cpp
+++ b/tests/auto/corelib/tools/collections/tst_collections.cpp
@@ -2235,7 +2235,7 @@ void tst_Collections::qstring()
void tst_Collections::bitArray()
{
QBitArray ba(20);
- QVERIFY(ba.testBit(17) == false);
+ QVERIFY(!ba.testBit(17));
ba.setBit(17);
QVERIFY(ba.size() == 20);
QVERIFY(ba.testBit(17)==true);
diff --git a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp
index 9bce948140..99e5c4c85d 100644..100755
--- a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp
+++ b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp
@@ -31,6 +31,7 @@
**
****************************************************************************/
+#include "../../../../../src/corelib/tools/qalgorithms.h"
#include <QtTest/QtTest>
#include <iostream>
@@ -80,6 +81,24 @@ private slots:
void popCount32() { popCount_impl<quint32>(); }
void popCount64() { popCount_impl<quint64>(); }
+ void countTrailing08_data() { countTrailing_data_impl(sizeof(quint8 )); }
+ void countTrailing16_data() { countTrailing_data_impl(sizeof(quint16)); }
+ void countTrailing32_data() { countTrailing_data_impl(sizeof(quint32)); }
+ void countTrailing64_data() { countTrailing_data_impl(sizeof(quint64)); }
+ void countTrailing08() { countTrailing_impl<quint8 >(); }
+ void countTrailing16() { countTrailing_impl<quint16>(); }
+ void countTrailing32() { countTrailing_impl<quint32>(); }
+ void countTrailing64() { countTrailing_impl<quint64>(); }
+
+ void countLeading08_data() { countLeading_data_impl(sizeof(quint8 )); }
+ void countLeading16_data() { countLeading_data_impl(sizeof(quint16)); }
+ void countLeading32_data() { countLeading_data_impl(sizeof(quint32)); }
+ void countLeading64_data() { countLeading_data_impl(sizeof(quint64)); }
+ void countLeading08() { countLeading_impl<quint8 >(); }
+ void countLeading16() { countLeading_impl<quint16>(); }
+ void countLeading32() { countLeading_impl<quint32>(); }
+ void countLeading64() { countLeading_impl<quint64>(); }
+
private:
#if Q_TEST_PERFORMANCE
void performance();
@@ -87,6 +106,14 @@ private:
void popCount_data_impl(size_t sizeof_T_Int);
template <typename T_Int>
void popCount_impl();
+
+ void countTrailing_data_impl(size_t sizeof_T_Int);
+ template <typename T_Int>
+ void countTrailing_impl();
+
+ void countLeading_data_impl(size_t sizeof_T_Int);
+ template <typename T_Int>
+ void countLeading_impl();
};
class TestInt
@@ -1084,6 +1111,86 @@ void tst_QAlgorithms::popCount_impl()
QCOMPARE(qPopulationCount(value), expected);
}
+void tst_QAlgorithms::countTrailing_data_impl(size_t sizeof_T_Int)
+{
+ using namespace QTest;
+ addColumn<quint64>("input");
+ addColumn<uint>("expected");
+
+ int nibs = sizeof_T_Int*2;
+
+ newRow(("0x"+QByteArray::number(0,16).rightJustified(nibs,'0')).constData()) << Q_UINT64_C(0) << uint(sizeof_T_Int*8);
+ for (uint i = 0; i < sizeof_T_Int*8; ++i) {
+ const quint64 input = Q_UINT64_C(1) << i;
+ newRow(("0x"+QByteArray::number(input,16).rightJustified(nibs,'0')).constData()) << input << i;
+ }
+
+ quint64 type_mask;
+ if (sizeof_T_Int>=8)
+ type_mask = ~Q_UINT64_C(0);
+ else
+ type_mask = (Q_UINT64_C(1) << (sizeof_T_Int*8))-1;
+
+ // and some random ones:
+ for (uint i = 0; i < sizeof_T_Int*8; ++i) {
+ for (uint j = 0; j < sizeof_T_Int*3; ++j) { // 3 is arbitrary
+ const quint64 r = quint64(qrand()) << 32 | quint32(qrand());
+ const quint64 b = Q_UINT64_C(1) << i;
+ const quint64 mask = ((~(b-1)) ^ b) & type_mask;
+ const quint64 input = (r&mask) | b;
+ newRow(("0x"+QByteArray::number(input,16).rightJustified(nibs,'0')).constData()) << input << i;
+ }
+ }
+}
+
+template <typename T_Int>
+void tst_QAlgorithms::countTrailing_impl()
+{
+ QFETCH(quint64, input);
+ QFETCH(uint, expected);
+
+ const T_Int value = static_cast<T_Int>(input);
+
+ QCOMPARE(qCountTrailingZeroBits(value), expected);
+}
+
+void tst_QAlgorithms::countLeading_data_impl(size_t sizeof_T_Int)
+{
+ using namespace QTest;
+ addColumn<quint64>("input");
+ addColumn<uint>("expected");
+
+ int nibs = sizeof_T_Int*2;
+
+ newRow(("0x"+QByteArray::number(0,16).rightJustified(nibs,'0')).constData()) << Q_UINT64_C(0) << uint(sizeof_T_Int*8);
+ for (uint i = 0; i < sizeof_T_Int*8; ++i) {
+ const quint64 input = Q_UINT64_C(1) << i;
+ newRow(("0x"+QByteArray::number(input,16).rightJustified(nibs,'0')).constData()) << input << uint(sizeof_T_Int*8-i-1);
+ }
+
+ // and some random ones:
+ for (uint i = 0; i < sizeof_T_Int*8; ++i) {
+ for (uint j = 0; j < sizeof_T_Int*3; ++j) { // 3 is arbitrary
+ const quint64 r = quint64(qrand()) << 32 | quint32(qrand());
+ const quint64 b = Q_UINT64_C(1) << i;
+ const quint64 mask = b-1;
+ const quint64 input = (r&mask) | b;
+ newRow(("0x"+QByteArray::number(input,16).rightJustified(nibs,'0')).constData()) << input << uint(sizeof_T_Int*8-i-1);
+ }
+ }
+}
+
+template <typename T_Int>
+void tst_QAlgorithms::countLeading_impl()
+{
+ QFETCH(quint64, input);
+ QFETCH(uint, expected);
+
+ const T_Int value = static_cast<T_Int>(input);
+
+ QCOMPARE(qCountLeadingZeroBits(value), expected);
+}
+
QTEST_APPLESS_MAIN(tst_QAlgorithms)
#include "tst_qalgorithms.moc"
diff --git a/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp b/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp
index 410b34e894..f942eab800 100644
--- a/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp
+++ b/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp
@@ -67,6 +67,7 @@ private slots:
void endsWith_data();
void endsWith();
void endsWith_char();
+ void reverseIterators();
void split_data();
void split();
void base64_data();
@@ -540,6 +541,20 @@ void tst_QByteArray::endsWith_char()
QVERIFY(!QByteArray().endsWith('\0'));
}
+void tst_QByteArray::reverseIterators()
+{
+ QByteArray s = "1234";
+ QByteArray sr = s;
+ std::reverse(sr.begin(), sr.end());
+ const QByteArray &csr = sr;
+ QVERIFY(std::equal(s.begin(), s.end(), sr.rbegin()));
+ QVERIFY(std::equal(s.begin(), s.end(), sr.crbegin()));
+ QVERIFY(std::equal(s.begin(), s.end(), csr.rbegin()));
+ QVERIFY(std::equal(sr.rbegin(), sr.rend(), s.begin()));
+ QVERIFY(std::equal(sr.crbegin(), sr.crend(), s.begin()));
+ QVERIFY(std::equal(csr.rbegin(), csr.rend(), s.begin()));
+}
+
void tst_QByteArray::split_data()
{
QTest::addColumn<QByteArray>("sample");
diff --git a/tests/auto/corelib/tools/qbytearray/tst_qbytearray_mac.mm b/tests/auto/corelib/tools/qbytearray/tst_qbytearray_mac.mm
index c2b76cc41a..95d05904a2 100644
--- a/tests/auto/corelib/tools/qbytearray/tst_qbytearray_mac.mm
+++ b/tests/auto/corelib/tools/qbytearray/tst_qbytearray_mac.mm
@@ -72,35 +72,31 @@ void tst_QByteArray_macTypes()
}
// QByteArray <-> NSData
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QByteArray qtByteArray("test bytearray");
const NSData *nsData = qtByteArray.toNSData();
QCOMPARE(QByteArray::fromNSData(nsData), qtByteArray);
- [autoreleasepool release];
}
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QByteArray qtByteArray("test bytearray");
const NSData *nsData = qtByteArray.toNSData();
QByteArray qtByteArrayCopy(qtByteArray);
qtByteArray = qtByteArray.toUpper(); // modify
QCOMPARE(QByteArray::fromNSData(nsData), qtByteArrayCopy);
- [autoreleasepool release];
}
// QByteArray <-> NSData Raw
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QByteArray qtByteArray("test bytearray");
const NSData *nsData = qtByteArray.toRawNSData();
QCOMPARE([nsData bytes], qtByteArray.constData());
- [autoreleasepool release];
}
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
const char data[] = "nsdata test";
const NSData *nsData = [NSData dataWithBytes:data length:sizeof(data)];
QByteArray qtByteArray = QByteArray::fromRawNSData(nsData);
QCOMPARE(qtByteArray.constData(), [nsData bytes]);
- [autoreleasepool release];
}
}
diff --git a/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp b/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp
index 7b1b7ce963..6e09ebb09b 100644
--- a/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp
+++ b/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp
@@ -73,6 +73,12 @@ int main(int argc, char *argv[])
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"));
parser.addOption(newlineOption);
+ // A hidden option
+ QCommandLineOption hiddenOption(QStringList() << QStringLiteral("hidden"));
+ hiddenOption.setDescription(QStringLiteral("THIS SHOULD NEVER APPEAR"));
+ hiddenOption.setHidden(true);
+ parser.addOption(hiddenOption);
+
// This program supports different options depending on the "command" (first argument).
// Call parse() to find out the positional arguments.
parser.parse(QCoreApplication::arguments());
diff --git a/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp b/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp
index 6ff46ed20b..fb0b971602 100644
--- a/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp
+++ b/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp
@@ -35,6 +35,7 @@
#include <QtCore/QCommandLineParser>
Q_DECLARE_METATYPE(char**)
+Q_DECLARE_METATYPE(QCommandLineParser::OptionsAfterPositionalArgumentsMode)
class tst_QCommandLineParser : public QObject
{
@@ -51,6 +52,8 @@ private slots:
void testPositionalArguments();
void testBooleanOption_data();
void testBooleanOption();
+ void testOptionsAndPositional_data();
+ void testOptionsAndPositional();
void testMultipleNames_data();
void testMultipleNames();
void testSingleValueOption_data();
@@ -130,7 +133,7 @@ void tst_QCommandLineParser::testBooleanOption()
QFETCH(bool, expectedIsSet);
QCoreApplication app(empty_argc, empty_argv);
QCommandLineParser parser;
- QVERIFY(parser.addOption(QCommandLineOption(QStringLiteral("b"), QStringLiteral("a boolean option"))));
+ QVERIFY(parser.addOption(QCommandLineOption(QStringLiteral("b"))));
QVERIFY(parser.parse(args));
QCOMPARE(parser.optionNames(), expectedOptionNames);
QCOMPARE(parser.isSet("b"), expectedIsSet);
@@ -141,6 +144,40 @@ void tst_QCommandLineParser::testBooleanOption()
QVERIFY(!parser.isSet("c"));
}
+void tst_QCommandLineParser::testOptionsAndPositional_data()
+{
+ QTest::addColumn<QStringList>("args");
+ QTest::addColumn<QStringList>("expectedOptionNames");
+ QTest::addColumn<bool>("expectedIsSet");
+ QTest::addColumn<QStringList>("expectedPositionalArguments");
+ QTest::addColumn<QCommandLineParser::OptionsAfterPositionalArgumentsMode>("parsingMode");
+
+ const QStringList arg = QStringList() << "arg";
+ QTest::newRow("before_positional_default") << (QStringList() << "tst_qcommandlineparser" << "-b" << "arg") << (QStringList() << "b") << true << arg << QCommandLineParser::ParseAsOptions;
+ QTest::newRow("after_positional_default") << (QStringList() << "tst_qcommandlineparser" << "arg" << "-b") << (QStringList() << "b") << true << arg << QCommandLineParser::ParseAsOptions;
+ QTest::newRow("before_positional_parseAsArg") << (QStringList() << "tst_qcommandlineparser" << "-b" << "arg") << (QStringList() << "b") << true << arg << QCommandLineParser::ParseAsPositionalArguments;
+ QTest::newRow("after_positional_parseAsArg") << (QStringList() << "tst_qcommandlineparser" << "arg" << "-b") << (QStringList()) << false << (QStringList() << "arg" << "-b") << QCommandLineParser::ParseAsPositionalArguments;
+}
+
+void tst_QCommandLineParser::testOptionsAndPositional()
+{
+ QFETCH(QStringList, args);
+ QFETCH(QStringList, expectedOptionNames);
+ QFETCH(bool, expectedIsSet);
+ QFETCH(QStringList, expectedPositionalArguments);
+ QFETCH(QCommandLineParser::OptionsAfterPositionalArgumentsMode, parsingMode);
+
+ QCoreApplication app(empty_argc, empty_argv);
+ QCommandLineParser parser;
+ parser.setOptionsAfterPositionalArgumentsMode(parsingMode);
+ QVERIFY(parser.addOption(QCommandLineOption(QStringLiteral("b"), QStringLiteral("a boolean option"))));
+ QVERIFY(parser.parse(args));
+ QCOMPARE(parser.optionNames(), expectedOptionNames);
+ QCOMPARE(parser.isSet("b"), expectedIsSet);
+ QCOMPARE(parser.values("b"), QStringList());
+ QCOMPARE(parser.positionalArguments(), expectedPositionalArguments);
+}
+
void tst_QCommandLineParser::testMultipleNames_data()
{
QTest::addColumn<QStringList>("args");
diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm b/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm
index 6bdaa94e49..0ad9a8253b 100644
--- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm
+++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm
@@ -56,19 +56,17 @@ void tst_QDateTime_macTypes()
}
// QDateTime <-> NSDate
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(0);
const NSDate *nsDate = qtDateTime.toNSDate();
QCOMPARE(QDateTime::fromNSDate(nsDate), qtDateTime);
- [autoreleasepool release];
}
{
- NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(0);
const NSDate *nsDate = qtDateTime.toNSDate();
QDateTime qtDateTimeCopy(qtDateTime);
qtDateTime.setTime_t(10000); // modify
QCOMPARE(QDateTime::fromNSDate(nsDate), qtDateTimeCopy);
- [autoreleasepool release];
}
}
diff --git a/tests/auto/corelib/tools/qhash/tst_qhash.cpp b/tests/auto/corelib/tools/qhash/tst_qhash.cpp
index 6ea33fb37f..6a5c6b5670 100644
--- a/tests/auto/corelib/tools/qhash/tst_qhash.cpp
+++ b/tests/auto/corelib/tools/qhash/tst_qhash.cpp
@@ -62,6 +62,7 @@ private slots:
void compare();
void compare2();
void iterators(); // sligthly modified from tst_QMap
+ void keyIterator();
void keys_values_uniqueKeys(); // slightly modified from tst_QMap
void noNeedlessRehashes();
@@ -965,6 +966,34 @@ void tst_QHash::iterators()
}
}
+void tst_QHash::keyIterator()
+{
+ QHash<int, int> hash;
+
+ for (int i = 0; i < 100; ++i)
+ hash.insert(i, i*100);
+
+ QHash<int, int>::key_iterator key_it = hash.keyBegin();
+ QHash<int, int>::const_iterator it = hash.cbegin();
+ for (int i = 0; i < 100; ++i) {
+ QCOMPARE(*key_it, it.key());
+ key_it++;
+ it++;
+ }
+
+ key_it = std::find(hash.keyBegin(), hash.keyEnd(), 50);
+ it = std::find(hash.cbegin(), hash.cend(), 50 * 100);
+
+ QVERIFY(key_it != hash.keyEnd());
+ QCOMPARE(*key_it, it.key());
+ QCOMPARE(*(key_it++), (it++).key());
+ QCOMPARE(*(key_it--), (it--).key());
+ QCOMPARE(*(++key_it), (++it).key());
+ QCOMPARE(*(--key_it), (--it).key());
+
+ QCOMPARE(std::count(hash.keyBegin(), hash.keyEnd(), 99), 1);
+}
+
void tst_QHash::rehash_isnt_quadratic()
{
// this test should be incredibly slow if rehash() is quadratic
diff --git a/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp b/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
index 82303b4f72..2e829bb05e 100644
--- a/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
+++ b/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
@@ -527,12 +527,12 @@ void tst_QLinkedList::contains() const
QLinkedList<T> list;
list << T_FOO << T_BAR << T_BAZ;
- QVERIFY(list.contains(T_FOO) == true);
+ QVERIFY(list.contains(T_FOO));
QVERIFY(list.contains(T_BLAH) != true);
// add it and make sure it matches
list.append(T_BLAH);
- QVERIFY(list.contains(T_BLAH) == true);
+ QVERIFY(list.contains(T_BLAH));
}
void tst_QLinkedList::containsInt() const
diff --git a/tests/auto/corelib/tools/qlist/tst_qlist.cpp b/tests/auto/corelib/tools/qlist/tst_qlist.cpp
index 1207986dde..1bb31afa9c 100644
--- a/tests/auto/corelib/tools/qlist/tst_qlist.cpp
+++ b/tests/auto/corelib/tools/qlist/tst_qlist.cpp
@@ -76,6 +76,13 @@ struct Movable {
return i == other.i;
}
+ bool operator<(const Movable &other) const
+ {
+ check(state, Constructed);
+ check(other.state, Constructed);
+ return i < other.i;
+ }
+
Movable &operator=(const Movable &other)
{
check(state, Constructed);
@@ -144,6 +151,13 @@ struct Optimal
return i == other.i;
}
+ bool operator<(const Optimal &other) const
+ {
+ check(state, Constructed);
+ check(other.state, Constructed);
+ return i < other.i;
+ }
+
Optimal &operator=(const Optimal &other)
{
check(state, Constructed);
@@ -220,6 +234,12 @@ struct Complex
return value == other.value;
}
+ bool operator<(Complex const &other) const
+ {
+ check(); other.check();
+ return value < other.value;
+ }
+
void check() const
{
QVERIFY(this == checkSum);
@@ -293,6 +313,8 @@ private slots:
void lastOptimal() const;
void lastMovable() const;
void lastComplex() const;
+ void constFirst() const;
+ void constLast() const;
void beginOptimal() const;
void beginMovable() const;
void beginComplex() const;
@@ -329,6 +351,9 @@ private slots:
void replaceOptimal() const;
void replaceMovable() const;
void replaceComplex() const;
+ void reverseIteratorsOptimal() const;
+ void reverseIteratorsMovable() const;
+ void reverseIteratorsComplex() const;
void startsWithOptimal() const;
void startsWithMovable() const;
void startsWithComplex() const;
@@ -376,6 +401,9 @@ private slots:
void eraseValidIteratorsOnSharedList() const;
void insertWithValidIteratorsOnSharedList() const;
+ void qhashOptimal() const { qhash<Optimal>(); }
+ void qhashMovable() const { qhash<Movable>(); }
+ void qhashComplex() const { qhash<Complex>(); }
void reserve() const;
private:
template<typename T> void length() const;
@@ -392,10 +420,12 @@ private:
template<typename T> void endsWith() const;
template<typename T> void lastIndexOf() const;
template<typename T> void move() const;
+ template<typename T> void qhash() const;
template<typename T> void removeAll() const;
template<typename T> void removeAt() const;
template<typename T> void removeOne() const;
template<typename T> void replace() const;
+ template<typename T> void reverseIterators() const;
template<typename T> void startsWith() const;
template<typename T> void swap() const;
template<typename T> void takeAt() const;
@@ -701,6 +731,140 @@ void tst_QList::firstComplex() const
QCOMPARE(liveCount, Complex::getLiveCount());
}
+void tst_QList::constFirst() const
+{
+ // Based on tst_QVector::constFirst()
+ QList<int> list;
+ list << 69 << 42 << 3;
+
+ // test it starts ok
+ QCOMPARE(list.constFirst(), 69);
+ QVERIFY(list.isDetached());
+
+ QList<int> listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constFirst(), 69);
+ QCOMPARE(listCopy.constFirst(), 69);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ // test removal changes
+ list.removeAt(0);
+ QVERIFY(list.isDetached());
+ QVERIFY(!list.isSharedWith(listCopy));
+ QCOMPARE(list.constFirst(), 42);
+ QCOMPARE(listCopy.constFirst(), 69);
+
+ listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constFirst(), 42);
+ QCOMPARE(listCopy.constFirst(), 42);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ // test prepend changes
+ list.prepend(23);
+ QVERIFY(list.isDetached());
+ QVERIFY(!list.isSharedWith(listCopy));
+ QCOMPARE(list.constFirst(), 23);
+ QCOMPARE(listCopy.constFirst(), 42);
+
+ listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constFirst(), 23);
+ QCOMPARE(listCopy.constFirst(), 23);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+}
+
+void tst_QList::constLast() const
+{
+ // Based on tst_QVector::constLast()
+ QList<int> list;
+ list << 69 << 42 << 3;
+
+ // test it starts ok
+ QCOMPARE(list.constLast(), 3);
+ QVERIFY(list.isDetached());
+
+ QList<int> listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constLast(), 3);
+ QCOMPARE(listCopy.constLast(), 3);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ // test removal changes
+ list.removeLast();
+ QVERIFY(list.isDetached());
+ QVERIFY(!list.isSharedWith(listCopy));
+ QCOMPARE(list.constLast(), 42);
+ QCOMPARE(listCopy.constLast(), 3);
+
+ listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constLast(), 42);
+ QCOMPARE(listCopy.constLast(), 42);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ // test prepend changes
+ list.append(23);
+ QVERIFY(list.isDetached());
+ QVERIFY(!list.isSharedWith(listCopy));
+ QCOMPARE(list.constLast(), 23);
+ QCOMPARE(listCopy.constLast(), 42);
+
+ listCopy = list;
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+
+ QCOMPARE(list.constLast(), 23);
+ QCOMPARE(listCopy.constLast(), 23);
+
+ QVERIFY(!list.isDetached());
+ QVERIFY(!listCopy.isDetached());
+ QVERIFY(list.isSharedWith(listCopy));
+ QVERIFY(listCopy.isSharedWith(list));
+}
+
template<typename T>
void tst_QList::last() const
{
@@ -812,12 +976,12 @@ void tst_QList::contains() const
QList<T> list;
list << T_FOO << T_BAR << T_BAZ;
- QVERIFY(list.contains(T_FOO) == true);
+ QVERIFY(list.contains(T_FOO));
QVERIFY(list.contains(T_BLAH) != true);
// add it and make sure it matches
list.append(T_BLAH);
- QVERIFY(list.contains(T_BLAH) == true);
+ QVERIFY(list.contains(T_BLAH));
}
void tst_QList::containsOptimal() const
@@ -1220,6 +1384,43 @@ void tst_QList::replaceComplex() const
}
template<typename T>
+void tst_QList::reverseIterators() const
+{
+ QList<T> v;
+ v << T_CAT << T_DOG << T_BLAH << T_BAZ;
+ QList<T> vr = v;
+ std::reverse(vr.begin(), vr.end());
+ const QList<T> &cvr = vr;
+ QVERIFY(std::equal(v.begin(), v.end(), vr.rbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), vr.crbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), cvr.rbegin()));
+ QVERIFY(std::equal(vr.rbegin(), vr.rend(), v.begin()));
+ QVERIFY(std::equal(vr.crbegin(), vr.crend(), v.begin()));
+ QVERIFY(std::equal(cvr.rbegin(), cvr.rend(), v.begin()));
+}
+
+void tst_QList::reverseIteratorsOptimal() const
+{
+ const int liveCount = Optimal::getLiveCount();
+ reverseIterators<Optimal>();
+ QCOMPARE(liveCount, Optimal::getLiveCount());
+}
+
+void tst_QList::reverseIteratorsMovable() const
+{
+ const int liveCount = Movable::getLiveCount();
+ reverseIterators<Movable>();
+ QCOMPARE(liveCount, Movable::getLiveCount());
+}
+
+void tst_QList::reverseIteratorsComplex() const
+{
+ const int liveCount = Complex::getLiveCount();
+ reverseIterators<Complex>();
+ QCOMPARE(liveCount, Complex::getLiveCount());
+}
+
+template<typename T>
void tst_QList::startsWith() const
{
QList<T> list;
@@ -1576,6 +1777,19 @@ void tst_QList::testOperators() const
// []
QCOMPARE(list[0], T_FOO);
QCOMPARE(list[list.size() - 1], T_CAT);
+
+ // <, >, <=, >=
+ QVERIFY(!(list < listtwo));
+ QVERIFY(!(list > listtwo));
+ QVERIFY( list <= listtwo);
+ QVERIFY( list >= listtwo);
+ listtwo.push_back(T_CAT);
+ QVERIFY( list < listtwo);
+ QVERIFY(!(list > listtwo));
+ QVERIFY( list <= listtwo);
+ QVERIFY(!(list >= listtwo));
+ QVERIFY(listtwo > list);
+ QVERIFY(listtwo >= list);
}
void tst_QList::testOperatorsOptimal() const
@@ -1834,6 +2048,16 @@ void tst_QList::insertWithValidIteratorsOnSharedList() const
QCOMPARE(a.at(1), 15);
}
+template <typename T>
+void tst_QList::qhash() const
+{
+ QList<T> l1, l2;
+ QCOMPARE(qHash(l1), qHash(l2));
+ l1 << T_BAR;
+ l2 << T_BAR;
+ QCOMPARE(qHash(l1), qHash(l2));
+}
+
void tst_QList::reserve() const
{
// Note:
diff --git a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
index b1e13a0384..11b6922278 100644
--- a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
+++ b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
@@ -371,6 +371,8 @@ void tst_QLocale::ctor()
QString("requested: \"" + QString(req_lc) + "\", got: " \
+ QLocale::languageToString(l.language()) \
+ "/" + QLocale::countryToString(l.country())).toLatin1().constData()); \
+ QCOMPARE(l, QLocale(QLocale::exp_lang, QLocale::exp_country)); \
+ QCOMPARE(qHash(l), qHash(QLocale(QLocale::exp_lang, QLocale::exp_country))); \
}
QLocale::setDefault(QLocale(QLocale::C));
diff --git a/tests/auto/corelib/tools/qmap/tst_qmap.cpp b/tests/auto/corelib/tools/qmap/tst_qmap.cpp
index 8560a2f18c..bb6535b635 100644
--- a/tests/auto/corelib/tools/qmap/tst_qmap.cpp
+++ b/tests/auto/corelib/tools/qmap/tst_qmap.cpp
@@ -65,6 +65,7 @@ private slots:
void take();
void iterators();
+ void keyIterator();
void keys_values_uniqueKeys();
void qmultimap_specific();
@@ -835,6 +836,34 @@ void tst_QMap::iterators()
}
}
+void tst_QMap::keyIterator()
+{
+ QMap<int, int> map;
+
+ for (int i = 0; i < 100; ++i)
+ map.insert(i, i*100);
+
+ QMap<int, int>::key_iterator key_it = map.keyBegin();
+ QMap<int, int>::const_iterator it = map.cbegin();
+ for (int i = 0; i < 100; ++i) {
+ QCOMPARE(*key_it, it.key());
+ ++key_it;
+ ++it;
+ }
+
+ key_it = std::find(map.keyBegin(), map.keyEnd(), 50);
+ it = std::find(map.cbegin(), map.cend(), 50 * 100);
+
+ QVERIFY(key_it != map.keyEnd());
+ QCOMPARE(*key_it, it.key());
+ QCOMPARE(*(key_it++), (it++).key());
+ QCOMPARE(*(key_it--), (it--).key());
+ QCOMPARE(*(++key_it), (++it).key());
+ QCOMPARE(*(--key_it), (--it).key());
+
+ QCOMPARE(std::count(map.keyBegin(), map.keyEnd(), 99), 1);
+}
+
void tst_QMap::keys_values_uniqueKeys()
{
QMap<QString, int> map;
@@ -996,11 +1025,16 @@ void tst_QMap::const_shared_null()
void tst_QMap::equal_range()
{
QMap<int, QString> map;
+ const QMap<int, QString> &cmap = map;
QPair<QMap<int, QString>::iterator, QMap<int, QString>::iterator> result = map.equal_range(0);
QCOMPARE(result.first, map.end());
QCOMPARE(result.second, map.end());
+ QPair<QMap<int, QString>::const_iterator, QMap<int, QString>::const_iterator> cresult = cmap.equal_range(0);
+ QCOMPARE(cresult.first, cmap.cend());
+ QCOMPARE(cresult.second, cmap.cend());
+
map.insert(1, "one");
result = map.equal_range(0);
@@ -1015,6 +1049,18 @@ void tst_QMap::equal_range()
QCOMPARE(result.first, map.end());
QCOMPARE(result.second, map.end());
+ cresult = cmap.equal_range(0);
+ QCOMPARE(cresult.first, cmap.find(1));
+ QCOMPARE(cresult.second, cmap.find(1));
+
+ cresult = cmap.equal_range(1);
+ QCOMPARE(cresult.first, cmap.find(1));
+ QCOMPARE(cresult.second, cmap.cend());
+
+ cresult = cmap.equal_range(2);
+ QCOMPARE(cresult.first, cmap.cend());
+ QCOMPARE(cresult.second, cmap.cend());
+
for (int i = -10; i < 10; i += 2)
map.insert(i, QString("%1").arg(i));
@@ -1030,11 +1076,28 @@ void tst_QMap::equal_range()
QCOMPARE(result.first, map.find(2));
QCOMPARE(result.second, map.find(4));
+ cresult = cmap.equal_range(0);
+ QCOMPARE(cresult.first, cmap.find(0));
+ QCOMPARE(cresult.second, cmap.find(1));
+
+ cresult = cmap.equal_range(1);
+ QCOMPARE(cresult.first, cmap.find(1));
+ QCOMPARE(cresult.second, cmap.find(2));
+
+ cresult = cmap.equal_range(2);
+ QCOMPARE(cresult.first, cmap.find(2));
+ QCOMPARE(cresult.second, cmap.find(4));
+
map.insertMulti(1, "another one");
+
result = map.equal_range(1);
QCOMPARE(result.first, map.find(1));
QCOMPARE(result.second, map.find(2));
+ cresult = cmap.equal_range(1);
+ QCOMPARE(cresult.first, cmap.find(1));
+ QCOMPARE(cresult.second, cmap.find(2));
+
QCOMPARE(map.count(1), 2);
}
diff --git a/tests/auto/corelib/tools/qregexp/tst_qregexp.cpp b/tests/auto/corelib/tools/qregexp/tst_qregexp.cpp
index fefdec7496..b9a3fc13c5 100644
--- a/tests/auto/corelib/tools/qregexp/tst_qregexp.cpp
+++ b/tests/auto/corelib/tools/qregexp/tst_qregexp.cpp
@@ -1224,6 +1224,9 @@ void tst_QRegExp::operator_eq()
for (int j = 0; j < I * J * K * ELL; ++j) {
QCOMPARE(rxtable[i] == rxtable[j], i / ELL == j / ELL);
QCOMPARE(rxtable[i] != rxtable[j], i / ELL != j / ELL);
+ // this just happens to have no hash collisions. If at some point
+ // we get collisions, restrict the test to only equal elements:
+ QCOMPARE(qHash(rxtable[i]) == qHash(rxtable[j]), i / ELL == j / ELL);
}
}
}
diff --git a/tests/auto/corelib/tools/qregularexpression/tst_qregularexpression.cpp b/tests/auto/corelib/tools/qregularexpression/tst_qregularexpression.cpp
index d185e64251..8ddd4979b6 100644
--- a/tests/auto/corelib/tools/qregularexpression/tst_qregularexpression.cpp
+++ b/tests/auto/corelib/tools/qregularexpression/tst_qregularexpression.cpp
@@ -1423,6 +1423,7 @@ static void verifyEquality(const QRegularExpression &re1, const QRegularExpressi
{
QVERIFY(re1 == re2);
QVERIFY(re2 == re1);
+ QCOMPARE(qHash(re1), qHash(re2));
QVERIFY(!(re1 != re2));
QVERIFY(!(re2 != re1));
@@ -1430,22 +1431,26 @@ static void verifyEquality(const QRegularExpression &re1, const QRegularExpressi
QVERIFY(re1 == re3);
QVERIFY(re3 == re1);
+ QCOMPARE(qHash(re1), qHash(re3));
QVERIFY(!(re1 != re3));
QVERIFY(!(re3 != re1));
QVERIFY(re2 == re3);
QVERIFY(re3 == re2);
+ QCOMPARE(qHash(re2), qHash(re3));
QVERIFY(!(re2 != re3));
QVERIFY(!(re3 != re2));
re3 = re2;
QVERIFY(re1 == re3);
QVERIFY(re3 == re1);
+ QCOMPARE(qHash(re1), qHash(re3));
QVERIFY(!(re1 != re3));
QVERIFY(!(re3 != re1));
QVERIFY(re2 == re3);
QVERIFY(re3 == re2);
+ QCOMPARE(qHash(re2), qHash(re3));
QVERIFY(!(re2 != re3));
QVERIFY(!(re3 != re2));
}
diff --git a/tests/auto/corelib/tools/qringbuffer/tst_qringbuffer.cpp b/tests/auto/corelib/tools/qringbuffer/tst_qringbuffer.cpp
index 8c29064457..77fc6ad6ae 100644
--- a/tests/auto/corelib/tools/qringbuffer/tst_qringbuffer.cpp
+++ b/tests/auto/corelib/tools/qringbuffer/tst_qringbuffer.cpp
@@ -48,10 +48,12 @@ private slots:
void sizeWhenReserved();
void free();
void reserveAndRead();
+ void reserveFrontAndRead();
void chop();
void ungetChar();
void indexOf();
void appendAndRead();
+ void peek();
void readLine();
};
@@ -60,7 +62,7 @@ void tst_QRingBuffer::sizeWhenReserved()
QRingBuffer ringBuffer;
ringBuffer.reserve(5);
- QCOMPARE(ringBuffer.size(), 5);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(5));
}
void tst_QRingBuffer::sizeWhenReservedAndChopped()
@@ -69,14 +71,14 @@ void tst_QRingBuffer::sizeWhenReservedAndChopped()
ringBuffer.reserve(31337);
ringBuffer.chop(31337);
- QCOMPARE(ringBuffer.size(), 0);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(0));
}
void tst_QRingBuffer::sizeWhenEmpty()
{
QRingBuffer ringBuffer;
- QCOMPARE(ringBuffer.size(), 0);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(0));
}
void tst_QRingBuffer::readPointerAtPositionReadTooMuch()
@@ -86,7 +88,7 @@ void tst_QRingBuffer::readPointerAtPositionReadTooMuch()
qint64 length;
const char *buf = ringBuffer.readPointerAtPosition(42, length);
QVERIFY(buf == 0);
- QVERIFY(length == 0);
+ QCOMPARE(length, Q_INT64_C(0));
}
void tst_QRingBuffer::readPointerAtPositionWithHead()
@@ -101,22 +103,22 @@ void tst_QRingBuffer::readPointerAtPositionWithHead()
qint64 length;
const char* buf2 = ringBuffer.readPointerAtPosition(0, length);
- QCOMPARE(length, qint64(2));
- QVERIFY(*buf2 == '2');
- QVERIFY(*(buf2+1) == '3');
+ QCOMPARE(length, Q_INT64_C(2));
+ QCOMPARE(*buf2, '2');
+ QCOMPARE(*(buf2 + 1), '3');
// advance 2 more, ringBuffer should be empty then
ringBuffer.free(2);
buf2 = ringBuffer.readPointerAtPosition(0, length);
- QCOMPARE(length, qint64(0));
+ QCOMPARE(length, Q_INT64_C(0));
QVERIFY(buf2 == 0);
// check buffer with 2 blocks
memcpy(ringBuffer.reserve(4), "0123", 4);
ringBuffer.append(QByteArray("45678", 5));
ringBuffer.free(3);
- buf2 = ringBuffer.readPointerAtPosition(1, length);
- QCOMPARE(length, qint64(5));
+ buf2 = ringBuffer.readPointerAtPosition(Q_INT64_C(1), length);
+ QCOMPARE(length, Q_INT64_C(5));
}
void tst_QRingBuffer::readPointerAtPositionEmptyRead()
@@ -126,7 +128,7 @@ void tst_QRingBuffer::readPointerAtPositionEmptyRead()
qint64 length;
const char *buf = ringBuffer.readPointerAtPosition(0, length);
QVERIFY(buf == 0);
- QVERIFY(length == 0);
+ QCOMPARE(length, Q_INT64_C(0));
}
void tst_QRingBuffer::readPointerAtPositionWriteRead()
@@ -149,14 +151,14 @@ void tst_QRingBuffer::readPointerAtPositionWriteRead()
// write in chunks of 50 bytes
// this ensures there will be multiple QByteArrays inside the QRingBuffer
// since QRingBuffer is then only using individual arrays of around 4000 bytes
- qint64 thisWrite = qMin(remaining, qint64(50));
+ qint64 thisWrite = qMin(remaining, Q_INT64_C(50));
char *pos = ringBuffer.reserve(thisWrite);
inData.read(pos, thisWrite);
remaining -= thisWrite;
}
// was data put into it?
QVERIFY(ringBuffer.size() > 0);
- QCOMPARE(qint64(ringBuffer.size()), inData.size());
+ QCOMPARE(ringBuffer.size(), inData.size());
//read from the QRingBuffer in loop, put back into another QBuffer
QBuffer outData;
@@ -187,12 +189,12 @@ void tst_QRingBuffer::free()
ringBuffer.append(QByteArray("01234", 5));
ringBuffer.free(1);
- QCOMPARE(ringBuffer.size(), 4095 + 2048 + 5);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(4095 + 2048 + 5));
ringBuffer.free(4096);
- QCOMPARE(ringBuffer.size(), 2047 + 5);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(2047 + 5));
ringBuffer.free(48);
ringBuffer.free(2000);
- QCOMPARE(ringBuffer.size(), 4);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(4));
QVERIFY(memcmp(ringBuffer.readPointer(), "1234", 4) == 0);
}
@@ -211,11 +213,33 @@ void tst_QRingBuffer::reserveAndRead()
for (int i = 1; i < 256; ++i) {
QByteArray ba;
ba.resize(i);
- int thisRead = ringBuffer.read(ba.data(), i);
- QCOMPARE(thisRead, i);
- QVERIFY(ba.count(char(i)) == i);
+ qint64 thisRead = ringBuffer.read(ba.data(), i);
+ QCOMPARE(thisRead, qint64(i));
+ QCOMPARE(ba.count(char(i)), i);
}
- QVERIFY(ringBuffer.size() == 0);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(0));
+}
+
+void tst_QRingBuffer::reserveFrontAndRead()
+{
+ QRingBuffer ringBuffer;
+ // fill buffer with an arithmetic progression
+ for (int i = 1; i < 256; ++i) {
+ QByteArray ba(i, char(i));
+ char *ringPos = ringBuffer.reserveFront(i);
+ QVERIFY(ringPos);
+ memcpy(ringPos, ba.constData(), i);
+ }
+
+ // readback and check stored data
+ for (int i = 255; i > 0; --i) {
+ QByteArray ba;
+ ba.resize(i);
+ qint64 thisRead = ringBuffer.read(ba.data(), i);
+ QCOMPARE(thisRead, qint64(i));
+ QCOMPARE(ba.count(char(i)), i);
+ }
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(0));
}
void tst_QRingBuffer::chop()
@@ -227,12 +251,12 @@ void tst_QRingBuffer::chop()
ringBuffer.reserve(4096);
ringBuffer.chop(1);
- QCOMPARE(ringBuffer.size(), 5 + 2048 + 4095);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(5 + 2048 + 4095));
ringBuffer.chop(4096);
- QCOMPARE(ringBuffer.size(), 5 + 2047);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(5 + 2047));
ringBuffer.chop(48);
ringBuffer.chop(2000);
- QCOMPARE(ringBuffer.size(), 4);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(4));
QVERIFY(memcmp(ringBuffer.readPointer(), "0123", 4) == 0);
}
@@ -244,11 +268,11 @@ void tst_QRingBuffer::ungetChar()
for (int i = 1; i < 31; ++i) {
int c = ringBuffer.getChar();
- QVERIFY(c == 1);
+ QCOMPARE(c, 1);
ringBuffer.getChar();
ringBuffer.ungetChar(char(c)); // unget first char
}
- QCOMPARE(ringBuffer.size(), 1);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(1));
}
void tst_QRingBuffer::indexOf()
@@ -258,10 +282,10 @@ void tst_QRingBuffer::indexOf()
ringBuffer.putChar(char(i));
for (int i = 1; i < 256; ++i) {
- int index = ringBuffer.indexOf(char(i));
- QCOMPARE(i - 1, index);
- QCOMPARE(index, ringBuffer.indexOf(char(i), i));
- QVERIFY(ringBuffer.indexOf(char(i), i - 1) == -1); // test for absent char
+ qint64 index = ringBuffer.indexOf(char(i));
+ QCOMPARE(index, qint64(i - 1));
+ QCOMPARE(ringBuffer.indexOf(char(i), i), index);
+ QCOMPARE(ringBuffer.indexOf(char(i), i - 1), -1); // test for absent char
}
}
@@ -275,9 +299,34 @@ void tst_QRingBuffer::appendAndRead()
ringBuffer.append(ba2);
ringBuffer.append(ba3);
- QVERIFY(ringBuffer.read() == ba1);
- QVERIFY(ringBuffer.read() == ba2);
- QVERIFY(ringBuffer.read() == ba3);
+ QCOMPARE(ringBuffer.read(), ba1);
+ QCOMPARE(ringBuffer.read(), ba2);
+ QCOMPARE(ringBuffer.read(), ba3);
+}
+
+void tst_QRingBuffer::peek()
+{
+ QRingBuffer ringBuffer;
+ QByteArray testBuffer;
+ // fill buffer with an arithmetic progression
+ for (int i = 1; i < 256; ++i) {
+ char *ringPos = ringBuffer.reserve(i);
+ QVERIFY(ringPos);
+ memset(ringPos, i, i);
+ testBuffer.append(ringPos, i);
+ }
+
+ // check stored data
+ QByteArray resultBuffer;
+ int peekPosition = testBuffer.size();
+ for (int i = 1; i < 256; ++i) {
+ QByteArray ba(i, 0);
+ peekPosition -= i;
+ qint64 thisPeek = ringBuffer.peek(ba.data(), i, peekPosition);
+ QCOMPARE(thisPeek, qint64(i));
+ resultBuffer.prepend(ba);
+ }
+ QCOMPARE(resultBuffer, testBuffer);
}
void tst_QRingBuffer::readLine()
@@ -293,18 +342,18 @@ void tst_QRingBuffer::readLine()
char stringBuf[102];
stringBuf[101] = 0; // non-crash terminator
- QVERIFY(ringBuffer.readLine(stringBuf, sizeof(stringBuf) - 2) == ba1.size());
- QVERIFY(QByteArray(stringBuf, int(strlen(stringBuf))) == ba1);
+ QCOMPARE(ringBuffer.readLine(stringBuf, sizeof(stringBuf) - 2), qint64(ba1.size()));
+ QCOMPARE(QByteArray(stringBuf, int(strlen(stringBuf))), ba1);
// check first empty string reading
stringBuf[0] = char(0xFF);
- QCOMPARE(ringBuffer.readLine(stringBuf, int(sizeof(stringBuf)) - 2), ba2.size());
- QVERIFY(stringBuf[0] == ba2[0]);
+ QCOMPARE(ringBuffer.readLine(stringBuf, int(sizeof(stringBuf)) - 2), qint64(ba2.size()));
+ QCOMPARE(stringBuf[0], ba2.at(0));
- QVERIFY(ringBuffer.readLine(stringBuf, int(sizeof(stringBuf)) - 2) == (ba3.size() + ba4.size()
- + ba2.size()));
- QVERIFY(QByteArray(stringBuf, int(strlen(stringBuf))) == (ba3 + ba4 + ba2));
- QVERIFY(ringBuffer.size() == 0);
+ QCOMPARE(ringBuffer.readLine(stringBuf, int(sizeof(stringBuf)) - 2),
+ qint64(ba3.size() + ba4.size() + ba2.size()));
+ QCOMPARE(QByteArray(stringBuf, int(strlen(stringBuf))), ba3 + ba4 + ba2);
+ QCOMPARE(ringBuffer.size(), Q_INT64_C(0));
}
QTEST_APPLESS_MAIN(tst_QRingBuffer)
diff --git a/tests/auto/corelib/tools/qset/tst_qset.cpp b/tests/auto/corelib/tools/qset/tst_qset.cpp
index f13d69514a..ef0ebabd66 100644
--- a/tests/auto/corelib/tools/qset/tst_qset.cpp
+++ b/tests/auto/corelib/tools/qset/tst_qset.cpp
@@ -73,6 +73,7 @@ private slots:
void makeSureTheComfortFunctionsCompile();
void initializerList();
void qhash();
+ void intersects();
};
struct IdentityTracker {
@@ -1030,6 +1031,32 @@ void tst_QSet::qhash()
}
}
+void tst_QSet::intersects()
+{
+ QSet<int> s1;
+ QSet<int> s2;
+
+ QVERIFY(!s1.intersects(s1));
+ QVERIFY(!s1.intersects(s2));
+
+ s1 << 100;
+ QVERIFY(s1.intersects(s1));
+ QVERIFY(!s1.intersects(s2));
+
+ s2 << 200;
+ QVERIFY(!s1.intersects(s2));
+
+ s1 << 200;
+ QVERIFY(s1.intersects(s2));
+
+ const QtQHashSeedSaver seedSaver(0x10101010);
+ QSet<int> s3;
+ s3 << 500;
+ QVERIFY(!s1.intersects(s3));
+ s3 << 200;
+ QVERIFY(s1.intersects(s3));
+}
+
QTEST_APPLESS_MAIN(tst_QSet)
#include "tst_qset.moc"
diff --git a/tests/auto/corelib/tools/qstring/tst_qstring.cpp b/tests/auto/corelib/tools/qstring/tst_qstring.cpp
index 6d4dbab1fd..745cbbfad3 100644
--- a/tests/auto/corelib/tools/qstring/tst_qstring.cpp
+++ b/tests/auto/corelib/tools/qstring/tst_qstring.cpp
@@ -60,11 +60,241 @@
#include <qhash.h>
#include <string>
+#include <algorithm>
#define CREATE_REF(string) \
const QString padded = QString::fromLatin1(" %1 ").arg(string); \
QStringRef ref = padded.midRef(1, padded.size() - 2);
+namespace {
+
+// this wraps an argument to a QString function, as well as how to apply
+// the argument to a given QString member function.
+template <typename T>
+class Arg;
+
+template <typename T>
+class Reversed {}; // marker for Arg<QChar> to apply the operation in reverse order (for prepend())
+
+class ArgBase
+{
+protected:
+ QString pinned;
+ explicit ArgBase(const char *str)
+ : pinned(QString::fromLatin1(str)) {}
+};
+
+template <>
+class Arg<QChar> : protected ArgBase
+{
+public:
+ explicit Arg(const char *str) : ArgBase(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { Q_FOREACH (QChar ch, this->pinned) (s.*mf)(ch); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { Q_FOREACH (QChar ch, this->pinned) (s.*mf)(a1, ch); }
+};
+
+template <>
+class Arg<Reversed<QChar> > : private Arg<QChar>
+{
+public:
+ explicit Arg(const char *str) : Arg<QChar>(str)
+ {
+ std::reverse(this->pinned.begin(), this->pinned.end());
+ }
+
+ using Arg<QChar>::apply0;
+ using Arg<QChar>::apply1;
+};
+
+template <>
+class Arg<QString> : ArgBase
+{
+public:
+ explicit Arg(const char *str) : ArgBase(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(this->pinned); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, this->pinned); }
+};
+
+template <>
+class Arg<QStringRef> : ArgBase
+{
+ QStringRef ref() const
+ { return this->pinned.isNull() ? QStringRef() : this->pinned.midRef(0) ; }
+public:
+ explicit Arg(const char *str) : ArgBase(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(ref()); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, ref()); }
+};
+
+template <>
+class Arg<QPair<const QChar *, int> > : ArgBase
+{
+public:
+ explicit Arg(const char *str) : ArgBase(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(this->pinned.constData(), this->pinned.length()); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, this->pinned.constData(), this->pinned.length()); }
+};
+
+template <>
+class Arg<QLatin1String>
+{
+ QLatin1String l1;
+public:
+ explicit Arg(const char *str) : l1(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(l1); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, l1); }
+};
+
+template <>
+class Arg<char>
+{
+protected:
+ const char *str;
+public:
+ explicit Arg(const char *str) : str(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ {
+ if (str) {
+ for (const char *it = str; *it; ++it)
+ (s.*mf)(*it);
+ }
+ }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ {
+ if (str) {
+ for (const char *it = str; *it; ++it)
+ (s.*mf)(a1, *it);
+ }
+ }
+};
+
+template <>
+class Arg<Reversed<char> > : private Arg<char>
+{
+ static const char *dupAndReverse(const char *s)
+ {
+ char *s2 = qstrdup(s);
+ std::reverse(s2, s2 + qstrlen(s2));
+ return s2;
+ }
+public:
+ explicit Arg(const char *str) : Arg<char>(dupAndReverse(str)) {}
+ ~Arg() { delete[] str; }
+
+ using Arg<char>::apply0;
+ using Arg<char>::apply1;
+};
+
+template <>
+class Arg<const char*>
+{
+ const char *str;
+public:
+ explicit Arg(const char *str) : str(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(str); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, str); }
+};
+
+template <>
+class Arg<QByteArray>
+{
+ QByteArray ba;
+public:
+ explicit Arg(const char *str) : ba(str) {}
+
+ template <typename MemFun>
+ void apply0(QString &s, MemFun mf) const
+ { (s.*mf)(ba); }
+
+ template <typename MemFun, typename A1>
+ void apply1(QString &s, MemFun mf, A1 a1) const
+ { (s.*mf)(a1, ba); }
+};
+
+// const char* is not allowed as columns in data-driven tests (causes static_assert failure),
+// so wrap it in a container (default ctor is a QMetaType/QVariant requirement):
+class CharStarContainer
+{
+ const char *str;
+public:
+ explicit Q_DECL_CONSTEXPR CharStarContainer(const char *s = Q_NULLPTR) : str(s) {}
+ Q_DECL_CONSTEXPR operator const char *() const { return str; }
+};
+
+} // unnamed namespace
+
+Q_DECLARE_METATYPE(CharStarContainer)
+
+// implementation helpers for append_impl/prepend_impl etc
+template <typename ArgType, typename MemFun>
+static void do_apply0(MemFun mf)
+{
+ QFETCH(QString, s);
+ QFETCH(CharStarContainer, arg);
+ QFETCH(QString, expected);
+
+ Arg<ArgType>(arg).apply0(s, mf);
+
+ QCOMPARE(s, expected);
+ QCOMPARE(s.isEmpty(), expected.isEmpty());
+ QCOMPARE(s.isNull(), expected.isNull());
+}
+
+template <typename ArgType, typename A1, typename MemFun>
+static void do_apply1(MemFun mf)
+{
+ QFETCH(QString, s);
+ QFETCH(CharStarContainer, arg);
+ QFETCH(A1, a1);
+ QFETCH(QString, expected);
+
+ Arg<ArgType>(arg).apply1(s, mf, a1);
+
+ QCOMPARE(s, expected);
+ QCOMPARE(s.isEmpty(), expected.isEmpty());
+ QCOMPARE(s.isNull(), expected.isNull());
+}
+
class tst_QString : public QObject
{
Q_OBJECT
@@ -73,6 +303,27 @@ class tst_QString : public QObject
void split_regexp(const QString &string, const QString &pattern, QStringList result);
template<typename List>
void split(const QString &string, const QString &separator, QStringList result);
+
+ template <typename ArgType, typename MemFun>
+ void append_impl() const { do_apply0<ArgType>(MemFun(&QString::append)); }
+ template <typename ArgType>
+ void append_impl() const { append_impl<ArgType, QString &(QString::*)(const ArgType&)>(); }
+ void append_data(bool emptyIsNoop = false);
+ template <typename ArgType, typename MemFun>
+ void operator_pluseq_impl() const { do_apply0<ArgType>(MemFun(&QString::operator+=)); }
+ template <typename ArgType>
+ void operator_pluseq_impl() const { operator_pluseq_impl<ArgType, QString &(QString::*)(const ArgType&)>(); }
+ void operator_pluseq_data(bool emptyIsNoop = false);
+ template <typename ArgType, typename MemFun>
+ void prepend_impl() const { do_apply0<ArgType>(MemFun(&QString::prepend)); }
+ template <typename ArgType>
+ void prepend_impl() const { prepend_impl<ArgType, QString &(QString::*)(const ArgType&)>(); }
+ void prepend_data(bool emptyIsNoop = false);
+ template <typename ArgType, typename MemFun>
+ void insert_impl() const { do_apply1<ArgType, int>(MemFun(&QString::insert)); }
+ template <typename ArgType>
+ void insert_impl() const { insert_impl<ArgType, QString &(QString::*)(int, const ArgType&)>(); }
+ void insert_data(bool emptyIsNoop = false);
public:
tst_QString();
public slots:
@@ -121,19 +372,86 @@ private slots:
void remove_regexp_data();
void remove_regexp();
void swap();
- void prepend();
- void prepend_bytearray_data();
- void prepend_bytearray();
- void append();
- void append_bytearray_data();
- void append_bytearray();
- void operator_pluseq_bytearray_data();
- void operator_pluseq_bytearray();
+
+ void prepend_qstring() { prepend_impl<QString>(); }
+ void prepend_qstring_data() { prepend_data(true); }
+ void prepend_qstringref() { prepend_impl<QStringRef>(); }
+ void prepend_qstringref_data() { prepend_data(true); }
+ void prepend_qlatin1string() { prepend_impl<QLatin1String, QString &(QString::*)(QLatin1String)>(); }
+ void prepend_qlatin1string_data() { prepend_data(true); }
+ void prepend_qcharstar_int() { prepend_impl<QPair<const QChar *, int>, QString &(QString::*)(const QChar *, int)>(); }
+ void prepend_qcharstar_int_data() { prepend_data(true); }
+ void prepend_qchar() { prepend_impl<Reversed<QChar>, QString &(QString::*)(QChar)>(); }
+ void prepend_qchar_data() { prepend_data(true); }
+ void prepend_qbytearray() { prepend_impl<QByteArray>(); }
+ void prepend_qbytearray_data() { prepend_data(true); }
+ void prepend_char() { prepend_impl<Reversed<char>, QString &(QString::*)(QChar)>(); }
+ void prepend_char_data() { prepend_data(true); }
+ void prepend_charstar() { prepend_impl<const char *, QString &(QString::*)(const char *)>(); }
+ void prepend_charstar_data() { prepend_data(true); }
+ void prepend_bytearray_special_cases_data();
+ void prepend_bytearray_special_cases();
+
+ void append_qstring() { append_impl<QString>(); }
+ void append_qstring_data() { append_data(); }
+ void append_qstringref() { append_impl<QStringRef>(); }
+ void append_qstringref_data() { append_data(); }
+ void append_qlatin1string() { append_impl<QLatin1String, QString &(QString::*)(QLatin1String)>(); }
+ void append_qlatin1string_data() { append_data(); }
+ void append_qcharstar_int() { append_impl<QPair<const QChar *, int>, QString&(QString::*)(const QChar *, int)>(); }
+ void append_qcharstar_int_data() { append_data(true); }
+ void append_qchar() { append_impl<QChar, QString &(QString::*)(QChar)>(); }
+ void append_qchar_data() { append_data(true); }
+ void append_qbytearray() { append_impl<QByteArray>(); }
+ void append_qbytearray_data() { append_data(); }
+ void append_char() { append_impl<char, QString &(QString::*)(QChar)>(); }
+ void append_char_data() { append_data(true); }
+ void append_charstar() { append_impl<const char *, QString &(QString::*)(const char *)>(); }
+ void append_charstar_data() { append_data(); }
+ void append_special_cases();
+ void append_bytearray_special_cases_data();
+ void append_bytearray_special_cases();
+
+ void operator_pluseq_qstring() { operator_pluseq_impl<QString>(); }
+ void operator_pluseq_qstring_data() { operator_pluseq_data(); }
+ void operator_pluseq_qstringref() { operator_pluseq_impl<QStringRef>(); }
+ void operator_pluseq_qstringref_data() { operator_pluseq_data(); }
+ void operator_pluseq_qlatin1string() { operator_pluseq_impl<QLatin1String, QString &(QString::*)(QLatin1String)>(); }
+ void operator_pluseq_qlatin1string_data() { operator_pluseq_data(); }
+ void operator_pluseq_qchar() { operator_pluseq_impl<QChar, QString &(QString::*)(QChar)>(); }
+ void operator_pluseq_qchar_data() { operator_pluseq_data(true); }
+ void operator_pluseq_qbytearray() { operator_pluseq_impl<QByteArray>(); }
+ void operator_pluseq_qbytearray_data() { operator_pluseq_data(); }
+ void operator_pluseq_char() { operator_pluseq_impl<char, QString &(QString::*)(char)>(); }
+ void operator_pluseq_char_data() { operator_pluseq_data(true); }
+ void operator_pluseq_charstar() { operator_pluseq_impl<const char *, QString &(QString::*)(const char *)>(); }
+ void operator_pluseq_charstar_data() { operator_pluseq_data(); }
+ void operator_pluseq_bytearray_special_cases_data();
+ void operator_pluseq_bytearray_special_cases();
+
void operator_eqeq_bytearray_data();
void operator_eqeq_bytearray();
void operator_eqeq_nullstring();
void operator_smaller();
- void insert();
+
+ void insert_qstring() { insert_impl<QString>(); }
+ void insert_qstring_data() { insert_data(true); }
+ void insert_qstringref() { insert_impl<QStringRef>(); }
+ void insert_qstringref_data() { insert_data(true); }
+ void insert_qlatin1string() { insert_impl<QLatin1String, QString &(QString::*)(int, QLatin1String)>(); }
+ void insert_qlatin1string_data() { insert_data(true); }
+ void insert_qcharstar_int() { insert_impl<QPair<const QChar *, int>, QString &(QString::*)(int, const QChar*, int) >(); }
+ void insert_qcharstar_int_data() { insert_data(true); }
+ void insert_qchar() { insert_impl<Reversed<QChar>, QString &(QString::*)(int, QChar)>(); }
+ void insert_qchar_data() { insert_data(true); }
+ void insert_qbytearray() { insert_impl<QByteArray>(); }
+ void insert_qbytearray_data() { insert_data(true); }
+ void insert_char() { insert_impl<Reversed<char>, QString &(QString::*)(int, QChar)>(); }
+ void insert_char_data() { insert_data(true); }
+ void insert_charstar() { insert_impl<const char *, QString &(QString::*)(int, const char*) >(); }
+ void insert_charstar_data() { insert_data(true); }
+ void insert_special_cases();
+
void simplified_data();
void simplified();
void trimmed();
@@ -183,6 +501,7 @@ private slots:
void fromLocal8Bit();
void local8Bit_data();
void local8Bit();
+ void nullFromLocal8Bit();
void fromLatin1Roundtrip_data();
void fromLatin1Roundtrip();
void toLatin1Roundtrip_data();
@@ -215,6 +534,7 @@ private slots:
void localeAwareCompare_data();
void localeAwareCompare();
#endif
+ void reverseIterators();
void split_data();
void split();
void split_regexp_data();
@@ -827,7 +1147,7 @@ void tst_QString::constructorQByteArray_data()
ba1[5] = 'e';
ba1[6] = 'f';
- QTest::newRow( "2" ) << ba1 << QString("abc");
+ QTest::newRow( "2" ) << ba1 << QStringLiteral("abc\0def");
QTest::newRow( "3" ) << QByteArray::fromRawData("abcd", 3) << QString("abc");
QTest::newRow( "4" ) << QByteArray("\xc3\xa9") << QString("\xc3\xa9");
@@ -848,12 +1168,6 @@ void tst_QString::constructorQByteArray()
QCOMPARE( strBA, expected );
// test operator= too
- if (src.constData()[src.length()] == '\0') {
- str1.clear();
- str1 = src.constData();
- QCOMPARE( str1, expected );
- }
-
strBA.clear();
strBA = src;
QCOMPARE( strBA, expected );
@@ -2066,7 +2380,46 @@ void tst_QString::simplified()
QCOMPARE(qMove(full).simplified(), simple);
}
-void tst_QString::insert()
+void tst_QString::insert_data(bool emptyIsNoop)
+{
+ QTest::addColumn<QString>("s");
+ QTest::addColumn<CharStarContainer>("arg");
+ QTest::addColumn<int>("a1");
+ QTest::addColumn<QString>("expected");
+
+ const CharStarContainer nullC;
+ const CharStarContainer emptyC("");
+ const CharStarContainer aC("a");
+ const CharStarContainer bC("b");
+ //const CharStarContainer abC("ab");
+ const CharStarContainer baC("ba");
+
+ const QString null;
+ const QString empty("");
+ const QString a("a");
+ const QString b("b");
+ const QString ab("ab");
+ const QString ba("ba");
+
+ QTest::newRow("null.insert(0, null)") << null << nullC << 0 << null;
+ QTest::newRow("null.insert(0, empty)") << null << emptyC << 0 << (emptyIsNoop ? null : empty);
+ QTest::newRow("null.insert(0, a)") << null << aC << 0 << a;
+ QTest::newRow("empty.insert(0, null)") << empty << nullC << 0 << empty;
+ QTest::newRow("empty.insert(0, empty)") << empty << emptyC << 0 << empty;
+ QTest::newRow("empty.insert(0, a)") << empty << aC << 0 << a;
+ QTest::newRow("a.insert(0, null)") << a << nullC << 0 << a;
+ QTest::newRow("a.insert(0, empty)") << a << emptyC << 0 << a;
+ QTest::newRow("a.insert(0, b)") << a << bC << 0 << ba;
+ QTest::newRow("a.insert(0, ba)") << a << baC << 0 << (ba + a);
+ QTest::newRow("a.insert(1, null)") << a << nullC << 1 << a;
+ QTest::newRow("a.insert(1, empty)") << a << emptyC << 1 << a;
+ QTest::newRow("a.insert(1, b)") << a << bC << 1 << ab;
+ QTest::newRow("a.insert(1, ba)") << a << baC << 1 << (a + ba);
+ QTest::newRow("ba.insert(1, a)") << ba << aC << 1 << (ba + a);
+ QTest::newRow("ba.insert(2, b)") << ba << bC << 2 << (ba + b);
+}
+
+void tst_QString::insert_special_cases()
{
QString a;
@@ -2097,14 +2450,37 @@ void tst_QString::insert()
QCOMPARE(a.insert(0, QLatin1String("a")), QString("aMontreal"));
}
-void tst_QString::append()
+void tst_QString::append_data(bool emptyIsNoop)
{
- {
- QString a;
- a = "<>ABCABCABCABC";
- QCOMPARE(a.append(">"),QString("<>ABCABCABCABC>"));
- }
+ QTest::addColumn<QString>("s");
+ QTest::addColumn<CharStarContainer>("arg");
+ QTest::addColumn<QString>("expected");
+
+ const CharStarContainer nullC;
+ const CharStarContainer emptyC("");
+ const CharStarContainer aC("a");
+ const CharStarContainer bC("b");
+ //const CharStarContainer abC("ab");
+ const QString null;
+ const QString empty("");
+ const QString a("a");
+ //const QString b("b");
+ const QString ab("ab");
+
+ QTest::newRow("null + null") << null << nullC << null;
+ QTest::newRow("null + empty") << null << emptyC << (emptyIsNoop ? null : empty);
+ QTest::newRow("null + a") << null << aC << a;
+ QTest::newRow("empty + null") << empty << nullC << empty;
+ QTest::newRow("empty + empty") << empty << emptyC << empty;
+ QTest::newRow("empty + a") << empty << aC << a;
+ QTest::newRow("a + null") << a << nullC << a;
+ QTest::newRow("a + empty") << a << emptyC << a;
+ QTest::newRow("a + b") << a << bC << ab;
+}
+
+void tst_QString::append_special_cases()
+{
{
QString a;
static const QChar unicode[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!' };
@@ -2124,7 +2500,7 @@ void tst_QString::append()
}
}
-void tst_QString::append_bytearray_data()
+void tst_QString::append_bytearray_special_cases_data()
{
QTest::addColumn<QString>("str" );
QTest::addColumn<QByteArray>("ba" );
@@ -2158,7 +2534,7 @@ void tst_QString::append_bytearray_data()
QTest::newRow( "nonAsciiByteArray2") << QString() << QByteArray("\xc3\xa9") << QString::fromUtf8("\xc3\xa9");
}
-void tst_QString::append_bytearray()
+void tst_QString::append_bytearray_special_cases()
{
{
QFETCH( QString, str );
@@ -2176,22 +2552,19 @@ void tst_QString::append_bytearray()
QTEST( str, "res" );
}
+}
- QFETCH( QByteArray, ba );
- if (ba.constData()[ba.length()] == '\0') {
- QFETCH( QString, str );
-
- str.append(ba.constData());
- QTEST( str, "res" );
- }
+void tst_QString::operator_pluseq_data(bool emptyIsNoop)
+{
+ append_data(emptyIsNoop);
}
-void tst_QString::operator_pluseq_bytearray_data()
+void tst_QString::operator_pluseq_bytearray_special_cases_data()
{
- append_bytearray_data();
+ append_bytearray_special_cases_data();
}
-void tst_QString::operator_pluseq_bytearray()
+void tst_QString::operator_pluseq_bytearray_special_cases()
{
{
QFETCH( QString, str );
@@ -2209,14 +2582,6 @@ void tst_QString::operator_pluseq_bytearray()
QTEST( str, "res" );
}
-
- QFETCH( QByteArray, ba );
- if (ba.constData()[ba.length()] == '\0') {
- QFETCH( QString, str );
-
- str += ba.constData();
- QTEST( str, "res" );
- }
}
void tst_QString::operator_eqeq_bytearray_data()
@@ -2231,11 +2596,6 @@ void tst_QString::operator_eqeq_bytearray()
QVERIFY(expected == src);
QVERIFY(!(expected != src));
-
- if (src.constData()[src.length()] == '\0') {
- QVERIFY(expected == src.constData());
- QVERIFY(!(expected != src.constData()));
- }
}
void tst_QString::swap()
@@ -2248,14 +2608,37 @@ void tst_QString::swap()
QCOMPARE(s2,QLatin1String("s1"));
}
-void tst_QString::prepend()
+void tst_QString::prepend_data(bool emptyIsNoop)
{
- QString a;
- a = "<>ABCABCABCABC>";
- QCOMPARE(a.prepend("-"),(QString)"-<>ABCABCABCABC>");
+ QTest::addColumn<QString>("s");
+ QTest::addColumn<CharStarContainer>("arg");
+ QTest::addColumn<QString>("expected");
+
+ const CharStarContainer nullC;
+ const CharStarContainer emptyC("");
+ const CharStarContainer aC("a");
+ const CharStarContainer bC("b");
+ const CharStarContainer baC("ba");
+
+ const QString null;
+ const QString empty("");
+ const QString a("a");
+ //const QString b("b");
+ const QString ba("ba");
+
+ QTest::newRow("null.prepend(null)") << null << nullC << null;
+ QTest::newRow("null.prepend(empty)") << null << emptyC << (emptyIsNoop ? null : empty);
+ QTest::newRow("null.prepend(a)") << null << aC << a;
+ QTest::newRow("empty.prepend(null)") << empty << nullC << empty;
+ QTest::newRow("empty.prepend(empty)") << empty << emptyC << empty;
+ QTest::newRow("empty.prepend(a)") << empty << aC << a;
+ QTest::newRow("a.prepend(null)") << a << nullC << a;
+ QTest::newRow("a.prepend(empty)") << a << emptyC << a;
+ QTest::newRow("a.prepend(b)") << a << bC << ba;
+ QTest::newRow("a.prepend(ba)") << a << baC << (ba + a);
}
-void tst_QString::prepend_bytearray_data()
+void tst_QString::prepend_bytearray_special_cases_data()
{
QTest::addColumn<QString>("str" );
QTest::addColumn<QByteArray>("ba" );
@@ -2270,7 +2653,7 @@ void tst_QString::prepend_bytearray_data()
// byte array with only a 0
ba.resize( 1 );
ba[0] = 0;
- QTest::newRow( "emptyString" ) << QString("foobar ") << ba << QString("foobar ");
+ QTest::newRow( "emptyString" ) << QString("foobar ") << ba << QStringLiteral("\0foobar ");
// empty byte array
ba.resize( 0 );
@@ -2281,7 +2664,7 @@ void tst_QString::prepend_bytearray_data()
QTest::newRow( "nonAsciiByteArray2") << QString() << QByteArray("\xc3\xa9") << QString::fromUtf8("\xc3\xa9");
}
-void tst_QString::prepend_bytearray()
+void tst_QString::prepend_bytearray_special_cases()
{
{
QFETCH( QString, str );
@@ -2300,14 +2683,6 @@ void tst_QString::prepend_bytearray()
QTEST( str, "res" );
}
-
- QFETCH( QByteArray, ba );
- if (ba.constData()[ba.length()] == '\0') {
- QFETCH( QString, str );
-
- str.prepend(ba.constData());
- QTEST( str, "res" );
- }
}
void tst_QString::replace_uint_uint()
@@ -3697,6 +4072,12 @@ void tst_QString::nullFromUtf8()
a = QString::fromUtf8("");
QVERIFY(!a.isNull());
QVERIFY(a.isEmpty());
+ a = QString::fromUtf8(QByteArray());
+ QVERIFY(a.isNull());
+ QVERIFY(a.isEmpty());
+ a = QString::fromUtf8(QByteArray(""));
+ QVERIFY(!a.isNull());
+ QVERIFY(a.isEmpty());
}
void tst_QString::fromLocal8Bit_data()
@@ -3779,6 +4160,23 @@ void tst_QString::local8Bit()
QCOMPARE(local8Bit.toLocal8Bit(), QByteArray(result));
}
+void tst_QString::nullFromLocal8Bit()
+{
+ QString a;
+ a = QString::fromLocal8Bit(0);
+ QVERIFY(a.isNull());
+ QVERIFY(a.isEmpty());
+ a = QString::fromLocal8Bit("");
+ QVERIFY(!a.isNull());
+ QVERIFY(a.isEmpty());
+ a = QString::fromLocal8Bit(QByteArray());
+ QVERIFY(a.isNull());
+ QVERIFY(a.isEmpty());
+ a = QString::fromLocal8Bit(QByteArray(""));
+ QVERIFY(!a.isNull());
+ QVERIFY(a.isEmpty());
+}
+
void tst_QString::stringRef_local8Bit_data()
{
local8Bit_data();
@@ -3945,6 +4343,12 @@ void tst_QString::fromLatin1()
a = QString::fromLatin1( "" );
QVERIFY( !a.isNull() );
QVERIFY( a.isEmpty() );
+ a = QString::fromLatin1(QByteArray());
+ QVERIFY(a.isNull());
+ QVERIFY(a.isEmpty());
+ a = QString::fromLatin1(QByteArray(""));
+ QVERIFY(!a.isNull());
+ QVERIFY(a.isEmpty());
a = QString::fromLatin1(0, 0);
QVERIFY(a.isNull());
@@ -4996,6 +5400,20 @@ void tst_QString::localeAwareCompare()
}
#endif //!defined(Q_OS_WIN) || defined(Q_OS_WIN_AND_WINCE)
+void tst_QString::reverseIterators()
+{
+ QString s = "1234";
+ QString sr = s;
+ std::reverse(sr.begin(), sr.end());
+ const QString &csr = sr;
+ QVERIFY(std::equal(s.begin(), s.end(), sr.rbegin()));
+ QVERIFY(std::equal(s.begin(), s.end(), sr.crbegin()));
+ QVERIFY(std::equal(s.begin(), s.end(), csr.rbegin()));
+ QVERIFY(std::equal(sr.rbegin(), sr.rend(), s.begin()));
+ QVERIFY(std::equal(sr.crbegin(), sr.crend(), s.begin()));
+ QVERIFY(std::equal(csr.rbegin(), csr.rend(), s.begin()));
+}
+
void tst_QString::split_data()
{
QTest::addColumn<QString>("str");
diff --git a/tests/auto/corelib/tools/qstring/tst_qstring_mac.mm b/tests/auto/corelib/tools/qstring/tst_qstring_mac.mm
index f4b748e62a..550f835bea 100644
--- a/tests/auto/corelib/tools/qstring/tst_qstring_mac.mm
+++ b/tests/auto/corelib/tools/qstring/tst_qstring_mac.mm
@@ -55,23 +55,19 @@ void tst_QString_macTypes()
}
// QString <-> NSString
{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QString qtString("test string");
const NSString *nsString = qtString.toNSString();
QCOMPARE(QString::fromNSString(nsString), qtString);
-
- [pool release];
}
{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ QMacAutoReleasePool pool;
QString qtString("test string");
const NSString *nsString = qtString.toNSString();
QString qtStringCopy(qtString);
qtString = qtString.toUpper(); // modify
QCOMPARE(QString::fromNSString(nsString), qtStringCopy);
-
- [pool release];
}
}
diff --git a/tests/auto/corelib/tools/qstringref/tst_qstringref.cpp b/tests/auto/corelib/tools/qstringref/tst_qstringref.cpp
index 7fc855a359..82d103c460 100644
--- a/tests/auto/corelib/tools/qstringref/tst_qstringref.cpp
+++ b/tests/auto/corelib/tools/qstringref/tst_qstringref.cpp
@@ -82,6 +82,7 @@ private slots:
void integer_conversion_data();
void integer_conversion();
void trimmed();
+ void truncate();
void left();
void right();
void mid();
@@ -1839,6 +1840,30 @@ void tst_QStringRef::trimmed()
QCOMPARE(b.trimmed().compare(QStringLiteral("a")), 0);
}
+void tst_QStringRef::truncate()
+{
+ const QString str = "OriginalString~";
+ const QStringRef cref = str.midRef(0);
+ {
+ QStringRef ref = cref;
+ ref.truncate(1000);
+ QCOMPARE(ref, cref);
+ for (int i = str.size(); i >= 0; --i) {
+ ref.truncate(i);
+ QCOMPARE(ref.size(), i);
+ QCOMPARE(ref, cref.left(i));
+ }
+ QVERIFY(ref.isEmpty());
+ }
+
+ {
+ QStringRef ref = cref;
+ QVERIFY(!ref.isEmpty());
+ ref.truncate(-1);
+ QVERIFY(ref.isEmpty());
+ }
+}
+
void tst_QStringRef::left()
{
QString originalString = "OrginalString~";
diff --git a/tests/auto/corelib/tools/qtimeline/BLACKLIST b/tests/auto/corelib/tools/qtimeline/BLACKLIST
new file mode 100644
index 0000000000..b5861756d8
--- /dev/null
+++ b/tests/auto/corelib/tools/qtimeline/BLACKLIST
@@ -0,0 +1,4 @@
+[interpolation]
+windows
+[duration]
+windows
diff --git a/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp b/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
index 975ed129fc..507f7e3992 100644
--- a/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
+++ b/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
@@ -208,7 +208,7 @@ void tst_QTimeLine::frameRate()
timeLine.start();
QTest::qWait(timeLine.duration()*2);
QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
- QVERIFY(slowCount < spy.count());
+ QVERIFY2(slowCount < spy.count(), QByteArray::number(spy.count()));
}
void tst_QTimeLine::value()
diff --git a/tests/auto/corelib/tools/qtimezone/BLACKLIST b/tests/auto/corelib/tools/qtimezone/BLACKLIST
new file mode 100644
index 0000000000..665e78bc08
--- /dev/null
+++ b/tests/auto/corelib/tools/qtimezone/BLACKLIST
@@ -0,0 +1,2 @@
+[tzTest]
+opensuse-13.1
diff --git a/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp b/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
index 94d81e0a5a..82f78b2b0b 100644
--- a/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
+++ b/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
@@ -47,10 +47,12 @@ private slots:
void appendCausingRealloc();
void resize();
void realloc();
+ void reverseIterators();
void count();
void first();
void last();
void squeeze();
+ void operators();
void indexOf();
void lastIndexOf();
void contains();
@@ -563,6 +565,21 @@ void tst_QVarLengthArray::realloc()
QVERIFY(reallocTestProceed);
}
+void tst_QVarLengthArray::reverseIterators()
+{
+ QVarLengthArray<int> v;
+ v << 1 << 2 << 3 << 4;
+ QVarLengthArray<int> vr = v;
+ std::reverse(vr.begin(), vr.end());
+ const QVarLengthArray<int> &cvr = vr;
+ QVERIFY(std::equal(v.begin(), v.end(), vr.rbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), vr.crbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), cvr.rbegin()));
+ QVERIFY(std::equal(vr.rbegin(), vr.rend(), v.begin()));
+ QVERIFY(std::equal(vr.crbegin(), vr.crend(), v.begin()));
+ QVERIFY(std::equal(cvr.rbegin(), cvr.rend(), v.begin()));
+}
+
void tst_QVarLengthArray::count()
{
// tests size(), count() and length(), since they're the same thing
@@ -691,6 +708,49 @@ void tst_QVarLengthArray::squeeze()
QCOMPARE(list.capacity(), sizeOnHeap);
}
+void tst_QVarLengthArray::operators()
+{
+ QVarLengthArray<QString> myvla;
+ myvla << "A" << "B" << "C";
+ QVarLengthArray<QString> myvlatwo;
+ myvlatwo << "D" << "E" << "F";
+ QVarLengthArray<QString> combined;
+ combined << "A" << "B" << "C" << "D" << "E" << "F";
+
+ // !=
+ QVERIFY(myvla != myvlatwo);
+
+ // +=: not provided, emulate
+ //myvla += myvlatwo;
+ Q_FOREACH (const QString &s, myvlatwo)
+ myvla.push_back(s);
+ QCOMPARE(myvla, combined);
+
+ // ==
+ QVERIFY(myvla == combined);
+
+ // <, >, <=, >=
+ QVERIFY(!(myvla < combined));
+ QVERIFY(!(myvla > combined));
+ QVERIFY( myvla <= combined);
+ QVERIFY( myvla >= combined);
+ combined.push_back("G");
+ QVERIFY( myvla < combined);
+ QVERIFY(!(myvla > combined));
+ QVERIFY( myvla <= combined);
+ QVERIFY(!(myvla >= combined));
+ QVERIFY(combined > myvla);
+ QVERIFY(combined >= myvla);
+
+ // []
+ QCOMPARE(myvla[0], QLatin1String("A"));
+ QCOMPARE(myvla[1], QLatin1String("B"));
+ QCOMPARE(myvla[2], QLatin1String("C"));
+ QCOMPARE(myvla[3], QLatin1String("D"));
+ QCOMPARE(myvla[4], QLatin1String("E"));
+ QCOMPARE(myvla[5], QLatin1String("F"));
+}
+
void tst_QVarLengthArray::indexOf()
{
QVarLengthArray<QString> myvec;
diff --git a/tests/auto/corelib/tools/qvector/qvector.pro b/tests/auto/corelib/tools/qvector/qvector.pro
index 22edde3412..c1e0564915 100644
--- a/tests/auto/corelib/tools/qvector/qvector.pro
+++ b/tests/auto/corelib/tools/qvector/qvector.pro
@@ -1,4 +1,5 @@
CONFIG += testcase parallel_test
+contains(QT_CONFIG, c++11):CONFIG += c++11
TARGET = tst_qvector
QT = core testlib
SOURCES = $$PWD/tst_qvector.cpp
diff --git a/tests/auto/corelib/tools/qvector/tst_qvector.cpp b/tests/auto/corelib/tools/qvector/tst_qvector.cpp
index 69da6e450e..87822bca6f 100644
--- a/tests/auto/corelib/tools/qvector/tst_qvector.cpp
+++ b/tests/auto/corelib/tools/qvector/tst_qvector.cpp
@@ -86,6 +86,8 @@ private:
}
};
+inline uint qHash(const Movable &key, uint seed = 0) { return qHash(key.i, seed); }
+
QAtomicInt Movable::counter = 0;
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(Movable, Q_MOVABLE_TYPE);
@@ -123,6 +125,13 @@ struct Custom {
return i == other.i;
}
+ bool operator<(const Custom &other) const
+ {
+ check(&other);
+ check(this);
+ return i < other.i;
+ }
+
Custom &operator=(const Custom &other)
{
check(&other);
@@ -148,6 +157,8 @@ private:
};
QAtomicInt Custom::counter = 0;
+inline uint qHash(const Custom &key, uint seed = 0) { return qHash(key.i, seed); }
+
Q_DECLARE_METATYPE(Custom);
// tests depends on the fact that:
@@ -179,6 +190,7 @@ private slots:
void appendInt() const;
void appendMovable() const;
void appendCustom() const;
+ void appendRvalue() const;
void at() const;
void capacityInt() const;
void capacityMovable() const;
@@ -187,6 +199,8 @@ private slots:
void clearMovable() const;
void clearCustom() const;
void constData() const;
+ void constFirst() const;
+ void constLast() const;
void contains() const;
void countInt() const;
void countMovable() const;
@@ -227,9 +241,15 @@ private slots:
void last() const;
void lastIndexOf() const;
void mid() const;
+ void moveInt() const;
+ void moveMovable() const;
+ void moveCustom() const;
void prependInt() const;
void prependMovable() const;
void prependCustom() const;
+ void qhashInt() const { qhash<int>(); }
+ void qhashMovable() const { qhash<Movable>(); }
+ void qhashCustom() const { qhash<Custom>(); }
void removeInt() const;
void removeMovable() const;
void removeCustom() const;
@@ -241,6 +261,7 @@ private slots:
void resizeComplex_data() const;
void resizeComplex() const;
void resizeCtorAndDtor() const;
+ void reverseIterators() const;
void sizeInt() const;
void sizeMovable() const;
void sizeCustom() const;
@@ -294,6 +315,8 @@ private:
template<typename T> void fill() const;
template<typename T> void fromList() const;
template<typename T> void insert() const;
+ template<typename T> void qhash() const;
+ template<typename T> void move() const;
template<typename T> void prepend() const;
template<typename T> void remove() const;
template<typename T> void size() const;
@@ -332,6 +355,14 @@ const Movable SimpleValue<Movable>::Values[] = { 110, 105, 101, 114, 111, 98 };
template<>
const Custom SimpleValue<Custom>::Values[] = { 110, 105, 101, 114, 111, 98 };
+// Make some macros for the tests to use in order to be slightly more readable...
+#define T_FOO SimpleValue<T>::at(0)
+#define T_BAR SimpleValue<T>::at(1)
+#define T_BAZ SimpleValue<T>::at(2)
+#define T_CAT SimpleValue<T>::at(3)
+#define T_DOG SimpleValue<T>::at(4)
+#define T_BLAH SimpleValue<T>::at(5)
+
void tst_QVector::constructors_empty() const
{
QVector<int> emptyInt;
@@ -608,6 +639,21 @@ void tst_QVector::appendCustom() const
QCOMPARE(instancesCount, Custom::counter.loadAcquire());
}
+void tst_QVector::appendRvalue() const
+{
+#ifdef Q_COMPILER_RVALUE_REFS
+ QVector<QString> v;
+ v.append("hello");
+ QString world = "world";
+ v.append(std::move(world));
+ QVERIFY(world.isEmpty());
+ QCOMPARE(v.front(), QString("hello"));
+ QCOMPARE(v.back(), QString("world"));
+#else
+ QSKIP("This test requires that C++11 move semantics support is enabled in the compiler");
+#endif
+}
+
void tst_QVector::at() const
{
QVector<QString> myvec;
@@ -1206,16 +1252,86 @@ void tst_QVector::first() const
// test it starts ok
QCOMPARE(myvec.first(), 69);
+ QCOMPARE(myvec.constFirst(), 69);
// test removal changes
myvec.remove(0);
QCOMPARE(myvec.first(), 42);
+ QCOMPARE(myvec.constFirst(), 42);
// test prepend changes
myvec.prepend(23);
QCOMPARE(myvec.first(), 23);
+ QCOMPARE(myvec.constFirst(), 23);
+}
+
+void tst_QVector::constFirst() const
+{
+ QVector<int> myvec;
+ myvec << 69 << 42 << 3;
+
+ // test it starts ok
+ QCOMPARE(myvec.constFirst(), 69);
+ QVERIFY(myvec.isDetached());
+
+ QVector<int> myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constFirst(), 69);
+ QCOMPARE(myvecCopy.constFirst(), 69);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ // test removal changes
+ myvec.remove(0);
+ QVERIFY(myvec.isDetached());
+ QVERIFY(!myvec.isSharedWith(myvecCopy));
+ QCOMPARE(myvec.constFirst(), 42);
+ QCOMPARE(myvecCopy.constFirst(), 69);
+
+ myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constFirst(), 42);
+ QCOMPARE(myvecCopy.constFirst(), 42);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ // test prepend changes
+ myvec.prepend(23);
+ QVERIFY(myvec.isDetached());
+ QVERIFY(!myvec.isSharedWith(myvecCopy));
+ QCOMPARE(myvec.constFirst(), 23);
+ QCOMPARE(myvecCopy.constFirst(), 42);
+
+ myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constFirst(), 23);
+ QCOMPARE(myvecCopy.constFirst(), 23);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
}
+
template<typename T>
void tst_QVector::fromList() const
{
@@ -1393,14 +1509,83 @@ void tst_QVector::last() const
// test starts ok
QCOMPARE(myvec.last(), QLatin1String("C"));
+ QCOMPARE(myvec.constLast(), QLatin1String("C"));
// test it changes ok
myvec.append(QLatin1String("X"));
QCOMPARE(myvec.last(), QLatin1String("X"));
+ QCOMPARE(myvec.constLast(), QLatin1String("X"));
// and remove again
myvec.remove(3);
QCOMPARE(myvec.last(), QLatin1String("C"));
+ QCOMPARE(myvec.constLast(), QLatin1String("C"));
+}
+
+void tst_QVector::constLast() const
+{
+ QVector<int> myvec;
+ myvec << 69 << 42 << 3;
+
+ // test it starts ok
+ QCOMPARE(myvec.constLast(), 3);
+ QVERIFY(myvec.isDetached());
+
+ QVector<int> myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constLast(), 3);
+ QCOMPARE(myvecCopy.constLast(), 3);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ // test removal changes
+ myvec.removeLast();
+ QVERIFY(myvec.isDetached());
+ QVERIFY(!myvec.isSharedWith(myvecCopy));
+ QCOMPARE(myvec.constLast(), 42);
+ QCOMPARE(myvecCopy.constLast(), 3);
+
+ myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constLast(), 42);
+ QCOMPARE(myvecCopy.constLast(), 42);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ // test prepend changes
+ myvec.append(23);
+ QVERIFY(myvec.isDetached());
+ QVERIFY(!myvec.isSharedWith(myvecCopy));
+ QCOMPARE(myvec.constLast(), 23);
+ QCOMPARE(myvecCopy.constLast(), 42);
+
+ myvecCopy = myvec;
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
+
+ QCOMPARE(myvec.constLast(), 23);
+ QCOMPARE(myvecCopy.constLast(), 23);
+
+ QVERIFY(!myvec.isDetached());
+ QVERIFY(!myvecCopy.isDetached());
+ QVERIFY(myvec.isSharedWith(myvecCopy));
+ QVERIFY(myvecCopy.isSharedWith(myvec));
}
void tst_QVector::lastIndexOf() const
@@ -1437,6 +1622,54 @@ void tst_QVector::mid() const
QCOMPARE(list.mid(4), QVector<QString>() << "buck" << "hello" << "kitty");
}
+template <typename T>
+void tst_QVector::qhash() const
+{
+ QVector<T> l1, l2;
+ QCOMPARE(qHash(l1), qHash(l2));
+ l1 << SimpleValue<T>::at(0);
+ l2 << SimpleValue<T>::at(0);
+ QCOMPARE(qHash(l1), qHash(l2));
+}
+
+template <typename T>
+void tst_QVector::move() const
+{
+ QVector<T> list;
+ list << T_FOO << T_BAR << T_BAZ;
+
+ // move an item
+ list.move(0, list.count() - 1);
+ QCOMPARE(list, QVector<T>() << T_BAR << T_BAZ << T_FOO);
+
+ // move it back
+ list.move(list.count() - 1, 0);
+ QCOMPARE(list, QVector<T>() << T_FOO << T_BAR << T_BAZ);
+
+ // move an item in the middle
+ list.move(1, 0);
+ QCOMPARE(list, QVector<T>() << T_BAR << T_FOO << T_BAZ);
+}
+
+void tst_QVector::moveInt() const
+{
+ move<int>();
+}
+
+void tst_QVector::moveMovable() const
+{
+ const int instancesCount = Movable::counter.loadAcquire();
+ move<Movable>();
+ QCOMPARE(instancesCount, Movable::counter.loadAcquire());
+}
+
+void tst_QVector::moveCustom() const
+{
+ const int instancesCount = Custom::counter.loadAcquire();
+ move<Custom>();
+ QCOMPARE(instancesCount, Custom::counter.loadAcquire());
+}
+
template<typename T>
void tst_QVector::prepend() const
{
@@ -1907,6 +2140,21 @@ void tst_QVector::resizeCtorAndDtor() const
QCOMPARE(Custom::counter.loadAcquire(), items);
}
+void tst_QVector::reverseIterators() const
+{
+ QVector<int> v;
+ v << 1 << 2 << 3 << 4;
+ QVector<int> vr = v;
+ std::reverse(vr.begin(), vr.end());
+ const QVector<int> &cvr = vr;
+ QVERIFY(std::equal(v.begin(), v.end(), vr.rbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), vr.crbegin()));
+ QVERIFY(std::equal(v.begin(), v.end(), cvr.rbegin()));
+ QVERIFY(std::equal(vr.rbegin(), vr.rend(), v.begin()));
+ QVERIFY(std::equal(vr.crbegin(), vr.crend(), v.begin()));
+ QVERIFY(std::equal(cvr.rbegin(), cvr.rend(), v.begin()));
+}
+
template<typename T>
void tst_QVector::size() const
{
@@ -2076,6 +2324,19 @@ void tst_QVector::testOperators() const
// ==
QVERIFY(myvec == combined);
+ // <, >, <=, >=
+ QVERIFY(!(myvec < combined));
+ QVERIFY(!(myvec > combined));
+ QVERIFY( myvec <= combined);
+ QVERIFY( myvec >= combined);
+ combined.push_back("G");
+ QVERIFY( myvec < combined);
+ QVERIFY(!(myvec > combined));
+ QVERIFY( myvec <= combined);
+ QVERIFY(!(myvec >= combined));
+ QVERIFY(combined > myvec);
+ QVERIFY(combined >= myvec);
+
// []
QCOMPARE(myvec[0], QLatin1String("A"));
QCOMPARE(myvec[1], QLatin1String("B"));
diff --git a/tests/auto/corelib/tools/qversionnumber/tst_qversionnumber.cpp b/tests/auto/corelib/tools/qversionnumber/tst_qversionnumber.cpp
index 4202b87b2d..0b8b63a1e8 100644
--- a/tests/auto/corelib/tools/qversionnumber/tst_qversionnumber.cpp
+++ b/tests/auto/corelib/tools/qversionnumber/tst_qversionnumber.cpp
@@ -33,7 +33,7 @@
****************************************************************************/
#include <QtTest/QtTest>
-#include <private/qversionnumber_p.h>
+#include <QtCore/qversionnumber.h>
class tst_QVersionNumber : public QObject
{
diff --git a/tests/auto/dbus/qdbusabstractadaptor/BLACKLIST b/tests/auto/dbus/qdbusabstractadaptor/BLACKLIST
new file mode 100644
index 0000000000..d3d970f4f4
--- /dev/null
+++ b/tests/auto/dbus/qdbusabstractadaptor/BLACKLIST
@@ -0,0 +1,2 @@
+[overloadedSignalEmission]
+linux
diff --git a/tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp b/tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp
index 32c228c186..d85e842a23 100644
--- a/tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp
+++ b/tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp
@@ -105,6 +105,8 @@ private slots:
void sendWithGui();
void sendAsync();
void sendSignal();
+ void sendSignalToName();
+ void sendSignalToOtherName();
void registerObject_data();
void registerObject();
@@ -189,6 +191,49 @@ void tst_QDBusConnection::sendSignal()
QTest::qWait(1000);
}
+void tst_QDBusConnection::sendSignalToName()
+{
+ QDBusSpy spy;
+
+ QDBusConnection con = QDBusConnection::sessionBus();
+
+ con.connect(con.baseService(), "/org/kde/selftest", "org.kde.selftest", "ping", &spy,
+ SLOT(handlePing(QString)));
+
+ QDBusMessage msg =
+ QDBusMessage::createTargetedSignal(con.baseService(), "/org/kde/selftest",
+ "org.kde.selftest", "ping");
+ msg << QLatin1String("ping");
+
+ QVERIFY(con.send(msg));
+
+ QTest::qWait(1000);
+
+ QCOMPARE(spy.args.count(), 1);
+ QCOMPARE(spy.args.at(0).toString(), QString("ping"));
+}
+
+void tst_QDBusConnection::sendSignalToOtherName()
+{
+ QDBusSpy spy;
+
+ QDBusConnection con = QDBusConnection::sessionBus();
+
+ con.connect(con.baseService(), "/org/kde/selftest", "org.kde.selftest", "ping", &spy,
+ SLOT(handlePing(QString)));
+
+ QDBusMessage msg =
+ QDBusMessage::createTargetedSignal("some.other.service", "/org/kde/selftest",
+ "org.kde.selftest", "ping");
+ msg << QLatin1String("ping");
+
+ QVERIFY(con.send(msg));
+
+ QTest::qWait(1000);
+
+ QCOMPARE(spy.args.count(), 0);
+}
+
void tst_QDBusConnection::send()
{
QDBusConnection con = QDBusConnection::sessionBus();
diff --git a/tests/auto/dbus/qdbusmarshall/BLACKLIST b/tests/auto/dbus/qdbusmarshall/BLACKLIST
new file mode 100644
index 0000000000..036378d204
--- /dev/null
+++ b/tests/auto/dbus/qdbusmarshall/BLACKLIST
@@ -0,0 +1,3 @@
+[receiveUnknownType]
+ubuntu-14.04
+opensuse-13.1
diff --git a/tests/auto/dbus/qdbusmarshall/tst_qdbusmarshall.cpp b/tests/auto/dbus/qdbusmarshall/tst_qdbusmarshall.cpp
index 16314a5dc5..b681f9829a 100644
--- a/tests/auto/dbus/qdbusmarshall/tst_qdbusmarshall.cpp
+++ b/tests/auto/dbus/qdbusmarshall/tst_qdbusmarshall.cpp
@@ -869,7 +869,7 @@ void tst_QDBusMarshall::sendSignalErrors()
"signalName");
msg << QVariant::fromValue(QDBusObjectPath());
- QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid object path passed in arguments");
+ QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal to service \"\" path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid object path passed in arguments");
QVERIFY(!con.send(msg));
msg.setArguments(QVariantList());
@@ -879,19 +879,19 @@ void tst_QDBusMarshall::sendSignalErrors()
path.setPath("abc");
msg << QVariant::fromValue(path);
- QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid object path passed in arguments");
+ QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal to service \"\" path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid object path passed in arguments");
QVERIFY(!con.send(msg));
QDBusSignature sig;
msg.setArguments(QVariantList() << QVariant::fromValue(sig));
- QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid signature passed in arguments");
+ QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal to service \"\" path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid signature passed in arguments");
QVERIFY(!con.send(msg));
QTest::ignoreMessage(QtWarningMsg, "QDBusSignature: invalid signature \"a\"");
sig.setSignature("a");
msg.setArguments(QVariantList());
msg << QVariant::fromValue(sig);
- QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid signature passed in arguments");
+ QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal to service \"\" path \"/foo\" interface \"local.interfaceName\" member \"signalName\": Marshalling failed: Invalid signature passed in arguments");
QVERIFY(!con.send(msg));
}
@@ -1079,7 +1079,7 @@ static bool canSendUnixFd(DBusConnection *connection)
# if DBUS_VERSION-0 >= 0x010400
can_send_type = dbus_connection_can_send_type;
# endif
-#else
+#elif !defined(QT_NO_LIBRARY)
// run-time check if the next functions are available
can_send_type = (can_send_type_t)qdbus_resolve_conditionally("dbus_connection_can_send_type");
#endif
diff --git a/tests/auto/dbus/qdbustype/tst_qdbustype.cpp b/tests/auto/dbus/qdbustype/tst_qdbustype.cpp
index 63444b61ad..4408729e7c 100644
--- a/tests/auto/dbus/qdbustype/tst_qdbustype.cpp
+++ b/tests/auto/dbus/qdbustype/tst_qdbustype.cpp
@@ -94,7 +94,11 @@ static void addFixedTypes()
// the library recognizes this as valid type first.
// The following function was added for Unix FD support, so if it is
// present, so is support for Unix FDs.
+# ifndef QT_NO_LIBRARY
bool supportsUnixFds = qdbus_resolve_conditionally("dbus_connection_can_send_type");
+# else
+ bool supportsUnixFds = false;
+# endif
# else
bool supportsUnixFds = true;
# endif
diff --git a/tests/auto/gui/image/qicon/tst_qicon.cpp b/tests/auto/gui/image/qicon/tst_qicon.cpp
index 20a08e10a2..9ed3873682 100644
--- a/tests/auto/gui/image/qicon/tst_qicon.cpp
+++ b/tests/auto/gui/image/qicon/tst_qicon.cpp
@@ -75,14 +75,8 @@ private:
const QString m_pngImageFileName;
const QString m_pngRectFileName;
const QString m_sourceFileName;
-
- const static QIcon staticIcon;
};
-// Creating an icon statically should not cause a crash.
-// But we do not officially support this. See QTBUG-8666
-const QIcon tst_QIcon::staticIcon = QIcon::fromTheme("edit-find");
-
bool tst_QIcon::haveImageFormat(QByteArray const& desiredFormat)
{
return QImageReader::supportedImageFormats().contains(desiredFormat);
@@ -354,10 +348,10 @@ void tst_QIcon::cacheKey()
qint64 icon1_key = icon1.cacheKey();
QIcon icon2 = icon1;
- QVERIFY(icon2.cacheKey() == icon1.cacheKey());
+ QCOMPARE(icon2.cacheKey(), icon1.cacheKey());
icon2.detach();
QVERIFY(icon2.cacheKey() != icon1.cacheKey());
- QVERIFY(icon1.cacheKey() == icon1_key);
+ QCOMPARE(icon1.cacheKey(), icon1_key);
}
void tst_QIcon::detach()
@@ -374,7 +368,7 @@ void tst_QIcon::detach()
img1 = icon1.pixmap(32, 32).toImage();
img2 = icon2.pixmap(32, 32).toImage();
- QVERIFY(img1 == img2);
+ QCOMPARE(img1, img2);
}
void tst_QIcon::addFile()
@@ -562,7 +556,7 @@ void tst_QIcon::fromTheme()
QString firstSearchPath = QLatin1String(":/icons");
QString secondSearchPath = QLatin1String(":/second_icons");
QIcon::setThemeSearchPaths(QStringList() << firstSearchPath << secondSearchPath);
- QVERIFY(QIcon::themeSearchPaths().size() == 2);
+ QCOMPARE(QIcon::themeSearchPaths().size(), 2);
QCOMPARE(firstSearchPath, QIcon::themeSearchPaths()[0]);
QCOMPARE(secondSearchPath, QIcon::themeSearchPaths()[1]);
@@ -599,7 +593,7 @@ void tst_QIcon::fromTheme()
// Test non existing icon with fallback
noIcon = QIcon::fromTheme("broken-icon", abIcon);
- QVERIFY(noIcon.cacheKey() == abIcon.cacheKey());
+ QCOMPARE(noIcon.cacheKey(), abIcon.cacheKey());
// Test svg-only icon
noIcon = QIcon::fromTheme("svg-icon", abIcon);
diff --git a/tests/auto/gui/image/qimage/tst_qimage.cpp b/tests/auto/gui/image/qimage/tst_qimage.cpp
index 8286c800c2..08f48abd20 100644
--- a/tests/auto/gui/image/qimage/tst_qimage.cpp
+++ b/tests/auto/gui/image/qimage/tst_qimage.cpp
@@ -478,7 +478,7 @@ void tst_QImage::setAlphaChannel()
image.setAlphaChannel(alphaChannel);
image = image.convertToFormat(QImage::Format_ARGB32);
- QVERIFY(image.format() == QImage::Format_ARGB32);
+ QCOMPARE(image.format(), QImage::Format_ARGB32);
// alpha of 0 becomes black at a=0 due to premultiplication
QRgb pixel = alpha == 0 ? 0 : qRgba(red, green, blue, alpha);
@@ -1565,12 +1565,12 @@ void tst_QImage::createHeuristicMask()
// line 2
QVERIFY(newMask.pixel(0,1) != newMask.pixel(1,1));
- QVERIFY(newMask.pixel(1,1) == newMask.pixel(2,1));
+ QCOMPARE(newMask.pixel(1,1), newMask.pixel(2,1));
QVERIFY(newMask.pixel(2,1) != newMask.pixel(3,1));
// line 3
QVERIFY(newMask.pixel(0,2) != newMask.pixel(1,2));
- QVERIFY(newMask.pixel(1,2) == newMask.pixel(2,2));
+ QCOMPARE(newMask.pixel(1,2), newMask.pixel(2,2));
QVERIFY(newMask.pixel(2,2) != newMask.pixel(3,2));
}
#endif
@@ -1581,10 +1581,10 @@ void tst_QImage::cacheKey()
qint64 image1_key = image1.cacheKey();
QImage image2 = image1;
- QVERIFY(image2.cacheKey() == image1.cacheKey());
+ QCOMPARE(image2.cacheKey(), image1.cacheKey());
image2.detach();
QVERIFY(image2.cacheKey() != image1.cacheKey());
- QVERIFY(image1.cacheKey() == image1_key);
+ QCOMPARE(image1.cacheKey(), image1_key);
}
void tst_QImage::smoothScale()
diff --git a/tests/auto/gui/image/qimagereader/tst_qimagereader.cpp b/tests/auto/gui/image/qimagereader/tst_qimagereader.cpp
index 4b3e2606fd..07b75adae4 100644
--- a/tests/auto/gui/image/qimagereader/tst_qimagereader.cpp
+++ b/tests/auto/gui/image/qimagereader/tst_qimagereader.cpp
@@ -733,7 +733,7 @@ void tst_QImageReader::gifHandlerBugs()
QVERIFY(io.loopCount() != 1);
int count=0;
for (; io.canRead(); io.read(), ++count) ;
- QVERIFY(count == 34);
+ QCOMPARE(count, 34);
}
// Task 95166
@@ -810,7 +810,7 @@ void tst_QImageReader::gifImageCount()
QVERIFY(io.canRead());
QImage greenFrame = io.read();
- QVERIFY(io.imageCount() == 4);
+ QCOMPARE(io.imageCount(), 4);
QVERIFY(io.canRead());
QImage blueFrame = io.read();
@@ -925,8 +925,8 @@ void tst_QImageReader::gifImageCount()
}
{
QImageReader io(":images/trolltech.gif");
- QVERIFY(io.imageCount() == 34);
- QVERIFY(io.size() == QSize(128,64));
+ QCOMPARE(io.imageCount(), 34);
+ QCOMPARE(io.size(), QSize(128,64));
}
}
diff --git a/tests/auto/gui/image/qmovie/tst_qmovie.cpp b/tests/auto/gui/image/qmovie/tst_qmovie.cpp
index c61c88d1a6..b8c99ca324 100644
--- a/tests/auto/gui/image/qmovie/tst_qmovie.cpp
+++ b/tests/auto/gui/image/qmovie/tst_qmovie.cpp
@@ -188,8 +188,8 @@ void tst_QMovie::jumpToFrame()
QMovie movie(QFINDTESTDATA(fileName));
movie.start();
movie.stop();
- QVERIFY(movie.jumpToFrame(-1) == false);
- QVERIFY(movie.currentFrameNumber() == 0);
+ QVERIFY(!movie.jumpToFrame(-1));
+ QCOMPARE(movie.currentFrameNumber(), 0);
}
void tst_QMovie::changeMovieFile()
@@ -198,7 +198,7 @@ void tst_QMovie::changeMovieFile()
movie.start();
movie.stop();
movie.setFileName(QFINDTESTDATA("animations/trolltech.gif"));
- QVERIFY(movie.currentFrameNumber() == -1);
+ QCOMPARE(movie.currentFrameNumber(), -1);
}
#ifndef QT_NO_WIDGETS
diff --git a/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp b/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp
index 58cc5824bd..67d7e57fd4 100644
--- a/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp
+++ b/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp
@@ -447,7 +447,7 @@ void tst_QPixmap::scroll()
QString fileName = QString(":/images/%1.png").arg(QTest::currentDataTag());
QPixmap output(fileName);
- QVERIFY(input.isNull() == output.isNull());
+ QCOMPARE(input.isNull(), output.isNull());
QVERIFY(lenientCompare(pixmap, output));
QCOMPARE(exp, exposed);
}
@@ -713,11 +713,11 @@ void tst_QPixmap::cacheKey()
QVERIFY(pixmap1.cacheKey() != pixmap2.cacheKey());
pixmap2 = pixmap1;
- QVERIFY(pixmap2.cacheKey() == pixmap1.cacheKey());
+ QCOMPARE(pixmap2.cacheKey(), pixmap1.cacheKey());
pixmap2.detach();
QVERIFY(pixmap2.cacheKey() != pixmap1.cacheKey());
- QVERIFY(pixmap1.cacheKey() == pixmap1_key);
+ QCOMPARE(pixmap1.cacheKey(), pixmap1_key);
}
// Test drawing a bitmap on a pixmap.
@@ -743,7 +743,7 @@ void tst_QPixmap::isNull()
{
{
QPixmap pixmap(1,1);
- QVERIFY(pixmap.isNull() == false);
+ QVERIFY(!pixmap.isNull());
}
{
QPixmap pixmap(0,0);
@@ -783,11 +783,11 @@ void tst_QPixmap::convertFromImageNoDetach()
QPixmap pix = QPixmap::fromImage(orig);
QImage copy = pix.toImage();
- QVERIFY(copy.format() == screenFormat);
+ QCOMPARE(copy.format(), screenFormat);
const QImage constOrig = orig;
const QImage constCopy = copy;
- QVERIFY(constOrig.bits() == constCopy.bits());
+ QCOMPARE(constOrig.bits(), constCopy.bits());
}
void tst_QPixmap::convertFromImageDetach()
@@ -821,7 +821,7 @@ void tst_QPixmap::convertFromImageCacheKey()
QPixmap pix = QPixmap::fromImage(orig);
QImage copy = pix.toImage();
- QVERIFY(copy.format() == screenFormat);
+ QCOMPARE(copy.format(), screenFormat);
QCOMPARE(orig.cacheKey(), pix.cacheKey());
QCOMPARE(copy.cacheKey(), pix.cacheKey());
@@ -1135,9 +1135,9 @@ void tst_QPixmap::copy()
void tst_QPixmap::depthOfNullObjects()
{
QBitmap b1;
- QVERIFY(b1.depth() == 0);
+ QCOMPARE(b1.depth(), 0);
QPixmap p4;
- QVERIFY(p4.depth() == 0);
+ QCOMPARE(p4.depth(), 0);
}
void tst_QPixmap::transformed()
@@ -1437,7 +1437,7 @@ void tst_QPixmap::task_246446()
{
QPixmap pm2(pm);
}
- QVERIFY(pm.width() == 10);
+ QCOMPARE(pm.width(), 10);
QVERIFY(pm.mask().isNull());
}
@@ -1490,14 +1490,14 @@ void tst_QPixmap::loadAsBitmapOrPixmap()
// The do the same check for bitmaps..
QBitmap bitmap("temp_image.png");
QVERIFY(!bitmap.isNull());
- QVERIFY(bitmap.depth() == 1);
+ QCOMPARE(bitmap.depth(), 1);
QVERIFY(bitmap.isQBitmap());
bitmap = QBitmap();
ok = bitmap.load("temp_image.png");
QVERIFY(ok);
QVERIFY(!bitmap.isNull());
- QVERIFY(bitmap.depth() == 1);
+ QCOMPARE(bitmap.depth(), 1);
QVERIFY(bitmap.isQBitmap());
}
diff --git a/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp b/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp
index f22aa63112..a3cf66da18 100644
--- a/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp
+++ b/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp
@@ -111,7 +111,7 @@ void tst_QPixmapCache::setCacheLimit()
delete p1;
QPixmapCache::setCacheLimit(0);
- QVERIFY(QPixmapCache::find("P1") == 0);
+ QVERIFY(!QPixmapCache::find("P1"));
p1 = new QPixmap(2, 3);
QPixmapCache::setCacheLimit(1000);
@@ -346,12 +346,12 @@ void tst_QPixmapCache::remove()
QVERIFY(p1.toImage() == p1.toImage()); // sanity check
QPixmapCache::remove("red");
- QVERIFY(QPixmapCache::find("red") == 0);
+ QVERIFY(!QPixmapCache::find("red"));
QPixmapCache::remove("red");
- QVERIFY(QPixmapCache::find("red") == 0);
+ QVERIFY(!QPixmapCache::find("red"));
QPixmapCache::remove("green");
- QVERIFY(QPixmapCache::find("green") == 0);
+ QVERIFY(!QPixmapCache::find("green"));
//The int part of the API
QPixmapCache::clear();
@@ -424,7 +424,7 @@ void tst_QPixmapCache::clear()
QPixmapCache::clear();
for (int k = 0; k < numberOfKeys; ++k)
- QVERIFY(QPixmapCache::find(QString::number(k)) == 0);
+ QVERIFY(!QPixmapCache::find(QString::number(k)));
//The int part of the API
QPixmap p2(10, 10);
diff --git a/tests/auto/gui/itemmodels/qstandarditem/tst_qstandarditem.cpp b/tests/auto/gui/itemmodels/qstandarditem/tst_qstandarditem.cpp
index 2448b89296..ff263c166a 100644
--- a/tests/auto/gui/itemmodels/qstandarditem/tst_qstandarditem.cpp
+++ b/tests/auto/gui/itemmodels/qstandarditem/tst_qstandarditem.cpp
@@ -278,9 +278,12 @@ void tst_QStandardItem::getSetFlags()
QVERIFY(item.isCheckable());
QCOMPARE(item.checkState(), Qt::Unchecked);
QVERIFY(item.flags() & Qt::ItemIsUserCheckable);
- item.setTristate(true);
- QVERIFY(item.isTristate());
- QVERIFY(item.flags() & Qt::ItemIsTristate);
+ item.setUserTristate(true);
+ QVERIFY(item.isUserTristate());
+ QVERIFY(item.flags() & Qt::ItemIsUserTristate);
+ item.setAutoTristate(true);
+ QVERIFY(item.isAutoTristate());
+ QVERIFY(item.flags() & Qt::ItemIsAutoTristate);
#ifndef QT_NO_DRAGANDDROP
item.setDragEnabled(true);
QVERIFY(item.isDragEnabled());
@@ -306,10 +309,12 @@ void tst_QStandardItem::getSetFlags()
item.setCheckable(false);
QVERIFY(!item.isCheckable());
QVERIFY(!(item.flags() & Qt::ItemIsUserCheckable));
- QVERIFY(item.isTristate());
- item.setTristate(false);
- QVERIFY(!item.isTristate());
- QVERIFY(!(item.flags() & Qt::ItemIsTristate));
+ item.setUserTristate(false);
+ QVERIFY(!item.isUserTristate());
+ QVERIFY(!(item.flags() & Qt::ItemIsUserTristate));
+ item.setAutoTristate(false);
+ QVERIFY(!item.isAutoTristate());
+ QVERIFY(!(item.flags() & Qt::ItemIsAutoTristate));
#ifndef QT_NO_DRAGANDDROP
QVERIFY(item.isDragEnabled());
item.setDragEnabled(false);
@@ -325,6 +330,13 @@ void tst_QStandardItem::getSetFlags()
item.setCheckState(Qt::Checked);
item.setCheckable(true);
QCOMPARE(item.checkState(), Qt::Checked);
+
+ // deprecated API
+ item.setTristate(true);
+ QVERIFY(item.isTristate());
+ QVERIFY(item.flags() & Qt::ItemIsTristate);
+ item.setTristate(false);
+ QVERIFY(!(item.flags() & Qt::ItemIsTristate));
}
void tst_QStandardItem::getSetRowAndColumnCount()
diff --git a/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp b/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp
index 19365bffdd..2ddfdad7e4 100644
--- a/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp
+++ b/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp
@@ -912,7 +912,7 @@ void tst_QGuiApplication::genericPluginsAndWindowSystemEvents()
QGuiApplication app(argc, argv);
QVERIFY(QGuiApplication::primaryScreen());
- QVERIFY(QGuiApplication::primaryScreen()->orientation() == testOrientationToSend);
+ QCOMPARE(QGuiApplication::primaryScreen()->orientation(), testOrientationToSend);
QCOMPARE(testReceiver.customEvents, 0);
QCoreApplication::sendPostedEvents(&testReceiver);
diff --git a/tests/auto/gui/kernel/qguieventloop/BLACKLIST b/tests/auto/gui/kernel/qguieventloop/BLACKLIST
new file mode 100644
index 0000000000..688df0192b
--- /dev/null
+++ b/tests/auto/gui/kernel/qguieventloop/BLACKLIST
@@ -0,0 +1,2 @@
+[processEvents]
+ubuntu-14.04
diff --git a/tests/auto/gui/kernel/qguivariant/no_application/main.cpp b/tests/auto/gui/kernel/qguivariant/no_application/main.cpp
index c37e633d75..1294751224 100644
--- a/tests/auto/gui/kernel/qguivariant/no_application/main.cpp
+++ b/tests/auto/gui/kernel/qguivariant/no_application/main.cpp
@@ -56,7 +56,7 @@ void tst_QGuiVariantNoApplication::variantWithoutApplication()
{
QVariant v = QString("red");
- QVERIFY(qvariant_cast<QColor>(v) == QColor(Qt::red));
+ QCOMPARE(qvariant_cast<QColor>(v), QColor(Qt::red));
}
diff --git a/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp b/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp
index 58c595ad07..0e822ced5b 100644
--- a/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp
+++ b/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp
@@ -140,13 +140,13 @@ void tst_QGuiVariant::constructor_invalid()
QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type, type id:"));
QVariant variant(static_cast<QVariant::Type>(typeId));
QVERIFY(!variant.isValid());
- QVERIFY(variant.userType() == QMetaType::UnknownType);
+ QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
}
{
QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type, type id:"));
QVariant variant(typeId, /* copy */ 0);
QVERIFY(!variant.isValid());
- QVERIFY(variant.userType() == QMetaType::UnknownType);
+ QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
}
}
@@ -611,9 +611,9 @@ void tst_QGuiVariant::writeToReadFromDataStream()
// the uninitialized float can be NaN (observed on Windows Mobile 5 ARMv4i)
float readFloat = qvariant_cast<float>(readVariant);
float writtenFloat = qvariant_cast<float>(writeVariant);
- QVERIFY(qIsNaN(readFloat) == qIsNaN(writtenFloat));
+ QCOMPARE(qIsNaN(readFloat), qIsNaN(writtenFloat));
if (!qIsNaN(readFloat))
- QVERIFY(readFloat == writtenFloat);
+ QCOMPARE(readFloat, writtenFloat);
}
break;
}
@@ -632,7 +632,7 @@ void tst_QGuiVariant::writeToReadFromOldDataStream()
dataFileStream.setVersion(QDataStream::Qt_4_9);
QVariant readVariant;
dataFileStream >> readVariant;
- QVERIFY(readVariant.userType() == QMetaType::QPolygonF);
+ QCOMPARE(readVariant.userType(), int(QMetaType::QPolygonF));
QCOMPARE(testVariant, readVariant);
file.close();
}
@@ -656,7 +656,7 @@ void tst_QGuiVariant::writeToReadFromOldDataStream()
QDataStream readVarData(variantData);
readVarData >> dummy;
readVarData >> polyData50;
- QVERIFY(polyData49 == polyData50);
+ QCOMPARE(polyData49, polyData50);
}
}
diff --git a/tests/auto/gui/kernel/qinputmethod/tst_qinputmethod.cpp b/tests/auto/gui/kernel/qinputmethod/tst_qinputmethod.cpp
index a36e31e2e2..ab17edecb6 100644
--- a/tests/auto/gui/kernel/qinputmethod/tst_qinputmethod.cpp
+++ b/tests/auto/gui/kernel/qinputmethod/tst_qinputmethod.cpp
@@ -292,6 +292,9 @@ void tst_qinputmethod::inputMethodAccepted()
if (qApp->platformName().toLower() == QLatin1String("wayland"))
QSKIP("Wayland: This fails. Figure out why.");
+ if (qApp->platformName().toLower() == QLatin1String("xcb"))
+ QSKIP("XCB: depends on dedicated platform context.");
+
InputItem disabledItem;
disabledItem.setEnabled(false);
diff --git a/tests/auto/gui/kernel/qopenglwindow/tst_qopenglwindow.cpp b/tests/auto/gui/kernel/qopenglwindow/tst_qopenglwindow.cpp
index dcead8bfbf..1fc4967b12 100644
--- a/tests/auto/gui/kernel/qopenglwindow/tst_qopenglwindow.cpp
+++ b/tests/auto/gui/kernel/qopenglwindow/tst_qopenglwindow.cpp
@@ -248,7 +248,7 @@ public:
GLuint fbo = 0xFFFF;
QOpenGLContext::currentContext()->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *) &fbo);
- QVERIFY(fbo == 0);
+ QCOMPARE(fbo, GLuint(0));
}
void paintGL() Q_DECL_OVERRIDE {
@@ -272,7 +272,7 @@ public:
GLuint fbo = 0xFFFF;
QOpenGLContext::currentContext()->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *) &fbo);
- QVERIFY(fbo == 0);
+ QCOMPARE(fbo, GLuint(0));
}
};
diff --git a/tests/auto/gui/kernel/qpixelformat/tst_qpixelformat.cpp b/tests/auto/gui/kernel/qpixelformat/tst_qpixelformat.cpp
index 0d5991ef41..a5f86c6c09 100644
--- a/tests/auto/gui/kernel/qpixelformat/tst_qpixelformat.cpp
+++ b/tests/auto/gui/kernel/qpixelformat/tst_qpixelformat.cpp
@@ -53,7 +53,7 @@ void tst_QPixelFormat::testOperators()
{
QPixelFormat first = qPixelFormatRgba(8,8,8,8,QPixelFormat::UsesAlpha, QPixelFormat::AtBeginning, QPixelFormat::Premultiplied);
QPixelFormat second = qPixelFormatRgba(8,8,8,8,QPixelFormat::UsesAlpha, QPixelFormat::AtBeginning, QPixelFormat::Premultiplied);
- QVERIFY(first == second);
+ QCOMPARE(first, second);
QPixelFormat third = qPixelFormatRgba(8,8,8,8,QPixelFormat::UsesAlpha, QPixelFormat::AtEnd, QPixelFormat::NotPremultiplied);
QVERIFY(first != third);
diff --git a/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp b/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp
index fd3cfd55ff..d754e0b3c3 100644
--- a/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp
+++ b/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp
@@ -39,33 +39,8 @@
#include <QtWidgets/QWidget>
#include <QtTest>
#include <qpa/qwindowsysteminterface.h>
-
-// FIXME: Use static functions of QWindowSystemInterface introduced with HighDPI scaling in 5.6 instead.
-static QWindowSystemInterface::TouchPoint touchPoint(const QTouchEvent::TouchPoint& pt)
-{
- QWindowSystemInterface::TouchPoint p;
- p.id = pt.id();
- p.flags = pt.flags();
- p.normalPosition = pt.normalizedPos();
- p.area = pt.screenRect();
- p.pressure = pt.pressure();
- p.state = pt.state();
- p.velocity = pt.velocity();
- p.rawPositions = pt.rawScreenPositions();
- return p;
-}
-
-static QList<struct QWindowSystemInterface::TouchPoint> touchPointList(const QList<QTouchEvent::TouchPoint>& pointList)
-{
- QList<struct QWindowSystemInterface::TouchPoint> newList;
-
- Q_FOREACH (QTouchEvent::TouchPoint p, pointList)
- {
- newList.append(touchPoint(p));
- }
- return newList;
-}
-
+#include <qpa/qwindowsysteminterface_p.h>
+#include <private/qhighdpiscaling_p.h>
class tst_QTouchEventWidget : public QWidget
{
@@ -622,11 +597,10 @@ void tst_QTouchEvent::basicRawEventTranslation()
rawPosList << QPointF(12, 34) << QPointF(56, 78);
rawTouchPoint.setRawScreenPositions(rawPosList);
const ulong timestamp = 1234;
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- timestamp,
- touchScreenDevice,
- touchPointList(
- QList<QTouchEvent::TouchPoint>() << rawTouchPoint));
+ QWindow *window = touchWidget.windowHandle();
+ QList<QWindowSystemInterface::TouchPoint> nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(QList<QTouchEvent::TouchPoint>() << rawTouchPoint, window);
+ QWindowSystemInterface::handleTouchEvent(window, timestamp, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -653,16 +627,16 @@ void tst_QTouchEvent::basicRawEventTranslation()
QCOMPARE(touchBeginPoint.sceneRect(), touchBeginPoint.screenRect());
QCOMPARE(touchBeginPoint.pressure(), qreal(1.));
QCOMPARE(touchBeginPoint.velocity(), QVector2D());
- QCOMPARE(touchBeginPoint.rawScreenPositions(), rawPosList);
+ if (!QHighDpiScaling::isActive())
+ QCOMPARE(touchBeginPoint.rawScreenPositions(), rawPosList);
// moving the point should translate to TouchUpdate
rawTouchPoint.setState(Qt::TouchPointMoved);
rawTouchPoint.setScreenPos(screenPos + delta);
rawTouchPoint.setNormalizedPos(normalized(rawTouchPoint.pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(QList<QTouchEvent::TouchPoint>() << rawTouchPoint));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(QList<QTouchEvent::TouchPoint>() << rawTouchPoint, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(touchWidget.seenTouchBegin);
QVERIFY(touchWidget.seenTouchUpdate);
@@ -692,10 +666,9 @@ void tst_QTouchEvent::basicRawEventTranslation()
rawTouchPoint.setState(Qt::TouchPointReleased);
rawTouchPoint.setScreenPos(screenPos + delta + delta);
rawTouchPoint.setNormalizedPos(normalized(rawTouchPoint.pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(QList<QTouchEvent::TouchPoint>() << rawTouchPoint));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(QList<QTouchEvent::TouchPoint>() << rawTouchPoint, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(touchWidget.seenTouchBegin);
QVERIFY(touchWidget.seenTouchUpdate);
@@ -762,10 +735,10 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen()
rawTouchPoints[1].setState(Qt::TouchPointPressed);
rawTouchPoints[1].setScreenPos(rightScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ QWindow *window = touchWidget.windowHandle();
+ QList<QWindowSystemInterface::TouchPoint> nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -827,10 +800,9 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen()
rawTouchPoints[1].setState(Qt::TouchPointMoved);
rawTouchPoints[1].setScreenPos(centerScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -892,10 +864,9 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen()
rawTouchPoints[1].setState(Qt::TouchPointReleased);
rawTouchPoints[1].setScreenPos(centerScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -992,10 +963,10 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchPad()
rawTouchPoints[1].setState(Qt::TouchPointPressed);
rawTouchPoints[1].setScreenPos(rightScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchPadDevice,
- touchPointList(rawTouchPoints));
+ QWindow *window = touchWidget.windowHandle();
+ QList<QWindowSystemInterface::TouchPoint> nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchPadDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -1058,10 +1029,9 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchPad()
rawTouchPoints[1].setState(Qt::TouchPointMoved);
rawTouchPoints[1].setScreenPos(centerScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchPadDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchPadDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -1123,10 +1093,9 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchPad()
rawTouchPoints[1].setState(Qt::TouchPointReleased);
rawTouchPoints[1].setScreenPos(centerScreenPos);
rawTouchPoints[1].setNormalizedPos(normalized(rawTouchPoints[1].pos(), screenGeometry));
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchPadDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchPadDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(!touchWidget.seenTouchBegin);
QVERIFY(!touchWidget.seenTouchUpdate);
@@ -1385,10 +1354,10 @@ void tst_QTouchEvent::deleteInRawEventTranslation()
rawTouchPoints[2].setNormalizedPos(normalized(rawTouchPoints[2].pos(), screenGeometry));
// generate begin events on all widgets, the left widget should die
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ QWindow *window = touchWidget.windowHandle();
+ QList<QWindowSystemInterface::TouchPoint> nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
QVERIFY(leftWidget.isNull());
QVERIFY(!centerWidget.isNull());
@@ -1398,20 +1367,18 @@ void tst_QTouchEvent::deleteInRawEventTranslation()
rawTouchPoints[0].setState(Qt::TouchPointMoved);
rawTouchPoints[1].setState(Qt::TouchPointMoved);
rawTouchPoints[2].setState(Qt::TouchPointMoved);
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
// generate end events on all widget, the right widget should die
rawTouchPoints[0].setState(Qt::TouchPointReleased);
rawTouchPoints[1].setState(Qt::TouchPointReleased);
rawTouchPoints[2].setState(Qt::TouchPointReleased);
- QWindowSystemInterface::handleTouchEvent(touchWidget.windowHandle(),
- 0,
- touchScreenDevice,
- touchPointList(rawTouchPoints));
+ nativeTouchPoints =
+ QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window);
+ QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints);
QCoreApplication::processEvents();
}
@@ -1447,6 +1414,8 @@ void tst_QTouchEvent::crashInQGraphicsSceneAfterNotHandlingTouchBegin()
void tst_QTouchEvent::touchBeginWithGraphicsWidget()
{
+ if (QHighDpiScaling::isActive())
+ QSKIP("Fails when scaling is active");
QGraphicsScene scene;
QGraphicsView view(&scene);
view.setWindowTitle(QTest::currentTestFunction());
@@ -1605,12 +1574,15 @@ void tst_QTouchEvent::testMultiDevice()
QWindowSystemInterface::TouchPoint tp;
tp.id = 0;
tp.state = Qt::TouchPointPressed;
- tp.area = QRectF(120, 120, 20, 20);
+ const QPoint screenOrigin = w.screen()->geometry().topLeft();
+ const QRect area0(120, 120, 20, 20);
+ tp.area = QHighDpi::toNative(area0, QHighDpiScaling::factor(&w), screenOrigin);
pointsOne.append(tp);
pointsTwo.append(tp);
tp.id = 1;
- tp.area = QRectF(140, 140, 20, 20);
+ const QRect area1(140, 140, 20, 20);
+ tp.area = QHighDpi::toNative(area1, QHighDpiScaling::factor(&w), screenOrigin);
pointsTwo.append(tp);
QWindowSystemInterface::handleTouchEvent(&w, deviceOne, pointsOne);
@@ -1625,12 +1597,12 @@ void tst_QTouchEvent::testMultiDevice()
QCOMPARE(filter.d.value(deviceOne).points.count(), 1);
QCOMPARE(filter.d.value(deviceTwo).points.count(), 2);
- QCOMPARE(filter.d.value(deviceOne).points.at(0).screenRect(), pointsOne[0].area);
+ QCOMPARE(filter.d.value(deviceOne).points.at(0).screenRect(), QRectF(area0));
QCOMPARE(filter.d.value(deviceOne).points.at(0).state(), pointsOne[0].state);
- QCOMPARE(filter.d.value(deviceTwo).points.at(0).screenRect(), pointsTwo[0].area);
+ QCOMPARE(filter.d.value(deviceTwo).points.at(0).screenRect(), QRectF(area0));
QCOMPARE(filter.d.value(deviceTwo).points.at(0).state(), pointsTwo[0].state);
- QCOMPARE(filter.d.value(deviceTwo).points.at(1).screenRect(), pointsTwo[1].area);
+ QCOMPARE(filter.d.value(deviceTwo).points.at(1).screenRect(), QRectF(area1));
QCOMPARE(filter.d.value(deviceTwo).points.at(1).state(), pointsTwo[1].state);
}
diff --git a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
index d361aa12a6..ccb8c759c6 100644
--- a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
+++ b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
@@ -35,6 +35,7 @@
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformintegration.h>
#include <private/qguiapplication_p.h>
+#include <private/qhighdpiscaling_p.h>
#include <QtGui/QPainter>
#include <QtTest/QtTest>
@@ -265,6 +266,19 @@ void tst_QWindow::positioning_data()
#endif
}
+// Compare a window position that may go through scaling in the platform plugin with fuzz.
+static inline bool qFuzzyCompareWindowPosition(const QPoint &p1, const QPoint p2, int fuzz)
+{
+ return (p1 - p2).manhattanLength() <= fuzz;
+}
+
+static QString msgPointMismatch(const QPoint &p1, const QPoint p2)
+{
+ QString result;
+ QDebug(&result) << p1 << "!=" << p2 << ", manhattanLength=" << (p1 - p2).manhattanLength();
+ return result;
+}
+
void tst_QWindow::positioning()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(
@@ -327,21 +341,25 @@ void tst_QWindow::positioning()
// if our positioning is actually fully respected by the window manager
// test whether it correctly handles frame positioning as well
if (originalPos == geometry.topLeft() && (originalMargins.top() != 0 || originalMargins.left() != 0)) {
- QPoint framePos = QPlatformScreen::platformScreenForWindow(&window)->availableGeometry().center();
+ const QScreen *screen = window.screen();
+ const QRect availableGeometry = screen->availableGeometry();
+ const QPoint framePos = availableGeometry.center();
window.reset();
const QPoint oldFramePos = window.framePosition();
window.setFramePosition(framePos);
QTRY_VERIFY(window.received(QEvent::Move));
- if (window.framePosition() != framePos) {
+ const int fuzz = int(QHighDpiScaling::factor(&window));
+ if (!qFuzzyCompareWindowPosition(window.framePosition(), framePos, fuzz)) {
qDebug() << "About to fail auto-test. Here is some additional information:";
qDebug() << "window.framePosition() == " << window.framePosition();
qDebug() << "old frame position == " << oldFramePos;
qDebug() << "We received " << window.received(QEvent::Move) << " move events";
qDebug() << "frame positions after each move event:" << window.m_framePositionsOnMove;
}
- QTRY_COMPARE(framePos, window.framePosition());
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(window.framePosition(), framePos, fuzz),
+ qPrintable(msgPointMismatch(window.framePosition(), framePos)));
QTRY_COMPARE(originalMargins, window.frameMargins());
QCOMPARE(window.position(), window.framePosition() + QPoint(originalMargins.left(), originalMargins.top()));
@@ -357,7 +375,8 @@ void tst_QWindow::positioning()
void tst_QWindow::positioningDuringMinimized()
{
// QTBUG-39544, setting a geometry in minimized state should work as well.
- if (QGuiApplication::platformName().compare("windows", Qt::CaseInsensitive))
+ if (QGuiApplication::platformName().compare("windows", Qt::CaseInsensitive) != 0
+ && QGuiApplication::platformName().compare("cocoa", Qt::CaseInsensitive) != 0)
QSKIP("Not supported on this platform");
Window window;
window.setTitle(QStringLiteral("positioningDuringMinimized"));
@@ -418,14 +437,14 @@ void tst_QWindow::platformSurface()
QCOMPARE(window.geometry(), geometry);
window.create();
- QTRY_VERIFY(window.received(QEvent::PlatformSurface) == 1);
- QTRY_VERIFY(window.surfaceEventType() == QPlatformSurfaceEvent::SurfaceCreated);
+ QTRY_COMPARE(window.received(QEvent::PlatformSurface), 1);
+ QTRY_COMPARE(window.surfaceEventType(), QPlatformSurfaceEvent::SurfaceCreated);
QTRY_VERIFY(window.handle() != Q_NULLPTR);
window.destroy();
- QTRY_VERIFY(window.received(QEvent::PlatformSurface) == 2);
- QTRY_VERIFY(window.surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed);
- QTRY_VERIFY(window.handle() == Q_NULLPTR);
+ QTRY_COMPARE(window.received(QEvent::PlatformSurface), 2);
+ QTRY_COMPARE(window.surfaceEventType(), QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed);
+ QTRY_VERIFY(!window.handle());
// Check for synchronous delivery of platform surface events and that the platform
// surface always existed upon event delivery
@@ -487,7 +506,7 @@ void tst_QWindow::isActive()
context.swapBuffers(&window);
#endif
QTRY_COMPARE(window.received(QEvent::Resize), 1);
- QTRY_VERIFY(QGuiApplication::focusWindow() == &window);
+ QTRY_COMPARE(QGuiApplication::focusWindow(), &window);
QVERIFY(window.isActive());
Window child;
@@ -499,7 +518,7 @@ void tst_QWindow::isActive()
child.requestActivate();
- QTRY_VERIFY(QGuiApplication::focusWindow() == &child);
+ QTRY_COMPARE(QGuiApplication::focusWindow(), &child);
QVERIFY(child.isActive());
// parent shouldn't receive new resize events from child being shown
@@ -522,7 +541,7 @@ void tst_QWindow::isActive()
QTRY_VERIFY(dialog.isExposed());
QCoreApplication::processEvents();
QTRY_COMPARE(dialog.received(QEvent::Resize), 1);
- QTRY_VERIFY(QGuiApplication::focusWindow() == &dialog);
+ QTRY_COMPARE(QGuiApplication::focusWindow(), &dialog);
QVERIFY(dialog.isActive());
// transient child has focus
@@ -533,7 +552,7 @@ void tst_QWindow::isActive()
window.requestActivate();
- QTRY_VERIFY(QGuiApplication::focusWindow() == &window);
+ QTRY_COMPARE(QGuiApplication::focusWindow(), &window);
QCoreApplication::processEvents();
QTRY_COMPARE(dialog.received(QEvent::FocusOut), 1);
QTRY_COMPARE(window.received(QEvent::FocusIn), 2);
@@ -654,15 +673,13 @@ void tst_QWindow::testInputEvents()
window.showNormal();
QVERIFY(QTest::qWaitForWindowExposed(&window));
- QWindowSystemInterface::handleKeyEvent(&window, QEvent::KeyPress, Qt::Key_A, Qt::NoModifier);
- QWindowSystemInterface::handleKeyEvent(&window, QEvent::KeyRelease, Qt::Key_A, Qt::NoModifier);
+ QTest::keyClick(&window, Qt::Key_A, Qt::NoModifier);
QCoreApplication::processEvents();
QCOMPARE(window.keyPressCode, int(Qt::Key_A));
QCOMPARE(window.keyReleaseCode, int(Qt::Key_A));
QPointF local(12, 34);
- QWindowSystemInterface::handleMouseEvent(&window, local, local, Qt::LeftButton);
- QWindowSystemInterface::handleMouseEvent(&window, local, local, Qt::NoButton);
+ QTest::mouseClick(&window, Qt::LeftButton, Qt::NoModifier, local.toPoint());
QCoreApplication::processEvents();
QCOMPARE(window.mousePressButton, int(Qt::LeftButton));
QCOMPARE(window.mouseReleaseButton, int(Qt::LeftButton));
@@ -688,15 +705,17 @@ void tst_QWindow::testInputEvents()
// Now with null pointer as window. local param should not be utilized:
// handleMouseEvent() with tlw == 0 means the event is in global coords only.
window.mousePressButton = window.mouseReleaseButton = 0;
- QPointF nonWindowGlobal(window.geometry().topRight() + QPoint(200, 50)); // not inside the window
- QWindowSystemInterface::handleMouseEvent(0, nonWindowGlobal, nonWindowGlobal, Qt::LeftButton);
- QWindowSystemInterface::handleMouseEvent(0, nonWindowGlobal, nonWindowGlobal, Qt::NoButton);
+ const QPointF nonWindowGlobal(window.geometry().topRight() + QPoint(200, 50)); // not inside the window
+ const QPointF deviceNonWindowGlobal = QHighDpi::toNativePixels(nonWindowGlobal, window.screen());
+ QWindowSystemInterface::handleMouseEvent(0, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::LeftButton);
+ QWindowSystemInterface::handleMouseEvent(0, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::NoButton);
QCoreApplication::processEvents();
QCOMPARE(window.mousePressButton, 0);
QCOMPARE(window.mouseReleaseButton, 0);
- QPointF windowGlobal = window.mapToGlobal(local.toPoint());
- QWindowSystemInterface::handleMouseEvent(0, windowGlobal, windowGlobal, Qt::LeftButton);
- QWindowSystemInterface::handleMouseEvent(0, windowGlobal, windowGlobal, Qt::NoButton);
+ const QPointF windowGlobal = window.mapToGlobal(local.toPoint());
+ const QPointF deviceWindowGlobal = QHighDpi::toNativePixels(windowGlobal, window.screen());
+ QWindowSystemInterface::handleMouseEvent(0, deviceWindowGlobal, deviceWindowGlobal, Qt::LeftButton);
+ QWindowSystemInterface::handleMouseEvent(0, deviceWindowGlobal, deviceWindowGlobal, Qt::NoButton);
QCoreApplication::processEvents();
QCOMPARE(window.mousePressButton, int(Qt::LeftButton));
QCOMPARE(window.mouseReleaseButton, int(Qt::LeftButton));
@@ -718,7 +737,7 @@ void tst_QWindow::touchToMouseTranslation()
const QRectF moveArea(105, 108, 4, 4);
tp1.id = 1;
tp1.state = Qt::TouchPointPressed;
- tp1.area = pressArea;
+ tp1.area = QHighDpi::toNativePixels(pressArea, &window);
tp2.id = 2;
tp2.state = Qt::TouchPointPressed;
points << tp1 << tp2;
@@ -729,7 +748,7 @@ void tst_QWindow::touchToMouseTranslation()
tp1.state = Qt::TouchPointStationary;
tp2.id = 1;
tp2.state = Qt::TouchPointMoved;
- tp2.area = moveArea;
+ tp2.area = QHighDpi::toNativePixels(moveArea, &window);
points.clear();
points << tp1 << tp2;
QWindowSystemInterface::handleTouchEvent(&window, touchDevice, points);
@@ -946,12 +965,15 @@ void tst_QWindow::touchCancelWithTouchToMouse()
tp1.id = 1;
tp1.state = Qt::TouchPointPressed;
- tp1.area = QRect(100, 100, 4, 4);
+ const QRect area(100, 100, 4, 4);
+ tp1.area = QHighDpi::toNativePixels(area, &window);
points << tp1;
QWindowSystemInterface::handleTouchEvent(&window, touchDevice, points);
QCoreApplication::processEvents();
QTRY_COMPARE(window.mousePressButton, int(Qt::LeftButton));
- QTRY_COMPARE(window.mousePressScreenPos, points[0].area.center());
+ const int fuzz = 2 * int(QHighDpiScaling::factor(&window));
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(window.mousePressScreenPos.toPoint(), area.center(), fuzz),
+ qPrintable(msgPointMismatch(window.mousePressScreenPos.toPoint(), area.center())));
// Cancel the touch. Should result in a mouse release for windows that have
// have an active touch-to-mouse sequence.
@@ -1149,8 +1171,9 @@ void tst_QWindow::mouseEventSequence()
ulong timestamp = 0;
QPointF local(12, 34);
- QWindowSystemInterface::handleMouseEvent(&window, timestamp++, local, local, Qt::LeftButton);
- QWindowSystemInterface::handleMouseEvent(&window, timestamp++, local, local, Qt::NoButton);
+ const QPointF deviceLocal = QHighDpi::toNativePixels(local, &window);
+ QWindowSystemInterface::handleMouseEvent(&window, timestamp++, deviceLocal, deviceLocal, Qt::LeftButton);
+ QWindowSystemInterface::handleMouseEvent(&window, timestamp++, deviceLocal, deviceLocal, Qt::NoButton);
QCoreApplication::processEvents();
QCOMPARE(window.mousePressedCount, 1);
QCOMPARE(window.mouseReleasedCount, 1);
@@ -1308,14 +1331,14 @@ void tst_QWindow::inputReentrancy()
class TabletTestWindow : public QWindow
{
public:
- TabletTestWindow() : eventType(0) { }
+ TabletTestWindow() : eventType(QEvent::None) { }
void tabletEvent(QTabletEvent *ev) {
eventType = ev->type();
eventGlobal = ev->globalPosF();
eventLocal = ev->posF();
eventDevice = ev->device();
}
- int eventType;
+ QEvent::Type eventType;
QPointF eventGlobal, eventLocal;
int eventDevice;
bool eventFilter(QObject *obj, QEvent *ev) {
@@ -1337,25 +1360,27 @@ void tst_QWindow::tabletEvents()
window.setGeometry(QRect(m_availableTopLeft + QPoint(10, 10), m_testWindowSize));
qGuiApp->installEventFilter(&window);
- QPoint local(10, 10);
- QPoint global = window.mapToGlobal(local);
- QWindowSystemInterface::handleTabletEvent(&window, true, local, global, 1, 2, 0.5, 1, 2, 0.1, 0, 0, 0);
+ const QPoint local(10, 10);
+ const QPoint global = window.mapToGlobal(local);
+ const QPoint deviceLocal = QHighDpi::toNativeLocalPosition(local, &window);
+ const QPoint deviceGlobal = QHighDpi::toNativePixels(global, window.screen());
+ QWindowSystemInterface::handleTabletEvent(&window, true, deviceLocal, deviceGlobal, 1, 2, 0.5, 1, 2, 0.1, 0, 0, 0);
QCoreApplication::processEvents();
QTRY_VERIFY(window.eventType == QEvent::TabletPress);
QTRY_COMPARE(window.eventGlobal.toPoint(), global);
QTRY_COMPARE(window.eventLocal.toPoint(), local);
- QWindowSystemInterface::handleTabletEvent(&window, false, local, global, 1, 2, 0.5, 1, 2, 0.1, 0, 0, 0);
+ QWindowSystemInterface::handleTabletEvent(&window, false, deviceLocal, deviceGlobal, 1, 2, 0.5, 1, 2, 0.1, 0, 0, 0);
QCoreApplication::processEvents();
- QTRY_VERIFY(window.eventType == QEvent::TabletRelease);
+ QTRY_COMPARE(window.eventType, QEvent::TabletRelease);
QWindowSystemInterface::handleTabletEnterProximityEvent(1, 2, 3);
QCoreApplication::processEvents();
- QTRY_VERIFY(window.eventType == QEvent::TabletEnterProximity);
+ QTRY_COMPARE(window.eventType, QEvent::TabletEnterProximity);
QTRY_COMPARE(window.eventDevice, 1);
QWindowSystemInterface::handleTabletLeaveProximityEvent(1, 2, 3);
QCoreApplication::processEvents();
- QTRY_VERIFY(window.eventType == QEvent::TabletLeaveProximity);
+ QTRY_COMPARE(window.eventType, QEvent::TabletLeaveProximity);
QTRY_COMPARE(window.eventDevice, 1);
#endif
@@ -1703,13 +1728,13 @@ void tst_QWindow::requestUpdate()
QCoreApplication::processEvents();
QTRY_VERIFY(window.isExposed());
- QVERIFY(window.received(QEvent::UpdateRequest) == 0);
+ QCOMPARE(window.received(QEvent::UpdateRequest), 0);
window.requestUpdate();
- QTRY_VERIFY(window.received(QEvent::UpdateRequest) == 1);
+ QTRY_COMPARE(window.received(QEvent::UpdateRequest), 1);
window.requestUpdate();
- QTRY_VERIFY(window.received(QEvent::UpdateRequest) == 2);
+ QTRY_COMPARE(window.received(QEvent::UpdateRequest), 2);
}
#include <tst_qwindow.moc>
diff --git a/tests/auto/gui/math3d/qmatrixnxn/tst_qmatrixnxn.cpp b/tests/auto/gui/math3d/qmatrixnxn/tst_qmatrixnxn.cpp
index e7659a25bd..463322ff2a 100644
--- a/tests/auto/gui/math3d/qmatrixnxn/tst_qmatrixnxn.cpp
+++ b/tests/auto/gui/math3d/qmatrixnxn/tst_qmatrixnxn.cpp
@@ -673,7 +673,7 @@ void tst_QMatrixNxN::compare2x2()
QMatrix2x2 m2(uniqueValues2);
QMatrix2x2 m3(transposedValues2);
- QVERIFY(m1 == m2);
+ QCOMPARE(m1, m2);
QVERIFY(!(m1 != m2));
QVERIFY(m1 != m3);
QVERIFY(!(m1 == m3));
@@ -686,7 +686,7 @@ void tst_QMatrixNxN::compare3x3()
QMatrix3x3 m2(uniqueValues3);
QMatrix3x3 m3(transposedValues3);
- QVERIFY(m1 == m2);
+ QCOMPARE(m1, m2);
QVERIFY(!(m1 != m2));
QVERIFY(m1 != m3);
QVERIFY(!(m1 == m3));
@@ -699,7 +699,7 @@ void tst_QMatrixNxN::compare4x4()
QMatrix4x4 m2(uniqueValues4);
QMatrix4x4 m3(transposedValues4);
- QVERIFY(m1 == m2);
+ QCOMPARE(m1, m2);
QVERIFY(!(m1 != m2));
QVERIFY(m1 != m3);
QVERIFY(!(m1 == m3));
@@ -712,7 +712,7 @@ void tst_QMatrixNxN::compare4x3()
QMatrix4x3 m2(uniqueValues4x3);
QMatrix4x3 m3(transposedValues3x4);
- QVERIFY(m1 == m2);
+ QCOMPARE(m1, m2);
QVERIFY(!(m1 != m2));
QVERIFY(m1 != m3);
QVERIFY(!(m1 == m3));
@@ -1858,7 +1858,7 @@ void tst_QMatrixNxN::inverted4x4()
if (invertible)
QVERIFY(m1.determinant() != 0.0f);
else
- QVERIFY(m1.determinant() == 0.0f);
+ QCOMPARE(m1.determinant(), 0.0f);
Matrix4 m1alt;
memcpy(m1alt.v, (const float *)m1Values, sizeof(m1alt.v));
@@ -1992,7 +1992,7 @@ void tst_QMatrixNxN::scale4x4()
if (z == 1.0f) {
QMatrix4x4 m2b;
m2b.scale(x, y);
- QVERIFY(m2b == m2);
+ QCOMPARE(m2b, m2);
}
QVector3D v1(2.0f, 3.0f, -4.0f);
@@ -2051,7 +2051,7 @@ void tst_QMatrixNxN::scale4x4()
if (z == 1.0f) {
QMatrix4x4 m4b(m3);
m4b.scale(x, y);
- QVERIFY(m4b == m4);
+ QCOMPARE(m4b, m4);
}
// Test coverage when the special matrix type is unknown.
@@ -2138,7 +2138,7 @@ void tst_QMatrixNxN::translate4x4()
if (z == 0.0f) {
QMatrix4x4 m2b;
m2b.translate(x, y);
- QVERIFY(m2b == m2);
+ QCOMPARE(m2b, m2);
}
QVector3D v1(2.0f, 3.0f, -4.0f);
@@ -2179,7 +2179,7 @@ void tst_QMatrixNxN::translate4x4()
if (z == 0.0f) {
QMatrix4x4 m4b(m3);
m4b.translate(x, y);
- QVERIFY(m4b == m4);
+ QCOMPARE(m4b, m4);
}
}
@@ -3073,7 +3073,7 @@ void tst_QMatrixNxN::convertQMatrix()
QPointF p2 = m2 * QPointF(100.0, 150.0);
QCOMPARE((double)p2.x(), 100.0 - 3.5);
QCOMPARE((double)p2.y(), 150.0 + 2.0);
- QVERIFY(m1 == m2.toAffine());
+ QCOMPARE(m1, m2.toAffine());
QMatrix m3;
m3.scale(1.5, -2.0);
@@ -3085,7 +3085,7 @@ void tst_QMatrixNxN::convertQMatrix()
QPointF p4 = m4 * QPointF(100.0, 150.0);
QCOMPARE((double)p4.x(), 1.5 * 100.0);
QCOMPARE((double)p4.y(), -2.0 * 150.0);
- QVERIFY(m3 == m4.toAffine());
+ QCOMPARE(m3, m4.toAffine());
QMatrix m5;
m5.rotate(45.0);
@@ -3120,7 +3120,7 @@ void tst_QMatrixNxN::convertQTransform()
QPointF p2 = m2 * QPointF(100.0, 150.0);
QCOMPARE((double)p2.x(), 100.0 - 3.5);
QCOMPARE((double)p2.y(), 150.0 + 2.0);
- QVERIFY(m1 == m2.toTransform());
+ QCOMPARE(m1, m2.toTransform());
QTransform m3;
m3.scale(1.5, -2.0);
@@ -3132,7 +3132,7 @@ void tst_QMatrixNxN::convertQTransform()
QPointF p4 = m4 * QPointF(100.0, 150.0);
QCOMPARE((double)p4.x(), 1.5 * 100.0);
QCOMPARE((double)p4.y(), -2.0 * 150.0);
- QVERIFY(m3 == m4.toTransform());
+ QCOMPARE(m3, m4.toTransform());
QTransform m5;
m5.rotate(45.0);
@@ -3206,16 +3206,16 @@ void tst_QMatrixNxN::mapRect()
QRect recti(qRound(x), qRound(y), qRound(width), qRound(height));
QMatrix4x4 m1;
- QVERIFY(m1.mapRect(rect) == rect);
- QVERIFY(m1.mapRect(recti) == recti);
+ QCOMPARE(m1.mapRect(rect), rect);
+ QCOMPARE(m1.mapRect(recti), recti);
QMatrix4x4 m2;
m2.translate(-100.5f, 64.0f);
QRectF translated = rect.translated(-100.5f, 64.0f);
QRect translatedi = QRect(qRound(recti.x() - 100.5f), recti.y() + 64,
recti.width(), recti.height());
- QVERIFY(m2.mapRect(rect) == translated);
- QVERIFY(m2.mapRect(recti) == translatedi);
+ QCOMPARE(m2.mapRect(rect), translated);
+ QCOMPARE(m2.mapRect(recti), translatedi);
QMatrix4x4 m3;
m3.scale(-100.5f, 64.0f);
@@ -3232,7 +3232,7 @@ void tst_QMatrixNxN::mapRect()
scaley -= scaleht;
}
QRectF scaled(scalex, scaley, scalewid, scaleht);
- QVERIFY(m3.mapRect(rect) == scaled);
+ QCOMPARE(m3.mapRect(rect), scaled);
scalex = recti.x() * -100.5f;
scaley = recti.y() * 64.0f;
scalewid = recti.width() * -100.5f;
@@ -3247,7 +3247,7 @@ void tst_QMatrixNxN::mapRect()
}
QRect scaledi(qRound(scalex), qRound(scaley),
qRound(scalewid), qRound(scaleht));
- QVERIFY(m3.mapRect(recti) == scaledi);
+ QCOMPARE(m3.mapRect(recti), scaledi);
QMatrix4x4 m4;
m4.translate(-100.5f, 64.0f);
@@ -3261,7 +3261,7 @@ void tst_QMatrixNxN::mapRect()
if (transy1 > transy2)
qSwap(transy1, transy2);
QRectF trans(transx1, transy1, transx2 - transx1, transy2 - transy1);
- QVERIFY(m4.mapRect(rect) == trans);
+ QCOMPARE(m4.mapRect(rect), trans);
transx1 = recti.x() * -2.5f - 100.5f;
transy1 = recti.y() * 4.0f + 64.0f;
transx2 = (recti.x() + recti.width()) * -2.5f - 100.5f;
@@ -3273,7 +3273,7 @@ void tst_QMatrixNxN::mapRect()
QRect transi(qRound(transx1), qRound(transy1),
qRound(transx2) - qRound(transx1),
qRound(transy2) - qRound(transy1));
- QVERIFY(m4.mapRect(recti) == transi);
+ QCOMPARE(m4.mapRect(recti), transi);
m4.rotate(45.0f, 0.0f, 0.0f, 1.0f);
@@ -3290,7 +3290,7 @@ void tst_QMatrixNxN::mapRect()
QRect mri = m4.mapRect(recti);
QRect tri = t4.mapRect(recti);
- QVERIFY(mri == tri);
+ QCOMPARE(mri, tri);
}
void tst_QMatrixNxN::mapVector_data()
@@ -3389,14 +3389,14 @@ void tst_QMatrixNxN::properties()
void tst_QMatrixNxN::metaTypes()
{
- QVERIFY(QMetaType::type("QMatrix4x4") == QMetaType::QMatrix4x4);
+ QCOMPARE(QMetaType::type("QMatrix4x4"), int(QMetaType::QMatrix4x4));
QCOMPARE(QByteArray(QMetaType::typeName(QMetaType::QMatrix4x4)),
QByteArray("QMatrix4x4"));
QVERIFY(QMetaType::isRegistered(QMetaType::QMatrix4x4));
- QVERIFY(qMetaTypeId<QMatrix4x4>() == QMetaType::QMatrix4x4);
+ QCOMPARE(qMetaTypeId<QMatrix4x4>(), int(QMetaType::QMatrix4x4));
}
QTEST_APPLESS_MAIN(tst_QMatrixNxN)
diff --git a/tests/auto/gui/math3d/qquaternion/tst_qquaternion.cpp b/tests/auto/gui/math3d/qquaternion/tst_qquaternion.cpp
index ec7af97f07..1fbad5b829 100644
--- a/tests/auto/gui/math3d/qquaternion/tst_qquaternion.cpp
+++ b/tests/auto/gui/math3d/qquaternion/tst_qquaternion.cpp
@@ -446,7 +446,7 @@ void tst_QQuaternion::compare()
QQuaternion v5(8, 1, 2, 3);
QQuaternion v6(3, 1, 2, 4);
- QVERIFY(v1 == v2);
+ QCOMPARE(v1, v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
QVERIFY(v1 != v5);
@@ -522,7 +522,7 @@ void tst_QQuaternion::add()
QQuaternion v4(v1);
v4 += v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() + v2.x());
QCOMPARE(v4.y(), v1.y() + v2.y());
@@ -560,7 +560,7 @@ void tst_QQuaternion::subtract()
QQuaternion v4(v3);
v4 -= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() - v1.x());
QCOMPARE(v4.y(), v3.y() - v1.y());
@@ -569,7 +569,7 @@ void tst_QQuaternion::subtract()
QQuaternion v5(v3);
v5 -= v2;
- QVERIFY(v5 == v1);
+ QCOMPARE(v5, v1);
QCOMPARE(v5.x(), v3.x() - v2.x());
QCOMPARE(v5.y(), v3.y() - v2.y());
@@ -704,7 +704,7 @@ void tst_QQuaternion::multiplyFactor()
QQuaternion v3(v1);
v3 *= factor;
- QVERIFY(v3 == v2);
+ QCOMPARE(v3, v2);
QCOMPARE(v3.x(), v1.x() * factor);
QCOMPARE(v3.y(), v1.y() * factor);
@@ -740,7 +740,7 @@ void tst_QQuaternion::divide()
QQuaternion v3(v2);
v3 /= factor;
- QVERIFY(v3 == v1);
+ QCOMPARE(v3, v1);
QCOMPARE(v3.x(), v2.x() / factor);
QCOMPARE(v3.y(), v2.y() / factor);
@@ -764,7 +764,7 @@ void tst_QQuaternion::negate()
QQuaternion v1(w1, x1, y1, z1);
QQuaternion v2(-w1, -x1, -y1, -z1);
- QVERIFY(-v1 == v2);
+ QCOMPARE(-v1, v2);
}
// Test quaternion conjugate calculations.
@@ -783,7 +783,7 @@ void tst_QQuaternion::conjugate()
QQuaternion v1(w1, x1, y1, z1);
QQuaternion v2(w1, -x1, -y1, -z1);
- QVERIFY(v1.conjugate() == v2);
+ QCOMPARE(v1.conjugate(), v2);
}
// Test quaternion creation from an axis and an angle.
@@ -1325,14 +1325,14 @@ void tst_QQuaternion::properties()
void tst_QQuaternion::metaTypes()
{
- QVERIFY(QMetaType::type("QQuaternion") == QMetaType::QQuaternion);
+ QCOMPARE(QMetaType::type("QQuaternion"), int(QMetaType::QQuaternion));
QCOMPARE(QByteArray(QMetaType::typeName(QMetaType::QQuaternion)),
QByteArray("QQuaternion"));
QVERIFY(QMetaType::isRegistered(QMetaType::QQuaternion));
- QVERIFY(qMetaTypeId<QQuaternion>() == QMetaType::QQuaternion);
+ QCOMPARE(qMetaTypeId<QQuaternion>(), int(QMetaType::QQuaternion));
}
QTEST_APPLESS_MAIN(tst_QQuaternion)
diff --git a/tests/auto/gui/math3d/qvectornd/tst_qvectornd.cpp b/tests/auto/gui/math3d/qvectornd/tst_qvectornd.cpp
index d2e0bbe375..eeff2c3bae 100644
--- a/tests/auto/gui/math3d/qvectornd/tst_qvectornd.cpp
+++ b/tests/auto/gui/math3d/qvectornd/tst_qvectornd.cpp
@@ -885,7 +885,7 @@ void tst_QVectorND::compare2()
QVector2D v3(3, 2);
QVector2D v4(1, 3);
- QVERIFY(v1 == v2);
+ QCOMPARE(v1, v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
}
@@ -899,7 +899,7 @@ void tst_QVectorND::compare3()
QVector3D v4(1, 3, 4);
QVector3D v5(1, 2, 3);
- QVERIFY(v1 == v2);
+ QCOMPARE(v1, v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
QVERIFY(v1 != v5);
@@ -915,7 +915,7 @@ void tst_QVectorND::compare4()
QVector4D v5(1, 2, 3, 8);
QVector4D v6(1, 2, 4, 3);
- QVERIFY(v1 == v2);
+ QCOMPARE(v1, v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
QVERIFY(v1 != v5);
@@ -969,7 +969,7 @@ void tst_QVectorND::add2()
QVector2D v4(v1);
v4 += v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() + v2.x());
QCOMPARE(v4.y(), v1.y() + v2.y());
@@ -1033,7 +1033,7 @@ void tst_QVectorND::add3()
QVector3D v4(v1);
v4 += v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() + v2.x());
QCOMPARE(v4.y(), v1.y() + v2.y());
@@ -1109,7 +1109,7 @@ void tst_QVectorND::add4()
QVector4D v4(v1);
v4 += v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() + v2.x());
QCOMPARE(v4.y(), v1.y() + v2.y());
@@ -1141,14 +1141,14 @@ void tst_QVectorND::subtract2()
QVector2D v4(v3);
v4 -= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() - v1.x());
QCOMPARE(v4.y(), v3.y() - v1.y());
QVector2D v5(v3);
v5 -= v2;
- QVERIFY(v5 == v1);
+ QCOMPARE(v5, v1);
QCOMPARE(v5.x(), v3.x() - v2.x());
QCOMPARE(v5.y(), v3.y() - v2.y());
@@ -1181,7 +1181,7 @@ void tst_QVectorND::subtract3()
QVector3D v4(v3);
v4 -= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() - v1.x());
QCOMPARE(v4.y(), v3.y() - v1.y());
@@ -1189,7 +1189,7 @@ void tst_QVectorND::subtract3()
QVector3D v5(v3);
v5 -= v2;
- QVERIFY(v5 == v1);
+ QCOMPARE(v5, v1);
QCOMPARE(v5.x(), v3.x() - v2.x());
QCOMPARE(v5.y(), v3.y() - v2.y());
@@ -1226,7 +1226,7 @@ void tst_QVectorND::subtract4()
QVector4D v4(v3);
v4 -= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() - v1.x());
QCOMPARE(v4.y(), v3.y() - v1.y());
@@ -1235,7 +1235,7 @@ void tst_QVectorND::subtract4()
QVector4D v5(v3);
v5 -= v2;
- QVERIFY(v5 == v1);
+ QCOMPARE(v5, v1);
QCOMPARE(v5.x(), v3.x() - v2.x());
QCOMPARE(v5.y(), v3.y() - v2.y());
@@ -1290,7 +1290,7 @@ void tst_QVectorND::multiply2()
QVector2D v4(v1);
v4 *= v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() * v2.x());
QCOMPARE(v4.y(), v1.y() * v2.y());
@@ -1354,7 +1354,7 @@ void tst_QVectorND::multiply3()
QVector3D v4(v1);
v4 *= v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() * v2.x());
QCOMPARE(v4.y(), v1.y() * v2.y());
@@ -1430,7 +1430,7 @@ void tst_QVectorND::multiply4()
QVector4D v4(v1);
v4 *= v2;
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
QCOMPARE(v4.x(), v1.x() * v2.x());
QCOMPARE(v4.y(), v1.y() * v2.y());
@@ -1488,7 +1488,7 @@ void tst_QVectorND::multiplyFactor2()
QVector2D v3(v1);
v3 *= factor;
- QVERIFY(v3 == v2);
+ QCOMPARE(v3, v2);
QCOMPARE(v3.x(), v1.x() * factor);
QCOMPARE(v3.y(), v1.y() * factor);
@@ -1553,7 +1553,7 @@ void tst_QVectorND::multiplyFactor3()
QVector3D v3(v1);
v3 *= factor;
- QVERIFY(v3 == v2);
+ QCOMPARE(v3, v2);
QCOMPARE(v3.x(), v1.x() * factor);
QCOMPARE(v3.y(), v1.y() * factor);
@@ -1628,7 +1628,7 @@ void tst_QVectorND::multiplyFactor4()
QVector4D v3(v1);
v3 *= factor;
- QVERIFY(v3 == v2);
+ QCOMPARE(v3, v2);
QCOMPARE(v3.x(), v1.x() * factor);
QCOMPARE(v3.y(), v1.y() * factor);
@@ -1660,7 +1660,7 @@ void tst_QVectorND::divide2()
QVector2D v4(v3);
v4 /= v2;
- QVERIFY(v4 == v1);
+ QCOMPARE(v4, v1);
QCOMPARE(v4.x(), v3.x() / v2.x());
QCOMPARE(v4.y(), v3.y() / v2.y());
@@ -1670,7 +1670,7 @@ void tst_QVectorND::divide2()
QVector2D v4(v3);
v4 /= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() / v1.x());
QCOMPARE(v4.y(), v3.y() / v1.y());
@@ -1704,7 +1704,7 @@ void tst_QVectorND::divide3()
QVector3D v4(v3);
v4 /= v2;
- QVERIFY(v4 == v1);
+ QCOMPARE(v4, v1);
QCOMPARE(v4.x(), v3.x() / v2.x());
QCOMPARE(v4.y(), v3.y() / v2.y());
@@ -1715,7 +1715,7 @@ void tst_QVectorND::divide3()
QVector3D v4(v3);
v4 /= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() / v1.x());
QCOMPARE(v4.y(), v3.y() / v1.y());
@@ -1753,7 +1753,7 @@ void tst_QVectorND::divide4()
QVector4D v4(v3);
v4 /= v2;
- QVERIFY(v4 == v1);
+ QCOMPARE(v4, v1);
QCOMPARE(v4.x(), v3.x() / v2.x());
QCOMPARE(v4.y(), v3.y() / v2.y());
@@ -1765,7 +1765,7 @@ void tst_QVectorND::divide4()
QVector4D v4(v3);
v4 /= v1;
- QVERIFY(v4 == v2);
+ QCOMPARE(v4, v2);
QCOMPARE(v4.x(), v3.x() / v1.x());
QCOMPARE(v4.y(), v3.y() / v1.y());
@@ -1798,7 +1798,7 @@ void tst_QVectorND::divideFactor2()
QVector2D v3(v2);
v3 /= factor;
- QVERIFY(v3 == v1);
+ QCOMPARE(v3, v1);
QCOMPARE(v3.x(), v2.x() / factor);
QCOMPARE(v3.y(), v2.y() / factor);
@@ -1830,7 +1830,7 @@ void tst_QVectorND::divideFactor3()
QVector3D v3(v2);
v3 /= factor;
- QVERIFY(v3 == v1);
+ QCOMPARE(v3, v1);
QCOMPARE(v3.x(), v2.x() / factor);
QCOMPARE(v3.y(), v2.y() / factor);
@@ -1865,7 +1865,7 @@ void tst_QVectorND::divideFactor4()
QVector4D v3(v2);
v3 /= factor;
- QVERIFY(v3 == v1);
+ QCOMPARE(v3, v1);
QCOMPARE(v3.x(), v2.x() / factor);
QCOMPARE(v3.y(), v2.y() / factor);
@@ -1887,7 +1887,7 @@ void tst_QVectorND::negate2()
QVector2D v1(x1, y1);
QVector2D v2(-x1, -y1);
- QVERIFY(-v1 == v2);
+ QCOMPARE(-v1, v2);
}
// Test vector negation for 3D vectors.
@@ -1905,7 +1905,7 @@ void tst_QVectorND::negate3()
QVector3D v1(x1, y1, z1);
QVector3D v2(-x1, -y1, -z1);
- QVERIFY(-v1 == v2);
+ QCOMPARE(-v1, v2);
}
// Test vector negation for 4D vectors.
@@ -1924,7 +1924,7 @@ void tst_QVectorND::negate4()
QVector4D v1(x1, y1, z1, w1);
QVector4D v2(-x1, -y1, -z1, -w1);
- QVERIFY(-v1 == v2);
+ QCOMPARE(-v1, v2);
}
// Test the computation of vector cross-products.
@@ -1976,7 +1976,7 @@ void tst_QVectorND::crossProduct()
QVector3D v3(x3, y3, z3);
QVector3D v4 = QVector3D::crossProduct(v1, v2);
- QVERIFY(v4 == v3);
+ QCOMPARE(v4, v3);
// Compute the cross-product long-hand and check again.
float xres = y1 * z2 - z1 * y2;
@@ -2667,9 +2667,9 @@ void tst_QVectorND::properties()
void tst_QVectorND::metaTypes()
{
- QVERIFY(QMetaType::type("QVector2D") == QMetaType::QVector2D);
- QVERIFY(QMetaType::type("QVector3D") == QMetaType::QVector3D);
- QVERIFY(QMetaType::type("QVector4D") == QMetaType::QVector4D);
+ QCOMPARE(QMetaType::type("QVector2D"), int(QMetaType::QVector2D));
+ QCOMPARE(QMetaType::type("QVector3D"), int(QMetaType::QVector3D));
+ QCOMPARE(QMetaType::type("QVector4D"), int(QMetaType::QVector4D));
QCOMPARE(QByteArray(QMetaType::typeName(QMetaType::QVector2D)),
QByteArray("QVector2D"));
@@ -2682,9 +2682,9 @@ void tst_QVectorND::metaTypes()
QVERIFY(QMetaType::isRegistered(QMetaType::QVector3D));
QVERIFY(QMetaType::isRegistered(QMetaType::QVector4D));
- QVERIFY(qMetaTypeId<QVector2D>() == QMetaType::QVector2D);
- QVERIFY(qMetaTypeId<QVector3D>() == QMetaType::QVector3D);
- QVERIFY(qMetaTypeId<QVector4D>() == QMetaType::QVector4D);
+ QCOMPARE(qMetaTypeId<QVector2D>(), int(QMetaType::QVector2D));
+ QCOMPARE(qMetaTypeId<QVector3D>(), int(QMetaType::QVector3D));
+ QCOMPARE(qMetaTypeId<QVector4D>(), int(QMetaType::QVector4D));
}
QTEST_APPLESS_MAIN(tst_QVectorND)
diff --git a/tests/auto/gui/painting/qbrush/tst_qbrush.cpp b/tests/auto/gui/painting/qbrush/tst_qbrush.cpp
index 4f58178f2c..30982f1e24 100644
--- a/tests/auto/gui/painting/qbrush/tst_qbrush.cpp
+++ b/tests/auto/gui/painting/qbrush/tst_qbrush.cpp
@@ -461,8 +461,8 @@ void tst_QBrush::textureBrushComparison()
imageBrush1.setTextureImage(image1);
imageBrush2.setTextureImage(image2);
- QVERIFY(imageBrush1 == imageBrush2);
- QVERIFY(pixmapBrush == imageBrush1);
+ QCOMPARE(imageBrush1, imageBrush2);
+ QCOMPARE(pixmapBrush, imageBrush1);
}
QTEST_MAIN(tst_QBrush)
diff --git a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
index 4fafbf9827..b81a4e2c4c 100644
--- a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
+++ b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
@@ -39,6 +39,7 @@
#include <qcolor.h>
#include <qdebug.h>
#include <private/qdrawingprimitive_sse2_p.h>
+#include <qrgba64.h>
class tst_QColor : public QObject
{
@@ -105,6 +106,10 @@ private slots:
void premultiply();
void unpremultiply_sse4();
+ void qrgba64();
+ void qrgba64MemoryLayout();
+ void qrgba64Premultiply();
+ void qrgba64Equivalence();
#ifdef Q_DEAD_CODE_FROM_QT4_X11
void setallowX11ColorNames();
@@ -249,7 +254,7 @@ void tst_QColor::isValid()
{
QFETCH(QColor, color);
QFETCH(bool, isValid);
- QVERIFY(color.isValid() == isValid);
+ QCOMPARE(color.isValid(), isValid);
}
Q_DECLARE_METATYPE(QColor::NameFormat);
@@ -1321,19 +1326,19 @@ void tst_QColor::convertTo()
QColor color(Qt::black);
QColor rgb = color.convertTo(QColor::Rgb);
- QVERIFY(rgb.spec() == QColor::Rgb);
+ QCOMPARE(rgb.spec(), QColor::Rgb);
QColor hsv = color.convertTo(QColor::Hsv);
- QVERIFY(hsv.spec() == QColor::Hsv);
+ QCOMPARE(hsv.spec(), QColor::Hsv);
QColor cmyk = color.convertTo(QColor::Cmyk);
- QVERIFY(cmyk.spec() == QColor::Cmyk);
+ QCOMPARE(cmyk.spec(), QColor::Cmyk);
QColor hsl = color.convertTo(QColor::Hsl);
- QVERIFY(hsl.spec() == QColor::Hsl);
+ QCOMPARE(hsl.spec(), QColor::Hsl);
QColor invalid = color.convertTo(QColor::Invalid);
- QVERIFY(invalid.spec() == QColor::Invalid);
+ QCOMPARE(invalid.spec(), QColor::Invalid);
}
void tst_QColor::light()
@@ -1464,5 +1469,102 @@ void tst_QColor::unpremultiply_sse4()
QSKIP("SSE4 not supported on this CPU.");
}
+void tst_QColor::qrgba64()
+{
+ QRgba64 rgb64 = QRgba64::fromRgba(0x22, 0x33, 0x44, 0xff);
+ QCOMPARE(rgb64.red(), quint16(0x2222));
+ QCOMPARE(rgb64.green(), quint16(0x3333));
+ QCOMPARE(rgb64.blue(), quint16(0x4444));
+ QCOMPARE(rgb64.alpha(), quint16(0xffff));
+
+ QColor c(rgb64);
+ QCOMPARE(c.red(), 0x22);
+ QCOMPARE(c.green(), 0x33);
+ QCOMPARE(c.blue(), 0x44);
+
+ QCOMPARE(c.rgba64(), rgb64);
+
+ QColor c2 = QColor::fromRgb(0x22, 0x33, 0x44, 0xff);
+ QCOMPARE(c, c2);
+ QCOMPARE(c2.rgba64(), rgb64);
+
+ rgb64.setAlpha(0x8000);
+ rgb64.setGreen(0x8844);
+ rgb64 = rgb64.premultiplied();
+ QCOMPARE(rgb64.red(), quint16(0x1111));
+ QCOMPARE(rgb64.blue(), quint16(0x2222));
+ QCOMPARE(rgb64.green(), quint16(0x4422));
+}
+
+void tst_QColor::qrgba64MemoryLayout()
+{
+ QRgba64 rgb64 = QRgba64::fromRgba64(0x0123, 0x4567, 0x89ab, 0xcdef);
+ QCOMPARE(rgb64.red(), quint16(0x0123));
+ QCOMPARE(rgb64.green(), quint16(0x4567));
+ QCOMPARE(rgb64.blue(), quint16(0x89ab));
+ QCOMPARE(rgb64.alpha(), quint16(0xcdef));
+
+ // Check in-memory order, so it can be used by things like SSE
+ Q_STATIC_ASSERT(sizeof(QRgba64) == sizeof(quint64));
+ quint16 memory[4];
+ memcpy(memory, &rgb64, sizeof(QRgba64));
+ QCOMPARE(memory[0], quint16(0x0123));
+ QCOMPARE(memory[1], quint16(0x4567));
+ QCOMPARE(memory[2], quint16(0x89ab));
+ QCOMPARE(memory[3], quint16(0xcdef));
+}
+
+void tst_QColor::qrgba64Premultiply()
+{
+ // Tests that qPremultiply(qUnpremultiply(rgba64)) returns rgba64.
+ for (uint a = 0; a < 0x10000; a+=7) {
+ const uint step = std::max(a/1024, 1u);
+ for (uint c = 0; c <= a; c+=step) {
+ QRgba64 p = qRgba64(c, a-c, a-c/2, a);
+ QRgba64 pp = qPremultiply(qUnpremultiply(p));
+ QCOMPARE(pp, p);
+ }
+ }
+}
+
+void tst_QColor::qrgba64Equivalence()
+{
+ // Any ARGB32 converted back and forth.
+ for (uint a = 0; a < 256; a++) {
+ for (uint c = 0; c < 256; c++) {
+ QRgb p1 = qRgba(c, 255-c, 255-c, a);
+ QRgba64 p64 = QRgba64::fromArgb32(p1);
+ QCOMPARE(p64.toArgb32(), p1);
+ }
+ }
+ // Any unpremultiplied ARGB32 value premultipled in RGB64 (except alpha 0).
+ for (uint a = 1; a < 256; a++) {
+ for (uint c = 0; c < 256; c++) {
+ QRgb p1 = qRgba(c, 255-c, 255-c, a);
+ QRgb pp1 = qPremultiply(p1);
+ QRgba64 pp64 = qPremultiply(QRgba64::fromArgb32(p1));
+ QRgb pp2 = pp64.toArgb32();
+ // 64bit premultiplied is more accurate than 32bit, so allow slight difference.
+ QCOMPARE(qAlpha(pp2), qAlpha(pp1));
+ QVERIFY(qAbs(qRed(pp2)-qRed(pp1)) <= 1);
+ QVERIFY(qAbs(qGreen(pp2)-qGreen(pp1)) <= 1);
+ QVERIFY(qAbs(qBlue(pp2)-qBlue(pp1)) <= 1);
+ // But verify the added accuracy means we can return to accurate unpremultiplied ARGB32.
+ QRgba64 pu64 = qUnpremultiply(pp64);
+ QRgb p2 = pu64.toArgb32();
+ QCOMPARE(p2, p1);
+ }
+ }
+ // Any premultiplied ARGB32 value unpremultipled in RGB64.
+ for (uint a = 0; a < 256; a++) {
+ for (uint c = 0; c <= a; c++) {
+ QRgb pp = qRgba(c, a-c, a-c, a);
+ QRgb pu = qUnpremultiply(pp);
+ QRgba64 pu64 = qUnpremultiply(QRgba64::fromArgb32(pp));
+ QCOMPARE(pu64.toArgb32(), pu);
+ }
+ }
+}
+
QTEST_MAIN(tst_QColor)
#include "tst_qcolor.moc"
diff --git a/tests/auto/gui/painting/qpagelayout/tst_qpagelayout.cpp b/tests/auto/gui/painting/qpagelayout/tst_qpagelayout.cpp
index 964487f566..0f2f51d9b6 100644
--- a/tests/auto/gui/painting/qpagelayout/tst_qpagelayout.cpp
+++ b/tests/auto/gui/painting/qpagelayout/tst_qpagelayout.cpp
@@ -76,7 +76,7 @@ void tst_QPageLayout::basics()
QCOMPARE(simple.paintRectPixels(72), QRect(0, 0, 595, 842));
const QPageLayout a4portrait = simple;
- QVERIFY(a4portrait == simple);
+ QCOMPARE(a4portrait, simple);
// Change orientation
simple.setOrientation(QPageLayout::Landscape);
diff --git a/tests/auto/gui/painting/qpainter/qpainter.pro b/tests/auto/gui/painting/qpainter/qpainter.pro
index 7e9d438e1b..e90b516ef2 100644
--- a/tests/auto/gui/painting/qpainter/qpainter.pro
+++ b/tests/auto/gui/painting/qpainter/qpainter.pro
@@ -2,7 +2,7 @@ CONFIG += testcase
CONFIG += parallel_test
TARGET = tst_qpainter
-QT += testlib
+QT += testlib gui-private core-private
qtHaveModule(widgets): QT += widgets widgets-private
SOURCES += tst_qpainter.cpp
diff --git a/tests/auto/gui/painting/qpainter/tst_qpainter.cpp b/tests/auto/gui/painting/qpainter/tst_qpainter.cpp
index 6582755aec..e8d90edd2d 100644
--- a/tests/auto/gui/painting/qpainter/tst_qpainter.cpp
+++ b/tests/auto/gui/painting/qpainter/tst_qpainter.cpp
@@ -53,6 +53,7 @@
#endif
#include <qpixmap.h>
+#include <private/qdrawhelper_p.h>
#include <qpainter.h>
#ifndef QT_NO_WIDGETS
@@ -125,8 +126,12 @@ private slots:
void fillRect3();
void fillRect4_data() { fillRect2_data(); }
void fillRect4();
+ void fillRectNonPremul_data();
void fillRectNonPremul();
+ void fillRectRGB30_data();
+ void fillRectRGB30();
+
void drawEllipse_data();
void drawEllipse();
void drawClippedEllipse_data();
@@ -198,6 +203,11 @@ private slots:
void gradientPixelFormat_data();
void gradientPixelFormat();
+ void linearGradientRgb30_data();
+ void linearGradientRgb30();
+ void radialGradientRgb30_data();
+ void radialGradientRgb30();
+
void fpe_pixmapTransform();
void fpe_zeroLengthLines();
void fpe_divByZero();
@@ -789,7 +799,7 @@ void tst_QPainter::drawPixmapFragments()
QImage origImage = origPixmap.toImage().convertToFormat(QImage::Format_ARGB32);
QImage resImage = resPixmap.toImage().convertToFormat(QImage::Format_ARGB32);
- QVERIFY(resImage.size() == resPixmap.size());
+ QCOMPARE(resImage.size(), resPixmap.size());
QVERIFY(resImage.pixel(5, 5) == origImage.pixel(15, 15));
QVERIFY(resImage.pixel(5, 15) == origImage.pixel(15, 5));
QVERIFY(resImage.pixel(15, 5) == origImage.pixel(5, 15));
@@ -797,16 +807,16 @@ void tst_QPainter::drawPixmapFragments()
QPainter::PixmapFragment fragment = QPainter::PixmapFragment::create(QPointF(20, 20), QRectF(30, 30, 2, 2));
- QVERIFY(fragment.x == 20);
- QVERIFY(fragment.y == 20);
- QVERIFY(fragment.sourceLeft == 30);
- QVERIFY(fragment.sourceTop == 30);
- QVERIFY(fragment.width == 2);
- QVERIFY(fragment.height == 2);
- QVERIFY(fragment.scaleX == 1);
- QVERIFY(fragment.scaleY == 1);
- QVERIFY(fragment.rotation == 0);
- QVERIFY(fragment.opacity == 1);
+ QCOMPARE(fragment.x, qreal(20));
+ QCOMPARE(fragment.y, qreal(20));
+ QCOMPARE(fragment.sourceLeft, qreal(30));
+ QCOMPARE(fragment.sourceTop, qreal(30));
+ QCOMPARE(fragment.width, qreal(2));
+ QCOMPARE(fragment.height, qreal(2));
+ QCOMPARE(fragment.scaleX, qreal(1));
+ QCOMPARE(fragment.scaleY, qreal(1));
+ QCOMPARE(fragment.rotation, qreal(0));
+ QCOMPARE(fragment.opacity, qreal(1));
}
void tst_QPainter::drawPixmapNegativeScale()
@@ -1245,22 +1255,87 @@ void tst_QPainter::fillRect4()
QCOMPARE(image, expected);
}
+void tst_QPainter::fillRectNonPremul_data()
+{
+ QTest::addColumn<QImage::Format>("format");
+ QTest::addColumn<uint>("color");
+
+ QTest::newRow("argb32 7f1f3f7f") << QImage::Format_ARGB32 << qRgba(31, 63, 127, 127);
+ QTest::newRow("rgba8888 7f1f3f7f") << QImage::Format_RGBA8888 << qRgba(31, 63, 127, 127);
+
+ QTest::newRow("argb32 3f1f3f7f") << QImage::Format_ARGB32 << qRgba(31, 63, 127, 63);
+ QTest::newRow("rgba8888 3f1f3f7f") << QImage::Format_RGBA8888 << qRgba(31, 63, 127, 63);
+
+ QTest::newRow("argb32 070375f4") << QImage::Format_ARGB32 << qRgba(3, 117, 244, 7);
+ QTest::newRow("rgba8888 070375f4") << QImage::Format_RGBA8888 << qRgba(3, 117, 244, 7);
+
+ QTest::newRow("argb32 0301fe0c") << QImage::Format_ARGB32 << qRgba(1, 254, 12, 3);
+ QTest::newRow("rgba8888 0301fe0c") << QImage::Format_RGBA8888 << qRgba(1, 254, 12, 3);
+
+ QTest::newRow("argb32 01804010") << QImage::Format_ARGB32 << qRgba(128, 64, 32, 1);
+ QTest::newRow("rgba8888 01804010") << QImage::Format_RGBA8888 << qRgba(128, 64, 32, 1);
+}
+
void tst_QPainter::fillRectNonPremul()
{
- QImage img1(1, 1, QImage::Format_ARGB32);
- QImage img2(1, 1, QImage::Format_RGBA8888);
+ QFETCH(QImage::Format, format);
+ QFETCH(uint, color);
+
+ QImage image(1, 1, format);
+ QRectF rect(0, 0, 1, 1);
+
+ // Fill with CompositionMode_SourceOver tests blend_color
+ image.fill(Qt::transparent);
+ QPainter painter(&image);
+ painter.fillRect(rect, QColor::fromRgba(color));
+ painter.end();
+
+ // Fill with CompositionMode_Source tests rectfill.
+ painter.begin(&image);
+ painter.setCompositionMode(QPainter::CompositionMode_Source);
+ painter.fillRect(rect, QColor::fromRgba(color));
+ painter.end();
+
+ QRgb p = image.pixel(0, 0);
+ QCOMPARE(qAlpha(p), qAlpha(color));
+ QVERIFY(qAbs(qRed(p)-qRed(color)) <= 1);
+ QVERIFY(qAbs(qGreen(p)-qGreen(color)) <= 1);
+ QVERIFY(qAbs(qBlue(p)-qBlue(color)) <= 1);
+}
+
+void tst_QPainter::fillRectRGB30_data()
+{
+ QTest::addColumn<uint>("color");
- QPainter p1(&img1);
- QPainter p2(&img2);
+ QTest::newRow("17|43|259") << (0xc0000000 | (17 << 20) | (43 << 10) | 259);
+ QTest::newRow("2|33|444") << (0xc0000000 | (2 << 20) | (33 << 10) | 444);
+ QTest::newRow("1000|1000|1000") << (0xc0000000 | (1000 << 20) | (1000 << 10) | 1000);
+}
+void tst_QPainter::fillRectRGB30()
+{
+ QFETCH(uint, color);
QRectF rect(0, 0, 1, 1);
- p1.fillRect(rect, qRgba(31, 63, 127, 127));
- p2.fillRect(rect, qRgba(31, 63, 127, 127));
- p1.end();
- p2.end();
+ // Fill with CompositionMode_SourceOver tests blend_color
+ QImage image1(1, 1, QImage::Format_A2BGR30_Premultiplied);
+ image1.fill(Qt::transparent);
+ QPainter painter(&image1);
+ painter.fillRect(rect, QColor::fromRgba64(qConvertA2rgb30ToRgb64<PixelOrderBGR>(color)));
+ painter.end();
+
+ uint pixel1 = ((const uint*)(image1.bits()))[0];
+ QCOMPARE(pixel1, color);
+
+ // Fill with CompositionMode_Source tests rectfill.
+ QImage image2(1, 1, QImage::Format_RGB30);
+ painter.begin(&image2);
+ painter.setCompositionMode(QPainter::CompositionMode_Source);
+ painter.fillRect(rect, QColor::fromRgba64(qConvertA2rgb30ToRgb64<PixelOrderRGB>(color)));
+ painter.end();
- QCOMPARE(img1.pixel(0, 0), img2.pixel(0,0));
+ uint pixel2 = ((const uint*)(image2.bits()))[0];
+ QCOMPARE(pixel2, color);
}
void tst_QPainter::drawPath_data()
@@ -1406,7 +1481,7 @@ void tst_QPainter::drawPath3()
p.drawPath(path);
p.end();
- QVERIFY(imgA == imgB);
+ QCOMPARE(imgA, imgB);
imgA.invertPixels();
imgB.fill(0xffffff);
@@ -1420,7 +1495,7 @@ void tst_QPainter::drawPath3()
p.drawPath(path);
p.end();
- QVERIFY(imgA == imgB);
+ QCOMPARE(imgA, imgB);
path.setFillRule(Qt::WindingFill);
imgB.fill(0xffffff);
@@ -2381,36 +2456,50 @@ void tst_QPainter::setOpacity_data()
QTest::newRow("RGBx8888 on RGBx8888") << QImage::Format_RGBX8888
<< QImage::Format_RGBX8888;
- QTest::newRow("RGBA8888P on ARGB32P") << QImage::Format_RGBA8888_Premultiplied
+ QTest::newRow("RGBA8888P on ARGB32P") << QImage::Format_ARGB32_Premultiplied
+ << QImage::Format_RGBA8888_Premultiplied;
+
+ QTest::newRow("RGBx8888 on ARGB32P") << QImage::Format_ARGB32_Premultiplied
+ << QImage::Format_RGBX8888;
+
+ QTest::newRow("ARGB32P on RGBA8888P") << QImage::Format_RGBA8888_Premultiplied
<< QImage::Format_ARGB32_Premultiplied;
- QTest::newRow("RGBx8888 on ARGB32P") << QImage::Format_RGBX8888
- << QImage::Format_ARGB32_Premultiplied;
+ QTest::newRow("RGB32 on RGBx8888") << QImage::Format_RGBX8888
+ << QImage::Format_RGB32;
- QTest::newRow("ARGB32P on RGBA8888P") << QImage::Format_ARGB32_Premultiplied
- << QImage::Format_RGBA8888_Premultiplied;
+ QTest::newRow("RGB30 on RGB32") << QImage::Format_RGB32
+ << QImage::Format_BGR30;
- QTest::newRow("RGB32 on RGBx8888") << QImage::Format_RGB32
- << QImage::Format_RGBX8888;
+ QTest::newRow("BGR30 on ARGB32P") << QImage::Format_ARGB32_Premultiplied
+ << QImage::Format_BGR30;
+
+ QTest::newRow("A2RGB30P on ARGB32P") << QImage::Format_ARGB32_Premultiplied
+ << QImage::Format_A2BGR30_Premultiplied;
QTest::newRow("A2RGB30P on A2RGB30P") << QImage::Format_A2RGB30_Premultiplied
<< QImage::Format_A2RGB30_Premultiplied;
- QTest::newRow("ARGB32P on A2RGB30P") << QImage::Format_ARGB32_Premultiplied
- << QImage::Format_A2RGB30_Premultiplied;
+ QTest::newRow("ARGB32P on A2RGB30P") << QImage::Format_A2RGB30_Premultiplied
+ << QImage::Format_ARGB32_Premultiplied;
+ QTest::newRow("RGB32 on A2BGR30P") << QImage::Format_A2BGR30_Premultiplied
+ << QImage::Format_RGB32;
- QTest::newRow("RGB32 on A2BGR30P") << QImage::Format_ARGB32_Premultiplied
- << QImage::Format_A2BGR30_Premultiplied;
+ QTest::newRow("RGB30 on A2BGR30P") << QImage::Format_A2BGR30_Premultiplied
+ << QImage::Format_RGB30;
- QTest::newRow("A2RGB30P on A2BGR30P") << QImage::Format_A2RGB30_Premultiplied
- << QImage::Format_A2BGR30_Premultiplied;
+ QTest::newRow("A2RGB30P on A2BGR30P") << QImage::Format_A2BGR30_Premultiplied
+ << QImage::Format_A2RGB30_Premultiplied;
- QTest::newRow("ARGB32P on BGR30") << QImage::Format_ARGB32_Premultiplied
- << QImage::Format_BGR30;
+ QTest::newRow("ARGB32P on BGR30") << QImage::Format_BGR30
+ << QImage::Format_ARGB32_Premultiplied;
- QTest::newRow("ARGB32P on RGB30") << QImage::Format_A2RGB30_Premultiplied
- << QImage::Format_RGB30;
+ QTest::newRow("ARGB32P on RGB30") << QImage::Format_RGB30
+ << QImage::Format_ARGB32_Premultiplied;
+
+ QTest::newRow("A2RGB30P on RGB30") << QImage::Format_RGB30
+ << QImage::Format_A2RGB30_Premultiplied;
}
@@ -2492,7 +2581,7 @@ void tst_QPainter::drawhelper_blend_untransformed()
QImage expected(size - 2, size, destFormat);
p.begin(&expected);
p.fillRect(0, 0, expected.width(), expected.height(),
- QColor(dest.pixel(1, 0)));
+ dest.pixelColor(1, 0));
p.end();
const QImage subDest(dest.bits() + dest.depth() / 8,
@@ -2500,9 +2589,7 @@ void tst_QPainter::drawhelper_blend_untransformed()
dest.bytesPerLine(), dest.format());
if (dest.format() == QImage::Format_ARGB8565_Premultiplied ||
- dest.format() == QImage::Format_ARGB8555_Premultiplied ||
- dest.format() == QImage::Format_A2BGR30_Premultiplied ||
- dest.format() == QImage::Format_A2RGB30_Premultiplied ) {
+ dest.format() == QImage::Format_ARGB8555_Premultiplied) {
// Test skipped due to rounding errors...
continue;
}
@@ -2551,7 +2638,7 @@ void tst_QPainter::drawhelper_blend_tiled_untransformed()
QImage expected(size - 2, size, destFormat);
p.begin(&expected);
p.fillRect(0, 0, expected.width(), expected.height(),
- QColor(dest.pixel(1, 0)));
+ dest.pixelColor(1, 0));
p.end();
const QImage subDest(dest.bits() + dest.depth() / 8,
@@ -2619,28 +2706,6 @@ void tst_QPainter::porterDuff_warning()
QVERIFY(qInstallMessageHandler(old) == porterDuff_warningChecker);
}
-class quint24
-{
-public:
- inline quint24(quint32 v)
- {
- data[0] = qBlue(v);
- data[1] = qGreen(v);
- data[2] = qRed(v);
- }
-
- inline operator quint32 ()
- {
- return qRgb(data[2], data[1], data[0]);
- }
-
- inline bool operator==(const quint24 &v) const {
- return (data[0] == v.data[0] && data[1] == v.data[1] && data[2] == v.data[2]);
- }
-
- uchar data[3];
-};
-
void tst_QPainter::drawhelper_blend_color()
{
QImage dest(32, 32, QImage::Format_ARGB8555_Premultiplied);
@@ -3889,6 +3954,65 @@ void tst_QPainter::gradientInterpolation()
}
}
+void tst_QPainter::linearGradientRgb30_data()
+{
+ QTest::addColumn<QColor>("stop0");
+ QTest::addColumn<QColor>("stop1");
+
+ QTest::newRow("white->black") << QColor(Qt::white) << QColor(Qt::black);
+ QTest::newRow("blue->black") << QColor(Qt::blue) << QColor(Qt::black);
+ QTest::newRow("white->red") << QColor(Qt::white) << QColor(Qt::red);
+}
+
+void tst_QPainter::linearGradientRgb30()
+{
+ QFETCH(QColor, stop0);
+ QFETCH(QColor, stop1);
+
+ QLinearGradient gradient(0, 0, 1000, 1);
+ gradient.setColorAt(0.0, stop0);
+ gradient.setColorAt(1.0, stop1);
+
+ QImage image(1000, 1, QImage::Format_RGB30);
+ QPainter painter(&image);
+ painter.fillRect(image.rect(), gradient);
+ painter.end();
+
+ for (int i = 1; i < 1000; ++i) {
+ QColor p1 = image.pixelColor(i - 1, 0);
+ QColor p2 = image.pixelColor(i, 0);
+ QVERIFY(p1 != p2);
+ QVERIFY(qGray(p1.rgb()) >= qGray(p2.rgb()));
+ }
+}
+
+void tst_QPainter::radialGradientRgb30_data()
+{
+ linearGradientRgb30_data();
+}
+
+void tst_QPainter::radialGradientRgb30()
+{
+ QFETCH(QColor, stop0);
+ QFETCH(QColor, stop1);
+
+ QRadialGradient gradient(0, 0, 1000);
+ gradient.setColorAt(0.0, stop0);
+ gradient.setColorAt(1.0, stop1);
+
+ QImage image(1000, 1, QImage::Format_A2BGR30_Premultiplied);
+ QPainter painter(&image);
+ painter.fillRect(image.rect(), gradient);
+ painter.end();
+
+ for (int i = 1; i < 1000; ++i) {
+ QColor p1 = image.pixelColor(i - 1, 0);
+ QColor p2 = image.pixelColor(i, 0);
+ QVERIFY(p1 != p2);
+ QVERIFY(qGray(p1.rgb()) >= qGray(p2.rgb()));
+ }
+}
+
void tst_QPainter::drawPolygon()
{
QImage img(128, 128, QImage::Format_ARGB32_Premultiplied);
@@ -4064,10 +4188,10 @@ void tst_QPainter::extendedBlendModes()
QVERIFY(testCompositionMode(255, 255, 255, QPainter::CompositionMode_Plus, 0.3));
QVERIFY(testCompositionMode( 0, 0, 0, QPainter::CompositionMode_Plus, 0.3));
- QVERIFY(testCompositionMode(127, 128, 165, QPainter::CompositionMode_Plus, 0.3));
- QVERIFY(testCompositionMode(127, 0, 37, QPainter::CompositionMode_Plus, 0.3));
+ QVERIFY(testCompositionMode(126, 128, 165, QPainter::CompositionMode_Plus, 0.3));
+ QVERIFY(testCompositionMode(127, 0, 38, QPainter::CompositionMode_Plus, 0.3));
QVERIFY(testCompositionMode( 0, 127, 127, QPainter::CompositionMode_Plus, 0.3));
- QVERIFY(testCompositionMode(255, 0, 75, QPainter::CompositionMode_Plus, 0.3));
+ QVERIFY(testCompositionMode(255, 0, 76, QPainter::CompositionMode_Plus, 0.3));
QVERIFY(testCompositionMode( 0, 255, 255, QPainter::CompositionMode_Plus, 0.3));
QVERIFY(testCompositionMode(128, 128, 166, QPainter::CompositionMode_Plus, 0.3));
QVERIFY(testCompositionMode(186, 200, 255, QPainter::CompositionMode_Plus, 0.3));
@@ -4752,6 +4876,22 @@ void tst_QPainter::blendARGBonRGB_data()
<< QPainter::CompositionMode_SourceIn << qRgba(255, 0, 0, 127) << 125;
QTest::newRow("ARGB_PM source-in RGB666") << QImage::Format_RGB666 << QImage::Format_ARGB32_Premultiplied
<< QPainter::CompositionMode_SourceIn << qRgba(127, 0, 0, 127) << 125;
+ QTest::newRow("ARGB over RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32
+ << QPainter::CompositionMode_SourceOver << qRgba(255, 0, 0, 85) << 85;
+ QTest::newRow("ARGB_PM over RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32_Premultiplied
+ << QPainter::CompositionMode_SourceOver << qRgba(85, 0, 0, 85) << 85;
+ QTest::newRow("ARGB source RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32
+ << QPainter::CompositionMode_Source << qRgba(255, 0, 0, 85) << 85;
+ QTest::newRow("ARGB source RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32
+ << QPainter::CompositionMode_Source << qRgba(255, 0, 0, 120) << 85;
+ QTest::newRow("ARGB_PM source RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32_Premultiplied
+ << QPainter::CompositionMode_Source << qRgba(85, 0, 0, 85) << 85;
+ QTest::newRow("ARGB_PM source RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32_Premultiplied
+ << QPainter::CompositionMode_Source << qRgba(180, 0, 0, 180) << 170;
+ QTest::newRow("ARGB source-in RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32
+ << QPainter::CompositionMode_SourceIn << qRgba(255, 0, 0, 85) << 85;
+ QTest::newRow("ARGB_PM source-in RGB30") << QImage::Format_RGB30 << QImage::Format_ARGB32_Premultiplied
+ << QPainter::CompositionMode_SourceIn << qRgba(85, 0, 0, 85) << 85;
}
void tst_QPainter::blendARGBonRGB()
diff --git a/tests/auto/gui/painting/qpainterpath/tst_qpainterpath.cpp b/tests/auto/gui/painting/qpainterpath/tst_qpainterpath.cpp
index 0a073f5c84..ae30719ee7 100644
--- a/tests/auto/gui/painting/qpainterpath/tst_qpainterpath.cpp
+++ b/tests/auto/gui/painting/qpainterpath/tst_qpainterpath.cpp
@@ -602,16 +602,16 @@ void tst_QPainterPath::testOperatorEquals()
{
QPainterPath empty1;
QPainterPath empty2;
- QVERIFY(empty1 == empty2);
+ QCOMPARE(empty1, empty2);
QPainterPath rect1;
rect1.addRect(100, 100, 100, 100);
- QVERIFY(rect1 == rect1);
+ QCOMPARE(rect1, rect1);
QVERIFY(rect1 != empty1);
QPainterPath rect2;
rect2.addRect(100, 100, 100, 100);
- QVERIFY(rect1 == rect2);
+ QCOMPARE(rect1, rect2);
rect2.setFillRule(Qt::WindingFill);
QVERIFY(rect1 != rect2);
@@ -622,7 +622,7 @@ void tst_QPainterPath::testOperatorEquals()
QPainterPath ellipse2;
ellipse2.addEllipse(50, 50, 100, 100);
- QVERIFY(ellipse1 == ellipse2);
+ QCOMPARE(ellipse1, ellipse2);
}
void tst_QPainterPath::testOperatorEquals_fuzzy()
@@ -638,12 +638,12 @@ void tst_QPainterPath::testOperatorEquals_fuzzy()
QPainterPath pb;
pb.addRect(b);
- QVERIFY(pa == pb);
+ QCOMPARE(pa, pb);
QTransform transform;
transform.translate(-100, -100);
- QVERIFY(transform.map(pa) == transform.map(pb));
+ QCOMPARE(transform.map(pa), transform.map(pb));
}
// higher tolerance for error when path's bounding rect is big
@@ -656,12 +656,12 @@ void tst_QPainterPath::testOperatorEquals_fuzzy()
QPainterPath pb;
pb.addRect(b);
- QVERIFY(pa == pb);
+ QCOMPARE(pa, pb);
QTransform transform;
transform.translate(-1, -1);
- QVERIFY(transform.map(pa) == transform.map(pb));
+ QCOMPARE(transform.map(pa), transform.map(pb));
}
// operator== should return true for a path that has
@@ -676,7 +676,7 @@ void tst_QPainterPath::testOperatorEquals_fuzzy()
QPainterPath b = transform.inverted().map(transform.map(a));
- QVERIFY(a == b);
+ QCOMPARE(a, b);
}
{
@@ -720,7 +720,7 @@ void tst_QPainterPath::testOperatorDatastream()
stream >> other;
}
- QVERIFY(other == path);
+ QCOMPARE(other, path);
}
void tst_QPainterPath::closing()
@@ -1066,19 +1066,19 @@ void tst_QPainterPath::setElementPositionAt()
{
QPainterPath path(QPointF(42., 42.));
QCOMPARE(path.elementCount(), 1);
- QVERIFY(path.elementAt(0).type == QPainterPath::MoveToElement);
+ QCOMPARE(path.elementAt(0).type, QPainterPath::MoveToElement);
QCOMPARE(path.elementAt(0).x, qreal(42.));
QCOMPARE(path.elementAt(0).y, qreal(42.));
QPainterPath copy = path;
copy.setElementPositionAt(0, qreal(0), qreal(0));
QCOMPARE(copy.elementCount(), 1);
- QVERIFY(copy.elementAt(0).type == QPainterPath::MoveToElement);
+ QCOMPARE(copy.elementAt(0).type, QPainterPath::MoveToElement);
QCOMPARE(copy.elementAt(0).x, qreal(0));
QCOMPARE(copy.elementAt(0).y, qreal(0));
QCOMPARE(path.elementCount(), 1);
- QVERIFY(path.elementAt(0).type == QPainterPath::MoveToElement);
+ QCOMPARE(path.elementAt(0).type, QPainterPath::MoveToElement);
QCOMPARE(path.elementAt(0).x, qreal(42.));
QCOMPARE(path.elementAt(0).y, qreal(42.));
}
@@ -1253,10 +1253,10 @@ void tst_QPainterPath::connectPathMoveTo()
path1.connectPath(path2);
- QVERIFY(path1.elementAt(0).type == QPainterPath::MoveToElement);
- QVERIFY(path2.elementAt(0).type == QPainterPath::MoveToElement);
- QVERIFY(path3.elementAt(0).type == QPainterPath::MoveToElement);
- QVERIFY(path4.elementAt(0).type == QPainterPath::MoveToElement);
+ QCOMPARE(path1.elementAt(0).type, QPainterPath::MoveToElement);
+ QCOMPARE(path2.elementAt(0).type, QPainterPath::MoveToElement);
+ QCOMPARE(path3.elementAt(0).type, QPainterPath::MoveToElement);
+ QCOMPARE(path4.elementAt(0).type, QPainterPath::MoveToElement);
}
void tst_QPainterPath::translate()
diff --git a/tests/auto/gui/painting/qregion/tst_qregion.cpp b/tests/auto/gui/painting/qregion/tst_qregion.cpp
index c0e3c6d187..33f81cc10e 100644
--- a/tests/auto/gui/painting/qregion/tst_qregion.cpp
+++ b/tests/auto/gui/painting/qregion/tst_qregion.cpp
@@ -173,7 +173,7 @@ void tst_QRegion::setRects()
QRect rect;
region.setRects(&rect, 0);
QVERIFY(region.isEmpty());
- QVERIFY(region == QRegion());
+ QCOMPARE(region, QRegion());
QVERIFY(!region.boundingRect().isValid());
QVERIFY(region.rects().isEmpty());
}
diff --git a/tests/auto/gui/painting/qtransform/tst_qtransform.cpp b/tests/auto/gui/painting/qtransform/tst_qtransform.cpp
index 13b15d09dd..60b89aa6ab 100644
--- a/tests/auto/gui/painting/qtransform/tst_qtransform.cpp
+++ b/tests/auto/gui/painting/qtransform/tst_qtransform.cpp
@@ -57,6 +57,7 @@ private slots:
void mapRect();
void assignments();
void mapToPolygon();
+ void qhash();
void translate();
void scale();
void matrix();
@@ -361,6 +362,22 @@ void tst_QTransform::mapToPolygon()
QVERIFY(equal);
}
+void tst_QTransform::qhash()
+{
+ QMatrix m1;
+ m1.shear(3.0, 2.0);
+ m1.rotate(44);
+
+ QMatrix m2 = m1;
+
+ QTransform t1(m1);
+ QTransform t2(m2);
+
+ // not really much to test here, so just the bare minimum:
+ QCOMPARE(qHash(m1), qHash(m2));
+ QCOMPARE(qHash(t1), qHash(t2));
+}
+
void tst_QTransform::translate()
{
@@ -411,14 +428,14 @@ void tst_QTransform::matrix()
mat1.m21(), mat1.m22(), 0,
mat1.dx(), mat1.dy(), 1);
- QVERIFY(tran1 == dummy);
- QVERIFY(tran1.inverted() == dummy.inverted());
- QVERIFY(tran1.inverted() == QTransform(mat1.inverted()));
- QVERIFY(tran2.inverted() == QTransform(mat2.inverted()));
+ QCOMPARE(tran1, dummy);
+ QCOMPARE(tran1.inverted(), dummy.inverted());
+ QCOMPARE(tran1.inverted(), QTransform(mat1.inverted()));
+ QCOMPARE(tran2.inverted(), QTransform(mat2.inverted()));
QMatrix mat3 = mat1 * mat2;
QTransform tran3 = tran1 * tran2;
- QVERIFY(QTransform(mat3) == tran3);
+ QCOMPARE(QTransform(mat3), tran3);
/* QMatrix::operator==() doesn't use qFuzzyCompare(), which
* on win32-g++ results in a failure. So we work around it by
@@ -430,15 +447,15 @@ void tst_QTransform::matrix()
QRect rect(43, 70, 200, 200);
QPoint pt(43, 66);
- QVERIFY(tranInv.map(pt) == matInv.map(pt));
- QVERIFY(tranInv.map(pt) == matInv.map(pt));
+ QCOMPARE(tranInv.map(pt), matInv.map(pt));
+ QCOMPARE(tranInv.map(pt), matInv.map(pt));
QPainterPath path;
path.moveTo(55, 60);
path.lineTo(110, 110);
path.quadTo(220, 50, 10, 20);
path.closeSubpath();
- QVERIFY(tranInv.map(path) == matInv.map(path));
+ QCOMPARE(tranInv.map(path), matInv.map(path));
}
void tst_QTransform::testOffset()
@@ -724,8 +741,8 @@ void tst_QTransform::inverted()
const QTransform inverted = matrix.inverted();
- QVERIFY(matrix.isIdentity() == inverted.isIdentity());
- QVERIFY(matrix.type() == inverted.type());
+ QCOMPARE(matrix.isIdentity(), inverted.isIdentity());
+ QCOMPARE(matrix.type(), inverted.type());
QVERIFY((matrix * inverted).isIdentity());
QVERIFY((inverted * matrix).isIdentity());
diff --git a/tests/auto/gui/qopengl/BLACKLIST b/tests/auto/gui/qopengl/BLACKLIST
new file mode 100644
index 0000000000..7f167d81df
--- /dev/null
+++ b/tests/auto/gui/qopengl/BLACKLIST
@@ -0,0 +1,8 @@
+[fboRendering]
+windows
+[QTBUG15621_triangulatingStrokerDivZero]
+windows
+[imageFormatPainting]
+windows
+[openGLPaintDevice]
+windows
diff --git a/tests/auto/gui/qopengl/tst_qopengl.cpp b/tests/auto/gui/qopengl/tst_qopengl.cpp
index 8c6c28b492..8103f27911 100644
--- a/tests/auto/gui/qopengl/tst_qopengl.cpp
+++ b/tests/auto/gui/qopengl/tst_qopengl.cpp
@@ -86,6 +86,8 @@ private slots:
void fboRenderingRGB30_data();
void fboRenderingRGB30();
void fboHandleNulledAfterContextDestroyed();
+ void fboMRT();
+ void fboMRT_differentFormats();
void openGLPaintDevice_data();
void openGLPaintDevice();
void aboutToBeDestroyed();
@@ -514,7 +516,7 @@ void tst_QOpenGL::fboTextureOwnership()
// pull out the texture
GLuint texture = fbo->takeTexture();
QVERIFY(texture != 0);
- QVERIFY(fbo->texture() == 0);
+ QCOMPARE(fbo->texture(), GLuint(0));
// verify that the next bind() creates a new texture
fbo->bind();
@@ -594,6 +596,14 @@ void tst_QOpenGL::fboRenderingRGB30_data()
common_data();
}
+#ifndef GL_RGB5_A1
+#define GL_RGB5_A1 0x8057
+#endif
+
+#ifndef GL_RGBA8
+#define GL_RGBA8 0x8058
+#endif
+
#ifndef GL_RGB10_A2
#define GL_RGB10_A2 0x8059
#endif
@@ -606,6 +616,24 @@ void tst_QOpenGL::fboRenderingRGB30_data()
#define GL_FULL_SUPPORT 0x82B7
#endif
+static bool hasRGB10A2(QOpenGLContext *ctx)
+{
+ if (ctx->format().majorVersion() < 3)
+ return false;
+#ifndef QT_OPENGL_ES_2
+ if (!ctx->isOpenGLES() && ctx->format().majorVersion() >= 4) {
+ GLint value = -1;
+ QOpenGLFunctions_4_2_Core* vFuncs = ctx->versionFunctions<QOpenGLFunctions_4_2_Core>();
+ if (vFuncs && vFuncs->initializeOpenGLFunctions()) {
+ vFuncs->glGetInternalformativ(GL_TEXTURE_2D, GL_RGB10_A2, GL_FRAMEBUFFER_RENDERABLE, 1, &value);
+ if (value != GL_FULL_SUPPORT)
+ return false;
+ }
+ }
+#endif
+ return true;
+}
+
void tst_QOpenGL::fboRenderingRGB30()
{
#if defined(Q_OS_LINUX) && defined(Q_CC_GNU) && !defined(__x86_64__)
@@ -623,24 +651,9 @@ void tst_QOpenGL::fboRenderingRGB30()
if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
QSKIP("QOpenGLFramebufferObject not supported on this platform");
- if (ctx.format().majorVersion() < 3)
+ if (!hasRGB10A2(&ctx))
QSKIP("An internal RGB30_A2 format is not guaranteed on this platform");
-#if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_2)
- // NVidia currently only supports RGB30 and RGB30_A2 in their Quadro drivers,
- // but they do provide an extension for querying the support. We use the query
- // in case they implement the required formats later.
- if (!ctx.isOpenGLES() && ctx.format().majorVersion() >= 4) {
- GLint value = -1;
- QOpenGLFunctions_4_2_Core* vFuncs = ctx.versionFunctions<QOpenGLFunctions_4_2_Core>();
- if (vFuncs && vFuncs->initializeOpenGLFunctions()) {
- vFuncs->glGetInternalformativ(GL_TEXTURE_2D, GL_RGB10_A2, GL_FRAMEBUFFER_RENDERABLE, 1, &value);
- if (value != GL_FULL_SUPPORT)
- QSKIP("The required RGB30_A2 format is not supported by this driver");
- }
- }
-#endif
-
// No multisample with combined depth/stencil attachment:
QOpenGLFramebufferObjectFormat fboFormat;
fboFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
@@ -720,6 +733,150 @@ void tst_QOpenGL::fboHandleNulledAfterContextDestroyed()
QCOMPARE(fbo->handle(), 0U);
}
+void tst_QOpenGL::fboMRT()
+{
+ QWindow window;
+ window.setSurfaceType(QWindow::OpenGLSurface);
+ window.setGeometry(0, 0, 10, 10);
+ window.create();
+
+ QOpenGLContext ctx;
+ QVERIFY(ctx.create());
+ ctx.makeCurrent(&window);
+
+ if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
+ QSKIP("QOpenGLFramebufferObject not supported on this platform");
+
+ if (!ctx.functions()->hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets))
+ QSKIP("Multiple render targets not supported on this platform");
+
+ QOpenGLExtraFunctions *ef = ctx.extraFunctions();
+
+ {
+ // 3 color attachments, different sizes, same internal format, no depth/stencil.
+ QVector<QSize> sizes;
+ sizes << QSize(128, 128) << QSize(192, 128) << QSize(432, 123);
+ QOpenGLFramebufferObject fbo(sizes[0]);
+ fbo.addColorAttachment(sizes[1]);
+ fbo.addColorAttachment(sizes[2]);
+ QVERIFY(fbo.bind());
+ QCOMPARE(fbo.attachment(), QOpenGLFramebufferObject::NoAttachment);
+ QCOMPARE(sizes, fbo.sizes());
+ QCOMPARE(sizes[0], fbo.size());
+ // Clear the three buffers to red, green and blue.
+ GLenum drawBuf = GL_COLOR_ATTACHMENT0;
+ ef->glDrawBuffers(1, &drawBuf);
+ ef->glClearColor(1, 0, 0, 1);
+ ef->glClear(GL_COLOR_BUFFER_BIT);
+ drawBuf = GL_COLOR_ATTACHMENT0 + 1;
+ ef->glDrawBuffers(1, &drawBuf);
+ ef->glClearColor(0, 1, 0, 1);
+ ef->glClear(GL_COLOR_BUFFER_BIT);
+ drawBuf = GL_COLOR_ATTACHMENT0 + 2;
+ ef->glDrawBuffers(1, &drawBuf);
+ ef->glClearColor(0, 0, 1, 1);
+ ef->glClear(GL_COLOR_BUFFER_BIT);
+ // Verify, keeping in mind that only a 128x123 area is touched in the buffers.
+ // Some drivers do not get this right, unfortunately, so do not rely on it.
+ const char *vendor = (const char *) ef->glGetString(GL_VENDOR);
+ bool hasCorrectMRT = false;
+ if (vendor && strstr(vendor, "NVIDIA")) // maybe others too
+ hasCorrectMRT = true;
+ QImage img = fbo.toImage(false, 0);
+ QCOMPARE(img.size(), sizes[0]);
+ QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0));
+ if (hasCorrectMRT)
+ QCOMPARE(img.pixel(127, 122), qRgb(255, 0, 0));
+ img = fbo.toImage(false, 1);
+ QCOMPARE(img.size(), sizes[1]);
+ QCOMPARE(img.pixel(0, 0), qRgb(0, 255, 0));
+ if (hasCorrectMRT)
+ QCOMPARE(img.pixel(127, 122), qRgb(0, 255, 0));
+ img = fbo.toImage(false, 2);
+ QCOMPARE(img.size(), sizes[2]);
+ QCOMPARE(img.pixel(0, 0), qRgb(0, 0, 255));
+ if (hasCorrectMRT)
+ QCOMPARE(img.pixel(127, 122), qRgb(0, 0, 255));
+ fbo.release();
+ }
+
+ {
+ // 2 color attachments, same size, same internal format, depth/stencil.
+ QVector<QSize> sizes;
+ sizes.fill(QSize(128, 128), 2);
+ QOpenGLFramebufferObject fbo(sizes[0], QOpenGLFramebufferObject::CombinedDepthStencil);
+ fbo.addColorAttachment(sizes[1]);
+ QVERIFY(fbo.bind());
+ QCOMPARE(fbo.attachment(), QOpenGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(sizes, fbo.sizes());
+ QCOMPARE(sizes[0], fbo.size());
+ ef->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ ef->glFinish();
+ fbo.release();
+ }
+}
+
+void tst_QOpenGL::fboMRT_differentFormats()
+{
+ QWindow window;
+ window.setSurfaceType(QWindow::OpenGLSurface);
+ window.setGeometry(0, 0, 10, 10);
+ window.create();
+
+ QOpenGLContext ctx;
+ QVERIFY(ctx.create());
+ ctx.makeCurrent(&window);
+
+ QOpenGLFunctions *f = ctx.functions();
+ const char * vendor = (const char *) f->glGetString(GL_VENDOR);
+ if (vendor && strstr(vendor, "VMware, Inc."))
+ QSKIP("The tested formats may not be supported on this platform");
+
+ if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
+ QSKIP("QOpenGLFramebufferObject not supported on this platform");
+
+ if (!f->hasOpenGLFeature(QOpenGLFunctions::MultipleRenderTargets))
+ QSKIP("Multiple render targets not supported on this platform");
+
+ if (!hasRGB10A2(&ctx))
+ QSKIP("RGB10_A2 not supported on this platform");
+
+ // 3 color attachments, same size, different internal format, depth/stencil.
+ QVector<QSize> sizes;
+ sizes.fill(QSize(128, 128), 3);
+ QOpenGLFramebufferObjectFormat format;
+ format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
+ QVector<GLenum> internalFormats;
+ internalFormats << GL_RGBA8 << GL_RGB10_A2 << GL_RGB5_A1;
+ format.setInternalTextureFormat(internalFormats[0]);
+ QOpenGLFramebufferObject fbo(sizes[0], format);
+ fbo.addColorAttachment(sizes[1], internalFormats[1]);
+ fbo.addColorAttachment(sizes[2], internalFormats[2]);
+
+ QVERIFY(fbo.bind());
+ QCOMPARE(fbo.attachment(), QOpenGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(sizes, fbo.sizes());
+ QCOMPARE(sizes[0], fbo.size());
+
+ QOpenGLExtraFunctions *ef = ctx.extraFunctions();
+ QVERIFY(ef->glGetError() == 0);
+ ef->glClearColor(1, 0, 0, 1);
+ GLenum drawBuf[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0 + 1, GL_COLOR_ATTACHMENT0 + 2 };
+ ef->glDrawBuffers(3, drawBuf);
+ ef->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ QVERIFY(ef->glGetError() == 0);
+
+ QImage img = fbo.toImage(true, 0);
+ QCOMPARE(img.size(), sizes[0]);
+ QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0));
+ img = fbo.toImage(true, 1);
+ QCOMPARE(img.size(), sizes[1]);
+ QCOMPARE(img.format(), QImage::Format_A2BGR30_Premultiplied);
+ QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0));
+
+ fbo.release();
+}
+
void tst_QOpenGL::imageFormatPainting()
{
QScopedPointer<QSurface> surface(createSurface(QSurface::Window));
@@ -1174,18 +1331,18 @@ void tst_QOpenGL::textureblitterPartTargetRectTransform()
void tst_QOpenGL::defaultSurfaceFormat()
{
QSurfaceFormat fmt;
- QVERIFY(QSurfaceFormat::defaultFormat() == fmt);
+ QCOMPARE(QSurfaceFormat::defaultFormat(), fmt);
fmt.setDepthBufferSize(16);
QSurfaceFormat::setDefaultFormat(fmt);
- QVERIFY(QSurfaceFormat::defaultFormat() == fmt);
+ QCOMPARE(QSurfaceFormat::defaultFormat(), fmt);
QCOMPARE(QSurfaceFormat::defaultFormat().depthBufferSize(), 16);
QScopedPointer<QWindow> window(new QWindow);
- QVERIFY(window->requestedFormat() == fmt);
+ QCOMPARE(window->requestedFormat(), fmt);
QScopedPointer<QOpenGLContext> context(new QOpenGLContext);
- QVERIFY(context->format() == fmt);
+ QCOMPARE(context->format(), fmt);
}
#ifdef USE_GLX
@@ -1214,7 +1371,7 @@ void tst_QOpenGL::glxContextWrap()
QOpenGLContext *ctx = new QOpenGLContext;
ctx->setNativeHandle(QVariant::fromValue<QGLXNativeContext>(QGLXNativeContext(context)));
QVERIFY(ctx->create());
- QVERIFY(ctx->nativeHandle().value<QGLXNativeContext>().context() == context);
+ QCOMPARE(ctx->nativeHandle().value<QGLXNativeContext>().context(), context);
QVERIFY(nativeIf->nativeResourceForContext(QByteArrayLiteral("glxcontext"), ctx) == (void *) context);
QVERIFY(ctx->makeCurrent(window));
diff --git a/tests/auto/gui/qopenglconfig/buglist.json b/tests/auto/gui/qopenglconfig/buglist.json
index c7b8e61bc8..ef311612b2 100644
--- a/tests/auto/gui/qopenglconfig/buglist.json
+++ b/tests/auto/gui/qopenglconfig/buglist.json
@@ -103,6 +103,28 @@
]
},
{
+ "id": 7,
+ "description": "driver description test",
+ "driver_description": "Long And Special Driver Description",
+ "os": {
+ "type": "win"
+ },
+ "features": [
+ "feature2"
+ ]
+ },
+ {
+ "id": 8,
+ "description": "Windows version test",
+ "os": {
+ "type": "win",
+ "release": [ "10" ]
+ },
+ "features": [
+ "win10_feature"
+ ]
+ },
+ {
"id": 128,
"description": "check for matching GL_VENDOR",
"gl_vendor": "The Qt Company",
diff --git a/tests/auto/gui/qopenglconfig/tst_qopenglconfig.cpp b/tests/auto/gui/qopenglconfig/tst_qopenglconfig.cpp
index f88cbdc758..48a15641b2 100644
--- a/tests/auto/gui/qopenglconfig/tst_qopenglconfig.cpp
+++ b/tests/auto/gui/qopenglconfig/tst_qopenglconfig.cpp
@@ -47,6 +47,7 @@
#include <QtCore/QVariant>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
+#include <QtCore/QJsonDocument>
#include <algorithm>
@@ -107,6 +108,7 @@ private slots:
void testConfiguration();
void testGlConfiguration();
void testBugList();
+ void testDefaultWindowsBlacklist();
};
static void dumpConfiguration(QTextStream &str)
@@ -243,29 +245,61 @@ void tst_QOpenGlConfig::testBugList()
QSet<QString> expectedFeatures;
expectedFeatures << "feature1";
+ // adapter info
QVersionNumber driverVersion(QVector<int>() << 9 << 18 << 13 << 4460);
- QOpenGLConfig::Gpu gpu = QOpenGLConfig::Gpu::fromDevice(0x10DE, 0x0DE9, driverVersion);
+ QOpenGLConfig::Gpu gpu = QOpenGLConfig::Gpu::fromDevice(0x10DE, 0x0DE9, driverVersion, QByteArrayLiteral("Unknown"));
QSet<QString> actualFeatures = QOpenGLConfig::gpuFeatures(gpu, QStringLiteral("win"),
- QVersionNumber(6, 3), fileName);
+ QVersionNumber(6, 3), QStringLiteral("7"), fileName);
QVERIFY2(expectedFeatures == actualFeatures,
msgSetMismatch(expectedFeatures, actualFeatures));
+ // driver_description
+ gpu = QOpenGLConfig::Gpu::fromDevice(0xDEAD, 0xBEEF, driverVersion, QByteArrayLiteral("Very Long And Special Driver Description"));
+ actualFeatures = QOpenGLConfig::gpuFeatures(gpu, QStringLiteral("win"),
+ QVersionNumber(6, 3), QStringLiteral("8"), fileName);
+ expectedFeatures = QSet<QString>() << "feature2";
+ QVERIFY2(expectedFeatures == actualFeatures,
+ msgSetMismatch(expectedFeatures, actualFeatures));
+
+ // os.release
+ gpu = QOpenGLConfig::Gpu::fromDevice(0xDEAD, 0xBEEF, driverVersion, QByteArrayLiteral("WinVerTest"));
+ actualFeatures = QOpenGLConfig::gpuFeatures(gpu, QStringLiteral("win"),
+ QVersionNumber(12, 34), QStringLiteral("10"), fileName);
+ expectedFeatures = QSet<QString>() << "win10_feature";
+ QVERIFY2(expectedFeatures == actualFeatures,
+ msgSetMismatch(expectedFeatures, actualFeatures));
+
+ // gl_vendor
gpu = QOpenGLConfig::Gpu::fromGLVendor(QByteArrayLiteral("Somebody Else"));
expectedFeatures.clear();
actualFeatures = QOpenGLConfig::gpuFeatures(gpu, QStringLiteral("linux"),
- QVersionNumber(1, 0), fileName);
+ QVersionNumber(1, 0), QString(), fileName);
QVERIFY2(expectedFeatures == actualFeatures,
msgSetMismatch(expectedFeatures, actualFeatures));
gpu = QOpenGLConfig::Gpu::fromGLVendor(QByteArrayLiteral("The Qt Company"));
expectedFeatures = QSet<QString>() << "cool_feature";
actualFeatures = QOpenGLConfig::gpuFeatures(gpu, QStringLiteral("linux"),
- QVersionNumber(1, 0), fileName);
+ QVersionNumber(1, 0), QString(), fileName);
QVERIFY2(expectedFeatures == actualFeatures,
msgSetMismatch(expectedFeatures, actualFeatures));
}
+void tst_QOpenGlConfig::testDefaultWindowsBlacklist()
+{
+ if (qGuiApp->platformName() != QStringLiteral("windows"))
+ QSKIP("Only applicable to Windows");
+
+ QFile f(QStringLiteral(":/qt-project.org/windows/openglblacklists/default.json"));
+ QVERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text));
+ QJsonParseError err;
+ QJsonDocument doc = QJsonDocument::fromJson(f.readAll(), &err);
+ QVERIFY2(err.error == 0,
+ QStringLiteral("Failed to parse built-in Windows GPU blacklist. %1 : %2")
+ .arg(err.offset).arg(err.errorString()).toLatin1());
+}
+
QTEST_MAIN(tst_QOpenGlConfig)
#include "tst_qopenglconfig.moc"
diff --git a/tests/auto/gui/text/qcssparser/tst_qcssparser.cpp b/tests/auto/gui/text/qcssparser/tst_qcssparser.cpp
index 5d78bc1d01..b1beb0ffd0 100644
--- a/tests/auto/gui/text/qcssparser/tst_qcssparser.cpp
+++ b/tests/auto/gui/text/qcssparser/tst_qcssparser.cpp
@@ -203,8 +203,8 @@ void tst_QCssParser::scanner()
QCss::Scanner::scan(QCss::Scanner::preprocess(QString::fromUtf8(inputFile.readAll())), &symbols);
QVERIFY(symbols.count() > 1);
- QVERIFY(symbols.last().token == QCss::S);
- QVERIFY(symbols.last().lexem() == QLatin1String("\n"));
+ QCOMPARE(symbols.last().token, QCss::S);
+ QCOMPARE(symbols.last().lexem(), QLatin1String("\n"));
symbols.remove(symbols.count() - 1, 1);
QFile outputFile(output);
@@ -861,7 +861,7 @@ void tst_QCssParser::colorValue()
QCss::Declaration decl;
QVERIFY(parser.parseNextDeclaration(&decl));
const QColor col = decl.colorValue();
- QVERIFY(expectedColor.isValid() == col.isValid());
+ QCOMPARE(expectedColor.isValid(), col.isValid());
QCOMPARE(col, expectedColor);
}
@@ -1304,7 +1304,7 @@ void tst_QCssParser::rulesForNode()
decls += rules.at(i).declarations;
}
- QVERIFY(decls.count() == declCount);
+ QCOMPARE(decls.count(), declCount);
if (declCount > 0)
QCOMPARE(decls.at(0).d->values.at(0).variant.toString(), value0);
@@ -1364,7 +1364,7 @@ void tst_QCssParser::shorthandBackgroundProperty()
v.extractBackground(&brush, &image, &repeat, &alignment, &origin, &attachment, &ignoredOrigin);
QFETCH(QBrush, expectedBrush);
- QVERIFY(expectedBrush.color() == brush.color());
+ QCOMPARE(expectedBrush.color(), brush.color());
QTEST(image, "expectedImage");
QTEST(int(repeat), "expectedRepeatValue");
@@ -1372,7 +1372,7 @@ void tst_QCssParser::shorthandBackgroundProperty()
//QTBUG-9674 : a second evaluation should give the same results
QVERIFY(v.extractBackground(&brush, &image, &repeat, &alignment, &origin, &attachment, &ignoredOrigin));
- QVERIFY(expectedBrush.color() == brush.color());
+ QCOMPARE(expectedBrush.color(), brush.color());
QTEST(image, "expectedImage");
QTEST(int(repeat), "expectedRepeatValue");
QTEST(int(alignment), "expectedAlignment");
@@ -1438,7 +1438,7 @@ void tst_QCssParser::pseudoElement()
decls += rules.at(i).declarations;
}
- QVERIFY(decls.count() == declCount);
+ QCOMPARE(decls.count(), declCount);
}
void tst_QCssParser::gradient_data()
@@ -1517,21 +1517,21 @@ void tst_QCssParser::gradient()
QBrush sbg, abg;
QVERIFY(ve.extractPalette(&fg, &sfg, &sbg, &abg));
if (type == "linear") {
- QVERIFY(sbg.style() == Qt::LinearGradientPattern);
+ QCOMPARE(sbg.style(), Qt::LinearGradientPattern);
const QLinearGradient *lg = static_cast<const QLinearGradient *>(sbg.gradient());
QCOMPARE(lg->start(), start);
QCOMPARE(lg->finalStop(), finalStop);
} else if (type == "conical") {
- QVERIFY(sbg.style() == Qt::ConicalGradientPattern);
+ QCOMPARE(sbg.style(), Qt::ConicalGradientPattern);
const QConicalGradient *cg = static_cast<const QConicalGradient *>(sbg.gradient());
QCOMPARE(cg->center(), start);
}
const QGradient *g = sbg.gradient();
QCOMPARE(g->spread(), QGradient::Spread(spread));
- QVERIFY(g->stops().at(0).first == stop0);
- QVERIFY(g->stops().at(0).second == color0);
- QVERIFY(g->stops().at(1).first == stop1);
- QVERIFY(g->stops().at(1).second == color1);
+ QCOMPARE(g->stops().at(0).first, stop0);
+ QCOMPARE(g->stops().at(0).second, color0);
+ QCOMPARE(g->stops().at(1).first, stop1);
+ QCOMPARE(g->stops().at(1).second, color1);
}
void tst_QCssParser::extractFontFamily_data()
@@ -1637,15 +1637,15 @@ void tst_QCssParser::extractBorder()
QSize radii[4];
extractor.extractBorder(widths, colors, styles, radii);
- QVERIFY(widths[QCss::TopEdge] == expectedTopWidth);
- QVERIFY(styles[QCss::TopEdge] == expectedTopStyle);
- QVERIFY(colors[QCss::TopEdge] == expectedTopColor);
+ QCOMPARE(widths[QCss::TopEdge], expectedTopWidth);
+ QCOMPARE(int(styles[QCss::TopEdge]), expectedTopStyle);
+ QCOMPARE(colors[QCss::TopEdge].color(), expectedTopColor);
//QTBUG-9674 : a second evaluation should give the same results
QVERIFY(extractor.extractBorder(widths, colors, styles, radii));
- QVERIFY(widths[QCss::TopEdge] == expectedTopWidth);
- QVERIFY(styles[QCss::TopEdge] == expectedTopStyle);
- QVERIFY(colors[QCss::TopEdge] == expectedTopColor);
+ QCOMPARE(widths[QCss::TopEdge], expectedTopWidth);
+ QCOMPARE(int(styles[QCss::TopEdge]), expectedTopStyle);
+ QCOMPARE(colors[QCss::TopEdge].color(), expectedTopColor);
}
void tst_QCssParser::noTextDecoration()
diff --git a/tests/auto/gui/text/qfont/BLACKLIST b/tests/auto/gui/text/qfont/BLACKLIST
new file mode 100644
index 0000000000..d859dee03e
--- /dev/null
+++ b/tests/auto/gui/text/qfont/BLACKLIST
@@ -0,0 +1,2 @@
+[exactMatch]
+opensuse-13.1
diff --git a/tests/auto/gui/text/qfont/tst_qfont.cpp b/tests/auto/gui/text/qfont/tst_qfont.cpp
index 64b06e9856..462e5115b4 100644
--- a/tests/auto/gui/text/qfont/tst_qfont.cpp
+++ b/tests/auto/gui/text/qfont/tst_qfont.cpp
@@ -217,15 +217,15 @@ void tst_QFont::exactMatch()
|| fontinfo.family().isEmpty());
}
if (font.pointSize() != -1) {
- QVERIFY(font.pointSize() == fontinfo.pointSize());
+ QCOMPARE(font.pointSize(), fontinfo.pointSize());
} else {
- QVERIFY(font.pixelSize() == fontinfo.pixelSize());
+ QCOMPARE(font.pixelSize(), fontinfo.pixelSize());
}
- QVERIFY(font.italic() == fontinfo.italic());
+ QCOMPARE(font.italic(), fontinfo.italic());
if (font.weight() != fontinfo.weight()) {
qDebug("font is %s", font.toString().toLatin1().constData());
}
- QVERIFY(font.weight() == fontinfo.weight());
+ QCOMPARE(font.weight(), fontinfo.weight());
} else {
font.setFixedPitch(!fontinfo.fixedPitch());
QFontInfo fontinfo1(font);
@@ -274,12 +274,12 @@ void tst_QFont::exactMatch()
|| fontinfo.family().contains(font.family())
|| fontinfo.family().isEmpty());
if (font.pointSize() != -1) {
- QVERIFY(font.pointSize() == fontinfo.pointSize());
+ QCOMPARE(font.pointSize(), fontinfo.pointSize());
} else {
- QVERIFY(font.pixelSize() == fontinfo.pixelSize());
+ QCOMPARE(font.pixelSize(), fontinfo.pixelSize());
}
- QVERIFY(font.italic() == fontinfo.italic());
- QVERIFY(font.weight() == fontinfo.weight());
+ QCOMPARE(font.italic(), fontinfo.italic());
+ QCOMPARE(font.weight(), fontinfo.weight());
} else {
font.setFixedPitch(!fontinfo.fixedPitch());
QFontInfo fontinfo1(font, (QFont::Script) script);
@@ -371,42 +371,42 @@ void tst_QFont::compare()
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font2.setItalic(false);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
font2.setWeight(QFont::Bold);
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font2.setWeight(QFont::Normal);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
font.setUnderline(true);
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font.setUnderline(false);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
font.setStrikeOut(true);
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font.setStrikeOut(false);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
font.setOverline(true);
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font.setOverline(false);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
font.setCapitalization(QFont::SmallCaps);
QVERIFY(font != font2);
QCOMPARE(font < font2,!(font2 < font));
font.setCapitalization(QFont::MixedCase);
- QVERIFY(font == font2);
+ QCOMPARE(font, font2);
QVERIFY(!(font < font2));
}
}
@@ -426,27 +426,27 @@ void tst_QFont::resolve()
font1.setWeight(QFont::Bold);
QFont font2 = font1.resolve(font);
- QVERIFY(font2.weight() == font1.weight());
+ QCOMPARE(font2.weight(), font1.weight());
- QVERIFY(font2.pointSize() == font.pointSize());
- QVERIFY(font2.italic() == font.italic());
- QVERIFY(font2.underline() == font.underline());
- QVERIFY(font2.overline() == font.overline());
- QVERIFY(font2.strikeOut() == font.strikeOut());
- QVERIFY(font2.stretch() == font.stretch());
+ QCOMPARE(font2.pointSize(), font.pointSize());
+ QCOMPARE(font2.italic(), font.italic());
+ QCOMPARE(font2.underline(), font.underline());
+ QCOMPARE(font2.overline(), font.overline());
+ QCOMPARE(font2.strikeOut(), font.strikeOut());
+ QCOMPARE(font2.stretch(), font.stretch());
QFont font3;
font3.setStretch(QFont::UltraCondensed);
QFont font4 = font3.resolve(font1).resolve(font);
- QVERIFY(font4.stretch() == font3.stretch());
+ QCOMPARE(font4.stretch(), font3.stretch());
- QVERIFY(font4.weight() == font.weight());
- QVERIFY(font4.pointSize() == font.pointSize());
- QVERIFY(font4.italic() == font.italic());
- QVERIFY(font4.underline() == font.underline());
- QVERIFY(font4.overline() == font.overline());
- QVERIFY(font4.strikeOut() == font.strikeOut());
+ QCOMPARE(font4.weight(), font.weight());
+ QCOMPARE(font4.pointSize(), font.pointSize());
+ QCOMPARE(font4.italic(), font.italic());
+ QCOMPARE(font4.underline(), font.underline());
+ QCOMPARE(font4.overline(), font.overline());
+ QCOMPARE(font4.strikeOut(), font.strikeOut());
QFont f1,f2,f3;
@@ -479,8 +479,8 @@ void tst_QFont::resetFont()
child->setFont(QFont()); // reset font
- QVERIFY(child->font().resolve() == 0);
- QVERIFY(child->font().pointSize() == parent.font().pointSize());
+ QCOMPARE(child->font().resolve(), uint(0));
+ QCOMPARE(child->font().pointSize(), parent.font().pointSize());
QVERIFY(parent.font().resolve() != 0);
}
#endif
@@ -728,24 +728,24 @@ void tst_QFont::sharing()
QCOMPARE(QFontPrivate::get(f)->engineData->ref.load(), 1 + refs_by_cache);
QFont f2(f);
- QVERIFY(QFontPrivate::get(f2) == QFontPrivate::get(f));
+ QCOMPARE(QFontPrivate::get(f2), QFontPrivate::get(f));
QCOMPARE(QFontPrivate::get(f2)->ref.load(), 2);
QVERIFY(QFontPrivate::get(f2)->engineData);
- QVERIFY(QFontPrivate::get(f2)->engineData == QFontPrivate::get(f)->engineData);
+ QCOMPARE(QFontPrivate::get(f2)->engineData, QFontPrivate::get(f)->engineData);
QCOMPARE(QFontPrivate::get(f2)->engineData->ref.load(), 1 + refs_by_cache);
f2.setKerning(!f.kerning());
QVERIFY(QFontPrivate::get(f2) != QFontPrivate::get(f));
QCOMPARE(QFontPrivate::get(f2)->ref.load(), 1);
QVERIFY(QFontPrivate::get(f2)->engineData);
- QVERIFY(QFontPrivate::get(f2)->engineData == QFontPrivate::get(f)->engineData);
+ QCOMPARE(QFontPrivate::get(f2)->engineData, QFontPrivate::get(f)->engineData);
QCOMPARE(QFontPrivate::get(f2)->engineData->ref.load(), 2 + refs_by_cache);
f2 = f;
- QVERIFY(QFontPrivate::get(f2) == QFontPrivate::get(f));
+ QCOMPARE(QFontPrivate::get(f2), QFontPrivate::get(f));
QCOMPARE(QFontPrivate::get(f2)->ref.load(), 2);
QVERIFY(QFontPrivate::get(f2)->engineData);
- QVERIFY(QFontPrivate::get(f2)->engineData == QFontPrivate::get(f)->engineData);
+ QCOMPARE(QFontPrivate::get(f2)->engineData, QFontPrivate::get(f)->engineData);
QCOMPARE(QFontPrivate::get(f2)->engineData->ref.load(), 1 + refs_by_cache);
if (f.pointSize() > 0)
diff --git a/tests/auto/gui/text/qrawfont/BLACKLIST b/tests/auto/gui/text/qrawfont/BLACKLIST
new file mode 100644
index 0000000000..a614595689
--- /dev/null
+++ b/tests/auto/gui/text/qrawfont/BLACKLIST
@@ -0,0 +1,4 @@
+[correctFontData]
+osx-10.8
+[unsupportedWritingSystem]
+osx-10.8
diff --git a/tests/auto/gui/text/qsyntaxhighlighter/tst_qsyntaxhighlighter.cpp b/tests/auto/gui/text/qsyntaxhighlighter/tst_qsyntaxhighlighter.cpp
index 014ed4c7c8..06448d11fe 100644
--- a/tests/auto/gui/text/qsyntaxhighlighter/tst_qsyntaxhighlighter.cpp
+++ b/tests/auto/gui/text/qsyntaxhighlighter/tst_qsyntaxhighlighter.cpp
@@ -120,7 +120,7 @@ void tst_QSyntaxHighlighter::cleanup()
class TestHighlighter : public QSyntaxHighlighter
{
public:
- inline TestHighlighter(const QList<QTextLayout::FormatRange> &fmts, QTextDocument *parent)
+ inline TestHighlighter(const QVector<QTextLayout::FormatRange> &fmts, QTextDocument *parent)
: QSyntaxHighlighter(parent), formats(fmts), highlighted(false), callCount(0) {}
inline TestHighlighter(QObject *parent)
: QSyntaxHighlighter(parent) {}
@@ -138,24 +138,15 @@ public:
++callCount;
}
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
bool highlighted;
int callCount;
QString highlightedText;
};
-QT_BEGIN_NAMESPACE
-bool operator==(const QTextLayout::FormatRange &lhs, const QTextLayout::FormatRange &rhs)
-{
- return lhs.start == rhs.start
- && lhs.length == rhs.length
- && lhs.format == rhs.format;
-}
-QT_END_NAMESPACE
-
void tst_QSyntaxHighlighter::basic()
{
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 2;
@@ -179,7 +170,7 @@ void tst_QSyntaxHighlighter::basic()
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
- QVERIFY(doc->begin().layout()->additionalFormats() == formats);
+ QCOMPARE(doc->begin().layout()->formats(), formats);
}
class CommentTestHighlighter : public QSyntaxHighlighter
@@ -222,7 +213,7 @@ void tst_QSyntaxHighlighter::basicTwo()
void tst_QSyntaxHighlighter::removeFormatsOnDelete()
{
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 9;
@@ -237,9 +228,9 @@ void tst_QSyntaxHighlighter::removeFormatsOnDelete()
QVERIFY(lout->documentChangedCalled);
lout->documentChangedCalled = false;
- QVERIFY(!doc->begin().layout()->additionalFormats().isEmpty());
+ QVERIFY(!doc->begin().layout()->formats().isEmpty());
delete hl;
- QVERIFY(doc->begin().layout()->additionalFormats().isEmpty());
+ QVERIFY(doc->begin().layout()->formats().isEmpty());
QVERIFY(lout->documentChangedCalled);
}
@@ -405,7 +396,7 @@ void tst_QSyntaxHighlighter::highlightToEndOfDocument2()
void tst_QSyntaxHighlighter::preservePreeditArea()
{
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 8;
@@ -432,12 +423,12 @@ void tst_QSyntaxHighlighter::preservePreeditArea()
hl->callCount = 0;
cursor.beginEditBlock();
- layout->setAdditionalFormats(formats);
+ layout->setFormats(formats);
cursor.endEditBlock();
QCOMPARE(hl->callCount, 1);
- formats = layout->additionalFormats();
+ formats = layout->formats();
QCOMPARE(formats.count(), 3);
range = formats.at(0);
@@ -483,7 +474,7 @@ void tst_QSyntaxHighlighter::avoidUnnecessaryRehighlight()
void tst_QSyntaxHighlighter::noContentsChangedDuringHighlight()
{
- QList<QTextLayout::FormatRange> formats;
+ QVector<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 10;
diff --git a/tests/auto/gui/text/qtextblock/tst_qtextblock.cpp b/tests/auto/gui/text/qtextblock/tst_qtextblock.cpp
index 967fe3114e..49300871d9 100644
--- a/tests/auto/gui/text/qtextblock/tst_qtextblock.cpp
+++ b/tests/auto/gui/text/qtextblock/tst_qtextblock.cpp
@@ -102,7 +102,7 @@ void tst_QTextBlock::fragmentOverBlockBoundaries()
// Block separators are always a fragment of their self. Thus:
// |Hello|\b|World|\b|
#if !defined(Q_OS_WIN)
- QVERIFY(doc->docHandle()->fragmentMap().numNodes() == 4);
+ QCOMPARE(doc->docHandle()->fragmentMap().numNodes(), 4);
#endif
QCOMPARE(cursor.block().text(), QString("Hello"));
cursor.movePosition(QTextCursor::NextBlock);
@@ -126,7 +126,7 @@ void tst_QTextBlock::excludeParagraphSeparatorFragment()
++it;
QVERIFY(it.atEnd());
- QVERIFY(it == block.end());
+ QCOMPARE(it, block.end());
}
void tst_QTextBlock::backwardsBlockIterator()
diff --git a/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp b/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
index 42b3c53bc5..9396cd678b 100644
--- a/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
+++ b/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
@@ -178,15 +178,15 @@ void tst_QTextCursor::navigation1()
QVERIFY(doc->toPlainText() == "Hello World");
cursor.movePosition(QTextCursor::End);
- QVERIFY(cursor.position() == 11);
+ QCOMPARE(cursor.position(), 11);
cursor.deletePreviousChar();
- QVERIFY(cursor.position() == 10);
+ QCOMPARE(cursor.position(), 10);
cursor.deletePreviousChar();
cursor.deletePreviousChar();
cursor.deletePreviousChar();
cursor.deletePreviousChar();
cursor.deletePreviousChar();
- QVERIFY(doc->toPlainText() == "Hello");
+ QCOMPARE(doc->toPlainText(), QLatin1String("Hello"));
QTextCursor otherCursor(doc);
otherCursor.movePosition(QTextCursor::Start);
@@ -195,12 +195,12 @@ void tst_QTextCursor::navigation1()
cursor.movePosition(QTextCursor::Right);
QVERIFY(cursor != otherCursor);
otherCursor.insertText("Hey");
- QVERIFY(cursor.position() == 5);
+ QCOMPARE(cursor.position(), 5);
doc->undo();
- QVERIFY(cursor.position() == 2);
+ QCOMPARE(cursor.position(), 2);
doc->redo();
- QVERIFY(cursor.position() == 5);
+ QCOMPARE(cursor.position(), 5);
doc->undo();
@@ -209,29 +209,29 @@ void tst_QTextCursor::navigation1()
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 6);
- QVERIFY(cursor.position() == 6);
+ QCOMPARE(cursor.position(), 6);
otherCursor = cursor;
otherCursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 2);
otherCursor.deletePreviousChar();
otherCursor.deletePreviousChar();
otherCursor.deletePreviousChar();
- QVERIFY(cursor.position() == 5);
+ QCOMPARE(cursor.position(), 5);
cursor.movePosition(QTextCursor::End);
cursor.insertBlock();
{
int oldPos = cursor.position();
cursor.movePosition(QTextCursor::End);
- QVERIFY(cursor.position() == oldPos);
+ QCOMPARE(cursor.position(), oldPos);
}
QVERIFY(cursor.atBlockStart());
- QVERIFY(cursor.position() == 9);
+ QCOMPARE(cursor.position(), 9);
QTextCharFormat fmt;
fmt.setForeground(Qt::blue);
cursor.insertText("Test", fmt);
- QVERIFY(fmt == cursor.charFormat());
- QVERIFY(cursor.position() == 13);
+ QCOMPARE(fmt, cursor.charFormat());
+ QCOMPARE(cursor.position(), 13);
}
void tst_QTextCursor::navigation2_data()
@@ -497,7 +497,7 @@ void tst_QTextCursor::navigation10()
QVERIFY(ok);
QCOMPARE(cursor.position(), 99);
ok = cursor.movePosition(QTextCursor::NextCell);
- QVERIFY(ok == false);
+ QVERIFY(!ok);
QCOMPARE(cursor.position(), 99); // didn't move.
QVERIFY(cursor.currentTable());
@@ -573,8 +573,8 @@ void tst_QTextCursor::insertBlock()
QTextBlockFormat fmt;
fmt.setTopMargin(100);
cursor.insertBlock(fmt);
- QVERIFY(cursor.position() == 1);
- QVERIFY(cursor.blockFormat() == fmt);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(cursor.blockFormat(), fmt);
}
void tst_QTextCursor::insertWithBlockSeparator1()
@@ -584,28 +584,28 @@ void tst_QTextCursor::insertWithBlockSeparator1()
cursor.insertText(text);
cursor.movePosition(QTextCursor::PreviousBlock);
- QVERIFY(cursor.position() == 0);
+ QCOMPARE(cursor.position(), 0);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 6);
+ QCOMPARE(cursor.position(), 6);
}
void tst_QTextCursor::insertWithBlockSeparator2()
{
cursor.insertText(QString(QChar::ParagraphSeparator));
- QVERIFY(cursor.position() == 1);
+ QCOMPARE(cursor.position(), 1);
}
void tst_QTextCursor::insertWithBlockSeparator3()
{
cursor.insertText(QString(QChar::ParagraphSeparator) + "Hi" + QString(QChar::ParagraphSeparator));
- QVERIFY(cursor.position() == 4);
+ QCOMPARE(cursor.position(), 4);
}
void tst_QTextCursor::insertWithBlockSeparator4()
{
cursor.insertText(QString(QChar::ParagraphSeparator) + QString(QChar::ParagraphSeparator));
- QVERIFY(cursor.position() == 2);
+ QCOMPARE(cursor.position(), 2);
}
void tst_QTextCursor::clearObjectType1()
@@ -656,7 +656,7 @@ void tst_QTextCursor::comparisonOperators1()
midCursor.movePosition(QTextCursor::NextWord);
QVERIFY(midCursor <= cursor);
- QVERIFY(midCursor == cursor);
+ QCOMPARE(midCursor, cursor);
QVERIFY(midCursor >= cursor);
QVERIFY(midCursor > startCursor);
@@ -690,7 +690,7 @@ void tst_QTextCursor::comparisonOperators2()
QTextCursor cursor2(&doc2);
QVERIFY(cursor1 != cursor2);
- QVERIFY(cursor1 == QTextCursor(&doc1));
+ QCOMPARE(cursor1, QTextCursor(&doc1));
}
void tst_QTextCursor::selection1()
@@ -718,97 +718,97 @@ void tst_QTextCursor::dontCopyTableAttributes()
void tst_QTextCursor::checkFrame1()
{
- QVERIFY(cursor.position() == 0);
+ QCOMPARE(cursor.position(), 0);
QPointer<QTextFrame> frame = cursor.insertFrame(QTextFrameFormat());
QVERIFY(frame != 0);
QTextFrame *root = frame->parentFrame();
QVERIFY(root != 0);
- QVERIFY(frame->firstPosition() == 1);
- QVERIFY(frame->lastPosition() == 1);
+ QCOMPARE(frame->firstPosition(), 1);
+ QCOMPARE(frame->lastPosition(), 1);
QVERIFY(frame->parentFrame() != 0);
- QVERIFY(root->childFrames().size() == 1);
+ QCOMPARE(root->childFrames().size(), 1);
- QVERIFY(cursor.position() == 1);
- QVERIFY(cursor.selectionStart() == 1);
- QVERIFY(cursor.selectionEnd() == 1);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(cursor.selectionStart(), 1);
+ QCOMPARE(cursor.selectionEnd(), 1);
doc->undo();
QVERIFY(!frame);
- QVERIFY(root->childFrames().size() == 0);
+ QCOMPARE(root->childFrames().size(), 0);
- QVERIFY(cursor.position() == 0);
- QVERIFY(cursor.selectionStart() == 0);
- QVERIFY(cursor.selectionEnd() == 0);
+ QCOMPARE(cursor.position(), 0);
+ QCOMPARE(cursor.selectionStart(), 0);
+ QCOMPARE(cursor.selectionEnd(), 0);
doc->redo();
frame = doc->frameAt(1);
QVERIFY(frame);
- QVERIFY(frame->firstPosition() == 1);
- QVERIFY(frame->lastPosition() == 1);
+ QCOMPARE(frame->firstPosition(), 1);
+ QCOMPARE(frame->lastPosition(), 1);
QVERIFY(frame->parentFrame() != 0);
- QVERIFY(root->childFrames().size() == 1);
+ QCOMPARE(root->childFrames().size(), 1);
- QVERIFY(cursor.position() == 1);
- QVERIFY(cursor.selectionStart() == 1);
- QVERIFY(cursor.selectionEnd() == 1);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(cursor.selectionStart(), 1);
+ QCOMPARE(cursor.selectionEnd(), 1);
// cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
-// QVERIFY(cursor.position() == 2);
-// QVERIFY(cursor.selectionStart() == 0);
-// QVERIFY(cursor.selectionEnd() == 2);
+// QCOMPARE(cursor.position(), 2);
+// QCOMPARE(cursor.selectionStart(), 0);
+// QCOMPARE(cursor.selectionEnd(), 2);
}
void tst_QTextCursor::checkFrame2()
{
- QVERIFY(cursor.position() == 0);
+ QCOMPARE(cursor.position(), 0);
cursor.insertText("A");
- QVERIFY(cursor.position() == 1);
+ QCOMPARE(cursor.position(), 1);
cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor);
QPointer<QTextFrame> frame = cursor.insertFrame(QTextFrameFormat());
QTextFrame *root = frame->parentFrame();
- QVERIFY(frame->firstPosition() == 1);
- QVERIFY(frame->lastPosition() == 2);
+ QCOMPARE(frame->firstPosition(), 1);
+ QCOMPARE(frame->lastPosition(), 2);
QVERIFY(frame->parentFrame() != 0);
- QVERIFY(root->childFrames().size() == 1);
+ QCOMPARE(root->childFrames().size(), 1);
- QVERIFY(cursor.position() == 1);
- QVERIFY(cursor.selectionStart() == 1);
- QVERIFY(cursor.selectionEnd() == 2);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(cursor.selectionStart(), 1);
+ QCOMPARE(cursor.selectionEnd(), 2);
doc->undo();
QVERIFY(!frame);
- QVERIFY(root->childFrames().size() == 0);
+ QCOMPARE(root->childFrames().size(), 0);
- QVERIFY(cursor.position() == 0);
- QVERIFY(cursor.selectionStart() == 0);
- QVERIFY(cursor.selectionEnd() == 1);
+ QCOMPARE(cursor.position(), 0);
+ QCOMPARE(cursor.selectionStart(), 0);
+ QCOMPARE(cursor.selectionEnd(), 1);
doc->redo();
frame = doc->frameAt(1);
QVERIFY(frame);
- QVERIFY(frame->firstPosition() == 1);
- QVERIFY(frame->lastPosition() == 2);
+ QCOMPARE(frame->firstPosition(), 1);
+ QCOMPARE(frame->lastPosition(), 2);
QVERIFY(frame->parentFrame() != 0);
- QVERIFY(root->childFrames().size() == 1);
+ QCOMPARE(root->childFrames().size(), 1);
- QVERIFY(cursor.position() == 1);
- QVERIFY(cursor.selectionStart() == 1);
- QVERIFY(cursor.selectionEnd() == 2);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(cursor.selectionStart(), 1);
+ QCOMPARE(cursor.selectionEnd(), 2);
cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
- QVERIFY(cursor.position() == 0);
- QVERIFY(cursor.selectionStart() == 0);
- QVERIFY(cursor.selectionEnd() == 3);
+ QCOMPARE(cursor.position(), 0);
+ QCOMPARE(cursor.selectionStart(), 0);
+ QCOMPARE(cursor.selectionEnd(), 3);
}
void tst_QTextCursor::insertBlockToUseCharFormat()
@@ -833,9 +833,9 @@ void tst_QTextCursor::insertBlockToUseCharFormat()
void tst_QTextCursor::tableMovement()
{
- QVERIFY(cursor.position() == 0);
+ QCOMPARE(cursor.position(), 0);
cursor.insertText("AA");
- QVERIFY(cursor.position() == 2);
+ QCOMPARE(cursor.position(), 2);
cursor.movePosition(QTextCursor::Left);
cursor.insertTable(3, 3);
@@ -1030,7 +1030,7 @@ void tst_QTextCursor::insertBlockShouldRemoveSelection()
cursor.insertBlock();
QVERIFY(!cursor.hasSelection());
- QVERIFY(doc->toPlainText().indexOf("Hello") == -1);
+ QCOMPARE(doc->toPlainText().indexOf("Hello"), -1);
}
void tst_QTextCursor::insertBlockShouldRemoveSelection2()
@@ -1046,7 +1046,7 @@ void tst_QTextCursor::insertBlockShouldRemoveSelection2()
cursor.insertBlock(fmt);
QVERIFY(!cursor.hasSelection());
- QVERIFY(doc->toPlainText().indexOf("Hello") == -1);
+ QCOMPARE(doc->toPlainText().indexOf("Hello"), -1);
}
void tst_QTextCursor::mergeCellShouldUpdateSelection()
@@ -1159,7 +1159,7 @@ void tst_QTextCursor::setBlockFormatInTable()
cursor.setBlockFormat(fmt);
cursor.movePosition(QTextCursor::Start);
- QVERIFY(cursor.blockFormat().background().color() == Qt::blue);
+ QCOMPARE(cursor.blockFormat().background().color(), QColor(Qt::blue));
}
void tst_QTextCursor::blockCharFormat2()
@@ -1174,7 +1174,7 @@ void tst_QTextCursor::blockCharFormat2()
cursor.movePosition(QTextCursor::Start);
cursor.insertText("Red");
cursor.movePosition(QTextCursor::PreviousCharacter);
- QVERIFY(cursor.charFormat().foreground().color() == Qt::red);
+ QCOMPARE(cursor.charFormat().foreground().color(), QColor(Qt::red));
}
void tst_QTextCursor::blockCharFormat3()
@@ -1189,21 +1189,23 @@ void tst_QTextCursor::blockCharFormat3()
cursor.insertText("Test");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
- QVERIFY(cursor.charFormat().foreground().color() == Qt::green);
+ const QColor red(Qt::red);
+ const QColor green(Qt::green);
+ QCOMPARE(cursor.charFormat().foreground().color(), green);
cursor.movePosition(QTextCursor::Start);
- QVERIFY(cursor.charFormat().foreground().color() == Qt::green);
+ QCOMPARE(cursor.charFormat().foreground().color(), green);
fmt.setForeground(Qt::red);
cursor.setBlockCharFormat(fmt);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::red);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), red);
cursor.movePosition(QTextCursor::End);
cursor.movePosition(QTextCursor::Start);
- QVERIFY(cursor.charFormat().foreground().color() == Qt::green);
+ QCOMPARE(cursor.charFormat().foreground().color(), green);
cursor.insertText("Test");
- QVERIFY(cursor.charFormat().foreground().color() == Qt::green);
+ QCOMPARE(cursor.charFormat().foreground().color(), green);
cursor.select(QTextCursor::Document);
cursor.removeSelectedText();
@@ -1212,7 +1214,7 @@ void tst_QTextCursor::blockCharFormat3()
QVERIFY(cursor.atStart());
cursor.insertText("Test");
- QVERIFY(cursor.charFormat().foreground().color() == Qt::red);
+ QCOMPARE(cursor.charFormat().foreground().color(), red);
}
void tst_QTextCursor::blockCharFormat()
@@ -1222,12 +1224,12 @@ void tst_QTextCursor::blockCharFormat()
cursor.insertBlock(QTextBlockFormat(), fmt);
cursor.insertText("Hm");
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::blue);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::blue));
fmt.setForeground(Qt::red);
cursor.setBlockCharFormat(fmt);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::red);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::red));
}
void tst_QTextCursor::blockCharFormatOnSelection()
@@ -1249,11 +1251,11 @@ void tst_QTextCursor::blockCharFormatOnSelection()
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::blue);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::blue));
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::red);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::red));
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::white);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::white));
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextBlock);
@@ -1264,17 +1266,17 @@ void tst_QTextCursor::blockCharFormatOnSelection()
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::cyan);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::cyan));
cursor.movePosition(QTextCursor::Right);
cursor.movePosition(QTextCursor::Right);
- QVERIFY(cursor.charFormat().foreground().color() == Qt::green);
+ QCOMPARE(cursor.charFormat().foreground().color(), QColor(Qt::green));
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::cyan);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::cyan));
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockCharFormat().foreground().color() == Qt::white);
+ QCOMPARE(cursor.blockCharFormat().foreground().color(), QColor(Qt::white));
}
void tst_QTextCursor::anchorInitialized1()
@@ -1404,7 +1406,7 @@ void tst_QTextCursor::selectBlock()
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignHCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignHCenter);
QCOMPARE(cursor.block().text(), QString("blah"));
}
@@ -1449,7 +1451,7 @@ void tst_QTextCursor::insertFragmentShouldUseCurrentCharFormat()
cursor.insertFragment(fragment);
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
- QVERIFY(cursor.charFormat() == fmt);
+ QCOMPARE(cursor.charFormat(), fmt);
}
int tst_QTextCursor::blockCount()
@@ -1910,15 +1912,15 @@ void tst_QTextCursor::cursorPositionWithBlockUndoAndRedo()
int cursorPositionAfter = cursor.position();
cursor.endEditBlock();
- QVERIFY(doc->toPlainText() == "*AAAA*BBBB*CCCC*DDDD");
+ QCOMPARE(doc->toPlainText(), QLatin1String("*AAAA*BBBB*CCCC*DDDD"));
QCOMPARE(12, cursorPositionBefore);
QCOMPARE(1, cursorPositionAfter);
doc->undo(&cursor);
- QVERIFY(doc->toPlainText() == "AAAABBBBCCCCDDDD");
+ QCOMPARE(doc->toPlainText(), QLatin1String("AAAABBBBCCCCDDDD"));
QCOMPARE(cursor.position(), cursorPositionBefore);
doc->redo(&cursor);
- QVERIFY(doc->toPlainText() == "*AAAA*BBBB*CCCC*DDDD");
+ QCOMPARE(doc->toPlainText(), QLatin1String("*AAAA*BBBB*CCCC*DDDD"));
QCOMPARE(cursor.position(), cursorPositionAfter);
}
@@ -1932,11 +1934,11 @@ void tst_QTextCursor::cursorPositionWithBlockUndoAndRedo2()
cursor.insertText("AAAABBBBCCCCDDDD");
cursor.endEditBlock();
doc->undo(&cursor);
- QVERIFY(doc->toPlainText() == "AAAABBBB");
+ QCOMPARE(doc->toPlainText(), QLatin1String("AAAABBBB"));
QCOMPARE(cursor.position(), cursorPositionBefore);
cursor.insertText("CCCC");
- QVERIFY(doc->toPlainText() == "AAAABBBBCCCC");
+ QCOMPARE(doc->toPlainText(), QLatin1String("AAAABBBBCCCC"));
cursorPositionBefore = cursor.position();
cursor.setPosition(0, QTextCursor::KeepAnchor);
@@ -1951,7 +1953,7 @@ void tst_QTextCursor::cursorPositionWithBlockUndoAndRedo2()
doc->undo(&cursor);
- QVERIFY(doc->toPlainText() == "AAAABBBBCCCC");
+ QCOMPARE(doc->toPlainText(), QLatin1String("AAAABBBBCCCC"));
QCOMPARE(cursor.position(), cursorPositionBefore);
}
diff --git a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp
index 5e6b606d83..7378ca85ee 100644
--- a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp
+++ b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp
@@ -744,7 +744,7 @@ void tst_QTextDocument::mightBeRichText()
{
QFETCH(QString, input);
QFETCH(bool, result);
- QVERIFY(result == Qt::mightBeRichText(input));
+ QCOMPARE(result, Qt::mightBeRichText(input));
}
Q_DECLARE_METATYPE(QTextDocumentFragment)
@@ -2222,7 +2222,7 @@ void tst_QTextDocument::clonePreservesUserStates()
b2 = b2.next();
QCOMPARE(b1.userState(), b2.userState());
}
- QVERIFY(b2 == clone->end());
+ QCOMPARE(b2, clone->end());
delete clone;
}
@@ -2269,7 +2269,7 @@ void tst_QTextDocument::resolvedFontInEmptyFormat()
doc->setDefaultFont(font);
QTextCharFormat fmt = doc->begin().charFormat();
QVERIFY(fmt.properties().isEmpty());
- QVERIFY(fmt.font() == font);
+ QCOMPARE(fmt.font(), font);
}
void tst_QTextDocument::defaultRootFrameMargin()
@@ -2369,6 +2369,7 @@ void tst_QTextDocument::deleteTextObjectsOnClear()
void tst_QTextDocument::defaultStyleSheet()
{
+ const QColor green("green");
const QString sheet("p { background-color: green; }");
QVERIFY(doc->defaultStyleSheet().isEmpty());
doc->setDefaultStyleSheet(sheet);
@@ -2376,30 +2377,30 @@ void tst_QTextDocument::defaultStyleSheet()
cursor.insertHtml("<p>test");
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
doc->clear();
cursor.insertHtml("<p>test");
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
QTextDocument *clone = doc->clone();
QCOMPARE(clone->defaultStyleSheet(), sheet);
cursor = QTextCursor(clone);
cursor.insertHtml("<p>test");
fmt = clone->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
delete clone;
cursor = QTextCursor(doc);
cursor.insertHtml("<p>test");
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
doc->clear();
cursor.insertHtml("<style>p { background-color: red; }</style><p>test");
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("red"));
+ QCOMPARE(fmt.background().color(), QColor(Qt::red));
doc->clear();
doc->setDefaultStyleSheet("invalid style sheet....");
@@ -2567,7 +2568,7 @@ void tst_QTextDocument::setTextPreservesUndoRedoEnabled()
void tst_QTextDocument::firstLast()
{
QCOMPARE(doc->blockCount(), 1);
- QVERIFY(doc->firstBlock() == doc->lastBlock());
+ QCOMPARE(doc->firstBlock(), doc->lastBlock());
doc->setPlainText("Hello\nTest\nWorld");
@@ -3013,8 +3014,8 @@ void tst_QTextDocument::QTBUG27354_spaceAndSoftSpace()
QTextBlock block = td.begin();
while (block.isValid()) {
QTextBlockFormat fmt = block.blockFormat();
- QVERIFY(fmt.lineHeightType() == QTextBlockFormat::SingleHeight);
- QVERIFY(fmt.lineHeight() == 0);
+ QCOMPARE(fmt.lineHeightType(), int(QTextBlockFormat::SingleHeight));
+ QCOMPARE(fmt.lineHeight(), qreal(0));
block = block.next();
}
}
@@ -3164,8 +3165,8 @@ void tst_QTextDocument::cssInheritance()
QTextBlock block = td.begin();
while (block.isValid()) {
QTextBlockFormat fmt = block.blockFormat();
- QVERIFY(fmt.lineHeightType() == QTextBlockFormat::ProportionalHeight);
- QVERIFY(fmt.lineHeight() == 200);
+ QCOMPARE(fmt.lineHeightType(), int(QTextBlockFormat::ProportionalHeight));
+ QCOMPARE(fmt.lineHeight(), qreal(200));
block = block.next();
}
}
@@ -3175,12 +3176,12 @@ void tst_QTextDocument::cssInheritance()
"<p style=\"line-height: 40px\">Foo</p><p>Bar</p><p>Baz</p></body></html>");
QTextBlock block = td.begin();
QTextBlockFormat fmt = block.blockFormat();
- QVERIFY(fmt.lineHeightType() == QTextBlockFormat::FixedHeight);
- QVERIFY(fmt.lineHeight() == 40);
+ QCOMPARE(fmt.lineHeightType(), int(QTextBlockFormat::FixedHeight));
+ QCOMPARE(fmt.lineHeight(), qreal(40));
block = block.next();
fmt = block.blockFormat();
- QVERIFY(fmt.lineHeightType() == QTextBlockFormat::ProportionalHeight);
- QVERIFY(fmt.lineHeight() == 300);
+ QCOMPARE(fmt.lineHeightType(), int(QTextBlockFormat::ProportionalHeight));
+ QCOMPARE(fmt.lineHeight(), qreal(300));
}
{
QTextDocument td;
@@ -3188,7 +3189,7 @@ void tst_QTextDocument::cssInheritance()
"<p>Foo</p><p>Bar</p><p>Baz</p></body></html>");
QTextBlock block = td.begin();
while (block.isValid()) {
- QVERIFY(block.blockFormat().background() == QBrush());
+ QCOMPARE(block.blockFormat().background(), QBrush());
QVERIFY(block.charFormat().font().bold());
block = block.next();
}
diff --git a/tests/auto/gui/text/qtextdocumentfragment/tst_qtextdocumentfragment.cpp b/tests/auto/gui/text/qtextdocumentfragment/tst_qtextdocumentfragment.cpp
index 8f0d306cba..1cd9d9bcbe 100644
--- a/tests/auto/gui/text/qtextdocumentfragment/tst_qtextdocumentfragment.cpp
+++ b/tests/auto/gui/text/qtextdocumentfragment/tst_qtextdocumentfragment.cpp
@@ -727,7 +727,7 @@ void tst_QTextDocumentFragment::html_listIndents5()
QCOMPARE(list->format().indent(), 1);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.currentList() == list);
+ QCOMPARE(cursor.currentList(), list);
QCOMPARE(cursor.blockFormat().indent(), 0);
}
@@ -778,7 +778,7 @@ void tst_QTextDocumentFragment::blockCharFormatCopied()
cleanup();
init();
cursor.insertFragment(frag);
- QVERIFY(cursor.blockCharFormat() == fmt);
+ QCOMPARE(cursor.blockCharFormat(), fmt);
}
void tst_QTextDocumentFragment::initialBlock()
@@ -794,19 +794,19 @@ void tst_QTextDocumentFragment::clone()
mod.setAlignment(Qt::AlignCenter);
cursor.mergeBlockFormat(mod);
cursor.insertText("Blah");
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignCenter);
QTextDocumentFragment frag(doc);
cleanup();
init();
cursor.insertFragment(frag);
cursor.movePosition(QTextCursor::Start);
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignCenter);
}
void tst_QTextDocumentFragment::dontRemoveInitialBlockIfItHoldsObjectIndexedCharFormat()
{
const char html[] = "<table><tr><td>cell one<td>cell two</tr><tr><td>cell three<td>cell four</tr></table>";
- QVERIFY(doc->begin().charFormat().objectIndex() == -1);
+ QCOMPARE(doc->begin().charFormat().objectIndex(), -1);
setHtml(QString::fromLatin1(html));
int cnt = 0;
@@ -841,13 +841,13 @@ void tst_QTextDocumentFragment::unorderedListEnumeration()
setHtml(QString::fromLatin1(html));
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListDisc);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListDisc);
const char html2[] = "<ul><ul><ul type=circle><li>Blah</li></ul></ul>";
setHtml(QString::fromLatin1(html2));
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListCircle);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListCircle);
}
@@ -873,7 +873,7 @@ void tst_QTextDocumentFragment::hrefAnchor()
setHtml(QString::fromLatin1(html));
QVERIFY(doc->begin().begin().fragment().charFormat().isAnchor());
QCOMPARE(doc->begin().begin().fragment().charFormat().anchorHref(), QString::fromLatin1("test"));
- QVERIFY(doc->begin().begin().fragment().charFormat().fontUnderline() == true);
+ QVERIFY(doc->begin().begin().fragment().charFormat().fontUnderline());
}
{
@@ -881,7 +881,7 @@ void tst_QTextDocumentFragment::hrefAnchor()
const char html[] = "<a>blah</a>";
setHtml(QString::fromLatin1(html));
QVERIFY(doc->begin().begin().fragment().charFormat().isAnchor());
- QVERIFY(doc->begin().begin().fragment().charFormat().fontUnderline() == false);
+ QVERIFY(!doc->begin().begin().fragment().charFormat().fontUnderline());
}
}
@@ -901,7 +901,7 @@ void tst_QTextDocumentFragment::namedAnchorFragments()
// the 'a'
QVERIFY(it.fragment().isValid());
QCOMPARE(it.fragment().text(), QString::fromLatin1("a"));
- QVERIFY(it.fragment().charFormat().isAnchor() == false);
+ QVERIFY(!it.fragment().charFormat().isAnchor());
// the 'b' of 'blah' as separate fragment with the anchor attribute
++it;
@@ -913,7 +913,7 @@ void tst_QTextDocumentFragment::namedAnchorFragments()
++it;
QVERIFY(it.fragment().isValid());
QVERIFY(it.fragment().text().startsWith("lah"));
- QVERIFY(it.fragment().charFormat().isAnchor() == false);
+ QVERIFY(!it.fragment().charFormat().isAnchor());
}
void tst_QTextDocumentFragment::namedAnchorFragments2()
@@ -982,7 +982,7 @@ void tst_QTextDocumentFragment::cellBlockCount()
int blockCount = 0;
for (QTextFrame::iterator it = cell.begin(); !it.atEnd(); ++it) {
- QVERIFY(it.currentFrame() == 0);
+ QVERIFY(!it.currentFrame());
QVERIFY(it.currentBlock().isValid());
++blockCount;
}
@@ -1003,7 +1003,7 @@ void tst_QTextDocumentFragment::cellBlockCount2()
int blockCount = 0;
for (QTextFrame::iterator it = cell.begin(); !it.atEnd(); ++it) {
- QVERIFY(it.currentFrame() == 0);
+ QVERIFY(!it.currentFrame());
QVERIFY(it.currentBlock().isValid());
++blockCount;
}
@@ -1037,7 +1037,7 @@ void tst_QTextDocumentFragment::emptyTable3()
QCOMPARE(table->columns(), 2);
QTextTableCell cell = table->cellAt(0, 0);
QVERIFY(cell.isValid());
- QVERIFY(cell.firstPosition() == cell.lastPosition());
+ QCOMPARE(cell.firstPosition(), cell.lastPosition());
cell = table->cellAt(0, 1);
QTextCursor cursor = cell.firstCursorPosition();
cursor.setPosition(cell.lastPosition(), QTextCursor::KeepAnchor);
@@ -1065,7 +1065,7 @@ void tst_QTextDocumentFragment::inheritAlignment()
const char html[] = "<body align=right><p>Hey";
setHtml(QString::fromLatin1(html));
// html alignment is absolute
- QVERIFY(doc->begin().blockFormat().alignment() == Qt::Alignment(Qt::AlignRight|Qt::AlignAbsolute));
+ QCOMPARE(doc->begin().blockFormat().alignment(), Qt::Alignment(Qt::AlignRight|Qt::AlignAbsolute));
}
void tst_QTextDocumentFragment::dontEmitEmptyNodeWhenEmptyTagIsFollowedByCloseTag()
@@ -1073,8 +1073,8 @@ void tst_QTextDocumentFragment::dontEmitEmptyNodeWhenEmptyTagIsFollowedByCloseTa
// make sure the Hey does not end up as tag text for the img tag
const char html[] = "<body align=right><p align=left>Blah<img></img><p>Hey";
setHtml(QString::fromLatin1(html));
- QVERIFY(doc->begin().blockFormat().alignment() == Qt::Alignment(Qt::AlignLeft|Qt::AlignAbsolute));
- QVERIFY(doc->begin().next().blockFormat().alignment() == Qt::Alignment(Qt::AlignRight|Qt::AlignAbsolute));
+ QCOMPARE(doc->begin().blockFormat().alignment(), Qt::Alignment(Qt::AlignLeft|Qt::AlignAbsolute));
+ QCOMPARE(doc->begin().next().blockFormat().alignment(), Qt::Alignment(Qt::AlignRight|Qt::AlignAbsolute));
}
void tst_QTextDocumentFragment::toPlainText()
@@ -1378,8 +1378,8 @@ void tst_QTextDocumentFragment::html_listStart1()
{
// don't create a block for the <ul> element, even if there's some whitespace between
// it and the <li>
- const char html[] = "<ul> <li>list item</li><ul>";
- cursor.insertFragment(QTextDocumentFragment::fromHtml(QByteArray::fromRawData(html, sizeof(html) / sizeof(html[0]))));
+ const QString html = QStringLiteral("<ul> <li>list item</li><ul>");
+ cursor.insertFragment(QTextDocumentFragment::fromHtml(html));
QCOMPARE(doc->blockCount(), 1);
}
@@ -1387,8 +1387,8 @@ void tst_QTextDocumentFragment::html_listStart1()
void tst_QTextDocumentFragment::html_listStart2()
{
// unlike with html_listStart1 we want a block showing the 'buggy' text here
- const char html[] = "<ul>buggy, but text should appear<li>list item</li><ul>";
- cursor.insertFragment(QTextDocumentFragment::fromHtml(QByteArray::fromRawData(html, sizeof(html) / sizeof(html[0]))));
+ const QString html = QStringLiteral("<ul>buggy, but text should appear<li>list item</li><ul>");
+ cursor.insertFragment(QTextDocumentFragment::fromHtml(html));
QCOMPARE(doc->blockCount(), 2);
}
@@ -1480,19 +1480,19 @@ void tst_QTextDocumentFragment::html_subAndSuperScript()
const char alignmentInherited[] = "<sub><font face=\"Verdana\">Subby</font></sub>";
setHtml(subHtml);
- QVERIFY(cursor.charFormat().verticalAlignment() == QTextCharFormat::AlignSubScript);
+ QCOMPARE(cursor.charFormat().verticalAlignment(), QTextCharFormat::AlignSubScript);
setHtml(subHtmlCss);
- QVERIFY(cursor.charFormat().verticalAlignment() == QTextCharFormat::AlignSubScript);
+ QCOMPARE(cursor.charFormat().verticalAlignment(), QTextCharFormat::AlignSubScript);
setHtml(superHtml);
- QVERIFY(cursor.charFormat().verticalAlignment() == QTextCharFormat::AlignSuperScript);
+ QCOMPARE(cursor.charFormat().verticalAlignment(), QTextCharFormat::AlignSuperScript);
setHtml(superHtmlCss);
- QVERIFY(cursor.charFormat().verticalAlignment() == QTextCharFormat::AlignSuperScript);
+ QCOMPARE(cursor.charFormat().verticalAlignment(), QTextCharFormat::AlignSuperScript);
setHtml(alignmentInherited);
- QVERIFY(cursor.charFormat().verticalAlignment() == QTextCharFormat::AlignSubScript);
+ QCOMPARE(cursor.charFormat().verticalAlignment(), QTextCharFormat::AlignSubScript);
}
void tst_QTextDocumentFragment::html_cssColors()
@@ -1695,7 +1695,7 @@ void tst_QTextDocumentFragment::html_bodyBackground()
const char html[] = "<body background=\"foo.png\">Foo</body>";
doc->setHtml(html);
- QVERIFY(doc->rootFrame()->frameFormat().background().style() == Qt::TexturePattern);
+ QCOMPARE(doc->rootFrame()->frameFormat().background().style(), Qt::TexturePattern);
}
void tst_QTextDocumentFragment::html_tableCellBackground()
@@ -1709,7 +1709,7 @@ void tst_QTextDocumentFragment::html_tableCellBackground()
QVERIFY(table);
QTextTableCell cell = table->cellAt(0, 0);
- QVERIFY(cell.format().background().style() == Qt::TexturePattern);
+ QCOMPARE(cell.format().background().style(), Qt::TexturePattern);
}
void tst_QTextDocumentFragment::css_bodyBackground()
@@ -1717,7 +1717,7 @@ void tst_QTextDocumentFragment::css_bodyBackground()
const char html[] = "<body style=\"background-image:url('foo.png')\">Foo</body>";
doc->setHtml(html);
- QVERIFY(doc->rootFrame()->frameFormat().background().style() == Qt::TexturePattern);
+ QCOMPARE(doc->rootFrame()->frameFormat().background().style(), Qt::TexturePattern);
}
void tst_QTextDocumentFragment::css_tableCellBackground()
@@ -1731,7 +1731,7 @@ void tst_QTextDocumentFragment::css_tableCellBackground()
QVERIFY(table);
QTextTableCell cell = table->cellAt(0, 0);
- QVERIFY(cell.format().background().style() == Qt::TexturePattern);
+ QCOMPARE(cell.format().background().style(), Qt::TexturePattern);
}
void tst_QTextDocumentFragment::css_cellPaddings()
@@ -1767,7 +1767,7 @@ void tst_QTextDocumentFragment::html_blockLevelDiv()
setHtml(html);
QCOMPARE(doc->begin().blockFormat().alignment(), Qt::AlignRight|Qt::AlignAbsolute);
- QVERIFY(doc->begin().next() == doc->end());
+ QCOMPARE(doc->begin().next(), doc->end());
}
void tst_QTextDocumentFragment::html_spanNesting()
@@ -1805,7 +1805,7 @@ void tst_QTextDocumentFragment::html_nestedLists()
cursor.movePosition(QTextCursor::NextBlock);
QTextList *thirdList = cursor.currentList();
QVERIFY(thirdList);
- QVERIFY(thirdList == firstList);
+ QCOMPARE(thirdList, firstList);
}
void tst_QTextDocumentFragment::noSpecialCharactersInPlainText()
@@ -1837,7 +1837,7 @@ void tst_QTextDocumentFragment::html_doNotInheritBackground()
for (QTextBlock block = doc->begin();
block.isValid(); block = block.next()) {
- QVERIFY(block.blockFormat().hasProperty(QTextFormat::BackgroundBrush) == false);
+ QVERIFY(!block.blockFormat().hasProperty(QTextFormat::BackgroundBrush));
}
QVERIFY(doc->rootFrame()->frameFormat().hasProperty(QTextFormat::BackgroundBrush));
@@ -2022,7 +2022,7 @@ void tst_QTextDocumentFragment::html_frameImport()
cursor.insertFragment(frag);
QList<QTextFrame *> childFrames = doc->rootFrame()->childFrames();
- QVERIFY(childFrames.count() == 1);
+ QCOMPARE(childFrames.count(), 1);
QTextFrame *frame = childFrames.first();
QCOMPARE(frame->frameFormat().margin(), ffmt.margin());
QCOMPARE(frame->frameFormat().border(), ffmt.border());
@@ -2050,7 +2050,7 @@ void tst_QTextDocumentFragment::html_frameImport2()
cursor.insertFragment(frag);
QList<QTextFrame *> childFrames = doc->rootFrame()->childFrames();
- QVERIFY(childFrames.count() == 1);
+ QCOMPARE(childFrames.count(), 1);
QTextFrame *frame = childFrames.first();
QCOMPARE(frame->frameFormat().topMargin(), ffmt.topMargin());
QCOMPARE(frame->frameFormat().bottomMargin(), ffmt.bottomMargin());
@@ -2065,7 +2065,7 @@ void tst_QTextDocumentFragment::html_dontAddMarginsAcrossTableCells()
cursor.insertFragment(QTextDocumentFragment::fromHtml(QString::fromLatin1(html)));
QList<QTextFrame *> childFrames = doc->rootFrame()->childFrames();
- QVERIFY(childFrames.count() == 1);
+ QCOMPARE(childFrames.count(), 1);
QTextFrame *frame = childFrames.first();
cursor = frame->firstCursorPosition();
QCOMPARE(cursor.blockFormat().leftMargin(), qreal(50.0));
@@ -2078,7 +2078,7 @@ void tst_QTextDocumentFragment::html_dontMergeCenterBlocks()
QCOMPARE(doc->blockCount(), 2);
QTextBlock blk = doc->begin();
- QVERIFY(blk.blockFormat().alignment() == Qt::AlignCenter);
+ QCOMPARE(blk.blockFormat().alignment(), Qt::AlignCenter);
blk = blk.next();
QVERIFY(blk.blockFormat().alignment() != Qt::AlignCenter);
}
@@ -2112,7 +2112,7 @@ void tst_QTextDocumentFragment::html_tableCellBgColor2()
QTextFrame::Iterator it = cell.begin();
QVERIFY(!it.atEnd());
- QVERIFY(it.currentFrame() == 0);
+ QVERIFY(!it.currentFrame());
QVERIFY(it.currentBlock().isValid());
++it;
@@ -2122,9 +2122,9 @@ void tst_QTextDocumentFragment::html_tableCellBgColor2()
++it;
QVERIFY(!it.atEnd());
- QVERIFY(it.currentFrame() == 0);
+ QVERIFY(!it.currentFrame());
QVERIFY(it.currentBlock().isValid());
- QVERIFY(it.currentBlock().blockFormat().background() == QBrush(Qt::NoBrush));
+ QCOMPARE(it.currentBlock().blockFormat().background(), QBrush(Qt::NoBrush));
++it;
QVERIFY(it.atEnd());
@@ -2245,8 +2245,8 @@ void tst_QTextDocumentFragment::html_blockVsInline()
{
{
setHtml("<html><body><div><b>Foo<div>Bar");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<html><body><p><b>Foo<p>Bar");
@@ -2255,23 +2255,23 @@ void tst_QTextDocumentFragment::html_blockVsInline()
}
{
setHtml("<html><body><b><center>Foo</center></b>");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<html><body><b><p>Foo");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<html><body><b><p>Foo<p>Bar");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<div><b>Foo<div>Bar");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<p><b>Foo<p>Bar");
@@ -2280,18 +2280,18 @@ void tst_QTextDocumentFragment::html_blockVsInline()
}
{
setHtml("<b><center>Foo</center></b>");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<b><p>Foo");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
{
setHtml("<b><p>Foo<p>Bar");
- QVERIFY(cursor.charFormat().fontWeight() == QFont::Bold);
- QVERIFY(cursor.blockCharFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(cursor.charFormat().fontWeight(), int(QFont::Bold));
+ QCOMPARE(cursor.blockCharFormat().fontWeight(), int(QFont::Bold));
}
}
@@ -2338,7 +2338,7 @@ void tst_QTextDocumentFragment::html_nestedTables()
QTextTable *firstNestedTable = cursor.currentTable();
QVERIFY(firstNestedTable);
- QVERIFY(firstNestedTable->parentFrame() == table);
+ QCOMPARE(firstNestedTable->parentFrame(), table);
QCOMPARE(firstNestedTable->rows(), 1);
QCOMPARE(firstNestedTable->columns(), 1);
QCOMPARE(firstNestedTable->cellAt(0, 0).firstCursorPosition().block().text(), QString("Hello"));
@@ -2348,13 +2348,13 @@ void tst_QTextDocumentFragment::html_nestedTables()
;
QVERIFY(!cursor.isNull());
- QVERIFY(cursor.currentTable() == table);
+ QCOMPARE(cursor.currentTable(), table);
cursor.movePosition(QTextCursor::NextBlock);
QTextTable *secondNestedTable = cursor.currentTable();
QVERIFY(secondNestedTable);
- QVERIFY(secondNestedTable->parentFrame() == table);
+ QCOMPARE(secondNestedTable->parentFrame(), table);
QCOMPARE(secondNestedTable->rows(), 1);
QCOMPARE(secondNestedTable->columns(), 1);
QCOMPARE(secondNestedTable->cellAt(0, 0).firstCursorPosition().block().text(), QString("World"));
@@ -2454,7 +2454,7 @@ void tst_QTextDocumentFragment::html_anchorColor()
setHtml("<span style=\"color: red;\"><a href=\"http://www.kde.org/\">Blue</a></span>");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
- QVERIFY(cursor.charFormat().foreground().color() == QGuiApplication::palette().link().color());
+ QCOMPARE(cursor.charFormat().foreground().color(), QGuiApplication::palette().link().color());
setHtml("<span style=\"color: red;\"><a href=\"http://www.kde.org/\" style=\"color: yellow;\">Green</a></span>");
cursor.movePosition(QTextCursor::Start);
@@ -2525,17 +2525,17 @@ void tst_QTextDocumentFragment::html_columnWidths()
const QVector<QTextLength> columnWidths = fmt.columnWidthConstraints();
QCOMPARE(columnWidths.count(), 2);
- QVERIFY(columnWidths.at(0).type() == QTextLength::VariableLength);
- QVERIFY(columnWidths.at(1).type() == QTextLength::PercentageLength);
- QVERIFY(columnWidths.at(1).rawValue() == 1);
+ QCOMPARE(columnWidths.at(0).type(), QTextLength::VariableLength);
+ QCOMPARE(columnWidths.at(1).type(), QTextLength::PercentageLength);
+ QCOMPARE(columnWidths.at(1).rawValue(), qreal(1));
}
void tst_QTextDocumentFragment::css_fontWeight()
{
setHtml("<p style=\"font-weight:bold\">blah</p>");
- QVERIFY(doc->begin().charFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(doc->begin().charFormat().fontWeight(), int(QFont::Bold));
setHtml("<p style=\"font-weight:600\">blah</p>");
- QVERIFY(doc->begin().charFormat().fontWeight() == QFont::Bold);
+ QCOMPARE(doc->begin().charFormat().fontWeight(), int(QFont::Bold));
}
@@ -2548,7 +2548,7 @@ void tst_QTextDocumentFragment::css_float()
QVERIFY(o);
QTextFormat f = o->format();
QVERIFY(f.isFrameFormat());
- QVERIFY(f.toFrameFormat().position() == QTextFrameFormat::FloatRight);
+ QCOMPARE(f.toFrameFormat().position(), QTextFrameFormat::FloatRight);
setHtml("<img src=\"foo\" align=right>");
fmt = doc->begin().begin().fragment().charFormat();
@@ -2557,7 +2557,7 @@ void tst_QTextDocumentFragment::css_float()
QVERIFY(o);
f = o->format();
QVERIFY(f.isFrameFormat());
- QVERIFY(f.toFrameFormat().position() == QTextFrameFormat::FloatRight);
+ QCOMPARE(f.toFrameFormat().position(), QTextFrameFormat::FloatRight);
setHtml("<img src=\"foo\" align=left>");
fmt = doc->begin().begin().fragment().charFormat();
@@ -2566,7 +2566,7 @@ void tst_QTextDocumentFragment::css_float()
QVERIFY(o);
f = o->format();
QVERIFY(f.isFrameFormat());
- QVERIFY(f.toFrameFormat().position() == QTextFrameFormat::FloatLeft);
+ QCOMPARE(f.toFrameFormat().position(), QTextFrameFormat::FloatLeft);
}
void tst_QTextDocumentFragment::css_textIndent()
@@ -2585,7 +2585,7 @@ void tst_QTextDocumentFragment::css_inline()
"<p>test</p>"
);
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
}
void tst_QTextDocumentFragment::css_external()
@@ -2596,11 +2596,12 @@ void tst_QTextDocumentFragment::css_external()
"<p>test</p>"
);
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
}
void tst_QTextDocumentFragment::css_import()
{
+ const QColor green("green");
doc->addResource(QTextDocument::StyleSheetResource, QUrl("test.css"), QString("@import \"other.css\";"));
doc->addResource(QTextDocument::StyleSheetResource, QUrl("other.css"), QString("@import url(\"other2.css\");"));
doc->addResource(QTextDocument::StyleSheetResource, QUrl("other2.css"), QString("p { background-color: green; }"));
@@ -2609,14 +2610,14 @@ void tst_QTextDocumentFragment::css_import()
"<p>test</p>"
);
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
doc->setHtml(""
"<style>@import \"test.css\" screen;</style>"
"<p>test</p>"
);
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
}
void tst_QTextDocumentFragment::css_selectors_data()
@@ -2662,9 +2663,9 @@ void tst_QTextDocumentFragment::css_selectors()
QTextBlockFormat fmt = doc->begin().blockFormat();
if (match)
- QVERIFY(fmt.background().color() == QColor("red"));
+ QCOMPARE(fmt.background().color(), QColor("red"));
else
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
}
void tst_QTextDocumentFragment::css_nodeNameCaseInsensitivity()
@@ -2674,7 +2675,7 @@ void tst_QTextDocumentFragment::css_nodeNameCaseInsensitivity()
"</style>"
"<p>test</p>");
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
}
void tst_QTextDocumentFragment::css_textUnderlineStyle_data()
@@ -2710,14 +2711,14 @@ void tst_QTextDocumentFragment::css_textUnderlineStyleAndDecoration()
QTextFragment fragment = doc->begin().begin().fragment();
QVERIFY(fragment.isValid());
- QVERIFY(fragment.charFormat().underlineStyle() == QTextCharFormat::SingleUnderline);
+ QCOMPARE(fragment.charFormat().underlineStyle(), QTextCharFormat::SingleUnderline);
QVERIFY(fragment.charFormat().fontOverline());
doc->setHtml("<span style=\"text-underline-style: solid; text-decoration: overline\">Test</span>");
fragment = doc->begin().begin().fragment();
QVERIFY(fragment.isValid());
- QVERIFY(fragment.charFormat().underlineStyle() == QTextCharFormat::SingleUnderline);
+ QCOMPARE(fragment.charFormat().underlineStyle(), QTextCharFormat::SingleUnderline);
QVERIFY(fragment.charFormat().fontOverline());
}
@@ -2726,48 +2727,48 @@ void tst_QTextDocumentFragment::css_listStyleType()
doc->setHtml("<ol style=\"list-style-type: disc\"><li>Blah</li></ol>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListDisc);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListDisc);
doc->setHtml("<ul style=\"list-style-type: square\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListSquare);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListSquare);
doc->setHtml("<ul style=\"list-style-type: circle\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListCircle);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListCircle);
doc->setHtml("<ul style=\"list-style-type: decimal\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListDecimal);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListDecimal);
doc->setHtml("<ul style=\"list-style-type: lower-alpha\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListLowerAlpha);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListLowerAlpha);
doc->setHtml("<ul style=\"list-style-type: upper-alpha\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListUpperAlpha);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListUpperAlpha);
doc->setHtml("<ul style=\"list-style-type: upper-roman\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListUpperRoman);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListUpperRoman);
doc->setHtml("<ul style=\"list-style-type: lower-roman\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListLowerRoman);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListLowerRoman);
// ignore the unsupported list-style-position inside the list-style shorthand property
doc->setHtml("<ul style=\"list-style: outside decimal\"><li>Blah</li></ul>");
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListDecimal);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListDecimal);
}
void tst_QTextDocumentFragment::css_linkPseudo()
@@ -2785,13 +2786,13 @@ void tst_QTextDocumentFragment::css_linkPseudo()
void tst_QTextDocumentFragment::css_pageBreaks()
{
doc->setHtml("<p>Foo</p>");
- QVERIFY(doc->begin().blockFormat().pageBreakPolicy() == QTextFormat::PageBreak_Auto);
+ QCOMPARE(doc->begin().blockFormat().pageBreakPolicy(), QTextFormat::PageBreak_Auto);
doc->setHtml("<p style=\" page-break-before:always;\">Foo</p>");
- QVERIFY(doc->begin().blockFormat().pageBreakPolicy() == QTextFormat::PageBreak_AlwaysBefore);
+ QCOMPARE(doc->begin().blockFormat().pageBreakPolicy(), QTextFormat::PageBreak_AlwaysBefore);
doc->setHtml("<p style=\" page-break-after:always;\">Foo</p>");
- QVERIFY(doc->begin().blockFormat().pageBreakPolicy() == QTextFormat::PageBreak_AlwaysAfter);
+ QCOMPARE(doc->begin().blockFormat().pageBreakPolicy(), QTextFormat::PageBreak_AlwaysAfter);
doc->setHtml("<p style=\" page-break-before:always; page-break-after:always;\">Foo</p>");
QVERIFY(doc->begin().blockFormat().pageBreakPolicy() == (QTextFormat::PageBreak_AlwaysAfter | QTextFormat::PageBreak_AlwaysBefore));
@@ -2832,13 +2833,14 @@ void tst_QTextDocumentFragment::universalSelectors()
QTextBlockFormat fmt = doc->begin().blockFormat();
if (match)
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
else
QVERIFY(!fmt.hasProperty(QTextFormat::BackgroundBrush));
}
void tst_QTextDocumentFragment::screenMedia()
{
+ const QColor green("green");
setHtml("<style>"
"@media screen {"
"p { background-color: green }"
@@ -2847,7 +2849,7 @@ void tst_QTextDocumentFragment::screenMedia()
"<p>test</p>"
"");
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
setHtml("<style>"
"@media foobar {"
@@ -2857,7 +2859,7 @@ void tst_QTextDocumentFragment::screenMedia()
"<p>test</p>"
"");
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() != QColor("green"));
+ QVERIFY(fmt.background().color() != green);
setHtml("<style>"
"@media sCrEeN {"
@@ -2867,7 +2869,7 @@ void tst_QTextDocumentFragment::screenMedia()
"<p>test</p>"
"");
fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), green);
}
void tst_QTextDocumentFragment::htmlResourceLoading()
@@ -2881,7 +2883,7 @@ void tst_QTextDocumentFragment::htmlResourceLoading()
doc->clear();
QTextCursor(doc).insertFragment(frag);
QTextBlockFormat fmt = doc->begin().blockFormat();
- QVERIFY(fmt.background().color() == QColor("green"));
+ QCOMPARE(fmt.background().color(), QColor("green"));
}
void tst_QTextDocumentFragment::someCaseInsensitiveAttributeValues()
@@ -2890,7 +2892,7 @@ void tst_QTextDocumentFragment::someCaseInsensitiveAttributeValues()
setHtml(QString::fromLatin1(html1));
cursor.movePosition(QTextCursor::End);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->format().style() == QTextListFormat::ListSquare);
+ QCOMPARE(cursor.currentList()->format().style(), QTextListFormat::ListSquare);
const char html2[] = "<div align=ceNTeR><b>Hello World";
setHtml(html2);
@@ -2925,7 +2927,7 @@ void tst_QTextDocumentFragment::backgroundImage()
doc.testPixmap.fill(Qt::blue);
doc.setHtml("<p style=\"background-image: url(testPixmap)\">Hello</p>");
QBrush bg = doc.begin().blockFormat().background();
- QVERIFY(bg.style() == Qt::TexturePattern);
+ QCOMPARE(bg.style(), Qt::TexturePattern);
QCOMPARE(bg.texture().cacheKey(), doc.testPixmap.cacheKey());
}
@@ -3109,7 +3111,7 @@ void tst_QTextDocumentFragment::html_tableStrangeNewline()
QCOMPARE(table->columns(), 1);
const QTextTableCell cell = table->cellAt(0, 0);
QCOMPARE(cell.firstCursorPosition().block().text(), QString("Foo"));
- QVERIFY(cell.firstCursorPosition().block() == cell.lastCursorPosition().block());
+ QCOMPARE(cell.firstCursorPosition().block(), cell.lastCursorPosition().block());
}
void tst_QTextDocumentFragment::html_tableStrangeNewline2()
@@ -3123,7 +3125,7 @@ void tst_QTextDocumentFragment::html_tableStrangeNewline2()
QCOMPARE(table->columns(), 1);
const QTextTableCell cell = table->cellAt(0, 0);
QCOMPARE(cell.firstCursorPosition().block().text(), QString("Foo"));
- QVERIFY(cell.firstCursorPosition().block() == cell.lastCursorPosition().block());
+ QCOMPARE(cell.firstCursorPosition().block(), cell.lastCursorPosition().block());
}
void tst_QTextDocumentFragment::html_tableStrangeNewline3()
@@ -3152,11 +3154,11 @@ void tst_QTextDocumentFragment::html_tableStrangeNewline3()
QTextTableCell cell = table->cellAt(0, 0);
QCOMPARE(cell.firstCursorPosition().block().text(), QString("Meh"));
- QVERIFY(cell.firstCursorPosition().block() == cell.lastCursorPosition().block());
+ QCOMPARE(cell.firstCursorPosition().block(), cell.lastCursorPosition().block());
cell = table->cellAt(0, 1);
QCOMPARE(cell.firstCursorPosition().block().text(), QString("Foo"));
- QVERIFY(cell.firstCursorPosition().block() == cell.lastCursorPosition().block());
+ QCOMPARE(cell.firstCursorPosition().block(), cell.lastCursorPosition().block());
}
void tst_QTextDocumentFragment::html_caption()
@@ -3170,7 +3172,7 @@ void tst_QTextDocumentFragment::html_caption()
cursor.movePosition(QTextCursor::NextBlock);
QCOMPARE(cursor.block().text(), QString("This is a Caption!"));
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignHCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignHCenter);
cursor.movePosition(QTextCursor::NextBlock);
QTextTable *table = cursor.currentTable();
@@ -3427,7 +3429,7 @@ void tst_QTextDocumentFragment::html_dontInheritAlignmentForFloatingImages()
QVERIFY(o);
QTextFormat f = o->format();
QVERIFY(f.isFrameFormat());
- QVERIFY(f.toFrameFormat().position() == QTextFrameFormat::InFlow);
+ QCOMPARE(f.toFrameFormat().position(), QTextFrameFormat::InFlow);
}
void tst_QTextDocumentFragment::html_verticalImageAlignment()
@@ -3437,35 +3439,35 @@ void tst_QTextDocumentFragment::html_verticalImageAlignment()
cursor.movePosition(QTextCursor::NextCharacter);
QVERIFY(cursor.charFormat().isImageFormat());
QTextImageFormat fmt = cursor.charFormat().toImageFormat();
- QVERIFY(fmt.verticalAlignment() == QTextCharFormat::AlignNormal);
+ QCOMPARE(fmt.verticalAlignment(), QTextCharFormat::AlignNormal);
doc->setHtml("<img src=\"foo\" align=middle />");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
QVERIFY(cursor.charFormat().isImageFormat());
fmt = cursor.charFormat().toImageFormat();
- QVERIFY(fmt.verticalAlignment() == QTextCharFormat::AlignMiddle);
+ QCOMPARE(fmt.verticalAlignment(), QTextCharFormat::AlignMiddle);
doc->setHtml("<img src=\"foo\" style=\"vertical-align: middle\" />");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
QVERIFY(cursor.charFormat().isImageFormat());
fmt = cursor.charFormat().toImageFormat();
- QVERIFY(fmt.verticalAlignment() == QTextCharFormat::AlignMiddle);
+ QCOMPARE(fmt.verticalAlignment(), QTextCharFormat::AlignMiddle);
doc->setHtml("<img src=\"foo\" align=top />");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
QVERIFY(cursor.charFormat().isImageFormat());
fmt = cursor.charFormat().toImageFormat();
- QVERIFY(fmt.verticalAlignment() == QTextCharFormat::AlignTop);
+ QCOMPARE(fmt.verticalAlignment(), QTextCharFormat::AlignTop);
doc->setHtml("<img src=\"foo\" style=\"vertical-align: top\" />");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextCharacter);
QVERIFY(cursor.charFormat().isImageFormat());
fmt = cursor.charFormat().toImageFormat();
- QVERIFY(fmt.verticalAlignment() == QTextCharFormat::AlignTop);
+ QCOMPARE(fmt.verticalAlignment(), QTextCharFormat::AlignTop);
}
void tst_QTextDocumentFragment::html_verticalCellAlignment()
@@ -3944,11 +3946,11 @@ void tst_QTextDocumentFragment::html_directionWithHtml()
block = block.next();
QVERIFY(block.blockFormat().hasProperty(QTextFormat::LayoutDirection));
- QVERIFY(block.blockFormat().layoutDirection() == Qt::RightToLeft);
+ QCOMPARE(block.blockFormat().layoutDirection(), Qt::RightToLeft);
block = block.next();
QVERIFY(block.blockFormat().hasProperty(QTextFormat::LayoutDirection));
- QVERIFY(block.blockFormat().layoutDirection() == Qt::LeftToRight);
+ QCOMPARE(block.blockFormat().layoutDirection(), Qt::LeftToRight);
}
void tst_QTextDocumentFragment::html_directionWithRichText()
@@ -3961,11 +3963,11 @@ void tst_QTextDocumentFragment::html_directionWithRichText()
block = block.next();
QVERIFY(block.blockFormat().hasProperty(QTextFormat::LayoutDirection));
- QVERIFY(block.blockFormat().layoutDirection() == Qt::RightToLeft);
+ QCOMPARE(block.blockFormat().layoutDirection(), Qt::RightToLeft);
block = block.next();
QVERIFY(block.blockFormat().hasProperty(QTextFormat::LayoutDirection));
- QVERIFY(block.blockFormat().layoutDirection() == Qt::LeftToRight);
+ QCOMPARE(block.blockFormat().layoutDirection(), Qt::LeftToRight);
}
void tst_QTextDocumentFragment::html_metaInBody()
diff --git a/tests/auto/gui/text/qtextdocumentlayout/BLACKLIST b/tests/auto/gui/text/qtextdocumentlayout/BLACKLIST
new file mode 100644
index 0000000000..b13b2497d3
--- /dev/null
+++ b/tests/auto/gui/text/qtextdocumentlayout/BLACKLIST
@@ -0,0 +1,2 @@
+[imageAtRightAlignedTab]
+linux
diff --git a/tests/auto/gui/text/qtextformat/tst_qtextformat.cpp b/tests/auto/gui/text/qtextformat/tst_qtextformat.cpp
index 7c742bc864..5a401031e2 100644
--- a/tests/auto/gui/text/qtextformat/tst_qtextformat.cpp
+++ b/tests/auto/gui/text/qtextformat/tst_qtextformat.cpp
@@ -101,7 +101,7 @@ void tst_QTextFormat::defaultAlignment()
QTextBlockFormat fmt;
QVERIFY(!fmt.hasProperty(QTextFormat::BlockAlignment));
QCOMPARE(fmt.intProperty(QTextFormat::BlockAlignment), 0);
- QVERIFY(fmt.alignment() == Qt::AlignLeft);
+ QCOMPARE(fmt.alignment(), Qt::AlignLeft);
}
void tst_QTextFormat::testUnderlinePropertyPrecedence()
@@ -209,7 +209,7 @@ void tst_QTextFormat::resolveFont()
QVector<QTextFormat> formats = doc.allFormats();
QCOMPARE(formats.count(), 3);
- QVERIFY(formats.at(2).type() == QTextFormat::CharFormat);
+ QCOMPARE(formats.at(2).type(), int(QTextFormat::CharFormat));
fmt = formats.at(2).toCharFormat();
QVERIFY(!fmt.font().underline());
diff --git a/tests/auto/gui/text/qtextlayout/tst_qtextlayout.cpp b/tests/auto/gui/text/qtextlayout/tst_qtextlayout.cpp
index 51f726ac86..18da61925d 100644
--- a/tests/auto/gui/text/qtextlayout/tst_qtextlayout.cpp
+++ b/tests/auto/gui/text/qtextlayout/tst_qtextlayout.cpp
@@ -1675,6 +1675,7 @@ void tst_QTextLayout::testTabDPIScale()
case QPaintDevice::PdmPhysicalDpiY:
return 72;
case QPaintDevice::PdmDevicePixelRatio:
+ case QPaintDevice::PdmDevicePixelRatioScaled:
; // fall through
}
return 0;
@@ -1744,7 +1745,7 @@ void tst_QTextLayout::capitalization_allUpperCase()
QTextEngine *engine = layout.engine();
engine->itemize();
QCOMPARE(engine->layoutData->items.count(), 1);
- QVERIFY(engine->layoutData->items.at(0).analysis.flags == QScriptAnalysis::Uppercase);
+ QCOMPARE(engine->layoutData->items.at(0).analysis.flags, ushort(QScriptAnalysis::Uppercase));
}
void tst_QTextLayout::capitalization_allUpperCase_newline()
@@ -1764,9 +1765,9 @@ void tst_QTextLayout::capitalization_allUpperCase_newline()
QTextEngine *engine = layout.engine();
engine->itemize();
QCOMPARE(engine->layoutData->items.count(), 3);
- QVERIFY(engine->layoutData->items.at(0).analysis.flags == QScriptAnalysis::Uppercase);
- QVERIFY(engine->layoutData->items.at(1).analysis.flags == QScriptAnalysis::LineOrParagraphSeparator);
- QVERIFY(engine->layoutData->items.at(2).analysis.flags == QScriptAnalysis::Uppercase);
+ QCOMPARE(engine->layoutData->items.at(0).analysis.flags, ushort(QScriptAnalysis::Uppercase));
+ QCOMPARE(engine->layoutData->items.at(1).analysis.flags, ushort(QScriptAnalysis::LineOrParagraphSeparator));
+ QCOMPARE(engine->layoutData->items.at(2).analysis.flags, ushort(QScriptAnalysis::Uppercase));
}
void tst_QTextLayout::capitalization_allLowerCase()
@@ -1782,7 +1783,7 @@ void tst_QTextLayout::capitalization_allLowerCase()
QTextEngine *engine = layout.engine();
engine->itemize();
QCOMPARE(engine->layoutData->items.count(), 1);
- QVERIFY(engine->layoutData->items.at(0).analysis.flags == QScriptAnalysis::Lowercase);
+ QCOMPARE(engine->layoutData->items.at(0).analysis.flags, ushort(QScriptAnalysis::Lowercase));
}
void tst_QTextLayout::capitalization_smallCaps()
@@ -1798,8 +1799,8 @@ void tst_QTextLayout::capitalization_smallCaps()
QTextEngine *engine = layout.engine();
engine->itemize();
QCOMPARE(engine->layoutData->items.count(), 2);
- QVERIFY(engine->layoutData->items.at(0).analysis.flags == QScriptAnalysis::None);
- QVERIFY(engine->layoutData->items.at(1).analysis.flags == QScriptAnalysis::SmallCaps);
+ QCOMPARE(engine->layoutData->items.at(0).analysis.flags, ushort(QScriptAnalysis::None));
+ QCOMPARE(engine->layoutData->items.at(1).analysis.flags, ushort(QScriptAnalysis::SmallCaps));
}
void tst_QTextLayout::capitalization_capitalize()
@@ -1815,11 +1816,11 @@ void tst_QTextLayout::capitalization_capitalize()
QTextEngine *engine = layout.engine();
engine->itemize();
QCOMPARE(engine->layoutData->items.count(), 5);
- QVERIFY(engine->layoutData->items.at(0).analysis.flags == QScriptAnalysis::Uppercase);
- QVERIFY(engine->layoutData->items.at(1).analysis.flags == QScriptAnalysis::None);
- QVERIFY(engine->layoutData->items.at(2).analysis.flags == QScriptAnalysis::Tab);
- QVERIFY(engine->layoutData->items.at(3).analysis.flags == QScriptAnalysis::Uppercase);
- QVERIFY(engine->layoutData->items.at(4).analysis.flags == QScriptAnalysis::None);
+ QCOMPARE(engine->layoutData->items.at(0).analysis.flags, ushort(QScriptAnalysis::Uppercase));
+ QCOMPARE(engine->layoutData->items.at(1).analysis.flags, ushort(QScriptAnalysis::None));
+ QCOMPARE(engine->layoutData->items.at(2).analysis.flags, ushort(QScriptAnalysis::Tab));
+ QCOMPARE(engine->layoutData->items.at(3).analysis.flags, ushort(QScriptAnalysis::Uppercase));
+ QCOMPARE(engine->layoutData->items.at(4).analysis.flags, ushort(QScriptAnalysis::None));
}
void tst_QTextLayout::longText()
@@ -2096,8 +2097,8 @@ void tst_QTextLayout::cursorInNonStopChars()
QTextLine line = layout.createLine();
layout.endLayout();
- QVERIFY(line.cursorToX(1) == line.cursorToX(3));
- QVERIFY(line.cursorToX(2) == line.cursorToX(3));
+ QCOMPARE(line.cursorToX(1), line.cursorToX(3));
+ QCOMPARE(line.cursorToX(2), line.cursorToX(3));
}
void tst_QTextLayout::justifyTrailingSpaces()
diff --git a/tests/auto/gui/text/qtextlist/tst_qtextlist.cpp b/tests/auto/gui/text/qtextlist/tst_qtextlist.cpp
index c57123af61..03e557d8dd 100644
--- a/tests/auto/gui/text/qtextlist/tst_qtextlist.cpp
+++ b/tests/auto/gui/text/qtextlist/tst_qtextlist.cpp
@@ -113,11 +113,11 @@ void tst_QTextList::autoNumbering()
for (int i = 0; i < 27; ++i)
cursor.insertBlock();
- QVERIFY(list->count() == 28);
+ QCOMPARE(list->count(), 28);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->itemNumber(cursor.block()) == 27);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == "ab.");
+ QCOMPARE(cursor.currentList()->itemNumber(cursor.block()), 27);
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String("ab."));
}
void tst_QTextList::autoNumberingPrefixAndSuffix()
@@ -132,11 +132,11 @@ void tst_QTextList::autoNumberingPrefixAndSuffix()
for (int i = 0; i < 27; ++i)
cursor.insertBlock();
- QVERIFY(list->count() == 28);
+ QCOMPARE(list->count(), 28);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->itemNumber(cursor.block()) == 27);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == "-ab)");
+ QCOMPARE(cursor.currentList()->itemNumber(cursor.block()), 27);
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String("-ab)"));
}
void tst_QTextList::autoNumberingPrefixAndSuffixRTL()
@@ -154,9 +154,9 @@ void tst_QTextList::autoNumberingPrefixAndSuffixRTL()
cursor.insertBlock();
- QVERIFY(list->count() == 2);
+ QCOMPARE(list->count(), 2);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == "*B-");
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String("*B-"));
}
void tst_QTextList::autoNumberingPrefixAndSuffixHtmlExportImport()
@@ -174,7 +174,7 @@ void tst_QTextList::autoNumberingPrefixAndSuffixHtmlExportImport()
for (int i = 0; i < 27; ++i)
cursor.insertBlock();
- QVERIFY(list->count() == 28);
+ QCOMPARE(list->count(), 28);
QString htmlExport = doc->toHtml();
QTextDocument importDoc;
@@ -185,9 +185,9 @@ void tst_QTextList::autoNumberingPrefixAndSuffixHtmlExportImport()
importCursor.movePosition(QTextCursor::NextBlock);
QVERIFY(importCursor.currentList());
- QVERIFY(importCursor.currentList()->itemNumber(importCursor.block()) == 27);
- QVERIFY(importCursor.currentList()->itemText(importCursor.block()) == "\"ab#");
- QVERIFY(importCursor.currentList()->format().indent() == 10);
+ QCOMPARE(importCursor.currentList()->itemNumber(importCursor.block()), 27);
+ QCOMPARE(importCursor.currentList()->itemText(importCursor.block()), QLatin1String("\"ab#"));
+ QCOMPARE(importCursor.currentList()->format().indent(), 10);
}
void tst_QTextList::autoNumberingRTL()
@@ -203,9 +203,9 @@ void tst_QTextList::autoNumberingRTL()
cursor.insertBlock();
- QVERIFY(list->count() == 2);
+ QCOMPARE(list->count(), 2);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == ".B");
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String(".B"));
}
void tst_QTextList::romanNumbering()
@@ -218,11 +218,11 @@ void tst_QTextList::romanNumbering()
for (int i = 0; i < 4998; ++i)
cursor.insertBlock();
- QVERIFY(list->count() == 4999);
+ QCOMPARE(list->count(), 4999);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->itemNumber(cursor.block()) == 4998);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == "MMMMCMXCIX.");
+ QCOMPARE(cursor.currentList()->itemNumber(cursor.block()), 4998);
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String("MMMMCMXCIX."));
}
void tst_QTextList::romanNumberingLimit()
@@ -235,11 +235,11 @@ void tst_QTextList::romanNumberingLimit()
for (int i = 0; i < 4999; ++i)
cursor.insertBlock();
- QVERIFY(list->count() == 5000);
+ QCOMPARE(list->count(), 5000);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->itemNumber(cursor.block()) == 4999);
- QVERIFY(cursor.currentList()->itemText(cursor.block()) == "?.");
+ QCOMPARE(cursor.currentList()->itemNumber(cursor.block()), 4999);
+ QCOMPARE(cursor.currentList()->itemText(cursor.block()), QLatin1String("?."));
}
void tst_QTextList::formatChange()
@@ -257,12 +257,12 @@ void tst_QTextList::formatChange()
QVERIFY(list && list->count() == 2);
QTextBlockFormat bfmt = cursor.blockFormat();
-// QVERIFY(bfmt.object() == list);
+// QCOMPARE(bfmt.object(), list);
bfmt.setObjectIndex(-1);
cursor.setBlockFormat(bfmt);
- QVERIFY(firstList->count() == 1);
+ QCOMPARE(firstList->count(), 1);
}
void tst_QTextList::cursorNavigation()
@@ -282,7 +282,7 @@ void tst_QTextList::cursorNavigation()
QVERIFY(cursor.currentList());
cursor.movePosition(QTextCursor::PreviousBlock);
QVERIFY(cursor.currentList());
- QVERIFY(cursor.currentList()->itemNumber(cursor.block()) == 0);
+ QCOMPARE(cursor.currentList()->itemNumber(cursor.block()), 0);
}
void tst_QTextList::partialRemoval()
diff --git a/tests/auto/gui/text/qtextpiecetable/tst_qtextpiecetable.cpp b/tests/auto/gui/text/qtextpiecetable/tst_qtextpiecetable.cpp
index ae8948a61f..cd43849729 100644
--- a/tests/auto/gui/text/qtextpiecetable/tst_qtextpiecetable.cpp
+++ b/tests/auto/gui/text/qtextpiecetable/tst_qtextpiecetable.cpp
@@ -157,7 +157,7 @@ void tst_QTextPieceTable::insertion3()
table->insert(pos, str, charFormatIndex);
compare.insert(pos, str);
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
}
void tst_QTextPieceTable::insertion4()
@@ -176,7 +176,7 @@ void tst_QTextPieceTable::insertion4()
// exit(12);
// }
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
}
void tst_QTextPieceTable::insertion5()
@@ -196,10 +196,10 @@ void tst_QTextPieceTable::insertion5()
}
compare.insert(pos, str);
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
for (QTextBlock it = table->blocksBegin(); it != table->blocksEnd(); it = it.next()) {
QTextDocumentPrivate::FragmentIterator fit = table->find(it.position());
- QVERIFY(fit.position() == it.position());
+ QCOMPARE(fit.position(), it.position());
}
}
@@ -260,7 +260,7 @@ void tst_QTextPieceTable::removal3()
// exit(12);
// }
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
}
void tst_QTextPieceTable::removal4()
@@ -294,7 +294,7 @@ void tst_QTextPieceTable::removal4()
// exit(12);
// }
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
}
void tst_QTextPieceTable::undoRedo1()
@@ -392,7 +392,7 @@ void tst_QTextPieceTable::undoRedo6()
QTextBlockFormat bfmt;
bfmt.setAlignment(Qt::AlignHCenter);
cursor.setBlockFormat(bfmt);
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignHCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignHCenter);
QTextCursor range = cursor;
range.clearSelection();
@@ -404,11 +404,11 @@ void tst_QTextPieceTable::undoRedo6()
range.mergeCharFormat(modifier);
cursor.movePosition(QTextCursor::Start);
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignHCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignHCenter);
doc.undo();
- QVERIFY(cursor.blockFormat().alignment() == Qt::AlignHCenter);
+ QCOMPARE(cursor.blockFormat().alignment(), Qt::AlignHCenter);
}
void tst_QTextPieceTable::undoRedo7()
@@ -497,13 +497,13 @@ void tst_QTextPieceTable::undoRedo11()
}
l += remove ? -1 : 2;
}
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
for (int i = 0; i < loops; ++i)
table->undo();
- QVERIFY(table->plainText() == QString(""));
+ QCOMPARE(table->plainText(), QString(""));
for (int i = 0; i < loops; ++i)
table->redo();
- QVERIFY(table->plainText() == compare);
+ QCOMPARE(table->plainText(), compare);
}
@@ -693,9 +693,9 @@ void tst_QTextPieceTable::setBlockFormat()
QTextBlock b = table->blocksFind(1);
table->setBlockFormat(b, b, newbfmt);
- QVERIFY(table->blocksFind(0).blockFormat() == bfmt);
- QVERIFY(table->blocksFind(1).blockFormat() == newbfmt);
- QVERIFY(table->blocksFind(2).blockFormat() == bfmt);
+ QCOMPARE(table->blocksFind(0).blockFormat(), bfmt);
+ QCOMPARE(table->blocksFind(1).blockFormat(), newbfmt);
+ QCOMPARE(table->blocksFind(2).blockFormat(), bfmt);
}
@@ -705,19 +705,19 @@ void tst_QTextPieceTable::blockInsertion()
fmt.setTopMargin(100);
int idx = table->formatCollection()->indexForFormat(fmt);
int charFormat = table->formatCollection()->indexForFormat(QTextCharFormat());
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
table->insertBlock(0, idx, charFormat);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).blockFormat() == fmt);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).blockFormat(), fmt);
table->undo();
- QVERIFY(table->blockMap().length() == 1);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
+ QCOMPARE(table->blockMap().length(), 1);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
table->redo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).blockFormat() == fmt);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).blockFormat(), fmt);
}
void tst_QTextPieceTable::blockInsertion2()
@@ -755,37 +755,37 @@ void tst_QTextPieceTable::blockRemoval1()
table->insertBlock(9, idx2, charFormatIndex);
table->insert(10, "0123", charFormatIndex);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->beginEditBlock();
table->remove(5, 5);
table->endEditBlock();
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(4).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 5);
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(4).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 5);
table->undo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->redo();
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(4).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 5);
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(4).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 5);
}
void tst_QTextPieceTable::blockRemoval2()
@@ -803,35 +803,35 @@ void tst_QTextPieceTable::blockRemoval2()
table->insertBlock(9, idx2, charFormatIndex);
table->insert(10, "0123", charFormatIndex);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->remove(4, 1);
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(6).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 0);
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(6).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 0);
table->undo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->redo();
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(6).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 0);
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(6).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 0);
}
void tst_QTextPieceTable::blockRemoval3()
@@ -849,38 +849,38 @@ void tst_QTextPieceTable::blockRemoval3()
table->insertBlock(9, idx2, charFormatIndex);
table->insert(10, "0123", charFormatIndex);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->beginEditBlock();
table->remove(3, 4);
table->endEditBlock();
- QVERIFY(table->blocksFind(1).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
+ QCOMPARE(table->blocksFind(1).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
table->undo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->redo();
- QVERIFY(table->blocksFind(1).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
+ QCOMPARE(table->blocksFind(1).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
}
void tst_QTextPieceTable::blockRemoval4()
@@ -899,35 +899,35 @@ void tst_QTextPieceTable::blockRemoval4()
table->insertBlock(9, idx2, charFormatIndex);
table->insert(10, "0123", charFormatIndex);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->remove(3, 7);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
- QVERIFY(table->blocksFind(1).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
+ QCOMPARE(table->blocksFind(1).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
table->undo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->redo();
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
- QVERIFY(table->blocksFind(1).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
+ QCOMPARE(table->blocksFind(1).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
#endif
}
@@ -946,38 +946,38 @@ void tst_QTextPieceTable::blockRemoval5()
table->insertBlock(9, idx2, charFormatIndex);
table->insert(10, "0123", charFormatIndex);
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->beginEditBlock();
table->remove(3, 8);
table->endEditBlock();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
table->undo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(4).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == fmt1);
- QVERIFY(table->blocksFind(10).blockFormat() == fmt2);
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(6).position() == 5);
- QVERIFY(table->blocksFind(11).position() == 10);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(4).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), fmt1);
+ QCOMPARE(table->blocksFind(10).blockFormat(), fmt2);
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(6).position(), 5);
+ QCOMPARE(table->blocksFind(11).position(), 10);
table->redo();
- QVERIFY(table->blocksFind(0).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(5).blockFormat() == QTextBlockFormat());
- QVERIFY(table->blocksFind(1).position() == 0);
- QVERIFY(table->blocksFind(5).position() == 0);
+ QCOMPARE(table->blocksFind(0).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(5).blockFormat(), QTextBlockFormat());
+ QCOMPARE(table->blocksFind(1).position(), 0);
+ QCOMPARE(table->blocksFind(5).position(), 0);
}
@@ -996,66 +996,66 @@ void tst_QTextPieceTable::checkFrames1()
QPointer<QTextFrame> frame = table->insertFrame(1, 3, ffmt);
QTextFrame *root = table->rootFrame();
- QVERIFY(root == frame->parentFrame());
+ QCOMPARE(root, frame->parentFrame());
QVERIFY(root);
- QVERIFY(root->parentFrame() == 0);
+ QVERIFY(!root->parentFrame());
- QVERIFY(root->childFrames().count() == 1);
+ QCOMPARE(root->childFrames().count(), 1);
QVERIFY(frame->format() == ffmt);
- QVERIFY(frame->firstPosition() == 2);
- QVERIFY(frame->lastPosition() == 4);
+ QCOMPARE(frame->firstPosition(), 2);
+ QCOMPARE(frame->lastPosition(), 4);
QPointer<QTextFrame> frame2 = table->insertFrame(2, 3, ffmt);
- QVERIFY(root->childFrames().count() == 1);
- QVERIFY(root->childFrames().at(0) == frame);
- QVERIFY(frame->childFrames().count() == 1);
- QVERIFY(frame2->childFrames().count() == 0);
- QVERIFY(frame2->parentFrame() == frame);
- QVERIFY(frame2->firstPosition() == 3);
- QVERIFY(frame2->lastPosition() == 4);
+ QCOMPARE(root->childFrames().count(), 1);
+ QCOMPARE(root->childFrames().at(0), frame.data());
+ QCOMPARE(frame->childFrames().count(), 1);
+ QCOMPARE(frame2->childFrames().count(), 0);
+ QCOMPARE(frame2->parentFrame(), frame.data());
+ QCOMPARE(frame2->firstPosition(), 3);
+ QCOMPARE(frame2->lastPosition(), 4);
QVERIFY(frame->format() == ffmt);
- QVERIFY(frame->firstPosition() == 2);
- QVERIFY(frame->lastPosition() == 6);
+ QCOMPARE(frame->firstPosition(), 2);
+ QCOMPARE(frame->lastPosition(), 6);
table->removeFrame(frame);
- QVERIFY(root->childFrames().count() == 1);
- QVERIFY(root->childFrames().at(0) == frame2);
+ QCOMPARE(root->childFrames().count(), 1);
+ QCOMPARE(root->childFrames().at(0), frame2.data());
QVERIFY(!frame);
- QVERIFY(frame2->childFrames().count() == 0);
- QVERIFY(frame2->parentFrame() == root);
- QVERIFY(frame2->firstPosition() == 2);
- QVERIFY(frame2->lastPosition() == 3);
+ QCOMPARE(frame2->childFrames().count(), 0);
+ QCOMPARE(frame2->parentFrame(), root);
+ QCOMPARE(frame2->firstPosition(), 2);
+ QCOMPARE(frame2->lastPosition(), 3);
table->undo();
frame = table->frameAt(2);
- QVERIFY(root->childFrames().count() == 1);
- QVERIFY(root->childFrames().at(0) == frame);
- QVERIFY(frame->childFrames().count() == 1);
- QVERIFY(frame->childFrames().at(0) == frame2);
- QVERIFY(frame2->childFrames().count() == 0);
- QVERIFY(frame2->parentFrame() == frame);
- QVERIFY(frame2->firstPosition() == 3);
- QVERIFY(frame2->lastPosition() == 4);
+ QCOMPARE(root->childFrames().count(), 1);
+ QCOMPARE(root->childFrames().at(0), frame.data());
+ QCOMPARE(frame->childFrames().count(), 1);
+ QCOMPARE(frame->childFrames().at(0), frame2.data());
+ QCOMPARE(frame2->childFrames().count(), 0);
+ QCOMPARE(frame2->parentFrame(), frame.data());
+ QCOMPARE(frame2->firstPosition(), 3);
+ QCOMPARE(frame2->lastPosition(), 4);
- QVERIFY(frame->firstPosition() == 2);
- QVERIFY(frame->lastPosition() == 6);
+ QCOMPARE(frame->firstPosition(), 2);
+ QCOMPARE(frame->lastPosition(), 6);
table->undo();
- QVERIFY(root->childFrames().count() == 1);
- QVERIFY(root->childFrames().at(0) == frame);
- QVERIFY(frame->childFrames().count() == 0);
+ QCOMPARE(root->childFrames().count(), 1);
+ QCOMPARE(root->childFrames().at(0), frame.data());
+ QCOMPARE(frame->childFrames().count(), 0);
QVERIFY(!frame2);
- QVERIFY(frame->firstPosition() == 2);
- QVERIFY(frame->lastPosition() == 4);
+ QCOMPARE(frame->firstPosition(), 2);
+ QCOMPARE(frame->lastPosition(), 4);
}
void tst_QTextPieceTable::removeFrameDirect()
@@ -1065,7 +1065,7 @@ void tst_QTextPieceTable::removeFrameDirect()
QTextFrame *frame = table->insertFrame(1, 5, ffmt);
- QVERIFY(frame->parentFrame() == table->rootFrame());
+ QCOMPARE(frame->parentFrame(), table->rootFrame());
const int start = frame->firstPosition() - 1;
const int end = frame->lastPosition();
diff --git a/tests/auto/gui/text/qtexttable/tst_qtexttable.cpp b/tests/auto/gui/text/qtexttable/tst_qtexttable.cpp
index c8d3122e6d..1c099acc56 100644
--- a/tests/auto/gui/text/qtexttable/tst_qtexttable.cpp
+++ b/tests/auto/gui/text/qtexttable/tst_qtexttable.cpp
@@ -146,87 +146,87 @@ void tst_QTextTable::variousTableModifications()
QTextTableFormat tableFmt;
QTextTable *tab = cursor.insertTable(2, 2, tableFmt);
- QVERIFY(doc->toPlainText().length() == 5);
- QVERIFY(tab == cursor.currentTable());
- QVERIFY(tab->columns() == 2);
- QVERIFY(tab->rows() == 2);
+ QCOMPARE(doc->toPlainText().length(), 5);
+ QCOMPARE(tab, cursor.currentTable());
+ QCOMPARE(tab->columns(), 2);
+ QCOMPARE(tab->rows(), 2);
- QVERIFY(cursor.position() == 1);
+ QCOMPARE(cursor.position(), 1);
QTextCharFormat fmt = cursor.charFormat();
- QVERIFY(fmt.objectIndex() == -1);
+ QCOMPARE(fmt.objectIndex(), -1);
QTextTableCell cell = tab->cellAt(cursor);
QVERIFY(cell.isValid());
- QVERIFY(cell.row() == 0);
- QVERIFY(cell.column() == 0);
+ QCOMPARE(cell.row(), 0);
+ QCOMPARE(cell.column(), 0);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 2);
+ QCOMPARE(cursor.position(), 2);
fmt = cursor.charFormat();
- QVERIFY(fmt.objectIndex() == -1);
+ QCOMPARE(fmt.objectIndex(), -1);
cell = tab->cellAt(cursor);
QVERIFY(cell.isValid());
- QVERIFY(cell.row() == 0);
- QVERIFY(cell.column() == 1);
+ QCOMPARE(cell.row(), 0);
+ QCOMPARE(cell.column(), 1);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 3);
+ QCOMPARE(cursor.position(), 3);
fmt = cursor.charFormat();
- QVERIFY(fmt.objectIndex() == -1);
+ QCOMPARE(fmt.objectIndex(), -1);
cell = tab->cellAt(cursor);
QVERIFY(cell.isValid());
- QVERIFY(cell.row() == 1);
- QVERIFY(cell.column() == 0);
+ QCOMPARE(cell.row(), 1);
+ QCOMPARE(cell.column(), 0);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 4);
+ QCOMPARE(cursor.position(), 4);
fmt = cursor.charFormat();
- QVERIFY(fmt.objectIndex() == -1);
+ QCOMPARE(fmt.objectIndex(), -1);
cell = tab->cellAt(cursor);
QVERIFY(cell.isValid());
- QVERIFY(cell.row() == 1);
- QVERIFY(cell.column() == 1);
+ QCOMPARE(cell.row(), 1);
+ QCOMPARE(cell.column(), 1);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 5);
+ QCOMPARE(cursor.position(), 5);
fmt = cursor.charFormat();
- QVERIFY(fmt.objectIndex() == -1);
+ QCOMPARE(fmt.objectIndex(), -1);
cell = tab->cellAt(cursor);
QVERIFY(!cell.isValid());
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 5);
+ QCOMPARE(cursor.position(), 5);
// check we can't delete the cells with the cursor
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 1);
+ QCOMPARE(cursor.position(), 1);
cursor.deleteChar();
- QVERIFY(doc->toPlainText().length() == 5);
+ QCOMPARE(doc->toPlainText().length(), 5);
cursor.movePosition(QTextCursor::NextBlock);
- QVERIFY(cursor.position() == 2);
+ QCOMPARE(cursor.position(), 2);
cursor.deleteChar();
- QVERIFY(doc->toPlainText().length() == 5);
+ QCOMPARE(doc->toPlainText().length(), 5);
cursor.deletePreviousChar();
- QVERIFY(cursor.position() == 2);
- QVERIFY(doc->toPlainText().length() == 5);
+ QCOMPARE(cursor.position(), 2);
+ QCOMPARE(doc->toPlainText().length(), 5);
QTextTable *table = cursor.currentTable();
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 2);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 2);
table->insertRows(2, 1);
- QVERIFY(table->rows() == 3);
- QVERIFY(table->columns() == 2);
- QVERIFY(doc->toPlainText().length() == 7);
+ QCOMPARE(table->rows(), 3);
+ QCOMPARE(table->columns(), 2);
+ QCOMPARE(doc->toPlainText().length(), 7);
table->insertColumns(2, 2);
- QVERIFY(table->rows() == 3);
- QVERIFY(table->columns() == 4);
- QVERIFY(doc->toPlainText().length() == 13);
+ QCOMPARE(table->rows(), 3);
+ QCOMPARE(table->columns(), 4);
+ QCOMPARE(doc->toPlainText().length(), 13);
table->resize(4, 5);
- QVERIFY(table->rows() == 4);
- QVERIFY(table->columns() == 5);
- QVERIFY(doc->toPlainText().length() == 21);
+ QCOMPARE(table->rows(), 4);
+ QCOMPARE(table->columns(), 5);
+ QCOMPARE(doc->toPlainText().length(), 21);
}
void tst_QTextTable::tableShrinking()
@@ -234,25 +234,25 @@ void tst_QTextTable::tableShrinking()
QTextTableFormat tableFmt;
cursor.insertTable(3, 4, tableFmt);
- QVERIFY(doc->toPlainText().length() == 13);
+ QCOMPARE(doc->toPlainText().length(), 13);
QTextTable *table = cursor.currentTable();
- QVERIFY(table->rows() == 3);
- QVERIFY(table->columns() == 4);
+ QCOMPARE(table->rows(), 3);
+ QCOMPARE(table->columns(), 4);
table->removeRows(1, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 4);
- QVERIFY(doc->toPlainText().length() == 9);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 4);
+ QCOMPARE(doc->toPlainText().length(), 9);
table->removeColumns(1, 2);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 2);
- QVERIFY(doc->toPlainText().length() == 5);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 2);
+ QCOMPARE(doc->toPlainText().length(), 5);
table->resize(1, 1);
- QVERIFY(table->rows() == 1);
- QVERIFY(table->columns() == 1);
- QVERIFY(doc->toPlainText().length() == 2);
+ QCOMPARE(table->rows(), 1);
+ QCOMPARE(table->columns(), 1);
+ QCOMPARE(doc->toPlainText().length(), 2);
}
void tst_QTextTable::spans()
@@ -264,12 +264,12 @@ void tst_QTextTable::spans()
QTextTable *table = cursor.currentTable();
QVERIFY(table->cellAt(0, 0) != table->cellAt(0, 1));
table->mergeCells(0, 0, 1, 2);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 2);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 2);
QVERIFY(table->cellAt(0, 0) == table->cellAt(0, 1));
table->mergeCells(0, 0, 2, 2);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 2);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 2);
}
void tst_QTextTable::variousModifications2()
@@ -277,45 +277,45 @@ void tst_QTextTable::variousModifications2()
QTextTableFormat tableFmt;
cursor.insertTable(2, 5, tableFmt);
- QVERIFY(doc->toPlainText().length() == 11);
+ QCOMPARE(doc->toPlainText().length(), 11);
QTextTable *table = cursor.currentTable();
- QVERIFY(cursor.position() == 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 5);
+ QCOMPARE(cursor.position(), 1);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 5);
table->insertColumns(0, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 6);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 6);
table->insertColumns(6, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 7);
table->insertRows(0, 1);
- QVERIFY(table->rows() == 3);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->rows(), 3);
+ QCOMPARE(table->columns(), 7);
table->insertRows(3, 1);
- QVERIFY(table->rows() == 4);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->rows(), 4);
+ QCOMPARE(table->columns(), 7);
table->removeRows(0, 1);
- QVERIFY(table->rows() == 3);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->rows(), 3);
+ QCOMPARE(table->columns(), 7);
table->removeRows(2, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 7);
table->removeColumns(0, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 6);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 6);
table->removeColumns(5, 1);
- QVERIFY(table->rows() == 2);
- QVERIFY(table->columns() == 5);
+ QCOMPARE(table->rows(), 2);
+ QCOMPARE(table->columns(), 5);
tableFmt = table->format();
table->insertColumns(2, 1);
table->setFormat(tableFmt);
table->insertColumns(2, 1);
- QVERIFY(table->columns() == 7);
+ QCOMPARE(table->columns(), 7);
}
void tst_QTextTable::tableManager_undo()
@@ -325,16 +325,16 @@ void tst_QTextTable::tableManager_undo()
QTextTable *table = cursor.insertTable(2, 2, fmt);
QVERIFY(table);
- QVERIFY(table->format().border() == 10);
+ QCOMPARE(table->format().border(), qreal(10));
fmt.setBorder(20);
table->setFormat(fmt);
- QVERIFY(table->format().border() == 20);
+ QCOMPARE(table->format().border(), qreal(20));
doc->undo();
- QVERIFY(table->format().border() == 10);
+ QCOMPARE(table->format().border(), qreal(10));
}
void tst_QTextTable::tableManager_removeCell()
@@ -360,10 +360,10 @@ void tst_QTextTable::rowAt()
QTextCursor cell20Cursor = table->cellAt(2, 0).firstCursorPosition();
QTextCursor cell21Cursor = table->cellAt(2, 1).firstCursorPosition();
QTextCursor cell30Cursor = table->cellAt(3, 0).firstCursorPosition();
- QVERIFY(table->cellAt(cell00Cursor).firstCursorPosition() == cell00Cursor);
- QVERIFY(table->cellAt(cell10Cursor).firstCursorPosition() == cell10Cursor);
- QVERIFY(table->cellAt(cell20Cursor).firstCursorPosition() == cell20Cursor);
- QVERIFY(table->cellAt(cell30Cursor).firstCursorPosition() == cell30Cursor);
+ QCOMPARE(table->cellAt(cell00Cursor).firstCursorPosition(), cell00Cursor);
+ QCOMPARE(table->cellAt(cell10Cursor).firstCursorPosition(), cell10Cursor);
+ QCOMPARE(table->cellAt(cell20Cursor).firstCursorPosition(), cell20Cursor);
+ QCOMPARE(table->cellAt(cell30Cursor).firstCursorPosition(), cell30Cursor);
table->mergeCells(1, 0, 2, 1);
@@ -433,16 +433,16 @@ void tst_QTextTable::insertRows()
QVERIFY(cursor == table->cellAt(0, 0).firstCursorPosition());
table->insertRows(0, 1);
- QVERIFY(table->rows() == 3);
+ QCOMPARE(table->rows(), 3);
table->insertRows(1, 1);
- QVERIFY(table->rows() == 4);
+ QCOMPARE(table->rows(), 4);
table->insertRows(-1, 1);
- QVERIFY(table->rows() == 5);
+ QCOMPARE(table->rows(), 5);
table->insertRows(5, 2);
- QVERIFY(table->rows() == 7);
+ QCOMPARE(table->rows(), 7);
}
@@ -552,9 +552,9 @@ void tst_QTextTable::mergeCells()
QTextBlock block = table->cellAt(0, 0).firstCursorPosition().block();
- QVERIFY(block.text() == "Blah Foo");
- QVERIFY(block.next().text() == "Hah");
- QVERIFY(block.next().next().text() == "Bar");
+ QCOMPARE(block.text(), QLatin1String("Blah Foo"));
+ QCOMPARE(block.next().text(), QLatin1String("Hah"));
+ QCOMPARE(block.next().next().text(), QLatin1String("Bar"));
table = create4x4Table();
@@ -580,7 +580,7 @@ void tst_QTextTable::mergeCells()
if (table) {
cursor = table->cellAt(0, 0).firstCursorPosition();
- QVERIFY(cursor.block().text() == "Test");
+ QCOMPARE(cursor.block().text(), QLatin1String("Test"));
}
table = create2x2Table();
@@ -750,7 +750,7 @@ void tst_QTextTable::setCellFormat()
fmt.setTableCellColumnSpan(25);
fmt.setTableCellRowSpan(42);
cell.setFormat(fmt);
- QVERIFY(cell.format().background().color() == QColor(Qt::blue));
+ QCOMPARE(cell.format().background().color(), QColor(Qt::blue));
QCOMPARE(cell.format().tableCellColumnSpan(), 1);
QCOMPARE(cell.format().tableCellRowSpan(), 1);
}
@@ -1086,6 +1086,8 @@ public:
{
if (PdmDevicePixelRatio == metric)
return 1;
+ if (PdmDevicePixelRatioScaled == metric)
+ return 1 * QPaintDevice::devicePixelRatioFScale();
if (PdmDpiY == metric)
return 96;
if (PdmDpiX == metric)
diff --git a/tests/auto/gui/text/qzip/tst_qzip.cpp b/tests/auto/gui/text/qzip/tst_qzip.cpp
index 90e93881b9..8381c93bc2 100644
--- a/tests/auto/gui/text/qzip/tst_qzip.cpp
+++ b/tests/auto/gui/text/qzip/tst_qzip.cpp
@@ -39,9 +39,6 @@
class tst_QZip : public QObject
{
Q_OBJECT
-public slots:
- void init();
- void cleanup();
private slots:
void basicUnpack();
@@ -50,18 +47,10 @@ private slots:
void createArchive();
};
-void tst_QZip::init()
-{
-}
-
-void tst_QZip::cleanup()
-{
-}
-
void tst_QZip::basicUnpack()
{
QZipReader zip(QFINDTESTDATA("/testdata/test.zip"), QIODevice::ReadOnly);
- QList<QZipReader::FileInfo> files = zip.fileInfoList();
+ QVector<QZipReader::FileInfo> files = zip.fileInfoList();
QCOMPARE(files.count(), 2);
QZipReader::FileInfo fi = files.at(0);
@@ -97,7 +86,7 @@ void tst_QZip::basicUnpack()
void tst_QZip::symlinks()
{
QZipReader zip(QFINDTESTDATA("/testdata/symlink.zip"), QIODevice::ReadOnly);
- QList<QZipReader::FileInfo> files = zip.fileInfoList();
+ QVector<QZipReader::FileInfo> files = zip.fileInfoList();
QCOMPARE(files.count(), 2);
QZipReader::FileInfo fi = files.at(0);
@@ -120,7 +109,7 @@ void tst_QZip::symlinks()
void tst_QZip::readTest()
{
QZipReader zip("foobar.zip", QIODevice::ReadOnly); // non existing file.
- QList<QZipReader::FileInfo> files = zip.fileInfoList();
+ QVector<QZipReader::FileInfo> files = zip.fileInfoList();
QCOMPARE(files.count(), 0);
QByteArray b = zip.fileData("foobar");
QCOMPARE(b.size(), 0);
@@ -139,7 +128,7 @@ void tst_QZip::createArchive()
QBuffer buffer2(&zipFile);
QZipReader zip2(&buffer2);
- QList<QZipReader::FileInfo> files = zip2.fileInfoList();
+ QVector<QZipReader::FileInfo> files = zip2.fileInfoList();
QCOMPARE(files.count(), 1);
QZipReader::FileInfo file = files.at(0);
QCOMPARE(file.filePath, QString("My Filename"));
diff --git a/tests/auto/gui/util/qdoublevalidator/tst_qdoublevalidator.cpp b/tests/auto/gui/util/qdoublevalidator/tst_qdoublevalidator.cpp
index c2833d9e67..78ab769137 100644
--- a/tests/auto/gui/util/qdoublevalidator/tst_qdoublevalidator.cpp
+++ b/tests/auto/gui/util/qdoublevalidator/tst_qdoublevalidator.cpp
@@ -256,41 +256,41 @@ void tst_QDoubleValidator::notifySignals()
dv.setTop(0.8);
QCOMPARE(topSpy.count(), 1);
QCOMPARE(changedSpy.count(), 1);
- QVERIFY(dv.top() == 0.8);
+ QCOMPARE(dv.top(), 0.8);
dv.setBottom(0.2);
QCOMPARE(bottomSpy.count(), 1);
QCOMPARE(changedSpy.count(), 2);
- QVERIFY(dv.bottom() == 0.2);
+ QCOMPARE(dv.bottom(), 0.2);
dv.setRange(0.2, 0.7);
QCOMPARE(topSpy.count(), 2);
QCOMPARE(bottomSpy.count(), 1);
QCOMPARE(decSpy.count(), 1);
QCOMPARE(changedSpy.count(), 3);
- QVERIFY(dv.bottom() == 0.2);
- QVERIFY(dv.top() == 0.7);
- QVERIFY(dv.decimals() == 0.);
+ QCOMPARE(dv.bottom(), 0.2);
+ QCOMPARE(dv.top(), 0.7);
+ QCOMPARE(dv.decimals(), 0);
dv.setRange(0.3, 0.7);
QCOMPARE(topSpy.count(), 2);
QCOMPARE(bottomSpy.count(), 2);
QCOMPARE(changedSpy.count(), 4);
- QVERIFY(dv.bottom() == 0.3);
- QVERIFY(dv.top() == 0.7);
- QVERIFY(dv.decimals() == 0.);
+ QCOMPARE(dv.bottom(), 0.3);
+ QCOMPARE(dv.top(), 0.7);
+ QCOMPARE(dv.decimals(), 0);
dv.setRange(0.4, 0.6);
QCOMPARE(topSpy.count(), 3);
QCOMPARE(bottomSpy.count(), 3);
QCOMPARE(changedSpy.count(), 5);
- QVERIFY(dv.bottom() == 0.4);
- QVERIFY(dv.top() == 0.6);
- QVERIFY(dv.decimals() == 0.);
+ QCOMPARE(dv.bottom(), 0.4);
+ QCOMPARE(dv.top(), 0.6);
+ QCOMPARE(dv.decimals(), 0);
dv.setDecimals(10);
QCOMPARE(decSpy.count(), 2);
QCOMPARE(changedSpy.count(), 6);
- QVERIFY(dv.decimals() == 10.);
+ QCOMPARE(dv.decimals(), 10);
dv.setRange(0.4, 0.6, 100);
@@ -298,14 +298,14 @@ void tst_QDoubleValidator::notifySignals()
QCOMPARE(bottomSpy.count(), 3);
QCOMPARE(decSpy.count(), 3);
QCOMPARE(changedSpy.count(), 7);
- QVERIFY(dv.bottom() == 0.4);
- QVERIFY(dv.top() == 0.6);
- QVERIFY(dv.decimals() == 100.);
+ QCOMPARE(dv.bottom(), 0.4);
+ QCOMPARE(dv.top(), 0.6);
+ QCOMPARE(dv.decimals(), 100);
dv.setNotation(QDoubleValidator::StandardNotation);
QCOMPARE(notSpy.count(), 1);
QCOMPARE(changedSpy.count(), 8);
- QVERIFY(dv.notation() == QDoubleValidator::StandardNotation);
+ QCOMPARE(dv.notation(), QDoubleValidator::StandardNotation);
dv.setRange(dv.bottom(), dv.top(), dv.decimals());
QCOMPARE(topSpy.count(), 3);
diff --git a/tests/auto/gui/util/qintvalidator/tst_qintvalidator.cpp b/tests/auto/gui/util/qintvalidator/tst_qintvalidator.cpp
index 43f7b58439..a683d903df 100644
--- a/tests/auto/gui/util/qintvalidator/tst_qintvalidator.cpp
+++ b/tests/auto/gui/util/qintvalidator/tst_qintvalidator.cpp
@@ -239,32 +239,32 @@ void tst_QIntValidator::notifySignals()
iv.setTop(9);
QCOMPARE(topSpy.count(), 1);
QCOMPARE(changedSpy.count(), 1);
- QVERIFY(iv.top() == 9);
+ QCOMPARE(iv.top(), 9);
iv.setBottom(1);
QCOMPARE(bottomSpy.count(), 1);
QCOMPARE(changedSpy.count(), 2);
- QVERIFY(iv.bottom() == 1);
+ QCOMPARE(iv.bottom(), 1);
iv.setRange(1, 8);
QCOMPARE(topSpy.count(), 2);
QCOMPARE(bottomSpy.count(), 1);
QCOMPARE(changedSpy.count(), 3);
- QVERIFY(iv.top() == 8);
- QVERIFY(iv.bottom() == 1);
+ QCOMPARE(iv.top(), 8);
+ QCOMPARE(iv.bottom(), 1);
iv.setRange(2, 8);
QCOMPARE(topSpy.count(), 2);
QCOMPARE(bottomSpy.count(), 2);
QCOMPARE(changedSpy.count(), 4);
- QVERIFY(iv.top() == 8);
- QVERIFY(iv.bottom() == 2);
+ QCOMPARE(iv.top(), 8);
+ QCOMPARE(iv.bottom(), 2);
iv.setRange(3, 7);
QCOMPARE(topSpy.count(), 3);
QCOMPARE(bottomSpy.count(), 3);
QCOMPARE(changedSpy.count(), 5);
- QVERIFY(iv.top() == 7);
- QVERIFY(iv.bottom() == 3);
+ QCOMPARE(iv.top(), 7);
+ QCOMPARE(iv.bottom(), 3);
iv.setRange(3, 7);
QCOMPARE(topSpy.count(), 3);
diff --git a/tests/auto/network/access/qabstractnetworkcache/BLACKLIST b/tests/auto/network/access/qabstractnetworkcache/BLACKLIST
new file mode 100644
index 0000000000..3bd3350e4b
--- /dev/null
+++ b/tests/auto/network/access/qabstractnetworkcache/BLACKLIST
@@ -0,0 +1,9 @@
+[cacheControl]
+windows
+osx
+[expires]
+osx
+[etag]
+osx
+[lastModified]
+osx
diff --git a/tests/auto/network/access/qftp/BLACKLIST b/tests/auto/network/access/qftp/BLACKLIST
new file mode 100644
index 0000000000..a67c22265c
--- /dev/null
+++ b/tests/auto/network/access/qftp/BLACKLIST
@@ -0,0 +1,11 @@
+# QTBUG-15111
+
+[activeMode:WithoutProxy]
+opensuse-13.1 64bit
+redhatenterpriselinuxworkstation-6.6
+osx-10.10
+
+[activeMode:WithoutProxyWithSession]
+opensuse-13.1 64bit
+redhatenterpriselinuxworkstation-6.6
+osx-10.10
diff --git a/tests/auto/network/access/qftp/qftp.pro b/tests/auto/network/access/qftp/qftp.pro
index 850e1a9417..4294f27e74 100644
--- a/tests/auto/network/access/qftp/qftp.pro
+++ b/tests/auto/network/access/qftp/qftp.pro
@@ -11,4 +11,3 @@ wince {
DEPLOYMENT += addFiles
}
-CONFIG+=insignificant_test # QTBUG-15111: uses live qt-test-server, inherently unstable
diff --git a/tests/auto/network/access/qftp/tst_qftp.cpp b/tests/auto/network/access/qftp/tst_qftp.cpp
index 7ea1859938..795548ccc8 100644
--- a/tests/auto/network/access/qftp/tst_qftp.cpp
+++ b/tests/auto/network/access/qftp/tst_qftp.cpp
@@ -390,8 +390,7 @@ void tst_QFtp::connectToUnresponsiveHost()
a lot of other stuff in QFtp, so we just expect this test to fail on Windows.
*/
QEXPECT_FAIL("", "timeout not working due to strange Windows socket behaviour (see source file of this test for explanation)", Abort);
-#else
- QEXPECT_FAIL("", "QTBUG-20687", Abort);
+
#endif
QVERIFY2(! QTestEventLoop::instance().timeout(), "Network timeout longer than expected (should have been 60 seconds)");
diff --git a/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp b/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
index 1d04921c9a..be3e839725 100644
--- a/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
+++ b/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
@@ -83,7 +83,7 @@ void tst_QNetworkCookie::getterSetter()
QNetworkCookie cookie;
QNetworkCookie otherCookie;
- QVERIFY(cookie == otherCookie);
+ QCOMPARE(cookie, otherCookie);
QCOMPARE(cookie, otherCookie);
QVERIFY(!(cookie != otherCookie));
@@ -133,7 +133,7 @@ void tst_QNetworkCookie::getterSetter()
cookie.setSecure(false);
QVERIFY(!cookie.isSecure());
- QVERIFY(cookie == otherCookie);
+ QCOMPARE(cookie, otherCookie);
}
void tst_QNetworkCookie::parseSingleCookie_data()
diff --git a/tests/auto/network/access/qnetworkreply/element.xml b/tests/auto/network/access/qnetworkreply/element.xml
new file mode 100644
index 0000000000..071ffae057
--- /dev/null
+++ b/tests/auto/network/access/qnetworkreply/element.xml
@@ -0,0 +1 @@
+<root attr="value" attr2="value2"><person /><fruit /></root>
diff --git a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
index 4ed175ff7f..debdc6bcb3 100644
--- a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
+++ b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
@@ -129,6 +129,14 @@ class tst_QNetworkReply: public QObject
return s;
};
+ static QString tempRedirectReplyStr() {
+ QString s = "HTTP/1.1 307 Temporary Redirect\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: %1\r\n"
+ "\r\n";
+ return s;
+ };
+
QEventLoop *loop;
enum RunSimpleRequestReturn { Timeout = 0, Success, Failure };
int returnCode;
@@ -426,6 +434,8 @@ private Q_SLOTS:
void qtbug28035browserDoesNotLoadQtProjectOrgCorrectly();
+ void qtbug45581WrongReplyStatusCode();
+
void synchronousRequest_data();
void synchronousRequest();
#ifndef QT_NO_SSL
@@ -464,6 +474,10 @@ private Q_SLOTS:
void putWithRateLimiting();
+ void ioHttpSingleRedirect();
+ void ioHttpChangeMaxRedirects();
+ void ioHttpRedirectErrors_data();
+ void ioHttpRedirectErrors();
#ifndef QT_NO_SSL
void putWithServerClosingConnectionImmediately();
#endif
@@ -605,10 +619,16 @@ protected:
virtual void reply() {
Q_ASSERT(!client.isNull());
// we need to emulate the bytesWrittenSlot call if the data is empty.
- if (dataToTransmit.size() == 0)
+ if (dataToTransmit.size() == 0) {
QMetaObject::invokeMethod(this, "bytesWrittenSlot", Qt::QueuedConnection);
- else
+ } else {
client->write(dataToTransmit);
+ // FIXME: For SSL connections, if we don't flush the socket, the
+ // client never receives the data and since we're doing a disconnect
+ // immediately afterwards, it causes a RemoteHostClosedError for the
+ // client
+ client->flush();
+ }
}
private:
void connectSocketSignals()
@@ -1666,7 +1686,7 @@ void tst_QNetworkReply::getFromFile()
static const char fileData[] = "This is some data that is in the file.\r\n";
QByteArray data = QByteArray::fromRawData(fileData, sizeof fileData - 1);
- QVERIFY(file.write(data) == data.size());
+ QCOMPARE(file.write(data), data.size());
file.flush();
QCOMPARE(file.size(), qint64(data.size()));
@@ -2914,9 +2934,9 @@ void tst_QNetworkReply::connectToIPv6Address()
//qDebug() << server.receivedData;
QByteArray hostinfo = "\r\nHost: " + hostfield + ":" + QByteArray::number(server.serverPort()) + "\r\n";
QVERIFY(server.receivedData.contains(hostinfo));
- QVERIFY(content == dataToSend);
+ QCOMPARE(content, dataToSend);
QCOMPARE(reply->url(), request.url());
- QVERIFY(reply->error() == error);
+ QCOMPARE(reply->error(), error);
}
void tst_QNetworkReply::sendCustomRequestToHttp_data()
@@ -3048,7 +3068,7 @@ void tst_QNetworkReply::ioGetFromFile()
QVERIFY(file.open());
QFETCH(QByteArray, data);
- QVERIFY(file.write(data) == data.size());
+ QCOMPARE(file.write(data), data.size());
file.flush();
QCOMPARE(file.size(), qint64(data.size()));
@@ -3118,8 +3138,8 @@ void tst_QNetworkReply::ioGetFromFtpWithReuse()
DataReader reader2(reply2);
QSignalSpy spy(reply1.data(), SIGNAL(finished()));
- QVERIFY(waitForFinish(reply1) == Success);
- QVERIFY(waitForFinish(reply2) == Success);
+ QCOMPARE(waitForFinish(reply1), int(Success));
+ QCOMPARE(waitForFinish(reply2), int(Success));
QCOMPARE(reply1->url(), request.url());
QCOMPARE(reply2->url(), request.url());
@@ -3169,8 +3189,8 @@ void tst_QNetworkReply::ioGetFromHttpWithReuseParallel()
DataReader reader2(reply2);
QSignalSpy spy(reply1.data(), SIGNAL(finished()));
- QVERIFY(waitForFinish(reply2) == Success);
- QVERIFY(waitForFinish(reply1) == Success);
+ QCOMPARE(waitForFinish(reply2), int(Success));
+ QCOMPARE(waitForFinish(reply1), int(Success));
QCOMPARE(reply1->url(), request.url());
QCOMPARE(reply2->url(), request.url());
@@ -3272,8 +3292,8 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth()
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
- QVERIFY(waitForFinish(reply2) == Success);
- QVERIFY(waitForFinish(reply1) == Success);
+ QCOMPARE(waitForFinish(reply2), int(Success));
+ QCOMPARE(waitForFinish(reply1), int(Success));
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
@@ -3402,8 +3422,8 @@ void tst_QNetworkReply::ioGetFromHttpWithProxyAuth()
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
- QVERIFY(waitForFinish(reply2) == Success);
- QVERIFY(waitForFinish(reply1) == Success);
+ QCOMPARE(waitForFinish(reply2), int(Success));
+ QCOMPARE(waitForFinish(reply1), int(Success));
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
@@ -3525,7 +3545,7 @@ void tst_QNetworkReply::ioGetFromHttpWithSocksProxy()
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
@@ -3613,7 +3633,7 @@ void tst_QNetworkReply::ioGetFromHttpsWithSslHandshakeError()
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration()));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError);
QCOMPARE(sslspy.count(), 0);
@@ -3671,7 +3691,7 @@ void tst_QNetworkReply::ioGetFromHttpBrokenServer()
QNetworkReplyPtr reply(manager.get(request));
QSignalSpy spy(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
QCOMPARE(reply->url(), request.url());
QCOMPARE(spy.count(), 1);
@@ -4722,7 +4742,7 @@ void tst_QNetworkReply::ioPostToHttpNoBufferFlag()
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
@@ -5092,7 +5112,7 @@ void tst_QNetworkReply::ioPostToHttpEmptyUploadProgress()
QVERIFY(!QTestEventLoop::instance().timeout());
// final check: only 1 uploadProgress has been emitted
- QVERIFY(spy.length() == 1);
+ QCOMPARE(spy.length(), 1);
QList<QVariant> args = spy.last();
QVERIFY(!args.isEmpty());
QCOMPARE(args.at(0).toLongLong(), buffer.size());
@@ -5336,7 +5356,7 @@ void tst_QNetworkReply::chaining()
QVERIFY(sourceFile.open());
QFETCH(QByteArray, data);
- QVERIFY(sourceFile.write(data) == data.size());
+ QCOMPARE(sourceFile.write(data), data.size());
sourceFile.flush();
QCOMPARE(sourceFile.size(), qint64(data.size()));
@@ -5348,7 +5368,7 @@ void tst_QNetworkReply::chaining()
request.setUrl(url);
QNetworkReplyPtr putReply(manager.put(request, getReply.data()));
- QVERIFY(waitForFinish(putReply) == Success);
+ QCOMPARE(waitForFinish(putReply), int(Success));
QCOMPARE(getReply->url(), QUrl::fromLocalFile(sourceFile.fileName()));
QCOMPARE(getReply->error(), QNetworkReply::NoError);
@@ -5755,7 +5775,7 @@ void tst_QNetworkReply::proxyChange()
// verify that the replies succeeded
QCOMPARE(reply1->error(), QNetworkReply::NoError);
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
- QVERIFY(reply1->size() == 1);
+ QCOMPARE(reply1->size(), 1);
QCOMPARE(reply2->error(), QNetworkReply::NoError);
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
@@ -5772,7 +5792,7 @@ void tst_QNetworkReply::proxyChange()
manager.setProxy(dummyProxy);
QNetworkReplyPtr reply3(manager.get(req));
- QVERIFY(waitForFinish(reply3) == Failure);
+ QCOMPARE(waitForFinish(reply3), int(Failure));
QVERIFY(int(reply3->error()) > 0);
}
@@ -5808,7 +5828,7 @@ void tst_QNetworkReply::authorizationError()
QSignalSpy errorSpy(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)));
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished()));
// now run the request:
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
QFETCH(int, errorSignalCount);
QCOMPARE(errorSpy.count(), errorSignalCount);
@@ -5983,7 +6003,7 @@ public slots:
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
QVERIFY(!reply->error());
- QVERIFY(reply->bytesAvailable() == 27906);
+ QCOMPARE(reply->bytesAvailable(), 27906);
if (requestsFinishedCount == 60) {
QTestEventLoop::instance().exitLoop();
@@ -6153,6 +6173,10 @@ void tst_QNetworkReply::sslSessionSharing_data()
void tst_QNetworkReply::sslSessionSharing()
{
+#ifdef QT_SECURETRANSPORT
+ QSKIP("Not implemented with SecureTransport");
+#endif
+
QString urlString("https://" + QtNetworkSettings::serverName());
QList<QNetworkReplyPtr> replies;
@@ -6217,6 +6241,10 @@ void tst_QNetworkReply::sslSessionSharingFromPersistentSession_data()
void tst_QNetworkReply::sslSessionSharingFromPersistentSession()
{
+#ifdef QT_SECURETRANSPORT
+ QSKIP("Not implemented with SecureTransport");
+#endif
+
QString urlString("https://" + QtNetworkSettings::serverName());
// warm up SSL session cache to get a working session
@@ -6501,7 +6529,7 @@ public:
void finishedSlot() {
// We should have already received all readyRead
QVERIFY(!bytesAvailableList.isEmpty());
- QVERIFY(bytesAvailableList.last() == uploadSize);
+ QCOMPARE(bytesAvailableList.last(), uploadSize);
}
};
@@ -6584,7 +6612,7 @@ void tst_QNetworkReply::ioGetFromHttpWithoutContentLength()
QCOMPARE(reply->url(), request.url());
QVERIFY(reply->isFinished());
- QVERIFY(reply->error() == QNetworkReply::NoError);
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
}
// Is handled somewhere else too, introduced this special test to have it more accessible
@@ -6651,7 +6679,7 @@ void tst_QNetworkReply::compressedHttpReplyBrokenGzip()
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
QNetworkReplyPtr reply(manager.get(request));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
QCOMPARE(reply->error(), QNetworkReply::ProtocolFailure);
}
@@ -6664,7 +6692,7 @@ void tst_QNetworkReply::getFromUnreachableIp()
QNetworkRequest request(QUrl("http://255.255.255.255/42/23/narf/narf/narf"));
QNetworkReplyPtr reply(manager.get(request));
- QVERIFY(waitForFinish(reply) == Failure);
+ QCOMPARE(waitForFinish(reply), int(Failure));
QVERIFY(reply->error() != QNetworkReply::NoError);
}
@@ -7255,6 +7283,34 @@ void tst_QNetworkReply::qtbug28035browserDoesNotLoadQtProjectOrgCorrectly() {
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), true);
}
+void tst_QNetworkReply::qtbug45581WrongReplyStatusCode()
+{
+ const QUrl url("file:" + testDataDir + "/element.xml");
+ QNetworkRequest request(url);
+
+ QNetworkReplyPtr reply;
+ QSignalSpy finishedSpy(&manager, SIGNAL(finished(QNetworkReply*)));
+ QSignalSpy sslErrorsSpy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
+ RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0));
+ QVERIFY(reply->isFinished());
+
+ const QByteArray expectedContent =
+ "<root attr=\"value\" attr2=\"value2\">"
+ "<person /><fruit /></root>\n";
+
+ QCOMPARE(reply->readAll(), expectedContent);
+
+ QCOMPARE(finishedSpy.count(), 0);
+ QCOMPARE(sslErrorsSpy.count(), 0);
+
+ QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), expectedContent.size());
+
+ QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
+ QCOMPARE(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(), QLatin1String("OK"));
+
+ reply->deleteLater();
+}
+
void tst_QNetworkReply::synchronousRequest_data()
{
QTest::addColumn<QUrl>("url");
@@ -7425,7 +7481,7 @@ void tst_QNetworkReply::httpAbort()
QNetworkRequest request3("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt");
QNetworkReplyPtr reply3(manager.get(request3));
- QVERIFY(waitForFinish(reply3) == Success);
+ QCOMPARE(waitForFinish(reply3), int(Success));
QVERIFY(reply3->isFinished());
reply3->abort();
@@ -7980,7 +8036,142 @@ void tst_QNetworkReply::putWithRateLimiting()
QCOMPARE(uploadedData, data);
}
+void tst_QNetworkReply::ioHttpSingleRedirect()
+{
+ QUrl localhost = QUrl("http://localhost");
+ QByteArray http200Reply = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";
+
+ // Setup server to which the second server will redirect to
+ MiniHttpServer server2(http200Reply);
+
+ QUrl redirectUrl = QUrl(localhost);
+ redirectUrl.setPort(server2.serverPort());
+
+ QByteArray tempRedirectReply =
+ tempRedirectReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1();
+
+
+ // Setup redirect server
+ MiniHttpServer server(tempRedirectReply);
+
+ localhost.setPort(server.serverPort());
+ QNetworkRequest request(localhost);
+ request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+
+ QNetworkReplyPtr reply(manager.get(request));
+ QSignalSpy redSpy(reply.data(), SIGNAL(redirected(QUrl)));
+ QSignalSpy finSpy(reply.data(), SIGNAL(finished()));
+
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+
+ // Redirected and finished should be emitted exactly once
+ QCOMPARE(redSpy.count(), 1);
+ QCOMPARE(finSpy.count(), 1);
+
+ // Original URL should not be changed after redirect
+ QCOMPARE(request.url(), localhost);
+ // Verify Redirect url
+ QList<QVariant> args = redSpy.takeFirst();
+ QCOMPARE(args.at(0).toUrl(), redirectUrl);
+
+ // Reply url is set to the redirect url
+ QCOMPARE(reply->url(), redirectUrl);
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+}
+
+void tst_QNetworkReply::ioHttpChangeMaxRedirects()
+{
+ QUrl localhost = QUrl("http://localhost");
+
+ QByteArray http200Reply = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";
+
+ MiniHttpServer server1("");
+ MiniHttpServer server2("");
+ MiniHttpServer server3(http200Reply);
+
+ QUrl server2Url(localhost);
+ server2Url.setPort(server2.serverPort());
+ server1.setDataToTransmit(tempRedirectReplyStr().arg(
+ QString(server2Url.toEncoded())).toLatin1());
+
+ QUrl server3Url(localhost);
+ server3Url.setPort(server3.serverPort());
+ server2.setDataToTransmit(tempRedirectReplyStr().arg(
+ QString(server3Url.toEncoded())).toLatin1());
+
+ localhost.setPort(server1.serverPort());
+ QNetworkRequest request(localhost);
+ request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+
+ // Set Max redirects to 1. This will cause TooManyRedirectsError
+ request.setMaximumRedirectsAllowed(1);
+
+ QNetworkReplyPtr reply(manager.get(request));
+ QSignalSpy redSpy(reply.data(), SIGNAL(redirected(QUrl)));
+ QSignalSpy spy(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)));
+
+ QCOMPARE(waitForFinish(reply), int(Failure));
+
+ QCOMPARE(redSpy.count(), request.maximumRedirectsAllowed());
+ QCOMPARE(spy.count(), 1);
+ QCOMPARE(reply->error(), QNetworkReply::TooManyRedirectsError);
+
+ // Increase max redirects to allow successful completion
+ request.setMaximumRedirectsAllowed(3);
+
+ QNetworkReplyPtr reply2(manager.get(request));
+ QSignalSpy redSpy2(reply2.data(), SIGNAL(redirected(QUrl)));
+
+ QVERIFY2(waitForFinish(reply2) == Success, msgWaitForFinished(reply2));
+
+ QCOMPARE(redSpy2.count(), 2);
+ QCOMPARE(reply2->url(), server3Url);
+ QCOMPARE(reply2->error(), QNetworkReply::NoError);
+}
+
+void tst_QNetworkReply::ioHttpRedirectErrors_data()
+{
+ QTest::addColumn<QString>("url");
+ QTest::addColumn<QString>("dataToSend");
+ QTest::addColumn<QNetworkReply::NetworkError>("error");
+
+ QString tempRedirectReply = QString("HTTP/1.1 307 Temporary Redirect\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: http://localhost:%1\r\n\r\n");
+
+ QTest::newRow("too-many-redirects") << "http://localhost" << tempRedirectReply << QNetworkReply::TooManyRedirectsError;
+ QTest::newRow("insecure-redirect") << "https://localhost" << tempRedirectReply << QNetworkReply::InsecureRedirectError;
+ QTest::newRow("unknown-redirect") << "http://localhost"<< tempRedirectReply.replace("http", "bad_protocol") << QNetworkReply::ProtocolUnknownError;
+}
+
+void tst_QNetworkReply::ioHttpRedirectErrors()
+{
+ QFETCH(QString, url);
+ QFETCH(QString, dataToSend);
+ QFETCH(QNetworkReply::NetworkError, error);
+
+ QUrl localhost(url);
+ MiniHttpServer server("", localhost.scheme() == "https");
+
+ localhost.setPort(server.serverPort());
+
+ QByteArray d2s = dataToSend.arg(
+ QString::number(server.serverPort())).toLatin1();
+ server.setDataToTransmit(d2s);
+
+ QNetworkRequest request(localhost);
+ request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+ QNetworkReplyPtr reply(manager.get(request));
+ if (localhost.scheme() == "https")
+ reply.data()->ignoreSslErrors();
+ QSignalSpy spy(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)));
+
+ QCOMPARE(waitForFinish(reply), int(Failure));
+
+ QCOMPARE(spy.count(), 1);
+ QCOMPARE(reply->error(), error);
+}
#ifndef QT_NO_SSL
class PutWithServerClosingConnectionImmediatelyHandler: public QObject
diff --git a/tests/auto/network/access/spdy/BLACKLIST b/tests/auto/network/access/spdy/BLACKLIST
new file mode 100644
index 0000000000..b13eae1000
--- /dev/null
+++ b/tests/auto/network/access/spdy/BLACKLIST
@@ -0,0 +1,4 @@
+[download]
+linux
+[upload]
+linux
diff --git a/tests/auto/network/access/spdy/spdy.pro b/tests/auto/network/access/spdy/spdy.pro
index 6bfc6d84e0..23efa85b47 100644
--- a/tests/auto/network/access/spdy/spdy.pro
+++ b/tests/auto/network/access/spdy/spdy.pro
@@ -5,3 +5,5 @@ SOURCES += tst_spdy.cpp
QT = core core-private network network-private testlib
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
+
+win32:CONFIG += insignificant_test # QTBUG-47128
diff --git a/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp b/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp
index 7dfc02463e..09ccff4968 100644
--- a/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp
+++ b/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp
@@ -68,7 +68,7 @@ void tst_QNetworkConfiguration::invalidPoint()
QVERIFY(pt.name().isEmpty());
QVERIFY(!pt.isValid());
- QVERIFY(pt.type() == QNetworkConfiguration::Invalid);
+ QCOMPARE(pt.type(), QNetworkConfiguration::Invalid);
QVERIFY(!(pt.state() & QNetworkConfiguration::Defined));
QVERIFY(!(pt.state() & QNetworkConfiguration::Discovered));
QVERIFY(!(pt.state() & QNetworkConfiguration::Active));
@@ -77,7 +77,7 @@ void tst_QNetworkConfiguration::invalidPoint()
QNetworkConfiguration pt2(pt);
QVERIFY(pt2.name().isEmpty());
QVERIFY(!pt2.isValid());
- QVERIFY(pt2.type() == QNetworkConfiguration::Invalid);
+ QCOMPARE(pt2.type(), QNetworkConfiguration::Invalid);
QVERIFY(!(pt2.state() & QNetworkConfiguration::Defined));
QVERIFY(!(pt2.state() & QNetworkConfiguration::Discovered));
QVERIFY(!(pt2.state() & QNetworkConfiguration::Active));
@@ -91,27 +91,27 @@ void tst_QNetworkConfiguration::comparison()
//compare invalid connection points
QNetworkConfiguration pt1;
QVERIFY(!pt1.isValid());
- QVERIFY(pt1.type() == QNetworkConfiguration::Invalid);
+ QCOMPARE(pt1.type(), QNetworkConfiguration::Invalid);
QNetworkConfiguration pt2(pt1);
QVERIFY(pt1==pt2);
QVERIFY(!(pt1!=pt2));
- QVERIFY(pt1.name() == pt2.name());
- QVERIFY(pt1.isValid() == pt2.isValid());
- QVERIFY(pt1.type() == pt2.type());
- QVERIFY(pt1.state() == pt2.state());
- QVERIFY(pt1.purpose() == pt2.purpose());
+ QCOMPARE(pt1.name(), pt2.name());
+ QCOMPARE(pt1.isValid(), pt2.isValid());
+ QCOMPARE(pt1.type(), pt2.type());
+ QCOMPARE(pt1.state(), pt2.state());
+ QCOMPARE(pt1.purpose(), pt2.purpose());
QNetworkConfiguration pt3;
pt3 = pt1;
QVERIFY(pt1==pt3);
QVERIFY(!(pt1!=pt3));
- QVERIFY(pt1.name() == pt3.name());
- QVERIFY(pt1.isValid() == pt3.isValid());
- QVERIFY(pt1.type() == pt3.type());
- QVERIFY(pt1.state() == pt3.state());
- QVERIFY(pt1.purpose() == pt3.purpose());
+ QCOMPARE(pt1.name(), pt3.name());
+ QCOMPARE(pt1.isValid(), pt3.isValid());
+ QCOMPARE(pt1.type(), pt3.type());
+ QCOMPARE(pt1.state(), pt3.state());
+ QCOMPARE(pt1.purpose(), pt3.purpose());
//test case must run on machine that has valid connection points
QNetworkConfigurationManager manager;
@@ -131,11 +131,11 @@ void tst_QNetworkConfiguration::comparison()
pt3 = defaultConfig;
QVERIFY(defaultConfig==pt3);
QVERIFY(!(defaultConfig!=pt3));
- QVERIFY(defaultConfig.name() == pt3.name());
- QVERIFY(defaultConfig.isValid() == pt3.isValid());
- QVERIFY(defaultConfig.type() == pt3.type());
- QVERIFY(defaultConfig.state() == pt3.state());
- QVERIFY(defaultConfig.purpose() == pt3.purpose());
+ QCOMPARE(defaultConfig.name(), pt3.name());
+ QCOMPARE(defaultConfig.isValid(), pt3.isValid());
+ QCOMPARE(defaultConfig.type(), pt3.type());
+ QCOMPARE(defaultConfig.state(), pt3.state());
+ QCOMPARE(defaultConfig.purpose(), pt3.purpose());
}
void tst_QNetworkConfiguration::children()
@@ -178,7 +178,7 @@ void tst_QNetworkConfiguration::isRoamingAvailable()
if ( c.children().count() <= 1 )
QVERIFY(!c.isRoamingAvailable());
foreach(QNetworkConfiguration child, c.children()) {
- QVERIFY(QNetworkConfiguration::InternetAccessPoint == child.type());
+ QCOMPARE(QNetworkConfiguration::InternetAccessPoint, child.type());
QCOMPARE(child.children().count(), 0);
}
} else {
diff --git a/tests/auto/network/bearer/qnetworkconfigurationmanager/tst_qnetworkconfigurationmanager.cpp b/tests/auto/network/bearer/qnetworkconfigurationmanager/tst_qnetworkconfigurationmanager.cpp
index afe1fc274e..94c4d903b2 100644
--- a/tests/auto/network/bearer/qnetworkconfigurationmanager/tst_qnetworkconfigurationmanager.cpp
+++ b/tests/auto/network/bearer/qnetworkconfigurationmanager/tst_qnetworkconfigurationmanager.cpp
@@ -168,7 +168,7 @@ void tst_QNetworkConfigurationManager::defaultConfiguration()
QVERIFY(!defaultConfig.isRoamingAvailable());
QCOMPARE(defaultConfig.state(), QNetworkConfiguration::Discovered);
QNetworkConfiguration copy = manager.configurationFromIdentifier(defaultConfig.identifier());
- QVERIFY(copy == defaultConfig);
+ QCOMPARE(copy, defaultConfig);
}
}
@@ -190,7 +190,7 @@ void tst_QNetworkConfigurationManager::configurationFromIdentifier()
QNetworkConfiguration direct = manager.configurationFromIdentifier(c.identifier());
QVERIFY(direct.isValid());
- QVERIFY(direct == c);
+ QCOMPARE(direct, c);
}
//assume that there is no item with identifier 'FooBar'
diff --git a/tests/auto/network/bearer/qnetworksession/test/tst_qnetworksession.cpp b/tests/auto/network/bearer/qnetworksession/test/tst_qnetworksession.cpp
index 2fd80b3e71..cd510ddfa8 100644
--- a/tests/auto/network/bearer/qnetworksession/test/tst_qnetworksession.cpp
+++ b/tests/auto/network/bearer/qnetworksession/test/tst_qnetworksession.cpp
@@ -187,19 +187,19 @@ void tst_QNetworkSession::invalidSession()
// 1. Verify that session created with invalid configuration remains in invalid state
QNetworkSession session(QNetworkConfiguration(), 0);
QVERIFY(!session.isOpen());
- QVERIFY(session.state() == QNetworkSession::Invalid);
- QVERIFY(session.error() == QNetworkSession::InvalidConfigurationError);
+ QCOMPARE(session.state(), QNetworkSession::Invalid);
+ QCOMPARE(session.error(), QNetworkSession::InvalidConfigurationError);
// 2. Verify that opening session with invalid configuration both 1) emits invalidconfigurationerror and 2) sets session's state as invalid.
QSignalSpy errorSpy(&session, SIGNAL(error(QNetworkSession::SessionError)));
session.open();
session.waitForOpened(1000); // Should bail out right away
- QVERIFY(errorSpy.count() == 1);
+ QCOMPARE(errorSpy.count(), 1);
QNetworkSession::SessionError error =
qvariant_cast<QNetworkSession::SessionError> (errorSpy.first().at(0));
- QVERIFY(error == QNetworkSession::InvalidConfigurationError);
- QVERIFY(session.error() == QNetworkSession::InvalidConfigurationError);
- QVERIFY(session.state() == QNetworkSession::Invalid);
+ QCOMPARE(error, QNetworkSession::InvalidConfigurationError);
+ QCOMPARE(session.error(), QNetworkSession::InvalidConfigurationError);
+ QCOMPARE(session.state(), QNetworkSession::Invalid);
#ifdef QNETWORKSESSION_MANUAL_TESTS
@@ -210,7 +210,7 @@ void tst_QNetworkSession::invalidSession()
qDebug() << "Delete the WLAN IAP from phone now (waiting 60 seconds): " << invalidatedConfig.name();
QTest::qWait(60000);
QVERIFY(!invalidatedConfig.isValid());
- QVERIFY(invalidatedSession.state() == QNetworkSession::Invalid);
+ QCOMPARE(invalidatedSession.state(), QNetworkSession::Invalid);
qDebug() << "Add the WLAN IAP back (waiting 60 seconds): " << invalidatedConfig.name();
QTest::qWait(60000);
}
@@ -235,11 +235,11 @@ void tst_QNetworkSession::invalidSession()
QVERIFY(definedSession.state() == QNetworkSession::NotAvailable); // State is not available because WLAN is not in coverage
QVERIFY(!errorSpy.isEmpty()); // Session tells with error about invalidated configuration
sessionError = qvariant_cast<QNetworkSession::SessionError> (errorSpy.first().at(0));
- QVERIFY(sessionError == QNetworkSession::InvalidConfigurationError);
+ QCOMPARE(sessionError, QNetworkSession::InvalidConfigurationError);
qDebug() << "Turn the WLAN IAP back on (waiting 60 seconds): " << definedConfig.name();
QTest::qWait(60000);
updateConfigurations();
- QVERIFY(definedConfig.state() == QNetworkConfiguration::Discovered);
+ QCOMPARE(definedConfig.state(), QNetworkConfiguration::Discovered);
}
#endif
}
@@ -260,7 +260,7 @@ void tst_QNetworkSession::sessionProperties()
{
QFETCH(QNetworkConfiguration, configuration);
QNetworkSession session(configuration);
- QVERIFY(session.configuration() == configuration);
+ QCOMPARE(session.configuration(), configuration);
QStringList validBearerNames = QStringList() << QLatin1String("Unknown")
<< QLatin1String("Ethernet")
<< QLatin1String("WLAN")
@@ -303,10 +303,10 @@ void tst_QNetworkSession::sessionProperties()
} else {
switch (configuration.state()) {
case QNetworkConfiguration::Undefined:
- QVERIFY(session.state() == QNetworkSession::NotAvailable);
+ QCOMPARE(session.state(), QNetworkSession::NotAvailable);
break;
case QNetworkConfiguration::Defined:
- QVERIFY(session.state() == QNetworkSession::NotAvailable);
+ QCOMPARE(session.state(), QNetworkSession::NotAvailable);
break;
case QNetworkConfiguration::Discovered:
QVERIFY(session.state() == QNetworkSession::Connecting ||
@@ -372,12 +372,12 @@ void tst_QNetworkSession::userChoiceSession()
{
QFETCH(QNetworkConfiguration, configuration);
- QVERIFY(configuration.type() == QNetworkConfiguration::UserChoice);
+ QCOMPARE(configuration.type(), QNetworkConfiguration::UserChoice);
QNetworkSession session(configuration);
// Check that configuration was really set
- QVERIFY(session.configuration() == configuration);
+ QCOMPARE(session.configuration(), configuration);
QVERIFY(!session.isOpen());
@@ -431,7 +431,7 @@ void tst_QNetworkSession::userChoiceSession()
if (expectStateChange)
QTRY_VERIFY_WITH_TIMEOUT(!stateChangedSpy.isEmpty(), TestTimeOut);
- QVERIFY(session.state() == QNetworkSession::Connected);
+ QCOMPARE(session.state(), QNetworkSession::Connected);
#ifndef QT_NO_NETWORKINTERFACE
QVERIFY(session.interface().isValid());
#endif
@@ -462,16 +462,16 @@ void tst_QNetworkSession::userChoiceSession()
manager.configurationFromIdentifier(activeIdentifier);
QVERIFY(activeConfiguration.isValid());
- QVERIFY(activeConfiguration.type() == QNetworkConfiguration::InternetAccessPoint);
+ QCOMPARE(activeConfiguration.type(), QNetworkConfiguration::InternetAccessPoint);
//resetting ActiveConfiguration is ignored (read only property)
session.setSessionProperty("ActiveConfiguration", testIdentifier);
QVERIFY(session.sessionProperty("ActiveConfiguration").toString() != testIdentifier);
if (userChoiceConfiguration.type() == QNetworkConfiguration::InternetAccessPoint) {
- QVERIFY(userChoiceConfiguration == activeConfiguration);
+ QCOMPARE(userChoiceConfiguration, activeConfiguration);
} else {
- QVERIFY(userChoiceConfiguration.type() == QNetworkConfiguration::ServiceNetwork);
+ QCOMPARE(userChoiceConfiguration.type(), QNetworkConfiguration::ServiceNetwork);
QVERIFY(userChoiceConfiguration.children().contains(activeConfiguration));
}
} else {
@@ -500,18 +500,21 @@ void tst_QNetworkSession::sessionOpenCloseStop()
{
QFETCH(QNetworkConfiguration, configuration);
QFETCH(bool, forceSessionStop);
+#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
+ QSKIP("Deadlocks on Linux due to QTBUG-45655");
+#endif
QNetworkSession session(configuration);
// Test initial state of the session.
{
- QVERIFY(session.configuration() == configuration);
+ QCOMPARE(session.configuration(), configuration);
QVERIFY(!session.isOpen());
// session may be invalid if configuration is removed between when
// sessionOpenCloseStop_data() is called and here.
QVERIFY((configuration.isValid() && (session.state() != QNetworkSession::Invalid)) ||
(!configuration.isValid() && (session.state() == QNetworkSession::Invalid)));
- QVERIFY(session.error() == QNetworkSession::UnknownSessionError);
+ QCOMPARE(session.error(), QNetworkSession::UnknownSessionError);
}
// The remaining tests require the session to be not NotAvailable.
@@ -541,7 +544,7 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QNetworkSession::SessionError error =
qvariant_cast<QNetworkSession::SessionError>(errorSpy.first().at(0));
- QVERIFY(session.state() == previousState);
+ QCOMPARE(session.state(), previousState);
if (error == QNetworkSession::OperationNotSupportedError) {
// The session needed to bring up the interface,
@@ -571,13 +574,13 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QNetworkSession::State state =
qvariant_cast<QNetworkSession::State>(stateChangedSpy.at(0).at(0));
- QVERIFY(state == QNetworkSession::Connecting);
+ QCOMPARE(state, QNetworkSession::Connecting);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy.at(1).at(0));
- QVERIFY(state == QNetworkSession::Connected);
+ QCOMPARE(state, QNetworkSession::Connected);
}
- QVERIFY(session.state() == QNetworkSession::Connected);
+ QCOMPARE(session.state(), QNetworkSession::Connected);
#ifndef QT_NO_NETWORKINTERFACE
QVERIFY(session.interface().isValid());
#endif
@@ -600,10 +603,10 @@ void tst_QNetworkSession::sessionOpenCloseStop()
// Test opening a second session.
{
- QVERIFY(session2.configuration() == configuration);
+ QCOMPARE(session2.configuration(), configuration);
QVERIFY(!session2.isOpen());
- QVERIFY(session2.state() == QNetworkSession::Connected);
- QVERIFY(session.error() == QNetworkSession::UnknownSessionError);
+ QCOMPARE(session2.state(), QNetworkSession::Connected);
+ QCOMPARE(session.error(), QNetworkSession::UnknownSessionError);
session2.open();
@@ -611,10 +614,10 @@ void tst_QNetworkSession::sessionOpenCloseStop()
if (errorSpy2.isEmpty()) {
QVERIFY(session2.isOpen());
- QVERIFY(session2.state() == QNetworkSession::Connected);
+ QCOMPARE(session2.state(), QNetworkSession::Connected);
}
QVERIFY(session.isOpen());
- QVERIFY(session.state() == QNetworkSession::Connected);
+ QCOMPARE(session.state(), QNetworkSession::Connected);
#ifndef QT_NO_NETWORKINTERFACE
QVERIFY(session.interface().isValid());
if (errorSpy2.isEmpty()) {
@@ -648,8 +651,8 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QNetworkSession::SessionError error2 =
qvariant_cast<QNetworkSession::SessionError>(errorSpy2.first().at(0));
- QVERIFY(error == QNetworkSession::SessionAbortedError);
- QVERIFY(error2 == QNetworkSession::SessionAbortedError);
+ QCOMPARE(error, QNetworkSession::SessionAbortedError);
+ QCOMPARE(error2, QNetworkSession::SessionAbortedError);
QCOMPARE(errorSpy.count(), 1);
QCOMPARE(errorSpy2.count(), 1);
@@ -668,8 +671,8 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QTRY_VERIFY_WITH_TIMEOUT(stateChangedSpy2.count() >= 1 || !errorSpy2.isEmpty(), TestTimeOut);
if (!errorSpy2.isEmpty()) {
- QVERIFY(session2.state() == previousState);
- QVERIFY(session.state() == previousState);
+ QCOMPARE(session2.state(), previousState);
+ QCOMPARE(session.state(), previousState);
QNetworkSession::SessionError error =
qvariant_cast<QNetworkSession::SessionError>(errorSpy2.first().at(0));
@@ -697,22 +700,22 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QNetworkSession::State state;
if (stateChangedSpy2.count() == 4) {
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(0).at(0));
- QVERIFY(state == QNetworkSession::Connecting);
+ QCOMPARE(state, QNetworkSession::Connecting);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(1).at(0));
- QVERIFY(state == QNetworkSession::Connected);
+ QCOMPARE(state, QNetworkSession::Connected);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(2).at(0));
- QVERIFY(state == QNetworkSession::Closing);
+ QCOMPARE(state, QNetworkSession::Closing);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(3).at(0));
- QVERIFY(state == QNetworkSession::Disconnected);
+ QCOMPARE(state, QNetworkSession::Disconnected);
} else if (stateChangedSpy2.count() == 2) {
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(0).at(0));
- QVERIFY(state == QNetworkSession::Closing);
+ QCOMPARE(state, QNetworkSession::Closing);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(1).at(0));
- QVERIFY(state == QNetworkSession::Disconnected);
+ QCOMPARE(state, QNetworkSession::Disconnected);
} else {
QFAIL("Unexpected amount of state changes when roaming.");
}
@@ -748,7 +751,7 @@ void tst_QNetworkSession::sessionOpenCloseStop()
if (stateChangedSpy.count() > 1) {
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy.at(stateChangedSpy.count() - 2).at(0));
- QVERIFY(state == QNetworkSession::Roaming);
+ QCOMPARE(state, QNetworkSession::Roaming);
}
roamedSuccessfully = true;
}
@@ -776,9 +779,9 @@ void tst_QNetworkSession::sessionOpenCloseStop()
if (stateChangedSpy2.count() == 2) {
QNetworkSession::State state =
qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(0).at(0));
- QVERIFY(state == QNetworkSession::Closing);
+ QCOMPARE(state, QNetworkSession::Closing);
state = qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(1).at(0));
- QVERIFY(state == QNetworkSession::Disconnected);
+ QCOMPARE(state, QNetworkSession::Disconnected);
} else {
QVERIFY(stateChangedSpy2.count() >= 1);
@@ -791,7 +794,7 @@ void tst_QNetworkSession::sessionOpenCloseStop()
QNetworkSession::State state =
qvariant_cast<QNetworkSession::State>(stateChangedSpy2.at(stateChangedSpy2.count() - 1).at(0));
- QVERIFY(state == QNetworkSession::Disconnected);
+ QCOMPARE(state, QNetworkSession::Disconnected);
}
}
@@ -818,14 +821,14 @@ void tst_QNetworkSession::sessionOpenCloseStop()
session2.close();
QTRY_VERIFY_WITH_TIMEOUT(!sessionClosedSpy2.isEmpty(), TestTimeOut);
- QVERIFY(stateChangedSpy2.count() == stateChangedCountBeforeClose);
+ QCOMPARE(stateChangedSpy2.count(), stateChangedCountBeforeClose);
QVERIFY(sessionClosedSpy.isEmpty());
QVERIFY(session.isOpen());
QVERIFY(!session2.isOpen());
- QVERIFY(session.state() == QNetworkSession::Connected);
- QVERIFY(session2.state() == QNetworkSession::Connected);
+ QCOMPARE(session.state(), QNetworkSession::Connected);
+ QCOMPARE(session2.state(), QNetworkSession::Connected);
#ifndef QT_NO_NETWORKINTERFACE
QVERIFY(session.interface().isValid());
QCOMPARE(session.interface().hardwareAddress(), session2.interface().hardwareAddress());
@@ -1233,7 +1236,7 @@ void tst_QNetworkSession::sessionAutoClose()
QNetworkSession session(configuration);
- QVERIFY(session.configuration() == configuration);
+ QCOMPARE(session.configuration(), configuration);
QVariant autoCloseSession = session.sessionProperty(QLatin1String("AutoCloseSessionTimeout"));
@@ -1259,7 +1262,7 @@ void tst_QNetworkSession::sessionAutoClose()
QVERIFY(!session.isOpen());
- QVERIFY(session.configuration() == configuration);
+ QCOMPARE(session.configuration(), configuration);
autoCloseSession = session.sessionProperty(QLatin1String("AutoCloseSessionTimeout"));
diff --git a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
index f6b7dfa3af..026a2a2722 100644
--- a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
+++ b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
@@ -82,7 +82,7 @@ void tst_QAuthenticator::basicAuth()
QAuthenticator auth;
auth.detach();
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(auth);
- QVERIFY(priv->phase == QAuthenticatorPrivate::Start);
+ QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
QList<QPair<QByteArray, QByteArray> > headers;
headers << qMakePair<QByteArray, QByteArray>(QByteArray("WWW-Authenticate"), "Basic " + data.toUtf8());
@@ -94,7 +94,7 @@ void tst_QAuthenticator::basicAuth()
auth.setUser(user);
auth.setPassword(password);
- QVERIFY(priv->phase == QAuthenticatorPrivate::Start);
+ QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
QCOMPARE(priv->calculateResponse("GET", "/").constData(), QByteArray("Basic " + expectedReply).constData());
}
@@ -125,7 +125,7 @@ void tst_QAuthenticator::ntlmAuth()
auth.detach();
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(auth);
- QVERIFY(priv->phase == QAuthenticatorPrivate::Start);
+ QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
QList<QPair<QByteArray, QByteArray> > headers;
diff --git a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
index ef24cbf3c8..8069865d93 100644
--- a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
+++ b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
@@ -83,22 +83,12 @@ private slots:
void isInSubnet();
void isLoopback_data();
void isLoopback();
+ void isMulticast_data();
+ void isMulticast();
void convertv4v6_data();
void convertv4v6();
};
-QT_BEGIN_NAMESPACE
-namespace QTest {
- template<>
- char *toString(const QHostAddress &addr)
- {
- if (addr.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol)
- return qstrdup("<invalid>");
- return qstrdup(addr.toString().toLatin1());
- }
-}
-QT_END_NAMESPACE
-
tst_QHostAddress::tst_QHostAddress()
{
}
@@ -234,7 +224,7 @@ void tst_QHostAddress::setAddress_QString()
QFETCH(int, protocol);
QHostAddress hostAddr;
- QVERIFY(hostAddr.setAddress(address) == ok);
+ QCOMPARE(hostAddr.setAddress(address), ok);
if (ok)
QTEST(hostAddr.toString(), "resAddr");
@@ -316,7 +306,7 @@ void tst_QHostAddress::compare_data()
QTest::newRow("6") << QHostAddress(QHostAddress::LocalHost) << QHostAddress(QHostAddress::LocalHostIPv6) << false;
QTest::newRow("7") << QHostAddress() << QHostAddress(QHostAddress::LocalHostIPv6) << false;
- Q_IPV6ADDR localhostv4mapped = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 0, 0, 1 };
+ Q_IPV6ADDR localhostv4mapped = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 0, 0, 1 } };
QTest::newRow("v4-v4mapped") << QHostAddress(QHostAddress::LocalHost) << QHostAddress("::ffff:127.0.0.1") << false;
QTest::newRow("v4-v4mapped-2") << QHostAddress(QHostAddress::LocalHost) << QHostAddress(localhostv4mapped) << false;
}
@@ -330,7 +320,7 @@ void tst_QHostAddress::compare()
QCOMPARE(first == second, result);
QCOMPARE(second == first, result);
if (result == true)
- QVERIFY(qHash(first) == qHash(second));
+ QCOMPARE(qHash(first), qHash(second));
}
void tst_QHostAddress::assignment()
@@ -399,11 +389,11 @@ void tst_QHostAddress::streaming()
QByteArray ba;
QDataStream ds1(&ba, QIODevice::WriteOnly);
ds1 << address;
- QVERIFY(ds1.status() == QDataStream::Ok);
+ QCOMPARE(ds1.status(), QDataStream::Ok);
QDataStream ds2(&ba, QIODevice::ReadOnly);
QHostAddress address2;
ds2 >> address2;
- QVERIFY(ds2.status() == QDataStream::Ok);
+ QCOMPARE(ds2.status(), QDataStream::Ok);
QCOMPARE(address, address2);
}
@@ -631,6 +621,9 @@ void tst_QHostAddress::isLoopback_data()
QTest::addColumn<QHostAddress>("address");
QTest::addColumn<bool>("result");
+ QTest::newRow("default") << QHostAddress() << false;
+ QTest::newRow("invalid") << QHostAddress("&&&") << false;
+
QTest::newRow("ipv6_loop") << QHostAddress(QHostAddress::LocalHostIPv6) << true;
QTest::newRow("::1") << QHostAddress("::1") << true;
@@ -639,7 +632,6 @@ void tst_QHostAddress::isLoopback_data()
QTest::newRow("127.0.0.2") << QHostAddress("127.0.0.2") << true;
QTest::newRow("127.3.2.1") << QHostAddress("127.3.2.1") << true;
- QTest::newRow("default") << QHostAddress() << false;
QTest::newRow("1.2.3.4") << QHostAddress("1.2.3.4") << false;
QTest::newRow("10.0.0.4") << QHostAddress("10.0.0.4") << false;
QTest::newRow("192.168.3.4") << QHostAddress("192.168.3.4") << false;
@@ -650,10 +642,12 @@ void tst_QHostAddress::isLoopback_data()
QTest::newRow("AnyIPv6") << QHostAddress(QHostAddress::AnyIPv6) << false;
QTest::newRow("Broadcast") << QHostAddress(QHostAddress::Broadcast) << false;
QTest::newRow("Null") << QHostAddress(QHostAddress::Null) << false;
+ QTest::newRow("ipv6-all-ffff") << QHostAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") << false;
QTest::newRow("::ffff:127.0.0.1") << QHostAddress("::ffff:127.0.0.1") << true;
QTest::newRow("::ffff:127.0.0.2") << QHostAddress("::ffff:127.0.0.2") << true;
QTest::newRow("::ffff:127.3.2.1") << QHostAddress("::ffff:127.3.2.1") << true;
+
}
void tst_QHostAddress::isLoopback()
@@ -664,6 +658,50 @@ void tst_QHostAddress::isLoopback()
QCOMPARE(address.isLoopback(), result);
}
+void tst_QHostAddress::isMulticast_data()
+{
+ QTest::addColumn<QHostAddress>("address");
+ QTest::addColumn<bool>("result");
+
+ QTest::newRow("default") << QHostAddress() << false;
+ QTest::newRow("invalid") << QHostAddress("&&&") << false;
+
+ QTest::newRow("ipv6_loop") << QHostAddress(QHostAddress::LocalHostIPv6) << false;
+ QTest::newRow("::1") << QHostAddress("::1") << false;
+ QTest::newRow("ipv4_loop") << QHostAddress(QHostAddress::LocalHost) << false;
+ QTest::newRow("127.0.0.1") << QHostAddress("127.0.0.1") << false;
+ QTest::newRow("::") << QHostAddress("::") << false;
+ QTest::newRow("Any") << QHostAddress(QHostAddress::Any) << false;
+ QTest::newRow("AnyIPv4") << QHostAddress(QHostAddress::AnyIPv4) << false;
+ QTest::newRow("AnyIPv6") << QHostAddress(QHostAddress::AnyIPv6) << false;
+ QTest::newRow("Broadcast") << QHostAddress(QHostAddress::Broadcast) << false;
+ QTest::newRow("Null") << QHostAddress(QHostAddress::Null) << false;
+
+ QTest::newRow("223.255.255.255") << QHostAddress("223.255.255.255") << false;
+ QTest::newRow("224.0.0.0") << QHostAddress("224.0.0.0") << true;
+ QTest::newRow("239.255.255.255") << QHostAddress("239.255.255.255") << true;
+ QTest::newRow("240.0.0.0") << QHostAddress("240.0.0.0") << false;
+
+ QTest::newRow("::ffff:223.255.255.255") << QHostAddress("::ffff:223.255.255.255") << false;
+ QTest::newRow("::ffff:224.0.0.0") << QHostAddress("::ffff:224.0.0.0") << true;
+ QTest::newRow("::ffff:239.255.255.255") << QHostAddress("::ffff:239.255.255.255") << true;
+ QTest::newRow("::ffff:240.0.0.0") << QHostAddress("::ffff:240.0.0.0") << false;
+
+ QTest::newRow("fc00::") << QHostAddress("fc00::") << false;
+ QTest::newRow("fe80::") << QHostAddress("fe80::") << false;
+ QTest::newRow("fec0::") << QHostAddress("fec0::") << false;
+ QTest::newRow("ff00::") << QHostAddress("ff00::") << true;
+ QTest::newRow("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") << QHostAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") << true;
+}
+
+void tst_QHostAddress::isMulticast()
+{
+ QFETCH(QHostAddress, address);
+ QFETCH(bool, result);
+
+ QCOMPARE(address.isMulticast(), result);
+}
+
void tst_QHostAddress::convertv4v6_data()
{
QTest::addColumn<QHostAddress>("source");
diff --git a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
index 599e475beb..5f0addba98 100644
--- a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
+++ b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
@@ -561,13 +561,13 @@ void tst_QHostInfo::cache()
QHostInfo result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(valid == false);
+ QVERIFY(!valid);
QVERIFY(result.addresses().isEmpty());
// loopkup second time, result should come directly
valid = false;
result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
- QVERIFY(valid == true);
+ QVERIFY(valid);
QVERIFY(!result.addresses().isEmpty());
// clear the cache
@@ -578,7 +578,7 @@ void tst_QHostInfo::cache()
result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(valid == false);
+ QVERIFY(!valid);
QVERIFY(result.addresses().isEmpty());
// the slot should have been called 2 times.
diff --git a/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp b/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
index d88b2e222c..cca670e13a 100644
--- a/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
+++ b/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
@@ -76,7 +76,7 @@ void tst_QNetworkAddressEntry::getSetCheck()
entry = entry2;
QCOMPARE(entry, entry2);
- QVERIFY(entry == entry);
+ QCOMPARE(entry, entry);
QVERIFY(!(entry != entry2));
}
diff --git a/tests/auto/network/kernel/qnetworkinterface/BLACKLIST b/tests/auto/network/kernel/qnetworkinterface/BLACKLIST
new file mode 100644
index 0000000000..23bb688d9a
--- /dev/null
+++ b/tests/auto/network/kernel/qnetworkinterface/BLACKLIST
@@ -0,0 +1,2 @@
+[localAddress]
+linux
diff --git a/tests/auto/network/socket/platformsocketengine/BLACKLIST b/tests/auto/network/socket/platformsocketengine/BLACKLIST
new file mode 100644
index 0000000000..8e1a55995e
--- /dev/null
+++ b/tests/auto/network/socket/platformsocketengine/BLACKLIST
@@ -0,0 +1 @@
+windows
diff --git a/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp b/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
index 9bd89cdf4f..71125f463a 100644
--- a/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
+++ b/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
@@ -130,18 +130,18 @@ void tst_PlatformSocketEngine::construction()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(socketDevice.isValid());
- QVERIFY(socketDevice.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(socketDevice.socketType() == QAbstractSocket::TcpSocket);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(socketDevice.socketType(), QAbstractSocket::TcpSocket);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
QVERIFY(socketDevice.socketDescriptor() != -1);
- QVERIFY(socketDevice.localAddress() == QHostAddress());
- QVERIFY(socketDevice.localPort() == 0);
- QVERIFY(socketDevice.peerAddress() == QHostAddress());
- QVERIFY(socketDevice.peerPort() == 0);
- QVERIFY(socketDevice.error() == QAbstractSocket::UnknownSocketError);
+ QCOMPARE(socketDevice.localAddress(), QHostAddress());
+ QCOMPARE(socketDevice.localPort(), quint16(0));
+ QCOMPARE(socketDevice.peerAddress(), QHostAddress());
+ QCOMPARE(socketDevice.peerPort(), quint16(0));
+ QCOMPARE(socketDevice.error(), QAbstractSocket::UnknownSocketError);
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::bytesAvailable() was called in QAbstractSocket::UnconnectedState");
- QVERIFY(socketDevice.bytesAvailable() == -1);
+ QCOMPARE(socketDevice.bytesAvailable(), -1);
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::hasPendingDatagrams() was called in QAbstractSocket::UnconnectedState");
QVERIFY(!socketDevice.hasPendingDatagrams());
@@ -154,16 +154,16 @@ void tst_PlatformSocketEngine::simpleConnectToIMAP()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
const bool isConnected = socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143);
if (!isConnected) {
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
}
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -200,8 +200,8 @@ void tst_PlatformSocketEngine::simpleConnectToIMAP()
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
//---------------------------------------------------------------------------
@@ -213,13 +213,13 @@ void tst_PlatformSocketEngine::udpLoopbackTest()
QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket));
QVERIFY(udpSocket.isValid());
QVERIFY(udpSocket.socketDescriptor() != -1);
- QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket);
- QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(udpSocket.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(udpSocket.socketType(), QAbstractSocket::UdpSocket);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::UnconnectedState);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0));
- QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
@@ -229,7 +229,7 @@ void tst_PlatformSocketEngine::udpLoopbackTest()
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port));
- QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(udpSocket2.state(), QAbstractSocket::ConnectedState);
// Write a message to #1
QByteArray message1 = "hei der";
@@ -243,13 +243,13 @@ void tst_PlatformSocketEngine::udpLoopbackTest()
QVERIFY(available > 0);
QByteArray answer;
answer.resize(available);
- QHostAddress senderAddress;
- quint16 senderPort = 0;
- QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(),
- &senderAddress,
- &senderPort) == message1.size());
- QVERIFY(senderAddress == QHostAddress("127.0.0.1"));
- QVERIFY(senderPort != 0);
+ QIpPacketHeader header;
+ QCOMPARE(udpSocket.readDatagram(answer.data(), answer.size(),
+ &header, QAbstractSocketEngine::WantDatagramSender),
+ qint64(message1.size()));
+ QVERIFY(header.senderAddress == QHostAddress("127.0.0.1"));
+ QCOMPARE(header.senderAddress, QHostAddress("127.0.0.1"));
+ QVERIFY(header.senderPort != 0);
}
//---------------------------------------------------------------------------
@@ -261,13 +261,13 @@ void tst_PlatformSocketEngine::udpIPv6LoopbackTest()
bool init = udpSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv6Protocol);
if (!init) {
- QVERIFY(udpSocket.error() == QAbstractSocket::UnsupportedSocketOperationError);
+ QCOMPARE(udpSocket.error(), QAbstractSocket::UnsupportedSocketOperationError);
} else {
- QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv6Protocol);
+ QCOMPARE(udpSocket.protocol(), QAbstractSocket::IPv6Protocol);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("::1"), 0));
- QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
@@ -277,7 +277,7 @@ void tst_PlatformSocketEngine::udpIPv6LoopbackTest()
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("::1"), port));
- QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(udpSocket2.state(), QAbstractSocket::ConnectedState);
// Write a message to #1
QByteArray message1 = "hei der";
@@ -291,13 +291,13 @@ void tst_PlatformSocketEngine::udpIPv6LoopbackTest()
QVERIFY(available > 0);
QByteArray answer;
answer.resize(available);
- QHostAddress senderAddress;
- quint16 senderPort = 0;
- QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(),
- &senderAddress,
- &senderPort) == message1.size());
- QVERIFY(senderAddress == QHostAddress("::1"));
- QVERIFY(senderPort != 0);
+ QIpPacketHeader header;
+ QCOMPARE(udpSocket.readDatagram(answer.data(), answer.size(),
+ &header, QAbstractSocketEngine::WantDatagramSender),
+ qint64(message1.size()));
+ QVERIFY(header.senderAddress == QHostAddress("::1"));
+ QCOMPARE(header.senderAddress, QHostAddress("::1"));
+ QVERIFY(header.senderPort != 0);
}
}
@@ -314,7 +314,7 @@ void tst_PlatformSocketEngine::broadcastTest()
// Bind to any port on all interfaces
QVERIFY(broadcastSocket.bind(QHostAddress::Any, 0));
- QVERIFY(broadcastSocket.state() == QAbstractSocket::BoundState);
+ QCOMPARE(broadcastSocket.state(), QAbstractSocket::BoundState);
quint16 port = broadcastSocket.localPort();
QVERIFY(port > 0);
@@ -323,9 +323,9 @@ void tst_PlatformSocketEngine::broadcastTest()
= "MOOT wtf is a MOOT? talk english not your sutpiD ENGLISH.";
qint64 written = broadcastSocket.writeDatagram(trollMessage.data(),
trollMessage.size(),
- QHostAddress::Broadcast,
- port);
+ QIpPacketHeader(QHostAddress::Broadcast, port));
+ QVERIFY2(written != -1, qt_error_string().toLocal8Bit());
QCOMPARE((int)written, trollMessage.size());
// Wait until we receive it ourselves
@@ -354,20 +354,20 @@ void tst_PlatformSocketEngine::serverTest()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
// Initialize a Tcp socket
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket));
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
- QVERIFY(client.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}
// The server accepts the connection
@@ -378,7 +378,7 @@ void tst_PlatformSocketEngine::serverTest()
// socket descriptor from accept(). It's pre-connected.
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
// The server socket sends a greeting to the clietn
QByteArray greeting = "Greetings!";
@@ -407,13 +407,13 @@ void tst_PlatformSocketEngine::udpLoopbackPerformance()
QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket));
QVERIFY(udpSocket.isValid());
QVERIFY(udpSocket.socketDescriptor() != -1);
- QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket);
- QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(udpSocket.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(udpSocket.socketType(), QAbstractSocket::UdpSocket);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::UnconnectedState);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0));
- QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
@@ -423,7 +423,7 @@ void tst_PlatformSocketEngine::udpLoopbackPerformance()
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port));
- QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(udpSocket2.state(), QAbstractSocket::ConnectedState);
const int messageSize = 8192;
QByteArray message1(messageSize, '@');
@@ -459,12 +459,12 @@ void tst_PlatformSocketEngine::tcpLoopbackPerformance()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
// Initialize a Tcp socket
PLATFORMSOCKETENGINE client;
@@ -472,9 +472,9 @@ void tst_PlatformSocketEngine::tcpLoopbackPerformance()
// Connect to our server
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
- QVERIFY(client.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}
// The server accepts the connection
@@ -485,7 +485,7 @@ void tst_PlatformSocketEngine::tcpLoopbackPerformance()
// socket descriptor from accept(). It's pre-connected.
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
const int messageSize = 1024 * 256;
QByteArray message1(messageSize, '@');
@@ -562,7 +562,7 @@ void tst_PlatformSocketEngine::bind()
PLATFORMSOCKETENGINE binder;
QVERIFY(binder.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(!binder.bind(QHostAddress::AnyIPv4, 82));
- QVERIFY(binder.error() == QAbstractSocket::SocketAccessError);
+ QCOMPARE(binder.error(), QAbstractSocket::SocketAccessError);
#endif
PLATFORMSOCKETENGINE binder2;
@@ -572,7 +572,7 @@ void tst_PlatformSocketEngine::bind()
PLATFORMSOCKETENGINE binder3;
QVERIFY(binder3.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(!binder3.bind(QHostAddress::AnyIPv4, 31180));
- QVERIFY(binder3.error() == QAbstractSocket::AddressInUseError);
+ QCOMPARE(binder3.error(), QAbstractSocket::AddressInUseError);
if (QtNetworkSettings::hasIPv6()) {
PLATFORMSOCKETENGINE binder4;
@@ -582,7 +582,7 @@ void tst_PlatformSocketEngine::bind()
PLATFORMSOCKETENGINE binder5;
QVERIFY(binder5.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv6Protocol));
QVERIFY(!binder5.bind(QHostAddress::AnyIPv6, 31180));
- QVERIFY(binder5.error() == QAbstractSocket::AddressInUseError);
+ QCOMPARE(binder5.error(), QAbstractSocket::AddressInUseError);
}
PLATFORMSOCKETENGINE binder6;
@@ -599,11 +599,11 @@ void tst_PlatformSocketEngine::networkError()
const bool isConnected = client.connectToHost(QtNetworkSettings::serverIP(), 143);
if (!isConnected) {
- QVERIFY(client.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
// An unexpected network error!
#ifdef Q_OS_WINRT
@@ -636,7 +636,7 @@ void tst_PlatformSocketEngine::invalidSend()
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::writeDatagram() was"
" called by a socket other than QAbstractSocket::UdpSocket");
- QCOMPARE(socket.writeDatagram("hei", 3, QHostAddress::LocalHost, 143),
+ QCOMPARE(socket.writeDatagram("hei", 3, QIpPacketHeader(QHostAddress::LocalHost, 143)),
(qlonglong) -1);
}
@@ -650,19 +650,19 @@ void tst_PlatformSocketEngine::receiveUrgentData()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
quint16 port = server.localPort();
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket));
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
- QVERIFY(client.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}
int socketDescriptor = server.accept();
@@ -670,7 +670,7 @@ void tst_PlatformSocketEngine::receiveUrgentData()
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
char msg;
int available;
diff --git a/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp b/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
index 76c36831bd..1c79b6c016 100644
--- a/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
+++ b/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
@@ -37,11 +37,6 @@
#include <qcoreapplication.h>
#include <qdebug.h>
#include <qabstractsocket.h>
-#include <qtcpserver.h>
-#include <qtcpsocket.h>
-#ifndef QT_NO_SSL
-#include <qsslsocket.h>
-#endif
class tst_QAbstractSocket : public QObject
{
@@ -52,9 +47,7 @@ public:
virtual ~tst_QAbstractSocket();
private slots:
- void initTestCase();
void getSetCheck();
- void serverDisconnectWithBuffered();
};
tst_QAbstractSocket::tst_QAbstractSocket()
@@ -73,11 +66,6 @@ public:
void setPeerPort(quint16 port) { QAbstractSocket::setPeerPort(port); }
};
-void tst_QAbstractSocket::initTestCase()
-{
- qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
-}
-
// Testing get/set functions
void tst_QAbstractSocket::getSetCheck()
{
@@ -106,46 +94,5 @@ void tst_QAbstractSocket::getSetCheck()
QCOMPARE(quint16(0xffff), obj1.peerPort());
}
-// Test buffered socket being properly closed on remote disconnect
-void tst_QAbstractSocket::serverDisconnectWithBuffered()
-{
- QTcpServer tcpServer;
-#ifndef QT_NO_SSL
- QSslSocket testSocket;
-#else
- QTcpSocket testSocket;
-#endif
-
- QVERIFY(tcpServer.listen(QHostAddress::LocalHost));
- testSocket.connectToHost(tcpServer.serverAddress(), tcpServer.serverPort());
- // Accept connection on server side
- QVERIFY(tcpServer.waitForNewConnection(5000));
- QTcpSocket *newConnection = tcpServer.nextPendingConnection();
- // Send one char and drop link
- QVERIFY(newConnection != NULL);
- QVERIFY(newConnection->putChar(0));
- QVERIFY(newConnection->flush());
- delete newConnection;
-
- QVERIFY(testSocket.waitForConnected(5000)); // ready for write
- QVERIFY(testSocket.state() == QAbstractSocket::ConnectedState);
-
- QSignalSpy spyStateChanged(&testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
- QSignalSpy spyDisconnected(&testSocket, SIGNAL(disconnected()));
-
- QVERIFY(testSocket.waitForReadyRead(5000)); // have one char already in internal buffer
- char buf[128];
- QCOMPARE(testSocket.read(buf, sizeof(buf)), Q_INT64_C(1));
- if (testSocket.state() != QAbstractSocket::UnconnectedState) {
- QVERIFY(testSocket.waitForDisconnected(5000));
- QVERIFY(testSocket.state() == QAbstractSocket::UnconnectedState);
- }
- // Test signal emitting
- QVERIFY(spyDisconnected.count() == 1);
- QVERIFY(spyStateChanged.count() > 0);
- QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
- == QAbstractSocket::UnconnectedState);
-}
-
QTEST_MAIN(tst_QAbstractSocket)
#include "tst_qabstractsocket.moc"
diff --git a/tests/auto/network/socket/qhttpsocketengine/BLACKLIST b/tests/auto/network/socket/qhttpsocketengine/BLACKLIST
new file mode 100644
index 0000000000..8e1a55995e
--- /dev/null
+++ b/tests/auto/network/socket/qhttpsocketengine/BLACKLIST
@@ -0,0 +1 @@
+windows
diff --git a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
index 10e8c95fc0..179cdb76bc 100644
--- a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
+++ b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
@@ -164,18 +164,18 @@ void tst_QHttpSocketEngine::construction()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(socketDevice.isValid());
- QVERIFY(socketDevice.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(socketDevice.socketType() == QAbstractSocket::TcpSocket);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(socketDevice.socketType(), QAbstractSocket::TcpSocket);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
// QVERIFY(socketDevice.socketDescriptor() != -1);
- QVERIFY(socketDevice.localAddress() == QHostAddress());
- QVERIFY(socketDevice.localPort() == 0);
- QVERIFY(socketDevice.peerAddress() == QHostAddress());
- QVERIFY(socketDevice.peerPort() == 0);
- QVERIFY(socketDevice.error() == QAbstractSocket::UnknownSocketError);
+ QCOMPARE(socketDevice.localAddress(), QHostAddress());
+ QCOMPARE(socketDevice.localPort(), quint16(0));
+ QCOMPARE(socketDevice.peerAddress(), QHostAddress());
+ QCOMPARE(socketDevice.peerPort(), quint16(0));
+ QCOMPARE(socketDevice.error(), QAbstractSocket::UnknownSocketError);
//QTest::ignoreMessage(QtWarningMsg, "QSocketLayer::bytesAvailable() was called in QAbstractSocket::UnconnectedState");
- QVERIFY(socketDevice.bytesAvailable() == 0);
+ QCOMPARE(socketDevice.bytesAvailable(), 0);
//QTest::ignoreMessage(QtWarningMsg, "QSocketLayer::hasPendingDatagrams() was called in QAbstractSocket::UnconnectedState");
QVERIFY(!socketDevice.hasPendingDatagrams());
@@ -299,15 +299,15 @@ void tst_QHttpSocketEngine::simpleConnectToIMAP()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3128));
QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
QVERIFY(!socketDevice.localAddress().isNull());
QVERIFY(socketDevice.localPort() > 0);
@@ -345,8 +345,8 @@ void tst_QHttpSocketEngine::simpleConnectToIMAP()
QVERIFY(socketDevice.waitForRead());
char c;
QCOMPARE(socketDevice.read(&c, sizeof(c)), (qint64) -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
//---------------------------------------------------------------------------
@@ -360,14 +360,14 @@ void tst_QHttpSocketEngine::simpleErrorsAndStates()
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3128));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
QVERIFY(!socketDevice.connectToHost(QHostAddress(QtNetworkSettings::serverName()), 8088));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
if (socketDevice.waitForWrite(30000)) {
QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState ||
socketDevice.state() == QAbstractSocket::UnconnectedState);
} else {
- QVERIFY(socketDevice.error() == QAbstractSocket::SocketTimeoutError);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::SocketTimeoutError);
}
}
@@ -381,12 +381,12 @@ void tst_QHttpSocketEngine::tcpLoopbackPerformance()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
// Initialize a Tcp socket
QHttpSocketEngine client;
@@ -408,7 +408,7 @@ void tst_QHttpSocketEngine::tcpLoopbackPerformance()
// socket descriptor from accept(). It's pre-connected.
QSocketLayer serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
const int messageSize = 1024 * 256;
QByteArray message1(messageSize, '@');
@@ -544,7 +544,7 @@ void tst_QHttpSocketEngine::tcpSocketNonBlockingTest()
QFAIL("Timed out");
}
- QVERIFY(tcpSocketNonBlocking_totalWritten == 8);
+ QCOMPARE(tcpSocketNonBlocking_totalWritten, 8);
QTestEventLoop::instance().enterLoop(30);
@@ -569,7 +569,7 @@ void tst_QHttpSocketEngine::tcpSocketNonBlockingTest()
QFAIL("Timed out");
}
- QVERIFY(tcpSocketNonBlocking_totalWritten == 10);
+ QCOMPARE(tcpSocketNonBlocking_totalWritten, 10);
// Wait for greeting
QTestEventLoop::instance().enterLoop(30);
@@ -637,7 +637,7 @@ void tst_QHttpSocketEngine::downloadBigFile()
QFAIL("Network operation timed out");
QByteArray hostName = QtNetworkSettings::serverName().toLatin1();
- QVERIFY(tmpSocket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
QVERIFY(tmpSocket->write("GET /qtest/mediumfile HTTP/1.0\r\n") > 0);
QVERIFY(tmpSocket->write("Host: ") > 0);
QVERIFY(tmpSocket->write(hostName.data()) > 0);
@@ -659,7 +659,7 @@ void tst_QHttpSocketEngine::downloadBigFile()
QVERIFY(bytesAvailable >= 10000000);
- QVERIFY(tmpSocket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s",
bytesAvailable / (1024.0 * 1024.0),
@@ -689,15 +689,15 @@ void tst_QHttpSocketEngine::passwordAuth()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3128, "qsockstest", "password"));
QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -733,8 +733,8 @@ void tst_QHttpSocketEngine::passwordAuth()
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
//----------------------------------------------------------------------------------
diff --git a/tests/auto/network/socket/qlocalsocket/BLACKLIST b/tests/auto/network/socket/qlocalsocket/BLACKLIST
new file mode 100644
index 0000000000..11ddef30a5
--- /dev/null
+++ b/tests/auto/network/socket/qlocalsocket/BLACKLIST
@@ -0,0 +1,2 @@
+[processConnection:1 client]
+windows
diff --git a/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp b/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
index 4881d86937..847e065aa8 100644
--- a/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
+++ b/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
@@ -246,8 +246,8 @@ void tst_QLocalSocket::socket_basic()
QCOMPARE(socket.serverName(), QString());
QCOMPARE(socket.fullServerName(), QString());
socket.abort();
- QVERIFY(socket.bytesAvailable() == 0);
- QVERIFY(socket.bytesToWrite() == 0);
+ QCOMPARE(socket.bytesAvailable(), 0);
+ QCOMPARE(socket.bytesToWrite(), 0);
QCOMPARE(socket.canReadLine(), false);
socket.close();
socket.disconnectFromServer();
@@ -255,7 +255,7 @@ void tst_QLocalSocket::socket_basic()
QVERIFY(!socket.errorString().isEmpty());
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), false);
- QVERIFY(socket.readBufferSize() == 0);
+ QCOMPARE(socket.readBufferSize(), 0);
socket.setReadBufferSize(0);
//QCOMPARE(socket.socketDescriptor(), (qintptr)-1);
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
@@ -375,13 +375,13 @@ void tst_QLocalSocket::listenAndConnect()
QVERIFY(!socket->errorString().isEmpty());
QVERIFY(socket->error() != QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::UnconnectedState);
- //QVERIFY(socket->socketDescriptor() == -1);
+ //QCOMPARE(socket->socketDescriptor(), -1);
QCOMPARE(qvariant_cast<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::ServerNotFoundError);
}
- QVERIFY(socket->bytesAvailable() == 0);
- QVERIFY(socket->bytesToWrite() == 0);
+ QCOMPARE(socket->bytesAvailable(), 0);
+ QCOMPARE(socket->bytesToWrite(), 0);
QCOMPARE(socket->canReadLine(), false);
QCOMPARE(socket->flush(), false);
QCOMPARE(socket->isValid(), canListen);
@@ -432,7 +432,7 @@ void tst_QLocalSocket::listenAndConnect()
} else {
QVERIFY(server.serverName().isEmpty());
QVERIFY(server.fullServerName().isEmpty());
- QVERIFY(server.nextPendingConnection() == (QLocalSocket*)0);
+ QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
QCOMPARE(spyNewConnection.count(), 0);
QCOMPARE(server.hits.count(), 0);
QVERIFY(!server.errorString().isEmpty());
@@ -616,7 +616,7 @@ void tst_QLocalSocket::readBufferOverflow()
QVERIFY(client.waitForReadyRead());
QCOMPARE(client.read(buffer, readBufferSize), qint64(readBufferSize));
// no more bytes available
- QVERIFY(client.bytesAvailable() == 0);
+ QCOMPARE(client.bytesAvailable(), 0);
}
// QLocalSocket/Server can take a name or path, check that it works as expected
@@ -912,7 +912,7 @@ void tst_QLocalSocket::waitForDisconnectByServer()
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
serverSocket->close();
- QVERIFY(serverSocket->state() == QLocalSocket::UnconnectedState);
+ QCOMPARE(serverSocket->state(), QLocalSocket::UnconnectedState);
QVERIFY(socket.waitForDisconnected(3000));
QCOMPARE(spy.count(), 1);
}
@@ -1197,11 +1197,12 @@ void tst_QLocalSocket::verifyListenWithDescriptor()
QVERIFY2(server.listen(listenSocket), "failed to start create QLocalServer with local socket");
#ifdef Q_OS_LINUX
+ const QChar at(QLatin1Char('@'));
if (!bound) {
- QVERIFY(server.serverName().at(0) == QLatin1Char('@'));
- QVERIFY(server.fullServerName().at(0) == QLatin1Char('@'));
+ QCOMPARE(server.serverName().at(0), at);
+ QCOMPARE(server.fullServerName().at(0), at);
} else if (abstract) {
- QVERIFY2(server.fullServerName().at(0) == QLatin1Char('@'), "abstract sockets should start with a '@'");
+ QVERIFY2(server.fullServerName().at(0) == at, "abstract sockets should start with a '@'");
} else {
QCOMPARE(server.fullServerName(), path);
if (path.contains(QLatin1String("/"))) {
diff --git a/tests/auto/network/socket/qsocks5socketengine/BLACKLIST b/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
index bf4afa8c45..2a32a326d0 100644
--- a/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
+++ b/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
@@ -2,3 +2,5 @@
*
[passwordAuth]
*
+[serverTest]
+windows
diff --git a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
index 0ae9887773..8da656aab7 100644
--- a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
+++ b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
@@ -193,18 +193,18 @@ void tst_QSocks5SocketEngine::construction()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(socketDevice.isValid());
- QVERIFY(socketDevice.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(socketDevice.socketType() == QAbstractSocket::TcpSocket);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(socketDevice.socketType(), QAbstractSocket::TcpSocket);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
// QVERIFY(socketDevice.socketDescriptor() != -1);
- QVERIFY(socketDevice.localAddress() == QHostAddress());
- QVERIFY(socketDevice.localPort() == 0);
- QVERIFY(socketDevice.peerAddress() == QHostAddress());
- QVERIFY(socketDevice.peerPort() == 0);
- QVERIFY(socketDevice.error() == QAbstractSocket::UnknownSocketError);
+ QCOMPARE(socketDevice.localAddress(), QHostAddress());
+ QCOMPARE(socketDevice.localPort(), quint16(0));
+ QCOMPARE(socketDevice.peerAddress(), QHostAddress());
+ QCOMPARE(socketDevice.peerPort(), quint16(0));
+ QCOMPARE(socketDevice.error(), QAbstractSocket::UnknownSocketError);
//QTest::ignoreMessage(QtWarningMsg, "QSocketLayer::bytesAvailable() was called in QAbstractSocket::UnconnectedState");
- QVERIFY(socketDevice.bytesAvailable() == 0);
+ QCOMPARE(socketDevice.bytesAvailable(), 0);
//QTest::ignoreMessage(QtWarningMsg, "QSocketLayer::hasPendingDatagrams() was called in QAbstractSocket::UnconnectedState");
QVERIFY(!socketDevice.hasPendingDatagrams());
@@ -334,15 +334,15 @@ void tst_QSocks5SocketEngine::simpleConnectToIMAP()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -377,8 +377,8 @@ void tst_QSocks5SocketEngine::simpleConnectToIMAP()
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
//---------------------------------------------------------------------------
@@ -392,14 +392,14 @@ void tst_QSocks5SocketEngine::simpleErrorsAndStates()
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
QVERIFY(!socketDevice.connectToHost(QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first(), 8088));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
if (socketDevice.waitForWrite(15000)) {
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState ||
socketDevice.state() == QAbstractSocket::ConnectedState);
} else {
- QVERIFY(socketDevice.error() == QAbstractSocket::SocketTimeoutError);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::SocketTimeoutError);
}
}
@@ -413,12 +413,12 @@ void tst_QSocks5SocketEngine::tcpLoopbackPerformance()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
// Initialize a Tcp socket
QSocks5SocketEngine client;
@@ -440,7 +440,7 @@ void tst_QSocks5SocketEngine::tcpLoopbackPerformance()
// socket descriptor from accept(). It's pre-connected.
QSocketLayer serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
const int messageSize = 1024 * 256;
QByteArray message1(messageSize, '@');
@@ -482,11 +482,11 @@ void tst_QSocks5SocketEngine::serverTest()
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
- QVERIFY(server.state() == QAbstractSocket::BoundState);
+ QCOMPARE(server.state(), QAbstractSocket::BoundState);
// Listen for incoming connections
QVERIFY(server.listen());
- QVERIFY(server.state() == QAbstractSocket::ListeningState);
+ QCOMPARE(server.state(), QAbstractSocket::ListeningState);
// Initialize a Tcp socket
QSocks5SocketEngine client;
@@ -501,7 +501,7 @@ void tst_QSocks5SocketEngine::serverTest()
if (!client.connectToHost(server.localAddress(), server.localPort())) {
QVERIFY(client.waitForWrite());
// QTest::wait(100); // ### timing problem on win32
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
//QTest::wait(100);
}
@@ -516,14 +516,14 @@ void tst_QSocks5SocketEngine::serverTest()
QSocks5SocketEngine serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
- QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(serverSocket.state(), QAbstractSocket::ConnectedState);
- QVERIFY(serverSocket.localAddress() == client.peerAddress());
- QVERIFY(serverSocket.localPort() == client.peerPort());
+ QCOMPARE(serverSocket.localAddress(), client.peerAddress());
+ QCOMPARE(serverSocket.localPort(), client.peerPort());
// this seems depends on the socks server implementation, especially
// when connecting /to/ the socks server /through/ the same socks server
- //QVERIFY(serverSocket.peerAddress() == client.localAddress());
- //QVERIFY(serverSocket.peerPort() == client.localPort());
+ //QCOMPARE(serverSocket.peerAddress(), client.localAddress());
+ //QCOMPARE(serverSocket.peerPort(), client.localPort());
// The server socket sends a greeting to the client
QByteArray greeting = "Greetings!";
@@ -557,16 +557,16 @@ void tst_QSocks5SocketEngine::udpTest()
udpSocket.setProxy(proxy);
- QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol);
- QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket);
- QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(udpSocket.protocol(), QAbstractSocket::IPv4Protocol);
+ QCOMPARE(udpSocket.socketType(), QAbstractSocket::UdpSocket);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::UnconnectedState);
// Bind #1
bool bindSuccessful = udpSocket.bind(QHostAddress("0.0.0.0"), 0);
if (!bindSuccessful)
QEXPECT_FAIL("", "QTBUG-23380 / QTBUG-35490: Fails on some Ubuntu 11.10 x64 configurations and on new network test server", Abort);
QVERIFY(bindSuccessful);
- QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
+ QCOMPARE(udpSocket.state(), QAbstractSocket::BoundState);
QVERIFY(udpSocket.localPort() != 0);
// Initialize device #2
@@ -577,7 +577,7 @@ void tst_QSocks5SocketEngine::udpTest()
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(udpSocket.localAddress(), udpSocket.localPort()));
- QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(udpSocket2.state(), QAbstractSocket::ConnectedState);
// Write a message to #1
QByteArray message1 = "hei der";
@@ -591,13 +591,13 @@ void tst_QSocks5SocketEngine::udpTest()
QVERIFY(available > 0);
QByteArray answer;
answer.resize(available);
- QHostAddress senderAddress;
- quint16 senderPort = 0;
- QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(),
- &senderAddress,
- &senderPort) == message1.size());
- QVERIFY(senderAddress == udpSocket2.localAddress());
- QVERIFY(senderPort == udpSocket2.localPort());
+ QIpPacketHeader header;
+ QCOMPARE(udpSocket.readDatagram(answer.data(), answer.size(),
+ &header, QAbstractSocketEngine::WantDatagramSender),
+ qint64(message1.size()));
+ QVERIFY(header.senderAddress == udpSocket2.localAddress());
+ QCOMPARE(header.senderAddress, udpSocket2.localAddress());
+ QCOMPARE(header.senderPort, udpSocket2.localPort());
}
void tst_QSocks5SocketEngine::tcpSocketBlockingTest()
@@ -705,7 +705,7 @@ void tst_QSocks5SocketEngine::tcpSocketNonBlockingTest()
QFAIL("Timed out");
}
- QVERIFY(tcpSocketNonBlocking_totalWritten == 8);
+ QCOMPARE(tcpSocketNonBlocking_totalWritten, 8);
QTestEventLoop::instance().enterLoop(30);
@@ -729,7 +729,7 @@ void tst_QSocks5SocketEngine::tcpSocketNonBlockingTest()
QFAIL("Timed out");
}
- QVERIFY(tcpSocketNonBlocking_totalWritten == 10);
+ QCOMPARE(tcpSocketNonBlocking_totalWritten, 10);
// Wait for greeting
QTestEventLoop::instance().enterLoop(30);
@@ -797,7 +797,7 @@ void tst_QSocks5SocketEngine::downloadBigFile()
QFAIL("Network operation timed out");
QByteArray hostName = QtNetworkSettings::serverName().toLatin1();
- QVERIFY(tmpSocket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
QVERIFY(tmpSocket->write("GET /qtest/mediumfile HTTP/1.0\r\n") > 0);
QVERIFY(tmpSocket->write("HOST: ") > 0);
QVERIFY(tmpSocket->write(hostName.data()) > 0);
@@ -819,7 +819,7 @@ void tst_QSocks5SocketEngine::downloadBigFile()
QCOMPARE(bytesAvailable, qint64(10000000));
- QVERIFY(tmpSocket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
/*qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s",
bytesAvailable / (1024.0 * 1024.0),
@@ -852,19 +852,19 @@ void tst_QSocks5SocketEngine::passwordAuth()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080, "qsockstest", "password"));
// Connect to imap.trolltech.com's IP
QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
if (!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143)) {
qDebug("%d, %s", socketDevice.error(), socketDevice.errorString().toLatin1().constData());
}
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -899,8 +899,8 @@ void tst_QSocks5SocketEngine::passwordAuth()
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
//----------------------------------------------------------------------------------
@@ -918,21 +918,21 @@ void tst_QSocks5SocketEngine::passwordAuth2()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081));
socketDevice.setReceiver(this);
QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
while (socketDevice.state() == QAbstractSocket::ConnectingState) {
QVERIFY(socketDevice.waitForWrite());
socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143);
}
if (socketDevice.state() != QAbstractSocket::ConnectedState)
qDebug("%d, %s", socketDevice.error(), socketDevice.errorString().toLatin1().constData());
- QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
- QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -967,8 +967,8 @@ void tst_QSocks5SocketEngine::passwordAuth2()
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
- QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
- QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socketDevice.error(), QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
}
void tst_QSocks5SocketEngine::fragmentation_data()
@@ -1017,7 +1017,7 @@ void tst_QSocks5SocketEngine::fragmentation()
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(socket.localAddress() == QHostAddress("1.2.3.4") || socket.localAddress() == QHostAddress("0123:4567:89ab:cdef:0123:4567:89ab:cdef"));
- QVERIFY(socket.localPort() == 0x0506);
+ QCOMPARE(socket.localPort(), quint16(0x0506));
}
void tst_QSocks5SocketEngine::incomplete_data()
diff --git a/tests/auto/network/socket/qtcpserver/BLACKLIST b/tests/auto/network/socket/qtcpserver/BLACKLIST
new file mode 100644
index 0000000000..f8b61808cc
--- /dev/null
+++ b/tests/auto/network/socket/qtcpserver/BLACKLIST
@@ -0,0 +1,13 @@
+windows
+[linkLocal]
+linux
+[listenWhileListening:WithSocks5Proxy]
+linux
+windows
+[ipv6Server:WithoutProxy]
+windows
+osx
+[clientServerLoop:WithSocks5Proxy]
+linux
+[crashTests:WithSocks5Proxy]
+linux
diff --git a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
index e0a6e3699d..5df5432cdd 100644
--- a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
+++ b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
@@ -265,11 +265,11 @@ void tst_QTcpServer::ipv6Server()
//### need to enter the event loop for the server to get the connection ?? ( windows)
QTcpServer server;
if (!server.listen(QHostAddress::LocalHostIPv6, 8944)) {
- QVERIFY(server.serverError() == QAbstractSocket::UnsupportedSocketOperationError);
+ QCOMPARE(server.serverError(), QAbstractSocket::UnsupportedSocketOperationError);
return;
}
- QVERIFY(server.serverPort() == 8944);
+ QCOMPARE(server.serverPort(), quint16(8944));
QVERIFY(server.serverAddress() == QHostAddress::LocalHostIPv6);
QTcpSocket client;
@@ -835,17 +835,17 @@ void tst_QTcpServer::qtbug14268_peek()
client.write("abc\n");
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(helper.lastDataPeeked == QByteArray("6162630a"));
+ QCOMPARE(helper.lastDataPeeked, QByteArray("6162630a"));
client.write("def\n");
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(helper.lastDataPeeked == QByteArray("6162630a6465660a"));
+ QCOMPARE(helper.lastDataPeeked, QByteArray("6162630a6465660a"));
client.write("ghi\n");
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(helper.lastDataPeeked == QByteArray("6162630a6465660a6768690a"));
+ QCOMPARE(helper.lastDataPeeked, QByteArray("6162630a6465660a6768690a"));
}
void tst_QTcpServer::serverAddress_data()
diff --git a/tests/auto/network/socket/qtcpsocket/test/test.pro b/tests/auto/network/socket/qtcpsocket/test/test.pro
index 3e64b87b53..325abcaab8 100644
--- a/tests/auto/network/socket/qtcpsocket/test/test.pro
+++ b/tests/auto/network/socket/qtcpsocket/test/test.pro
@@ -21,3 +21,5 @@ win32 {
} else {
DESTDIR = ../
}
+
+win32: CONFIG += insignificant_test # Hangs in release builds
diff --git a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
index 0ba9b6a58c..abbc560414 100644
--- a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
+++ b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
@@ -200,6 +200,7 @@ private slots:
void setSocketOption();
void clientSendDataOnDelayedDisconnect();
+ void serverDisconnectWithBuffered();
protected slots:
void nonBlockingIMAP_hostFound();
@@ -241,7 +242,6 @@ private:
mutable int proxyAuthCalled;
- int numConnections;
static int loopLevel;
SocketPair *earlyConstructedSockets;
@@ -483,9 +483,9 @@ void tst_QTcpSocket::constructing()
QCOMPARE(socket->readLine(), QByteArray());
QCOMPARE(socket->socketDescriptor(), (qintptr)-1);
QCOMPARE((int) socket->localPort(), 0);
- QVERIFY(socket->localAddress() == QHostAddress());
+ QCOMPARE(socket->localAddress(), QHostAddress());
QCOMPARE((int) socket->peerPort(), 0);
- QVERIFY(socket->peerAddress() == QHostAddress());
+ QCOMPARE(socket->peerAddress(), QHostAddress());
QCOMPARE(socket->error(), QTcpSocket::UnknownSocketError);
QCOMPARE(socket->errorString(), QString("Unknown error"));
@@ -755,7 +755,7 @@ void tst_QTcpSocket::socketDescriptor()
QVERIFY(socket->state() == QAbstractSocket::HostLookupState ||
socket->state() == QAbstractSocket::ConnectingState);
QVERIFY(socket->waitForConnected(10000));
- QVERIFY(socket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(socket->state(), QAbstractSocket::ConnectedState);
QVERIFY(socket->socketDescriptor() != -1);
delete socket;
@@ -936,7 +936,7 @@ void tst_QTcpSocket::nonBlockingIMAP()
QFAIL("Timed out");
}
- QVERIFY(nonBlockingIMAP_totalWritten == 8);
+ QCOMPARE(nonBlockingIMAP_totalWritten, 8);
enterLoop(30);
@@ -961,7 +961,7 @@ void tst_QTcpSocket::nonBlockingIMAP()
QFAIL("Timed out");
}
- QVERIFY(nonBlockingIMAP_totalWritten == 10);
+ QCOMPARE(nonBlockingIMAP_totalWritten, 10);
// Wait for greeting
enterLoop(30);
@@ -1086,7 +1086,7 @@ void tst_QTcpSocket::partialRead()
QTcpSocket *socket = newSocket();
socket->connectToHost(QtNetworkSettings::serverName(), 143);
QVERIFY(socket->waitForConnected(10000));
- QVERIFY(socket->state() == QTcpSocket::ConnectedState);
+ QCOMPARE(socket->state(), QTcpSocket::ConnectedState);
char buf[512];
QByteArray greeting = expectedReplyIMAP();
@@ -1110,7 +1110,7 @@ void tst_QTcpSocket::unget()
QTcpSocket *socket = newSocket();
socket->connectToHost(QtNetworkSettings::serverName(), 143);
QVERIFY(socket->waitForConnected(10000));
- QVERIFY(socket->state() == QTcpSocket::ConnectedState);
+ QCOMPARE(socket->state(), QTcpSocket::ConnectedState);
char buf[512];
QByteArray greeting = expectedReplyIMAP();
@@ -1168,7 +1168,7 @@ void tst_QTcpSocket::openCloseOpenClose()
QCOMPARE(int(socket->openMode()), int(QIODevice::NotOpen));
QVERIFY(socket->isSequential());
QVERIFY(!socket->isOpen());
- QVERIFY(socket->socketType() == QTcpSocket::TcpSocket);
+ QCOMPARE(socket->socketType(), QTcpSocket::TcpSocket);
char c;
QCOMPARE(socket->getChar(&c), false);
@@ -1177,13 +1177,13 @@ void tst_QTcpSocket::openCloseOpenClose()
QCOMPARE(socket->readLine(), QByteArray());
QCOMPARE(socket->socketDescriptor(), (qintptr)-1);
QCOMPARE((int) socket->localPort(), 0);
- QVERIFY(socket->localAddress() == QHostAddress());
+ QCOMPARE(socket->localAddress(), QHostAddress());
QCOMPARE((int) socket->peerPort(), 0);
- QVERIFY(socket->peerAddress() == QHostAddress());
+ QCOMPARE(socket->peerAddress(), QHostAddress());
QCOMPARE(socket->error(), QTcpSocket::UnknownSocketError);
QCOMPARE(socket->errorString(), QString("Unknown error"));
- QVERIFY(socket->state() == QTcpSocket::UnconnectedState);
+ QCOMPARE(socket->state(), QTcpSocket::UnconnectedState);
socket->connectToHost(QtNetworkSettings::serverName(), 143);
QVERIFY(socket->waitForConnected(10000));
@@ -1200,7 +1200,7 @@ void tst_QTcpSocket::connectDisconnectConnectDisconnect()
for (int i = 0; i < 3; ++i) {
QCOMPARE(socket->state(), QTcpSocket::UnconnectedState);
- QVERIFY(socket->socketType() == QTcpSocket::TcpSocket);
+ QCOMPARE(socket->socketType(), QTcpSocket::TcpSocket);
socket->connectToHost(QtNetworkSettings::serverName(), 143);
QVERIFY(socket->waitForReadyRead(10000));
@@ -1260,7 +1260,7 @@ void tst_QTcpSocket::disconnectWhileConnecting()
connect(socket, SIGNAL(disconnected()), SLOT(exitLoopSlot()));
enterLoop(10);
QVERIFY2(!timeout(), "Network timeout");
- QVERIFY(socket->state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
if (!closeDirectly) {
QCOMPARE(int(socket->openMode()), int(QIODevice::ReadWrite));
socket->close();
@@ -1272,7 +1272,7 @@ void tst_QTcpSocket::disconnectWhileConnecting()
QTcpSocket *othersocket = server.nextPendingConnection();
if (othersocket->state() != QAbstractSocket::UnconnectedState)
QVERIFY2(othersocket->waitForDisconnected(10000), "Network timeout");
- QVERIFY(othersocket->state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(othersocket->state(), QAbstractSocket::UnconnectedState);
QCOMPARE(othersocket->readAll(), data);
delete socket;
@@ -1375,7 +1375,7 @@ void tst_QTcpSocket::disconnectWhileConnectingNoEventLoop()
}
QVERIFY2(socket->waitForDisconnected(10000), "Network timeout");
- QVERIFY(socket->state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
if (!closeDirectly) {
QCOMPARE(int(socket->openMode()), int(QIODevice::ReadWrite));
socket->close();
@@ -1414,10 +1414,10 @@ void tst_QTcpSocket::disconnectWhileLookingUp()
QFETCH(bool, doClose);
if (doClose) {
socket->close();
- QVERIFY(socket->openMode() == QIODevice::NotOpen);
+ QCOMPARE(socket->openMode(), QIODevice::NotOpen);
} else {
socket->disconnectFromHost();
- QVERIFY(socket->openMode() == QIODevice::ReadWrite);
+ QCOMPARE(socket->openMode(), QIODevice::ReadWrite);
QVERIFY(socket->waitForDisconnected(5000));
}
@@ -1428,12 +1428,12 @@ void tst_QTcpSocket::disconnectWhileLookingUp()
// recheck
if (doClose) {
- QVERIFY(socket->openMode() == QIODevice::NotOpen);
+ QCOMPARE(socket->openMode(), QIODevice::NotOpen);
} else {
- QVERIFY(socket->openMode() == QIODevice::ReadWrite);
+ QCOMPARE(socket->openMode(), QIODevice::ReadWrite);
}
- QVERIFY(socket->state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
}
//----------------------------------------------------------------------------------
@@ -1457,7 +1457,7 @@ void tst_QTcpSocket::downloadBigFile()
}
QByteArray hostName = QtNetworkSettings::serverName().toLatin1();
- QVERIFY(tmpSocket->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
QVERIFY(tmpSocket->write("GET /qtest/mediumfile HTTP/1.0\r\n") > 0);
QVERIFY(tmpSocket->write("HOST: ") > 0);
QVERIFY(tmpSocket->write(hostName.data()) > 0);
@@ -1830,7 +1830,6 @@ private slots:
}
#endif // !QT_NO_NETWORKPROXY
private:
- int exitCode;
QTcpSocket *socket;
QByteArray socketData;
};
@@ -2686,12 +2685,12 @@ void tst_QTcpSocket::taskQtBug7054TimeoutErrorResetting()
socket->connectToHost(QtNetworkSettings::serverName(), 443);
QVERIFY(socket->waitForConnected(5*1000));
- QVERIFY(socket->error() == QAbstractSocket::UnknownSocketError);
+ QCOMPARE(socket->error(), QAbstractSocket::UnknownSocketError);
// We connected to the HTTPS port. Wait two seconds to receive data. We will receive
// nothing because we would need to start the SSL handshake
QVERIFY(!socket->waitForReadyRead(2*1000));
- QVERIFY(socket->error() == QAbstractSocket::SocketTimeoutError);
+ QCOMPARE(socket->error(), QAbstractSocket::SocketTimeoutError);
// Now write some crap to make the server disconnect us. 4 lines are enough.
socket->write("a\r\nb\r\nc\r\nd\r\n");
@@ -2701,7 +2700,7 @@ void tst_QTcpSocket::taskQtBug7054TimeoutErrorResetting()
// should get a better error since the server disconnected us
QVERIFY(!socket->waitForReadyRead(2*1000));
// It must NOT be the SocketTimeoutError that had been set before
- QVERIFY(socket->error() == QAbstractSocket::RemoteHostClosedError);
+ QCOMPARE(socket->error(), QAbstractSocket::RemoteHostClosedError);
}
#ifndef QT_NO_NETWORKPROXY
@@ -2895,25 +2894,25 @@ void tst_QTcpSocket::qtbug14268_peek()
QTcpSocket *outgoing = socketPair.endPoints[0];
QTcpSocket *incoming = socketPair.endPoints[1];
- QVERIFY(incoming->state() == QTcpSocket::ConnectedState);
- QVERIFY(outgoing->state() == QTcpSocket::ConnectedState);
+ QCOMPARE(incoming->state(), QTcpSocket::ConnectedState);
+ QCOMPARE(outgoing->state(), QTcpSocket::ConnectedState);
outgoing->write("abc\n");
QVERIFY(outgoing->waitForBytesWritten(2000));
QVERIFY(incoming->waitForReadyRead(2000));
- QVERIFY(incoming->peek(128*1024) == QByteArray("abc\n"));
+ QCOMPARE(incoming->peek(128*1024), QByteArray("abc\n"));
outgoing->write("def\n");
QVERIFY(outgoing->waitForBytesWritten(2000));
QVERIFY(incoming->waitForReadyRead(2000));
- QVERIFY(incoming->peek(128*1024) == QByteArray("abc\ndef\n"));
+ QCOMPARE(incoming->peek(128*1024), QByteArray("abc\ndef\n"));
outgoing->write("ghi\n");
QVERIFY(outgoing->waitForBytesWritten(2000));
QVERIFY(incoming->waitForReadyRead(2000));
- QVERIFY(incoming->peek(128*1024) == QByteArray("abc\ndef\nghi\n"));
+ QCOMPARE(incoming->peek(128*1024), QByteArray("abc\ndef\nghi\n"));
- QVERIFY(incoming->read(128*1024) == QByteArray("abc\ndef\nghi\n"));
+ QCOMPARE(incoming->read(128*1024), QByteArray("abc\ndef\nghi\n"));
}
void tst_QTcpSocket::setSocketOption()
@@ -2927,8 +2926,8 @@ void tst_QTcpSocket::setSocketOption()
QTcpSocket *outgoing = socketPair.endPoints[0];
QTcpSocket *incoming = socketPair.endPoints[1];
- QVERIFY(incoming->state() == QTcpSocket::ConnectedState);
- QVERIFY(outgoing->state() == QTcpSocket::ConnectedState);
+ QCOMPARE(incoming->state(), QTcpSocket::ConnectedState);
+ QCOMPARE(outgoing->state(), QTcpSocket::ConnectedState);
outgoing->setSocketOption(QAbstractSocket::LowDelayOption, true);
QVariant v = outgoing->socketOption(QAbstractSocket::LowDelayOption);
@@ -2984,5 +2983,50 @@ void tst_QTcpSocket::clientSendDataOnDelayedDisconnect()
delete socket;
}
+// Test buffered socket being properly closed on remote disconnect
+void tst_QTcpSocket::serverDisconnectWithBuffered()
+{
+ QFETCH_GLOBAL(bool, setProxy);
+ if (setProxy)
+ return;
+
+ qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
+
+ QTcpServer tcpServer;
+ QTcpSocket *socket = newSocket();
+
+ QVERIFY(tcpServer.listen(QHostAddress::LocalHost));
+ socket->connectToHost(tcpServer.serverAddress(), tcpServer.serverPort());
+ // Accept connection on server side
+ QVERIFY(tcpServer.waitForNewConnection(5000));
+ QTcpSocket *newConnection = tcpServer.nextPendingConnection();
+ // Send one char and drop link
+ QVERIFY(newConnection != NULL);
+ QVERIFY(newConnection->putChar(0));
+ QVERIFY(newConnection->flush());
+ delete newConnection;
+
+ QVERIFY(socket->waitForConnected(5000)); // ready for write
+ QCOMPARE(socket->state(), QAbstractSocket::ConnectedState);
+
+ QSignalSpy spyStateChanged(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
+ QSignalSpy spyDisconnected(socket, SIGNAL(disconnected()));
+
+ QVERIFY(socket->waitForReadyRead(5000)); // have one char already in internal buffer
+ char buf[128];
+ QCOMPARE(socket->read(buf, sizeof(buf)), Q_INT64_C(1));
+ if (socket->state() != QAbstractSocket::UnconnectedState) {
+ QVERIFY(socket->waitForDisconnected(5000));
+ QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
+ }
+ // Test signal emitting
+ QCOMPARE(spyDisconnected.count(), 1);
+ QVERIFY(spyStateChanged.count() > 0);
+ QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
+ == QAbstractSocket::UnconnectedState);
+
+ delete socket;
+}
+
QTEST_MAIN(tst_QTcpSocket)
#include "tst_qtcpsocket.moc"
diff --git a/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp b/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
index b6129bec08..2331bc19aa 100644
--- a/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
+++ b/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
@@ -223,7 +223,7 @@ void tst_QUdpSocket::constructing()
QVERIFY(socket.isSequential());
QVERIFY(!socket.isOpen());
- QVERIFY(socket.socketType() == QUdpSocket::UdpSocket);
+ QCOMPARE(socket.socketType(), QUdpSocket::UdpSocket);
QCOMPARE((int) socket.bytesAvailable(), 0);
QCOMPARE(socket.canReadLine(), false);
QCOMPARE(socket.readLine(), QByteArray());
@@ -749,7 +749,7 @@ void tst_QUdpSocket::writeDatagram()
QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
break;
}
- QVERIFY(bytesspy.count() == 1);
+ QCOMPARE(bytesspy.count(), 1);
QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
qint64(i * 1024));
QCOMPARE(errorspy.count(), 0);
diff --git a/tests/auto/network/ssl/qsslcertificate/BLACKLIST b/tests/auto/network/ssl/qsslcertificate/BLACKLIST
new file mode 100644
index 0000000000..2e376fa2a9
--- /dev/null
+++ b/tests/auto/network/ssl/qsslcertificate/BLACKLIST
@@ -0,0 +1,3 @@
+# OpenSSL version is too new. Rich will fix :)
+[subjectAndIssuerAttributes]
+osx
diff --git a/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp b/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
index 748c240f3d..4c288fffaf 100644
--- a/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
+++ b/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
@@ -775,7 +775,7 @@ void tst_QSslCertificate::certInfo()
QVERIFY(cert.expiryDate() < QDateTime::currentDateTime()); // cert has expired
QSslCertificate copy = cert;
- QVERIFY(cert == copy);
+ QCOMPARE(cert, copy);
QVERIFY(!(cert != copy));
QCOMPARE(cert, QSslCertificate(pem, QSsl::Pem));
@@ -833,6 +833,9 @@ void tst_QSslCertificate::task256066toPem()
void tst_QSslCertificate::nulInCN()
{
+#ifdef QT_SECURETRANSPORT
+ QSKIP("Generic QSslCertificatePrivate fails this test");
+#endif
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "/more-certificates/badguy-nul-cn.crt");
QCOMPARE(certList.size(), 1);
@@ -849,6 +852,9 @@ void tst_QSslCertificate::nulInCN()
void tst_QSslCertificate::nulInSan()
{
+#ifdef QT_SECURETRANSPORT
+ QSKIP("Generic QSslCertificatePrivate fails this test");
+#endif
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "/more-certificates/badguy-nul-san.crt");
QCOMPARE(certList.size(), 1);
@@ -976,6 +982,9 @@ void tst_QSslCertificate::subjectAndIssuerAttributes()
void tst_QSslCertificate::verify()
{
+#ifdef QT_SECURETRANSPORT
+ QSKIP("Not implemented in SecureTransport");
+#endif
QList<QSslError> errors;
QList<QSslCertificate> toVerify;
@@ -1069,7 +1078,7 @@ void tst_QSslCertificate::extensions()
QSslCertificate cert = certList[0];
QList<QSslCertificateExtension> extensions = cert.extensions();
- QVERIFY(extensions.count() == 9);
+ QCOMPARE(extensions.count(), 9);
int unknown_idx = -1;
int authority_info_idx = -1;
@@ -1101,8 +1110,8 @@ void tst_QSslCertificate::extensions()
// Unknown
QSslCertificateExtension unknown = extensions[unknown_idx];
- QVERIFY(unknown.oid() == QStringLiteral("1.3.6.1.5.5.7.1.12"));
- QVERIFY(unknown.name() == QStringLiteral("1.3.6.1.5.5.7.1.12"));
+ QCOMPARE(unknown.oid(), QStringLiteral("1.3.6.1.5.5.7.1.12"));
+ QCOMPARE(unknown.name(), QStringLiteral("1.3.6.1.5.5.7.1.12"));
QVERIFY(!unknown.isCritical());
QVERIFY(!unknown.isSupported());
@@ -1114,8 +1123,8 @@ void tst_QSslCertificate::extensions()
// Authority Info Access
QSslCertificateExtension aia = extensions[authority_info_idx];
- QVERIFY(aia.oid() == QStringLiteral("1.3.6.1.5.5.7.1.1"));
- QVERIFY(aia.name() == QStringLiteral("authorityInfoAccess"));
+ QCOMPARE(aia.oid(), QStringLiteral("1.3.6.1.5.5.7.1.1"));
+ QCOMPARE(aia.name(), QStringLiteral("authorityInfoAccess"));
QVERIFY(!aia.isCritical());
QVERIFY(aia.isSupported());
@@ -1124,32 +1133,32 @@ void tst_QSslCertificate::extensions()
QString ocsp = aiaValue[QStringLiteral("OCSP")].toString();
QString caIssuers = aiaValue[QStringLiteral("caIssuers")].toString();
- QVERIFY(ocsp == QStringLiteral("http://EVIntl-ocsp.verisign.com"));
- QVERIFY(caIssuers == QStringLiteral("http://EVIntl-aia.verisign.com/EVIntl2006.cer"));
+ QCOMPARE(ocsp, QStringLiteral("http://EVIntl-ocsp.verisign.com"));
+ QCOMPARE(caIssuers, QStringLiteral("http://EVIntl-aia.verisign.com/EVIntl2006.cer"));
// Basic constraints
QSslCertificateExtension basic = extensions[basic_constraints_idx];
- QVERIFY(basic.oid() == QStringLiteral("2.5.29.19"));
- QVERIFY(basic.name() == QStringLiteral("basicConstraints"));
+ QCOMPARE(basic.oid(), QStringLiteral("2.5.29.19"));
+ QCOMPARE(basic.name(), QStringLiteral("basicConstraints"));
QVERIFY(!basic.isCritical());
QVERIFY(basic.isSupported());
QVariantMap basicValue = basic.value().toMap();
QCOMPARE(basicValue.keys(), QList<QString>() << QStringLiteral("ca"));
- QVERIFY(basicValue[QStringLiteral("ca")].toBool() == false);
+ QVERIFY(!basicValue[QStringLiteral("ca")].toBool());
// Subject key identifier
QSslCertificateExtension subjectKey = extensions[subject_key_idx];
- QVERIFY(subjectKey.oid() == QStringLiteral("2.5.29.14"));
- QVERIFY(subjectKey.name() == QStringLiteral("subjectKeyIdentifier"));
+ QCOMPARE(subjectKey.oid(), QStringLiteral("2.5.29.14"));
+ QCOMPARE(subjectKey.name(), QStringLiteral("subjectKeyIdentifier"));
QVERIFY(!subjectKey.isCritical());
QVERIFY(subjectKey.isSupported());
- QVERIFY(subjectKey.value().toString() == QStringLiteral("5F:90:23:CD:24:CA:52:C9:36:29:F0:7E:9D:B1:FE:08:E0:EE:69:F0"));
+ QCOMPARE(subjectKey.value().toString(), QStringLiteral("5F:90:23:CD:24:CA:52:C9:36:29:F0:7E:9D:B1:FE:08:E0:EE:69:F0"));
// Authority key identifier
QSslCertificateExtension authKey = extensions[auth_key_idx];
- QVERIFY(authKey.oid() == QStringLiteral("2.5.29.35"));
- QVERIFY(authKey.name() == QStringLiteral("authorityKeyIdentifier"));
+ QCOMPARE(authKey.oid(), QStringLiteral("2.5.29.35"));
+ QCOMPARE(authKey.name(), QStringLiteral("authorityKeyIdentifier"));
QVERIFY(!authKey.isCritical());
QVERIFY(authKey.isSupported());
@@ -1167,7 +1176,7 @@ void tst_QSslCertificate::extensionsCritical()
QSslCertificate cert = certList[0];
QList<QSslCertificateExtension> extensions = cert.extensions();
- QVERIFY(extensions.count() == 9);
+ QCOMPARE(extensions.count(), 9);
int basic_constraints_idx = -1;
int key_usage_idx = -1;
@@ -1186,19 +1195,19 @@ void tst_QSslCertificate::extensionsCritical()
// Basic constraints
QSslCertificateExtension basic = extensions[basic_constraints_idx];
- QVERIFY(basic.oid() == QStringLiteral("2.5.29.19"));
- QVERIFY(basic.name() == QStringLiteral("basicConstraints"));
+ QCOMPARE(basic.oid(), QStringLiteral("2.5.29.19"));
+ QCOMPARE(basic.name(), QStringLiteral("basicConstraints"));
QVERIFY(basic.isCritical());
QVERIFY(basic.isSupported());
QVariantMap basicValue = basic.value().toMap();
QCOMPARE(basicValue.keys(), QList<QString>() << QStringLiteral("ca"));
- QVERIFY(basicValue[QStringLiteral("ca")].toBool() == false);
+ QVERIFY(!basicValue[QStringLiteral("ca")].toBool());
// Key Usage
QSslCertificateExtension keyUsage = extensions[key_usage_idx];
- QVERIFY(keyUsage.oid() == QStringLiteral("2.5.29.15"));
- QVERIFY(keyUsage.name() == QStringLiteral("keyUsage"));
+ QCOMPARE(keyUsage.oid(), QStringLiteral("2.5.29.15"));
+ QCOMPARE(keyUsage.name(), QStringLiteral("keyUsage"));
QVERIFY(keyUsage.isCritical());
QVERIFY(!keyUsage.isSupported());
}
@@ -1257,21 +1266,21 @@ void tst_QSslCertificate::threadSafeConstMethods()
t2.start();
QVERIFY(t1.wait(5000));
QVERIFY(t2.wait(5000));
- QVERIFY(t1.cert == t2.cert);
- QVERIFY(t1.effectiveDate == t2.effectiveDate);
- QVERIFY(t1.expiryDate == t2.expiryDate);
+ QCOMPARE(t1.cert, t2.cert);
+ QCOMPARE(t1.effectiveDate, t2.effectiveDate);
+ QCOMPARE(t1.expiryDate, t2.expiryDate);
//QVERIFY(t1.extensions == t2.extensions); // no equality operator, so not tested
- QVERIFY(t1.isBlacklisted == t2.isBlacklisted);
- QVERIFY(t1.issuerInfo == t2.issuerInfo);
- QVERIFY(t1.issuerInfoAttributes == t2.issuerInfoAttributes);
- QVERIFY(t1.publicKey == t2.publicKey);
- QVERIFY(t1.serialNumber == t2.serialNumber);
- QVERIFY(t1.subjectInfo == t2.subjectInfo);
- QVERIFY(t1.subjectInfoAttributes == t2.subjectInfoAttributes);
- QVERIFY(t1.toDer == t2.toDer);
- QVERIFY(t1.toPem == t2.toPem);
- QVERIFY(t1.toText == t2.toText);
- QVERIFY(t1.version == t2.version);
+ QCOMPARE(t1.isBlacklisted, t2.isBlacklisted);
+ QCOMPARE(t1.issuerInfo, t2.issuerInfo);
+ QCOMPARE(t1.issuerInfoAttributes, t2.issuerInfoAttributes);
+ QCOMPARE(t1.publicKey, t2.publicKey);
+ QCOMPARE(t1.serialNumber, t2.serialNumber);
+ QCOMPARE(t1.subjectInfo, t2.subjectInfo);
+ QCOMPARE(t1.subjectInfoAttributes, t2.subjectInfoAttributes);
+ QCOMPARE(t1.toDer, t2.toDer);
+ QCOMPARE(t1.toPem, t2.toPem);
+ QCOMPARE(t1.toText, t2.toText);
+ QCOMPARE(t1.version, t2.version);
}
diff --git a/tests/auto/network/ssl/qsslkey/BLACKLIST b/tests/auto/network/ssl/qsslkey/BLACKLIST
new file mode 100644
index 0000000000..a08e1f35eb
--- /dev/null
+++ b/tests/auto/network/ssl/qsslkey/BLACKLIST
@@ -0,0 +1 @@
+linux
diff --git a/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp b/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
index d570037015..a7957d3288 100644
--- a/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
+++ b/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
@@ -39,7 +39,7 @@
#include <QtNetwork/qhostaddress.h>
#include <QtNetwork/qnetworkproxy.h>
-#if !defined(QT_NO_SSL) && defined(QT_NO_OPENSSL) && defined(QT_BUILD_INTERNAL)
+#if !defined(QT_NO_SSL) && defined(QT_BUILD_INTERNAL)
#include "private/qsslkey_p.h"
#define TEST_CRYPTO
#endif
diff --git a/tests/auto/network/ssl/qsslsocket/BLACKLIST b/tests/auto/network/ssl/qsslsocket/BLACKLIST
index 17b606e2be..4146a352e9 100644
--- a/tests/auto/network/ssl/qsslsocket/BLACKLIST
+++ b/tests/auto/network/ssl/qsslsocket/BLACKLIST
@@ -1,2 +1,3 @@
+windows
[waitForConnectedEncryptedReadyRead:WithSocks5ProxyAuth]
*
diff --git a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
index b95b72a41e..c7d655af3d 100644
--- a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
+++ b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
@@ -170,6 +170,9 @@ private slots:
void protocol();
void protocolServerSide_data();
void protocolServerSide();
+#ifndef QT_NO_OPENSSL
+ void serverCipherPreferences();
+#endif // QT_NO_OPENSSL
void setCaCertificates();
void setLocalCertificate();
void localCertificateChain();
@@ -817,7 +820,7 @@ void tst_QSslSocket::peerCertificateChain()
this->socket = socket.data();
QList<QSslCertificate> caCertificates = QSslCertificate::fromPath(QLatin1String(SRCDIR "certs/qt-test-server-cacert.pem"));
- QVERIFY(caCertificates.count() == 1);
+ QCOMPARE(caCertificates.count(), 1);
socket->addCaCertificates(caCertificates);
#ifdef QSSLSOCKET_CERTUNTRUSTED_WORKAROUND
connect(socket.data(), SIGNAL(sslErrors(QList<QSslError>)),
@@ -863,7 +866,7 @@ void tst_QSslSocket::peerCertificateChain()
QSKIP("Skipping flaky test - See QTBUG-29941");
QCOMPARE(socket->peerCertificateChain().first(), socket->peerCertificate());
- QVERIFY(socket->peerCertificateChain() == certChain);
+ QCOMPARE(socket->peerCertificateChain(), certChain);
socket->disconnectFromHost();
QVERIFY(socket->waitForDisconnected());
@@ -1063,6 +1066,7 @@ public:
const QString &certFile = SRCDIR "certs/fluke.cert",
const QString &interFile = QString())
: socket(0),
+ config(QSslConfiguration::defaultConfiguration()),
ignoreSslErrors(true),
peerVerifyMode(QSslSocket::AutoVerifyPeer),
protocol(QSsl::TlsV1_0),
@@ -1071,6 +1075,7 @@ public:
m_interFile(interFile)
{ }
QSslSocket *socket;
+ QSslConfiguration config;
QString addCaCertificates;
bool ignoreSslErrors;
QSslSocket::PeerVerifyMode peerVerifyMode;
@@ -1084,6 +1089,7 @@ protected:
void incomingConnection(qintptr socketDescriptor)
{
socket = new QSslSocket(this);
+ socket->setSslConfiguration(config);
socket->setPeerVerifyMode(peerVerifyMode);
socket->setProtocol(protocol);
if (ignoreSslErrors)
@@ -1254,6 +1260,78 @@ void tst_QSslSocket::protocolServerSide()
QCOMPARE(client->isEncrypted(), works);
}
+#ifndef QT_NO_OPENSSL
+
+void tst_QSslSocket::serverCipherPreferences()
+{
+ if (!QSslSocket::supportsSsl()) {
+ qWarning("SSL not supported, skipping test");
+ return;
+ }
+
+ QFETCH_GLOBAL(bool, setProxy);
+ if (setProxy)
+ return;
+
+ // First using the default (server preference)
+ {
+ SslServer server;
+ server.ciphers = QString("AES128-SHA:AES256-SHA");
+ QVERIFY(server.listen());
+
+ QEventLoop loop;
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+
+ QSslSocketPtr client(new QSslSocket);
+ socket = client.data();
+ socket->setCiphers("AES256-SHA:AES128-SHA");
+
+ // upon SSL wrong version error, error will be triggered, not sslErrors
+ connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), &loop, SLOT(quit()));
+ connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(ignoreErrorSlot()));
+ connect(socket, SIGNAL(encrypted()), &loop, SLOT(quit()));
+
+ client->connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(), server.serverPort());
+
+ loop.exec();
+
+ QVERIFY(client->isEncrypted());
+ QCOMPARE(client->sessionCipher().name(), QString("AES128-SHA"));
+ }
+
+ {
+ // Now using the client preferences
+ SslServer server;
+ QSslConfiguration config = QSslConfiguration::defaultConfiguration();
+ config.setSslOption(QSsl::SslOptionDisableServerCipherPreference, true);
+ server.config = config;
+ server.ciphers = QString("AES128-SHA:AES256-SHA");
+ QVERIFY(server.listen());
+
+ QEventLoop loop;
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+
+ QSslSocketPtr client(new QSslSocket);
+ socket = client.data();
+ socket->setCiphers("AES256-SHA:AES128-SHA");
+
+ // upon SSL wrong version error, error will be triggered, not sslErrors
+ connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), &loop, SLOT(quit()));
+ connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(ignoreErrorSlot()));
+ connect(socket, SIGNAL(encrypted()), &loop, SLOT(quit()));
+
+ client->connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(), server.serverPort());
+
+ loop.exec();
+
+ QVERIFY(client->isEncrypted());
+ QCOMPARE(client->sessionCipher().name(), QString("AES256-SHA"));
+ }
+}
+
+#endif // QT_NO_OPENSSL
+
+
void tst_QSslSocket::setCaCertificates()
{
if (!QSslSocket::supportsSsl())
@@ -1655,7 +1733,7 @@ void tst_QSslSocket::spontaneousWrite()
QSslSocket *sender = server.socket;
QVERIFY(sender);
- QVERIFY(sender->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(sender->state(), QAbstractSocket::ConnectedState);
receiver->setObjectName("receiver");
sender->setObjectName("sender");
receiver->ignoreSslErrors();
@@ -1700,7 +1778,7 @@ void tst_QSslSocket::setReadBufferSize()
QSslSocket *sender = server.socket;
QVERIFY(sender);
- QVERIFY(sender->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(sender->state(), QAbstractSocket::ConnectedState);
receiver->setObjectName("receiver");
sender->setObjectName("sender");
receiver->ignoreSslErrors();
@@ -2254,7 +2332,7 @@ void tst_QSslSocket::readFromClosedSocket()
socket->close();
QVERIFY(!socket->bytesAvailable());
QVERIFY(!socket->bytesToWrite());
- QVERIFY(socket->state() == QAbstractSocket::UnconnectedState);
+ QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
}
void tst_QSslSocket::writeBigChunk()
@@ -2281,7 +2359,7 @@ void tst_QSslSocket::writeBigChunk()
QString errorBefore = socket->errorString();
int ret = socket->write(data.constData(), data.size());
- QVERIFY(data.size() == ret);
+ QCOMPARE(data.size(), ret);
// spin the event loop once so QSslSocket::transmit() gets called
QCoreApplication::processEvents();
@@ -2298,7 +2376,7 @@ void tst_QSslSocket::writeBigChunk()
QByteArray("unexpected error: ").append(qPrintable(errorAfter)));
// check that everything has been written to OpenSSL
- QVERIFY(socket->bytesToWrite() == 0);
+ QCOMPARE(socket->bytesToWrite(), 0);
socket->close();
}
@@ -2322,7 +2400,7 @@ void tst_QSslSocket::blacklistedCertificates()
QSslSocket *sender = server.socket;
QVERIFY(sender);
- QVERIFY(sender->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(sender->state(), QAbstractSocket::ConnectedState);
receiver->setObjectName("receiver");
sender->setObjectName("sender");
receiver->startClientEncryption();
@@ -2354,28 +2432,28 @@ void tst_QSslSocket::sslOptions()
#ifdef SSL_OP_NO_COMPRESSION
QCOMPARE(QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SecureProtocols,
QSslConfigurationPrivate::defaultSslOptions),
- long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION));
+ long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION|SSL_OP_CIPHER_SERVER_PREFERENCE));
#else
QCOMPARE(QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SecureProtocols,
QSslConfigurationPrivate::defaultSslOptions),
- long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3));
+ long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_CIPHER_SERVER_PREFERENCE));
#endif
QCOMPARE(QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SecureProtocols,
QSsl::SslOptionDisableEmptyFragments
|QSsl::SslOptionDisableLegacyRenegotiation),
- long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3));
+ long(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_CIPHER_SERVER_PREFERENCE));
#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
QCOMPARE(QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SecureProtocols,
QSsl::SslOptionDisableEmptyFragments),
- long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)));
+ long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION|SSL_OP_CIPHER_SERVER_PREFERENCE)));
#endif
#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
QCOMPARE(QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SecureProtocols,
QSsl::SslOptionDisableLegacyRenegotiation),
- long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3) & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS));
+ long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_CIPHER_SERVER_PREFERENCE) & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS));
#endif
#ifdef SSL_OP_NO_TICKET
@@ -2383,7 +2461,7 @@ void tst_QSslSocket::sslOptions()
QSsl::SslOptionDisableEmptyFragments
|QSsl::SslOptionDisableLegacyRenegotiation
|QSsl::SslOptionDisableSessionTickets),
- long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TICKET)));
+ long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TICKET|SSL_OP_CIPHER_SERVER_PREFERENCE)));
#endif
#ifdef SSL_OP_NO_TICKET
@@ -2393,7 +2471,7 @@ void tst_QSslSocket::sslOptions()
|QSsl::SslOptionDisableLegacyRenegotiation
|QSsl::SslOptionDisableSessionTickets
|QSsl::SslOptionDisableCompression),
- long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TICKET|SSL_OP_NO_COMPRESSION)));
+ long((SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TICKET|SSL_OP_NO_COMPRESSION|SSL_OP_CIPHER_SERVER_PREFERENCE)));
#endif
#endif
}
@@ -2648,9 +2726,9 @@ void tst_QSslSocket::qtbug18498_peek2()
while (client->bytesAvailable() < 7 && stopwatch.elapsed() < 5000)
QTest::qWait(100);
char c;
- QVERIFY(client->peek(&c,1) == 1);
+ QCOMPARE(client->peek(&c,1), 1);
QCOMPARE(c, 'H');
- QVERIFY(client->read(&c,1) == 1);
+ QCOMPARE(client->read(&c,1), 1);
QCOMPARE(c, 'H');
QByteArray b = client->peek(2);
QCOMPARE(b, QByteArray("EL"));
@@ -2686,7 +2764,7 @@ void tst_QSslSocket::qtbug18498_peek2()
// ### Qt5 use QTRY_VERIFY
while (server->bytesAvailable() < 10 && stopwatch.elapsed() < 5000)
QTest::qWait(100);
- QVERIFY(server->peek(&c,1) == 1);
+ QCOMPARE(server->peek(&c,1), 1);
QCOMPARE(c, 'S');
b = server->peek(3);
QCOMPARE(b, QByteArray("STA"));
@@ -2722,9 +2800,9 @@ void tst_QSslSocket::qtbug18498_peek2()
while (client->bytesAvailable() < 7 && stopwatch.elapsed() < 5000)
QTest::qWait(100);
QVERIFY(server->mode() == QSslSocket::SslServerMode && client->mode() == QSslSocket::SslClientMode);
- QVERIFY(client->peek(&c,1) == 1);
+ QCOMPARE(client->peek(&c,1), 1);
QCOMPARE(c, 'h');
- QVERIFY(client->read(&c,1) == 1);
+ QCOMPARE(client->read(&c,1), 1);
QCOMPARE(c, 'h');
b = client->peek(2);
QCOMPARE(b, QByteArray("el"));
@@ -2734,7 +2812,7 @@ void tst_QSslSocket::qtbug18498_peek2()
stopwatch.start();
while (server->bytesAvailable() < 9 && stopwatch.elapsed() < 5000)
QTest::qWait(100);
- QVERIFY(server->peek(&c,1) == 1);
+ QCOMPARE(server->peek(&c,1), 1);
QCOMPARE(c, 'g');
QCOMPARE(server->readAll(), QByteArray("goodbye\r\n"));
client->disconnectFromHost();
@@ -2768,7 +2846,7 @@ void tst_QSslSocket::dhServer()
client->connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(), server.serverPort());
loop.exec();
- QVERIFY(client->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client->state(), QAbstractSocket::ConnectedState);
}
void tst_QSslSocket::ecdhServer()
@@ -2798,7 +2876,7 @@ void tst_QSslSocket::ecdhServer()
client->connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(), server.serverPort());
loop.exec();
- QVERIFY(client->state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client->state(), QAbstractSocket::ConnectedState);
}
void tst_QSslSocket::verifyClientCertificate_data()
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST
new file mode 100644
index 0000000000..c9b628d79b
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST
@@ -0,0 +1,2 @@
+[onDemandRootCertLoadingMemberMethods]
+linux
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST
new file mode 100644
index 0000000000..52bd2bc86d
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST
@@ -0,0 +1,2 @@
+[onDemandRootCertLoadingStaticMethods:WithSocks5ProxyAuth]
+windows
diff --git a/tests/auto/opengl/qgl/BLACKLIST b/tests/auto/opengl/qgl/BLACKLIST
new file mode 100644
index 0000000000..fa7c829b30
--- /dev/null
+++ b/tests/auto/opengl/qgl/BLACKLIST
@@ -0,0 +1,16 @@
+[glWidgetRendering]
+windows
+[glFBORendering]
+windows
+[multipleFBOInterleavedRendering]
+windows
+[glPBufferRendering]
+windows
+[replaceClipping]
+windows
+[clipTest]
+windows
+[graphicsViewClipping]
+windows
+[glFBOUseInGLWidget]
+windows
diff --git a/tests/auto/opengl/qgl/tst_qgl.cpp b/tests/auto/opengl/qgl/tst_qgl.cpp
index 9bd82559b7..7970725355 100644
--- a/tests/auto/opengl/qgl/tst_qgl.cpp
+++ b/tests/auto/opengl/qgl/tst_qgl.cpp
@@ -459,113 +459,113 @@ void tst_QGL::getSetCheck()
QGLFormat format1;
QGLFormat format2;
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setDoubleBuffer(false);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setDoubleBuffer(false);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setDepthBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setDepthBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setAccumBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setAccumBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setRedBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setRedBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setGreenBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setGreenBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setBlueBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setBlueBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setAlphaBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setAlphaBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setStencilBufferSize(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setStencilBufferSize(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setSamples(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setSamples(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setSwapInterval(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setSwapInterval(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setPlane(8);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setPlane(8);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setVersion(3, 2);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setVersion(3, 2);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setProfile(QGLFormat::CoreProfile);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setProfile(QGLFormat::CoreProfile);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
format1.setOption(QGL::NoDeprecatedFunctions);
QVERIFY(!(format1 == format2));
QVERIFY(format1 != format2);
format2.setOption(QGL::NoDeprecatedFunctions);
- QVERIFY(format1 == format2);
+ QCOMPARE(format1, format2);
QVERIFY(!(format1 != format2));
// Copy constructor and assignment for QGLFormat.
QGLFormat format3(format1);
QGLFormat format4;
- QVERIFY(format1 == format3);
+ QCOMPARE(format1, format3);
QVERIFY(format1 != format4);
format4 = format1;
- QVERIFY(format1 == format4);
+ QCOMPARE(format1, format4);
// Check that modifying a copy doesn't affect the original.
format3.setRedBufferSize(16);
@@ -584,15 +584,15 @@ void tst_QGL::getSetCheck()
QCOMPARE(format5.plane(), 3);
// The default format should be the same as QGLFormat().
- QVERIFY(QGLFormat::defaultFormat() == QGLFormat());
+ QCOMPARE(QGLFormat::defaultFormat(), QGLFormat());
// Modify the default format and check that it was changed.
QGLFormat::setDefaultFormat(format1);
- QVERIFY(QGLFormat::defaultFormat() == format1);
+ QCOMPARE(QGLFormat::defaultFormat(), format1);
// Restore the default format.
QGLFormat::setDefaultFormat(QGLFormat());
- QVERIFY(QGLFormat::defaultFormat() == QGLFormat());
+ QCOMPARE(QGLFormat::defaultFormat(), QGLFormat());
// Check the default overlay format's expected values.
QGLFormat overlay(QGLFormat::defaultOverlayFormat());
@@ -618,11 +618,11 @@ void tst_QGL::getSetCheck()
// Modify the default overlay format and check that it was changed.
QGLFormat::setDefaultOverlayFormat(format1);
- QVERIFY(QGLFormat::defaultOverlayFormat() == format1);
+ QCOMPARE(QGLFormat::defaultOverlayFormat(), format1);
// Restore the default overlay format.
QGLFormat::setDefaultOverlayFormat(overlay);
- QVERIFY(QGLFormat::defaultOverlayFormat() == overlay);
+ QCOMPARE(QGLFormat::defaultOverlayFormat(), overlay);
MyGLContext obj2(obj1);
// bool QGLContext::windowCreated()
@@ -1512,9 +1512,9 @@ void tst_QGL::colormap()
QGLColormap cmap1;
QVERIFY(cmap1.isEmpty());
QCOMPARE(cmap1.size(), 0);
- QVERIFY(cmap1.entryRgb(0) == 0);
- QVERIFY(cmap1.entryRgb(-1) == 0);
- QVERIFY(cmap1.entryRgb(100) == 0);
+ QCOMPARE(cmap1.entryRgb(0), QRgb(0));
+ QCOMPARE(cmap1.entryRgb(-1), QRgb(0));
+ QCOMPARE(cmap1.entryRgb(100), QRgb(0));
QVERIFY(!cmap1.entryColor(0).isValid());
QVERIFY(!cmap1.entryColor(-1).isValid());
QVERIFY(!cmap1.entryColor(100).isValid());
@@ -1529,7 +1529,7 @@ void tst_QGL::colormap()
// not to detect when it is empty!
QVERIFY(cmap1.isEmpty());
QCOMPARE(cmap1.size(), 256);
- QVERIFY(cmap1.entryRgb(0) == 0);
+ QCOMPARE(cmap1.entryRgb(0), QRgb(0));
QVERIFY(cmap1.entryColor(0) == QColor(0, 0, 0, 255));
QVERIFY(cmap1.entryRgb(56) == qRgb(255, 0, 0));
QVERIFY(cmap1.entryColor(56) == QColor(255, 0, 0, 255));
@@ -1611,7 +1611,7 @@ void tst_QGL::colormap()
QVERIFY(cmap4.isEmpty());
QCOMPARE(cmap4.size(), 256);
cmap4.setHandle(Qt::HANDLE(42));
- QVERIFY(cmap4.handle() == Qt::HANDLE(42));
+ QCOMPARE(cmap4.handle(), Qt::HANDLE(42));
QVERIFY(!cmap4.isEmpty());
QCOMPARE(cmap4.size(), 256);
}
@@ -1629,7 +1629,7 @@ void tst_QGL::fboFormat()
// Check the initial conditions.
QGLFramebufferObjectFormat format1;
QCOMPARE(format1.samples(), 0);
- QVERIFY(format1.attachment() == QGLFramebufferObject::NoAttachment);
+ QCOMPARE(format1.attachment(), QGLFramebufferObject::NoAttachment);
QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_2D));
int expectedFormat =
#ifdef QT_OPENGL_ES_2
@@ -1645,7 +1645,7 @@ void tst_QGL::fboFormat()
format1.setTextureTarget(GL_TEXTURE_3D);
format1.setInternalTextureFormat(GL_RGB16);
QCOMPARE(format1.samples(), 8);
- QVERIFY(format1.attachment() == QGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(format1.attachment(), QGLFramebufferObject::CombinedDepthStencil);
QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_3D));
QCOMPARE(int(format1.internalTextureFormat()), int(GL_RGB16));
@@ -1653,12 +1653,12 @@ void tst_QGL::fboFormat()
QGLFramebufferObjectFormat format2(format1);
QGLFramebufferObjectFormat format3;
QCOMPARE(format2.samples(), 8);
- QVERIFY(format2.attachment() == QGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(format2.attachment(), QGLFramebufferObject::CombinedDepthStencil);
QCOMPARE(int(format2.textureTarget()), int(GL_TEXTURE_3D));
QCOMPARE(int(format2.internalTextureFormat()), int(GL_RGB16));
format3 = format1;
QCOMPARE(format3.samples(), 8);
- QVERIFY(format3.attachment() == QGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(format3.attachment(), QGLFramebufferObject::CombinedDepthStencil);
QCOMPARE(int(format3.textureTarget()), int(GL_TEXTURE_3D));
QCOMPARE(int(format3.internalTextureFormat()), int(GL_RGB16));
@@ -1666,7 +1666,7 @@ void tst_QGL::fboFormat()
format2.setSamples(9);
format3.setTextureTarget(GL_TEXTURE_2D);
QCOMPARE(format1.samples(), 8);
- QVERIFY(format1.attachment() == QGLFramebufferObject::CombinedDepthStencil);
+ QCOMPARE(format1.attachment(), QGLFramebufferObject::CombinedDepthStencil);
QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_3D));
QCOMPARE(int(format1.internalTextureFormat()), int(GL_RGB16));
@@ -1674,39 +1674,39 @@ void tst_QGL::fboFormat()
QGLFramebufferObjectFormat format1c;
QGLFramebufferObjectFormat format2c;
- QVERIFY(format1c == format2c);
+ QCOMPARE(format1c, format2c);
QVERIFY(!(format1c != format2c));
format1c.setSamples(8);
QVERIFY(!(format1c == format2c));
QVERIFY(format1c != format2c);
format2c.setSamples(8);
- QVERIFY(format1c == format2c);
+ QCOMPARE(format1c, format2c);
QVERIFY(!(format1c != format2c));
format1c.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
QVERIFY(!(format1c == format2c));
QVERIFY(format1c != format2c);
format2c.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
- QVERIFY(format1c == format2c);
+ QCOMPARE(format1c, format2c);
QVERIFY(!(format1c != format2c));
format1c.setTextureTarget(GL_TEXTURE_3D);
QVERIFY(!(format1c == format2c));
QVERIFY(format1c != format2c);
format2c.setTextureTarget(GL_TEXTURE_3D);
- QVERIFY(format1c == format2c);
+ QCOMPARE(format1c, format2c);
QVERIFY(!(format1c != format2c));
format1c.setInternalTextureFormat(GL_RGB16);
QVERIFY(!(format1c == format2c));
QVERIFY(format1c != format2c);
format2c.setInternalTextureFormat(GL_RGB16);
- QVERIFY(format1c == format2c);
+ QCOMPARE(format1c, format2c);
QVERIFY(!(format1c != format2c));
QGLFramebufferObjectFormat format3c(format1c);
QGLFramebufferObjectFormat format4c;
- QVERIFY(format1c == format3c);
+ QCOMPARE(format1c, format3c);
QVERIFY(!(format1c != format3c));
format3c.setInternalTextureFormat(
#ifdef QT_OPENGL_ES_2
@@ -1719,7 +1719,7 @@ void tst_QGL::fboFormat()
QVERIFY(format1c != format3c);
format4c = format1c;
- QVERIFY(format1c == format4c);
+ QCOMPARE(format1c, format4c);
QVERIFY(!(format1c != format4c));
format4c.setInternalTextureFormat(
#ifdef QT_OPENGL_ES_2
@@ -1947,7 +1947,7 @@ void tst_QGL::destroyFBOAfterContext()
delete glw;
// The handle should now be zero.
- QVERIFY(fbo->handle() == 0);
+ QVERIFY(!fbo->handle());
QVERIFY(!fbo->isValid());
delete fbo;
@@ -1984,14 +1984,14 @@ void tst_QGL::shareRegister()
// Create a guard for the first context.
QOpenGLSharedResourceGuard guard(glw1->context()->contextHandle());
- QVERIFY(guard.id() == 0);
+ QCOMPARE(guard.id(), 0);
guard.setId(3);
- QVERIFY(guard.id() == 3);
+ QCOMPARE(guard.id(), 3);
// Request a tst_QGLResource object for the first context.
tst_QGLResource *res1 = qt_shared_test()->value(glw1->context()->contextHandle());
QVERIFY(res1);
- QVERIFY(qt_shared_test()->value(glw1->context()->contextHandle()) == res1);
+ QCOMPARE(qt_shared_test()->value(glw1->context()->contextHandle()), res1);
// Create another context that shares with the first.
QVERIFY(!glw1->isSharing());
@@ -2005,12 +2005,12 @@ void tst_QGL::shareRegister()
QVERIFY(glw1->context() != glw2->context());
// Check that the first context's resource is also on the second.
- QVERIFY(qt_shared_test()->value(glw1->context()) == res1);
- QVERIFY(qt_shared_test()->value(glw2->context()) == res1);
+ QCOMPARE(qt_shared_test()->value(glw1->context()), res1);
+ QCOMPARE(qt_shared_test()->value(glw2->context()), res1);
// Guard should still be the same.
- QVERIFY(guard.context() == glw1->context());
- QVERIFY(guard.id() == 3);
+ QCOMPARE(guard.context(), glw1->context());
+ QCOMPARE(guard.id(), 3);
// Check the sharing relationships.
QVERIFY(QGLContext::areSharing(glw1->context(), glw1->context()));
@@ -2032,9 +2032,9 @@ void tst_QGL::shareRegister()
// Request a resource to the third context.
tst_QGLResource *res3 = qt_shared_test()->value(glw3->context());
QVERIFY(res3);
- QVERIFY(qt_shared_test()->value(glw1->context()) == res1);
- QVERIFY(qt_shared_test()->value(glw2->context()) == res1);
- QVERIFY(qt_shared_test()->value(glw3->context()) == res3);
+ QCOMPARE(qt_shared_test()->value(glw1->context()), res1);
+ QCOMPARE(qt_shared_test()->value(glw2->context()), res1);
+ QCOMPARE(qt_shared_test()->value(glw3->context()), res3);
// Check the sharing relationships again.
QVERIFY(QGLContext::areSharing(glw1->context(), glw1->context()));
@@ -2053,8 +2053,8 @@ void tst_QGL::shareRegister()
QVERIFY(!QGLContext::areSharing(0, 0));
// Shared guard should still be the same.
- QVERIFY(guard.context() == glw1->context());
- QVERIFY(guard.id() == 3);
+ QCOMPARE(guard.context(), glw1->context());
+ QCOMPARE(guard.id(), 3);
// Delete the first context.
delete glw1;
@@ -2064,14 +2064,14 @@ void tst_QGL::shareRegister()
// The first context's resource should transfer to the second context.
QCOMPARE(tst_QGLResource::deletions, 0);
- QVERIFY(qt_shared_test()->value(glw2->context()) == res1);
- QVERIFY(qt_shared_test()->value(glw3->context()) == res3);
+ QCOMPARE(qt_shared_test()->value(glw2->context()), res1);
+ QCOMPARE(qt_shared_test()->value(glw3->context()), res3);
// Shared guard should now be the second context, with the id the same.
- QVERIFY(guard.context() == glw2->context());
- QVERIFY(guard.id() == 3);
- QVERIFY(guard3.context() == glw3->context());
- QVERIFY(guard3.id() == 5);
+ QCOMPARE(guard.context(), glw2->context());
+ QCOMPARE(guard.id(), 3);
+ QCOMPARE(guard3.context(), glw3->context());
+ QCOMPARE(guard3.id(), 5);
// Clean up and check that the resources are properly deleted.
delete glw2;
@@ -2115,25 +2115,25 @@ void tst_QGL::qglContextDefaultBindTexture()
QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
// Make sure the texture IDs returned are valid:
- QCOMPARE((bool)funcs->glIsTexture(boundImageTextureId), GL_TRUE);
- QCOMPARE((bool)funcs->glIsTexture(boundPixmapTextureId), GL_TRUE);
+ QCOMPARE(funcs->glIsTexture(boundImageTextureId), GLboolean(GL_TRUE));
+ QCOMPARE(funcs->glIsTexture(boundPixmapTextureId), GLboolean(GL_TRUE));
// Make sure the textures are still valid after we delete the image/pixmap:
// Also check that although the textures are left intact, the cache entries are removed:
delete boundImage;
boundImage = 0;
- QCOMPARE((bool)funcs->glIsTexture(boundImageTextureId), GL_TRUE);
+ QCOMPARE(funcs->glIsTexture(boundImageTextureId), GLboolean(GL_TRUE));
QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
delete boundPixmap;
boundPixmap = 0;
- QCOMPARE((bool)funcs->glIsTexture(boundPixmapTextureId), GL_TRUE);
+ QCOMPARE(funcs->glIsTexture(boundPixmapTextureId), GLboolean(GL_TRUE));
QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
// Finally, make sure QGLContext::deleteTexture deletes the texture IDs:
ctx->deleteTexture(boundImageTextureId);
ctx->deleteTexture(boundPixmapTextureId);
- QCOMPARE((bool)funcs->glIsTexture(boundImageTextureId), GL_FALSE);
- QCOMPARE((bool)funcs->glIsTexture(boundPixmapTextureId), GL_FALSE);
+ QCOMPARE(funcs->glIsTexture(boundImageTextureId), GLboolean(GL_FALSE));
+ QCOMPARE(funcs->glIsTexture(boundPixmapTextureId), GLboolean(GL_FALSE));
}
#endif
diff --git a/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp b/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp
index b0409d46d0..f96e3514a7 100644
--- a/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp
+++ b/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp
@@ -86,14 +86,14 @@ void tst_QGLBuffer::testBuffer(QGLBuffer::Type type)
// Create the local object, but not the buffer in the server.
QGLBuffer buffer(type);
- QVERIFY(buffer.usagePattern() == QGLBuffer::StaticDraw);
+ QCOMPARE(buffer.usagePattern(), QGLBuffer::StaticDraw);
buffer.setUsagePattern(QGLBuffer::UsagePattern(usagePattern));
// Check the initial state.
- QVERIFY(buffer.type() == type);
+ QCOMPARE(buffer.type(), type);
QVERIFY(!buffer.isCreated());
- QVERIFY(buffer.bufferId() == 0);
- QVERIFY(buffer.usagePattern() == QGLBuffer::UsagePattern(usagePattern));
+ QCOMPARE(buffer.bufferId(), GLuint(0));
+ QCOMPARE(buffer.usagePattern(), QGLBuffer::UsagePattern(usagePattern));
QCOMPARE(buffer.size(), -1);
// Should not be able to bind it yet because it isn't created.
@@ -253,7 +253,7 @@ void tst_QGLBuffer::bufferSharing()
delete w2;
// The buffer should now be invalid.
- QVERIFY(buffer.bufferId() == 0);
+ QCOMPARE(buffer.bufferId(), GLuint(0));
QVERIFY(!buffer.isCreated());
}
diff --git a/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp b/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp
index 866cd57381..07fdba4664 100644
--- a/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp
+++ b/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp
@@ -200,13 +200,13 @@ void tst_QGLFunctions::multitexture()
GLint active = 0;
funcs.glGetIntegerv(GL_ACTIVE_TEXTURE, &active);
- QVERIFY(active == GL_TEXTURE1);
+ QCOMPARE(active, GL_TEXTURE1);
funcs.glActiveTexture(GL_TEXTURE0);
active = 0;
funcs.glGetIntegerv(GL_ACTIVE_TEXTURE, &active);
- QVERIFY(active == GL_TEXTURE0);
+ QCOMPARE(active, GL_TEXTURE0);
}
// Verify that the glBlendColor() function appears to resolve and work.
diff --git a/tests/auto/other/compiler/tst_compiler.cpp b/tests/auto/other/compiler/tst_compiler.cpp
index 8f7dcdb3c5..5ef247483d 100644
--- a/tests/auto/other/compiler/tst_compiler.cpp
+++ b/tests/auto/other/compiler/tst_compiler.cpp
@@ -336,17 +336,17 @@ struct Qxxx {};
void tst_Compiler::detectDataStream()
{
- QVERIFY(QtTestInternal::DataStreamChecker<int>::HasDataStream == true);
- QVERIFY(QtTestInternal::DataStreamChecker<uint>::HasDataStream == true);
+ QVERIFY(QtTestInternal::DataStreamChecker<int>::HasDataStream);
+ QVERIFY(QtTestInternal::DataStreamChecker<uint>::HasDataStream);
QVERIFY(QtTestInternal::DataStreamChecker<char *>::HasDataStream == true);
QVERIFY(QtTestInternal::DataStreamChecker<const int>::HasInDataStream == true);
QVERIFY(QtTestInternal::DataStreamChecker<const int>::HasOutDataStream == false);
QVERIFY(QtTestInternal::DataStreamChecker<const int>::HasDataStream == false);
- QVERIFY(QtTestInternal::DataStreamChecker<double>::HasDataStream == true);
+ QVERIFY(QtTestInternal::DataStreamChecker<double>::HasDataStream);
- QVERIFY(QtTestInternal::DataStreamChecker<QString>::HasDataStream == true);
- QVERIFY(QtTestInternal::DataStreamChecker<MyString>::HasDataStream == true);
- QVERIFY(QtTestInternal::DataStreamChecker<Qxxx>::HasDataStream == false);
+ QVERIFY(QtTestInternal::DataStreamChecker<QString>::HasDataStream);
+ QVERIFY(QtTestInternal::DataStreamChecker<MyString>::HasDataStream);
+ QVERIFY(!QtTestInternal::DataStreamChecker<Qxxx>::HasDataStream);
QVERIFY(QtTestInternal::getSaveOperator<int>() != 0);
QVERIFY(QtTestInternal::getSaveOperator<uint>() != 0);
@@ -354,7 +354,7 @@ void tst_Compiler::detectDataStream()
QVERIFY(QtTestInternal::getSaveOperator<double>() != 0);
QVERIFY(QtTestInternal::getSaveOperator<QString>() != 0);
QVERIFY(QtTestInternal::getSaveOperator<MyString>() != 0);
- QVERIFY(QtTestInternal::getSaveOperator<Qxxx>() == 0);
+ QVERIFY(!QtTestInternal::getSaveOperator<Qxxx>());
}
#else
void tst_Compiler::detectDataStream()
@@ -637,7 +637,7 @@ void tst_Compiler::cxx11_alignas()
QSKIP("Compiler does not support C++11 feature");
#else
alignas(double) char c;
- QVERIFY(Q_ALIGNOF(c) == Q_ALIGNOF(double));
+ QCOMPARE(Q_ALIGNOF(c), Q_ALIGNOF(double));
#endif
}
diff --git a/tests/auto/other/gestures/BLACKLIST b/tests/auto/other/gestures/BLACKLIST
new file mode 100644
index 0000000000..4e8745ca78
--- /dev/null
+++ b/tests/auto/other/gestures/BLACKLIST
@@ -0,0 +1,2 @@
+[customGesture]
+opensuse-13.1
diff --git a/tests/auto/other/gestures/tst_gestures.cpp b/tests/auto/other/gestures/tst_gestures.cpp
index 43ce6b2d72..2a4f88c627 100644
--- a/tests/auto/other/gestures/tst_gestures.cpp
+++ b/tests/auto/other/gestures/tst_gestures.cpp
@@ -1461,7 +1461,7 @@ void tst_Gestures::ungrabGesture() // a method on QWidget
QPointer<QGesture> customGestureB;
customGestureB = *(b->gestures.begin());
QVERIFY(!customGestureB.isNull());
- QVERIFY(customGestureA.data() == customGestureB.data());
+ QCOMPARE(customGestureA.data(), customGestureB.data());
QCOMPARE(customGestureB->gestureType(), CustomGesture::GestureType);
a->gestures.clear();
diff --git a/tests/auto/other/macgui/tst_macgui.cpp b/tests/auto/other/macgui/tst_macgui.cpp
index 56035f4be4..ba6ac536f2 100644
--- a/tests/auto/other/macgui/tst_macgui.cpp
+++ b/tests/auto/other/macgui/tst_macgui.cpp
@@ -146,7 +146,7 @@ void tst_MacGui::splashScreenModality()
connect(wn.getWidget(interface), SIGNAL(clicked()), SLOT(exitLoopSlot()));
const int timeout = 4;
QTestEventLoop::instance().enterLoop(timeout);
- QVERIFY(QTestEventLoop::instance().timeout() == false);
+ QVERIFY(!QTestEventLoop::instance().timeout());
}
class PrimaryWindowDialog : public QDialog
@@ -231,7 +231,7 @@ void tst_MacGui::spinBoxArrowButtons()
const QRect lessRect = lessInterface->rect();
const QRect lessLocalRect(colorWidget.mapFromGlobal(lessRect.topLeft()), colorWidget.mapFromGlobal(lessRect.bottomRight()));
const QRect compareRect = lessLocalRect.adjusted(5, 3, -5, -7);
- QVERIFY(noFocus.copy(compareRect) == focus.copy(compareRect));
+ QCOMPARE(noFocus.copy(compareRect), focus.copy(compareRect));
}
QTEST_MAIN(tst_MacGui)
diff --git a/tests/auto/other/macnativeevents/BLACKLIST b/tests/auto/other/macnativeevents/BLACKLIST
index 2820457075..4129868022 100644
--- a/tests/auto/other/macnativeevents/BLACKLIST
+++ b/tests/auto/other/macnativeevents/BLACKLIST
@@ -3,9 +3,22 @@
osx
[testMouseEnter]
osx-10.9
+osx-10.8
[testChildDialogInFrontOfModalParent]
osx
[testChildWindowInFrontOfStaysOnTopParentWindow]
osx
[testModifierCtrlWithDontSwapCtrlAndMeta]
osx
+[testMouseMoveLocation]
+osx
+[testMouseLeftDoubleClick]
+osx
+[stressTestMouseLeftDoubleClick]
+osx
+[testMouseDragInside]
+osx
+[testMouseDragOutside]
+osx
+[testMouseDragToNonClientArea]
+osx
diff --git a/tests/auto/other/macnativeevents/tst_macnativeevents.cpp b/tests/auto/other/macnativeevents/tst_macnativeevents.cpp
index 5d24655144..d1c5e4a35e 100644
--- a/tests/auto/other/macnativeevents/tst_macnativeevents.cpp
+++ b/tests/auto/other/macnativeevents/tst_macnativeevents.cpp
@@ -457,8 +457,8 @@ void tst_MacNativeEvents::testModifierCtrl()
QWidget w;
w.show();
- QVERIFY(kControlUnicode == QKeySequence(Qt::Key_Meta).toString(QKeySequence::NativeText)[0]);
- QVERIFY(kCommandUnicode == QKeySequence(Qt::Key_Control).toString(QKeySequence::NativeText)[0]);
+ QCOMPARE(ushort(kControlUnicode), QKeySequence(Qt::Key_Meta).toString(QKeySequence::NativeText).at(0).unicode());
+ QCOMPARE(ushort(kCommandUnicode), QKeySequence(Qt::Key_Control).toString(QKeySequence::NativeText).at(0).unicode());
NativeEventList native;
native.append(new QNativeModifierEvent(Qt::ControlModifier));
@@ -490,8 +490,8 @@ void tst_MacNativeEvents::testModifierCtrlWithDontSwapCtrlAndMeta()
QWidget w;
w.show();
- QVERIFY(kCommandUnicode == QKeySequence(Qt::Key_Meta).toString(QKeySequence::NativeText)[0]);
- QVERIFY(kControlUnicode == QKeySequence(Qt::Key_Control).toString(QKeySequence::NativeText)[0]);
+ QCOMPARE(ushort(kCommandUnicode), QKeySequence(Qt::Key_Meta).toString(QKeySequence::NativeText).at(0).unicode());
+ QCOMPARE(ushort(kControlUnicode), QKeySequence(Qt::Key_Control).toString(QKeySequence::NativeText).at(0).unicode());
NativeEventList native;
native.append(new QNativeModifierEvent(Qt::ControlModifier));
diff --git a/tests/auto/other/modeltest/modeltest.cpp b/tests/auto/other/modeltest/modeltest.cpp
index 72a4a0ad29..c119fdaa4e 100644
--- a/tests/auto/other/modeltest/modeltest.cpp
+++ b/tests/auto/other/modeltest/modeltest.cpp
@@ -569,7 +569,7 @@ void ModelTest::dataChanged(const QModelIndex &topLeft, const QModelIndex &botto
QVERIFY(topLeft.isValid());
QVERIFY(bottomRight.isValid());
QModelIndex commonParent = bottomRight.parent();
- QVERIFY(topLeft.parent() == commonParent);
+ QCOMPARE(topLeft.parent(), commonParent);
QVERIFY(topLeft.row() <= bottomRight.row());
QVERIFY(topLeft.column() <= bottomRight.column());
int rowCount = model->rowCount(commonParent);
diff --git a/tests/auto/other/networkselftest/tst_networkselftest.cpp b/tests/auto/other/networkselftest/tst_networkselftest.cpp
index 5612260cca..7ce385121c 100644
--- a/tests/auto/other/networkselftest/tst_networkselftest.cpp
+++ b/tests/auto/other/networkselftest/tst_networkselftest.cpp
@@ -34,6 +34,8 @@
#include <QtTest/QtTest>
#include <QtNetwork/QtNetwork>
#include <QtCore/QDateTime>
+#include <QtCore/QTextStream>
+#include <QtCore/QStandardPaths>
#include <QtCore/private/qiodevice_p.h>
#ifndef QT_NO_BEARERMANAGEMENT
@@ -460,7 +462,7 @@ void tst_NetworkSelfTest::remotePortsOpen()
else
QFAIL(QString("Error connecting to server on port %1: %2").arg(portNumber).arg(socket.errorString()).toLocal8Bit());
}
- QVERIFY(socket.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
}
static QList<Chat> ftpChat(const QByteArray &userSuffix = QByteArray())
@@ -960,6 +962,25 @@ void tst_NetworkSelfTest::supportsSsl()
#endif
}
+#ifndef QT_NO_PROCESS
+static const QByteArray msgProcessError(const QProcess &process, const char *what)
+{
+ QString result;
+ QTextStream(&result) << what << ": \"" << process.program() << ' '
+ << process.arguments().join(QLatin1Char(' ')) << "\": " << process.errorString();
+ return result.toLocal8Bit();
+}
+
+static void ensureTermination(QProcess &process)
+{
+ if (process.state() == QProcess::Running) {
+ process.terminate();
+ if (!process.waitForFinished(300))
+ process.kill();
+ }
+}
+#endif // !QT_NO_PROCESS
+
void tst_NetworkSelfTest::smbServer()
{
static const char contents[] = "This is 34 bytes. Do not change...";
@@ -977,19 +998,24 @@ void tst_NetworkSelfTest::smbServer()
QVERIFY(memcmp(buf, contents, strlen(contents)) == 0);
#else
#ifndef QT_NO_PROCESS
+ enum { sambaTimeOutSecs = 5 };
// try to use Samba
- QString progname = "smbclient";
- QProcess smbclient;
- smbclient.start(progname, QIODevice::ReadOnly);
- if (!smbclient.waitForStarted(2000))
+ const QString progname = "smbclient";
+ const QString binary = QStandardPaths::findExecutable(progname);
+ if (binary.isEmpty())
QSKIP("Could not find smbclient (from Samba), cannot continue testing");
- if (!smbclient.waitForFinished(2000) || smbclient.exitStatus() != QProcess::NormalExit)
- QSKIP("smbclient isn't working, cannot continue testing");
- smbclient.close();
// try listing the server
- smbclient.start(progname, QStringList() << "-g" << "-N" << "-L" << QtNetworkSettings::winServerName(), QIODevice::ReadOnly);
- QVERIFY(smbclient.waitForFinished(5000));
+ const QStringList timeOutArguments = QStringList()
+ << "--timeout" << QString::number(sambaTimeOutSecs);
+ QStringList arguments = timeOutArguments;
+ arguments << "-g" << "-N" << "-L" << QtNetworkSettings::winServerName();
+ QProcess smbclient;
+ smbclient.start(binary, arguments, QIODevice::ReadOnly);
+ QVERIFY2(smbclient.waitForStarted(), msgProcessError(smbclient, "Unable to start"));
+ const bool listFinished = smbclient.waitForFinished((1 + sambaTimeOutSecs) * 1000);
+ ensureTermination(smbclient);
+ QVERIFY2(listFinished, msgProcessError(smbclient, "Listing servers timed out"));
if (smbclient.exitStatus() != QProcess::NormalExit)
QSKIP("smbclient crashed");
QVERIFY2(smbclient.exitCode() == 0, "Test server not found");
@@ -1004,9 +1030,13 @@ void tst_NetworkSelfTest::smbServer()
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("PAGER", "/bin/cat"); // just in case
smbclient.setProcessEnvironment(env);
- smbclient.start(progname, QStringList() << "-N" << "-c" << "more test.pri"
- << QString("\\\\%1\\testshare").arg(QtNetworkSettings::winServerName()), QIODevice::ReadOnly);
- QVERIFY(smbclient.waitForFinished(5000));
+ arguments = timeOutArguments;
+ arguments << "-N" << "-c" << "more test.pri"
+ << ("\\\\" + QtNetworkSettings::winServerName() + "\\testshare");
+ smbclient.start(binary, arguments, QIODevice::ReadOnly);
+ const bool fileFinished = smbclient.waitForFinished((1 + sambaTimeOutSecs) * 1000);
+ ensureTermination(smbclient);
+ QVERIFY2(fileFinished, msgProcessError(smbclient, "Timed out"));
if (smbclient.exitStatus() != QProcess::NormalExit)
QSKIP("smbclient crashed");
QVERIFY2(smbclient.exitCode() == 0, "File //qt-test-server/testshare/test.pri not found");
diff --git a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
index 4f891fcda0..62c2c0a916 100644
--- a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
+++ b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
@@ -162,16 +162,6 @@ static inline bool verifyChild(QWidget *child, QAccessibleInterface *interface,
return true;
}
-static inline int indexOfChild(QAccessibleInterface *parentInterface, QWidget *childWidget)
-{
- if (!parentInterface || !childWidget)
- return -1;
- QAccessibleInterface *childInterface(QAccessible::queryAccessibleInterface(childWidget));
- if (!childInterface)
- return -1;
- return parentInterface->indexOfChild(childInterface);
-}
-
#define EXPECT(cond) \
do { \
if (!errorAt && !(cond)) { \
@@ -462,15 +452,15 @@ void tst_QAccessibility::statesStructTest()
QVERIFY(s1.modal == 0);
QAccessible::State s2;
- QVERIFY(s2 == s1);
+ QCOMPARE(s2, s1);
s2.busy = true;
QVERIFY(!(s2 == s1));
s1.busy = true;
- QVERIFY(s2 == s1);
+ QCOMPARE(s2, s1);
s1 = QAccessible::State();
QVERIFY(!(s2 == s1));
s1 = s2;
- QVERIFY(s2 == s1);
+ QCOMPARE(s2, s1);
QVERIFY(s1.busy == 1);
}
@@ -533,9 +523,9 @@ void tst_QAccessibility::navigateHierarchy()
QVERIFY(ifaceW->isValid());
QAccessibleInterface *target = ifaceW->child(14);
- QVERIFY(target == 0);
+ QVERIFY(!target);
target = ifaceW->child(-1);
- QVERIFY(target == 0);
+ QVERIFY(!target);
target = ifaceW->child(0);
QAccessibleInterface *interfaceW1(ifaceW->child(0));
QVERIFY(target);
@@ -551,7 +541,7 @@ void tst_QAccessibility::navigateHierarchy()
QCOMPARE(target->object(), (QObject*)w3);
QAccessibleInterface *child = target->child(1);
- QVERIFY(child == 0);
+ QVERIFY(!child);
child = target->child(0);
QVERIFY(child != 0);
QVERIFY(child->isValid());
@@ -969,7 +959,7 @@ void tst_QAccessibility::mainWindowTest()
QWindow window;
window.setGeometry(80, 80, 40, 40);
window.show();
- QTRY_VERIFY(QGuiApplication::focusWindow() == &window);
+ QTRY_COMPARE(QGuiApplication::focusWindow(), &window);
// We currently don't have an accessible interface for QWindow
// the active state is either in the QMainWindow or QQuickView
@@ -1313,7 +1303,7 @@ void tst_QAccessibility::tabTest()
QCOMPARE(child1->text(QAccessible::Description), QLatin1String("Cool tool tip"));
QCOMPARE(child1->text(QAccessible::Help), QLatin1String("I don't know"));
- QVERIFY((child1->state().invisible) == false);
+ QVERIFY(!(child1->state().invisible));
tabBar->hide();
QCoreApplication::processEvents();
@@ -1660,7 +1650,7 @@ void tst_QAccessibility::spinBoxTest()
// make sure that the line edit is not there
const int numChildren = interface->childCount();
QCOMPARE(numChildren, 0);
- QVERIFY(interface->child(0) == Q_NULLPTR);
+ QVERIFY(!interface->child(0));
QVERIFY(interface->valueInterface());
QCOMPARE(interface->valueInterface()->currentValue().toInt(), 3);
@@ -1746,6 +1736,13 @@ static bool fuzzyRectCompare(const QRect &a, const QRect &b)
&& qAbs(delta.right()) <= MAX_ACCEPTABLE_DELTA && qAbs(delta.bottom()) <= MAX_ACCEPTABLE_DELTA;
}
+static QByteArray msgRectMismatch(const QRect &a, const QRect &b)
+{
+ QString result;
+ QDebug(&result) << a << "!=" << b;
+ return result.toLocal8Bit();
+}
+
void tst_QAccessibility::textEditTest()
{
for (int pass = 0; pass < 2; ++pass) {
@@ -1791,16 +1788,24 @@ void tst_QAccessibility::textEditTest()
int offset = 10;
QCOMPARE(textIface->text(offset, offset + 1), QStringLiteral("d"));
- QVERIFY(fuzzyRectCompare(textIface->characterRect(offset), characterRect(edit, offset)));
+ const QRect actual10 = textIface->characterRect(offset);
+ const QRect expected10 = characterRect(edit, offset);
+ QVERIFY2(fuzzyRectCompare(actual10, expected10), msgRectMismatch(actual10, expected10).constData());
offset = 13;
QCOMPARE(textIface->text(offset, offset + 1), QStringLiteral("H"));
- QVERIFY(fuzzyRectCompare(textIface->characterRect(offset), characterRect(edit, offset)));
+ const QRect actual13 = textIface->characterRect(offset);
+ const QRect expected13 = characterRect(edit, offset);
+ QVERIFY2(fuzzyRectCompare(actual13, expected13), msgRectMismatch(actual13, expected13).constData());
offset = 21;
QCOMPARE(textIface->text(offset, offset + 1), QStringLiteral("y"));
- QVERIFY(fuzzyRectCompare(textIface->characterRect(offset), characterRect(edit, offset)));
+ const QRect actual21 = textIface->characterRect(offset);
+ const QRect expected21 = characterRect(edit, offset);
+ QVERIFY2(fuzzyRectCompare(actual21, expected21), msgRectMismatch(actual21, expected21).constData());
offset = 32;
QCOMPARE(textIface->text(offset, offset + 1), QStringLiteral("I"));
- QVERIFY(fuzzyRectCompare(textIface->characterRect(offset), characterRect(edit, offset)));
+ const QRect actual32 = textIface->characterRect(offset);
+ const QRect expected32 = characterRect(edit, offset);
+ QVERIFY2(fuzzyRectCompare(actual32, expected32), msgRectMismatch(actual32, expected32).constData());
QTestAccessibility::clearEvents();
@@ -2481,7 +2486,7 @@ void tst_QAccessibility::groupBoxTest()
QCOMPARE(iface->text(QAccessible::Name), QLatin1String("Test QGroupBox"));
QCOMPARE(iface->text(QAccessible::Description), QLatin1String("This group box will be used to test accessibility"));
QVector<QPair<QAccessibleInterface*, QAccessible::Relation> > relations = rButtonIface->relations();
- QVERIFY(relations.size() == 1);
+ QCOMPARE(relations.size(), 1);
QPair<QAccessibleInterface*, QAccessible::Relation> relation = relations.first();
QCOMPARE(relation.first->object(), groupBox);
QCOMPARE(relation.second, QAccessible::Label);
@@ -3526,13 +3531,13 @@ void tst_QAccessibility::dockWidgetTest()
QPoint buttonPoint = pb2->mapToGlobal(QPoint(pb2->width()/2, pb2->height()/2));
QAccessibleInterface *childAt = accDock2->childAt(buttonPoint.x(), buttonPoint.y());
QVERIFY(childAt);
- QVERIFY(childAt->object() == pb2);
+ QCOMPARE(childAt->object(), pb2);
QWidget *close1 = qobject_cast<QWidget*>(dock1Close->object());
QPoint close1ButtonPoint = close1->mapToGlobal(QPoint(close1->width()/2, close1->height()/2));
QAccessibleInterface *childAt2 = accDock1->childAt(close1ButtonPoint.x(), close1ButtonPoint.y());
QVERIFY(childAt2);
- QVERIFY(childAt2->object() == close1);
+ QCOMPARE(childAt2->object(), close1);
// custom title bar widget
QDockWidget *dock3 = new QDockWidget(mw);
diff --git a/tests/auto/other/qcomplextext/tst_qcomplextext.cpp b/tests/auto/other/qcomplextext/tst_qcomplextext.cpp
index a9234b7060..1428a63123 100644
--- a/tests/auto/other/qcomplextext/tst_qcomplextext.cpp
+++ b/tests/auto/other/qcomplextext/tst_qcomplextext.cpp
@@ -173,7 +173,7 @@ void tst_QComplexText::bidiCursor_qtbug2795()
qreal x2 = line2.cursorToX(0) - line2.cursorToX(str.size());
// The cursor should remain at the same position after a digit is appended
- QVERIFY(x1 == x2);
+ QCOMPARE(x1, x2);
}
void tst_QComplexText::bidiCursorMovement_data()
diff --git a/tests/auto/other/windowsmobile/test/tst_windowsmobile.cpp b/tests/auto/other/windowsmobile/test/tst_windowsmobile.cpp
index b161dccb88..acb0d28c6b 100644
--- a/tests/auto/other/windowsmobile/test/tst_windowsmobile.cpp
+++ b/tests/auto/other/windowsmobile/test/tst_windowsmobile.cpp
@@ -132,7 +132,7 @@ void compareScreenshots(const QString &image1, const QString &image2)
//screenShot.save("scr2.png", "PNG");
//original.save("orig1.png", "PNG");
- QVERIFY(original == screenShot);
+ QCOMPARE(original, screenShot);
}
void takeScreenShot(const QString filename)
diff --git a/tests/auto/printsupport/kernel/qprintdevice/tst_qprintdevice.cpp b/tests/auto/printsupport/kernel/qprintdevice/tst_qprintdevice.cpp
index 598abca43b..f3b865ed92 100644
--- a/tests/auto/printsupport/kernel/qprintdevice/tst_qprintdevice.cpp
+++ b/tests/auto/printsupport/kernel/qprintdevice/tst_qprintdevice.cpp
@@ -57,7 +57,6 @@ void tst_QPrintDevice::basics()
if (defaultId.isEmpty()) {
qDebug() << "No default printer found";
} else {
- qDebug() << "Default Printer ID :" << defaultId;
QVERIFY(ps->availablePrintDeviceIds().contains(defaultId));
}
@@ -66,7 +65,9 @@ void tst_QPrintDevice::basics()
// Just exercise the api for now as we don't know what is installed
foreach (const QString id, ps->availablePrintDeviceIds()) {
QPrintDevice printDevice = ps->createPrintDevice(id);
- qDebug() << "Created printer" << id;
+ const char quote = id == defaultId ? '*' : '"';
+ qDebug().noquote().nospace() << "\nCreated printer " << quote << id
+ << quote << ":\n" << printDevice << '\n';
QCOMPARE(printDevice.isValid(), true);
printDevice.id();
printDevice.name();
diff --git a/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp b/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp
index c256d9ba82..318f87467c 100644
--- a/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp
+++ b/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp
@@ -425,12 +425,12 @@ void tst_QPrinter::outputFormatFromSuffix()
if (QPrinterInfo::availablePrinters().size() == 0)
QSKIP("No printers available.");
QPrinter p;
- QVERIFY(p.outputFormat() == QPrinter::NativeFormat);
+ QCOMPARE(p.outputFormat(), QPrinter::NativeFormat);
p.setOutputFileName("test.pdf");
TempFileCleanup tmpFile("test.pdf");
- QVERIFY(p.outputFormat() == QPrinter::PdfFormat);
+ QCOMPARE(p.outputFormat(), QPrinter::PdfFormat);
p.setOutputFileName(QString());
- QVERIFY(p.outputFormat() == QPrinter::NativeFormat);
+ QCOMPARE(p.outputFormat(), QPrinter::NativeFormat);
}
void tst_QPrinter::testPageMargins_data()
diff --git a/tests/auto/sql/kernel/qsqldatabase/testdata/qtest.mdb b/tests/auto/sql/kernel/qsqldatabase/testdata/qtest.mdb
index f388f192ac..f388f192ac 100755..100644
--- a/tests/auto/sql/kernel/qsqldatabase/testdata/qtest.mdb
+++ b/tests/auto/sql/kernel/qsqldatabase/testdata/qtest.mdb
Binary files differ
diff --git a/tests/auto/sql/kernel/qsqldatabase/tst_databases.h b/tests/auto/sql/kernel/qsqldatabase/tst_databases.h
index c499aed481..fe8a3689b0 100644
--- a/tests/auto/sql/kernel/qsqldatabase/tst_databases.h
+++ b/tests/auto/sql/kernel/qsqldatabase/tst_databases.h
@@ -261,8 +261,8 @@ public:
// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org" );
// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org", 3307 );
-// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org", 3308, "CLIENT_COMPRESS=1;CLIENT_SSL=1" ); // MySQL 4.1.1
-// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org", 3309, "CLIENT_COMPRESS=1;CLIENT_SSL=1" ); // MySQL 5.0.18 Linux
+// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org", 3308, "CLIENT_COMPRESS=1" ); // MySQL 4.1.1
+// addDb( "QMYSQL3", "testdb", "troll", "trond", "horsehead.qt-project.org", 3309, "CLIENT_COMPRESS=1" ); // MySQL 5.0.18 Linux
// addDb( "QMYSQL3", "testdb", "troll", "trond", "silence.qt-project.org" ); // MySQL 5.1.36 Windows
// addDb( "QMYSQL3", "testdb", "testuser", "Ee4Gabf6_", "bq-mysql41.qt-project.org" ); // MySQL 4.1.22-2.el4 linux
diff --git a/tests/auto/sql/kernel/qsqldatabase/tst_qsqldatabase.cpp b/tests/auto/sql/kernel/qsqldatabase/tst_qsqldatabase.cpp
index 1993f23672..83cf0394f9 100644
--- a/tests/auto/sql/kernel/qsqldatabase/tst_qsqldatabase.cpp
+++ b/tests/auto/sql/kernel/qsqldatabase/tst_qsqldatabase.cpp
@@ -1569,11 +1569,11 @@ void tst_QSqlDatabase::ibase_numericFields()
QCOMPARE(q.value(2).toString(), QString("%1").arg(num2));
QCOMPARE(QString("%1").arg(q.value(3).toDouble()), QString("%1").arg(num3));
QCOMPARE(QString("%1").arg(q.value(4).toDouble()), QString("%1").arg(num4));
- QVERIFY(q.value(0).type() == QVariant::Int);
- QVERIFY(q.value(1).type() == QVariant::Double);
- QVERIFY(q.value(2).type() == QVariant::Double);
- QVERIFY(q.value(3).type() == QVariant::Double);
- QVERIFY(q.value(4).type() == QVariant::Double);
+ QCOMPARE(q.value(0).type(), QVariant::Int);
+ QCOMPARE(q.value(1).type(), QVariant::Double);
+ QCOMPARE(q.value(2).type(), QVariant::Double);
+ QCOMPARE(q.value(3).type(), QVariant::Double);
+ QCOMPARE(q.value(4).type(), QVariant::Double);
QCOMPARE(q.record().field(1).length(), 2);
QCOMPARE(q.record().field(1).precision(), 1);
@@ -1583,16 +1583,16 @@ void tst_QSqlDatabase::ibase_numericFields()
QCOMPARE(q.record().field(3).precision(), 3);
QCOMPARE(q.record().field(4).length(), 18);
QCOMPARE(q.record().field(4).precision(), 4);
- QVERIFY(q.record().field(0).requiredStatus() == QSqlField::Required);
- QVERIFY(q.record().field(1).requiredStatus() == QSqlField::Optional);
+ QCOMPARE(q.record().field(0).requiredStatus(), QSqlField::Required);
+ QCOMPARE(q.record().field(1).requiredStatus(), QSqlField::Optional);
}
QSqlRecord r = db.record(tableName);
- QVERIFY(r.field(0).type() == QVariant::Int);
- QVERIFY(r.field(1).type() == QVariant::Double);
- QVERIFY(r.field(2).type() == QVariant::Double);
- QVERIFY(r.field(3).type() == QVariant::Double);
- QVERIFY(r.field(4).type() == QVariant::Double);
+ QCOMPARE(r.field(0).type(), QVariant::Int);
+ QCOMPARE(r.field(1).type(), QVariant::Double);
+ QCOMPARE(r.field(2).type(), QVariant::Double);
+ QCOMPARE(r.field(3).type(), QVariant::Double);
+ QCOMPARE(r.field(4).type(), QVariant::Double);
QCOMPARE(r.field(1).length(), 2);
QCOMPARE(r.field(1).precision(), 1);
QCOMPARE(r.field(2).length(), 5);
@@ -1601,8 +1601,8 @@ void tst_QSqlDatabase::ibase_numericFields()
QCOMPARE(r.field(3).precision(), 3);
QCOMPARE(r.field(4).length(), 18);
QCOMPARE(r.field(4).precision(), 4);
- QVERIFY(r.field(0).requiredStatus() == QSqlField::Required);
- QVERIFY(r.field(1).requiredStatus() == QSqlField::Optional);
+ QCOMPARE(r.field(0).requiredStatus(), QSqlField::Required);
+ QCOMPARE(r.field(1).requiredStatus(), QSqlField::Optional);
}
void tst_QSqlDatabase::ibase_fetchBlobs()
@@ -2086,7 +2086,7 @@ void tst_QSqlDatabase::eventNotificationIBase()
QCOMPARE(spy.count(), 1);
QList<QVariant> arguments = spy.takeFirst();
- QVERIFY(arguments.at(0).toString() == procedureName);
+ QCOMPARE(arguments.at(0).toString(), procedureName);
QVERIFY_SQL(*driver, unsubscribeFromNotification(procedureName));
q.exec(QString("DROP PROCEDURE %1").arg(procedureName));
}
diff --git a/tests/auto/sql/kernel/qsqlerror/tst_qsqlerror.cpp b/tests/auto/sql/kernel/qsqlerror/tst_qsqlerror.cpp
index 7a12f66452..70e09a2b80 100644
--- a/tests/auto/sql/kernel/qsqlerror/tst_qsqlerror.cpp
+++ b/tests/auto/sql/kernel/qsqlerror/tst_qsqlerror.cpp
@@ -160,7 +160,7 @@ void tst_QSqlError::operators()
error2.setType(QSqlError::NoError);
error3.setType(QSqlError::UnknownError);
- QVERIFY(error1 == error2);
+ QCOMPARE(error1, error2);
QVERIFY(error1 != error3);
}
diff --git a/tests/auto/sql/kernel/qsqlquery/tst_qsqlquery.cpp b/tests/auto/sql/kernel/qsqlquery/tst_qsqlquery.cpp
index 61586eb841..b98ab68ae9 100644
--- a/tests/auto/sql/kernel/qsqlquery/tst_qsqlquery.cpp
+++ b/tests/auto/sql/kernel/qsqlquery/tst_qsqlquery.cpp
@@ -241,6 +241,10 @@ private slots:
void aggregateFunctionTypes_data() { generic_data(); }
void aggregateFunctionTypes();
+
+ void integralTypesMysql_data() { generic_data("QMYSQL"); }
+ void integralTypesMysql();
+
private:
// returns all database connections
void generic_data(const QString &engine=QString());
@@ -3974,5 +3978,65 @@ void tst_QSqlQuery::aggregateFunctionTypes()
}
}
+template<typename T>
+void runIntegralTypesMysqlTest(QSqlDatabase &db, const QString &tableName, const QString &type, const bool withPreparedStatement,
+ const T min = std::numeric_limits<T>::min(), const T max = std::numeric_limits<T>::max())
+{
+ QSqlQuery q(db);
+ QVERIFY_SQL(q, exec("DROP TABLE IF EXISTS " + tableName));
+ QVERIFY_SQL(q, exec("CREATE TABLE " + tableName + " (id " + type + ")"));
+
+ const int steps = 20;
+ const T increment = max / steps - min / steps;
+
+ // insert some values
+ QVector<T> values;
+ values.resize(steps);
+ T v = min;
+ if (withPreparedStatement) {
+ QVERIFY_SQL(q, prepare("INSERT INTO " + tableName + " (id) VALUES (?)"));
+ }
+ for (int i = 0; i < values.size(); ++i) {
+ if (withPreparedStatement) {
+ q.bindValue(0, v);
+ QVERIFY_SQL(q, exec());
+ } else {
+ QVERIFY_SQL(q, exec("INSERT INTO " + tableName + " (id) VALUES (" + QString::number(v) + ")"));
+ }
+ values[i] = v;
+ v += increment;
+ }
+
+ // ensure we can read them back properly
+ QVERIFY_SQL(q, exec("SELECT id FROM " + tableName));
+ QVector<T> actualValues;
+ actualValues.reserve(values.size());
+ while (q.next()) {
+ actualValues << q.value(0).value<T>();
+ }
+ QCOMPARE(actualValues, values);
+}
+
+void tst_QSqlQuery::integralTypesMysql()
+{
+ QFETCH(QString, dbName);
+ QSqlDatabase db = QSqlDatabase::database(dbName);
+ CHECK_DATABASE(db);
+
+ for (int i = 0; i < 2; ++i) {
+ const bool withPreparedStatement = (i == 1);
+ runIntegralTypesMysqlTest<char>(db, "tinyIntTest", "TINYINT", withPreparedStatement);
+ runIntegralTypesMysqlTest<unsigned char>(db, "unsignedTinyIntTest", "TINYINT UNSIGNED", withPreparedStatement);
+ runIntegralTypesMysqlTest<char>(db, "smallIntTest", "SMALLINT", withPreparedStatement);
+ runIntegralTypesMysqlTest<unsigned char>(db, "unsignedSmallIntTest", "SMALLINT UNSIGNED", withPreparedStatement);
+ runIntegralTypesMysqlTest<int>(db, "mediumIntTest", "MEDIUMINT", withPreparedStatement, -(1 << 23), (1 << 23) - 1);
+ runIntegralTypesMysqlTest<unsigned int>(db, "unsignedMediumIntTest", "MEDIUMINT UNSIGNED", withPreparedStatement, 0, (1 << 24) - 1);
+ runIntegralTypesMysqlTest<int>(db, "intTest", "INT", withPreparedStatement);
+ runIntegralTypesMysqlTest<unsigned int>(db, "unsignedIntTest", "INT UNSIGNED", withPreparedStatement);
+ runIntegralTypesMysqlTest<long long>(db, "bigIntTest", "BIGINT", withPreparedStatement);
+ runIntegralTypesMysqlTest<unsigned long long>(db, "unsignedBigIntTest", "BIGINT UNSIGNED", withPreparedStatement);
+ }
+}
+
QTEST_MAIN( tst_QSqlQuery )
#include "tst_qsqlquery.moc"
diff --git a/tests/auto/sql/models/qsqlrelationaltablemodel/tst_qsqlrelationaltablemodel.cpp b/tests/auto/sql/models/qsqlrelationaltablemodel/tst_qsqlrelationaltablemodel.cpp
index 71ec2b6588..3702631275 100644
--- a/tests/auto/sql/models/qsqlrelationaltablemodel/tst_qsqlrelationaltablemodel.cpp
+++ b/tests/auto/sql/models/qsqlrelationaltablemodel/tst_qsqlrelationaltablemodel.cpp
@@ -858,7 +858,7 @@ static void testRevert(QSqlRelationalTableModel &model)
/* Now revert the newly inserted rows */
model.revertAll();
- QVERIFY(model.rowCount() == initialRowCount);
+ QCOMPARE(model.rowCount(), initialRowCount);
/* Insert rows again */
QVERIFY(model.insertRows(4, 4));
@@ -1026,7 +1026,7 @@ void tst_QSqlRelationalTableModel::invalidData()
QCOMPARE(model.data(model.index(0, 2)).toString(), QString("herr"));
//try to set data in non valid index
- QVERIFY(model.setData(model.index(0,10),5) == false);
+ QVERIFY(!model.setData(model.index(0,10),5));
//same test with LeftJoin mode
model.setJoinMode(QSqlRelationalTableModel::LeftJoin);
@@ -1037,7 +1037,7 @@ void tst_QSqlRelationalTableModel::invalidData()
QCOMPARE(model.data(model.index(0, 2)).toString(), QString("herr"));
//try to set data in non valid index
- QVERIFY(model.setData(model.index(0,10),5) == false);
+ QVERIFY(!model.setData(model.index(0,10),5));
}
void tst_QSqlRelationalTableModel::relationModel()
@@ -1051,20 +1051,20 @@ void tst_QSqlRelationalTableModel::relationModel()
model.setRelation(2, QSqlRelation(reltest2, "tid", "title"));
QVERIFY_SQL(model, select());
- QVERIFY(model.relationModel(0) == NULL);
- QVERIFY(model.relationModel(1) == NULL);
+ QVERIFY(!model.relationModel(0));
+ QVERIFY(!model.relationModel(1));
QVERIFY(model.relationModel(2) != NULL);
- QVERIFY(model.relationModel(3) == NULL);
- QVERIFY(model.relationModel(4) == NULL);
+ QVERIFY(!model.relationModel(3));
+ QVERIFY(!model.relationModel(4));
model.setRelation(3, QSqlRelation(reltest4, "id", "name"));
QVERIFY_SQL(model, select());
- QVERIFY(model.relationModel(0) == NULL);
- QVERIFY(model.relationModel(1) == NULL);
+ QVERIFY(!model.relationModel(0));
+ QVERIFY(!model.relationModel(1));
QVERIFY(model.relationModel(2) != NULL);
QVERIFY(model.relationModel(3) != NULL);
- QVERIFY(model.relationModel(4) == NULL);
+ QVERIFY(!model.relationModel(4));
QSqlTableModel *rel_model = model.relationModel(2);
QCOMPARE(rel_model->data(rel_model->index(0,1)).toString(), QString("herr"));
@@ -1073,11 +1073,11 @@ void tst_QSqlRelationalTableModel::relationModel()
model.setJoinMode(QSqlRelationalTableModel::LeftJoin);
QVERIFY_SQL(model, select());
- QVERIFY(model.relationModel(0) == NULL);
- QVERIFY(model.relationModel(1) == NULL);
+ QVERIFY(!model.relationModel(0));
+ QVERIFY(!model.relationModel(1));
QVERIFY(model.relationModel(2) != NULL);
QVERIFY(model.relationModel(3) != NULL);
- QVERIFY(model.relationModel(4) == NULL);
+ QVERIFY(!model.relationModel(4));
QSqlTableModel *rel_model2 = model.relationModel(2);
QCOMPARE(rel_model2->data(rel_model->index(0,1)).toString(), QString("herr"));
@@ -1487,13 +1487,13 @@ void tst_QSqlRelationalTableModel::selectAfterUpdate()
model.setTable(reltest1);
model.setRelation(2, QSqlRelation(reltest2, "tid", "title"));
QVERIFY_SQL(model, select());
- QVERIFY(model.relationModel(2)->rowCount() == 2);
+ QCOMPARE(model.relationModel(2)->rowCount(), 2);
{
QSqlQuery q(db);
QVERIFY_SQL(q, exec("insert into " + reltest2 + " values(3, 'mrs')"));
model.relationModel(2)->select();
}
- QVERIFY(model.relationModel(2)->rowCount() == 3);
+ QCOMPARE(model.relationModel(2)->rowCount(), 3);
QVERIFY(model.setData(model.index(0,2), 3));
QVERIFY(model.submitAll());
QCOMPARE(model.data(model.index(0,2)), QVariant("mrs"));
diff --git a/tests/auto/sql/models/qsqltablemodel/tst_qsqltablemodel.cpp b/tests/auto/sql/models/qsqltablemodel/tst_qsqltablemodel.cpp
index 9c351f4657..2ace79973b 100644
--- a/tests/auto/sql/models/qsqltablemodel/tst_qsqltablemodel.cpp
+++ b/tests/auto/sql/models/qsqltablemodel/tst_qsqltablemodel.cpp
@@ -533,7 +533,7 @@ void tst_QSqlTableModel::setData()
idx = model.index(0, 0);
QVERIFY_SQL(model, setData(idx, QVariant(QVariant::Int)));
val = model.data(idx);
- QVERIFY(val == QVariant(QVariant::Int));
+ QCOMPARE(val, QVariant(QVariant::Int));
QVERIFY(val.isNull());
QVERIFY_SQL(model, isDirty(idx));
QVERIFY_SQL(model, submitAll());
@@ -560,13 +560,13 @@ void tst_QSqlTableModel::setData()
// initial state
idx = model.index(0, 0);
QSqlRecord rec = model.record(0);
- QVERIFY(rec.value(0) == QVariant(QVariant::Int));
+ QCOMPARE(rec.value(0), QVariant(QVariant::Int));
QVERIFY(rec.isNull(0));
QVERIFY(!rec.isGenerated(0));
// unchanged value, but causes column to be included in INSERT
QVERIFY_SQL(model, setData(idx, QVariant(QVariant::Int)));
rec = model.record(0);
- QVERIFY(rec.value(0) == QVariant(QVariant::Int));
+ QCOMPARE(rec.value(0), QVariant(QVariant::Int));
QVERIFY(rec.isNull(0));
QVERIFY(rec.isGenerated(0));
QVERIFY_SQL(model, submitAll());
@@ -1136,8 +1136,8 @@ void tst_QSqlTableModel::removeRows()
QVERIFY_SQL(model, removeRows(0, 1));
QVERIFY_SQL(model, removeRows(1, 1));
QCOMPARE(beforeDeleteSpy.count(), 2);
- QVERIFY(beforeDeleteSpy.at(0).at(0).toInt() == 0);
- QVERIFY(beforeDeleteSpy.at(1).at(0).toInt() == 1);
+ QCOMPARE(beforeDeleteSpy.at(0).at(0).toInt(), 0);
+ QCOMPARE(beforeDeleteSpy.at(1).at(0).toInt(), 1);
// deleted rows shown as empty until select
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.data(model.index(0, 1)).toString(), QString(""));
@@ -1172,11 +1172,11 @@ void tst_QSqlTableModel::removeRows()
QCOMPARE(headerDataChangedSpy.at(1).at(1).toInt(), 0);
QCOMPARE(headerDataChangedSpy.at(1).at(2).toInt(), 0);
QCOMPARE(model.rowCount(), 3);
- QVERIFY(beforeDeleteSpy.count() == 0);
+ QCOMPARE(beforeDeleteSpy.count(), 0);
QVERIFY(model.submitAll());
- QVERIFY(beforeDeleteSpy.count() == 2);
- QVERIFY(beforeDeleteSpy.at(0).at(0).toInt() == 0);
- QVERIFY(beforeDeleteSpy.at(1).at(0).toInt() == 1);
+ QCOMPARE(beforeDeleteSpy.count(), 2);
+ QCOMPARE(beforeDeleteSpy.at(0).at(0).toInt(), 0);
+ QCOMPARE(beforeDeleteSpy.at(1).at(0).toInt(), 1);
QCOMPARE(model.rowCount(), 1);
QCOMPARE(model.data(model.index(0, 1)).toString(), QString("vohi"));
}
diff --git a/tests/auto/testlib/selftests/cmptest/tst_cmptest.cpp b/tests/auto/testlib/selftests/cmptest/tst_cmptest.cpp
index 6b94dfb529..6446fec510 100644
--- a/tests/auto/testlib/selftests/cmptest/tst_cmptest.cpp
+++ b/tests/auto/testlib/selftests/cmptest/tst_cmptest.cpp
@@ -124,6 +124,8 @@ class tst_Cmptest: public QObject
Q_OBJECT
private slots:
+ void compare_unregistered_enums();
+ void compare_registered_enums();
void compare_boolfuncs();
void compare_pointerfuncs();
void compare_tostring();
@@ -138,8 +140,26 @@ private slots:
void compareQImages();
void compareQImages_data();
#endif
+ void verify();
+ void verify2();
+ void tryVerify();
+ void tryVerify2();
};
+enum MyUnregisteredEnum { MyUnregisteredEnumValue1, MyUnregisteredEnumValue2 };
+
+void tst_Cmptest::compare_unregistered_enums()
+{
+ QCOMPARE(MyUnregisteredEnumValue1, MyUnregisteredEnumValue1);
+ QCOMPARE(MyUnregisteredEnumValue1, MyUnregisteredEnumValue2);
+}
+
+void tst_Cmptest::compare_registered_enums()
+{
+ QCOMPARE(Qt::ArrowCursor, Qt::ArrowCursor);
+ QCOMPARE(Qt::ArrowCursor, Qt::BusyCursor);
+}
+
static bool boolfunc() { return true; }
static bool boolfunc2() { return true; }
@@ -371,7 +391,36 @@ void tst_Cmptest::compareQImages()
QCOMPARE(opA, opB);
}
-#endif
+#endif // QT_GUI_LIB
+
+static int opaqueFunc()
+{
+ return 42;
+}
+
+void tst_Cmptest::verify()
+{
+ QVERIFY(opaqueFunc() > 2);
+ QVERIFY(opaqueFunc() < 2);
+}
+
+void tst_Cmptest::verify2()
+{
+ QVERIFY2(opaqueFunc() > 2, QByteArray::number(opaqueFunc()).constData());
+ QVERIFY2(opaqueFunc() < 2, QByteArray::number(opaqueFunc()).constData());
+}
+
+void tst_Cmptest::tryVerify()
+{
+ QTRY_VERIFY(opaqueFunc() > 2);
+ QTRY_VERIFY_WITH_TIMEOUT(opaqueFunc() < 2, 1);
+}
+
+void tst_Cmptest::tryVerify2()
+{
+ QTRY_VERIFY2(opaqueFunc() > 2, QByteArray::number(opaqueFunc()).constData());
+ QTRY_VERIFY2_WITH_TIMEOUT(opaqueFunc() < 2, QByteArray::number(opaqueFunc()).constData(), 1);
+}
QTEST_MAIN(tst_Cmptest)
#include "tst_cmptest.moc"
diff --git a/tests/auto/testlib/selftests/expected_cmptest.lightxml b/tests/auto/testlib/selftests/expected_cmptest.lightxml
index 4a376b5c8b..36929cec6b 100644
--- a/tests/auto/testlib/selftests/expected_cmptest.lightxml
+++ b/tests/auto/testlib/selftests/expected_cmptest.lightxml
@@ -5,18 +5,32 @@
</Environment>
<TestFunction name="initTestCase">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="compare_unregistered_enums">
+<Incident type="fail" file="tst_cmptest.cpp" line="154">
+ <Description><![CDATA[Compared values are not the same]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="compare_registered_enums">
+<Incident type="fail" file="tst_cmptest.cpp" line="160">
+ <Description><![CDATA[Compared values are not the same
+ Actual (Qt::ArrowCursor): ArrowCursor
+ Expected (Qt::BusyCursor) : BusyCursor]]></Description>
+</Incident>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_boolfuncs">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_pointerfuncs">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_tostring">
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[int, string]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(int,123)
@@ -25,25 +39,25 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both invalid]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[null hash, invalid]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(QVariantHash)
Expected (expected): QVariant()]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[string, null user type]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(QString,A simple string)
Expected (expected): QVariant(PhonyClass)]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[both non-null user type]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(PhonyClass,<value not representable as string>)
Expected (expected): QVariant(PhonyClass,<value not representable as string>)]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQStringLists">
<Incident type="pass" file="" line="0">
@@ -52,65 +66,65 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal lists]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[last item different]]></DataTag>
<Description><![CDATA[Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[second-last item different]]></DataTag>
<Description><![CDATA[Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[prefix]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 2
Expected (opB) size: 1]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[short list second]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 12
Expected (opB) size: 1]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[short list first]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 1
Expected (opB) size: 12]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQListInt">
-<Incident type="fail" file="tst_cmptest.cpp" line="320">
+<Incident type="fail" file="tst_cmptest.cpp" line="332">
<Description><![CDATA[Compared lists differ at index 2.
Actual (int1): 3
Expected (int2): 4]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQListDouble">
-<Incident type="fail" file="tst_cmptest.cpp" line="327">
+<Incident type="fail" file="tst_cmptest.cpp" line="339">
<Description><![CDATA[Compared lists differ at index 0.
Actual (double1): 1.5
Expected (double2): 1]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQPixmaps">
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both null]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[one null]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[other null]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ.
Actual (opA).isNull(): 0
@@ -119,29 +133,29 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[different size]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ in size.
Actual (opA): 11x20
Expected (opB): 20x20]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[different pixels]]></DataTag>
<Description><![CDATA[Compared values are not the same]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQImages">
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both null]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[one null]]></DataTag>
<Description><![CDATA[Compared QImages differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[other null]]></DataTag>
<Description><![CDATA[Compared QImages differ.
Actual (opA).isNull(): 0
@@ -150,26 +164,50 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different size]]></DataTag>
<Description><![CDATA[Compared QImages differ in size.
Actual (opA): 11x20
Expected (opB): 20x20]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different format]]></DataTag>
<Description><![CDATA[Compared QImages differ in format.
Actual (opA): 6
Expected (opB): 3]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different pixels]]></DataTag>
<Description><![CDATA[Compared values are not the same]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="verify">
+<Incident type="fail" file="tst_cmptest.cpp" line="404">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. ()]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="verify2">
+<Incident type="fail" file="tst_cmptest.cpp" line="410">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. (42)]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="tryVerify">
+<Incident type="fail" file="tst_cmptest.cpp" line="416">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. ()]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="tryVerify2">
+<Incident type="fail" file="tst_cmptest.cpp" line="422">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. (42)]]></Description>
+</Incident>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="cleanupTestCase">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<Duration msecs="0"/>
diff --git a/tests/auto/testlib/selftests/expected_cmptest.txt b/tests/auto/testlib/selftests/expected_cmptest.txt
index 9e8c56ed99..70c54704f9 100644
--- a/tests/auto/testlib/selftests/expected_cmptest.txt
+++ b/tests/auto/testlib/selftests/expected_cmptest.txt
@@ -1,91 +1,105 @@
********* Start testing of tst_Cmptest *********
-Config: Using QtTest library @INSERT_QT_VERSION_HERE@, Qt @INSERT_QT_VERSION_HERE@
+Config: Using QtTest library
PASS : tst_Cmptest::initTestCase()
+FAIL! : tst_Cmptest::compare_unregistered_enums() Compared values are not the same
+ Loc: [tst_cmptest.cpp(154)]
+FAIL! : tst_Cmptest::compare_registered_enums() Compared values are not the same
+ Actual (Qt::ArrowCursor): ArrowCursor
+ Expected (Qt::BusyCursor) : BusyCursor
+ Loc: [tst_cmptest.cpp(160)]
PASS : tst_Cmptest::compare_boolfuncs()
PASS : tst_Cmptest::compare_pointerfuncs()
FAIL! : tst_Cmptest::compare_tostring(int, string) Compared values are not the same
Actual (actual) : QVariant(int,123)
Expected (expected): QVariant(QString,hi)
- Loc: [tst_cmptest.cpp(219)]
+ Loc: [tst_cmptest.cpp(231)]
PASS : tst_Cmptest::compare_tostring(both invalid)
FAIL! : tst_Cmptest::compare_tostring(null hash, invalid) Compared values are not the same
Actual (actual) : QVariant(QVariantHash)
Expected (expected): QVariant()
- Loc: [tst_cmptest.cpp(219)]
+ Loc: [tst_cmptest.cpp(231)]
FAIL! : tst_Cmptest::compare_tostring(string, null user type) Compared values are not the same
Actual (actual) : QVariant(QString,A simple string)
Expected (expected): QVariant(PhonyClass)
- Loc: [tst_cmptest.cpp(219)]
+ Loc: [tst_cmptest.cpp(231)]
FAIL! : tst_Cmptest::compare_tostring(both non-null user type) Compared values are not the same
Actual (actual) : QVariant(PhonyClass,<value not representable as string>)
Expected (expected): QVariant(PhonyClass,<value not representable as string>)
- Loc: [tst_cmptest.cpp(219)]
+ Loc: [tst_cmptest.cpp(231)]
PASS : tst_Cmptest::compareQStringLists(empty lists)
PASS : tst_Cmptest::compareQStringLists(equal lists)
FAIL! : tst_Cmptest::compareQStringLists(last item different) Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"
- Loc: [tst_cmptest.cpp(313)]
+ Loc: [tst_cmptest.cpp(325)]
FAIL! : tst_Cmptest::compareQStringLists(second-last item different) Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"
- Loc: [tst_cmptest.cpp(313)]
+ Loc: [tst_cmptest.cpp(325)]
FAIL! : tst_Cmptest::compareQStringLists(prefix) Compared lists have different sizes.
Actual (opA) size: 2
Expected (opB) size: 1
- Loc: [tst_cmptest.cpp(313)]
+ Loc: [tst_cmptest.cpp(325)]
FAIL! : tst_Cmptest::compareQStringLists(short list second) Compared lists have different sizes.
Actual (opA) size: 12
Expected (opB) size: 1
- Loc: [tst_cmptest.cpp(313)]
+ Loc: [tst_cmptest.cpp(325)]
FAIL! : tst_Cmptest::compareQStringLists(short list first) Compared lists have different sizes.
Actual (opA) size: 1
Expected (opB) size: 12
- Loc: [tst_cmptest.cpp(313)]
+ Loc: [tst_cmptest.cpp(325)]
FAIL! : tst_Cmptest::compareQListInt() Compared lists differ at index 2.
Actual (int1): 3
Expected (int2): 4
- Loc: [tst_cmptest.cpp(320)]
+ Loc: [tst_cmptest.cpp(332)]
FAIL! : tst_Cmptest::compareQListDouble() Compared lists differ at index 0.
Actual (double1): 1.5
Expected (double2): 1
- Loc: [tst_cmptest.cpp(327)]
+ Loc: [tst_cmptest.cpp(339)]
PASS : tst_Cmptest::compareQPixmaps(both null)
FAIL! : tst_Cmptest::compareQPixmaps(one null) Compared QPixmaps differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0
- Loc: [tst_cmptest.cpp(353)]
+ Loc: [tst_cmptest.cpp(365)]
FAIL! : tst_Cmptest::compareQPixmaps(other null) Compared QPixmaps differ.
Actual (opA).isNull(): 0
Expected (opB).isNull(): 1
- Loc: [tst_cmptest.cpp(353)]
+ Loc: [tst_cmptest.cpp(365)]
PASS : tst_Cmptest::compareQPixmaps(equal)
FAIL! : tst_Cmptest::compareQPixmaps(different size) Compared QPixmaps differ in size.
Actual (opA): 11x20
Expected (opB): 20x20
- Loc: [tst_cmptest.cpp(353)]
+ Loc: [tst_cmptest.cpp(365)]
FAIL! : tst_Cmptest::compareQPixmaps(different pixels) Compared values are not the same
- Loc: [tst_cmptest.cpp(353)]
+ Loc: [tst_cmptest.cpp(365)]
PASS : tst_Cmptest::compareQImages(both null)
FAIL! : tst_Cmptest::compareQImages(one null) Compared QImages differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0
- Loc: [tst_cmptest.cpp(380)]
+ Loc: [tst_cmptest.cpp(392)]
FAIL! : tst_Cmptest::compareQImages(other null) Compared QImages differ.
Actual (opA).isNull(): 0
Expected (opB).isNull(): 1
- Loc: [tst_cmptest.cpp(380)]
+ Loc: [tst_cmptest.cpp(392)]
PASS : tst_Cmptest::compareQImages(equal)
FAIL! : tst_Cmptest::compareQImages(different size) Compared QImages differ in size.
Actual (opA): 11x20
Expected (opB): 20x20
- Loc: [tst_cmptest.cpp(380)]
+ Loc: [tst_cmptest.cpp(392)]
FAIL! : tst_Cmptest::compareQImages(different format) Compared QImages differ in format.
Actual (opA): 6
Expected (opB): 3
- Loc: [tst_cmptest.cpp(380)]
+ Loc: [tst_cmptest.cpp(392)]
FAIL! : tst_Cmptest::compareQImages(different pixels) Compared values are not the same
- Loc: [tst_cmptest.cpp(380)]
+ Loc: [tst_cmptest.cpp(392)]
+FAIL! : tst_Cmptest::verify() 'opaqueFunc() < 2' returned FALSE. ()
+ Loc: [tst_cmptest.cpp(404)]
+FAIL! : tst_Cmptest::verify2() 'opaqueFunc() < 2' returned FALSE. (42)
+ Loc: [tst_cmptest.cpp(410)]
+FAIL! : tst_Cmptest::tryVerify() 'opaqueFunc() < 2' returned FALSE. ()
+ Loc: [tst_cmptest.cpp(416)]
+FAIL! : tst_Cmptest::tryVerify2() 'opaqueFunc() < 2' returned FALSE. (42)
+ Loc: [tst_cmptest.cpp(422)]
PASS : tst_Cmptest::cleanupTestCase()
-Totals: 11 passed, 20 failed, 0 skipped, 0 blacklisted
+Totals: 11 passed, 26 failed, 0 skipped, 0 blacklisted
********* Finished testing of tst_Cmptest *********
diff --git a/tests/auto/testlib/selftests/expected_cmptest.xml b/tests/auto/testlib/selftests/expected_cmptest.xml
index aefb1b5f4c..9437e8e4b7 100644
--- a/tests/auto/testlib/selftests/expected_cmptest.xml
+++ b/tests/auto/testlib/selftests/expected_cmptest.xml
@@ -7,18 +7,32 @@
</Environment>
<TestFunction name="initTestCase">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="compare_unregistered_enums">
+<Incident type="fail" file="tst_cmptest.cpp" line="154">
+ <Description><![CDATA[Compared values are not the same]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="compare_registered_enums">
+<Incident type="fail" file="tst_cmptest.cpp" line="160">
+ <Description><![CDATA[Compared values are not the same
+ Actual (Qt::ArrowCursor): ArrowCursor
+ Expected (Qt::BusyCursor) : BusyCursor]]></Description>
+</Incident>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_boolfuncs">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_pointerfuncs">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compare_tostring">
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[int, string]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(int,123)
@@ -27,25 +41,25 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both invalid]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[null hash, invalid]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(QVariantHash)
Expected (expected): QVariant()]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[string, null user type]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(QString,A simple string)
Expected (expected): QVariant(PhonyClass)]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="219">
+<Incident type="fail" file="tst_cmptest.cpp" line="231">
<DataTag><![CDATA[both non-null user type]]></DataTag>
<Description><![CDATA[Compared values are not the same
Actual (actual) : QVariant(PhonyClass,<value not representable as string>)
Expected (expected): QVariant(PhonyClass,<value not representable as string>)]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQStringLists">
<Incident type="pass" file="" line="0">
@@ -54,65 +68,65 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal lists]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[last item different]]></DataTag>
<Description><![CDATA[Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[second-last item different]]></DataTag>
<Description><![CDATA[Compared lists differ at index 2.
Actual (opA): "string3"
Expected (opB): "DIFFERS"]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[prefix]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 2
Expected (opB) size: 1]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[short list second]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 12
Expected (opB) size: 1]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="313">
+<Incident type="fail" file="tst_cmptest.cpp" line="325">
<DataTag><![CDATA[short list first]]></DataTag>
<Description><![CDATA[Compared lists have different sizes.
Actual (opA) size: 1
Expected (opB) size: 12]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQListInt">
-<Incident type="fail" file="tst_cmptest.cpp" line="320">
+<Incident type="fail" file="tst_cmptest.cpp" line="332">
<Description><![CDATA[Compared lists differ at index 2.
Actual (int1): 3
Expected (int2): 4]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQListDouble">
-<Incident type="fail" file="tst_cmptest.cpp" line="327">
+<Incident type="fail" file="tst_cmptest.cpp" line="339">
<Description><![CDATA[Compared lists differ at index 0.
Actual (double1): 1.5
Expected (double2): 1]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQPixmaps">
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both null]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[one null]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[other null]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ.
Actual (opA).isNull(): 0
@@ -121,29 +135,29 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[different size]]></DataTag>
<Description><![CDATA[Compared QPixmaps differ in size.
Actual (opA): 11x20
Expected (opB): 20x20]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="353">
+<Incident type="fail" file="tst_cmptest.cpp" line="365">
<DataTag><![CDATA[different pixels]]></DataTag>
<Description><![CDATA[Compared values are not the same]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="compareQImages">
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[both null]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[one null]]></DataTag>
<Description><![CDATA[Compared QImages differ.
Actual (opA).isNull(): 1
Expected (opB).isNull(): 0]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[other null]]></DataTag>
<Description><![CDATA[Compared QImages differ.
Actual (opA).isNull(): 0
@@ -152,27 +166,51 @@
<Incident type="pass" file="" line="0">
<DataTag><![CDATA[equal]]></DataTag>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different size]]></DataTag>
<Description><![CDATA[Compared QImages differ in size.
Actual (opA): 11x20
Expected (opB): 20x20]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different format]]></DataTag>
<Description><![CDATA[Compared QImages differ in format.
Actual (opA): 6
Expected (opB): 3]]></Description>
</Incident>
-<Incident type="fail" file="tst_cmptest.cpp" line="380">
+<Incident type="fail" file="tst_cmptest.cpp" line="392">
<DataTag><![CDATA[different pixels]]></DataTag>
<Description><![CDATA[Compared values are not the same]]></Description>
</Incident>
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="verify">
+<Incident type="fail" file="tst_cmptest.cpp" line="404">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. ()]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="verify2">
+<Incident type="fail" file="tst_cmptest.cpp" line="410">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. (42)]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="tryVerify">
+<Incident type="fail" file="tst_cmptest.cpp" line="416">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. ()]]></Description>
+</Incident>
+ <Duration msecs="0"/>
+</TestFunction>
+<TestFunction name="tryVerify2">
+<Incident type="fail" file="tst_cmptest.cpp" line="422">
+ <Description><![CDATA['opaqueFunc() < 2' returned FALSE. (42)]]></Description>
+</Incident>
+ <Duration msecs="0"/>
</TestFunction>
<TestFunction name="cleanupTestCase">
<Incident type="pass" file="" line="0" />
-<Duration msecs="0"/>
+ <Duration msecs="0"/>
</TestFunction>
<Duration msecs="0"/>
</TestCase>
diff --git a/tests/auto/testlib/selftests/expected_cmptest.xunitxml b/tests/auto/testlib/selftests/expected_cmptest.xunitxml
index 7502d3cc54..fa970d4172 100644
--- a/tests/auto/testlib/selftests/expected_cmptest.xunitxml
+++ b/tests/auto/testlib/selftests/expected_cmptest.xunitxml
@@ -1,11 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<testsuite errors="0" failures="20" tests="10" name="tst_Cmptest">
+<testsuite errors="0" failures="26" tests="16" name="tst_Cmptest">
<properties>
<property value="@INSERT_QT_VERSION_HERE@" name="QTestVersion"/>
<property value="@INSERT_QT_VERSION_HERE@" name="QtVersion"/>
<property value="" name="QtBuild"/>
</properties>
<testcase result="pass" name="initTestCase"/>
+ <testcase result="fail" name="compare_unregistered_enums">
+ <failure message="Compared values are not the same" result="fail"/>
+ </testcase>
+ <testcase result="fail" name="compare_registered_enums">
+ <failure message="Compared values are not the same
+ Actual (Qt::ArrowCursor): ArrowCursor
+ Expected (Qt::BusyCursor) : BusyCursor" result="fail"/>
+ </testcase>
<testcase result="pass" name="compare_boolfuncs"/>
<testcase result="pass" name="compare_pointerfuncs"/>
<testcase result="fail" name="compare_tostring">
@@ -76,6 +84,18 @@
Expected (opB): 3" result="fail"/>
<failure tag="different pixels" message="Compared values are not the same" result="fail"/>
</testcase>
+ <testcase result="fail" name="verify">
+ <failure message="&apos;opaqueFunc() &lt; 2&apos; returned FALSE. ()" result="fail"/>
+ </testcase>
+ <testcase result="fail" name="verify2">
+ <failure message="&apos;opaqueFunc() &lt; 2&apos; returned FALSE. (42)" result="fail"/>
+ </testcase>
+ <testcase result="fail" name="tryVerify">
+ <failure message="&apos;opaqueFunc() &lt; 2&apos; returned FALSE. ()" result="fail"/>
+ </testcase>
+ <testcase result="fail" name="tryVerify2">
+ <failure message="&apos;opaqueFunc() &lt; 2&apos; returned FALSE. (42)" result="fail"/>
+ </testcase>
<testcase result="pass" name="cleanupTestCase"/>
<system-err/>
</testsuite>
diff --git a/tests/auto/testlib/selftests/tst_selftests.cpp b/tests/auto/testlib/selftests/tst_selftests.cpp
index 6536f103ac..9b76bca28c 100644
--- a/tests/auto/testlib/selftests/tst_selftests.cpp
+++ b/tests/auto/testlib/selftests/tst_selftests.cpp
@@ -571,7 +571,9 @@ void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& logge
#endif
QProcess proc;
- static const QProcessEnvironment environment = processEnvironment();
+ QProcessEnvironment environment = processEnvironment();
+ if (crashes)
+ environment.insert("QTEST_DISABLE_STACK_DUMP", "1");
proc.setProcessEnvironment(environment);
const QString path = subdir + QLatin1Char('/') + subdir;
proc.start(path, arguments);
@@ -626,8 +628,8 @@ void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& logge
QList<QByteArray> res = splitLines(actualOutputs[n]);
const QString expectedFileName = expectedFileNameFromTest(subdir, logger);
QList<QByteArray> exp = expectedResult(expectedFileName);
-#if defined (Q_CC_MSVC) || defined(Q_CC_MINGW)
- // MSVC, MinGW format double numbers differently
+#if (defined (Q_CC_MSVC) && _MSC_VER < 1900)|| defined(Q_CC_MINGW)
+ // MSVC up to MSVC2013, MinGW format double numbers differently
if (n == 0 && subdir == QStringLiteral("float")) {
for (int i = 0; i < exp.size(); ++i) {
exp[i].replace("e-07", "e-007");
diff --git a/tests/auto/tools/moc/tst_moc.cpp b/tests/auto/tools/moc/tst_moc.cpp
index 350c6142d2..fa1b68b4f9 100644
--- a/tests/auto/tools/moc/tst_moc.cpp
+++ b/tests/auto/tools/moc/tst_moc.cpp
@@ -880,7 +880,7 @@ void tst_Moc::preprocessorConditionals()
QVERIFY(mobj->indexOfSignal("signalInIf1()") != -1);
QVERIFY(mobj->indexOfSignal("signalInIf2()") != -1);
QVERIFY(mobj->indexOfSignal("signalInIf3()") != -1);
- QVERIFY(mobj->indexOfSignal("doNotExist()") == -1);
+ QCOMPARE(mobj->indexOfSignal("doNotExist()"), -1);
}
void tst_Moc::blackslashNewlines()
@@ -888,7 +888,7 @@ void tst_Moc::blackslashNewlines()
BackslashNewlines tst;
const QMetaObject *mobj = tst.metaObject();
QVERIFY(mobj->indexOfSlot("works()") != -1);
- QVERIFY(mobj->indexOfSlot("buggy()") == -1);
+ QCOMPARE(mobj->indexOfSlot("buggy()"), -1);
}
void tst_Moc::slotWithSillyConst()
@@ -928,8 +928,8 @@ void tst_Moc::testExtraDataForEnum()
const QMetaObject * const *objects = mobjUser->d.relatedMetaObjects;
QVERIFY(objects);
- QVERIFY(objects[0] == mobjSource);
- QVERIFY(objects[1] == 0);
+ QCOMPARE(objects[0], mobjSource);
+ QVERIFY(!objects[1]);
}
void tst_Moc::namespaceTypeProperty()
@@ -982,7 +982,7 @@ void tst_Moc::namespacedFlags()
const QVariant v = bar.property("flags");
QVERIFY(v.isValid());
QVERIFY(baz.setProperty("flags", v));
- QVERIFY(baz.flags() == bar.flags());
+ QCOMPARE(baz.flags(), bar.flags());
QList<Foo::Bar::Flags> l;
l << baz.flags();
@@ -1104,7 +1104,7 @@ void tst_Moc::winNewline()
if (data.at(i) == QLatin1Char('\r')) {
QVERIFY(i < data.count() - 1);
++i;
- QVERIFY(data.at(i) == '\n');
+ QCOMPARE(data.at(i), '\n');
} else {
QVERIFY(data.at(i) != '\n');
}
@@ -1255,14 +1255,14 @@ void tst_Moc::invokable()
{
const QMetaObject &mobj = InvokableBeforeReturnType::staticMetaObject;
QCOMPARE(mobj.methodCount(), 6);
- QVERIFY(mobj.method(5).methodSignature() == QByteArray("foo()"));
+ QCOMPARE(mobj.method(5).methodSignature(), QByteArray("foo()"));
}
{
const QMetaObject &mobj = InvokableBeforeInline::staticMetaObject;
QCOMPARE(mobj.methodCount(), 7);
- QVERIFY(mobj.method(5).methodSignature() == QByteArray("foo()"));
- QVERIFY(mobj.method(6).methodSignature() == QByteArray("bar()"));
+ QCOMPARE(mobj.method(5).methodSignature(), QByteArray("foo()"));
+ QCOMPARE(mobj.method(6).methodSignature(), QByteArray("bar()"));
}
}
@@ -1271,22 +1271,22 @@ void tst_Moc::singleFunctionKeywordSignalAndSlot()
{
const QMetaObject &mobj = SingleFunctionKeywordBeforeReturnType::staticMetaObject;
QCOMPARE(mobj.methodCount(), 7);
- QVERIFY(mobj.method(5).methodSignature() == QByteArray("mySignal()"));
- QVERIFY(mobj.method(6).methodSignature() == QByteArray("mySlot()"));
+ QCOMPARE(mobj.method(5).methodSignature(), QByteArray("mySignal()"));
+ QCOMPARE(mobj.method(6).methodSignature(), QByteArray("mySlot()"));
}
{
const QMetaObject &mobj = SingleFunctionKeywordBeforeInline::staticMetaObject;
QCOMPARE(mobj.methodCount(), 7);
- QVERIFY(mobj.method(5).methodSignature() == QByteArray("mySignal()"));
- QVERIFY(mobj.method(6).methodSignature() == QByteArray("mySlot()"));
+ QCOMPARE(mobj.method(5).methodSignature(), QByteArray("mySignal()"));
+ QCOMPARE(mobj.method(6).methodSignature(), QByteArray("mySlot()"));
}
{
const QMetaObject &mobj = SingleFunctionKeywordAfterInline::staticMetaObject;
QCOMPARE(mobj.methodCount(), 7);
- QVERIFY(mobj.method(5).methodSignature() == QByteArray("mySignal()"));
- QVERIFY(mobj.method(6).methodSignature() == QByteArray("mySlot()"));
+ QCOMPARE(mobj.method(5).methodSignature(), QByteArray("mySignal()"));
+ QCOMPARE(mobj.method(6).methodSignature(), QByteArray("mySlot()"));
}
}
@@ -1740,34 +1740,34 @@ template <class T>
void tst_Moc::revisions_T()
{
int idx = T::staticMetaObject.indexOfProperty("prop1");
- QVERIFY(T::staticMetaObject.property(idx).revision() == 0);
+ QCOMPARE(T::staticMetaObject.property(idx).revision(), 0);
idx = T::staticMetaObject.indexOfProperty("prop2");
- QVERIFY(T::staticMetaObject.property(idx).revision() == 2);
+ QCOMPARE(T::staticMetaObject.property(idx).revision(), 2);
idx = T::staticMetaObject.indexOfMethod("method1()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 0);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 0);
idx = T::staticMetaObject.indexOfMethod("method2()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 4);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 4);
idx = T::staticMetaObject.indexOfSlot("slot1()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 0);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 0);
idx = T::staticMetaObject.indexOfSlot("slot2()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 3);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 3);
idx = T::staticMetaObject.indexOfSlot("slot3()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 6);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 6);
idx = T::staticMetaObject.indexOfSlot("slot4()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 6);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 6);
idx = T::staticMetaObject.indexOfSignal("signal1()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 0);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 0);
idx = T::staticMetaObject.indexOfSignal("signal2()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 5);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 5);
idx = T::staticMetaObject.indexOfSignal("signal3()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 7);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 7);
idx = T::staticMetaObject.indexOfSignal("signal4()");
- QVERIFY(T::staticMetaObject.method(idx).revision() == 7);
+ QCOMPARE(T::staticMetaObject.method(idx).revision(), 7);
idx = T::staticMetaObject.indexOfEnumerator("TestEnum");
QCOMPARE(T::staticMetaObject.enumerator(idx).keyCount(), 2);
@@ -1947,7 +1947,7 @@ public:
void tst_Moc::privateClass()
{
- QVERIFY(PrivateClass::staticMetaObject.indexOfConstructor("PrivateClass()") == 0);
+ QCOMPARE(PrivateClass::staticMetaObject.indexOfConstructor("PrivateClass()"), 0);
QVERIFY(PrivateClass::staticMetaObject.indexOfSignal("someSignal()") > 0);
}
@@ -3068,7 +3068,7 @@ void tst_Moc::parseDefines()
int index = mo->indexOfSlot("stringMethod()");
QVERIFY(index != -1);
- QVERIFY(mo->method(index).returnType() == QMetaType::QString);
+ QCOMPARE(mo->method(index).returnType(), int(QMetaType::QString));
index = mo->indexOfSlot("combined1()");
QVERIFY(index != -1);
@@ -3127,7 +3127,7 @@ void tst_Moc::parseDefines()
QVERIFY(!qstrcmp(mci.value(), "TestValue"));
}
}
- QVERIFY(count == 3);
+ QCOMPARE(count, 3);
index = mo->indexOfSlot("PD_DEFINE_ITSELF_SUFFIX(int)");
QVERIFY(index != -1);
@@ -3253,7 +3253,7 @@ void tst_Moc::relatedMetaObjectsWithinNamespaces()
const QMetaObject *testMo = &QTBUG_2151::B::staticMetaObject;
QVERIFY(testMo->d.relatedMetaObjects);
- QVERIFY(testMo->d.relatedMetaObjects[0] == relatedMo);
+ QCOMPARE(testMo->d.relatedMetaObjects[0], relatedMo);
}
void tst_Moc::relatedMetaObjectsInGadget()
@@ -3262,7 +3262,7 @@ void tst_Moc::relatedMetaObjectsInGadget()
const QMetaObject *testMo = &QTBUG_35657::B::staticMetaObject;
QVERIFY(testMo->d.relatedMetaObjects);
- QVERIFY(testMo->d.relatedMetaObjects[0] == relatedMo);
+ QCOMPARE(testMo->d.relatedMetaObjects[0], relatedMo);
}
void tst_Moc::relatedMetaObjectsNameConflict_data()
diff --git a/tests/auto/tools/qmake/qmake.pro b/tests/auto/tools/qmake/qmake.pro
index 5ed3073e20..d0817247db 100644
--- a/tests/auto/tools/qmake/qmake.pro
+++ b/tests/auto/tools/qmake/qmake.pro
@@ -8,5 +8,11 @@ SOURCES += tst_qmake.cpp testcompiler.cpp
QT = core testlib
cross_compile: DEFINES += QMAKE_CROSS_COMPILED
+debug_and_release {
+ CONFIG(debug, debug|release): \
+ DEFINES += DEBUG_BUILD
+ else: \
+ DEFINES += RELEASE_BUILD
+}
TESTDATA += testdata/*
diff --git a/tests/auto/widgets/kernel/qapplication/wincmdline/main.cpp b/tests/auto/tools/qmake/testdata/resources/main.cpp
index 2d86b46875..78f9814396 100644
--- a/tests/auto/widgets/kernel/qapplication/wincmdline/main.cpp
+++ b/tests/auto/tools/qmake/testdata/resources/main.cpp
@@ -30,17 +30,13 @@
** $QT_END_LICENSE$
**
****************************************************************************/
-#include <QApplication>
-#include <stdio.h>
-int main(int argc, char *argv[])
+
+
+#include <qguiapplication.h>
+
+int main( int argc, char **argv )
{
- QApplication app(argc, argv);
- if (argc > 1)
- fprintf(stderr, "%s", argv[1]);
- else
- fprintf(stderr, "Failed");
- fflush(stderr);
- return 0;
+ QGuiApplication a( argc, argv );
+ return a.exec();
}
-
diff --git a/tests/auto/tools/qmake/testdata/resources/resources.pro b/tests/auto/tools/qmake/testdata/resources/resources.pro
new file mode 100644
index 0000000000..f024fe5617
--- /dev/null
+++ b/tests/auto/tools/qmake/testdata/resources/resources.pro
@@ -0,0 +1,10 @@
+TEMPLATE = app
+SOURCES = main.cpp
+
+pro_file.files = resources.pro
+pro_file.prefix = /prefix
+
+subdir.files = subdir/file.txt
+subdir.base = subdir
+
+RESOURCES = test.qrc main.cpp pro_file subdir
diff --git a/tests/auto/tools/qmake/testdata/resources/subdir/file.txt b/tests/auto/tools/qmake/testdata/resources/subdir/file.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/auto/tools/qmake/testdata/resources/subdir/file.txt
diff --git a/tests/auto/tools/qmake/testdata/resources/test.qrc b/tests/auto/tools/qmake/testdata/resources/test.qrc
new file mode 100644
index 0000000000..decde3dd24
--- /dev/null
+++ b/tests/auto/tools/qmake/testdata/resources/test.qrc
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/">
+ <file>test.qrc</file>
+ </qresource>
+</RCC>
diff --git a/tests/auto/tools/qmake/tst_qmake.cpp b/tests/auto/tools/qmake/tst_qmake.cpp
index da5314c83b..ac94d1a2b9 100644
--- a/tests/auto/tools/qmake/tst_qmake.cpp
+++ b/tests/auto/tools/qmake/tst_qmake.cpp
@@ -39,6 +39,14 @@
#include <QStandardPaths>
#include <QDir>
+#if defined(DEBUG_BUILD)
+# define DIR_INFIX "debug/"
+#elif defined(RELEASE_BUILD)
+# define DIR_INFIX "release/"
+#else
+# define DIR_INFIX ""
+#endif
+
class tst_qmake : public QObject
{
Q_OBJECT
@@ -77,6 +85,7 @@ private slots:
void substitutes();
void project();
void proFileCache();
+ void resources();
private:
TestCompiler test_compiler;
@@ -490,5 +499,38 @@ void tst_qmake::proFileCache()
QVERIFY( test_compiler.qmake( workDir, "pro_file_cache" ));
}
+void tst_qmake::resources()
+{
+ QString workDir = base_path + "/testdata/resources";
+ QVERIFY(test_compiler.qmake(workDir, "resources"));
+
+ {
+ QFile qrcFile(workDir + "/.rcc/" DIR_INFIX "qmake_pro_file.qrc");
+ QVERIFY(qrcFile.exists());
+ QVERIFY(qrcFile.open(QFile::ReadOnly));
+ QByteArray qrcXml = qrcFile.readAll();
+ QVERIFY(qrcXml.contains("alias=\"resources.pro\""));
+ QVERIFY(qrcXml.contains("prefix=\"/prefix\""));
+ }
+
+ {
+ QFile qrcFile(workDir + "/.rcc/" DIR_INFIX "qmake_subdir.qrc");
+ QVERIFY(qrcFile.exists());
+ QVERIFY(qrcFile.open(QFile::ReadOnly));
+ QByteArray qrcXml = qrcFile.readAll();
+ QVERIFY(qrcXml.contains("alias=\"file.txt\""));
+ }
+
+ {
+ QFile qrcFile(workDir + "/.rcc/" DIR_INFIX "qmake_qmake_immediate.qrc");
+ QVERIFY(qrcFile.exists());
+ QVERIFY(qrcFile.open(QFile::ReadOnly));
+ QByteArray qrcXml = qrcFile.readAll();
+ QVERIFY(qrcXml.contains("alias=\"main.cpp\""));
+ }
+
+ QVERIFY(test_compiler.make(workDir));
+}
+
QTEST_MAIN(tst_qmake)
#include "tst_qmake.moc"
diff --git a/tests/auto/widgets/dialogs/qcolordialog/qcolordialog.pro b/tests/auto/widgets/dialogs/qcolordialog/qcolordialog.pro
index 22f6bab497..c379e67ec5 100644
--- a/tests/auto/widgets/dialogs/qcolordialog/qcolordialog.pro
+++ b/tests/auto/widgets/dialogs/qcolordialog/qcolordialog.pro
@@ -4,5 +4,4 @@ TARGET = tst_qcolordialog
QT += widgets testlib
SOURCES += tst_qcolordialog.cpp
-
-
+linux*: CONFIG += insignificant_test # Crashes on different Linux distros
diff --git a/tests/auto/widgets/dialogs/qcolordialog/tst_qcolordialog.cpp b/tests/auto/widgets/dialogs/qcolordialog/tst_qcolordialog.cpp
index 59227a6168..c5e31a4bd4 100644
--- a/tests/auto/widgets/dialogs/qcolordialog/tst_qcolordialog.cpp
+++ b/tests/auto/widgets/dialogs/qcolordialog/tst_qcolordialog.cpp
@@ -98,7 +98,7 @@ void tst_QColorDialog::testNativeActiveModalWidget()
TestNativeDialog d;
QTimer::singleShot(1000, &d, SLOT(hide()));
d.exec();
- QVERIFY(&d == d.m_activeModalWidget);
+ QCOMPARE(&d, d.m_activeModalWidget);
}
void tst_QColorDialog::native_activeModalWidget()
diff --git a/tests/auto/widgets/dialogs/qdialog/BLACKLIST b/tests/auto/widgets/dialogs/qdialog/BLACKLIST
new file mode 100644
index 0000000000..3da7337784
--- /dev/null
+++ b/tests/auto/widgets/dialogs/qdialog/BLACKLIST
@@ -0,0 +1,2 @@
+[snapToDefaultButton]
+osx
diff --git a/tests/auto/widgets/dialogs/qfiledialog/qfiledialog.pro b/tests/auto/widgets/dialogs/qfiledialog/qfiledialog.pro
index 3a96827352..2a11a29420 100644
--- a/tests/auto/widgets/dialogs/qfiledialog/qfiledialog.pro
+++ b/tests/auto/widgets/dialogs/qfiledialog/qfiledialog.pro
@@ -21,3 +21,5 @@ wince* {
} else {
DEFINES += SRCDIR=\\\"$$PWD/\\\"
}
+
+linux*: CONFIG += insignificant_test # Crashes on different Linux distros
diff --git a/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp b/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp
index ffc000a418..cc321bb137 100644
--- a/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp
+++ b/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp
@@ -677,7 +677,7 @@ void tst_QFiledialog::filters()
// effects
QList<QComboBox*> views = fd.findChildren<QComboBox*>("fileTypeCombo");
- QVERIFY(views.count() == 1);
+ QCOMPARE(views.count(), 1);
QCOMPARE(views.at(0)->isVisible(), false);
QStringList filters;
@@ -1296,7 +1296,7 @@ void tst_QFiledialog::clearLineEdit()
QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit");
QVERIFY(lineEdit);
- QVERIFY(lineEdit->text() == "foo");
+ QCOMPARE(lineEdit->text(), QLatin1String("foo"));
fd.setDirectory(QDir::home());
QListView* list = fd.findChild<QListView*>("listView");
@@ -1393,12 +1393,12 @@ void tst_QFiledialog::trailingDotsAndSpaces()
QTest::keyClick(lineEdit, Qt::Key_Space);
QTest::keyClick(lineEdit, Qt::Key_Period);
QTest::qWait(1000);
- QVERIFY(currentChildrenCount == list->model()->rowCount(list->rootIndex()));
+ QCOMPARE(currentChildrenCount, list->model()->rowCount(list->rootIndex()));
lineEdit->clear();
QTest::keyClick(lineEdit, Qt::Key_Period);
QTest::keyClick(lineEdit, Qt::Key_Space);
QTest::qWait(1000);
- QVERIFY(currentChildrenCount == list->model()->rowCount(list->rootIndex()));
+ QCOMPARE(currentChildrenCount, list->model()->rowCount(list->rootIndex()));
}
#ifdef Q_OS_UNIX
diff --git a/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp b/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp
index 03f0d25375..0e7f760b4e 100644
--- a/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp
+++ b/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp
@@ -167,7 +167,7 @@ void tst_QFileSystemModel::cleanup()
QVERIFY(dir.rmdir(list.at(i)));
}
list = dir.entryList(QDir::AllEntries | QDir::System | QDir::Hidden | QDir::NoDotAndDotDot);
- QVERIFY(list.count() == 0);
+ QCOMPARE(list.count(), 0);
}
}
@@ -523,8 +523,14 @@ void tst_QFileSystemModel::rowsInserted()
QVERIFY(createFiles(tmp, QStringList(".hidden_file"), 5 + count));
- if (count != 0) QTRY_VERIFY(spy0.count() >= 1); else QTRY_VERIFY(spy0.count() == 0);
- if (count != 0) QTRY_VERIFY(spy1.count() >= 1); else QTRY_VERIFY(spy1.count() == 0);
+ if (count != 0)
+ QTRY_VERIFY(spy0.count() >= 1);
+ else
+ QTRY_COMPARE(spy0.count(), 0);
+ if (count != 0)
+ QTRY_VERIFY(spy1.count() >= 1);
+ else
+ QTRY_COMPARE(spy1.count(), 0);
}
void tst_QFileSystemModel::rowsRemoved_data()
@@ -563,8 +569,8 @@ void tst_QFileSystemModel::rowsRemoved()
}
} else {
if (i == 10 || spy0.count() == 0) {
- QVERIFY(spy0.count() == 0);
- QVERIFY(spy1.count() == 0);
+ QCOMPARE(spy0.count(), 0);
+ QCOMPARE(spy1.count(), 0);
}
}
QStringList lst;
@@ -583,8 +589,8 @@ void tst_QFileSystemModel::rowsRemoved()
QVERIFY(QFile::remove(tmp + '/' + QString(".c")));
QTest::qWait(WAITTIME);
- if (count != 0) QVERIFY(spy0.count() >= 1); else QVERIFY(spy0.count() == 0);
- if (count != 0) QVERIFY(spy1.count() >= 1); else QVERIFY(spy1.count() == 0);
+ if (count != 0) QVERIFY(spy0.count() >= 1); else QCOMPARE(spy0.count(), 0);
+ if (count != 0) QVERIFY(spy1.count() >= 1); else QCOMPARE(spy1.count(), 0);
}
void tst_QFileSystemModel::dataChanged_data()
@@ -614,7 +620,7 @@ void tst_QFileSystemModel::dataChanged()
QTest::qWait(WAITTIME);
- if (count != 0) QVERIFY(spy.count() >= 1); else QVERIFY(spy.count() == 0);
+ if (count != 0) QVERIFY(spy.count() >= 1); else QCOMPARE(spy.count(), 0);
*/
}
diff --git a/tests/auto/widgets/dialogs/qfontdialog/BLACKLIST b/tests/auto/widgets/dialogs/qfontdialog/BLACKLIST
new file mode 100644
index 0000000000..31fbc428c9
--- /dev/null
+++ b/tests/auto/widgets/dialogs/qfontdialog/BLACKLIST
@@ -0,0 +1,4 @@
+[task256466_wrongStyle]
+opensuse-13.1
+[setFont]
+ubuntu-14.04
diff --git a/tests/auto/widgets/dialogs/qfontdialog/tst_qfontdialog_mac_helpers.mm b/tests/auto/widgets/dialogs/qfontdialog/tst_qfontdialog_mac_helpers.mm
index 6e4ad29190..0d29f5b7a2 100644
--- a/tests/auto/widgets/dialogs/qfontdialog/tst_qfontdialog_mac_helpers.mm
+++ b/tests/auto/widgets/dialogs/qfontdialog/tst_qfontdialog_mac_helpers.mm
@@ -36,7 +36,7 @@
void click_cocoa_button()
{
- QMacCocoaAutoReleasePool pool;
+ QMacAutoReleasePool pool;
NSArray *windows = [NSApp windows];
for (NSWindow *window in windows) {
// This is NOT how one should do RTTI, but since I don't want to leak the class too much...
diff --git a/tests/auto/widgets/dialogs/qmessagebox/tst_qmessagebox.cpp b/tests/auto/widgets/dialogs/qmessagebox/tst_qmessagebox.cpp
index cb816a7e85..97cfec8171 100644
--- a/tests/auto/widgets/dialogs/qmessagebox/tst_qmessagebox.cpp
+++ b/tests/auto/widgets/dialogs/qmessagebox/tst_qmessagebox.cpp
@@ -216,7 +216,7 @@ void tst_QMessageBox::button()
// remove the cancel, should not exist anymore
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- QVERIFY(msgBox.button(QMessageBox::Cancel) == 0);
+ QVERIFY(!msgBox.button(QMessageBox::Cancel));
QVERIFY(msgBox.button(QMessageBox::Yes) != 0);
// should not crash
@@ -228,10 +228,10 @@ void tst_QMessageBox::button()
void tst_QMessageBox::defaultButton()
{
QMessageBox msgBox;
- QVERIFY(msgBox.defaultButton() == 0);
+ QVERIFY(!msgBox.defaultButton());
msgBox.addButton(QMessageBox::Ok);
msgBox.addButton(QMessageBox::Cancel);
- QVERIFY(msgBox.defaultButton() == 0);
+ QVERIFY(!msgBox.defaultButton());
QPushButton pushButton;
msgBox.setDefaultButton(&pushButton);
QVERIFY(msgBox.defaultButton() == 0); // we have not added it yet
@@ -250,27 +250,27 @@ void tst_QMessageBox::defaultButton()
exec(&msgBox, Qt::Key_Enter);
QCOMPARE(msgBox.clickedButton(), okButton);
msgBox.setDefaultButton(QMessageBox::Yes); // its not in there!
- QVERIFY(msgBox.defaultButton() == okButton);
+ QCOMPARE(msgBox.defaultButton(), okButton);
msgBox.removeButton(okButton);
delete okButton;
okButton = 0;
- QVERIFY(msgBox.defaultButton() == 0);
+ QVERIFY(!msgBox.defaultButton());
msgBox.setDefaultButton(QMessageBox::Ok);
- QVERIFY(msgBox.defaultButton() == 0);
+ QVERIFY(!msgBox.defaultButton());
}
void tst_QMessageBox::escapeButton()
{
QMessageBox msgBox;
- QVERIFY(msgBox.escapeButton() == 0);
+ QVERIFY(!msgBox.escapeButton());
msgBox.addButton(QMessageBox::Ok);
exec(&msgBox);
QVERIFY(msgBox.clickedButton() == msgBox.button(QMessageBox::Ok)); // auto detected (one button only)
msgBox.addButton(QMessageBox::Cancel);
- QVERIFY(msgBox.escapeButton() == 0);
+ QVERIFY(!msgBox.escapeButton());
QPushButton invalidButton;
msgBox.setEscapeButton(&invalidButton);
- QVERIFY(msgBox.escapeButton() == 0);
+ QVERIFY(!msgBox.escapeButton());
QAbstractButton *retryButton = msgBox.addButton(QMessageBox::Retry);
exec(&msgBox);
@@ -293,13 +293,13 @@ void tst_QMessageBox::escapeButton()
exec(&msgBox, Qt::Key_Escape);
QCOMPARE(msgBox.clickedButton(), okButton);
msgBox.setEscapeButton(QMessageBox::Yes); // its not in there!
- QVERIFY(msgBox.escapeButton() == okButton);
+ QCOMPARE(msgBox.escapeButton(), okButton);
msgBox.removeButton(okButton);
delete okButton;
okButton = 0;
- QVERIFY(msgBox.escapeButton() == 0);
+ QVERIFY(!msgBox.escapeButton());
msgBox.setEscapeButton(QMessageBox::Ok);
- QVERIFY(msgBox.escapeButton() == 0);
+ QVERIFY(!msgBox.escapeButton());
QMessageBox msgBox2;
msgBox2.addButton(QMessageBox::Yes);
@@ -527,13 +527,13 @@ void tst_QMessageBox::testSymbols()
QCOMPARE(mb1.text(), text);
icon = mb1.icon();
- QVERIFY(icon == QMessageBox::NoIcon);
+ QCOMPARE(icon, QMessageBox::NoIcon);
mb1.setIcon(QMessageBox::Question);
- QVERIFY(mb1.icon() == QMessageBox::Question);
+ QCOMPARE(mb1.icon(), QMessageBox::Question);
QPixmap iconPixmap = mb1.iconPixmap();
mb1.setIconPixmap(iconPixmap);
- QVERIFY(mb1.icon() == QMessageBox::NoIcon);
+ QCOMPARE(mb1.icon(), QMessageBox::NoIcon);
QCOMPARE(mb1.buttonText(QMessageBox::Ok), QLatin1String("OK"));
QCOMPARE(mb1.buttonText(QMessageBox::Cancel), QString());
diff --git a/tests/auto/widgets/dialogs/qprogressdialog/BLACKLIST b/tests/auto/widgets/dialogs/qprogressdialog/BLACKLIST
new file mode 100644
index 0000000000..a2670e8f36
--- /dev/null
+++ b/tests/auto/widgets/dialogs/qprogressdialog/BLACKLIST
@@ -0,0 +1,2 @@
+[autoShow:50_to_100_fast_0_compat]
+osx
diff --git a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
index 21c15edff2..b2bdbac79a 100644
--- a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
+++ b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
@@ -400,7 +400,7 @@ void tst_QWizard::setButton()
// revert to default button
wizard.setButton(QWizard::NextButton, 0);
- QVERIFY(toolButton == 0);
+ QVERIFY(toolButton.isNull());
QVERIFY(qobject_cast<QPushButton *>(wizard.button(QWizard::NextButton)));
QVERIFY(wizard.button(QWizard::NextButton)->text().contains("Next"));
}
@@ -408,16 +408,16 @@ void tst_QWizard::setButton()
void tst_QWizard::setTitleFormatEtc()
{
QWizard wizard;
- QVERIFY(wizard.titleFormat() == Qt::AutoText);
- QVERIFY(wizard.subTitleFormat() == Qt::AutoText);
+ QCOMPARE(wizard.titleFormat(), Qt::AutoText);
+ QCOMPARE(wizard.subTitleFormat(), Qt::AutoText);
wizard.setTitleFormat(Qt::RichText);
- QVERIFY(wizard.titleFormat() == Qt::RichText);
- QVERIFY(wizard.subTitleFormat() == Qt::AutoText);
+ QCOMPARE(wizard.titleFormat(), Qt::RichText);
+ QCOMPARE(wizard.subTitleFormat(), Qt::AutoText);
wizard.setSubTitleFormat(Qt::PlainText);
- QVERIFY(wizard.titleFormat() == Qt::RichText);
- QVERIFY(wizard.subTitleFormat() == Qt::PlainText);
+ QCOMPARE(wizard.titleFormat(), Qt::RichText);
+ QCOMPARE(wizard.subTitleFormat(), Qt::PlainText);
}
void tst_QWizard::setPixmap()
@@ -439,7 +439,7 @@ void tst_QWizard::setPixmap()
QVERIFY(wizard.pixmap(QWizard::LogoPixmap).isNull());
QVERIFY(wizard.pixmap(QWizard::WatermarkPixmap).isNull());
#ifdef Q_OS_OSX
- QVERIFY(wizard.pixmap(QWizard::BackgroundPixmap).isNull() == false);
+ QVERIFY(!wizard.pixmap(QWizard::BackgroundPixmap).isNull());
#else
QVERIFY(wizard.pixmap(QWizard::BackgroundPixmap).isNull());
#endif
@@ -448,7 +448,7 @@ void tst_QWizard::setPixmap()
QVERIFY(page->pixmap(QWizard::LogoPixmap).isNull());
QVERIFY(page->pixmap(QWizard::WatermarkPixmap).isNull());
#ifdef Q_OS_OSX
- QVERIFY(wizard.pixmap(QWizard::BackgroundPixmap).isNull() == false);
+ QVERIFY(!wizard.pixmap(QWizard::BackgroundPixmap).isNull());
#else
QVERIFY(page->pixmap(QWizard::BackgroundPixmap).isNull());
#endif
@@ -459,20 +459,20 @@ void tst_QWizard::setPixmap()
page->setPixmap(QWizard::LogoPixmap, p5);
- QVERIFY(wizard.pixmap(QWizard::BannerPixmap).size() == p1.size());
- QVERIFY(wizard.pixmap(QWizard::LogoPixmap).size() == p2.size());
- QVERIFY(wizard.pixmap(QWizard::WatermarkPixmap).size() == p3.size());
- QVERIFY(wizard.pixmap(QWizard::BackgroundPixmap).size() == p4.size());
+ QCOMPARE(wizard.pixmap(QWizard::BannerPixmap).size(), p1.size());
+ QCOMPARE(wizard.pixmap(QWizard::LogoPixmap).size(), p2.size());
+ QCOMPARE(wizard.pixmap(QWizard::WatermarkPixmap).size(), p3.size());
+ QCOMPARE(wizard.pixmap(QWizard::BackgroundPixmap).size(), p4.size());
- QVERIFY(page->pixmap(QWizard::BannerPixmap).size() == p1.size());
- QVERIFY(page->pixmap(QWizard::LogoPixmap).size() == p5.size());
- QVERIFY(page->pixmap(QWizard::WatermarkPixmap).size() == p3.size());
- QVERIFY(page->pixmap(QWizard::BackgroundPixmap).size() == p4.size());
+ QCOMPARE(page->pixmap(QWizard::BannerPixmap).size(), p1.size());
+ QCOMPARE(page->pixmap(QWizard::LogoPixmap).size(), p5.size());
+ QCOMPARE(page->pixmap(QWizard::WatermarkPixmap).size(), p3.size());
+ QCOMPARE(page->pixmap(QWizard::BackgroundPixmap).size(), p4.size());
- QVERIFY(page2->pixmap(QWizard::BannerPixmap).size() == p1.size());
- QVERIFY(page2->pixmap(QWizard::LogoPixmap).size() == p2.size());
- QVERIFY(page2->pixmap(QWizard::WatermarkPixmap).size() == p3.size());
- QVERIFY(page2->pixmap(QWizard::BackgroundPixmap).size() == p4.size());
+ QCOMPARE(page2->pixmap(QWizard::BannerPixmap).size(), p1.size());
+ QCOMPARE(page2->pixmap(QWizard::LogoPixmap).size(), p2.size());
+ QCOMPARE(page2->pixmap(QWizard::WatermarkPixmap).size(), p3.size());
+ QCOMPARE(page2->pixmap(QWizard::BackgroundPixmap).size(), p4.size());
}
class MyPage1 : public QWizardPage
@@ -571,7 +571,7 @@ void tst_QWizard::addPage()
}
for (int i = 0; i < N; ++i) {
- QVERIFY(pages[i] == wizard.page(i));
+ QCOMPARE(pages[i], wizard.page(i));
}
QVERIFY(!wizard.page(-1));
QVERIFY(!wizard.page(N));
@@ -667,7 +667,7 @@ void tst_QWizard::setPage()
QCOMPARE(wizard.page(-2), page);
QCOMPARE(wizard.startId(), -2);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == page);
+ QCOMPARE(wizard.currentPage(), page);
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -2);
@@ -679,14 +679,14 @@ void tst_QWizard::setPage()
QCOMPARE(wizard.page(2), page);
QCOMPARE(wizard.startId(), -2);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -2);
wizard.restart();
QCOMPARE(wizard.startId(), -2);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -2);
@@ -698,28 +698,28 @@ void tst_QWizard::setPage()
QCOMPARE(wizard.page(-3), page);
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -2);
wizard.restart();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -3);
- QVERIFY(wizard.currentPage() == wizard.page(-3));
+ QCOMPARE(wizard.currentPage(), wizard.page(-3));
QCOMPARE(wizard.nextId(), -2);
CHECK_VISITED(wizard, QList<int>() << -3);
wizard.next();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -3 << -2);
wizard.next();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), 0);
- QVERIFY(wizard.currentPage() == wizard.page(0));
+ QCOMPARE(wizard.currentPage(), wizard.page(0));
QCOMPARE(wizard.nextId(), 2);
CHECK_VISITED(wizard, QList<int>() << -3 << -2 << 0);
@@ -727,7 +727,7 @@ void tst_QWizard::setPage()
wizard.next();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), 2);
- QVERIFY(wizard.currentPage() == wizard.page(2));
+ QCOMPARE(wizard.currentPage(), wizard.page(2));
QCOMPARE(wizard.nextId(), -1);
CHECK_VISITED(wizard, QList<int>() << -3 << -2 << 0 << 2);
}
@@ -735,14 +735,14 @@ void tst_QWizard::setPage()
wizard.back();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), 0);
- QVERIFY(wizard.currentPage() == wizard.page(0));
+ QCOMPARE(wizard.currentPage(), wizard.page(0));
QCOMPARE(wizard.nextId(), 2);
CHECK_VISITED(wizard, QList<int>() << -3 << -2 << 0);
wizard.back();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
CHECK_VISITED(wizard, QList<int>() << -3 << -2);
@@ -750,7 +750,7 @@ void tst_QWizard::setPage()
wizard.back();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -3);
- QVERIFY(wizard.currentPage() == wizard.page(-3));
+ QCOMPARE(wizard.currentPage(), wizard.page(-3));
QCOMPARE(wizard.nextId(), -2);
CHECK_VISITED(wizard, QList<int>() << -3);
}
@@ -759,7 +759,7 @@ void tst_QWizard::setPage()
wizard.restart();
QCOMPARE(wizard.startId(), -3);
QCOMPARE(wizard.currentId(), -3);
- QVERIFY(wizard.currentPage() == wizard.page(-3));
+ QCOMPARE(wizard.currentPage(), wizard.page(-3));
QCOMPARE(wizard.nextId(), -2);
CHECK_VISITED(wizard, QList<int>() << -3);
}
@@ -808,31 +808,31 @@ void tst_QWizard::setStartId()
wizard.restart();
QCOMPARE(wizard.startId(), -2);
QCOMPARE(wizard.currentId(), -2);
- QVERIFY(wizard.currentPage() == wizard.page(-2));
+ QCOMPARE(wizard.currentPage(), wizard.page(-2));
QCOMPARE(wizard.nextId(), 0);
wizard.next();
QCOMPARE(wizard.startId(), -2);
QCOMPARE(wizard.currentId(), 0);
- QVERIFY(wizard.currentPage() == wizard.page(0));
+ QCOMPARE(wizard.currentPage(), wizard.page(0));
QCOMPARE(wizard.nextId(), 1);
wizard.setStartId(INT_MIN);
QCOMPARE(wizard.startId(), INT_MIN);
QCOMPARE(wizard.currentId(), 0);
- QVERIFY(wizard.currentPage() == wizard.page(0));
+ QCOMPARE(wizard.currentPage(), wizard.page(0));
QCOMPARE(wizard.nextId(), 1);
wizard.next();
QCOMPARE(wizard.startId(), INT_MIN);
QCOMPARE(wizard.currentId(), 1);
- QVERIFY(wizard.currentPage() == wizard.page(1));
+ QCOMPARE(wizard.currentPage(), wizard.page(1));
QCOMPARE(wizard.nextId(), INT_MAX);
wizard.next();
QCOMPARE(wizard.startId(), INT_MIN);
QCOMPARE(wizard.currentId(), INT_MAX);
- QVERIFY(wizard.currentPage() == wizard.page(INT_MAX));
+ QCOMPARE(wizard.currentPage(), wizard.page(INT_MAX));
QCOMPARE(wizard.nextId(), -1);
CHECK_VISITED(wizard, QList<int>() << -2 << 0 << 1 << INT_MAX);
}
@@ -1143,12 +1143,12 @@ void tst_QWizard::setOption_ExtendedWatermarkPixmap()
}
if (wizard1.wizardStyle() == QWizard::MacStyle) {
- QVERIFY(i1[0] == i1[1]);
- QVERIFY(i2[0] == i2[1]);
- QVERIFY(i1[0] == i2[0]);
+ QCOMPARE(i1[0], i1[1]);
+ QCOMPARE(i2[0], i2[1]);
+ QCOMPARE(i1[0], i2[0]);
} else {
QVERIFY(i1[0] != i1[1]);
- QVERIFY(i2[0] == i2[1]);
+ QCOMPARE(i2[0], i2[1]);
QVERIFY(i1[0] != i2[0]);
QVERIFY(i1[1] != i2[1]);
}
@@ -2425,19 +2425,19 @@ void tst_QWizard::sideWidget()
QWizard wizard;
wizard.setSideWidget(0);
- QVERIFY(wizard.sideWidget() == 0);
+ QVERIFY(!wizard.sideWidget());
QScopedPointer<QWidget> w1(new QWidget(&wizard));
wizard.setSideWidget(w1.data());
QCOMPARE(wizard.sideWidget(), w1.data());
QWidget *w2 = new QWidget(&wizard);
wizard.setSideWidget(w2);
- QVERIFY(wizard.sideWidget() == w2);
+ QCOMPARE(wizard.sideWidget(), w2);
QVERIFY(w1->parent() != 0);
QCOMPARE(w1->window(), static_cast<QWidget *>(&wizard));
QCOMPARE(w2->window(), static_cast<QWidget *>(&wizard));
w1->setParent(0);
wizard.setSideWidget(0);
- QVERIFY(wizard.sideWidget() == 0);
+ QVERIFY(!wizard.sideWidget());
}
void tst_QWizard::objectNames_data()
@@ -2558,7 +2558,7 @@ void tst_QWizard::task183550_stretchFactor()
page2->disableVerticalExpansion();
wizard.next();
QCOMPARE(wizard.currentPage(), static_cast<QWizardPage*>(page2));
- QVERIFY(page2->treeWidgetHeight() == page2->treeWidgetSizeHintHeight());
+ QCOMPARE(page2->treeWidgetHeight(), page2->treeWidgetSizeHintHeight());
wizard.back();
QCOMPARE(wizard.currentPage(), static_cast<QWizardPage*>(page1));
@@ -2576,7 +2576,7 @@ void tst_QWizard::task183550_stretchFactor()
page2->disableVerticalExpansion();
wizard.next();
QCOMPARE(wizard.currentPage(), static_cast<QWizardPage*>(page2));
- QVERIFY(page2->treeWidgetHeight() == page2->treeWidgetSizeHintHeight());
+ QCOMPARE(page2->treeWidgetHeight(), page2->treeWidgetSizeHintHeight());
}
void tst_QWizard::task161658_alignments()
diff --git a/tests/auto/widgets/effects/qgraphicseffect/tst_qgraphicseffect.cpp b/tests/auto/widgets/effects/qgraphicseffect/tst_qgraphicseffect.cpp
index 4d7f55f37d..c7d1dd0aa1 100644
--- a/tests/auto/widgets/effects/qgraphicseffect/tst_qgraphicseffect.cpp
+++ b/tests/auto/widgets/effects/qgraphicseffect/tst_qgraphicseffect.cpp
@@ -520,7 +520,7 @@ public:
void draw(QPainter *painter)
{
- QVERIFY(sourcePixmap(Qt::LogicalCoordinates).handle() == pixmap.handle());
+ QCOMPARE(sourcePixmap(Qt::LogicalCoordinates).handle(), pixmap.handle());
QVERIFY((painter->worldTransform().type() <= QTransform::TxTranslate) == (sourcePixmap(Qt::DeviceCoordinates).handle() == pixmap.handle()));
++repaints;
@@ -595,7 +595,7 @@ void tst_QGraphicsEffect::deviceCoordinateTranslateCaching()
item->translate(10, 0);
- QTRY_VERIFY(item->numRepaints == numRepaints);
+ QTRY_COMPARE(item->numRepaints, numRepaints);
}
void tst_QGraphicsEffect::inheritOpacity()
diff --git a/tests/auto/widgets/gestures/qgesturerecognizer/BLACKLIST b/tests/auto/widgets/gestures/qgesturerecognizer/BLACKLIST
new file mode 100644
index 0000000000..7f55c2dae0
--- /dev/null
+++ b/tests/auto/widgets/gestures/qgesturerecognizer/BLACKLIST
@@ -0,0 +1,2 @@
+[panGesture:Two finger]
+xcb
diff --git a/tests/auto/widgets/graphicsview/qgraphicsanchorlayout/tst_qgraphicsanchorlayout.cpp b/tests/auto/widgets/graphicsview/qgraphicsanchorlayout/tst_qgraphicsanchorlayout.cpp
index ca01b27bee..f71308cdaf 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsanchorlayout/tst_qgraphicsanchorlayout.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsanchorlayout/tst_qgraphicsanchorlayout.cpp
@@ -133,7 +133,6 @@ static bool checkReverseDirection(QGraphicsWidget *widget)
layout->getContentsMargins(&left, &top, &right, &bottom);
widget->setLayoutDirection(Qt::LeftToRight);
QApplication::processEvents();
- const QRectF layoutGeometry = layout->geometry();
QMap<QGraphicsLayoutItem *, QRectF> geometries;
for (int i = 0; i < layout->count(); ++i) {
QGraphicsLayoutItem *item = layout->itemAt(i);
@@ -141,7 +140,7 @@ static bool checkReverseDirection(QGraphicsWidget *widget)
}
widget->setLayoutDirection(Qt::RightToLeft);
QApplication::processEvents();
- layoutGeometry.adjusted(+right, +top, -left, -bottom);
+ const QRectF layoutGeometry = layout->geometry().adjusted(+right, +top, -left, -bottom);
for (int i = 0; i < layout->count(); ++i) {
QGraphicsLayoutItem *item = layout->itemAt(i);
const QRectF rightToLeftGeometry = item->geometry();
@@ -653,7 +652,7 @@ void tst_QGraphicsAnchorLayout::snake()
QCOMPARE(c->geometry(), QRectF(90.0, 200.0, 100.0, 100.0));
QCOMPARE(p.size(), layoutMaximumSize);
- QVERIFY(layoutHasConflict(l) == false);
+ QVERIFY(!layoutHasConflict(l));
// Test QSizePolicy::ExpandFlag, it shouldn't change the extreme
// points of the layout...
@@ -2041,9 +2040,9 @@ void tst_QGraphicsAnchorLayout::graphicsAnchorHandling()
QGraphicsAnchor *invalidAnchor = l->anchor(a, Qt::AnchorTop, l, Qt::AnchorBottom);
// Ensure none of these anchors are accessible.
- QVERIFY(layoutAnchor == 0);
- QVERIFY(itemAnchor == 0);
- QVERIFY(invalidAnchor == 0);
+ QVERIFY(!layoutAnchor);
+ QVERIFY(!itemAnchor);
+ QVERIFY(!invalidAnchor);
// Hook the anchors to a QObject
QObject object;
diff --git a/tests/auto/widgets/graphicsview/qgraphicsanchorlayout1/tst_qgraphicsanchorlayout1.cpp b/tests/auto/widgets/graphicsview/qgraphicsanchorlayout1/tst_qgraphicsanchorlayout1.cpp
index a2108dd494..a58f295575 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsanchorlayout1/tst_qgraphicsanchorlayout1.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsanchorlayout1/tst_qgraphicsanchorlayout1.cpp
@@ -715,7 +715,7 @@ void tst_QGraphicsAnchorLayout1::testSpecialCases()
widget1->setGeometry(QRectF(0,0,100,100));
QCOMPARE(childWidget->geometry(), QRectF(1,1,98,98));
- QVERIFY(childWidget->parentLayoutItem() == layout1);
+ QCOMPARE(childWidget->parentLayoutItem(), layout1);
QGraphicsWidget *widget2 = new QGraphicsWidget;
TheAnchorLayout *layout2 = new TheAnchorLayout();
widget2->setLayout(layout2);
@@ -739,10 +739,10 @@ void tst_QGraphicsAnchorLayout1::testSpecialCases()
widget2->setGeometry(QRectF(0,0,100,100));
QCOMPARE(childWidget->geometry(), QRectF(1,1,98,98));
- QVERIFY(childWidget->parentLayoutItem() == layout2);
+ QCOMPARE(childWidget->parentLayoutItem(), layout2);
QCOMPARE(widget4->geometry(), QRectF(1,1,98,98));
- QVERIFY(widget4->parentLayoutItem() == layout2);
- QVERIFY(widget4->parentItem() == widget2);
+ QCOMPARE(widget4->parentLayoutItem(), layout2);
+ QCOMPARE(widget4->parentItem(), widget2);
delete widget4;
delete widget3;
diff --git a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
index 0dd1161dcf..835aeaa4df 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
@@ -4274,7 +4274,7 @@ void tst_QGraphicsItem::cursor()
void tst_QGraphicsItem::textControlGetterSetter()
{
QGraphicsTextItem *item = new QGraphicsTextItem;
- QVERIFY(item->textControl()->parent() == item);
+ QCOMPARE(item->textControl()->parent(), item);
QPointer<QWidgetTextControl> control = item->textControl();
delete item;
QVERIFY(!control);
@@ -4285,7 +4285,7 @@ void tst_QGraphicsItem::textControlGetterSetter()
control = new QWidgetTextControl;
item->setTextControl(control);
- QVERIFY(item->textControl() == control);
+ QCOMPARE(item->textControl(), control);
QVERIFY(!control->parent());
QVERIFY(!oldControl);
@@ -5141,19 +5141,19 @@ void tst_QGraphicsItem::paint()
//nominal case, update call paint
tester2.update();
qApp->processEvents();
- QTRY_VERIFY(tester2.painted == 2);
+ QTRY_COMPARE(tester2.painted, 2);
//we remove the item from the scene, number of updates is still the same
tester2.update();
scene2.removeItem(&tester2);
qApp->processEvents();
- QTRY_VERIFY(tester2.painted == 2);
+ QTRY_COMPARE(tester2.painted, 2);
//We re-add the item, the number of paint should increase
scene2.addItem(&tester2);
tester2.update();
qApp->processEvents();
- QTRY_VERIFY(tester2.painted == 3);
+ QTRY_COMPARE(tester2.painted, 3);
}
class HarakiriItem : public QGraphicsRectItem
@@ -5878,7 +5878,7 @@ void tst_QGraphicsItem::itemContainsChildrenInShape()
scene.setItemIndexMethod(QGraphicsScene::NoIndex);
scene.addItem(parent);
- QVERIFY(parent->boundingRectCalls == childOutsideShape->boundingRectCalls);
+ QCOMPARE(parent->boundingRectCalls, childOutsideShape->boundingRectCalls);
int oldParentBoundingRectCalls = parent->boundingRectCalls;
int oldChildBoundingRectCalls = childOutsideShape->boundingRectCalls;
@@ -5886,10 +5886,10 @@ void tst_QGraphicsItem::itemContainsChildrenInShape()
// First test that both items are searched if no optimization flags are set
QGraphicsItem* item = scene.itemAt(25,5);
- QVERIFY(item == childOutsideShape);
+ QCOMPARE(item, childOutsideShape);
QVERIFY(parent->boundingRectCalls > oldParentBoundingRectCalls);
QVERIFY(childOutsideShape->boundingRectCalls > oldChildBoundingRectCalls);
- QVERIFY(parent->boundingRectCalls == childOutsideShape->boundingRectCalls);
+ QCOMPARE(parent->boundingRectCalls, childOutsideShape->boundingRectCalls);
oldParentBoundingRectCalls = parent->boundingRectCalls;
oldChildBoundingRectCalls = childOutsideShape->boundingRectCalls;
@@ -5897,10 +5897,10 @@ void tst_QGraphicsItem::itemContainsChildrenInShape()
// Repeat the test to make sure that no caching/indexing is in effect
item = scene.itemAt(25,5);
- QVERIFY(item == childOutsideShape);
+ QCOMPARE(item, childOutsideShape);
QVERIFY(parent->boundingRectCalls > oldParentBoundingRectCalls);
QVERIFY(childOutsideShape->boundingRectCalls > oldChildBoundingRectCalls);
- QVERIFY(parent->boundingRectCalls == childOutsideShape->boundingRectCalls);
+ QCOMPARE(parent->boundingRectCalls, childOutsideShape->boundingRectCalls);
oldParentBoundingRectCalls = parent->boundingRectCalls;
oldChildBoundingRectCalls = childOutsideShape->boundingRectCalls;
@@ -5912,7 +5912,7 @@ void tst_QGraphicsItem::itemContainsChildrenInShape()
QVERIFY(!(item));
QVERIFY(parent->boundingRectCalls > oldParentBoundingRectCalls);
- QVERIFY(childOutsideShape->boundingRectCalls == oldChildBoundingRectCalls);
+ QCOMPARE(childOutsideShape->boundingRectCalls, oldChildBoundingRectCalls);
QVERIFY(parent->boundingRectCalls > childOutsideShape->boundingRectCalls);
}
@@ -11205,21 +11205,21 @@ void tst_QGraphicsItem::QTBUG_6738_missingUpdateWithSetParent()
child2->setVisible(false);
child2->setParentItem(child);
- QTRY_VERIFY(view.repaints == 1);
+ QTRY_COMPARE(view.repaints, 1);
// test case #2
view.reset();
child3->setOpacity(0.0);
child3->setParentItem(child);
- QTRY_VERIFY(view.repaints == 1);
+ QTRY_COMPARE(view.repaints, 1);
// test case #3
view.reset();
child4->setParentItem(child);
child4->setVisible(false);
- QTRY_VERIFY(view.repaints == 1);
+ QTRY_COMPARE(view.repaints, 1);
}
void tst_QGraphicsItem::QT_2653_fullUpdateDiscardingOpacityUpdate()
@@ -11469,9 +11469,9 @@ void tst_QGraphicsItem::itemDiesDuringDraggingOperation()
QGraphicsSceneDragDropEvent event(QEvent::GraphicsSceneDragMove);
event.setScenePos(item->boundingRect().center());
QApplication::sendEvent(&scene, &event);
- QVERIFY(QGraphicsScenePrivate::get(&scene)->dragDropItem == item);
+ QCOMPARE(QGraphicsScenePrivate::get(&scene)->dragDropItem, item);
delete item;
- QVERIFY(QGraphicsScenePrivate::get(&scene)->dragDropItem == 0);
+ QVERIFY(!QGraphicsScenePrivate::get(&scene)->dragDropItem);
}
void tst_QGraphicsItem::QTBUG_12112_focusItem()
diff --git a/tests/auto/widgets/graphicsview/qgraphicslayout/tst_qgraphicslayout.cpp b/tests/auto/widgets/graphicsview/qgraphicslayout/tst_qgraphicslayout.cpp
index bd104539ac..a2740edc54 100644
--- a/tests/auto/widgets/graphicsview/qgraphicslayout/tst_qgraphicslayout.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicslayout/tst_qgraphicslayout.cpp
@@ -948,7 +948,7 @@ void tst_QGraphicsLayout::ownership()
destructedSet.clear();
window->setLayout(0);
- QVERIFY(destructedSet.count() == 0);
+ QCOMPARE(destructedSet.count(), 0);
delete window;
}
diff --git a/tests/auto/widgets/graphicsview/qgraphicslinearlayout/tst_qgraphicslinearlayout.cpp b/tests/auto/widgets/graphicsview/qgraphicslinearlayout/tst_qgraphicslinearlayout.cpp
index 6a8b690560..8bebd4eddd 100644
--- a/tests/auto/widgets/graphicsview/qgraphicslinearlayout/tst_qgraphicslinearlayout.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicslinearlayout/tst_qgraphicslinearlayout.cpp
@@ -1230,8 +1230,8 @@ void tst_QGraphicsLinearLayout::testStretch()
layout->addStretch(2);
layout->addItem(w2);
QCOMPARE(layout->count(), 2);
- QVERIFY(layout->itemAt(0) == w1);
- QVERIFY(layout->itemAt(1) == w2);
+ QCOMPARE(layout->itemAt(0), w1);
+ QCOMPARE(layout->itemAt(1), w2);
layout->activate();
//view->setSceneRect(-50, -50, 800, 800);
diff --git a/tests/auto/widgets/graphicsview/qgraphicsobject/tst_qgraphicsobject.cpp b/tests/auto/widgets/graphicsview/qgraphicsobject/tst_qgraphicsobject.cpp
index 84c39bbb98..0f9e8c101e 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsobject/tst_qgraphicsobject.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsobject/tst_qgraphicsobject.cpp
@@ -102,7 +102,7 @@ void tst_QGraphicsObject::pos()
QCOMPARE(xSpy.count(), 1);
QCOMPARE(ySpy.count(), 1);
- QVERIFY(object.pos() == QPointF(10,10));
+ QCOMPARE(object.pos(), QPointF(10,10));
object.setPos(10, 10);
QCOMPARE(xSpy.count(), 1);
@@ -111,12 +111,12 @@ void tst_QGraphicsObject::pos()
object.setProperty("pos", QPointF(0, 0));
QCOMPARE(xSpy.count(), 2);
QCOMPARE(ySpy.count(), 2);
- QVERIFY(object.property("pos") == QPointF(0,0));
+ QCOMPARE(object.property("pos").toPointF(), QPointF(0,0));
object.setProperty("pos", QPointF(10, 0));
QCOMPARE(xSpy.count(), 3);
QCOMPARE(ySpy.count(), 2);
- QVERIFY(object.property("pos") == QPointF(10,0));
+ QCOMPARE(object.property("pos").toPointF(), QPointF(10,0));
object.setProperty("pos", QPointF(10, 10));
QCOMPARE(xSpy.count(), 3);
@@ -135,7 +135,7 @@ void tst_QGraphicsObject::x()
QCOMPARE(ySpy.count(), 0);
QVERIFY(object.pos() == QPointF(10, 0));
- QVERIFY(object.x() == 10);
+ QCOMPARE(object.x(), qreal(10));
object.setX(10);
QCOMPARE(xSpy.count(), 1);
@@ -144,7 +144,7 @@ void tst_QGraphicsObject::x()
object.setProperty("x", 0);
QCOMPARE(xSpy.count(), 2);
QCOMPARE(ySpy.count(), 0);
- QVERIFY(object.property("x") == 0);
+ QCOMPARE(object.property("x").toDouble(), double(0));
}
void tst_QGraphicsObject::y()
@@ -158,7 +158,7 @@ void tst_QGraphicsObject::y()
QCOMPARE(ySpy.count(), 1);
QVERIFY(object.pos() == QPointF(0, 10));
- QVERIFY(object.y() == 10);
+ QCOMPARE(object.y(), qreal(10));
object.setY(10);
QCOMPARE(xSpy.count(), 0);
@@ -167,79 +167,79 @@ void tst_QGraphicsObject::y()
object.setProperty("y", 0);
QCOMPARE(xSpy.count(), 0);
QCOMPARE(ySpy.count(), 2);
- QVERIFY(object.property("y") == 0);
+ QCOMPARE(object.property("y").toDouble(), qreal(0));
}
void tst_QGraphicsObject::z()
{
MyGraphicsObject object;
QSignalSpy zSpy(&object, SIGNAL(zChanged()));
- QVERIFY(object.zValue() == 0);
+ QCOMPARE(object.zValue(), qreal(0));
object.setZValue(10);
QCOMPARE(zSpy.count(), 1);
- QVERIFY(object.zValue() == 10);
+ QCOMPARE(object.zValue(), qreal(10));
object.setZValue(10);
QCOMPARE(zSpy.count(), 1);
object.setProperty("z", 0);
QCOMPARE(zSpy.count(), 2);
- QVERIFY(object.property("z") == 0);
+ QCOMPARE(object.property("z").toDouble(), double(0));
}
void tst_QGraphicsObject::opacity()
{
MyGraphicsObject object;
QSignalSpy spy(&object, SIGNAL(opacityChanged()));
- QVERIFY(object.opacity() == 1.);
+ QCOMPARE(object.opacity(), 1.);
object.setOpacity(0);
QCOMPARE(spy.count(), 1);
- QVERIFY(object.opacity() == 0.);
+ QCOMPARE(object.opacity(), 0.);
object.setOpacity(0);
QCOMPARE(spy.count(), 1);
object.setProperty("opacity", .5);
QCOMPARE(spy.count(), 2);
- QVERIFY(object.property("opacity") == .5);
+ QCOMPARE(object.property("opacity").toDouble(), .5);
}
void tst_QGraphicsObject::enabled()
{
MyGraphicsObject object;
QSignalSpy spy(&object, SIGNAL(enabledChanged()));
- QVERIFY(object.isEnabled() == true);
+ QVERIFY(object.isEnabled());
object.setEnabled(false);
QCOMPARE(spy.count(), 1);
- QVERIFY(object.isEnabled() == false);
+ QVERIFY(!object.isEnabled());
object.setEnabled(false);
QCOMPARE(spy.count(), 1);
object.setProperty("enabled", true);
QCOMPARE(spy.count(), 2);
- QVERIFY(object.property("enabled") == true);
+ QVERIFY(object.property("enabled").toBool());
}
void tst_QGraphicsObject::visible()
{
MyGraphicsObject object;
QSignalSpy spy(&object, SIGNAL(visibleChanged()));
- QVERIFY(object.isVisible() == true);
+ QVERIFY(object.isVisible());
object.setVisible(false);
QCOMPARE(spy.count(), 1);
- QVERIFY(object.isVisible() == false);
+ QVERIFY(!object.isVisible());
object.setVisible(false);
QCOMPARE(spy.count(), 1);
object.setProperty("visible", true);
QCOMPARE(spy.count(), 2);
- QVERIFY(object.property("visible") == true);
+ QVERIFY(object.property("visible").toBool());
}
class DeleteTester : public QGraphicsObject
diff --git a/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp b/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
index cd40c5541c..4896d52343 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
@@ -97,8 +97,8 @@ private slots:
void paint_2();
void setWidget_data();
void setWidget();
- void eventFilter_data();
- void eventFilter();
+ void testEventFilter_data();
+ void testEventFilter();
void focusInEvent_data();
void focusInEvent();
void focusInEventNoWidget();
@@ -314,7 +314,7 @@ void tst_QGraphicsProxyWidget::qgraphicsproxywidget()
SubQGraphicsProxyWidget proxy;
proxy.paint(0, 0, 0);
proxy.setWidget(0);
- QVERIFY(proxy.type() == QGraphicsProxyWidget::Type);
+ QCOMPARE(proxy.type(), int(QGraphicsProxyWidget::Type));
QVERIFY(!proxy.widget());
QEvent event(QEvent::None);
proxy.call_eventFilter(0, &event);
@@ -533,7 +533,7 @@ void tst_QGraphicsProxyWidget::setWidget()
}
Q_DECLARE_METATYPE(QEvent::Type)
-void tst_QGraphicsProxyWidget::eventFilter_data()
+void tst_QGraphicsProxyWidget::testEventFilter_data()
{
QTest::addColumn<QEvent::Type>("eventType");
QTest::addColumn<bool>("fromObject"); // big grin evil
@@ -552,7 +552,7 @@ void tst_QGraphicsProxyWidget::eventFilter_data()
}
// protected bool eventFilter(QObject* object, QEvent* event)
-void tst_QGraphicsProxyWidget::eventFilter()
+void tst_QGraphicsProxyWidget::testEventFilter()
{
QFETCH(QEvent::Type, eventType);
QFETCH(bool, fromObject);
@@ -1223,6 +1223,7 @@ void tst_QGraphicsProxyWidget::mousePressReleaseEvent()
QGraphicsScene scene;
QGraphicsView view(&scene);
+ view.resize(500, 500);
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
@@ -1231,7 +1232,6 @@ void tst_QGraphicsProxyWidget::mousePressReleaseEvent()
QPushButton *widget = new QPushButton;
QSignalSpy spy(widget, SIGNAL(clicked()));
widget->resize(50, 50);
- view.resize(100, 100);
if (hasWidget) {
proxy->setWidget(widget);
proxy->show();
@@ -3017,36 +3017,36 @@ void tst_QGraphicsProxyWidget::createProxyForChildWidget()
layout->addWidget(rightDial);
window.setLayout(layout);
- QVERIFY(window.graphicsProxyWidget() == 0);
- QVERIFY(checkbox->graphicsProxyWidget() == 0);
+ QVERIFY(!window.graphicsProxyWidget());
+ QVERIFY(!checkbox->graphicsProxyWidget());
QGraphicsProxyWidget *windowProxy = scene.addWidget(&window);
QGraphicsView view(&scene);
view.show();
view.resize(500,500);
- QVERIFY(window.graphicsProxyWidget() == windowProxy);
- QVERIFY(box->graphicsProxyWidget() == 0);
- QVERIFY(checkbox->graphicsProxyWidget() == 0);
+ QCOMPARE(window.graphicsProxyWidget(), windowProxy);
+ QVERIFY(!box->graphicsProxyWidget());
+ QVERIFY(!checkbox->graphicsProxyWidget());
QPointer<QGraphicsProxyWidget> checkboxProxy = windowProxy->createProxyForChildWidget(checkbox);
QGraphicsProxyWidget *boxProxy = box->graphicsProxyWidget();
QVERIFY(boxProxy);
- QVERIFY(checkbox->graphicsProxyWidget() == checkboxProxy);
- QVERIFY(checkboxProxy->parentItem() == boxProxy);
- QVERIFY(boxProxy->parentItem() == windowProxy);
+ QCOMPARE(checkbox->graphicsProxyWidget(), checkboxProxy.data());
+ QCOMPARE(checkboxProxy->parentItem(), boxProxy);
+ QCOMPARE(boxProxy->parentItem(), windowProxy);
QVERIFY(checkboxProxy->mapToScene(QPointF()) == checkbox->mapTo(&window, QPoint()));
- QVERIFY(checkboxProxy->size() == checkbox->size());
- QVERIFY(boxProxy->size() == box->size());
+ QCOMPARE(checkboxProxy->size().toSize(), checkbox->size());
+ QCOMPARE(boxProxy->size().toSize(), box->size());
window.resize(500,500);
- QVERIFY(windowProxy->size() == QSize(500,500));
+ QCOMPARE(windowProxy->size().toSize(), QSize(500,500));
QVERIFY(checkboxProxy->mapToScene(QPointF()) == checkbox->mapTo(&window, QPoint()));
- QVERIFY(checkboxProxy->size() == checkbox->size());
- QVERIFY(boxProxy->size() == box->size());
+ QCOMPARE(checkboxProxy->size().toSize(), checkbox->size());
+ QCOMPARE(boxProxy->size().toSize(), box->size());
QTest::qWait(10);
@@ -3064,9 +3064,9 @@ void tst_QGraphicsProxyWidget::createProxyForChildWidget()
boxProxy->setWidget(0);
- QVERIFY(checkbox->graphicsProxyWidget() == 0);
- QVERIFY(box->graphicsProxyWidget() == 0);
- QVERIFY(checkboxProxy == 0);
+ QVERIFY(!checkbox->graphicsProxyWidget());
+ QVERIFY(!box->graphicsProxyWidget());
+ QVERIFY(checkboxProxy.isNull());
delete boxProxy;
}
diff --git a/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp b/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp
index 7bd0393760..ae71b0412f 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp
@@ -1282,33 +1282,16 @@ void tst_QGraphicsScene::removeItem()
view.show();
QApplication::setActiveWindow(&view);
QVERIFY(QTest::qWaitForWindowActive(&view));
- QTest::mouseMove(view.viewport(), QPoint(-1, -1));
- {
- QMouseEvent moveEvent(QEvent::MouseMove, view.mapFromScene(hoverItem->scenePos() + QPointF(20, 20)), Qt::NoButton, 0, 0);
- QApplication::sendEvent(view.viewport(), &moveEvent);
- }
- qApp->processEvents(); // update
- qApp->processEvents(); // draw
- QVERIFY(!hoverItem->isHovered);
+ QTest::mouseMove(view.viewport(), view.mapFromScene(hoverItem->scenePos() + QPointF(20, 20)), Qt::NoButton);
+ QTRY_VERIFY(!hoverItem->isHovered);
- {
- QTest::qWait(250);
- QTest::mouseMove(view.viewport(), view.mapFromScene(hoverItem->scenePos()), Qt::NoButton);
- QTest::qWait(10);
- QMouseEvent moveEvent(QEvent::MouseMove, view.mapFromScene(hoverItem->scenePos()), Qt::NoButton, 0, 0);
- QApplication::sendEvent(view.viewport(), &moveEvent);
- }
- qApp->processEvents(); // update
- qApp->processEvents(); // draw
- QVERIFY(hoverItem->isHovered);
+ QTest::mouseMove(view.viewport(), view.mapFromScene(hoverItem->scenePos()), Qt::NoButton);
+ QTRY_VERIFY(hoverItem->isHovered);
scene.removeItem(hoverItem);
hoverItem->setAcceptsHoverEvents(false);
scene.addItem(hoverItem);
- qApp->processEvents(); // <- delayed update is called
- qApp->processEvents(); // <- scene schedules pending update
- qApp->processEvents(); // <- pending update is sent to view
- QVERIFY(!hoverItem->isHovered);
+ QTRY_VERIFY(!hoverItem->isHovered);
}
void tst_QGraphicsScene::focusItem()
@@ -3509,6 +3492,8 @@ void tst_QGraphicsScene::task160653_selectionChanged()
QSignalSpy spy(&scene, SIGNAL(selectionChanged()));
QGraphicsView view(&scene);
+ view.show();
+ QVERIFY(QTest::qWaitForWindowActive(&view));
QTest::mouseClick(
view.viewport(), Qt::LeftButton, 0, view.mapFromScene(scene.items().first()->scenePos()));
QCOMPARE(spy.count(), 1);
@@ -4742,9 +4727,9 @@ void tst_QGraphicsScene::minimumRenderSize()
QTRY_VERIFY(view.repaints > viewRepaints);
viewRepaints = view.repaints;
- QVERIFY(viewRepaints == bigParent->repaints);
- QVERIFY(viewRepaints == smallChild->repaints);
- QVERIFY(viewRepaints == smallerGrandChild->repaints);
+ QCOMPARE(viewRepaints, bigParent->repaints);
+ QCOMPARE(viewRepaints, smallChild->repaints);
+ QCOMPARE(viewRepaints, smallerGrandChild->repaints);
// Setting a minimum render size should cause a repaint
scene.setMinimumRenderSize(0.5);
@@ -4753,9 +4738,9 @@ void tst_QGraphicsScene::minimumRenderSize()
QTRY_VERIFY(view.repaints > viewRepaints);
viewRepaints = view.repaints;
- QVERIFY(viewRepaints == bigParent->repaints);
- QVERIFY(viewRepaints == smallChild->repaints);
- QVERIFY(viewRepaints == smallerGrandChild->repaints);
+ QCOMPARE(viewRepaints, bigParent->repaints);
+ QCOMPARE(viewRepaints, smallChild->repaints);
+ QCOMPARE(viewRepaints, smallerGrandChild->repaints);
// Scaling should cause a repaint of big items only.
view.scale(0.1, 0.1);
@@ -4764,8 +4749,8 @@ void tst_QGraphicsScene::minimumRenderSize()
QTRY_VERIFY(view.repaints > viewRepaints);
viewRepaints = view.repaints;
- QVERIFY(viewRepaints == bigParent->repaints);
- QVERIFY(viewRepaints == smallChild->repaints);
+ QCOMPARE(viewRepaints, bigParent->repaints);
+ QCOMPARE(viewRepaints, smallChild->repaints);
QVERIFY(smallChild->repaints > smallerGrandChild->repaints);
// Scaling further should cause even fewer items to be repainted
@@ -4775,7 +4760,7 @@ void tst_QGraphicsScene::minimumRenderSize()
QTRY_VERIFY(view.repaints > viewRepaints);
viewRepaints = view.repaints;
- QVERIFY(viewRepaints == bigParent->repaints);
+ QCOMPARE(viewRepaints, bigParent->repaints);
QVERIFY(bigParent->repaints > smallChild->repaints);
QVERIFY(smallChild->repaints > smallerGrandChild->repaints);
}
diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/BLACKLIST b/tests/auto/widgets/graphicsview/qgraphicsview/BLACKLIST
index be7a7e398b..3cba8bad7e 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsview/BLACKLIST
+++ b/tests/auto/widgets/graphicsview/qgraphicsview/BLACKLIST
@@ -1,4 +1,18 @@
[task255529_transformationAnchorMouseAndViewportMargins]
-ubuntu-14.04
+xcb
[cursor]
-ubuntu-14.04
+xcb
+[cursor2]
+xcb
+[rubberBandExtendSelection]
+xcb
+[rotated_rubberBand]
+xcb
+[sendEvent]
+xcb
+[forwardMousePress]
+xcb
+[hoverLeave]
+xcb
+[resizeAnchor]
+xcb
diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
index d1d4c1ab86..6db4295286 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
@@ -3525,7 +3525,7 @@ void tst_QGraphicsView::embeddedViews()
v2->QWidget::render(&actual);
QTransform b = item->transform;
- QVERIFY(a == b);
+ QCOMPARE(a, b);
delete v1;
}
diff --git a/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp b/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp
index 9b92c34fb5..ec2203e615 100644
--- a/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp
@@ -182,14 +182,6 @@ private slots:
void QTBUG_45867_send_itemChildAddedChange_to_parent();
};
-
-static void sendMouseMove(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::NoButton, Qt::MouseButtons buttons = 0)
-{
- QTest::mouseMove(widget, point);
- QMouseEvent event(QEvent::MouseMove, point, button, buttons, 0);
- QApplication::sendEvent(widget, &event);
-}
-
// Subclass that exposes the protected functions.
class SubQGraphicsWidget : public QGraphicsWidget {
public:
@@ -197,7 +189,7 @@ public:
: QGraphicsWidget(parent, windowFlags), eventCount(0)
{ }
- void initStyleOption(QStyleOption *option)
+ void initStyleOption(QStyleOption *option) const
{ QGraphicsWidget::initStyleOption(option); }
void call_changeEvent(QEvent* event)
@@ -1110,8 +1102,8 @@ void tst_QGraphicsWidget::initStyleOption()
{
QGraphicsScene scene;
QGraphicsView view(&scene);
+ view.resize(300, 300);
view.show();
- QApplication::setActiveWindow(&view);
QVERIFY(QTest::qWaitForWindowActive(&view));
view.setAlignment(Qt::AlignTop | Qt::AlignLeft);
@@ -1133,10 +1125,8 @@ void tst_QGraphicsWidget::initStyleOption()
}
QFETCH(bool, underMouse);
if (underMouse) {
- view.resize(300, 300);
- view.show();
- QVERIFY(QTest::qWaitForWindowActive(&view));
- sendMouseMove(view.viewport(), view.mapFromScene(widget->mapToScene(widget->boundingRect().center())));
+ QCursor::setPos(view.viewport()->mapToGlobal(view.mapFromScene(widget->mapToScene(widget->boundingRect().center()))));
+ QTest::qWait(100);
}
QFETCH(QPalette, palette);
diff --git a/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp b/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp
index eed38752d9..fac3f5857b 100644
--- a/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp
+++ b/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp
@@ -1036,7 +1036,7 @@ void tst_QAbstractItemView::dragAndDropOnChild()
++successes;
}
- QVERIFY(successes == 0);
+ QCOMPARE(successes, 0);
}
#endif // 0
@@ -1214,7 +1214,7 @@ void tst_QAbstractItemView::setCurrentIndex()
view->setModel(model);
view->setCurrentIndex(model->index(0,0));
- QVERIFY(view->currentIndex() == model->index(0,0));
+ QCOMPARE(view->currentIndex(), model->index(0,0));
view->setCurrentIndex(model->index(1,0));
QVERIFY(view->currentIndex() == model->index(result ? 1 : 0,0));
}
diff --git a/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp b/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp
index f5e6facaad..6645da727c 100644
--- a/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp
+++ b/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp
@@ -292,7 +292,7 @@ void tst_QColumnView::grips()
for (int i = 0 ; i < list.count(); ++i) {
if (QAbstractItemView *view = qobject_cast<QAbstractItemView*>(list.at(i))) {
if (view->isVisible())
- QVERIFY(view->cornerWidget() == 0);
+ QVERIFY(!view->cornerWidget());
}
}
}
@@ -587,7 +587,7 @@ void tst_QColumnView::selectAll()
QVERIFY(view.selectionModel()->selectedIndexes().count() > 0);
view.setCurrentIndex(QModelIndex());
- QVERIFY(view.selectionModel()->selectedIndexes().count() == 0);
+ QCOMPARE(view.selectionModel()->selectedIndexes().count(), 0);
}
void tst_QColumnView::clicked()
diff --git a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
index 21e4b82366..7e73c19539 100644
--- a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
+++ b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
@@ -403,7 +403,7 @@ void tst_QHeaderView::init()
view = new QHeaderView(Qt::Vertical,topLevel);
// Some initial value tests before a model is added
QCOMPARE(view->length(), 0);
- QVERIFY(view->sizeHint() == QSize(0,0));
+ QCOMPARE(view->sizeHint(), QSize(0,0));
QCOMPARE(view->sectionSizeHint(0), -1);
/*
@@ -925,9 +925,9 @@ void tst_QHeaderView::moveSection()
QFETCH(QList<int>, logical);
QFETCH(int, count);
- QVERIFY(from.count() == to.count());
- QVERIFY(from.count() == moved.count());
- QVERIFY(view->count() == logical.count());
+ QCOMPARE(from.count(), to.count());
+ QCOMPARE(from.count(), moved.count());
+ QCOMPARE(view->count(), logical.count());
QSignalSpy spy1(view, SIGNAL(sectionMoved(int,int,int)));
QCOMPARE(view->sectionsMoved(), false);
@@ -1370,15 +1370,15 @@ void tst_QHeaderView::unhideSection()
QCOMPARE(view->sectionsHidden(), false);
view->setSectionHidden(0, true);
QCOMPARE(view->sectionsHidden(), true);
- QVERIFY(view->sectionSize(0) == 0);
+ QCOMPARE(view->sectionSize(0), 0);
view->setSectionResizeMode(QHeaderView::Interactive);
view->setSectionHidden(0, false);
QVERIFY(view->sectionSize(0) > 0);
view->setSectionHidden(0, true);
- QVERIFY(view->sectionSize(0) == 0);
+ QCOMPARE(view->sectionSize(0), 0);
view->setSectionHidden(0, true);
- QVERIFY(view->sectionSize(0) == 0);
+ QCOMPARE(view->sectionSize(0), 0);
view->setSectionResizeMode(QHeaderView::Stretch);
view->setSectionHidden(0, false);
QVERIFY(view->sectionSize(0) > 0);
@@ -1645,7 +1645,7 @@ void tst_QHeaderView::saveRestore()
QByteArray s2 = h2.saveState();
- QVERIFY(s1 == s2);
+ QCOMPARE(s1, s2);
QVERIFY(!h2.restoreState(QByteArrayLiteral("Garbage")));
// QTBUG-40462
@@ -1659,7 +1659,7 @@ void tst_QHeaderView::saveRestore()
int sectionItemsLengthTotal = 0;
for (int i = 0; i < h2.count(); ++i)
sectionItemsLengthTotal += h2.sectionSize(i);
- QVERIFY(sectionItemsLengthTotal == h2.length());
+ QCOMPARE(sectionItemsLengthTotal, h2.length());
// Buggy setting where sum(sectionItems) != length. Check false is returned and this corrupted
// state isn't restored
@@ -1676,8 +1676,8 @@ void tst_QHeaderView::saveRestore()
// Check setting is correctly recognized as corrupted
QVERIFY(!h2.restoreState(settings_buggy_length));
// Check nothing has been actually restored
- QVERIFY(h2.length() == old_length);
- QVERIFY(h2.saveState() == old_state);
+ QCOMPARE(h2.length(), old_length);
+ QCOMPARE(h2.saveState(), old_state);
}
void tst_QHeaderView::defaultSectionSizeTest()
@@ -1699,7 +1699,7 @@ void tst_QHeaderView::defaultSectionSizeTest()
// no hidden Sections
hv->resizeSection(1, 0);
hv->setDefaultSectionSize(defaultSize);
- QVERIFY(hv->sectionSize(1) == defaultSize);
+ QCOMPARE(hv->sectionSize(1), defaultSize);
// with hidden sections
hv->resizeSection(1, 0);
@@ -2277,7 +2277,7 @@ void tst_QHeaderView::QTBUG14242_hideSectionAutoSize()
for (int u = 0; u < hv->count(); ++u)
calced_length += hv->sectionSize(u);
- QVERIFY(calced_length == afterlength);
+ QCOMPARE(calced_length, afterlength);
}
void tst_QHeaderView::ensureNoIndexAtLength()
@@ -2286,9 +2286,9 @@ void tst_QHeaderView::ensureNoIndexAtLength()
QStandardItemModel amodel(4, 4);
qtv.setModel(&amodel);
QHeaderView *hv = qtv.verticalHeader();
- QVERIFY(hv->visualIndexAt(hv->length()) == -1);
+ QCOMPARE(hv->visualIndexAt(hv->length()), -1);
hv->resizeSection(hv->count() - 1, 0);
- QVERIFY(hv->visualIndexAt(hv->length()) == -1);
+ QCOMPARE(hv->visualIndexAt(hv->length()), -1);
}
void tst_QHeaderView::offsetConsistent()
@@ -2307,7 +2307,7 @@ void tst_QHeaderView::offsetConsistent()
hv->hideSection(sectionToHide);
hv->setOffsetToSectionPosition(150);
int offset2 = hv->offset();
- QVERIFY(offset1 == offset2);
+ QCOMPARE(offset1, offset2);
// Ensure that hidden indexes (still) is considered.
hv->resizeSection(sectionToHide, hv->sectionSize(200) * 2);
hv->setOffsetToSectionPosition(800);
@@ -2600,8 +2600,8 @@ void tst_QHeaderView::logicalIndexAtTest()
//qDebug() << "logicalIndexAtTest" << check1 << check2;
const int precalced_check1 = 106327;
const int precalced_check2 = 29856418;
- QVERIFY(precalced_check1 == check1);
- QVERIFY(precalced_check2 == check2);
+ QCOMPARE(precalced_check1, check1);
+ QCOMPARE(precalced_check2, check2);
const int precalced_results[] = { 1145298384, -1710423344, -650981936, 372919464, -1544372176, -426463328, 12124 };
calculateAndCheck(__LINE__, precalced_results);
@@ -2628,8 +2628,8 @@ void tst_QHeaderView::visualIndexAtTest()
//qDebug() << "visualIndexAtTest" << check1 << check2;
const int precalced_check1 = 72665;
const int precalced_check2 = 14015890;
- QVERIFY(precalced_check1 == check1);
- QVERIFY(precalced_check2 == check2);
+ QCOMPARE(precalced_check1, check1);
+ QCOMPARE(precalced_check2, check2);
const int precalced_results[] = { 1145298384, -1710423344, -1457520212, 169223959, 557466160, -324939600, 5453 };
calculateAndCheck(__LINE__, precalced_results);
diff --git a/tests/auto/widgets/itemviews/qitemdelegate/tst_qitemdelegate.cpp b/tests/auto/widgets/itemviews/qitemdelegate/tst_qitemdelegate.cpp
index 439eeff005..25f27cb0c7 100644
--- a/tests/auto/widgets/itemviews/qitemdelegate/tst_qitemdelegate.cpp
+++ b/tests/auto/widgets/itemviews/qitemdelegate/tst_qitemdelegate.cpp
@@ -804,9 +804,9 @@ void tst_QItemDelegate::dateTimeEditor()
dateTimeEditor->setTime(time.addSecs(600));
widget.clearFocus();
- QVERIFY(item1->data(Qt::EditRole).userType() == QMetaType::QTime);
- QVERIFY(item2->data(Qt::EditRole).userType() == QMetaType::QDate);
- QVERIFY(item3->data(Qt::EditRole).userType() == QMetaType::QDateTime);
+ QCOMPARE(item1->data(Qt::EditRole).userType(), int(QMetaType::QTime));
+ QCOMPARE(item2->data(Qt::EditRole).userType(), int(QMetaType::QDate));
+ QCOMPARE(item3->data(Qt::EditRole).userType(), int(QMetaType::QDateTime));
}
// A delegate where we can either enforce a certain widget or use the standard widget.
@@ -901,9 +901,9 @@ void tst_QItemDelegate::dateAndTimeEditorTest2()
s.setData(i1, datetime2);
editor = w.fastEdit(i1);
timeEdit = qobject_cast<QTimeEdit*>(editor);
- QVERIFY(timeEdit == 0);
+ QVERIFY(!timeEdit);
dateEdit = qobject_cast<QDateEdit*>(editor);
- QVERIFY(dateEdit == 0);
+ QVERIFY(!dateEdit);
dateTimeEdit = qobject_cast<QDateTimeEdit*>(editor);
QVERIFY(dateTimeEdit);
QCOMPARE(dateTimeEdit->dateTime(), datetime2);
@@ -1154,7 +1154,7 @@ void tst_QItemDelegate::editorEvent_data()
QTest::newRow("unchecked, tristate, release")
<< (int)(Qt::Unchecked)
- << (int)(defaultFlags | Qt::ItemIsTristate)
+ << (int)(defaultFlags | Qt::ItemIsAutoTristate)
<< true
<< (int)(QEvent::MouseButtonRelease)
<< (int)(Qt::LeftButton)
@@ -1163,7 +1163,7 @@ void tst_QItemDelegate::editorEvent_data()
QTest::newRow("partially checked, tristate, release")
<< (int)(Qt::PartiallyChecked)
- << (int)(defaultFlags | Qt::ItemIsTristate)
+ << (int)(defaultFlags | Qt::ItemIsAutoTristate)
<< true
<< (int)(QEvent::MouseButtonRelease)
<< (int)(Qt::LeftButton)
@@ -1172,7 +1172,7 @@ void tst_QItemDelegate::editorEvent_data()
QTest::newRow("checked, tristate, release")
<< (int)(Qt::Checked)
- << (int)(defaultFlags | Qt::ItemIsTristate)
+ << (int)(defaultFlags | Qt::ItemIsAutoTristate)
<< true
<< (int)(QEvent::MouseButtonRelease)
<< (int)(Qt::LeftButton)
diff --git a/tests/auto/widgets/itemviews/qitemview/tst_qitemview.cpp b/tests/auto/widgets/itemviews/qitemview/tst_qitemview.cpp
index 3a6f1f933d..8fd86ea467 100644
--- a/tests/auto/widgets/itemviews/qitemview/tst_qitemview.cpp
+++ b/tests/auto/widgets/itemviews/qitemview/tst_qitemview.cpp
@@ -483,6 +483,7 @@ void tst_QItemView::spider()
view->setHorizontalScrollMode((QAbstractItemView::ScrollMode)hscroll);
view->setModel(treeModel);
view->show();
+ QVERIFY(QTest::qWaitForWindowActive(view));
#if defined(Q_OS_WINCE)
srandom(0);
#else
@@ -551,7 +552,7 @@ void tst_QItemView::visualRect()
QFETCH(bool, displays);
if (!displays){
- QVERIFY(view->visualRect(topIndex) == QRect());
+ QCOMPARE(view->visualRect(topIndex), QRect());
return;
}
@@ -559,15 +560,15 @@ void tst_QItemView::visualRect()
view->show();
QVERIFY(view->visualRect(topIndex) != QRect());
- QVERIFY(topIndex == view->indexAt(view->visualRect(topIndex).center()));
- QVERIFY(topIndex == view->indexAt(view->visualRect(topIndex).bottomLeft()));
- QVERIFY(topIndex == view->indexAt(view->visualRect(topIndex).bottomRight()));
- QVERIFY(topIndex == view->indexAt(view->visualRect(topIndex).topLeft()));
- QVERIFY(topIndex == view->indexAt(view->visualRect(topIndex).topRight()));
+ QCOMPARE(topIndex, view->indexAt(view->visualRect(topIndex).center()));
+ QCOMPARE(topIndex, view->indexAt(view->visualRect(topIndex).bottomLeft()));
+ QCOMPARE(topIndex, view->indexAt(view->visualRect(topIndex).bottomRight()));
+ QCOMPARE(topIndex, view->indexAt(view->visualRect(topIndex).topLeft()));
+ QCOMPARE(topIndex, view->indexAt(view->visualRect(topIndex).topRight()));
testViews->hideIndexes(view);
QModelIndex hiddenIndex = treeModel->index(1, 0);
- QVERIFY(view->visualRect(hiddenIndex) == QRect());
+ QCOMPARE(view->visualRect(hiddenIndex), QRect());
}
void tst_QItemView::walkScreen(QAbstractItemView *view)
@@ -615,7 +616,7 @@ void walkIndex(QModelIndex index, QAbstractItemView *view)
if (view->indexAt(point) != index) {
qDebug() << "index" << index << "visualRect" << visualRect << point << view->indexAt(point);
}
- QVERIFY(view->indexAt(point) == index);
+ QCOMPARE(view->indexAt(point), index);
}
}
diff --git a/tests/auto/widgets/itemviews/qlistview/qlistview.pro b/tests/auto/widgets/itemviews/qlistview/qlistview.pro
index 0623fc8ede..509303b62e 100644
--- a/tests/auto/widgets/itemviews/qlistview/qlistview.pro
+++ b/tests/auto/widgets/itemviews/qlistview/qlistview.pro
@@ -3,3 +3,4 @@ TARGET = tst_qlistview
QT += widgets gui-private widgets-private core-private testlib
SOURCES += tst_qlistview.cpp
win32:!wince:!winrt: LIBS += -luser32
+linux*: CONFIG += insignificant_test # Crashes
diff --git a/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp b/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp
index 244af1316a..fc671fdc9f 100644
--- a/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp
+++ b/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp
@@ -38,6 +38,7 @@
#include <qapplication.h>
#include <qlistview.h>
#include <private/qlistview_p.h>
+#include <private/qcoreapplication_p.h>
#include <qlistwidget.h>
#include <qitemdelegate.h>
#include <qstandarditemmodel.h>
@@ -149,6 +150,7 @@ private slots:
void testScrollToWithHidden();
void testViewOptions();
void taskQTBUG_39902_mutualScrollBars();
+ void horizontalScrollingByVerticalWheelEvents();
};
// Testing get/set functions
@@ -1208,7 +1210,7 @@ void tst_QListView::scrollTo()
list << "Short item";
model.setStringList(list);
lv.setModel(&model);
- lv.setFixedSize(100, 200);
+ lv.setFixedSize(110, 200);
topLevel.show();
QVERIFY(QTest::qWaitForWindowExposed(&topLevel));
@@ -2423,5 +2425,52 @@ void tst_QListView::taskQTBUG_39902_mutualScrollBars()
QTRY_VERIFY(!view->verticalScrollBar()->isVisible());
}
+void tst_QListView::horizontalScrollingByVerticalWheelEvents()
+{
+ QListView lv;
+ lv.setWrapping(true);
+
+ TestDelegate *delegate = new TestDelegate(&lv);
+ delegate->m_sizeHint = QSize(100, 100);
+ lv.setItemDelegate(delegate);
+
+ QtTestModel model;
+ model.colCount = 1;
+ model.rCount = 100;
+
+ lv.setModel(&model);
+
+ lv.resize(300, 300);
+ lv.show();
+ QTest::qWaitForWindowExposed(&lv);
+
+ QPoint globalPos = lv.geometry().center();
+ QPoint pos = lv.viewport()->geometry().center();
+
+ QWheelEvent wheelDownEvent(pos, globalPos, QPoint(0, 0), QPoint(0, -120), -120, Qt::Vertical, 0, 0);
+ QWheelEvent wheelUpEvent(pos, globalPos, QPoint(0, 0), QPoint(0, 120), 120, Qt::Vertical, 0, 0);
+ QWheelEvent wheelLeftDownEvent(pos, globalPos, QPoint(0, 0), QPoint(120, -120), -120, Qt::Vertical, 0, 0);
+
+ int hValue = lv.horizontalScrollBar()->value();
+ QApplication::sendEvent(lv.viewport(), &wheelDownEvent);
+ QVERIFY(lv.horizontalScrollBar()->value() > hValue);
+
+ QApplication::sendEvent(lv.viewport(), &wheelUpEvent);
+ QCOMPARE(lv.horizontalScrollBar()->value(), hValue);
+
+ QApplication::sendEvent(lv.viewport(), &wheelLeftDownEvent);
+ QCOMPARE(lv.horizontalScrollBar()->value(), hValue);
+
+ // ensure that vertical wheel events are not converted when vertical
+ // scroll bar is not visible but vertical scrolling is possible
+ lv.setWrapping(false);
+ lv.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ QApplication::processEvents();
+
+ int vValue = lv.verticalScrollBar()->value();
+ QApplication::sendEvent(lv.viewport(), &wheelDownEvent);
+ QVERIFY(lv.verticalScrollBar()->value() > vValue);
+}
+
QTEST_MAIN(tst_QListView)
#include "tst_qlistview.moc"
diff --git a/tests/auto/widgets/itemviews/qlistwidget/tst_qlistwidget.cpp b/tests/auto/widgets/itemviews/qlistwidget/tst_qlistwidget.cpp
index dcbdbe824a..ecf72613da 100644
--- a/tests/auto/widgets/itemviews/qlistwidget/tst_qlistwidget.cpp
+++ b/tests/auto/widgets/itemviews/qlistwidget/tst_qlistwidget.cpp
@@ -427,9 +427,9 @@ void tst_QListWidget::currentItem()
// actual test
QModelIndex currentIndex = testWidget->selectionModel()->currentIndex();
if (currentIndex.isValid())
- QVERIFY(testWidget->currentItem() == testWidget->item(currentIndex.row()));
+ QCOMPARE(testWidget->currentItem(), testWidget->item(currentIndex.row()));
else
- QVERIFY(testWidget->currentItem() == (QListWidgetItem*)0);
+ QCOMPARE(testWidget->currentItem(), (QListWidgetItem*)0);
}
void tst_QListWidget::currentRow()
@@ -742,7 +742,7 @@ void tst_QListWidget::selectedItems()
QFETCH(IntList, selectedRows);
QFETCH(IntList, expectedRows);
- QVERIFY(testWidget->count() == 0);
+ QCOMPARE(testWidget->count(), 0);
//insert items
for (int i=0; i<itemCount; ++i)
@@ -1159,7 +1159,7 @@ void tst_QListWidget::setData()
QFETCH(int, expectedSignalCount);
qRegisterMetaType<QListWidgetItem *>("QListWidgetItem*");
- QVERIFY(roles.count() == values.count());
+ QCOMPARE(roles.count(), values.count());
for (int manipulateModel=0; manipulateModel<2; ++manipulateModel) {
testWidget->clear();
@@ -1711,7 +1711,7 @@ void tst_QListWidget::mimeData()
QVERIFY(data->hasFormat(format));
QVERIFY(data2->hasFormat(format));
- QVERIFY(data->data(format) == data2->data(format));
+ QCOMPARE(data->data(format), data2->data(format));
delete data;
delete data2;
diff --git a/tests/auto/widgets/itemviews/qtableview/BLACKLIST b/tests/auto/widgets/itemviews/qtableview/BLACKLIST
index fc231a4e30..329010a86e 100644
--- a/tests/auto/widgets/itemviews/qtableview/BLACKLIST
+++ b/tests/auto/widgets/itemviews/qtableview/BLACKLIST
@@ -1,2 +1,4 @@
[moveCursorBiggerJump]
osx
+[resizeColumnsToContents]
+ubuntu-14.04
diff --git a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
index 75f77f8107..e5abd6bc46 100644
--- a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
+++ b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
@@ -2249,11 +2249,11 @@ void tst_QTableView::resizeColumnsToContents_data()
QTest::addColumn<int>("rowHeight");
QTest::addColumn<int>("columnWidth");
- QTest::newRow("10x10 grid shown 40x40")
- << 10 << 10 << false << 40 << 40 << 40 << 40;
+ QTest::newRow("10x10 grid not shown 60x60")
+ << 10 << 10 << false << 60 << 60 << 60 << 60;
- QTest::newRow("10x10 grid not shown 40x40")
- << 10 << 10 << true << 40 << 40 << 41 << 41;
+ QTest::newRow("10x10 grid shown 60x60")
+ << 10 << 10 << true << 60 << 60 << 61 << 61;
}
void tst_QTableView::resizeColumnsToContents()
@@ -4051,9 +4051,9 @@ void tst_QTableView::mouseWheel()
QWheelEvent verticalEvent(pos, delta, 0, 0, Qt::Vertical);
QWheelEvent horizontalEvent(pos, delta, 0, 0, Qt::Horizontal);
QApplication::sendEvent(view.viewport(), &horizontalEvent);
- QVERIFY(qAbs(view.horizontalScrollBar()->value() - horizontalPositon) < 10);
+ QVERIFY(qAbs(view.horizontalScrollBar()->value() - horizontalPositon) < 15);
QApplication::sendEvent(view.viewport(), &verticalEvent);
- QVERIFY(qAbs(view.verticalScrollBar()->value() - verticalPosition) < 10);
+ QVERIFY(qAbs(view.verticalScrollBar()->value() - verticalPosition) < 15);
}
#endif // !QT_NO_WHEELEVENT
diff --git a/tests/auto/widgets/itemviews/qtablewidget/tst_qtablewidget.cpp b/tests/auto/widgets/itemviews/qtablewidget/tst_qtablewidget.cpp
index 36bc23910c..6d2b2ea964 100644
--- a/tests/auto/widgets/itemviews/qtablewidget/tst_qtablewidget.cpp
+++ b/tests/auto/widgets/itemviews/qtablewidget/tst_qtablewidget.cpp
@@ -196,9 +196,9 @@ void tst_QTableWidget::clearContents()
{
QTableWidgetItem *item = new QTableWidgetItem("test");
testWidget->setHorizontalHeaderItem(0, item);
- QVERIFY(testWidget->horizontalHeaderItem(0) == item);
+ QCOMPARE(testWidget->horizontalHeaderItem(0), item);
testWidget->clearContents();
- QVERIFY(testWidget->horizontalHeaderItem(0) == item);
+ QCOMPARE(testWidget->horizontalHeaderItem(0), item);
}
void tst_QTableWidget::clear()
@@ -1559,7 +1559,7 @@ void tst_QTableWidget::mimeData()
QVERIFY(data->hasFormat(format));
QVERIFY(data2->hasFormat(format));
- QVERIFY(data->data(format) == data2->data(format));
+ QCOMPARE(data->data(format), data2->data(format));
delete data;
delete data2;
diff --git a/tests/auto/widgets/itemviews/qtreeview/qtreeview.pro b/tests/auto/widgets/itemviews/qtreeview/qtreeview.pro
index 3abd58e73d..e8406dab7b 100644
--- a/tests/auto/widgets/itemviews/qtreeview/qtreeview.pro
+++ b/tests/auto/widgets/itemviews/qtreeview/qtreeview.pro
@@ -4,3 +4,5 @@ QT += widgets testlib
QT += widgets-private gui-private core-private
SOURCES += tst_qtreeview.cpp
HEADERS += ../../../../shared/fakedirmodel.h
+
+win32: CONFIG += insignificant_test
diff --git a/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp b/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp
index 340637513c..4edf5d1a3b 100644
--- a/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp
+++ b/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp
@@ -3657,7 +3657,7 @@ void tst_QTreeView::task202039_closePersistentEditor()
QVERIFY(view.indexWidget(current));
view.closePersistentEditor(current);
- QVERIFY(view.indexWidget(current) == 0);
+ QVERIFY(!view.indexWidget(current));
//here was the bug: closing the persistent editor would not reset the state
//and it was impossible to go into editinon again
diff --git a/tests/auto/widgets/itemviews/qtreewidget/tst_qtreewidget.cpp b/tests/auto/widgets/itemviews/qtreewidget/tst_qtreewidget.cpp
index 5c881369a0..727bc41478 100644
--- a/tests/auto/widgets/itemviews/qtreewidget/tst_qtreewidget.cpp
+++ b/tests/auto/widgets/itemviews/qtreewidget/tst_qtreewidget.cpp
@@ -1037,7 +1037,7 @@ void tst_QTreeWidget::checkState()
QCOMPARE(firstChild->checkState(0), Qt::Checked);
QCOMPARE(seccondChild->checkState(0), Qt::Unchecked);
- item->setFlags(item->flags()|Qt::ItemIsTristate);
+ item->setFlags(item->flags()|Qt::ItemIsAutoTristate);
QCOMPARE(item->checkState(0), Qt::PartiallyChecked);
QCOMPARE(firstChild->checkState(0), Qt::Checked);
QCOMPARE(seccondChild->checkState(0), Qt::Unchecked);
@@ -1586,7 +1586,7 @@ void tst_QTreeWidget::scrollToItem()
testWidget->setHeaderLabels(QStringList() << "foo");
testWidget->scrollToItem(search);
- QVERIFY(search->text(0) == "111");
+ QCOMPARE(search->text(0), QLatin1String("111"));
bar = search->parent();
QVERIFY(testWidget->isItemExpanded(bar));
@@ -2287,7 +2287,7 @@ void tst_QTreeWidget::insertExpandedItemsWithSorting()
QCOMPARE(parent->childCount(), childText.count());
QVERIFY(parent->isExpanded());
}
- QVERIFY(tree.model()->rowCount() == parentText.count());
+ QCOMPARE(tree.model()->rowCount(), parentText.count());
// verify that the items are still expanded
foreach (QTreeWidgetItem *item, items) {
@@ -2659,7 +2659,7 @@ void tst_QTreeWidget::sortedIndexOfChild()
tw.sortItems(0, (Qt::SortOrder)sortOrder);
tw.expandAll();
- QVERIFY(itms.count() == expectedIndexes.count());
+ QCOMPARE(itms.count(), expectedIndexes.count());
for (int j = 0; j < expectedIndexes.count(); ++j)
QCOMPARE(top->indexOfChild(itms.at(j)), expectedIndexes.at(j));
}
@@ -3155,11 +3155,11 @@ void tst_QTreeWidget::setSelectionModel()
void tst_QTreeWidget::task217309()
{
QTreeWidgetItem item;
- item.setFlags(item.flags() | Qt::ItemIsTristate);
+ item.setFlags(item.flags() | Qt::ItemIsAutoTristate);
QTreeWidgetItem subitem1;
- subitem1.setFlags(subitem1.flags() | Qt::ItemIsTristate);
+ subitem1.setFlags(subitem1.flags() | Qt::ItemIsAutoTristate);
QTreeWidgetItem subitem2;
- subitem2.setFlags(subitem2.flags() | Qt::ItemIsTristate);
+ subitem2.setFlags(subitem2.flags() | Qt::ItemIsAutoTristate);
item.addChild(&subitem1);
item.addChild(&subitem2);
subitem1.setCheckState(0, Qt::Checked);
@@ -3180,7 +3180,7 @@ void tst_QTreeWidget::nonEditableTristate()
QTreeWidget *tree = new QTreeWidget;
QTreeWidgetItem *item = new QTreeWidgetItem();
tree->insertTopLevelItem(0, item);
- item->setFlags(item->flags() | Qt::ItemIsTristate);
+ item->setFlags(item->flags() | Qt::ItemIsAutoTristate);
item->setCheckState(0, Qt::Unchecked);
QTreeWidgetItem *subitem1 = new QTreeWidgetItem(item);
subitem1->setCheckState(0, Qt::Unchecked);
@@ -3235,7 +3235,7 @@ void tst_QTreeWidget::setCurrentItemExpandsParent()
QTreeWidgetItem *i1 = new QTreeWidgetItem(&w, QStringList() << "parent");
QTreeWidgetItem *i2 = new QTreeWidgetItem(i1, QStringList() << "child");
QVERIFY(!i2->isExpanded());
- QVERIFY(w.currentItem() == 0);
+ QVERIFY(!w.currentItem());
w.setCurrentItem(i2);
QVERIFY(!i2->isExpanded());
QCOMPARE(w.currentItem(), i2);
diff --git a/tests/auto/widgets/itemviews/qtreewidgetitemiterator/tst_qtreewidgetitemiterator.cpp b/tests/auto/widgets/itemviews/qtreewidgetitemiterator/tst_qtreewidgetitemiterator.cpp
index 490f87a7ef..c52198fa2c 100644
--- a/tests/auto/widgets/itemviews/qtreewidgetitemiterator/tst_qtreewidgetitemiterator.cpp
+++ b/tests/auto/widgets/itemviews/qtreewidgetitemiterator/tst_qtreewidgetitemiterator.cpp
@@ -1112,13 +1112,13 @@ void tst_QTreeWidgetItemIterator::updateIfModifiedFromWidget()
delete item;
item = *it;
if (expecteditemIsNull) {
- QVERIFY(item == 0);
+ QVERIFY(!item);
} else {
QVERIFY(item);
QCOMPARE(item->text(0), expecteditemvalue);
item = *itRemove;
if (expectedUpdatedCurrent.isNull()) {
- QVERIFY(item == 0);
+ QVERIFY(!item);
} else {
QCOMPARE(item->text(0), expectedUpdatedCurrent);
}
diff --git a/tests/auto/widgets/kernel/qaction/BLACKLIST b/tests/auto/widgets/kernel/qaction/BLACKLIST
index f67a3c471e..1ad524fdbf 100644
--- a/tests/auto/widgets/kernel/qaction/BLACKLIST
+++ b/tests/auto/widgets/kernel/qaction/BLACKLIST
@@ -1,2 +1,2 @@
[setStandardKeys]
-ubuntu-14.04
+linux
diff --git a/tests/auto/widgets/kernel/qaction/tst_qaction.cpp b/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
index 897128d40e..71b55d71ea 100644
--- a/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
+++ b/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
@@ -242,7 +242,7 @@ void tst_QAction::setStandardKeys()
QList<QKeySequence> list;
act.setShortcuts(list);
act.setShortcuts(QKeySequence::Copy);
- QVERIFY(act.shortcut() == act.shortcuts().first());
+ QCOMPARE(act.shortcut(), act.shortcuts().first());
QList<QKeySequence> expected;
const QKeySequence ctrlC = QKeySequence(QStringLiteral("CTRL+C"));
diff --git a/tests/auto/widgets/kernel/qactiongroup/BLACKLIST b/tests/auto/widgets/kernel/qactiongroup/BLACKLIST
new file mode 100644
index 0000000000..fdc424b6ac
--- /dev/null
+++ b/tests/auto/widgets/kernel/qactiongroup/BLACKLIST
@@ -0,0 +1,2 @@
+[QTBUG_14292_filesystem]
+linux
diff --git a/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp b/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
index 8ce9941238..81e5542e91 100644
--- a/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
+++ b/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
@@ -42,6 +42,7 @@ class tst_QActionGroup : public QObject
Q_OBJECT
private slots:
+ void cleanup() { QVERIFY(QApplication::topLevelWidgets().isEmpty()); }
void enabledPropagation();
void visiblePropagation();
void exclusive();
@@ -223,7 +224,7 @@ void tst_QActionGroup::unCheckCurrentAction()
current->setChecked(false);
QVERIFY(!action1.isChecked());
QVERIFY(!action2.isChecked());
- QVERIFY(group.checkedAction() == 0);
+ QVERIFY(!group.checkedAction());
}
diff --git a/tests/auto/widgets/kernel/qapplication/BLACKLIST b/tests/auto/widgets/kernel/qapplication/BLACKLIST
new file mode 100644
index 0000000000..6abb1d9988
--- /dev/null
+++ b/tests/auto/widgets/kernel/qapplication/BLACKLIST
@@ -0,0 +1,4 @@
+[quitOnLastWindowClosed]
+osx-10.10
+[touchEventPropagation]
+xcb
diff --git a/tests/auto/widgets/kernel/qapplication/qapplication.pro b/tests/auto/widgets/kernel/qapplication/qapplication.pro
index 3d167827a3..5154c915cd 100644
--- a/tests/auto/widgets/kernel/qapplication/qapplication.pro
+++ b/tests/auto/widgets/kernel/qapplication/qapplication.pro
@@ -2,6 +2,5 @@ TEMPLATE = subdirs
SUBDIRS = desktopsettingsaware modal
-win32:!wince: SUBDIRS += wincmdline
test.depends += $$SUBDIRS
SUBDIRS += test
diff --git a/tests/auto/widgets/kernel/qapplication/test/BLACKLIST b/tests/auto/widgets/kernel/qapplication/test/BLACKLIST
new file mode 100644
index 0000000000..f4a9cb6166
--- /dev/null
+++ b/tests/auto/widgets/kernel/qapplication/test/BLACKLIST
@@ -0,0 +1,2 @@
+[quitOnLastWindowClosed]
+osx-10.10
diff --git a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp
index 84956d0a02..878136b4a0 100644
--- a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp
+++ b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp
@@ -62,6 +62,7 @@
#endif
#include <qpa/qwindowsysteminterface.h>
+#include <private/qhighdpiscaling_p.h>
#include "../../../qtest-config.h"
@@ -162,9 +163,6 @@ private slots:
void setAttribute();
- void windowsCommandLine_data();
- void windowsCommandLine();
-
void touchEventPropagation();
void qtbug_12673();
@@ -1160,7 +1158,7 @@ void tst_QApplication::sendPostedEvents()
QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
QPointer<SendPostedEventsTester> p = tester;
(void) app.exec();
- QVERIFY(p == 0);
+ QVERIFY(p.isNull());
}
void tst_QApplication::thread()
@@ -1178,8 +1176,8 @@ void tst_QApplication::thread()
// *before* the QApplication has a thread
QObject object;
QObject child(&object);
- QVERIFY(object.thread() == currentThread);
- QVERIFY(child.thread() == currentThread);
+ QCOMPARE(object.thread(), currentThread);
+ QCOMPARE(child.thread(), currentThread);
{
int argc = 0;
@@ -1209,8 +1207,8 @@ void tst_QApplication::thread()
QVERIFY(!currentThread->isFinished());
// should still have a thread
- QVERIFY(object.thread() == currentThread);
- QVERIFY(child.thread() == currentThread);
+ QCOMPARE(object.thread(), currentThread);
+ QCOMPARE(child.thread(), currentThread);
// do the test again, making sure that the thread is the same as
// before
@@ -1231,8 +1229,8 @@ void tst_QApplication::thread()
QVERIFY(!currentThread->isFinished());
// should still have a thread
- QVERIFY(object.thread() == currentThread);
- QVERIFY(child.thread() == currentThread);
+ QCOMPARE(object.thread(), currentThread);
+ QCOMPARE(child.thread(), currentThread);
QTestEventLoop::instance().enterLoop(1);
}
@@ -1246,8 +1244,8 @@ void tst_QApplication::thread()
QVERIFY(!currentThread->isFinished());
// should still have a thread
- QVERIFY(object.thread() == currentThread);
- QVERIFY(child.thread() == currentThread);
+ QCOMPARE(object.thread(), currentThread);
+ QCOMPARE(child.thread(), currentThread);
}
class DeleteLaterWidget : public QWidget
@@ -1561,9 +1559,9 @@ void tst_QApplication::focusChanged()
QCOMPARE(spy.at(0).count(), 2);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &le1);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == 0);
+ QCOMPARE(now, &le1);
+ QCOMPARE(now, QApplication::focusWidget());
+ QVERIFY(!old);
spy.clear();
QCOMPARE(spy.count(), 0);
@@ -1571,27 +1569,27 @@ void tst_QApplication::focusChanged()
QCOMPARE(spy.count(), 1);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &pb1);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &le1);
+ QCOMPARE(now, &pb1);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &le1);
spy.clear();
lb1.setFocus();
QCOMPARE(spy.count(), 1);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &lb1);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &pb1);
+ QCOMPARE(now, &lb1);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &pb1);
spy.clear();
lb1.clearFocus();
QCOMPARE(spy.count(), 1);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == 0);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &lb1);
+ QVERIFY(!now);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &lb1);
spy.clear();
QWidget parent2;
@@ -1608,9 +1606,9 @@ void tst_QApplication::focusChanged()
QVERIFY(spy.count() > 0); // one for deactivation, one for activation on Windows
old = qvariant_cast<QWidget*>(spy.at(spy.count()-1).at(0));
now = qvariant_cast<QWidget*>(spy.at(spy.count()-1).at(1));
- QVERIFY(now == &le2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == 0);
+ QCOMPARE(now, &le2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QVERIFY(!old);
spy.clear();
QTestKeyEvent tab(QTest::Press, Qt::Key_Tab, 0, 0);
@@ -1632,82 +1630,82 @@ void tst_QApplication::focusChanged()
tab.simulate(now);
if (!tabAllControls) {
- QVERIFY(spy.count() == 0);
- QVERIFY(now == QApplication::focusWidget());
+ QCOMPARE(spy.count(), 0);
+ QCOMPARE(now, QApplication::focusWidget());
} else {
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &pb2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &le2);
+ QCOMPARE(now, &pb2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &le2);
spy.clear();
}
if (!tabAllControls) {
- QVERIFY(spy.count() == 0);
- QVERIFY(now == QApplication::focusWidget());
+ QCOMPARE(spy.count(), 0);
+ QCOMPARE(now, QApplication::focusWidget());
} else {
tab.simulate(now);
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &le2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &pb2);
+ QCOMPARE(now, &le2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &pb2);
spy.clear();
}
if (!tabAllControls) {
- QVERIFY(spy.count() == 0);
- QVERIFY(now == QApplication::focusWidget());
+ QCOMPARE(spy.count(), 0);
+ QCOMPARE(now, QApplication::focusWidget());
} else {
backtab.simulate(now);
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &pb2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &le2);
+ QCOMPARE(now, &pb2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &le2);
spy.clear();
}
if (!tabAllControls) {
- QVERIFY(spy.count() == 0);
- QVERIFY(now == QApplication::focusWidget());
+ QCOMPARE(spy.count(), 0);
+ QCOMPARE(now, QApplication::focusWidget());
old = &pb2;
} else {
backtab.simulate(now);
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &le2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &pb2);
+ QCOMPARE(now, &le2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &pb2);
spy.clear();
}
click.simulate(old);
if (!(pb2.focusPolicy() & Qt::ClickFocus)) {
- QVERIFY(spy.count() == 0);
- QVERIFY(now == QApplication::focusWidget());
+ QCOMPARE(spy.count(), 0);
+ QCOMPARE(now, QApplication::focusWidget());
} else {
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &pb2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &le2);
+ QCOMPARE(now, &pb2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &le2);
spy.clear();
click.simulate(old);
QVERIFY(spy.count() > 0);
old = qvariant_cast<QWidget*>(spy.at(0).at(0));
now = qvariant_cast<QWidget*>(spy.at(0).at(1));
- QVERIFY(now == &le2);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &pb2);
+ QCOMPARE(now, &le2);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &pb2);
spy.clear();
}
@@ -1722,9 +1720,9 @@ void tst_QApplication::focusChanged()
else
old = qvariant_cast<QWidget*>(spy.at(spy.count()-2).at(0));
now = qvariant_cast<QWidget*>(spy.at(spy.count()-1).at(1));
- QVERIFY(now == &le1);
- QVERIFY(now == QApplication::focusWidget());
- QVERIFY(old == &le2);
+ QCOMPARE(now, &le1);
+ QCOMPARE(now, QApplication::focusWidget());
+ QCOMPARE(old, &le2);
spy.clear();
}
@@ -1933,39 +1931,6 @@ void tst_QApplication::setAttribute()
delete w;
}
-void tst_QApplication::windowsCommandLine_data()
-{
-#if defined(Q_OS_WIN)
- QTest::addColumn<QString>("args");
- QTest::addColumn<QString>("expected");
-
- QTest::newRow("hello world")
- << QString("Hello \"World\"")
- << QString("Hello \"World\"");
- QTest::newRow("sql")
- << QString("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PNR' AND TABLE_TYPE = 'VIEW' ORDER BY TABLE_NAME")
- << QString("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PNR' AND TABLE_TYPE = 'VIEW' ORDER BY TABLE_NAME");
-#endif
-}
-
-void tst_QApplication::windowsCommandLine()
-{
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
- QFETCH(QString, args);
- QFETCH(QString, expected);
-
- QProcess testProcess;
- const QString path = QStringLiteral("wincmdline/wincmdline");
- testProcess.start(path, QStringList(args));
- QVERIFY2(testProcess.waitForStarted(),
- qPrintable(QString::fromLatin1("Cannot start '%1': %2").arg(path, testProcess.errorString())));
- QVERIFY(testProcess.waitForFinished(10000));
- QByteArray error = testProcess.readAllStandardError();
- QString procError(error);
- QCOMPARE(procError, expected);
-#endif
-}
-
class TouchEventPropagationTestWidget : public QWidget
{
Q_OBJECT
@@ -2038,8 +2003,10 @@ void tst_QApplication::touchEventPropagation()
QVERIFY(QTest::qWaitForWindowExposed(&window));
// QPA always takes screen positions and since we map the TouchPoint back to QPA's structure first,
// we must ensure there is a screen position in the TouchPoint that maps to a local 0, 0.
- pressedTouchPoints[0].setScreenPos(window.mapToGlobal(QPoint(0, 0)));
- releasedTouchPoints[0].setScreenPos(window.mapToGlobal(QPoint(0, 0)));
+ const QPoint deviceGlobalPos =
+ QHighDpi::toNativePixels(window.mapToGlobal(QPoint(0, 0)), window.windowHandle()->screen());
+ pressedTouchPoints[0].setScreenPos(deviceGlobalPos);
+ releasedTouchPoints[0].setScreenPos(deviceGlobalPos);
QWindowSystemInterface::handleTouchEvent(window.windowHandle(),
0,
@@ -2092,8 +2059,10 @@ void tst_QApplication::touchEventPropagation()
widget.setObjectName("2. widget");
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
- pressedTouchPoints[0].setScreenPos(window.mapToGlobal(QPoint(50, 50)));
- releasedTouchPoints[0].setScreenPos(window.mapToGlobal(QPoint(50, 50)));
+ const QPoint deviceGlobalPos =
+ QHighDpi::toNativePixels(window.mapToGlobal(QPoint(50, 50)), window.windowHandle()->screen());
+ pressedTouchPoints[0].setScreenPos(deviceGlobalPos);
+ releasedTouchPoints[0].setScreenPos(deviceGlobalPos);
QWindowSystemInterface::handleTouchEvent(window.windowHandle(),
0,
diff --git a/tests/auto/widgets/kernel/qapplication/wincmdline/wincmdline.pro b/tests/auto/widgets/kernel/qapplication/wincmdline/wincmdline.pro
deleted file mode 100644
index 3e32a6798d..0000000000
--- a/tests/auto/widgets/kernel/qapplication/wincmdline/wincmdline.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-QT += widgets
-CONFIG -= app_bundle debug_and_release_target
-SOURCES += main.cpp
-DESTDIR = ./
-
diff --git a/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp b/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp
index 35a8636f0b..aeaf1e7bf0 100644
--- a/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp
+++ b/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp
@@ -48,17 +48,8 @@ class tst_QBoxLayout : public QObject
{
Q_OBJECT
-public:
- tst_QBoxLayout();
- virtual ~tst_QBoxLayout();
-
-public slots:
- void initTestCase();
- void cleanupTestCase();
- void init();
- void cleanup();
-
private slots:
+ void cleanup();
void insertSpacerItem();
void insertLayout();
void sizeHint();
@@ -120,34 +111,15 @@ int CustomLayoutStyle::pixelMetric(PixelMetric metric, const QStyleOption * opti
return QProxyStyle::pixelMetric(metric, option, widget);
}
-
-tst_QBoxLayout::tst_QBoxLayout()
-{
-}
-
-tst_QBoxLayout::~tst_QBoxLayout()
-{
-}
-
-void tst_QBoxLayout::initTestCase()
-{
-}
-
-void tst_QBoxLayout::cleanupTestCase()
-{
-}
-
-void tst_QBoxLayout::init()
-{
-}
-
void tst_QBoxLayout::cleanup()
{
+ QVERIFY(QApplication::topLevelWidgets().isEmpty());
}
void tst_QBoxLayout::insertSpacerItem()
{
- QWidget *window = new QWidget;
+ QWidget window;
+ window.setWindowTitle(QTest::currentTestFunction());
QSpacerItem *spacer1 = new QSpacerItem(20, 10, QSizePolicy::Expanding, QSizePolicy::Expanding);
QSpacerItem *spacer2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Expanding);
@@ -157,44 +129,43 @@ void tst_QBoxLayout::insertSpacerItem()
layout->addSpacerItem(spacer1);
layout->addWidget(new QLineEdit("Baaaaaaaaaaaaaaaaaaaaaaaaar"));
layout->insertSpacerItem(0, spacer2);
- window->setLayout(layout);
+ window.setLayout(layout);
- QVERIFY(layout->itemAt(0) == spacer2);
- QVERIFY(layout->itemAt(2) == spacer1);
+ QCOMPARE(layout->itemAt(0), spacer2);
+ QCOMPARE(layout->itemAt(2), spacer1);
- window->show();
+ window.show();
}
void tst_QBoxLayout::insertLayout()
{
- QWidget *window = new QWidget;
- QVBoxLayout *vbox = new QVBoxLayout(window);
- QVBoxLayout *dummyParentLayout = new QVBoxLayout;
+ QWidget window;
+ QVBoxLayout *vbox = new QVBoxLayout(&window);
+ QScopedPointer<QVBoxLayout> dummyParentLayout(new QVBoxLayout);
QHBoxLayout *subLayout = new QHBoxLayout;
dummyParentLayout->addLayout(subLayout);
- QCOMPARE(subLayout->parent(), dummyParentLayout);
+ QCOMPARE(subLayout->parent(), dummyParentLayout.data());
QCOMPARE(dummyParentLayout->count(), 1);
// add subLayout to another layout
QTest::ignoreMessage(QtWarningMsg, "QLayout::addChildLayout: layout \"\" already has a parent");
vbox->addLayout(subLayout);
QCOMPARE((subLayout->parent() == vbox), (vbox->count() == 1));
-
- delete dummyParentLayout;
- delete window;
}
void tst_QBoxLayout::sizeHint()
{
- QWidget *window = new QWidget;
+ QWidget window;
+ window.setWindowTitle(QTest::currentTestFunction());
QHBoxLayout *lay1 = new QHBoxLayout;
QHBoxLayout *lay2 = new QHBoxLayout;
QLabel *label = new QLabel("widget twooooooooooooooooooooooooooooooooooooooooooooooooooooooo");
lay2->addWidget(label);
lay1->addLayout(lay2);
- window->setLayout(lay1);
- window->show();
+ window.setLayout(lay1);
+ window.show();
+ QTest::qWaitForWindowExposed(&window);
label->setText("foooooooo baaaaaaar");
QSize sh = lay1->sizeHint();
QApplication::processEvents();
@@ -207,24 +178,26 @@ void tst_QBoxLayout::sizeHint()
void tst_QBoxLayout::sizeConstraints()
{
- QWidget *window = new QWidget;
+ QWidget window;
+ window.setWindowTitle(QTest::currentTestFunction());
QHBoxLayout *lay = new QHBoxLayout;
lay->addWidget(new QLabel("foooooooooooooooooooooooooooooooooooo"));
lay->addWidget(new QLabel("baaaaaaaaaaaaaaaaaaaaaaaaaaaaaar"));
lay->setSizeConstraint(QLayout::SetFixedSize);
- window->setLayout(lay);
- window->show();
- QApplication::processEvents();
- QSize sh = window->sizeHint();
+ window.setLayout(lay);
+ window.show();
+ QTest::qWaitForWindowExposed(&window);
+ QSize sh = window.sizeHint();
lay->takeAt(1);
- QVERIFY(sh.width() >= window->sizeHint().width() &&
- sh.height() >= window->sizeHint().height());
+ QVERIFY(sh.width() >= window.sizeHint().width() &&
+ sh.height() >= window.sizeHint().height());
}
void tst_QBoxLayout::setGeometry()
{
QWidget toplevel;
+ toplevel.setWindowTitle(QTest::currentTestFunction());
setFrameless(&toplevel);
QWidget w(&toplevel);
QVBoxLayout *lay = new QVBoxLayout;
@@ -247,33 +220,30 @@ void tst_QBoxLayout::setGeometry()
void tst_QBoxLayout::setStyleShouldChangeSpacing()
{
- QWidget *window = new QWidget;
- QHBoxLayout *hbox = new QHBoxLayout(window);
+ QWidget window;
+ window.setWindowTitle(QTest::currentTestFunction());
+ QHBoxLayout *hbox = new QHBoxLayout(&window);
QPushButton *pb1 = new QPushButton(tr("The spacing between this"));
QPushButton *pb2 = new QPushButton(tr("and this button should depend on the style of the parent widget"));;
pb1->setAttribute(Qt::WA_LayoutUsesWidgetRect);
pb2->setAttribute(Qt::WA_LayoutUsesWidgetRect);
hbox->addWidget(pb1);
hbox->addWidget(pb2);
- CustomLayoutStyle *style1 = new CustomLayoutStyle;
+ QScopedPointer<CustomLayoutStyle> style1(new CustomLayoutStyle);
style1->hspacing = 6;
- window->setStyle(style1);
- window->show();
+ window.setStyle(style1.data());
+ window.show();
+ QTest::qWaitForWindowExposed(&window);
- QTest::qWait(100);
int spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
QCOMPARE(spacing, 6);
- CustomLayoutStyle *style2 = new CustomLayoutStyle();
+ QScopedPointer<CustomLayoutStyle> style2(new CustomLayoutStyle());
style2->hspacing = 10;
- window->setStyle(style2);
+ window.setStyle(style2.data());
QTest::qWait(100);
spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
QCOMPARE(spacing, 10);
-
- delete window;
- delete style1;
- delete style2;
}
void tst_QBoxLayout::taskQTBUG_7103_minMaxWidthNotRespected()
@@ -287,6 +257,7 @@ void tst_QBoxLayout::taskQTBUG_7103_minMaxWidthNotRespected()
layout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::Expanding));
QWidget widget;
+ widget.setWindowTitle(QTest::currentTestFunction());
widget.setLayout(layout);
widget.show();
QVERIFY(QTest::qWaitForWindowExposed(&widget));
@@ -325,6 +296,7 @@ void tst_QBoxLayout::taskQTBUG_27420_takeAtShouldUnparentLayout()
void tst_QBoxLayout::taskQTBUG_40609_addingWidgetToItsOwnLayout(){
QWidget widget;
+ widget.setWindowTitle(QTest::currentTestFunction());
widget.setObjectName("347b469225a24a0ef05150a");
QVBoxLayout layout(&widget);
layout.setObjectName("ef9e2b42298e0e6420105bb");
@@ -340,6 +312,7 @@ void tst_QBoxLayout::taskQTBUG_40609_addingWidgetToItsOwnLayout(){
void tst_QBoxLayout::taskQTBUG_40609_addingLayoutToItself(){
QWidget widget;
+ widget.setWindowTitle(QTest::currentTestFunction());
widget.setObjectName("fe44e5cb6c08006597126a");
QVBoxLayout layout(&widget);
layout.setObjectName("cc751dd0f50f62b05a62da");
diff --git a/tests/auto/widgets/kernel/qdesktopwidget/tst_qdesktopwidget.cpp b/tests/auto/widgets/kernel/qdesktopwidget/tst_qdesktopwidget.cpp
index b717c1deb1..e94dfa5754 100644
--- a/tests/auto/widgets/kernel/qdesktopwidget/tst_qdesktopwidget.cpp
+++ b/tests/auto/widgets/kernel/qdesktopwidget/tst_qdesktopwidget.cpp
@@ -73,6 +73,7 @@ void tst_QDesktopWidget::init()
void tst_QDesktopWidget::cleanup()
{
+ QVERIFY(QApplication::topLevelWidgets().isEmpty());
}
void tst_QDesktopWidget::numScreens()
diff --git a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
index 8588df7afa..e1b494c9f1 100644
--- a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
+++ b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
@@ -60,17 +60,8 @@ class tst_QFormLayout : public QObject
{
Q_OBJECT
-public:
- tst_QFormLayout();
- ~tst_QFormLayout();
-
-public slots:
- void initTestCase();
- void cleanupTestCase();
- void init();
- void cleanup();
-
private slots:
+ void cleanup();
void rowCount();
void buddies();
void getItemPosition();
@@ -132,34 +123,15 @@ private slots:
};
-tst_QFormLayout::tst_QFormLayout()
-{
-}
-
-tst_QFormLayout::~tst_QFormLayout()
-{
-}
-
-void tst_QFormLayout::initTestCase()
-{
-}
-
-void tst_QFormLayout::cleanupTestCase()
-{
-}
-
-void tst_QFormLayout::init()
-{
-}
-
void tst_QFormLayout::cleanup()
{
+ QVERIFY(QApplication::topLevelWidgets().isEmpty());
}
void tst_QFormLayout::rowCount()
{
- QWidget *w = new QWidget;
- QFormLayout *fl = new QFormLayout(w);
+ QWidget w;
+ QFormLayout *fl = new QFormLayout(&w);
fl->addRow(tr("Label 1"), new QLineEdit);
fl->addRow(tr("Label 2"), new QLineEdit);
@@ -174,14 +146,12 @@ void tst_QFormLayout::rowCount()
QCOMPARE(fl->rowCount(), 6);
//TODO: remove items
-
- delete w;
}
void tst_QFormLayout::buddies()
{
- QWidget *w = new QWidget;
- QFormLayout *fl = new QFormLayout(w);
+ QWidget w;
+ QFormLayout *fl = new QFormLayout(&w);
//normal buddy case
QLineEdit *le = new QLineEdit;
@@ -195,23 +165,21 @@ void tst_QFormLayout::buddies()
QLineEdit *le2 = new QLineEdit;
fl->addRow(0, le2);
QWidget *label2 = fl->labelForField(le2);
- QVERIFY(label2 == 0);
+ QVERIFY(!label2);
//no label
QLineEdit *le3 = new QLineEdit;
fl->addRow(le3);
QWidget *label3 = fl->labelForField(le3);
- QVERIFY(label3 == 0);
+ QVERIFY(!label3);
//TODO: empty label?
-
- delete w;
}
void tst_QFormLayout::getItemPosition()
{
- QWidget *w = new QWidget;
- QFormLayout *fl = new QFormLayout(w);
+ QWidget w;
+ QFormLayout *fl = new QFormLayout(&w);
QList<QLabel*> labels;
QList<QLineEdit*> fields;
@@ -249,14 +217,12 @@ void tst_QFormLayout::getItemPosition()
QCOMPARE(row, 2);
QCOMPARE(role, QFormLayout::FieldRole);
}
-
- delete w;
}
void tst_QFormLayout::wrapping()
{
- QWidget *w = new QWidget;
- QFormLayout *fl = new QFormLayout(w);
+ QWidget w;
+ QFormLayout *fl = new QFormLayout(&w);
fl->setRowWrapPolicy(QFormLayout::WrapLongRows);
QLineEdit *le = new QLineEdit;
@@ -264,14 +230,13 @@ void tst_QFormLayout::wrapping()
le->setMinimumWidth(200);
fl->addRow(lbl, le);
- w->setFixedWidth(240);
- w->show();
+ w.setFixedWidth(240);
+ w.setWindowTitle(QTest::currentTestFunction());
+ w.show();
QCOMPARE(le->geometry().y() > lbl->geometry().y(), true);
//TODO: additional tests covering different wrapping cases
-
- delete w;
}
class CustomLayoutStyle : public QProxyStyle
@@ -309,12 +274,12 @@ int CustomLayoutStyle::pixelMetric(PixelMetric metric, const QStyleOption * opti
void tst_QFormLayout::spacing()
{
//TODO: confirm spacing behavior
- QWidget *w = new QWidget;
- CustomLayoutStyle *style = new CustomLayoutStyle;
+ QWidget w;
+ QScopedPointer<CustomLayoutStyle> style(new CustomLayoutStyle);
style->hspacing = 5;
style->vspacing = 10;
- w->setStyle(style);
- QFormLayout *fl = new QFormLayout(w);
+ w.setStyle(style.data());
+ QFormLayout *fl = new QFormLayout(&w);
QCOMPARE(style->hspacing, fl->horizontalSpacing());
QCOMPARE(style->vspacing, fl->verticalSpacing());
@@ -351,12 +316,10 @@ void tst_QFormLayout::spacing()
QCheckBox *checkBox = new QCheckBox(tr("Yes"));
fl->setWidget(0, QFormLayout::LabelRole, label);
fl->setWidget(1, QFormLayout::FieldRole, checkBox);
- w->resize(200, 100);
- w->show();
- QVERIFY(QTest::qWaitForWindowExposed(w));
-
- delete w;
- delete style;
+ w.resize(200, 100);
+ w.setWindowTitle(QTest::currentTestFunction());
+ w.show();
+ QVERIFY(QTest::qWaitForWindowExposed(&w));
}
void tst_QFormLayout::contentsRect()
@@ -366,6 +329,7 @@ void tst_QFormLayout::contentsRect()
QFormLayout form;
w.setLayout(&form);
form.addRow("Label", new QPushButton(&w));
+ w.setWindowTitle(QTest::currentTestFunction());
w.show();
QVERIFY(QTest::qWaitForWindowExposed(&w));
int l, t, r, b;
@@ -425,18 +389,18 @@ void tst_QFormLayout::setFormStyle()
#if 0 // QT_NO_STYLE_PLASTIQUE
widget.setStyle(new QPlastiqueStyle());
- QVERIFY(layout.labelAlignment() == Qt::AlignRight);
+ QCOMPARE(layout.labelAlignment(), Qt::AlignRight);
QVERIFY(layout.formAlignment() == (Qt::AlignLeft | Qt::AlignTop));
- QVERIFY(layout.fieldGrowthPolicy() == QFormLayout::ExpandingFieldsGrow);
- QVERIFY(layout.rowWrapPolicy() == QFormLayout::DontWrapRows);
+ QCOMPARE(layout.fieldGrowthPolicy(), QFormLayout::ExpandingFieldsGrow);
+ QCOMPARE(layout.rowWrapPolicy(), QFormLayout::DontWrapRows);
#endif
widget.setStyle(QStyleFactory::create("windows"));
- QVERIFY(layout.labelAlignment() == Qt::AlignLeft);
+ QCOMPARE(layout.labelAlignment(), Qt::AlignLeft);
QVERIFY(layout.formAlignment() == (Qt::AlignLeft | Qt::AlignTop));
- QVERIFY(layout.fieldGrowthPolicy() == QFormLayout::AllNonFixedFieldsGrow);
- QVERIFY(layout.rowWrapPolicy() == QFormLayout::DontWrapRows);
+ QCOMPARE(layout.fieldGrowthPolicy(), QFormLayout::AllNonFixedFieldsGrow);
+ QCOMPARE(layout.rowWrapPolicy(), QFormLayout::DontWrapRows);
/* can't directly create mac style or qtopia style, since
this test is cross platform.. so create dummy styles that
@@ -444,17 +408,17 @@ void tst_QFormLayout::setFormStyle()
*/
widget.setStyle(new DummyMacStyle());
- QVERIFY(layout.labelAlignment() == Qt::AlignRight);
+ QCOMPARE(layout.labelAlignment(), Qt::AlignRight);
QVERIFY(layout.formAlignment() == (Qt::AlignHCenter | Qt::AlignTop));
- QVERIFY(layout.fieldGrowthPolicy() == QFormLayout::FieldsStayAtSizeHint);
- QVERIFY(layout.rowWrapPolicy() == QFormLayout::DontWrapRows);
+ QCOMPARE(layout.fieldGrowthPolicy(), QFormLayout::FieldsStayAtSizeHint);
+ QCOMPARE(layout.rowWrapPolicy(), QFormLayout::DontWrapRows);
widget.setStyle(new DummyQtopiaStyle());
- QVERIFY(layout.labelAlignment() == Qt::AlignRight);
+ QCOMPARE(layout.labelAlignment(), Qt::AlignRight);
QVERIFY(layout.formAlignment() == (Qt::AlignLeft | Qt::AlignTop));
- QVERIFY(layout.fieldGrowthPolicy() == QFormLayout::AllNonFixedFieldsGrow);
- QVERIFY(layout.rowWrapPolicy() == QFormLayout::WrapLongRows);
+ QCOMPARE(layout.fieldGrowthPolicy(), QFormLayout::AllNonFixedFieldsGrow);
+ QCOMPARE(layout.rowWrapPolicy(), QFormLayout::WrapLongRows);
}
void tst_QFormLayout::setFieldGrowthPolicy()
@@ -479,14 +443,14 @@ void tst_QFormLayout::setFieldGrowthPolicy()
layout.activate();
if (i == 0) {
- QVERIFY(fld1.width() == fld2.width());
- QVERIFY(fld2.width() == fld3.width());
+ QCOMPARE(fld1.width(), fld2.width());
+ QCOMPARE(fld2.width(), fld3.width());
} else if (i == 1) {
- QVERIFY(fld1.width() == fld2.width());
+ QCOMPARE(fld1.width(), fld2.width());
QVERIFY(fld2.width() < fld3.width());
} else {
QVERIFY(fld1.width() < fld2.width());
- QVERIFY(fld2.width() == fld3.width());
+ QCOMPARE(fld2.width(), fld3.width());
}
}
}
@@ -505,33 +469,39 @@ void tst_QFormLayout::setFormAlignment()
void tst_QFormLayout::addRow()
{
- QFormLayout layout;
- QWidget w1, w2, w3;
- QHBoxLayout l1, l2, l3;
- QLabel lbl1, lbl2;
-
- QCOMPARE(layout.rowCount(), 0);
-
- layout.addRow(&lbl1, &w1);
- layout.addRow(&lbl2, &l1);
- layout.addRow("Foo:", &w2);
- layout.addRow("Bar:", &l2);
- layout.addRow(&w3);
- layout.addRow(&l3);
-
- QCOMPARE(layout.rowCount(), 6);
-
- QVERIFY(layout.itemAt(0, QFormLayout::LabelRole)->widget() == &lbl1);
- QVERIFY(layout.itemAt(1, QFormLayout::LabelRole)->widget() == &lbl2);
- QVERIFY(layout.itemAt(2, QFormLayout::LabelRole)->widget()->property("text") == "Foo:");
- QVERIFY(layout.itemAt(3, QFormLayout::LabelRole)->widget()->property("text") == "Bar:");
- QVERIFY(layout.itemAt(4, QFormLayout::LabelRole) == 0);
- QVERIFY(layout.itemAt(5, QFormLayout::LabelRole) == 0);
-
- QVERIFY(layout.itemAt(0, QFormLayout::FieldRole)->widget() == &w1);
- QVERIFY(layout.itemAt(1, QFormLayout::FieldRole)->layout() == &l1);
- QVERIFY(layout.itemAt(2, QFormLayout::FieldRole)->widget() == &w2);
- QVERIFY(layout.itemAt(3, QFormLayout::FieldRole)->layout() == &l2);
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
+ QWidget *w1 = new QWidget(&topLevel);
+ QWidget *w2 = new QWidget(&topLevel);
+ QWidget *w3 = new QWidget(&topLevel);
+ QHBoxLayout *l1 = new QHBoxLayout;
+ QHBoxLayout *l2 = new QHBoxLayout;
+ QHBoxLayout *l3 = new QHBoxLayout;
+ QLabel *lbl1 = new QLabel(&topLevel);
+ QLabel *lbl2 = new QLabel(&topLevel);
+
+ QCOMPARE(layout->rowCount(), 0);
+
+ layout->addRow(lbl1, w1);
+ layout->addRow(lbl2, l1);
+ layout->addRow("Foo:", w2);
+ layout->addRow("Bar:", l2);
+ layout->addRow(w3);
+ layout->addRow(l3);
+
+ QCOMPARE(layout->rowCount(), 6);
+
+ QVERIFY(layout->itemAt(0, QFormLayout::LabelRole)->widget() == lbl1);
+ QVERIFY(layout->itemAt(1, QFormLayout::LabelRole)->widget() == lbl2);
+ QVERIFY(layout->itemAt(2, QFormLayout::LabelRole)->widget()->property("text") == "Foo:");
+ QVERIFY(layout->itemAt(3, QFormLayout::LabelRole)->widget()->property("text") == "Bar:");
+ QVERIFY(layout->itemAt(4, QFormLayout::LabelRole) == 0);
+ QVERIFY(layout->itemAt(5, QFormLayout::LabelRole) == 0);
+
+ QVERIFY(layout->itemAt(0, QFormLayout::FieldRole)->widget() == w1);
+ QVERIFY(layout->itemAt(1, QFormLayout::FieldRole)->layout() == l1);
+ QVERIFY(layout->itemAt(2, QFormLayout::FieldRole)->widget() == w2);
+ QVERIFY(layout->itemAt(3, QFormLayout::FieldRole)->layout() == l2);
// ### should have a third role, FullRowRole?
// QVERIFY(layout.itemAt(4, QFormLayout::FieldRole) == 0);
// QVERIFY(layout.itemAt(5, QFormLayout::FieldRole) == 0);
@@ -539,17 +509,24 @@ void tst_QFormLayout::addRow()
void tst_QFormLayout::insertRow_QWidget_QWidget()
{
- QFormLayout layout;
- QLabel lbl1, lbl2, lbl3, lbl4;
- QLineEdit fld1, fld2, fld3, fld4;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
+ QLabel *lbl1 = new QLabel(&topLevel);
+ QLabel *lbl2 = new QLabel(&topLevel);
+ QLabel *lbl3 = new QLabel(&topLevel);
+ QLabel *lbl4 = new QLabel(&topLevel);
+ QLineEdit *fld1 = new QLineEdit(&topLevel);
+ QLineEdit *fld2 = new QLineEdit(&topLevel);
+ QLineEdit *fld3 = new QLineEdit(&topLevel);
+ QLineEdit *fld4 = new QLineEdit(&topLevel);
- layout.insertRow(0, &lbl1, &fld1);
- QCOMPARE(layout.rowCount(), 1);
+ layout->insertRow(0, lbl1, fld1);
+ QCOMPARE(layout->rowCount(), 1);
{
int row = -1;
QFormLayout::ItemRole role = QFormLayout::ItemRole(-123);
- layout.getWidgetPosition(&lbl1, &row, &role);
+ layout->getWidgetPosition(lbl1, &row, &role);
QCOMPARE(row, 0);
QCOMPARE(int(role), int(QFormLayout::LabelRole));
}
@@ -557,63 +534,68 @@ void tst_QFormLayout::insertRow_QWidget_QWidget()
{
int row = -1;
QFormLayout::ItemRole role = QFormLayout::ItemRole(-123);
- layout.getWidgetPosition(&fld1, &row, &role);
+ layout->getWidgetPosition(fld1, &row, &role);
QCOMPARE(row, 0);
QCOMPARE(int(role), int(QFormLayout::FieldRole));
}
// check that negative values append
- layout.insertRow(-2, &lbl2, &fld2);
- QCOMPARE(layout.rowCount(), 2);
+ layout->insertRow(-2, lbl2, fld2);
+ QCOMPARE(layout->rowCount(), 2);
- QVERIFY(layout.itemAt(0, QFormLayout::LabelRole)->widget() == &lbl1);
- QVERIFY(layout.itemAt(1, QFormLayout::LabelRole)->widget() == &lbl2);
+ QVERIFY(layout->itemAt(0, QFormLayout::LabelRole)->widget() == lbl1);
+ QVERIFY(layout->itemAt(1, QFormLayout::LabelRole)->widget() == lbl2);
// check that too large values append
- layout.insertRow(100, &lbl3, &fld3);
- QCOMPARE(layout.rowCount(), 3);
- QCOMPARE(layout.count(), 6);
+ layout->insertRow(100, lbl3, fld3);
+ QCOMPARE(layout->rowCount(), 3);
+ QCOMPARE(layout->count(), 6);
- layout.insertRow(3, (QWidget *)0, (QWidget *)0);
- QCOMPARE(layout.rowCount(), 4);
- QCOMPARE(layout.count(), 6);
+ layout->insertRow(3, (QWidget *)0, (QWidget *)0);
+ QCOMPARE(layout->rowCount(), 4);
+ QCOMPARE(layout->count(), 6);
- layout.insertRow(4, (QWidget *)0, &fld4);
- QCOMPARE(layout.rowCount(), 5);
- QCOMPARE(layout.count(), 7);
+ layout->insertRow(4, (QWidget *)0, fld4);
+ QCOMPARE(layout->rowCount(), 5);
+ QCOMPARE(layout->count(), 7);
- layout.insertRow(5, &lbl4, (QWidget *)0);
- QCOMPARE(layout.rowCount(), 6);
- QCOMPARE(layout.count(), 8);
-
- QVERIFY(layout.itemAt(0, QFormLayout::LabelRole)->widget() == &lbl1);
- QVERIFY(layout.itemAt(1, QFormLayout::LabelRole)->widget() == &lbl2);
- QVERIFY(layout.itemAt(2, QFormLayout::LabelRole)->widget() == &lbl3);
- QVERIFY(layout.itemAt(3, QFormLayout::LabelRole) == 0);
- QVERIFY(layout.itemAt(4, QFormLayout::LabelRole) == 0);
- QVERIFY(layout.itemAt(5, QFormLayout::LabelRole)->widget() == &lbl4);
-
- QVERIFY(layout.itemAt(0, QFormLayout::FieldRole)->widget() == &fld1);
- QVERIFY(layout.itemAt(1, QFormLayout::FieldRole)->widget() == &fld2);
- QVERIFY(layout.itemAt(2, QFormLayout::FieldRole)->widget() == &fld3);
- QVERIFY(layout.itemAt(3, QFormLayout::FieldRole) == 0);
- QVERIFY(layout.itemAt(4, QFormLayout::FieldRole)->widget() == &fld4);
- QVERIFY(layout.itemAt(5, QFormLayout::FieldRole) == 0);
+ layout->insertRow(5, lbl4, (QWidget *)0);
+ QCOMPARE(layout->rowCount(), 6);
+ QCOMPARE(layout->count(), 8);
+
+ QVERIFY(layout->itemAt(0, QFormLayout::LabelRole)->widget() == lbl1);
+ QVERIFY(layout->itemAt(1, QFormLayout::LabelRole)->widget() == lbl2);
+ QVERIFY(layout->itemAt(2, QFormLayout::LabelRole)->widget() == lbl3);
+ QVERIFY(layout->itemAt(3, QFormLayout::LabelRole) == 0);
+ QVERIFY(layout->itemAt(4, QFormLayout::LabelRole) == 0);
+ QVERIFY(layout->itemAt(5, QFormLayout::LabelRole)->widget() == lbl4);
+
+ QVERIFY(layout->itemAt(0, QFormLayout::FieldRole)->widget() == fld1);
+ QVERIFY(layout->itemAt(1, QFormLayout::FieldRole)->widget() == fld2);
+ QVERIFY(layout->itemAt(2, QFormLayout::FieldRole)->widget() == fld3);
+ QVERIFY(layout->itemAt(3, QFormLayout::FieldRole) == 0);
+ QVERIFY(layout->itemAt(4, QFormLayout::FieldRole)->widget() == fld4);
+ QVERIFY(layout->itemAt(5, QFormLayout::FieldRole) == 0);
}
void tst_QFormLayout::insertRow_QWidget_QLayout()
{
- QFormLayout layout;
- QLabel lbl1, lbl2, lbl3, lbl4;
- QHBoxLayout fld1, fld2, fld3, fld4;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
+ QLabel *lbl1 = new QLabel(&topLevel);
+ QLabel *lbl2 = new QLabel(&topLevel);
+ QLabel *lbl3 = new QLabel(&topLevel);
+ QHBoxLayout *fld1 = new QHBoxLayout;
+ QHBoxLayout *fld2 = new QHBoxLayout;
+ QHBoxLayout *fld3 = new QHBoxLayout;
- layout.insertRow(0, &lbl1, &fld1);
- QCOMPARE(layout.rowCount(), 1);
+ layout->insertRow(0, lbl1, fld1);
+ QCOMPARE(layout->rowCount(), 1);
{
int row = -1;
QFormLayout::ItemRole role = QFormLayout::ItemRole(-123);
- layout.getWidgetPosition(&lbl1, &row, &role);
+ layout->getWidgetPosition(lbl1, &row, &role);
QCOMPARE(row, 0);
QCOMPARE(int(role), int(QFormLayout::LabelRole));
}
@@ -621,77 +603,83 @@ void tst_QFormLayout::insertRow_QWidget_QLayout()
{
int row = -1;
QFormLayout::ItemRole role = QFormLayout::ItemRole(-123);
- layout.getLayoutPosition(&fld1, &row, &role);
+ layout->getLayoutPosition(fld1, &row, &role);
QCOMPARE(row, 0);
QCOMPARE(int(role), int(QFormLayout::FieldRole));
}
// check that negative values append
- layout.insertRow(-2, &lbl2, &fld2);
- QCOMPARE(layout.rowCount(), 2);
+ layout->insertRow(-2, lbl2, fld2);
+ QCOMPARE(layout->rowCount(), 2);
- QVERIFY(layout.itemAt(0, QFormLayout::LabelRole)->widget() == &lbl1);
- QVERIFY(layout.itemAt(1, QFormLayout::LabelRole)->widget() == &lbl2);
+ QVERIFY(layout->itemAt(0, QFormLayout::LabelRole)->widget() == lbl1);
+ QVERIFY(layout->itemAt(1, QFormLayout::LabelRole)->widget() == lbl2);
// check that too large values append
- layout.insertRow(100, &lbl3, &fld3);
- QCOMPARE(layout.rowCount(), 3);
+ layout->insertRow(100, lbl3, fld3);
+ QCOMPARE(layout->rowCount(), 3);
- QVERIFY(layout.itemAt(0, QFormLayout::LabelRole)->widget() == &lbl1);
- QVERIFY(layout.itemAt(1, QFormLayout::LabelRole)->widget() == &lbl2);
- QVERIFY(layout.itemAt(2, QFormLayout::LabelRole)->widget() == &lbl3);
+ QVERIFY(layout->itemAt(0, QFormLayout::LabelRole)->widget() == lbl1);
+ QVERIFY(layout->itemAt(1, QFormLayout::LabelRole)->widget() == lbl2);
+ QVERIFY(layout->itemAt(2, QFormLayout::LabelRole)->widget() == lbl3);
- QVERIFY(layout.itemAt(0, QFormLayout::FieldRole)->layout() == &fld1);
- QVERIFY(layout.itemAt(1, QFormLayout::FieldRole)->layout() == &fld2);
- QVERIFY(layout.itemAt(2, QFormLayout::FieldRole)->layout() == &fld3);
+ QVERIFY(layout->itemAt(0, QFormLayout::FieldRole)->layout() == fld1);
+ QVERIFY(layout->itemAt(1, QFormLayout::FieldRole)->layout() == fld2);
+ QVERIFY(layout->itemAt(2, QFormLayout::FieldRole)->layout() == fld3);
}
void tst_QFormLayout::insertRow_QString_QWidget()
{
- QFormLayout layout;
- QLineEdit fld1, fld2, fld3;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
+ QLineEdit *fld1 = new QLineEdit(&topLevel);
+ QLineEdit *fld2 = new QLineEdit(&topLevel);
+ QLineEdit *fld3 = new QLineEdit(&topLevel);
- layout.insertRow(-5, "&Name:", &fld1);
- QLabel *label1 = qobject_cast<QLabel *>(layout.itemAt(0, QFormLayout::LabelRole)->widget());
+ layout->insertRow(-5, "&Name:", fld1);
+ QLabel *label1 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label1 != 0);
- QVERIFY(label1->buddy() == &fld1);
+ QCOMPARE(label1->buddy(), fld1);
- layout.insertRow(0, "&Email:", &fld2);
- QLabel *label2 = qobject_cast<QLabel *>(layout.itemAt(0, QFormLayout::LabelRole)->widget());
+ layout->insertRow(0, "&Email:", fld2);
+ QLabel *label2 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label2 != 0);
- QVERIFY(label2->buddy() == &fld2);
+ QCOMPARE(label2->buddy(), fld2);
- layout.insertRow(5, "&Age:", &fld3);
- QLabel *label3 = qobject_cast<QLabel *>(layout.itemAt(2, QFormLayout::LabelRole)->widget());
+ layout->insertRow(5, "&Age:", fld3);
+ QLabel *label3 = qobject_cast<QLabel *>(layout->itemAt(2, QFormLayout::LabelRole)->widget());
QVERIFY(label3 != 0);
- QVERIFY(label3->buddy() == &fld3);
+ QCOMPARE(label3->buddy(), fld3);
}
void tst_QFormLayout::insertRow_QString_QLayout()
{
- QFormLayout layout;
- QHBoxLayout fld1, fld2, fld3;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
+ QHBoxLayout *fld1 = new QHBoxLayout;
+ QHBoxLayout *fld2 = new QHBoxLayout;
+ QHBoxLayout *fld3 = new QHBoxLayout;
- layout.insertRow(-5, "&Name:", &fld1);
- QLabel *label1 = qobject_cast<QLabel *>(layout.itemAt(0, QFormLayout::LabelRole)->widget());
+ layout->insertRow(-5, "&Name:", fld1);
+ QLabel *label1 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label1 != 0);
- QVERIFY(label1->buddy() == 0);
+ QVERIFY(!label1->buddy());
- QCOMPARE(layout.rowCount(), 1);
+ QCOMPARE(layout->rowCount(), 1);
- layout.insertRow(0, "&Email:", &fld2);
- QLabel *label2 = qobject_cast<QLabel *>(layout.itemAt(0, QFormLayout::LabelRole)->widget());
+ layout->insertRow(0, "&Email:", fld2);
+ QLabel *label2 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label2 != 0);
- QVERIFY(label2->buddy() == 0);
+ QVERIFY(!label2->buddy());
- QCOMPARE(layout.rowCount(), 2);
+ QCOMPARE(layout->rowCount(), 2);
- layout.insertRow(5, "&Age:", &fld3);
- QLabel *label3 = qobject_cast<QLabel *>(layout.itemAt(2, QFormLayout::LabelRole)->widget());
+ layout->insertRow(5, "&Age:", fld3);
+ QLabel *label3 = qobject_cast<QLabel *>(layout->itemAt(2, QFormLayout::LabelRole)->widget());
QVERIFY(label3 != 0);
- QVERIFY(label3->buddy() == 0);
+ QVERIFY(!label3->buddy());
- QCOMPARE(layout.rowCount(), 3);
+ QCOMPARE(layout->rowCount(), 3);
}
void tst_QFormLayout::insertRow_QWidget()
@@ -840,39 +828,40 @@ void tst_QFormLayout::setLayout()
void tst_QFormLayout::itemAt()
{
- QFormLayout layout;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
- QWidget w1;
- QWidget w2;
- QWidget w3;
- QWidget w4;
- QWidget w5;
- QHBoxLayout l6;
+ QWidget *w1 = new QWidget(&topLevel);
+ QWidget *w2 = new QWidget(&topLevel);
+ QWidget *w3 = new QWidget(&topLevel);
+ QWidget *w4 = new QWidget(&topLevel);
+ QWidget *w5 = new QWidget(&topLevel);
+ QHBoxLayout *l6 = new QHBoxLayout;
- layout.setWidget(5, QFormLayout::LabelRole, &w1);
- layout.setWidget(3, QFormLayout::FieldRole, &w2);
- layout.setWidget(3, QFormLayout::LabelRole, &w3);
- layout.addRow(&w4, &w5);
- layout.addRow("Foo:", &l6);
+ layout->setWidget(5, QFormLayout::LabelRole, w1);
+ layout->setWidget(3, QFormLayout::FieldRole, w2);
+ layout->setWidget(3, QFormLayout::LabelRole, w3);
+ layout->addRow(w4, w5);
+ layout->addRow("Foo:", l6);
- QCOMPARE(layout.count(), 7);
+ QCOMPARE(layout->count(), 7);
QBitArray scoreBoard(7);
for (int i = 0; i < 7; ++i) {
- QLayoutItem *item = layout.itemAt(i);
+ QLayoutItem *item = layout->itemAt(i);
QVERIFY(item != 0);
- if (item->widget() == &w1) {
+ if (item->widget() == w1) {
scoreBoard[0] = true;
- } else if (item->widget() == &w2) {
+ } else if (item->widget() == w2) {
scoreBoard[1] = true;
- } else if (item->widget() == &w3) {
+ } else if (item->widget() == w3) {
scoreBoard[2] = true;
- } else if (item->widget() == &w4) {
+ } else if (item->widget() == w4) {
scoreBoard[3] = true;
- } else if (item->widget() == &w5) {
+ } else if (item->widget() == w5) {
scoreBoard[4] = true;
- } else if (item->layout() == &l6) {
+ } else if (item->layout() == l6) {
scoreBoard[5] = true;
} else if (qobject_cast<QLabel *>(item->widget())) {
scoreBoard[6] = true;
@@ -883,26 +872,27 @@ void tst_QFormLayout::itemAt()
void tst_QFormLayout::takeAt()
{
- QFormLayout layout;
+ QWidget topLevel;
+ QFormLayout *layout = new QFormLayout(&topLevel);
- QWidget w1;
- QWidget w2;
- QWidget w3;
- QWidget w4;
- QWidget w5;
- QHBoxLayout l6;
+ QWidget *w1 = new QWidget(&topLevel);
+ QWidget *w2 = new QWidget(&topLevel);
+ QWidget *w3 = new QWidget(&topLevel);
+ QWidget *w4 = new QWidget(&topLevel);
+ QWidget *w5 = new QWidget(&topLevel);
+ QHBoxLayout *l6 = new QHBoxLayout;
- layout.setWidget(5, QFormLayout::LabelRole, &w1);
- layout.setWidget(3, QFormLayout::FieldRole, &w2);
- layout.setWidget(3, QFormLayout::LabelRole, &w3);
- layout.addRow(&w4, &w5);
- layout.addRow("Foo:", &l6);
+ layout->setWidget(5, QFormLayout::LabelRole, w1);
+ layout->setWidget(3, QFormLayout::FieldRole, w2);
+ layout->setWidget(3, QFormLayout::LabelRole, w3);
+ layout->addRow(w4, w5);
+ layout->addRow("Foo:", l6);
- QCOMPARE(layout.count(), 7);
+ QCOMPARE(layout->count(), 7);
for (int i = 6; i >= 0; --i) {
- layout.takeAt(0);
- QCOMPARE(layout.count(), i);
+ layout->takeAt(0);
+ QCOMPARE(layout->count(), i);
}
}
@@ -917,6 +907,7 @@ void tst_QFormLayout::layoutAlone()
QHBoxLayout hlay;
layout.setLayout(1, QFormLayout::LabelRole, &hlay);
QCOMPARE(layout.count(), 2);
+ w.setWindowTitle(QTest::currentTestFunction());
w.show();
layout.activate();
QTest::qWait(500);
diff --git a/tests/auto/widgets/kernel/qgridlayout/tst_qgridlayout.cpp b/tests/auto/widgets/kernel/qgridlayout/tst_qgridlayout.cpp
index 7f3c289fb4..1e67c675ef 100644
--- a/tests/auto/widgets/kernel/qgridlayout/tst_qgridlayout.cpp
+++ b/tests/auto/widgets/kernel/qgridlayout/tst_qgridlayout.cpp
@@ -60,18 +60,9 @@ class tst_QGridLayout : public QObject
{
Q_OBJECT
-public:
- tst_QGridLayout();
- virtual ~tst_QGridLayout();
-
-
-public slots:
+private slots:
void initTestCase();
- void cleanupTestCase();
- void init();
void cleanup();
-
-private slots:
void getItemPosition();
void itemAtPosition();
void badDistributionBug();
@@ -97,76 +88,72 @@ private slots:
void taskQTBUG_40609_addingLayoutToItself();
void replaceWidget();
void dontCrashWhenExtendsToEnd();
-
-private:
- QWidget *testWidget;
- QGridLayout *testLayout;
- QWidget *w1;
- QWidget *w2;
- QWidget *w3;
- QSpacerItem *sp;
-
- QGridLayout *m_grid;
- QWidget *m_toplevel;
};
-
-tst_QGridLayout::tst_QGridLayout()
+void tst_QGridLayout::initTestCase()
{
- m_grid = 0;
- m_toplevel = 0;
+#ifdef Q_OS_WINCE //disable magic for WindowsCE
+ qApp->setAutoMaximizeThreshold(-1);
+#endif
}
-tst_QGridLayout::~tst_QGridLayout()
+static inline int visibleTopLevelWidgetCount()
{
- delete m_toplevel;
+ int result= 0;
+ foreach (const QWidget *topLevel, QApplication::topLevelWidgets()) {
+ if (topLevel->isVisible())
+ ++result;
+ }
+ return result;
}
-void tst_QGridLayout::initTestCase()
+void tst_QGridLayout::cleanup()
{
-#ifdef Q_OS_WINCE //disable magic for WindowsCE
- qApp->setAutoMaximizeThreshold(-1);
-#endif
- // Create the test class
- testWidget = new QWidget(0);
+ // Verify that no visible top levels are leaked. Cannot check for
+ // topLevelWidgets().isEmpty() here since the data driven test layoutSpacing()
+ // will appear to "leak" top levels due to it creating widgets in the test data.
+ QCOMPARE(visibleTopLevelWidgetCount(), 0);
+}
- testLayout = new QGridLayout(testWidget);
+class ItemTestWidget : public QWidget {
+public:
+ ItemTestWidget();
+
+ QGridLayout *testLayout;
+ QWidget *w1;
+ QWidget *w2;
+ QWidget *w3;
+ QSpacerItem *sp;
+};
+
+ItemTestWidget::ItemTestWidget()
+ : testLayout(new QGridLayout(this))
+ , w1(new QWidget(this))
+ , w2(new QWidget(this))
+ , w3(new QWidget(this))
+ , sp(new QSpacerItem(4, 4))
+{
+ setObjectName("testWidget");
+ setWindowTitle(QTest::currentTestFunction());
- w1 = new QWidget(testWidget);
w1->setPalette(QPalette(Qt::red));
testLayout->addWidget(w1, 0, 0);
- w2 = new QWidget(testWidget);
testLayout->addWidget(w2, 1, 1, 2, 2);
w2->setPalette(QPalette(Qt::green));
- w3 = new QWidget(testWidget);
testLayout->addWidget(w3, 0, 1, 1, 2);
w3->setPalette(QPalette(Qt::blue));
- sp = new QSpacerItem(4, 4);
testLayout->addItem(sp, 1, 3, 2, 1);
-
- testWidget->resize( 200, 200 );
- testWidget->show();
-}
-
-void tst_QGridLayout::cleanupTestCase()
-{
- delete testWidget;
- testWidget = 0;
-}
-
-void tst_QGridLayout::init()
-{
-}
-
-void tst_QGridLayout::cleanup()
-{
}
void tst_QGridLayout::getItemPosition()
{
+ ItemTestWidget testWidget;
+ testWidget.resize(200, 200);
+ testWidget.show();
+
QLayoutItem *item;
int counter = 0;
@@ -175,28 +162,28 @@ void tst_QGridLayout::getItemPosition()
bool seenW3 = false;
bool seenSpacer = false;
- while ((item = testLayout->itemAt(counter))) {
+ while ((item = testWidget.testLayout->itemAt(counter))) {
QWidget *w = item->widget();
int r,c,rs,cs;
- testLayout->getItemPosition(counter, &r, &c, &rs, &cs);
+ testWidget.testLayout->getItemPosition(counter, &r, &c, &rs, &cs);
// qDebug() << "item" << counter << "has" <<r << c << rs << cs;
- if (w == w1) {
+ if (w == testWidget.w1) {
QVERIFY(!seenW1);
seenW1 = true;
QCOMPARE(r, 0);
QCOMPARE(c, 0);
QCOMPARE(rs, 1);
QCOMPARE(cs, 1);
- } else if (w == w2) {
+ } else if (w == testWidget.w2) {
QVERIFY(!seenW2);
seenW2 = true;
QCOMPARE(r, 1);
QCOMPARE(c, 1);
QCOMPARE(rs, 2);
QCOMPARE(cs, 2);
- } else if (w == w3) {
+ } else if (w == testWidget.w3) {
QVERIFY(!seenW3);
seenW3 = true;
QCOMPARE(r, 0);
@@ -223,16 +210,20 @@ void tst_QGridLayout::getItemPosition()
void tst_QGridLayout::itemAtPosition()
{
+ ItemTestWidget testWidget;
+ testWidget.resize(200, 200);
+ testWidget.show();
+
void *table[4][5] = {
- { w1, w3, w3, 0, 0 },
- { 0, w2, w2, sp, 0 },
- { 0, w2, w2, sp, 0 },
+ { testWidget.w1, testWidget.w3,testWidget.w3, 0, 0 },
+ { 0, testWidget.w2, testWidget.w2, testWidget.sp, 0 },
+ { 0, testWidget.w2, testWidget.w2, testWidget.sp, 0 },
{ 0, 0, 0, 0, 0 }
};
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 5; ++col) {
- QLayoutItem *item = testLayout->itemAtPosition(row, col);
+ QLayoutItem *item = testWidget.testLayout->itemAtPosition(row, col);
QVERIFY(item == table[row][col]
|| (item && item->widget() == table[row][col]));
}
@@ -860,32 +851,31 @@ void tst_QGridLayout::minMaxSize()
}
}
QApplication::setStyle(style);
- if (!m_grid)
- m_grid = new QGridLayout();
- if (!m_toplevel) {
- m_toplevel = new QWidget();
- setFrameless(m_toplevel);
- }
+ QWidget toplevel;
+ toplevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())
+ + QLatin1Char(' ') + QLatin1String(QTest::currentDataTag()));
+ setFrameless(&toplevel);
+ QGridLayout *grid = new QGridLayout;
if (fixedSize.isValid()) {
- m_toplevel->setFixedSize(fixedSize);
+ toplevel.setFixedSize(fixedSize);
} else {
- m_toplevel->setMinimumSize(QSize(0,0));
- m_toplevel->setMaximumSize(QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX));
+ toplevel.setMinimumSize(QSize(0,0));
+ toplevel.setMaximumSize(QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX));
}
// Do a two-pass one using the real testdata, the other pass enables heightForWidth
// on the widget, but the heightForWidth() function just return sizeHint().width()
for (int pass = 0; pass < 2; ++pass) {
- m_toplevel->hide();
+ toplevel.hide();
QApplication::processEvents();
QTest::qWait(20);
// Test if removeItem uninitializes data properly
- while (m_grid->count()) {
- QLayoutItem *item = m_grid->itemAt(0);
- m_grid->removeItem(item);
+ while (grid->count()) {
+ QLayoutItem *item = grid->itemAt(0);
+ grid->removeItem(item);
delete item->widget();
delete item;
}
- m_toplevel->setLayout(m_grid);
+ toplevel.setLayout(grid);
// a layout with a top-level parent widget
QList<QPointer<SizeHinterFrame> > sizehinters;
@@ -899,29 +889,29 @@ void tst_QGridLayout::minMaxSize()
QSizePolicy sp = sh->sizePolicy();
sp.setHorizontalPolicy((QSizePolicy::Policy)sizePolicy);
sh->setSizePolicy(sp);
- sh->setParent(m_toplevel);
+ sh->setParent(&toplevel);
if (si.minSize.isValid())
sh->setMinimumSize(si.minSize);
if (si.maxSize.isValid())
sh->setMaximumSize(si.maxSize);
sizehinters.append(sh);
- m_grid->addWidget(sh, i, j);
+ grid->addWidget(sh, i, j);
}
}
- m_toplevel->show();
- QVERIFY(QTest::qWaitForWindowExposed(m_toplevel));
- m_toplevel->adjustSize();
+ toplevel.show();
+ QVERIFY(QTest::qWaitForWindowExposed(&toplevel));
+ toplevel.adjustSize();
QTest::qWait(240); // wait for the implicit adjustSize
// If the following fails we might have to wait longer.
// If that does not help there is likely a problem with the implicit adjustSize in show()
if (!fixedSize.isValid()) {
// Note that this can fail if the desktop has large fonts on windows.
- QTRY_COMPARE(m_toplevel->size(), m_toplevel->sizeHint());
+ QTRY_COMPARE(toplevel.size(), toplevel.sizeHint());
}
// We are relying on the order here...
for (int pi = 0; pi < sizehinters.count(); ++pi) {
- QPoint pt = sizehinters.at(pi)->mapTo(m_toplevel, QPoint(0, 0));
+ QPoint pt = sizehinters.at(pi)->mapTo(&toplevel, QPoint(0, 0));
QCOMPARE(pt, sizeinfos.at(pi).expectedPos);
}
}
diff --git a/tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp b/tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp
index d661c074ac..4d15ac9a93 100644
--- a/tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp
+++ b/tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp
@@ -66,6 +66,7 @@ public:
virtual ~tst_QLayout();
private slots:
+ void cleanup() { QVERIFY(QApplication::topLevelWidgets().isEmpty()); }
void getSetCheck();
void geometry();
void smartMaxSize();
@@ -217,12 +218,12 @@ void tst_QLayout::setLayoutBugs()
}
widget.setLayout(hBoxLayout);
- QVERIFY(widget.layout() == hBoxLayout);
+ QCOMPARE(widget.layout(), hBoxLayout);
QWidget containerWidget(0);
containerWidget.setLayout(widget.layout());
- QVERIFY(widget.layout() == 0);
- QVERIFY(containerWidget.layout() == hBoxLayout);
+ QVERIFY(!widget.layout());
+ QCOMPARE(containerWidget.layout(), hBoxLayout);
}
class MyLayout : public QLayout
diff --git a/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp b/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
index 7b9eaa418f..f206a5fe9a 100644
--- a/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
+++ b/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
@@ -108,6 +108,7 @@ public slots:
public slots:
void initTestCase();
void cleanupTestCase();
+ void cleanup() { QCOMPARE(QApplication::topLevelWidgets().size(), 1); }
private slots:
void number_data();
diff --git a/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp b/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp
index 6c88f8731b..0f8c9d1c9e 100644
--- a/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp
+++ b/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp
@@ -44,6 +44,7 @@ class tst_QSizePolicy : public QObject
Q_OBJECT
private Q_SLOTS:
+ void cleanup() { QVERIFY(QApplication::topLevelWidgets().isEmpty()); }
void qtest();
void defaultValues();
void getSetCheck_data() { data(); }
@@ -51,6 +52,8 @@ private Q_SLOTS:
void dataStream();
void horizontalStretch();
void verticalStretch();
+ void qhash_data() { data(); }
+ void qhash();
private:
void data() const;
};
@@ -149,8 +152,6 @@ void tst_QSizePolicy::getSetCheck()
QCOMPARE(sp.expandingDirections(), ed);
}
-#undef FETCH_TEST_DATA
-
static void makeRow(QSizePolicy sp, QSizePolicy::Policy hp, QSizePolicy::Policy vp,
int hst, int vst, QSizePolicy::ControlType ct, bool hfw, bool wfh,
Qt::Orientations orients)
@@ -314,5 +315,21 @@ void tst_QSizePolicy::verticalStretch()
QCOMPARE(sp.verticalStretch(), 255);
}
+void tst_QSizePolicy::qhash()
+{
+ FETCH_TEST_DATA;
+ Q_UNUSED(ed);
+
+ QSizePolicy sp2(hp, vp, ct);
+ sp2.setVerticalStretch(vst);
+ sp2.setHorizontalStretch(hst);
+ if (hfw) sp2.setHeightForWidth(true);
+ if (wfh) sp2.setWidthForHeight(true);
+ QCOMPARE(sp, sp2);
+ QCOMPARE(qHash(sp), qHash(sp2));
+}
+
+#undef FETCH_TEST_DATA
+
QTEST_MAIN(tst_QSizePolicy)
#include "tst_qsizepolicy.moc"
diff --git a/tests/auto/widgets/kernel/qtooltip/BLACKLIST b/tests/auto/widgets/kernel/qtooltip/BLACKLIST
new file mode 100644
index 0000000000..f8d062cc46
--- /dev/null
+++ b/tests/auto/widgets/kernel/qtooltip/BLACKLIST
@@ -0,0 +1,4 @@
+[whatsThis]
+ubuntu-14.04
+[task183679]
+opensuse-13.1
diff --git a/tests/auto/widgets/kernel/qwidget/BLACKLIST b/tests/auto/widgets/kernel/qwidget/BLACKLIST
index 591aa9e40f..78ccbe302a 100644
--- a/tests/auto/widgets/kernel/qwidget/BLACKLIST
+++ b/tests/auto/widgets/kernel/qwidget/BLACKLIST
@@ -12,7 +12,7 @@ osx
ubuntu-14.04
osx
[focusProxyAndInputMethods]
-ubuntu-14.04
+linux
[touchEventSynthesizedMouseEvent]
ubuntu-14.04
[grabMouse]
@@ -28,73 +28,17 @@ osx
[stackUnder]
osx
[raise]
-osx-10.9
+osx
[widgetAt]
osx
[sheetOpacity]
osx
[resizeEvent]
osx
-[setWindowGeometry:100,123 200x200, flags 0]
-osx-10.10
-[windowMoveResize:100,123 200x200, flags 0]
-osx-10.10
-[setWindowGeometry:100,122 200x200, flags 0]
-osx-10.9
-[windowMoveResize:100,122 200x200, flags 0]
-osx-10.9
-[setWindowGeometry:100,100 824x564, flags 0]
-osx-10.10
-[windowMoveResize:100,100 824x564, flags 0]
-osx-10.10
-[setWindowGeometry:100,100 824x516, flags 0]
-osx-10.10
-[windowMoveResize:100,100 824x516, flags 0]
-osx-10.10
-[setWindowGeometry:100,73 200x0, flags 0]
-osx-10.10
-[windowMoveResize:100,73 200x0, flags 0]
-osx-10.10
-[setWindowGeometry:100,100 824x519, flags 0]
-osx-10.10
-[windowMoveResize:100,100 824x519, flags 0]
-osx-10.10
-[setWindowGeometry:100,100 824x518, flags 0]
-osx-10.10
-[windowMoveResize:100,100 824x518, flags 0]
-osx-10.10
-[setWindowGeometry:100,72 200x0, flags 0]
-osx-10.9
-[windowMoveResize:100,72 200x0, flags 0]
-osx-10.9
-[setWindowGeometry:100,122 952x574, flags 0]
-osx-10.9
-[windowMoveResize:100,122 952x574, flags 0]
-osx-10.9
-[setWindowGeometry:100,122 952x578, flags 0]
-osx-10.9
-[windowMoveResize:100,122 952x578, flags 0]
-osx-10.9
-[setWindowGeometry:100,122 952x576, flags 0]
-osx-10.9
-[windowMoveResize:100,122 952x576, flags 0]
-osx-10.9
-[setWindowGeometry:100,100 824x521, flags 0]
-osx-10.10
-[windowMoveResize:100,100 824x521, flags 0]
-osx-10.10
-[setWindowGeometry:100,122 952x577, flags 0]
-osx-10.9
-[windowMoveResize:100,122 952x577, flags 0]
-osx-10.9
-[setWindowGeometry:100,122 952x580, flags 0]
-osx-10.9
-[windowMoveResize:100,122 952x580, flags 0]
-osx-10.9
-[windowMoveResize:130,72 0x0, flags 0]
-osx-10.9
-[windowMoveResize:130,122 0x200, flags 0]
-osx-10.9
+[setWindowGeometry]
+osx
+[windowMoveResize]
+osx
[childEvents]
osx
[renderInvisible]
@@ -114,9 +58,9 @@ osx
[showMinimizedKeepsFocus]
osx-10.10
[moveWindowInShowEvent:1]
-osx-10.9
+osx
[moveWindowInShowEvent:2]
-osx-10.9
+osx
[taskQTBUG_4055_sendSyntheticEnterLeave]
osx
[syntheticEnterLeave]
@@ -128,10 +72,14 @@ osx-10.10
[hideOpaqueChildWhileHidden]
osx
[resizeStaticContentsChildWidget_QTBUG35282]
-osx-10.9
+osx
[lower]
osx
[setClearAndResizeMask]
osx
[setToolTip]
osx-10.9
+[moveInResizeEvent]
+ubuntu-14.04
+[moveChild:right]
+osx
diff --git a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp
index a0d94d2dc9..34bd575646 100644
--- a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp
+++ b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp
@@ -51,6 +51,7 @@
#include <qdesktopwidget.h>
#include <private/qwidget_p.h>
#include <private/qapplication_p.h>
+#include <private/qhighdpiscaling_p.h>
#include <qcalendarwidget.h>
#include <qmainwindow.h>
#include <qdockwidget.h>
@@ -193,6 +194,19 @@ static QByteArray msgComparisonFailed(T v1, const char *op, T v2)
return s.toLocal8Bit();
}
+// Compare a window position that may go through scaling in the platform plugin with fuzz.
+static inline bool qFuzzyCompareWindowPosition(const QPoint &p1, const QPoint p2, int fuzz)
+{
+ return (p1 - p2).manhattanLength() <= fuzz;
+}
+
+static QString msgPointMismatch(const QPoint &p1, const QPoint p2)
+{
+ QString result;
+ QDebug(&result) << p1 << "!=" << p2 << ", manhattanLength=" << (p1 - p2).manhattanLength();
+ return result;
+}
+
class tst_QWidget : public QObject
{
Q_OBJECT
@@ -1905,8 +1919,10 @@ void tst_QWidget::windowState()
widget1.setWindowState(widget1.windowState() ^ Qt::WindowMaximized);
QTest::qWait(100);
+ const int fuzz = int(QHighDpiScaling::factor(widget1.windowHandle()));
QVERIFY(!(widget1.windowState() & Qt::WindowMaximized));
- QTRY_COMPARE(widget1.pos(), pos);
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(widget1.pos(), pos, fuzz),
+ qPrintable(msgPointMismatch(widget1.pos(), pos)));
QCOMPARE(widget1.windowHandle()->windowState(), Qt::WindowNoState);
widget1.setWindowState(Qt::WindowMinimized);
@@ -1927,7 +1943,8 @@ void tst_QWidget::windowState()
widget1.setWindowState(widget1.windowState() ^ Qt::WindowMaximized);
QTest::qWait(100);
QVERIFY(!(widget1.windowState() & (Qt::WindowMinimized|Qt::WindowMaximized)));
- QTRY_COMPARE(widget1.pos(), pos);
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(widget1.pos(), pos, fuzz),
+ qPrintable(msgPointMismatch(widget1.pos(), pos)));
QCOMPARE(widget1.windowHandle()->windowState(), Qt::WindowNoState);
widget1.setWindowState(Qt::WindowFullScreen);
@@ -1948,7 +1965,8 @@ void tst_QWidget::windowState()
widget1.setWindowState(Qt::WindowNoState);
QTest::qWait(100);
VERIFY_STATE(Qt::WindowNoState);
- QTRY_COMPARE(widget1.pos(), pos);
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(widget1.pos(), pos, fuzz),
+ qPrintable(msgPointMismatch(widget1.pos(), pos)));
QCOMPARE(widget1.windowHandle()->windowState(), Qt::WindowNoState);
widget1.setWindowState(Qt::WindowFullScreen);
@@ -1981,7 +1999,8 @@ void tst_QWidget::windowState()
QVERIFY(!(widget1.windowState() & stateMask));
QCOMPARE(widget1.windowHandle()->windowState(), Qt::WindowNoState);
- QTRY_COMPARE(widget1.pos(), pos);
+ QTRY_VERIFY2(qFuzzyCompareWindowPosition(widget1.pos(), pos, fuzz),
+ qPrintable(msgPointMismatch(widget1.pos(), pos)));
QTRY_COMPARE(widget1.size(), size);
}
@@ -3079,12 +3098,12 @@ void tst_QWidget::saveRestoreGeometry()
const QByteArray four("abca");
const QByteArray garbage("abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc");
- QVERIFY(widget.restoreGeometry(empty) == false);
- QVERIFY(widget.restoreGeometry(one) == false);
- QVERIFY(widget.restoreGeometry(two) == false);
- QVERIFY(widget.restoreGeometry(three) == false);
- QVERIFY(widget.restoreGeometry(four) == false);
- QVERIFY(widget.restoreGeometry(garbage) == false);
+ QVERIFY(!widget.restoreGeometry(empty));
+ QVERIFY(!widget.restoreGeometry(one));
+ QVERIFY(!widget.restoreGeometry(two));
+ QVERIFY(!widget.restoreGeometry(three));
+ QVERIFY(!widget.restoreGeometry(four));
+ QVERIFY(!widget.restoreGeometry(garbage));
QVERIFY(widget.restoreGeometry(savedGeometry));
widget.showNormal();
@@ -3354,7 +3373,7 @@ void tst_QWidget::widgetAt()
#if defined(Q_OS_WINCE)
QEXPECT_FAIL("", "Windows CE does only support rectangular regions", Continue); //See also task 147191
#endif
- QTRY_VERIFY(QApplication::widgetAt(testPos) == w1.data());
+ QTRY_COMPARE(QApplication::widgetAt(testPos), w1.data());
QTRY_VERIFY(QApplication::widgetAt(testPos + QPoint(1, 1)) == w2.data());
}
@@ -3401,24 +3420,24 @@ void tst_QWidget::testDeletionInEventHandlers()
QPointer<Widget> w = new Widget;
w->deleteThis = true;
w->close();
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// focusOut (crashes)
//w = new Widget;
//w->show();
//w->setFocus();
- //QVERIFY(qApp->focusWidget() == w);
+ //QCOMPARE(qApp->focusWidget(), w);
//w->deleteThis = true;
//w->clearFocus();
- //QVERIFY(w == 0);
+ //QVERIFY(w.isNull());
// key press
w = new Widget;
w->show();
w->deleteThis = true;
QTest::keyPress(w, Qt::Key_A);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// key release
@@ -3426,7 +3445,7 @@ void tst_QWidget::testDeletionInEventHandlers()
w->show();
w->deleteThis = true;
QTest::keyRelease(w, Qt::Key_A);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// mouse press
@@ -3434,15 +3453,16 @@ void tst_QWidget::testDeletionInEventHandlers()
w->show();
w->deleteThis = true;
QTest::mousePress(w, Qt::LeftButton);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// mouse release
w = new Widget;
w->show();
w->deleteThis = true;
- QTest::mouseRelease(w, Qt::LeftButton);
- QVERIFY(w == 0);
+ QMouseEvent me(QEvent::MouseButtonRelease, QPoint(1, 1), Qt::LeftButton, Qt::LeftButton, 0);
+ qApp->notify(w, &me);
+ QVERIFY(w.isNull());
delete w;
// mouse double click
@@ -3450,7 +3470,7 @@ void tst_QWidget::testDeletionInEventHandlers()
w->show();
w->deleteThis = true;
QTest::mouseDClick(w, Qt::LeftButton);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// hide event (crashes)
@@ -3458,13 +3478,13 @@ void tst_QWidget::testDeletionInEventHandlers()
//w->show();
//w->deleteThis = true;
//w->hide();
- //QVERIFY(w == 0);
+ //QVERIFY(w.isNull());
// action event
w = new Widget;
w->deleteThis = true;
w->addAction(new QAction(w));
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
// change event
@@ -3472,16 +3492,16 @@ void tst_QWidget::testDeletionInEventHandlers()
w->show();
w->deleteThis = true;
w->setMouseTracking(true);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
w = new Widget;
w->setMouseTracking(true);
w->show();
w->deleteThis = true;
- QMouseEvent me(QEvent::MouseMove, QPoint(0, 0), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
+ me = QMouseEvent(QEvent::MouseMove, QPoint(0, 0), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(w, &me);
- QVERIFY(w == 0);
+ QVERIFY(w.isNull());
delete w;
}
@@ -3675,6 +3695,8 @@ void tst_QWidget::optimizedResizeMove()
void tst_QWidget::optimizedResize_topLevel()
{
+ if (QHighDpiScaling::isActive())
+ QSKIP("Skip due to rounding errors in the regions.");
StaticWidget topLevel;
topLevel.gotPaintEvent = false;
topLevel.show();
@@ -3909,7 +3931,7 @@ void tst_QWidget::winIdChangeEvent()
QCOMPARE(winIdBefore, winIdAfter);
QCOMPARE(child.winIdChangeEventCount(), 3);
// winId is set to zero during reparenting
- QVERIFY(0 == child.m_winIdList[1]);
+ QCOMPARE(WId(0), child.m_winIdList[1]);
}
{
@@ -3949,7 +3971,7 @@ void tst_QWidget::winIdChangeEvent()
QCOMPARE(winIdBefore, winIdAfter);
QCOMPARE(child.winIdChangeEventCount(), 3);
// winId is set to zero during reparenting
- QVERIFY(0 == child.m_winIdList[1]);
+ QCOMPARE(WId(0), child.m_winIdList[1]);
}
}
@@ -4495,7 +4517,7 @@ void tst_QWidget::qobject_castInDestroyedSlot()
QObject::connect(widget, SIGNAL(destroyed(QObject*)), &checker, SLOT(destroyedSlot(QObject*)));
delete widget;
- QVERIFY(checker.wasQWidget == true);
+ QVERIFY(checker.wasQWidget);
}
// Since X11 WindowManager operations are all async, and we have no way to know if the window
@@ -6007,10 +6029,13 @@ void tst_QWidget::childEvents()
expected =
EventRecorder::EventList()
<< qMakePair(&widget, QEvent::Polish)
+ << qMakePair(&widget, QEvent::PlatformSurface)
<< qMakePair(&widget, QEvent::WinIdChange)
+ << qMakePair(&widget, QEvent::WindowIconChange)
<< qMakePair(&widget, QEvent::Move)
<< qMakePair(&widget, QEvent::Resize)
<< qMakePair(&widget, QEvent::Show)
+ << qMakePair(&widget, QEvent::CursorChange)
<< qMakePair(&widget, QEvent::ShowToParent);
QVERIFY2(spy.eventList() == expected,
@@ -6022,13 +6047,9 @@ void tst_QWidget::childEvents()
EventRecorder::EventList()
<< qMakePair(&widget, QEvent::PolishRequest)
<< qMakePair(&widget, QEvent::Type(QEvent::User + 1))
-#if defined(Q_OS_OSX) || defined(Q_OS_QNX)
<< qMakePair(&widget, QEvent::UpdateLater)
-#endif
<< qMakePair(&widget, QEvent::UpdateRequest);
- if (m_platform == QStringLiteral("windows") || m_platform == QStringLiteral("xcb"))
- QEXPECT_FAIL("", EventRecorder::msgExpectFailQtBug26424(expected, spy.eventList()).constData(), Continue);
QVERIFY2(spy.eventList() == expected,
EventRecorder::msgEventListMismatch(expected, spy.eventList()).constData());
}
@@ -6097,10 +6118,13 @@ void tst_QWidget::childEvents()
<< qMakePair(&widget, QEvent::Polish)
<< qMakePair(&widget, QEvent::ChildPolished)
<< qMakePair(&widget, QEvent::ChildPolished)
+ << qMakePair(&widget, QEvent::PlatformSurface)
<< qMakePair(&widget, QEvent::WinIdChange)
+ << qMakePair(&widget, QEvent::WindowIconChange)
<< qMakePair(&widget, QEvent::Move)
<< qMakePair(&widget, QEvent::Resize)
<< qMakePair(&widget, QEvent::Show)
+ << qMakePair(&widget, QEvent::CursorChange)
<< qMakePair(&widget, QEvent::ShowToParent);
QVERIFY2(spy.eventList() == expected,
@@ -6113,13 +6137,9 @@ void tst_QWidget::childEvents()
<< qMakePair(&widget, QEvent::PolishRequest)
<< qMakePair(&widget, QEvent::Type(QEvent::User + 1))
<< qMakePair(&widget, QEvent::Type(QEvent::User + 2))
-#if defined(Q_OS_OSX) || defined(Q_OS_QNX)
<< qMakePair(&widget, QEvent::UpdateLater)
-#endif
<< qMakePair(&widget, QEvent::UpdateRequest);
- if (m_platform == QStringLiteral("windows") || m_platform == QStringLiteral("xcb"))
- QEXPECT_FAIL("", EventRecorder::msgExpectFailQtBug26424(expected, spy.eventList()).constData(), Continue);
QVERIFY2(spy.eventList() == expected,
EventRecorder::msgEventListMismatch(expected, spy.eventList()).constData());
}
@@ -6190,10 +6210,13 @@ void tst_QWidget::childEvents()
EventRecorder::EventList()
<< qMakePair(&widget, QEvent::Polish)
<< qMakePair(&widget, QEvent::ChildPolished)
+ << qMakePair(&widget, QEvent::PlatformSurface)
<< qMakePair(&widget, QEvent::WinIdChange)
+ << qMakePair(&widget, QEvent::WindowIconChange)
<< qMakePair(&widget, QEvent::Move)
<< qMakePair(&widget, QEvent::Resize)
<< qMakePair(&widget, QEvent::Show)
+ << qMakePair(&widget, QEvent::CursorChange)
<< qMakePair(&widget, QEvent::ShowToParent);
QVERIFY2(spy.eventList() == expected,
@@ -6206,13 +6229,9 @@ void tst_QWidget::childEvents()
<< qMakePair(&widget, QEvent::PolishRequest)
<< qMakePair(&widget, QEvent::Type(QEvent::User + 1))
<< qMakePair(&widget, QEvent::Type(QEvent::User + 2))
-#if defined(Q_OS_OSX) || defined(Q_OS_QNX)
<< qMakePair(&widget, QEvent::UpdateLater)
-#endif
<< qMakePair(&widget, QEvent::UpdateRequest);
- if (m_platform == QStringLiteral("windows") || m_platform == QStringLiteral("xcb"))
- QEXPECT_FAIL("", EventRecorder::msgExpectFailQtBug26424(expected, spy.eventList()).constData(), Continue);
QVERIFY2(spy.eventList() == expected,
EventRecorder::msgEventListMismatch(expected, spy.eventList()).constData());
}
@@ -8957,7 +8976,7 @@ void tst_QWidget::taskQTBUG_4055_sendSyntheticEnterLeave()
int numEnterEvents, numMouseMoveEvents;
};
- QCursor::setPos(QPoint(0,0));
+ QCursor::setPos(QPoint(0,0));
SELParent parent;
parent.move(200, 200);
@@ -8965,8 +8984,7 @@ void tst_QWidget::taskQTBUG_4055_sendSyntheticEnterLeave()
SELChild child(&parent);
child.resize(200, 200);
parent.show();
- QVERIFY(QTest::qWaitForWindowExposed(&parent));
- QTest::qWait(150);
+ QVERIFY(QTest::qWaitForWindowActive(&parent));
QCursor::setPos(child.mapToGlobal(QPoint(100, 100)));
// Make sure the cursor has entered the child.
@@ -9714,8 +9732,9 @@ void tst_QWidget::grabMouse()
QVERIFY(QTest::qWaitForWindowActive(&w));
QStringList expectedLog;
- grabber->grabMouse();
QPoint mousePos = QPoint(w.width() / 2, 10);
+ QTest::mouseMove(w.windowHandle(), mousePos);
+ grabber->grabMouse();
const int step = w.height() / 5;
for ( ; mousePos.y() < w.height() ; mousePos.ry() += step) {
QTest::mouseClick(w.windowHandle(), Qt::LeftButton, 0, mousePos);
@@ -10385,6 +10404,9 @@ public:
void tst_QWidget::keyboardModifiers()
{
KeyboardWidget w;
+ w.resize(300, 300);
+ w.show();
+ QVERIFY(QTest::qWaitForWindowActive(&w));
QTest::mouseClick(&w, Qt::LeftButton, Qt::ControlModifier);
QCOMPARE(w.m_eventCounter, 1);
QCOMPARE(int(w.m_modifiers), int(Qt::ControlModifier));
@@ -10462,7 +10484,7 @@ void tst_QWidget::qmlSetParentHelper()
QWidget child;
QVERIFY(QAbstractDeclarativeData::setWidgetParent);
QAbstractDeclarativeData::setWidgetParent(&child, &parent);
- QVERIFY(child.parentWidget() == &parent);
+ QCOMPARE(child.parentWidget(), &parent);
QAbstractDeclarativeData::setWidgetParent(&child, 0);
QVERIFY(!child.parentWidget());
#else
diff --git a/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp b/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp
index 148c2352a5..4bdb299213 100644
--- a/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp
+++ b/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp
@@ -97,6 +97,8 @@ private slots:
void tst_resize_count();
void tst_move_count();
+
+ void tst_eventfilter_on_toplevel();
};
void tst_QWidget_window::initTestCase()
@@ -762,5 +764,48 @@ void tst_QWidget_window::tst_move_count()
QTRY_VERIFY(move.moveCount >= 1);
}
+class EventFilter : public QObject
+{
+public:
+ int eventCount;
+
+ EventFilter()
+ : QObject(),
+ eventCount(0)
+ {
+ }
+
+ static QEvent::Type filterEventType()
+ {
+ static int type = QEvent::registerEventType();
+ return static_cast<QEvent::Type>(type);
+ }
+
+protected:
+ bool eventFilter(QObject *o, QEvent *e) Q_DECL_OVERRIDE
+ {
+ if (e->type() == filterEventType())
+ ++eventCount;
+
+ return QObject::eventFilter(o, e);
+ }
+};
+
+void tst_QWidget_window::tst_eventfilter_on_toplevel()
+{
+ QWidget w;
+ EventFilter filter;
+ w.installEventFilter(&filter);
+ w.show();
+ QVERIFY(QTest::qWaitForWindowActive(&w));
+ QVERIFY(w.isWindow());
+ QCOMPARE(filter.eventCount, 0);
+
+ // send an event not handled in a special way by QWidgetWindow::event,
+ // and check that it's received by the event filter
+ QCoreApplication::postEvent(w.windowHandle(), new QEvent(EventFilter::filterEventType()));
+ QTRY_COMPARE(filter.eventCount, 1);
+}
+
QTEST_MAIN(tst_QWidget_window)
#include "tst_qwidget_window.moc"
diff --git a/tests/auto/widgets/kernel/qwidgetaction/tst_qwidgetaction.cpp b/tests/auto/widgets/kernel/qwidgetaction/tst_qwidgetaction.cpp
index df54d22a2f..207ce00dbf 100644
--- a/tests/auto/widgets/kernel/qwidgetaction/tst_qwidgetaction.cpp
+++ b/tests/auto/widgets/kernel/qwidgetaction/tst_qwidgetaction.cpp
@@ -55,6 +55,8 @@ class tst_QWidgetAction : public QObject
{
Q_OBJECT
private slots:
+ void initTestCase();
+ void cleanup();
void defaultWidget();
void visibilityUpdate();
void customWidget();
@@ -65,6 +67,19 @@ private slots:
void releaseWidgetCrash();
};
+void tst_QWidgetAction::initTestCase()
+{
+ // Disable menu/combo animations to prevent the alpha widgets from getting in the
+ // way in popup(), failing the top level leak check in cleanup().
+ QApplication::setEffectEnabled(Qt::UI_AnimateMenu, false);
+ QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
+}
+
+void tst_QWidgetAction::cleanup()
+{
+ QVERIFY(QApplication::topLevelWidgets().isEmpty());
+}
+
void tst_QWidgetAction::defaultWidget()
{
{
@@ -123,14 +138,14 @@ void tst_QWidgetAction::defaultWidget()
action->setDefaultWidget(combo);
tb1.addAction(action);
- QVERIFY(combo->parent() == &tb1);
+ QCOMPARE(combo->parent(), &tb1);
qApp->processEvents();
qApp->processEvents();
QVERIFY(combo->isVisible());
// not supported, not supposed to work, hence the parent() check
tb2.addAction(action);
- QVERIFY(combo->parent() == &tb1);
+ QCOMPARE(combo->parent(), &tb1);
tb2.removeAction(action);
tb1.removeAction(action);
@@ -141,11 +156,11 @@ void tst_QWidgetAction::defaultWidget()
tb2.addAction(action);
qApp->processEvents(); //the call to hide is delayd by the toolbar layout
qApp->processEvents();
- QVERIFY(combo->parent() == &tb2);
+ QCOMPARE(combo->parent(), &tb2);
QVERIFY(combo->isVisible());
tb1.addAction(action);
- QVERIFY(combo->parent() == &tb2);
+ QCOMPARE(combo->parent(), &tb2);
delete action;
QVERIFY(!combo);
@@ -156,17 +171,17 @@ void tst_QWidgetAction::defaultWidget()
QPointer<QComboBox> combo1 = new QComboBox;
a->setDefaultWidget(combo1);
- QVERIFY(a->defaultWidget() == combo1);
+ QCOMPARE(a->defaultWidget(), combo1.data());
a->setDefaultWidget(combo1);
QVERIFY(combo1);
- QVERIFY(a->defaultWidget() == combo1);
+ QCOMPARE(a->defaultWidget(), combo1.data());
QPointer<QComboBox> combo2 = new QComboBox;
QVERIFY(combo1 != combo2);
a->setDefaultWidget(combo2);
QVERIFY(!combo1);
- QVERIFY(a->defaultWidget() == combo2);
+ QCOMPARE(a->defaultWidget(), combo2.data());
delete a;
QVERIFY(!combo2);
@@ -238,7 +253,7 @@ void tst_QWidgetAction::customWidget()
combos = action->createdWidgets();
QCOMPARE(combos.count(), 2);
- QVERIFY(combos.at(0) == combo1);
+ QCOMPARE(combos.at(0), combo1.data());
QPointer<QComboBox> combo2 = qobject_cast<QComboBox *>(combos.at(1));
QVERIFY(combo2);
@@ -262,7 +277,7 @@ void tst_QWidgetAction::keepOwnership()
{
QToolBar *tb = new QToolBar;
tb->addAction(action);
- QVERIFY(combo->parent() == tb);
+ QCOMPARE(combo->parent(), tb);
delete tb;
}
diff --git a/tests/auto/widgets/kernel/qwidgetsvariant/tst_qwidgetsvariant.cpp b/tests/auto/widgets/kernel/qwidgetsvariant/tst_qwidgetsvariant.cpp
index 8b566713f9..690ef30f71 100644
--- a/tests/auto/widgets/kernel/qwidgetsvariant/tst_qwidgetsvariant.cpp
+++ b/tests/auto/widgets/kernel/qwidgetsvariant/tst_qwidgetsvariant.cpp
@@ -84,13 +84,13 @@ void tst_QWidgetsVariant::constructor_invalid()
QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type, type id:"));
QVariant variant(static_cast<QVariant::Type>(typeId));
QVERIFY(!variant.isValid());
- QVERIFY(variant.userType() == QMetaType::UnknownType);
+ QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
}
{
QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type, type id:"));
QVariant variant(typeId, /* copy */ 0);
QVERIFY(!variant.isValid());
- QVERIFY(variant.userType() == QMetaType::UnknownType);
+ QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
}
}
@@ -208,7 +208,7 @@ void tst_QWidgetsVariant::qvariant_cast_QObject_derived()
CustomQWidget customWidget;
QWidget *widget = &customWidget;
QVariant data = QVariant::fromValue(widget);
- QVERIFY(data.userType() == qMetaTypeId<QWidget*>());
+ QCOMPARE(data.userType(), qMetaTypeId<QWidget*>());
QCOMPARE(data.value<QObject*>(), widget);
QCOMPARE(data.value<QWidget*>(), widget);
diff --git a/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp b/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp
index 33427788f6..7d48ab760d 100644
--- a/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp
+++ b/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp
@@ -327,7 +327,7 @@ void tst_QWindowContainer::testDockWidget()
QTest::qWait(1000);
dock->setFloating(false);
- QTRY_VERIFY(window->parent() == mainWindow.window()->windowHandle());
+ QTRY_COMPARE(window->parent(), mainWindow.window()->windowHandle());
}
QTEST_MAIN(tst_QWindowContainer)
diff --git a/tests/auto/widgets/styles/qstyle/tst_qstyle.cpp b/tests/auto/widgets/styles/qstyle/tst_qstyle.cpp
index 7aa529d5ee..21369d4520 100644
--- a/tests/auto/widgets/styles/qstyle/tst_qstyle.cpp
+++ b/tests/auto/widgets/styles/qstyle/tst_qstyle.cpp
@@ -214,12 +214,12 @@ void tst_QStyle::testProxyStyle()
QProxyStyle *proxyStyle = new QProxyStyle();
QVERIFY(proxyStyle->baseStyle());
QStyle *style = QStyleFactory::create("Windows");
- QVERIFY(style->proxy() == style);
+ QCOMPARE(style->proxy(), style);
proxyStyle->setBaseStyle(style);
- QVERIFY(style->proxy() == proxyStyle);
- QVERIFY(style->parent() == proxyStyle);
- QVERIFY(proxyStyle->baseStyle() == style);
+ QCOMPARE(style->proxy(), proxyStyle);
+ QCOMPARE(style->parent(), proxyStyle);
+ QCOMPARE(proxyStyle->baseStyle(), style);
QVERIFY(testAllFunctions(proxyStyle));
proxyStyle->setBaseStyle(0);
@@ -236,7 +236,7 @@ void tst_QStyle::testProxyStyle()
QLineEdit edit;
edit.setStyle(&customStyle);
QVERIFY(!customStyle.parent());
- QVERIFY(edit.style()->pixelMetric(QStyle::PM_ButtonIconSize) == 13);
+ QCOMPARE(edit.style()->pixelMetric(QStyle::PM_ButtonIconSize), 13);
}
void tst_QStyle::drawItemPixmap()
diff --git a/tests/auto/widgets/styles/qstylesheetstyle/BLACKLIST b/tests/auto/widgets/styles/qstylesheetstyle/BLACKLIST
new file mode 100644
index 0000000000..cf78fb47c2
--- /dev/null
+++ b/tests/auto/widgets/styles/qstylesheetstyle/BLACKLIST
@@ -0,0 +1,2 @@
+[hoverColors]
+ubuntu-14.04
diff --git a/tests/auto/widgets/styles/qstylesheetstyle/tst_qstylesheetstyle.cpp b/tests/auto/widgets/styles/qstylesheetstyle/tst_qstylesheetstyle.cpp
index 25f7715e3b..a511e91e2c 100644
--- a/tests/auto/widgets/styles/qstylesheetstyle/tst_qstylesheetstyle.cpp
+++ b/tests/auto/widgets/styles/qstylesheetstyle/tst_qstylesheetstyle.cpp
@@ -178,45 +178,49 @@ void tst_QStyleSheetStyle::numinstances()
void tst_QStyleSheetStyle::widgetsBeforeAppStyleSheet()
{
QPushButton w1; // widget with no stylesheet
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
qApp->setStyleSheet("* { color: red; }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
w1.setStyleSheet("color: white");
- QVERIFY(COLOR(w1) == QColor("white"));
+ QCOMPARE(COLOR(w1), white);
qApp->setStyleSheet("");
- QVERIFY(COLOR(w1) == QColor("white"));
+ QCOMPARE(COLOR(w1), white);
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
}
class FriendlySpinBox : public QSpinBox { friend class tst_QStyleSheetStyle; };
void tst_QStyleSheetStyle::widgetsAfterAppStyleSheet()
{
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
qApp->setStyleSheet("* { color: red; font-size: 32pt; }");
QPushButton w1;
FriendlySpinBox spin;
- QVERIFY(COLOR(w1) == QColor("red"));
- QVERIFY(COLOR(spin) == QColor("red"));
- QVERIFY(COLOR(*spin.lineEdit()) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
+ QCOMPARE(COLOR(spin), red);
+ QCOMPARE(COLOR(*spin.lineEdit()), red);
QCOMPARE(FONTSIZE(w1), 32);
QCOMPARE(FONTSIZE(spin), 32);
QCOMPARE(FONTSIZE(*spin.lineEdit()), 32);
w1.setStyleSheet("color: white");
- QVERIFY(COLOR(w1) == QColor("white"));
- QVERIFY(COLOR(spin) == QColor("red"));
- QVERIFY(COLOR(*spin.lineEdit()) == QColor("red"));
+ QCOMPARE(COLOR(w1), white);
+ QCOMPARE(COLOR(spin), red);
+ QCOMPARE(COLOR(*spin.lineEdit()), red);
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == QColor("red"));
- QVERIFY(COLOR(spin) == QColor("red"));
- QVERIFY(COLOR(*spin.lineEdit()) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
+ QCOMPARE(COLOR(spin), red);
+ QCOMPARE(COLOR(*spin.lineEdit()), red);
w1.setStyleSheet("color: white");
- QVERIFY(COLOR(w1) == QColor("white"));
+ QCOMPARE(COLOR(w1), white);
qApp->setStyleSheet("");
- QVERIFY(COLOR(w1) == QColor("white"));
- QVERIFY(COLOR(spin) == APPCOLOR(spin));
- QVERIFY(COLOR(*spin.lineEdit()) == APPCOLOR(*spin.lineEdit()));
+ QCOMPARE(COLOR(w1), white);
+ QCOMPARE(COLOR(spin), APPCOLOR(spin));
+ QCOMPARE(COLOR(*spin.lineEdit()), APPCOLOR(*spin.lineEdit()));
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
// QCOMPARE(FONTSIZE(w1), APPFONTSIZE(w1)); //### task 244261
QCOMPARE(FONTSIZE(spin), APPFONTSIZE(spin));
//QCOMPARE(FONTSIZE(*spin.lineEdit()), APPFONTSIZE(*spin.lineEdit())); //### task 244261
@@ -224,121 +228,135 @@ void tst_QStyleSheetStyle::widgetsAfterAppStyleSheet()
void tst_QStyleSheetStyle::applicationStyleSheet()
{
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
QPushButton w1;
qApp->setStyleSheet("* { color: red; }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
qApp->setStyleSheet("* { color: white; }");
- QVERIFY(COLOR(w1) == QColor("white"));
+ QCOMPARE(COLOR(w1), white);
qApp->setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
qApp->setStyleSheet("* { color: red }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
}
void tst_QStyleSheetStyle::windowStyleSheet()
{
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
QPushButton w1;
qApp->setStyleSheet("");
w1.setStyleSheet("* { color: red; }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
w1.setStyleSheet("* { color: white; }");
- QVERIFY(COLOR(w1) == QColor("white"));
+ QCOMPARE(COLOR(w1), white);
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
w1.setStyleSheet("* { color: red }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
qApp->setStyleSheet("* { color: green }");
- QVERIFY(COLOR(w1) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == QColor("green"));
+ QCOMPARE(COLOR(w1), QColor("green"));
qApp->setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
}
void tst_QStyleSheetStyle::widgetStyleSheet()
{
+ const QColor blue(Qt::blue);
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
QPushButton w1;
QPushButton *pb = new QPushButton(&w1);
QPushButton &w2 = *pb;
qApp->setStyleSheet("");
w1.setStyleSheet("* { color: red }");
- QVERIFY(COLOR(w1) == QColor("red"));
- QVERIFY(COLOR(w2) == QColor("red"));
+ QCOMPARE(COLOR(w1), red);
+ QCOMPARE(COLOR(w2), red);
w2.setStyleSheet("* { color: white }");
- QVERIFY(COLOR(w2) == QColor("white"));
+ QCOMPARE(COLOR(w2), white);
w1.setStyleSheet("* { color: blue }");
- QVERIFY(COLOR(w1) == QColor("blue"));
- QVERIFY(COLOR(w2) == QColor("white"));
+ QCOMPARE(COLOR(w1), blue);
+ QCOMPARE(COLOR(w2), white);
w1.setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
- QVERIFY(COLOR(w2) == QColor("white"));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
+ QCOMPARE(COLOR(w2), white);
w2.setStyleSheet("");
- QVERIFY(COLOR(w1) == APPCOLOR(w1));
- QVERIFY(COLOR(w2) == APPCOLOR(w2));
+ QCOMPARE(COLOR(w1), APPCOLOR(w1));
+ QCOMPARE(COLOR(w2), APPCOLOR(w2));
}
void tst_QStyleSheetStyle::reparentWithNoChildStyleSheet()
{
+ const QColor blue(Qt::blue);
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
QPushButton p1, p2;
QPushButton *pb = new QPushButton(&p1);
QPushButton &c1 = *pb; // child with no stylesheet
qApp->setStyleSheet("");
p1.setStyleSheet("* { color: red }");
- QVERIFY(COLOR(c1) == QColor("red"));
+ QCOMPARE(COLOR(c1), red);
c1.setParent(&p2);
- QVERIFY(COLOR(c1) == APPCOLOR(c1));
+ QCOMPARE(COLOR(c1), APPCOLOR(c1));
p2.setStyleSheet("* { color: white }");
- QVERIFY(COLOR(c1) == QColor("white"));
+ QCOMPARE(COLOR(c1), white);
c1.setParent(&p1);
- QVERIFY(COLOR(c1) == QColor("red"));
+ QCOMPARE(COLOR(c1), red);
qApp->setStyleSheet("* { color: blue }");
c1.setParent(0);
- QVERIFY(COLOR(c1) == QColor("blue"));
+ QCOMPARE(COLOR(c1), blue);
delete pb;
}
void tst_QStyleSheetStyle::reparentWithChildStyleSheet()
{
+ const QColor gray("gray");
+ const QColor white(Qt::white);
qApp->setStyleSheet("");
QPushButton p1, p2;
QPushButton *pb = new QPushButton(&p1);
QPushButton &c1 = *pb;
c1.setStyleSheet("background: gray");
- QVERIFY(BACKGROUND(c1) == QColor("gray"));
+ QCOMPARE(BACKGROUND(c1), gray);
c1.setParent(&p2);
- QVERIFY(BACKGROUND(c1) == QColor("gray"));
+ QCOMPARE(BACKGROUND(c1), gray);
qApp->setStyleSheet("* { color: white }");
c1.setParent(&p1);
- QVERIFY(BACKGROUND(c1) == QColor("gray"));
- QVERIFY(COLOR(c1) == QColor("white"));
+ QCOMPARE(BACKGROUND(c1), gray);
+ QCOMPARE(COLOR(c1), white);
}
void tst_QStyleSheetStyle::repolish()
{
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
qApp->setStyleSheet("");
QPushButton p1;
p1.setStyleSheet("color: red; background: white");
- QVERIFY(BACKGROUND(p1) == QColor("white"));
+ QCOMPARE(BACKGROUND(p1), white);
p1.setStyleSheet("background: white");
- QVERIFY(COLOR(p1) == APPCOLOR(p1));
+ QCOMPARE(COLOR(p1), APPCOLOR(p1));
p1.setStyleSheet("color: red");
- QVERIFY(COLOR(p1) == QColor("red"));
- QVERIFY(BACKGROUND(p1) == APPBACKGROUND(p1));
+ QCOMPARE(COLOR(p1), red);
+ QCOMPARE(BACKGROUND(p1), APPBACKGROUND(p1));
p1.setStyleSheet("");
- QVERIFY(COLOR(p1) == APPCOLOR(p1));
- QVERIFY(BACKGROUND(p1) == APPBACKGROUND(p1));
+ QCOMPARE(COLOR(p1), APPCOLOR(p1));
+ QCOMPARE(BACKGROUND(p1), APPBACKGROUND(p1));
}
void tst_QStyleSheetStyle::widgetStyle()
@@ -492,12 +510,12 @@ void tst_QStyleSheetStyle::appStyle()
QPointer<QStyle> style2 = QStyleFactory::create("Windows");
qApp->setStyle(style1);
// Basic sanity
- QVERIFY(qApp->style() == style1);
+ QCOMPARE(QApplication::style(), style1.data());
qApp->setStyle(style2);
QVERIFY(style1.isNull()); // qApp must have taken ownership and deleted it
// Setting null should not crash
qApp->setStyle(0);
- QVERIFY(qApp->style() == style2);
+ QCOMPARE(QApplication::style(), style2.data());
// Set the stylesheet
qApp->setStyleSheet("whatever");
@@ -505,7 +523,7 @@ void tst_QStyleSheetStyle::appStyle()
QVERIFY(!sss.isNull());
QCOMPARE(sss->metaObject()->className(), "QStyleSheetStyle"); // must be our proxy now
QVERIFY(!style2.isNull()); // this should exist as it is the base of the proxy
- QVERIFY(sss->baseStyle() == style2);
+ QCOMPARE(sss->baseStyle(), style2.data());
style1 = QStyleFactory::create("Windows");
qApp->setStyle(style1);
QVERIFY(style2.isNull()); // should disappear automatically
@@ -514,16 +532,16 @@ void tst_QStyleSheetStyle::appStyle()
// Update the stylesheet and check nothing changes
sss = (QStyleSheetStyle *)qApp->style();
qApp->setStyleSheet("whatever2");
- QVERIFY(qApp->style() == sss);
- QVERIFY(sss->baseStyle() == style1);
+ QCOMPARE(QApplication::style(), sss.data());
+ QCOMPARE(sss->baseStyle(), style1.data());
// Revert the stylesheet
qApp->setStyleSheet("");
QVERIFY(sss.isNull()); // should have disappeared
- QVERIFY(qApp->style() == style1);
+ QCOMPARE(QApplication::style(), style1.data());
qApp->setStyleSheet("");
- QVERIFY(qApp->style() == style1);
+ QCOMPARE(QApplication::style(), style1.data());
}
void tst_QStyleSheetStyle::dynamicProperty()
@@ -589,21 +607,24 @@ namespace ns {
void tst_QStyleSheetStyle::namespaces()
{
+ const QColor blue(Qt::blue);
+ const QColor red(Qt::red);
+ const QColor white(Qt::white);
ns::PushButton1 pb1;
qApp->setStyleSheet("ns--PushButton1 { background: white }");
- QVERIFY(BACKGROUND(pb1) == QColor("white"));
+ QCOMPARE(BACKGROUND(pb1), white);
qApp->setStyleSheet(".ns--PushButton1 { background: red }");
- QVERIFY(BACKGROUND(pb1) == QColor("red"));
+ QCOMPARE(BACKGROUND(pb1), red);
ns::PushButton2 pb2;
qApp->setStyleSheet("ns--PushButton1 { background: blue}");
- QVERIFY(BACKGROUND(pb2) == QColor("blue"));
+ QCOMPARE(BACKGROUND(pb2), blue);
qApp->setStyleSheet("ns--PushButton2 { background: magenta }");
- QVERIFY(BACKGROUND(pb2) == QColor("magenta"));
+ QCOMPARE(BACKGROUND(pb2), QColor(Qt::magenta));
qApp->setStyleSheet(".PushButtonTwo { background: white; }");
- QVERIFY(BACKGROUND(pb2) == QColor("white"));
+ QCOMPARE(BACKGROUND(pb2), white);
qApp->setStyleSheet(".PushButtonDuo { background: red; }");
- QVERIFY(BACKGROUND(pb2) == QColor("red"));
+ QCOMPARE(BACKGROUND(pb2), red);
}
void tst_QStyleSheetStyle::palettePropagation()
@@ -639,8 +660,8 @@ void tst_QStyleSheetStyle::fontPropagation()
int viewFontSize = FONTSIZE(*popup);
cb.setStyleSheet("QComboBox { font-size: 20pt; }");
- QVERIFY(FONTSIZE(cb) == 20);
- QVERIFY(FONTSIZE(*popup) == viewFontSize);
+ QCOMPARE(FONTSIZE(cb), 20);
+ QCOMPARE(FONTSIZE(*popup), viewFontSize);
QGroupBox gb;
QPushButton *push = new QPushButton(&gb);
QPushButton &pb = *push;
@@ -648,25 +669,25 @@ void tst_QStyleSheetStyle::fontPropagation()
int gbFontSize = FONTSIZE(gb);
gb.setStyleSheet("QGroupBox { font-size: 20pt }");
- QVERIFY(FONTSIZE(gb) == 20);
+ QCOMPARE(FONTSIZE(gb), 20);
QVERIFY(FONTSIZE(pb) == buttonFontSize); // font does not propagate
gb.setStyleSheet("QGroupBox * { font-size: 20pt; }");
- QVERIFY(FONTSIZE(gb) == gbFontSize);
- QVERIFY(FONTSIZE(pb) == 20);
+ QCOMPARE(FONTSIZE(gb), gbFontSize);
+ QCOMPARE(FONTSIZE(pb), 20);
QWidget window;
window.setStyleSheet("* { font-size: 10pt }");
pb.setParent(&window);
QCOMPARE(FONTSIZE(pb), 10);
window.setStyleSheet("");
- QVERIFY(FONTSIZE(pb) == buttonFontSize);
+ QCOMPARE(FONTSIZE(pb), buttonFontSize);
QTabWidget tw;
tw.setStyleSheet("QTabWidget { font-size: 20pt; }");
- QVERIFY(FONTSIZE(tw) == 20);
+ QCOMPARE(FONTSIZE(tw), 20);
QWidget *child = tw.findChild<QWidget *>("qt_tabwidget_tabbar");
QVERIFY2(child, "QTabWidget did not contain a widget named \"qt_tabwidget_tabbar\"");
- QVERIFY(FONTSIZE(*child) == 20);
+ QCOMPARE(FONTSIZE(*child), 20);
}
void tst_QStyleSheetStyle::onWidgetDestroyed()
@@ -1009,6 +1030,8 @@ void tst_QStyleSheetStyle::tabAlignement()
void tst_QStyleSheetStyle::attributesList()
{
+ const QColor blue(Qt::blue);
+ const QColor red(Qt::red);
QWidget w;
QPushButton *p1=new QPushButton(&w);
QPushButton *p2=new QPushButton(&w);
@@ -1019,10 +1042,10 @@ void tst_QStyleSheetStyle::attributesList()
p3->setProperty("prop", QStringList() << "foo" << "bar");
w.setStyleSheet(" QPushButton{ background-color:blue; } QPushButton[prop~=red] { background-color:red; }");
- QCOMPARE(BACKGROUND(*p1) , QColor("red"));
- QCOMPARE(BACKGROUND(*p2) , QColor("red"));
- QCOMPARE(BACKGROUND(*p3) , QColor("blue"));
- QCOMPARE(BACKGROUND(*p4) , QColor("blue"));
+ QCOMPARE(BACKGROUND(*p1) , red);
+ QCOMPARE(BACKGROUND(*p2) , red);
+ QCOMPARE(BACKGROUND(*p3) , blue);
+ QCOMPARE(BACKGROUND(*p4) , blue);
}
void tst_QStyleSheetStyle::minmaxSizes()
@@ -1065,6 +1088,7 @@ void tst_QStyleSheetStyle::minmaxSizes()
void tst_QStyleSheetStyle::task206238_twice()
{
+ const QColor red(Qt::red);
QMainWindow w;
QTabWidget* tw = new QTabWidget;
tw->addTab(new QLabel("foo"), "test");
@@ -1073,12 +1097,12 @@ void tst_QStyleSheetStyle::task206238_twice()
centerOnScreen(&w);
w.show();
QTest::qWait(20);
- QCOMPARE(BACKGROUND(w) , QColor("red"));
- QCOMPARE(BACKGROUND(*tw), QColor("red"));
+ QCOMPARE(BACKGROUND(w) , red);
+ QCOMPARE(BACKGROUND(*tw), red);
w.setStyleSheet("background: red;");
QTest::qWait(20);
- QCOMPARE(BACKGROUND(w) , QColor("red"));
- QCOMPARE(BACKGROUND(*tw), QColor("red"));
+ QCOMPARE(BACKGROUND(w) , red);
+ QCOMPARE(BACKGROUND(*tw), red);
}
void tst_QStyleSheetStyle::transparent()
diff --git a/tests/auto/widgets/util/qcompleter/BLACKLIST b/tests/auto/widgets/util/qcompleter/BLACKLIST
index ffbcc94a1f..fdc424b6ac 100644
--- a/tests/auto/widgets/util/qcompleter/BLACKLIST
+++ b/tests/auto/widgets/util/qcompleter/BLACKLIST
@@ -1,2 +1,2 @@
[QTBUG_14292_filesystem]
-ubuntu-14.04
+linux
diff --git a/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp b/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp
index dbfeda8104..e8ac9aa5d2 100644
--- a/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp
+++ b/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp
@@ -1043,9 +1043,9 @@ void tst_QCompleter::setters()
QAbstractItemModel *oldModel = completer->model();
completer->setModel(dirModel);
QVERIFY(completer->popup()->model() != oldModel);
- QVERIFY(completer->popup()->model() == completer->completionModel());
+ QCOMPARE(completer->popup()->model(), completer->completionModel());
completer->setPopup(new QListView);
- QVERIFY(completer->popup()->model() == completer->completionModel());
+ QCOMPARE(completer->popup()->model(), completer->completionModel());
completer->setModel(new QStringListModel(completer));
QVERIFY(dirModel == 0); // must have been deleted
@@ -1062,7 +1062,7 @@ void tst_QCompleter::modelDeletion()
QStringListModel *listModel = new QStringListModel(list);
completer->setCompletionPrefix("i");
completer->setModel(listModel);
- QVERIFY(completer->completionCount() == 3);
+ QCOMPARE(completer->completionCount(), 3);
QScopedPointer<QListView> view(new QListView);
view->setModel(completer->completionModel());
delete listModel;
@@ -1070,8 +1070,8 @@ void tst_QCompleter::modelDeletion()
view->show();
qApp->processEvents();
view.reset();
- QVERIFY(completer->completionCount() == 0);
- QVERIFY(completer->currentRow() == -1);
+ QCOMPARE(completer->completionCount(), 0);
+ QCOMPARE(completer->currentRow(), -1);
}
void tst_QCompleter::multipleWidgets()
@@ -1098,7 +1098,7 @@ void tst_QCompleter::multipleWidgets()
window.activateWindow();
QApplication::setActiveWindow(&window);
QTest::qWait(50);
- QTRY_VERIFY(qApp->focusWidget() == comboBox);
+ QTRY_COMPARE(QApplication::focusWidget(), comboBox);
comboBox->lineEdit()->setText("it");
QCOMPARE(comboBox->currentText(), QString("it")); // should not complete with setText
QTest::keyPress(comboBox, 'e');
@@ -1111,7 +1111,7 @@ void tst_QCompleter::multipleWidgets()
lineEdit->show();
lineEdit->setFocus();
QTest::qWait(50);
- QTRY_VERIFY(qApp->focusWidget() == lineEdit);
+ QTRY_COMPARE(QApplication::focusWidget(), lineEdit);
lineEdit->setText("it");
QCOMPARE(lineEdit->text(), QString("it")); // should not completer with setText
QCOMPARE(comboBox->currentText(), QString("")); // combo box text must not change!
@@ -1148,13 +1148,13 @@ void tst_QCompleter::focusIn()
lineEdit2->show();
comboBox->setFocus();
- QTRY_VERIFY(completer.widget() == comboBox);
+ QTRY_COMPARE(completer.widget(), comboBox);
lineEdit->setFocus();
- QTRY_VERIFY(completer.widget() == lineEdit);
+ QTRY_COMPARE(completer.widget(), lineEdit);
comboBox->setFocus();
- QTRY_VERIFY(completer.widget() == comboBox);
+ QTRY_COMPARE(completer.widget(), comboBox);
lineEdit2->setFocus();
- QTRY_VERIFY(completer.widget() == comboBox);
+ QTRY_COMPARE(completer.widget(), comboBox);
}
void tst_QCompleter::dynamicSortOrder()
diff --git a/tests/auto/widgets/util/qscroller/tst_qscroller.cpp b/tests/auto/widgets/util/qscroller/tst_qscroller.cpp
index d2e88a1656..58a655321c 100644
--- a/tests/auto/widgets/util/qscroller/tst_qscroller.cpp
+++ b/tests/auto/widgets/util/qscroller/tst_qscroller.cpp
@@ -297,7 +297,7 @@ void tst_QScroller::staticScrollers()
QScrollerProperties sp2 = QScroller::scroller(o2)->scrollerProperties();
// default properties should be the same
- QVERIFY(sp1 == sp2);
+ QCOMPARE(sp1, sp2);
QCOMPARE(QScroller::scroller(o1)->scrollerProperties(), sp1);
diff --git a/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp b/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp
index 7ea63911ae..05511a17a1 100644
--- a/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp
+++ b/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp
@@ -136,7 +136,7 @@ void tst_QSystemTrayIcon::lastWindowClosed()
QTimer::singleShot(2500, &window, SLOT(close()));
QTimer::singleShot(20000, qApp, SLOT(quit())); // in case the test fails
qApp->exec();
- QVERIFY(spy.count() == 1);
+ QCOMPARE(spy.count(), 1);
}
QTEST_MAIN(tst_QSystemTrayIcon)
diff --git a/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp b/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
index a633ba0cf0..43d6912c6e 100644
--- a/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
+++ b/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
@@ -283,9 +283,9 @@ void tst_QAbstractButton::setAutoRepeat()
QTest::qWait(REPEAT_DELAY);
QVERIFY(testWidget->isDown());
QTest::keyRelease(testWidget, Qt::Key_Space);
- QVERIFY(release_count == press_count);
- QVERIFY(toggle_count == 0);
- QVERIFY(press_count == click_count);
+ QCOMPARE(release_count, press_count);
+ QCOMPARE(toggle_count, uint(0));
+ QCOMPARE(press_count, click_count);
QVERIFY(click_count > 1);
break;
case 4:
diff --git a/tests/auto/widgets/widgets/qbuttongroup/tst_qbuttongroup.cpp b/tests/auto/widgets/widgets/qbuttongroup/tst_qbuttongroup.cpp
index df69063540..5dec6224ca 100644
--- a/tests/auto/widgets/widgets/qbuttongroup/tst_qbuttongroup.cpp
+++ b/tests/auto/widgets/widgets/qbuttongroup/tst_qbuttongroup.cpp
@@ -324,13 +324,13 @@ void tst_QButtonGroup::testSignals()
int expectedId = -2;
- QVERIFY(clickedIdSpy.takeFirst().at(0).toInt() == expectedId);
+ QCOMPARE(clickedIdSpy.takeFirst().at(0).toInt(), expectedId);
QCOMPARE(pressedSpy.count(), 1);
QCOMPARE(pressedIdSpy.count(), 1);
- QVERIFY(pressedIdSpy.takeFirst().at(0).toInt() == expectedId);
+ QCOMPARE(pressedIdSpy.takeFirst().at(0).toInt(), expectedId);
QCOMPARE(releasedSpy.count(), 1);
QCOMPARE(releasedIdSpy.count(), 1);
- QVERIFY(releasedIdSpy.takeFirst().at(0).toInt() == expectedId);
+ QCOMPARE(releasedIdSpy.takeFirst().at(0).toInt(), expectedId);
clickedSpy.clear();
clickedIdSpy.clear();
@@ -344,13 +344,13 @@ void tst_QButtonGroup::testSignals()
QCOMPARE(clickedSpy.count(), 1);
QCOMPARE(clickedIdSpy.count(), 1);
- QVERIFY(clickedIdSpy.takeFirst().at(0).toInt() == 23);
+ QCOMPARE(clickedIdSpy.takeFirst().at(0).toInt(), 23);
QCOMPARE(pressedSpy.count(), 1);
QCOMPARE(pressedIdSpy.count(), 1);
- QVERIFY(pressedIdSpy.takeFirst().at(0).toInt() == 23);
+ QCOMPARE(pressedIdSpy.takeFirst().at(0).toInt(), 23);
QCOMPARE(releasedSpy.count(), 1);
QCOMPARE(releasedIdSpy.count(), 1);
- QVERIFY(releasedIdSpy.takeFirst().at(0).toInt() == 23);
+ QCOMPARE(releasedIdSpy.takeFirst().at(0).toInt(), 23);
QSignalSpy toggledSpy(&buttons, SIGNAL(buttonToggled(QAbstractButton*, bool)));
@@ -427,25 +427,25 @@ void tst_QButtonGroup::checkedButton()
buttons.addButton(&pb1);
buttons.addButton(&pb2, 23);
- QVERIFY(buttons.checkedButton() == 0);
+ QVERIFY(!buttons.checkedButton());
pb1.setChecked(true);
- QVERIFY(buttons.checkedButton() == &pb1);
+ QCOMPARE(buttons.checkedButton(), &pb1);
pb2.setChecked(true);
- QVERIFY(buttons.checkedButton() == &pb2);
+ QCOMPARE(buttons.checkedButton(), &pb2);
pb2.setChecked(false);
- QVERIFY(buttons.checkedButton() == &pb1);
+ QCOMPARE(buttons.checkedButton(), &pb1);
pb1.setChecked(false);
- QVERIFY(buttons.checkedButton() == 0);
+ QVERIFY(!buttons.checkedButton());
buttons.setExclusive(true);
- QVERIFY(buttons.checkedButton() == 0);
+ QVERIFY(!buttons.checkedButton());
pb1.setChecked(true);
- QVERIFY(buttons.checkedButton() == &pb1);
+ QCOMPARE(buttons.checkedButton(), &pb1);
pb2.setChecked(true);
- QVERIFY(buttons.checkedButton() == &pb2);
+ QCOMPARE(buttons.checkedButton(), &pb2);
// checked button cannot be unchecked
pb2.setChecked(false);
- QVERIFY(buttons.checkedButton() == &pb2);
+ QCOMPARE(buttons.checkedButton(), &pb2);
}
class task209485_ButtonDeleter : public QObject
@@ -523,9 +523,9 @@ void tst_QButtonGroup::autoIncrementId()
radio1->setChecked(true);
- QVERIFY(buttons->id(radio1) == -2);
- QVERIFY(buttons->id(radio2) == -3);
- QVERIFY(buttons->id(radio3) == -4);
+ QCOMPARE(buttons->id(radio1), -2);
+ QCOMPARE(buttons->id(radio2), -3);
+ QCOMPARE(buttons->id(radio3), -4);
dlg.show();
}
diff --git a/tests/auto/widgets/widgets/qcheckbox/tst_qcheckbox.cpp b/tests/auto/widgets/widgets/qcheckbox/tst_qcheckbox.cpp
index e76e11fc67..5696382fab 100644
--- a/tests/auto/widgets/widgets/qcheckbox/tst_qcheckbox.cpp
+++ b/tests/auto/widgets/widgets/qcheckbox/tst_qcheckbox.cpp
@@ -83,9 +83,7 @@ private:
uint press_count;
uint release_count;
int cur_state;
- uint tmp;
QCheckBox *testWidget;
- uint tmp2;
};
tst_QCheckBox::tst_QCheckBox()
@@ -326,7 +324,7 @@ void tst_QCheckBox::isToggleButton()
void tst_QCheckBox::foregroundRole()
{
- QVERIFY(testWidget->foregroundRole() == QPalette::WindowText);
+ QCOMPARE(testWidget->foregroundRole(), QPalette::WindowText);
}
void tst_QCheckBox::minimumSizeHint()
diff --git a/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp b/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
index 7824172812..09129f0676 100644
--- a/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
+++ b/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
@@ -164,6 +164,7 @@ private slots:
void keyboardSelection();
void setCustomModelAndView();
void updateDelegateOnEditableChange();
+ void respectChangedOwnershipOfItemView();
void task_QTBUG_39088_inputMethodHints();
};
@@ -453,7 +454,7 @@ void tst_QComboBox::setPalette()
for (int i = 0; i < comboChildren.size(); ++i) {
QObject *o = comboChildren.at(i);
if (o->isWidgetType()) {
- QVERIFY(((QWidget*)o)->palette() == pal);
+ QCOMPARE(((QWidget*)o)->palette(), pal);
}
}
@@ -462,12 +463,12 @@ void tst_QComboBox::setPalette()
//Setting it on the lineedit should be separate form the combo
testWidget->lineEdit()->setPalette(pal);
QVERIFY(testWidget->palette() != pal);
- QVERIFY(testWidget->lineEdit()->palette() == pal);
+ QCOMPARE(testWidget->lineEdit()->palette(), pal);
pal.setColor(QPalette::Base, Qt::green);
//Setting it on the combo directly should override lineedit
testWidget->setPalette(pal);
- QVERIFY(testWidget->palette() == pal);
- QVERIFY(testWidget->lineEdit()->palette() == pal);
+ QCOMPARE(testWidget->palette(), pal);
+ QCOMPARE(testWidget->lineEdit()->palette(), pal);
}
void tst_QComboBox::sizeAdjustPolicy()
@@ -478,7 +479,7 @@ void tst_QComboBox::sizeAdjustPolicy()
QComboBox *testWidget = topLevel.comboBox();
// test that adding new items will not change the sizehint for AdjustToContentsOnFirstShow
QVERIFY(!testWidget->count());
- QVERIFY(testWidget->sizeAdjustPolicy() == QComboBox::AdjustToContentsOnFirstShow);
+ QCOMPARE(testWidget->sizeAdjustPolicy(), QComboBox::AdjustToContentsOnFirstShow);
QVERIFY(testWidget->isVisible());
QSize firstShow = testWidget->sizeHint();
testWidget->addItem("normal item");
@@ -751,7 +752,7 @@ void tst_QComboBox::insertPolicy()
// First check that there is the right number of entries, or
// we may unwittingly pass
- QVERIFY((int)result.count() == testWidget->count());
+ QCOMPARE((int)result.count(), testWidget->count());
// No need to compare if there are no strings to compare
if (result.count() > 0) {
@@ -796,7 +797,7 @@ void tst_QComboBox::virtualAutocompletion()
QApplication::sendEvent(testWidget, &kr1);
qApp->processEvents(); // Process events to trigger autocompletion
- QTRY_VERIFY(testWidget->currentIndex() == 1);
+ QTRY_COMPARE(testWidget->currentIndex(), 1);
QKeyEvent kp2(QEvent::KeyPress, Qt::Key_O, 0, "o");
QKeyEvent kr2(QEvent::KeyRelease, Qt::Key_O, 0, "o");
@@ -845,7 +846,7 @@ void tst_QComboBox::autoCompletionCaseSensitivity()
testWidget->clearEditText();
QSignalSpy spyReturn(testWidget, SIGNAL(activated(int)));
testWidget->setAutoCompletionCaseSensitivity(Qt::CaseInsensitive);
- QVERIFY(testWidget->autoCompletionCaseSensitivity() == Qt::CaseInsensitive);
+ QCOMPARE(testWidget->autoCompletionCaseSensitivity(), Qt::CaseInsensitive);
QTest::keyClick(testWidget->lineEdit(), Qt::Key_A);
qApp->processEvents();
@@ -879,7 +880,7 @@ void tst_QComboBox::autoCompletionCaseSensitivity()
// case sensitive
testWidget->clearEditText();
testWidget->setAutoCompletionCaseSensitivity(Qt::CaseSensitive);
- QVERIFY(testWidget->autoCompletionCaseSensitivity() == Qt::CaseSensitive);
+ QCOMPARE(testWidget->autoCompletionCaseSensitivity(), Qt::CaseSensitive);
QTest::keyClick(testWidget->lineEdit(), Qt::Key_A);
qApp->processEvents();
QCOMPARE(testWidget->currentText(), QString("aww"));
@@ -1377,7 +1378,7 @@ void tst_QComboBox::textpixmapdata()
QCOMPARE(icon.cacheKey(), icons.at(i).cacheKey());
QPixmap original = icons.at(i).pixmap(1024);
QPixmap pixmap = icon.pixmap(1024);
- QVERIFY(pixmap.toImage() == original.toImage());
+ QCOMPARE(pixmap.toImage(), original.toImage());
}
for (int i = 0; i<text.count(); ++i) {
@@ -1611,7 +1612,7 @@ void tst_QComboBox::setModel()
QCOMPARE(box.currentIndex(), 0);
QVERIFY(box.model() != oldModel);
QVERIFY(box.rootModelIndex() != rootModelIndex);
- QVERIFY(box.rootModelIndex() == QModelIndex());
+ QCOMPARE(box.rootModelIndex(), QModelIndex());
// check that setting the very same model doesn't move the current item
box.setCurrentIndex(1);
@@ -3178,5 +3179,27 @@ void tst_QComboBox::task_QTBUG_39088_inputMethodHints()
QCOMPARE(box.lineEdit()->inputMethodHints(), Qt::ImhNoPredictiveText);
}
+void tst_QComboBox::respectChangedOwnershipOfItemView()
+{
+ QComboBox box1;
+ QComboBox box2;
+ QTableView *v1 = new QTableView;
+ box1.setView(v1);
+
+ QSignalSpy spy1(v1, SIGNAL(destroyed()));
+ box2.setView(v1); // Ownership should now be transferred to box2
+
+
+ QTableView *v2 = new QTableView(&box1);
+ box1.setView(v2); // Here we do not expect v1 to be deleted
+ QApplication::processEvents();
+ QCOMPARE(spy1.count(), 0);
+
+ QSignalSpy spy2(v2, SIGNAL(destroyed()));
+ box1.setView(v1);
+ QCOMPARE(spy2.count(), 1);
+}
+
+
QTEST_MAIN(tst_QComboBox)
#include "tst_qcombobox.moc"
diff --git a/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp b/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
index d8cb7c01ad..a57553097a 100644
--- a/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
+++ b/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
@@ -98,11 +98,11 @@ void tst_QCommandLinkButton::getSetCheck()
QString text("mytext");
QVERIFY(obj1.description().isEmpty());
obj1.setDescription(text);
- QVERIFY(obj1.description() == text);
+ QCOMPARE(obj1.description(), text);
QVERIFY(obj1.text().isEmpty());
obj1.setText(text);
- QVERIFY(obj1.text() == text);
+ QCOMPARE(obj1.text(), text);
QMenu *var1 = new QMenu;
obj1.setMenu(var1);
@@ -236,8 +236,8 @@ void tst_QCommandLinkButton::setAutoRepeat()
QVERIFY( testWidget->isDown() );
QVERIFY( toggle_count == 0 );
QTest::keyRelease( testWidget, Qt::Key_Space );
- QVERIFY(press_count == release_count);
- QVERIFY(release_count == click_count);
+ QCOMPARE(press_count, release_count);
+ QCOMPARE(release_count, click_count);
QVERIFY(press_count > 1);
// #### shouldn't I check here to see if multiple signals have been fired???
diff --git a/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp b/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
index c9ae60dd76..e8a0916dc5 100644
--- a/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
+++ b/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
@@ -2416,7 +2416,7 @@ void tst_QDateTimeEdit::displayedSections()
QFETCH(uint, section);
testWidget->setDisplayFormat(format);
- QVERIFY((QDateTimeEdit::Section)section == testWidget->displayedSections());
+ QCOMPARE(QDateTimeEdit::Sections(section), testWidget->displayedSections());
}
void tst_QDateTimeEdit::currentSection_data()
@@ -2460,7 +2460,7 @@ void tst_QDateTimeEdit::currentSection()
if ((QDateTimeEdit::Section)section == QDateTimeEdit::NoSection)
testWidget->setCurrentSection(QDateTimeEdit::YearSection); // Ensure it's not reset (see above)
testWidget->setCurrentSection((QDateTimeEdit::Section)section);
- QVERIFY((QDateTimeEdit::Section)currentSection == testWidget->currentSection());
+ QCOMPARE((QDateTimeEdit::Section)currentSection, testWidget->currentSection());
}
void tst_QDateTimeEdit::readOnly()
@@ -2825,7 +2825,7 @@ void tst_QDateTimeEdit::calendarPopup()
rect = style->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, &timeEdit);
QTest::mouseClick(&timeEdit, Qt::LeftButton, 0, QPoint(rect.left()+rect.width()/2, rect.top()+rect.height()/2));
QWidget *wid2 = timeEdit.findChild<QWidget *>("qt_datetimedit_calendar");
- QVERIFY(wid2 == 0);
+ QVERIFY(!wid2);
timeEdit.hide();
@@ -2839,7 +2839,7 @@ void tst_QDateTimeEdit::calendarPopup()
rect = style->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, &dateEdit);
QTest::mouseClick(&dateEdit, Qt::LeftButton, 0, QPoint(rect.left()+rect.width()/2, rect.top()+rect.height()/2));
QWidget *wid3 = dateEdit.findChild<QWidget *>("qt_datetimedit_calendar");
- QVERIFY(wid3 == 0);
+ QVERIFY(!wid3);
dateEdit.hide();
}
diff --git a/tests/auto/widgets/widgets/qdialogbuttonbox/tst_qdialogbuttonbox.cpp b/tests/auto/widgets/widgets/qdialogbuttonbox/tst_qdialogbuttonbox.cpp
index 38b473e5ae..32412afcd5 100644
--- a/tests/auto/widgets/widgets/qdialogbuttonbox/tst_qdialogbuttonbox.cpp
+++ b/tests/auto/widgets/widgets/qdialogbuttonbox/tst_qdialogbuttonbox.cpp
@@ -132,12 +132,12 @@ void tst_QDialogButtonBox::layoutReuse()
QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok);
QPointer<QLayout> layout = box->layout();
box->setCenterButtons(!box->centerButtons());
- QVERIFY(layout == box->layout());
+ QCOMPARE(layout.data(), box->layout());
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(box, &event);
- QVERIFY(layout == box->layout());
+ QCOMPARE(layout.data(), box->layout());
box->setOrientation(box->orientation() == Qt::Horizontal ? Qt::Vertical : Qt::Horizontal);
- QVERIFY(layout == 0);
+ QVERIFY(layout.isNull());
QVERIFY(layout != box->layout());
delete box;
}
diff --git a/tests/auto/widgets/widgets/qdockwidget/BLACKLIST b/tests/auto/widgets/widgets/qdockwidget/BLACKLIST
new file mode 100644
index 0000000000..60adfb9f4b
--- /dev/null
+++ b/tests/auto/widgets/widgets/qdockwidget/BLACKLIST
@@ -0,0 +1,2 @@
+[restoreDockWidget]
+ubuntu-14.04
diff --git a/tests/auto/widgets/widgets/qdockwidget/tst_qdockwidget.cpp b/tests/auto/widgets/widgets/qdockwidget/tst_qdockwidget.cpp
index 2bbc2e05b7..82832bced1 100644
--- a/tests/auto/widgets/widgets/qdockwidget/tst_qdockwidget.cpp
+++ b/tests/auto/widgets/widgets/qdockwidget/tst_qdockwidget.cpp
@@ -120,7 +120,7 @@ void tst_QDockWidget::widget()
{
{
QDockWidget dw;
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
}
{
@@ -130,32 +130,32 @@ void tst_QDockWidget::widget()
dw.setWidget(w1);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w1);
+ QCOMPARE(dw.widget(), w1);
QCOMPARE(w1->parentWidget(), (QWidget*)&dw);
dw.setWidget(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
dw.setWidget(w2);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w2);
+ QCOMPARE(dw.widget(), w2);
QCOMPARE(w2->parentWidget(), (QWidget*)&dw);
dw.setWidget(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
dw.setWidget(w1);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w1);
+ QCOMPARE(dw.widget(), w1);
QCOMPARE(w1->parentWidget(), (QWidget*)&dw);
dw.setWidget(w2);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w2);
+ QCOMPARE(dw.widget(), w2);
QCOMPARE(w2->parentWidget(), (QWidget*)&dw);
dw.setWidget(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
}
{
@@ -165,37 +165,37 @@ void tst_QDockWidget::widget()
dw.setWidget(w1);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w1);
+ QCOMPARE(dw.widget(), w1);
QCOMPARE(w1->parentWidget(), (QWidget*)&dw);
w1->setParent(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
dw.setWidget(w2);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w2);
+ QCOMPARE(dw.widget(), w2);
QCOMPARE(w2->parentWidget(), (QWidget*)&dw);
w2->setParent(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
dw.setWidget(w1);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w1);
+ QCOMPARE(dw.widget(), w1);
QCOMPARE(w1->parentWidget(), (QWidget*)&dw);
dw.setWidget(w2);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w2);
+ QCOMPARE(dw.widget(), w2);
QCOMPARE(w2->parentWidget(), (QWidget*)&dw);
w1->setParent(0);
QVERIFY(dw.widget() != 0);
- QVERIFY(dw.widget() == w2);
+ QCOMPARE(dw.widget(), w2);
QCOMPARE(w2->parentWidget(), (QWidget*)&dw);
w2->setParent(0);
- QVERIFY(dw.widget() == 0);
+ QVERIFY(!dw.widget());
delete w1;
delete w2;
}
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_0.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_1.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_2.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_0_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_0.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_1.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_2.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_1_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_0.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_1.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_2.png
index a75833c89c..00447760ec 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_raised_2_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_0.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_1.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_2.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_0_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_0.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_1.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_2.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_1_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_0.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_0.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_0.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_0.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_1.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_1.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_1.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_1.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_2.png b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_2.png
index d656ac56f0..4c809a2c80 100644
--- a/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_2.png
+++ b/tests/auto/widgets/widgets/qframe/images/winpanel_sunken_2_2.png
Binary files differ
diff --git a/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp b/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
index 1d995b5eea..789a280e80 100644
--- a/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
+++ b/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
@@ -111,7 +111,6 @@ private:
QLabel *testWidget;
QPointer<Widget> test_box;
QPointer<QLabel> test_label;
- QLineEdit *test_edit;
};
// Testing get/set functions
@@ -196,7 +195,7 @@ void tst_QLabel::setBuddy()
test_box = new Widget;
test_label= new QLabel( test_box );
test_label->setText( "&Test with a buddy" );
- test_edit = new QLineEdit( test_box );
+ QWidget *test_edit = new QLineEdit( test_box );
QVBoxLayout *layout = new QVBoxLayout(test_box);
layout->addWidget(test_label);
layout->addWidget(test_edit);
@@ -322,7 +321,7 @@ void tst_QLabel::eventPropagation()
test_label->setText(text);
test_box->events.clear();
test_label->setTextInteractionFlags(Qt::TextInteractionFlags(textInteractionFlags));
- QVERIFY(int(test_label->focusPolicy()) == focusPolicy);
+ QCOMPARE(int(test_label->focusPolicy()), focusPolicy);
QTest::mousePress(test_label, Qt::LeftButton);
QVERIFY(test_box->events.contains(QEvent::MouseButtonPress) == propagation); // should have propagated!
}
diff --git a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
index e6d63ee4d9..a41d80d7dd 100644
--- a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
+++ b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
@@ -1669,7 +1669,7 @@ void tst_QLineEdit::displayText()
testWidget->setEchoMode(mode);
testWidget->setText(insertString);
QCOMPARE(testWidget->displayText(), expectedString);
- QVERIFY(testWidget->echoMode() == mode);
+ QCOMPARE(testWidget->echoMode(), mode);
}
void tst_QLineEdit::passwordEchoOnEdit()
@@ -1839,9 +1839,9 @@ void tst_QLineEdit::maxLength()
// Make sure that the textChanged is not emitted unless the text is actually changed
if (insertString == expectedString) {
- QVERIFY(changed_count == 0);
+ QCOMPARE(changed_count, 0);
} else {
- QVERIFY(changed_count == 1);
+ QCOMPARE(changed_count, 1);
}
}
@@ -1962,7 +1962,7 @@ void tst_QLineEdit::psKeyClick(QTestEventList &keys, Qt::Key key, Qt::KeyboardMo
void tst_QLineEdit::cursorPosition()
{
QLineEdit *testWidget = ensureTestWidget();
- QVERIFY(testWidget->cursorPosition() == 0);
+ QCOMPARE(testWidget->cursorPosition(), 0);
// start with a basic text
QTest::keyClicks(testWidget, "The");
@@ -2208,7 +2208,7 @@ void tst_QLineEdit::selectedText()
testWidget->cursorForward(true, 9);
QVERIFY(testWidget->hasSelectedText());
QCOMPARE(testWidget->selectedText(), QString("Abc defg "));
- QVERIFY(selection_count == 1);
+ QCOMPARE(selection_count, 1);
// reset selection
testWidget->home(false);
@@ -2264,19 +2264,19 @@ void tst_QLineEdit::textChangedAndTextEdited()
QLineEdit *testWidget = ensureTestWidget();
QTest::keyClick(testWidget, Qt::Key_A);
QCOMPARE(changed_count, 1);
- QVERIFY(edited_count == changed_count);
+ QCOMPARE(edited_count, changed_count);
QTest::keyClick(testWidget, 'b');
QCOMPARE(changed_count, 2);
- QVERIFY(edited_count == changed_count);
+ QCOMPARE(edited_count, changed_count);
QTest::keyClick(testWidget, 'c');
QCOMPARE(changed_count, 3);
- QVERIFY(edited_count == changed_count);
+ QCOMPARE(edited_count, changed_count);
QTest::keyClick(testWidget, ' ');
QCOMPARE(changed_count, 4);
- QVERIFY(edited_count == changed_count);
+ QCOMPARE(edited_count, changed_count);
QTest::keyClick(testWidget, 'd');
QCOMPARE(changed_count, 5);
- QVERIFY(edited_count == changed_count);
+ QCOMPARE(edited_count, changed_count);
changed_count = 0;
edited_count = 0;
@@ -2322,27 +2322,27 @@ void tst_QLineEdit::returnPressed()
QLineEdit *testWidget = ensureTestWidget();
QTest::keyClick(testWidget, Qt::Key_Return);
- QVERIFY(return_count == 1);
+ QCOMPARE(return_count, 1);
return_count = 0;
QTest::keyClick(testWidget, 'A');
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, 'b');
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, 'c');
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, ' ');
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, 'd');
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
psKeyClick(testWidget, Qt::Key_Home);
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
psKeyClick(testWidget, Qt::Key_End);
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, Qt::Key_Escape);
- QVERIFY(return_count == 0);
+ QCOMPARE(return_count, 0);
QTest::keyClick(testWidget, Qt::Key_Return);
- QVERIFY(return_count == 1);
+ QCOMPARE(return_count, 1);
}
// int validator that fixes all !isNumber to '0'
@@ -2498,14 +2498,14 @@ void tst_QLineEdit::setValidator()
QCOMPARE(testWidget->validator(), static_cast<const QValidator*>(&iv1));
testWidget->setValidator(0);
- QVERIFY(testWidget->validator() == 0);
+ QVERIFY(!testWidget->validator());
QIntValidator iv2(0, 99, 0);
testWidget->setValidator(&iv2);
QCOMPARE(testWidget->validator(), static_cast<const QValidator *>(&iv2));
testWidget->setValidator(0);
- QVERIFY(testWidget->validator() == 0);
+ QVERIFY(!testWidget->validator());
}
void tst_QLineEdit::setValidator_QIntValidator_data()
@@ -2747,7 +2747,7 @@ void tst_QLineEdit::setAlignment()
QTEST(testWidget, "left");
#endif
#endif
- QVERIFY(testWidget->alignment() == Qt::AlignLeft);
+ QCOMPARE(testWidget->alignment(), Qt::AlignLeft);
testWidget->setText("hcenter");
testWidget->setAlignment(Qt::AlignHCenter);
@@ -2756,7 +2756,7 @@ void tst_QLineEdit::setAlignment()
QTEST(testWidget, "hcenter");
#endif
#endif
- QVERIFY(testWidget->alignment() == Qt::AlignHCenter);
+ QCOMPARE(testWidget->alignment(), Qt::AlignHCenter);
testWidget->setText("right");
testWidget->setAlignment(Qt::AlignRight);
@@ -2765,16 +2765,16 @@ void tst_QLineEdit::setAlignment()
QTEST(testWidget, "right");
#endif
#endif
- QVERIFY(testWidget->alignment() == Qt::AlignRight);
+ QCOMPARE(testWidget->alignment(), Qt::AlignRight);
testWidget->setAlignment(Qt::AlignTop);
- QVERIFY(testWidget->alignment() == Qt::AlignTop);
+ QCOMPARE(testWidget->alignment(), Qt::AlignTop);
testWidget->setAlignment(Qt::AlignBottom);
- QVERIFY(testWidget->alignment() == Qt::AlignBottom);
+ QCOMPARE(testWidget->alignment(), Qt::AlignBottom);
testWidget->setAlignment(Qt::AlignCenter);
- QVERIFY(testWidget->alignment() == Qt::AlignCenter);
+ QCOMPARE(testWidget->alignment(), Qt::AlignCenter);
}
void tst_QLineEdit::isModified()
@@ -3082,10 +3082,10 @@ void tst_QLineEdit::maxLengthAndInputMask()
QLineEdit *testWidget = ensureTestWidget();
QVERIFY(testWidget->inputMask().isNull());
testWidget->setMaxLength(10);
- QVERIFY(testWidget->maxLength() == 10);
+ QCOMPARE(testWidget->maxLength(), 10);
testWidget->setInputMask(QString::null);
QVERIFY(testWidget->inputMask().isNull());
- QVERIFY(testWidget->maxLength() == 10);
+ QCOMPARE(testWidget->maxLength(), 10);
}
@@ -4453,7 +4453,7 @@ void tst_QLineEdit::QTBUG1266_setInputMaskEmittingTextEdited()
QSignalSpy spy(&lineEdit, SIGNAL(textEdited(QString)));
lineEdit.setInputMask("AAAA");
lineEdit.setInputMask(QString());
- QVERIFY(spy.count() == 0);
+ QCOMPARE(spy.count(), 0);
}
QTEST_MAIN(tst_QLineEdit)
diff --git a/tests/auto/widgets/widgets/qmainwindow/tst_qmainwindow.cpp b/tests/auto/widgets/widgets/qmainwindow/tst_qmainwindow.cpp
index 270e5168f7..6282028746 100644
--- a/tests/auto/widgets/widgets/qmainwindow/tst_qmainwindow.cpp
+++ b/tests/auto/widgets/widgets/qmainwindow/tst_qmainwindow.cpp
@@ -149,6 +149,8 @@ private slots:
void toggleUnifiedTitleAndToolBarOnMac();
#endif
void QTBUG21378_animationFinished();
+ void resizeDocks();
+ void resizeDocks_data();
};
@@ -211,15 +213,15 @@ tst_QMainWindow::tst_QMainWindow()
void tst_QMainWindow::constructor()
{
QMainWindow mw;
- QVERIFY(mw.parentWidget() == 0);
+ QVERIFY(!mw.parentWidget());
QVERIFY(mw.isWindow());
QMainWindow mw2(&mw);
- QVERIFY(mw2.parentWidget() == &mw);
+ QCOMPARE(mw2.parentWidget(), &mw);
QVERIFY(mw2.isWindow());
QMainWindow mw3(&mw, Qt::FramelessWindowHint);
- QVERIFY(mw3.parentWidget() == &mw);
+ QCOMPARE(mw3.parentWidget(), &mw);
QVERIFY(mw3.isWindow());
}
@@ -607,7 +609,7 @@ void tst_QMainWindow::menuBar()
QVERIFY(mw.menuBar() != 0);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb1 == 0);
+ QVERIFY(mb1.isNull());
mw.setMenuBar(mb2);
QVERIFY(mw.menuBar() != 0);
@@ -618,7 +620,7 @@ void tst_QMainWindow::menuBar()
QVERIFY(mw.menuBar() != 0);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb2 == 0);
+ QVERIFY(mb2.isNull());
mb1 = new QMenuBar;
mw.setMenuBar(mb1);
@@ -631,7 +633,7 @@ void tst_QMainWindow::menuBar()
QCOMPARE(mw.menuBar(), (QMenuBar *)mb2);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb1 == 0);
+ QVERIFY(mb1.isNull());
mb1 = new QMenuBar;
mw.setMenuBar(mb1);
@@ -639,7 +641,7 @@ void tst_QMainWindow::menuBar()
QCOMPARE(mw.menuBar(), (QMenuBar *)mb1);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb2 == 0);
+ QVERIFY(mb2.isNull());
QPointer<QWidget> topLeftCornerWidget = new QWidget;
mb1->setCornerWidget(topLeftCornerWidget, Qt::TopLeftCorner);
@@ -652,7 +654,7 @@ void tst_QMainWindow::menuBar()
QCOMPARE(mw.menuBar(), (QMenuBar *)mb2);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb1 == 0);
+ QVERIFY(mb1.isNull());
QVERIFY(topLeftCornerWidget);
QCOMPARE(mb2->cornerWidget(Qt::TopLeftCorner), static_cast<QWidget *>(topLeftCornerWidget));
@@ -663,8 +665,8 @@ void tst_QMainWindow::menuBar()
QVERIFY(mw.menuBar() != 0);
//we now call deleteLater on the previous menubar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mb2 == 0);
+ QVERIFY(mb2.isNull());
QVERIFY(!topLeftCornerWidget);
QVERIFY(!topRightCornerWidget);
}
@@ -692,7 +694,7 @@ void tst_QMainWindow::statusBar()
QVERIFY(mw.statusBar() != 0);
//we now call deleteLater on the previous statusbar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(sb1 == 0);
+ QVERIFY(sb1.isNull());
mw.setStatusBar(sb2);
QVERIFY(mw.statusBar() != 0);
@@ -703,7 +705,7 @@ void tst_QMainWindow::statusBar()
QVERIFY(mw.statusBar() != 0);
//we now call deleteLater on the previous statusbar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(sb2 == 0);
+ QVERIFY(sb2.isNull());
sb1 = new QStatusBar;
mw.setStatusBar(sb1);
@@ -718,7 +720,7 @@ void tst_QMainWindow::statusBar()
QCOMPARE(sb2->parentWidget(), (QWidget *)&mw);
//we now call deleteLater on the previous statusbar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(sb1 == 0);
+ QVERIFY(sb1.isNull());
sb1 = new QStatusBar;
mw.setStatusBar(sb1);
@@ -727,7 +729,7 @@ void tst_QMainWindow::statusBar()
QCOMPARE(sb1->parentWidget(), (QWidget *)&mw);
//we now call deleteLater on the previous statusbar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(sb2 == 0);
+ QVERIFY(sb2.isNull());
sb2 = new QStatusBar;
mw.setStatusBar(sb2);
@@ -736,7 +738,7 @@ void tst_QMainWindow::statusBar()
QCOMPARE(sb2->parentWidget(), (QWidget *)&mw);
//we now call deleteLater on the previous statusbar
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(sb1 == 0);
+ QVERIFY(sb1.isNull());
}
{
@@ -749,7 +751,7 @@ void tst_QMainWindow::statusBar()
QVERIFY(indexOfSb != -1);
delete sb;
indexOfSb = l->indexOf(sb);
- QVERIFY(indexOfSb == -1);
+ QCOMPARE(indexOfSb, -1);
}
}
@@ -791,7 +793,7 @@ void tst_QMainWindow::centralWidget()
{
{
QMainWindow mw;
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
}
{
@@ -799,7 +801,7 @@ void tst_QMainWindow::centralWidget()
QPointer<QWidget> w1 = new QWidget;
QPointer<QWidget> w2 = new QWidget;
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
mw.setCentralWidget(w1);
QVERIFY(mw.centralWidget() != 0);
@@ -812,12 +814,12 @@ void tst_QMainWindow::centralWidget()
QCOMPARE(w2->parentWidget(), (QWidget *)&mw);
mw.setCentralWidget(0);
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
//we now call deleteLater on the previous central widgets
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(w1 == 0);
- QVERIFY(w2 == 0);
+ QVERIFY(w1.isNull());
+ QVERIFY(w2.isNull());
}
{
@@ -831,7 +833,7 @@ void tst_QMainWindow::centralWidget()
QPointer<QWidget> w1 = new QWidget;
QPointer<QWidget> w2 = new QWidget;
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
mw.setCentralWidget(w1);
QVERIFY(mw.centralWidget() != 0);
@@ -844,12 +846,12 @@ void tst_QMainWindow::centralWidget()
QCOMPARE(w2->parentWidget(), (QWidget *)&mw);
mw.setCentralWidget(0);
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
//we now call deleteLater on the previous central widgets
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(w1 == 0);
- QVERIFY(w2 == 0);
+ QVERIFY(w1.isNull());
+ QVERIFY(w2.isNull());
}
}
@@ -860,25 +862,25 @@ void tst_QMainWindow::takeCentralWidget() {
QPointer<QWidget> w1 = new QWidget;
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
mw.setCentralWidget(w1);
QWidget *oldCentralWidget = mw.takeCentralWidget();
- QVERIFY(oldCentralWidget == w1.data());
+ QCOMPARE(oldCentralWidget, w1.data());
// ensure that takeCentralWidget doesn't end up calling deleteLater
// on the central widget
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
QVERIFY(!w1.isNull());
- QVERIFY(w1->parent() == 0);
+ QVERIFY(!w1->parent());
mw.setCentralWidget(w1);
// ensure that the deleteLater called by setCentralWidget
// gets executed
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- QVERIFY(mw.centralWidget() == w1.data());
+ QCOMPARE(mw.centralWidget(), w1.data());
QPointer<QWidget> w2 = new QWidget;
@@ -887,10 +889,10 @@ void tst_QMainWindow::takeCentralWidget() {
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
QVERIFY(w1.isNull());
- QVERIFY(mw.centralWidget() == w2.data());
+ QCOMPARE(mw.centralWidget(), w2.data());
QWidget *hopefullyW2 = mw.takeCentralWidget();
- QVERIFY(mw.centralWidget() == 0);
+ QVERIFY(!mw.centralWidget());
// ensure that takeCentralWidget doesn't end up calling deleteLater
// on the central widget
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
@@ -1928,9 +1930,9 @@ void tst_QMainWindow::toggleUnifiedTitleAndToolBarOnMac()
mw.show();
QRect frameGeometry = mw.frameGeometry();
mw.setUnifiedTitleAndToolBarOnMac(false);
- QVERIFY(frameGeometry.topLeft() == mw.frameGeometry().topLeft());
+ QCOMPARE(frameGeometry.topLeft(), mw.frameGeometry().topLeft());
mw.setUnifiedTitleAndToolBarOnMac(true);
- QVERIFY(frameGeometry.topLeft() == mw.frameGeometry().topLeft());
+ QCOMPARE(frameGeometry.topLeft(), mw.frameGeometry().topLeft());
}
#endif
@@ -1950,5 +1952,96 @@ void tst_QMainWindow::QTBUG21378_animationFinished()
delete mwClickTimer;
QVERIFY(true);
}
+
+Q_DECLARE_METATYPE(Qt::Orientation)
+
+void tst_QMainWindow::resizeDocks_data()
+{
+ QTest::addColumn<Qt::Orientation>("orientation");
+ QTest::addColumn<QStringList>("docks");
+ QTest::addColumn<QList<int> >("sizes");
+
+ QTest::newRow("1") << Qt::Horizontal
+ << (QStringList() << "blue" << "orange" << "green" << "gray")
+ << (QList<int>() << 190 << 190 << 320 << 160);
+
+ QTest::newRow("2") << Qt::Vertical
+ << (QStringList() << "yellow" << "orange")
+ << (QList<int>() << 147 << 133 );
+
+
+ QTest::newRow("3") << Qt::Horizontal
+ << (QStringList() << "blue" << "yellow")
+ << (QList<int>() << 190 << 600);
+}
+
+void tst_QMainWindow::resizeDocks()
+{
+ AddList addList;
+ addList
+ << AddDockWidget("blue", Qt::LeftDockWidgetArea)
+ << AddDockWidget("red", Qt::TopDockWidgetArea)
+ << AddDockWidget("pink", "red")
+ << AddDockWidget("yellow", Qt::RightDockWidgetArea)
+ << AddDockWidget("orange", Qt::RightDockWidgetArea)
+ << AddDockWidget("green", "orange", Qt::Horizontal)
+ << AddDockWidget("gray", "orange", Qt::Horizontal);
+ /*
+ +--------------------------------+
+ | red/pink |
+ +------+-+-----------------------+
+ | | | yellow |
+ | blue + +--------+------+-------+
+ | | | orange | gray | green |
+ +------+-+--------+------+-------+
+
+ */
+
+ QMainWindow mw(0, Qt::BypassWindowManagerHint);
+ mw.setDockNestingEnabled(true);
+ mw.resize(1800, 600);
+
+ foreach (const AddDockWidget &i, addList)
+ i.apply(&mw);
+
+ foreach (QDockWidget *dw, mw.findChildren<QDockWidget *>())
+ dw->setStyleSheet( "* { background-color: " + dw->objectName() +" }");
+
+ mw.setCentralWidget(new QTextEdit);
+
+ mw.show();
+ QTest::qWaitForWindowExposed(&mw);
+
+ QFETCH(Qt::Orientation, orientation);
+ QFETCH(QStringList, docks);
+ QFETCH(QList<int>, sizes);
+
+ QList<QDockWidget *> list;
+ foreach (const QString &name, docks) {
+ QDockWidget *d = mw.findChild<QDockWidget *>(name);
+ QVERIFY(d);
+ list << d;
+ }
+
+ mw.resizeDocks(list, sizes, orientation);
+
+ qApp->processEvents();
+
+ int totalFromList = 0;
+ int actualTotal = 0;
+ for (int i = 0; i < docks.count(); ++i) {
+ totalFromList += sizes[i];
+ QSize s = list[i]->size();
+ actualTotal += (orientation == Qt::Horizontal) ? s.width() : s.height();
+// qDebug() << list[i] << list[i]->size() << sizes[i];
+ }
+
+ for (int i = 0; i < docks.count(); ++i) {
+ QSize s = list[i]->size();
+ int value = (orientation == Qt::Horizontal) ? s.width() : s.height();
+ QCOMPARE(value, qRound(sizes[i]*actualTotal/double(totalFromList)));
+ }
+}
+
QTEST_MAIN(tst_QMainWindow)
#include "tst_qmainwindow.moc"
diff --git a/tests/auto/widgets/widgets/qmdiarea/BLACKLIST b/tests/auto/widgets/widgets/qmdiarea/BLACKLIST
index b8640e9ac3..63da2e3ae3 100644
--- a/tests/auto/widgets/widgets/qmdiarea/BLACKLIST
+++ b/tests/auto/widgets/widgets/qmdiarea/BLACKLIST
@@ -1,2 +1,5 @@
[updateScrollBars]
osx
+[tileSubWindows]
+osx
+xcb
diff --git a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
index 53defce423..e7de027b22 100644
--- a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
+++ b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
@@ -377,13 +377,13 @@ void tst_QMdiArea::subWindowActivated()
while (workspace->activeSubWindow() ) {
workspace->activeSubWindow()->close();
qApp->processEvents();
- QVERIFY(activeWindow == workspace->activeSubWindow());
+ QCOMPARE(activeWindow, workspace->activeSubWindow());
QCOMPARE(spy.count(), 1);
spy.clear();
}
- QVERIFY(activeWindow == 0);
- QVERIFY(workspace->activeSubWindow() == 0);
+ QVERIFY(!activeWindow);
+ QVERIFY(!workspace->activeSubWindow());
QCOMPARE(workspace->subWindowList().count(), 0);
{
@@ -432,13 +432,13 @@ void tst_QMdiArea::subWindowActivated()
QCOMPARE(spy.count(), 1);
spy.clear();
QVERIFY( activeWindow == window );
- QVERIFY(workspace->activeSubWindow() == window);
+ QCOMPARE(workspace->activeSubWindow(), window);
window->close();
qApp->processEvents();
QCOMPARE(spy.count(), 1);
spy.clear();
- QVERIFY(workspace->activeSubWindow() == 0);
- QVERIFY( activeWindow == 0 );
+ QVERIFY(!workspace->activeSubWindow());
+ QVERIFY(!activeWindow);
}
}
@@ -564,8 +564,8 @@ void tst_QMdiArea::subWindowActivatedWithMinimize()
window1->close();
qApp->processEvents();
- QVERIFY(workspace->activeSubWindow() == 0);
- QVERIFY( activeWindow == 0 );
+ QVERIFY(!workspace->activeSubWindow());
+ QVERIFY(!activeWindow);
QVERIFY( workspace->subWindowList().count() == 0 );
}
@@ -1104,7 +1104,7 @@ void tst_QMdiArea::addAndRemoveWindows()
QVERIFY(window);
qApp->processEvents();
QCOMPARE(workspace.subWindowList().count(), 1);
- QVERIFY(window->windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window->windowFlags(), DefaultWindowFlags);
QCOMPARE(window->size(), workspace.viewport()->size());
}
@@ -1115,7 +1115,7 @@ void tst_QMdiArea::addAndRemoveWindows()
QVERIFY(window);
qApp->processEvents();
QCOMPARE(workspace.subWindowList().count(), 2);
- QVERIFY(window->windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window->windowFlags(), DefaultWindowFlags);
QCOMPARE(window->size(), window->minimumSize());
}
@@ -1127,7 +1127,7 @@ void tst_QMdiArea::addAndRemoveWindows()
QVERIFY(window);
qApp->processEvents();
QCOMPARE(workspace.subWindowList().count(), 3);
- QVERIFY(window->windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window->windowFlags(), DefaultWindowFlags);
QCOMPARE(window->size(), QSize(1500, 1500));
}
@@ -1142,7 +1142,7 @@ void tst_QMdiArea::addAndRemoveWindows()
QMdiSubWindow *window = new QMdiSubWindow;
workspace.addSubWindow(window);
qApp->processEvents();
- QVERIFY(window->windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window->windowFlags(), DefaultWindowFlags);
window->setWidget(new QWidget);
QCOMPARE(workspace.subWindowList().count(), 4);
QTest::ignoreMessage(QtWarningMsg, "QMdiArea::addSubWindow: window is already added");
@@ -1206,7 +1206,7 @@ void tst_QMdiArea::addAndRemoveWindowsWithReparenting()
{
QMdiArea workspace;
QMdiSubWindow window(&workspace);
- QVERIFY(window.windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window.windowFlags(), DefaultWindowFlags);
// 0 because the window list contains widgets and not actual
// windows. Silly, but that's the behavior.
@@ -1219,7 +1219,7 @@ void tst_QMdiArea::addAndRemoveWindowsWithReparenting()
QCOMPARE(workspace.subWindowList().count(), 0);
window.setParent(&workspace);
QCOMPARE(workspace.subWindowList().count(), 1);
- QVERIFY(window.windowFlags() == DefaultWindowFlags);
+ QCOMPARE(window.windowFlags(), DefaultWindowFlags);
QTest::ignoreMessage(QtWarningMsg, "QMdiArea::addSubWindow: window is already added");
workspace.addSubWindow(&window);
diff --git a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
index 46d3177a56..843bb3437c 100644
--- a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
+++ b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
@@ -78,6 +78,7 @@ public slots:
private slots:
void getSetCheck();
void addActionsAndClear();
+ void addActionsConnect();
void keyboardNavigation_data();
void keyboardNavigation();
@@ -264,6 +265,34 @@ void tst_QMenu::addActionsAndClear()
QCOMPARE(menus[0]->actions().count(), 0);
}
+static void testFunction() { }
+
+void tst_QMenu::addActionsConnect()
+{
+ QMenu menu;
+ const QString text = QLatin1String("bla");
+ const QIcon icon;
+ menu.addAction(text, &menu, SLOT(deleteLater()));
+ menu.addAction(text, &menu, &QMenu::deleteLater);
+ menu.addAction(text, testFunction);
+ menu.addAction(text, &menu, testFunction);
+ menu.addAction(icon, text, &menu, SLOT(deleteLater()));
+ menu.addAction(icon, text, &menu, &QMenu::deleteLater);
+ menu.addAction(icon, text, testFunction);
+ menu.addAction(icon, text, &menu, testFunction);
+#ifndef QT_NO_SHORTCUT
+ const QKeySequence keySequence(Qt::CTRL + Qt::Key_C);
+ menu.addAction(text, &menu, SLOT(deleteLater()), keySequence);
+ menu.addAction(text, &menu, &QMenu::deleteLater, keySequence);
+ menu.addAction(text, testFunction, keySequence);
+ menu.addAction(text, &menu, testFunction, keySequence);
+ menu.addAction(icon, text, &menu, SLOT(deleteLater()), keySequence);
+ menu.addAction(icon, text, &menu, &QMenu::deleteLater, keySequence);
+ menu.addAction(icon, text, testFunction, keySequence);
+ menu.addAction(icon, text, &menu, testFunction, keySequence);
+#endif // !QT_NO_SHORTCUT
+}
+
// We have a separate mouseActivation test for Windows mobile
#ifndef Q_OS_WINCE
void tst_QMenu::mouseActivation()
@@ -334,8 +363,10 @@ void tst_QMenu::keyboardNavigation_data()
QTest::newRow("data9") << Qt::Key(Qt::Key_Down) << Qt::KeyboardModifiers(Qt::NoModifier) << 3 << 0 << false << false<< true;
QTest::newRow("data10") << Qt::Key(Qt::Key_Return) << Qt::KeyboardModifiers(Qt::NoModifier) << 3 << 0 << false << true << false;
- // Test shortcuts.
- QTest::newRow("shortcut0") << Qt::Key(Qt::Key_V) << Qt::KeyboardModifiers(Qt::AltModifier) << 5 << 0 << true << true << false;
+ if (qApp->platformName().toLower() != QStringLiteral("xcb")) {
+ // Test shortcuts.
+ QTest::newRow("shortcut0") << Qt::Key(Qt::Key_V) << Qt::KeyboardModifiers(Qt::AltModifier) << 5 << 0 << true << true << false;
+ }
}
void tst_QMenu::keyboardNavigation()
@@ -513,7 +544,7 @@ void tst_QMenu::onStatusTipTimer()
menu->close(); //goes out of the menu
QCOMPARE(st, QString("sub action"));
- QVERIFY(menu->isVisible() == false);
+ QVERIFY(!menu->isVisible());
m_onStatusTipTimerExecuted = true;
}
diff --git a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
index 31e9c737e2..baf60551c4 100644
--- a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
+++ b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
@@ -146,7 +146,7 @@ private:
QAction* m_lastSimpleAcceleratorId;
int m_simpleActivatedCount;
- int m_complexTriggerCount['k'];
+ int m_complexTriggerCount[int('k')];
};
// Testing get/set functions
@@ -534,60 +534,60 @@ void tst_QMenuBar::check_accelKeys()
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_A, Qt::ControlModifier);
QCOMPARE(m_complexTriggerCount[1], 0);
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 1);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 1);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_C, Qt::ControlModifier);
QCOMPARE(m_complexTriggerCount[1], 0);
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 1);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['c'], 1);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 1);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('c')], 1);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_B, Qt::ControlModifier);
QCOMPARE(m_complexTriggerCount[1], 0);
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 1);
- QCOMPARE(m_complexTriggerCount['b'], 1);
- QCOMPARE(m_complexTriggerCount['c'], 1);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 1);
+ QCOMPARE(m_complexTriggerCount[int('b')], 1);
+ QCOMPARE(m_complexTriggerCount[int('c')], 1);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_D, Qt::ControlModifier);
QCOMPARE(m_complexTriggerCount[1], 0);
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 1);
- QCOMPARE(m_complexTriggerCount['b'], 1);
- QCOMPARE(m_complexTriggerCount['c'], 1);
- QCOMPARE(m_complexTriggerCount['d'], 1);
+ QCOMPARE(m_complexTriggerCount[int('a')], 1);
+ QCOMPARE(m_complexTriggerCount[int('b')], 1);
+ QCOMPARE(m_complexTriggerCount[int('c')], 1);
+ QCOMPARE(m_complexTriggerCount[int('d')], 1);
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_J, Qt::AltModifier);
QCOMPARE(m_complexTriggerCount[1], 0);
QCOMPARE(m_complexTriggerCount[2], 0);
QCOMPARE(m_complexTriggerCount[3], 1);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 1);
- QCOMPARE(m_complexTriggerCount['b'], 1);
- QCOMPARE(m_complexTriggerCount['c'], 1);
- QCOMPARE(m_complexTriggerCount['d'], 1);
+ QCOMPARE(m_complexTriggerCount[int('a')], 1);
+ QCOMPARE(m_complexTriggerCount[int('b')], 1);
+ QCOMPARE(m_complexTriggerCount[int('c')], 1);
+ QCOMPARE(m_complexTriggerCount[int('d')], 1);
}
#endif
@@ -606,10 +606,10 @@ void tst_QMenuBar::check_cursorKeys1()
// the Popupmenu should be visible now
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
// Simulate a cursor key down click
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_Down );
@@ -618,10 +618,10 @@ void tst_QMenuBar::check_cursorKeys1()
// Let's see if the correct slot is called...
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0); // this shouldn't have been called
- QCOMPARE(m_complexTriggerCount['b'], 1); // and this should have been called by a signal now
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0); // this shouldn't have been called
+ QCOMPARE(m_complexTriggerCount[int('b')], 1); // and this should have been called by a signal now
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
}
#endif
@@ -648,10 +648,10 @@ void tst_QMenuBar::check_cursorKeys2()
// Let's see if the correct slot is called...
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0); // this shouldn't have been caled
- QCOMPARE(m_complexTriggerCount['b'], 0); // and this should have been called by a signal ow
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 1);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0); // this shouldn't have been caled
+ QCOMPARE(m_complexTriggerCount[int('b')], 0); // and this should have been called by a signal ow
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 1);
}
#endif
@@ -679,10 +679,10 @@ void tst_QMenuBar::check_cursorKeys3()
// Let's see if the correct slot is called...
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0); // this shouldn't have been called
- QCOMPARE(m_complexTriggerCount['b'], 1); // and this should have been called by a signal now
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0); // this shouldn't have been called
+ QCOMPARE(m_complexTriggerCount[int('b')], 1); // and this should have been called by a signal now
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
}
#endif
@@ -715,17 +715,17 @@ void tst_QMenuBar::check_homeKey()
// and press ENTER
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_Enter );
// Let's see if the correct slot is called...
-// QVERIFY2( m_complexActionTriggerCount['c'] == 1, "Popupmenu should respond to a Home key" );
- QCOMPARE(m_complexTriggerCount['c'], 1);
+// QVERIFY2( m_complexActionTriggerCount[int('c')] == 1, "Popupmenu should respond to a Home key" );
+ QCOMPARE(m_complexTriggerCount[int('c')], 1);
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
- QCOMPARE(m_complexTriggerCount['e'], 0);
- QCOMPARE(m_complexTriggerCount['f'], 0);
- QCOMPARE(m_complexTriggerCount['g'], 0);
- QCOMPARE(m_complexTriggerCount['h'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
+ QCOMPARE(m_complexTriggerCount[int('e')], 0);
+ QCOMPARE(m_complexTriggerCount[int('f')], 0);
+ QCOMPARE(m_complexTriggerCount[int('g')], 0);
+ QCOMPARE(m_complexTriggerCount[int('h')], 0);
}
/*!
@@ -754,17 +754,17 @@ void tst_QMenuBar::check_endKey()
// and press ENTER
QTest::keyClick(static_cast<QWidget *>(0), Qt::Key_Enter );
// Let's see if the correct slot is called...
-// QVERIFY2( m_complexActionTriggerCount['h'] == 1, "Popupmenu should respond to an End key" );
- QCOMPARE(m_complexTriggerCount['h'], 1);//, "Popupmenu should respond to an End key");
+// QVERIFY2( m_complexActionTriggerCount[int('h')] == 1, "Popupmenu should respond to an End key" );
+ QCOMPARE(m_complexTriggerCount[int('h')], 1);//, "Popupmenu should respond to an End key");
QCOMPARE(m_complexTriggerCount[3], 0);
QCOMPARE(m_complexTriggerCount[4], 0);
- QCOMPARE(m_complexTriggerCount['a'], 0);
- QCOMPARE(m_complexTriggerCount['b'], 0);
- QCOMPARE(m_complexTriggerCount['c'], 0);
- QCOMPARE(m_complexTriggerCount['d'], 0);
- QCOMPARE(m_complexTriggerCount['e'], 0);
- QCOMPARE(m_complexTriggerCount['f'], 0);
- QCOMPARE(m_complexTriggerCount['g'], 0);
+ QCOMPARE(m_complexTriggerCount[int('a')], 0);
+ QCOMPARE(m_complexTriggerCount[int('b')], 0);
+ QCOMPARE(m_complexTriggerCount[int('c')], 0);
+ QCOMPARE(m_complexTriggerCount[int('d')], 0);
+ QCOMPARE(m_complexTriggerCount[int('e')], 0);
+ QCOMPARE(m_complexTriggerCount[int('f')], 0);
+ QCOMPARE(m_complexTriggerCount[int('g')], 0);
}
/*!
@@ -808,7 +808,7 @@ void tst_QMenuBar::check_escKey()
// and press ENTER
QTest::keyClick( menu.menus.at(1), Qt::Key_Enter );
// Let's see if the correct slot is called...
- QVERIFY2( m_complexTriggerCount['c'] == 1, "Expected item 2C to be selected" );
+ QVERIFY2(m_complexTriggerCount[int('c')] == 1, "Expected item 2C to be selected");
}
#endif
diff --git a/tests/auto/widgets/widgets/qopenglwidget/BLACKLIST b/tests/auto/widgets/widgets/qopenglwidget/BLACKLIST
new file mode 100644
index 0000000000..725b8e93b4
--- /dev/null
+++ b/tests/auto/widgets/widgets/qopenglwidget/BLACKLIST
@@ -0,0 +1,2 @@
+[clearAndGrab]
+opensuse-13.1
diff --git a/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp b/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
index e9f9c67856..638fad6206 100644
--- a/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
+++ b/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
@@ -70,7 +70,7 @@ void tst_QOpenGLWidget::create()
QVERIFY(w->isValid());
QVERIFY(w->context());
- QVERIFY(w->context()->format() == w->format());
+ QCOMPARE(w->context()->format(), w->format());
QVERIFY(w->defaultFramebufferObject() != 0);
}
@@ -304,7 +304,7 @@ void tst_QOpenGLWidget::asViewport()
// the widget stack.
btn->update();
qApp->processEvents();
- QVERIFY(view->paintCount() == 0);
+ QCOMPARE(view->paintCount(), 0);
}
class PaintCountWidget : public QOpenGLWidget
diff --git a/tests/auto/widgets/widgets/qplaintextedit/tst_qplaintextedit.cpp b/tests/auto/widgets/widgets/qplaintextedit/tst_qplaintextedit.cpp
index e7de6b0b75..2145260013 100644
--- a/tests/auto/widgets/widgets/qplaintextedit/tst_qplaintextedit.cpp
+++ b/tests/auto/widgets/widgets/qplaintextedit/tst_qplaintextedit.cpp
@@ -333,7 +333,7 @@ void tst_QPlainTextEdit::selectAllSetsNotSelection()
QSKIP("Test only relevant for systems with selection");
QApplication::clipboard()->setText(QString("foobar"), QClipboard::Selection);
- QVERIFY(QApplication::clipboard()->text(QClipboard::Selection) == QString("foobar"));
+ QCOMPARE(QApplication::clipboard()->text(QClipboard::Selection), QString("foobar"));
ed->insertPlainText("Hello World");
ed->selectAll();
@@ -905,13 +905,13 @@ void tst_QPlainTextEdit::mouseCursorShape()
{
// always show an IBeamCursor, see change 170146
QVERIFY(!ed->isReadOnly());
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
ed->setReadOnly(true);
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
ed->setPlainText("Foo");
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
}
#endif
@@ -1324,7 +1324,7 @@ void tst_QPlainTextEdit::preserveCharFormatAfterSetPlainText()
QTextBlock block = ed->document()->begin();
block = block.next();
QCOMPARE(block.text(), QString("This should still be blue"));
- QVERIFY(block.begin().fragment().charFormat().foreground().color() == QColor(Qt::blue));
+ QCOMPARE(block.begin().fragment().charFormat().foreground().color(), QColor(Qt::blue));
}
void tst_QPlainTextEdit::extraSelections()
@@ -1444,7 +1444,7 @@ void tst_QPlainTextEdit::wordWrapProperty()
doc->setDocumentLayout(new QPlainTextDocumentLayout(doc));
edit.setDocument(doc);
edit.setWordWrapMode(QTextOption::NoWrap);
- QVERIFY(doc->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(doc->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
{
QPlainTextEdit edit;
@@ -1452,18 +1452,18 @@ void tst_QPlainTextEdit::wordWrapProperty()
doc->setDocumentLayout(new QPlainTextDocumentLayout(doc));
edit.setWordWrapMode(QTextOption::NoWrap);
edit.setDocument(doc);
- QVERIFY(doc->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(doc->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
}
void tst_QPlainTextEdit::lineWrapProperty()
{
- QVERIFY(ed->wordWrapMode() == QTextOption::WrapAtWordBoundaryOrAnywhere);
- QVERIFY(ed->lineWrapMode() == QPlainTextEdit::WidgetWidth);
+ QCOMPARE(ed->wordWrapMode(), QTextOption::WrapAtWordBoundaryOrAnywhere);
+ QCOMPARE(ed->lineWrapMode(), QPlainTextEdit::WidgetWidth);
ed->setLineWrapMode(QPlainTextEdit::NoWrap);
- QVERIFY(ed->lineWrapMode() == QPlainTextEdit::NoWrap);
- QVERIFY(ed->wordWrapMode() == QTextOption::WrapAtWordBoundaryOrAnywhere);
- QVERIFY(ed->document()->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(ed->lineWrapMode(), QPlainTextEdit::NoWrap);
+ QCOMPARE(ed->wordWrapMode(), QTextOption::WrapAtWordBoundaryOrAnywhere);
+ QCOMPARE(ed->document()->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
void tst_QPlainTextEdit::selectionChanged()
@@ -1560,7 +1560,7 @@ void tst_QPlainTextEdit::findWithRegExp()
bool found = ed->find(rx);
- QVERIFY(found == true);
+ QVERIFY(found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("text"));
}
@@ -1574,7 +1574,7 @@ void tst_QPlainTextEdit::findBackwardWithRegExp()
bool found = ed->find(rx, QTextDocument::FindBackward);
- QVERIFY(found == true);
+ QVERIFY(found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("arbit"));
}
@@ -1586,7 +1586,7 @@ void tst_QPlainTextEdit::findWithRegExpReturnsFalseIfNoMoreResults()
bool found = ed->find(rx);
- QVERIFY(found == false);
+ QVERIFY(!found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("text"));
}
#endif
diff --git a/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp b/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
index 4fd8b99acf..44a554ad82 100644
--- a/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
+++ b/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
@@ -227,8 +227,8 @@ void tst_QPushButton::autoRepeat()
QVERIFY( testWidget->isDown() );
QVERIFY( toggle_count == 0 );
QTest::keyRelease( testWidget, Qt::Key_Space );
- QVERIFY(press_count == release_count);
- QVERIFY(release_count == click_count);
+ QCOMPARE(press_count, release_count);
+ QCOMPARE(release_count, click_count);
QVERIFY(press_count > 1);
// #### shouldn't I check here to see if multiple signals have been fired???
diff --git a/tests/auto/widgets/widgets/qscrollarea/tst_qscrollarea.cpp b/tests/auto/widgets/widgets/qscrollarea/tst_qscrollarea.cpp
index 40e13c8e8d..ce6afc0a57 100644
--- a/tests/auto/widgets/widgets/qscrollarea/tst_qscrollarea.cpp
+++ b/tests/auto/widgets/widgets/qscrollarea/tst_qscrollarea.cpp
@@ -166,8 +166,8 @@ void tst_QScrollArea::checkHFW_Task_197736()
scrollArea.setWidgetResizable(false);
scrollArea.resize(QSize(100,100));
w->resize(QSize(200,200));
- QVERIFY(w->width() == 200);
- QVERIFY(w->height() == 200);
+ QCOMPARE(w->width(), 200);
+ QCOMPARE(w->height(), 200);
}
QTEST_MAIN(tst_QScrollArea)
diff --git a/tests/auto/widgets/widgets/qsizegrip/BLACKLIST b/tests/auto/widgets/widgets/qsizegrip/BLACKLIST
new file mode 100644
index 0000000000..2c874bcb57
--- /dev/null
+++ b/tests/auto/widgets/widgets/qsizegrip/BLACKLIST
@@ -0,0 +1,2 @@
+[hideAndShowOnWindowStateChange:Qt::Window]
+xcb
diff --git a/tests/auto/widgets/widgets/qspinbox/BLACKLIST b/tests/auto/widgets/widgets/qspinbox/BLACKLIST
new file mode 100644
index 0000000000..5bf6c3beed
--- /dev/null
+++ b/tests/auto/widgets/widgets/qspinbox/BLACKLIST
@@ -0,0 +1,3 @@
+[editingFinished]
+osx-10.8
+osx-10.9
diff --git a/tests/auto/widgets/widgets/qtabbar/BLACKLIST b/tests/auto/widgets/widgets/qtabbar/BLACKLIST
new file mode 100644
index 0000000000..b000b08444
--- /dev/null
+++ b/tests/auto/widgets/widgets/qtabbar/BLACKLIST
@@ -0,0 +1,2 @@
+[sizeHints]
+ubuntu-14.04
diff --git a/tests/auto/widgets/widgets/qtabwidget/tst_qtabwidget.cpp b/tests/auto/widgets/widgets/qtabwidget/tst_qtabwidget.cpp
index fffbbc2ec7..a991f18110 100644
--- a/tests/auto/widgets/widgets/qtabwidget/tst_qtabwidget.cpp
+++ b/tests/auto/widgets/widgets/qtabwidget/tst_qtabwidget.cpp
@@ -165,7 +165,7 @@ void tst_QTabWidget::init()
tw = new QTabWidget(0);
QCOMPARE(tw->count(), 0);
QCOMPARE(tw->currentIndex(), -1);
- QVERIFY(tw->currentWidget() == NULL);
+ QVERIFY(!tw->currentWidget());
}
void tst_QTabWidget::cleanup()
@@ -208,7 +208,7 @@ void tst_QTabWidget::addRemoveTab()
QCOMPARE(tw->count(), 0);
tw->removeTab(-1);
QCOMPARE(tw->count(), 0);
- QVERIFY(tw->widget(-1) == 0);
+ QVERIFY(!tw->widget(-1));
QWidget *w = new QWidget();
int index = tw->addTab(w, LABEL);
@@ -216,7 +216,7 @@ void tst_QTabWidget::addRemoveTab()
QCOMPARE(tw->indexOf(w), index);
QCOMPARE(tw->count(), 1);
- QVERIFY(tw->widget(index) == w);
+ QCOMPARE(tw->widget(index), w);
QCOMPARE(tw->tabText(index), QString(LABEL));
removePage(index);
@@ -238,7 +238,7 @@ void tst_QTabWidget::tabPosition()
void tst_QTabWidget::tabEnabled()
{
// Test bad arguments
- QVERIFY(tw->isTabEnabled(-1) == false);
+ QVERIFY(!tw->isTabEnabled(-1));
tw->setTabEnabled(-1, false);
int index = addPage();
@@ -333,21 +333,21 @@ void tst_QTabWidget::currentWidget()
{
// Test bad arguments
tw->setCurrentWidget(NULL);
- QVERIFY(tw->currentWidget() == NULL);
+ QVERIFY(!tw->currentWidget());
int index = addPage();
QWidget *w = tw->widget(index);
- QVERIFY(tw->currentWidget() == w);
+ QCOMPARE(tw->currentWidget(), w);
QCOMPARE(tw->currentIndex(), index);
tw->setCurrentWidget(NULL);
- QVERIFY(tw->currentWidget() == w);
+ QCOMPARE(tw->currentWidget(), w);
QCOMPARE(tw->currentIndex(), index);
int index2 = addPage();
QWidget *w2 = tw->widget(index2);
Q_UNUSED(w2);
- QVERIFY(tw->currentWidget() == w);
+ QCOMPARE(tw->currentWidget(), w);
QCOMPARE(tw->currentIndex(), index);
removePage(index2);
@@ -372,7 +372,7 @@ void tst_QTabWidget::currentIndex()
QCOMPARE(tw->currentIndex(), firstIndex);
QCOMPARE(spy.count(), 1);
QList<QVariant> arguments = spy.takeFirst();
- QVERIFY(arguments.at(0).toInt() == firstIndex);
+ QCOMPARE(arguments.at(0).toInt(), firstIndex);
int index = addPage();
QCOMPARE(tw->currentIndex(), firstIndex);
@@ -380,19 +380,19 @@ void tst_QTabWidget::currentIndex()
QCOMPARE(tw->currentIndex(), index);
QCOMPARE(spy.count(), 1);
arguments = spy.takeFirst();
- QVERIFY(arguments.at(0).toInt() == index);
+ QCOMPARE(arguments.at(0).toInt(), index);
removePage(index);
QCOMPARE(tw->currentIndex(), firstIndex);
QCOMPARE(spy.count(), 1);
arguments = spy.takeFirst();
- QVERIFY(arguments.at(0).toInt() == firstIndex);
+ QCOMPARE(arguments.at(0).toInt(), firstIndex);
removePage(firstIndex);
QCOMPARE(tw->currentIndex(), -1);
QCOMPARE(spy.count(), 1);
arguments = spy.takeFirst();
- QVERIFY(arguments.at(0).toInt() == -1);
+ QCOMPARE(arguments.at(0).toInt(), -1);
}
void tst_QTabWidget::cornerWidget()
@@ -400,24 +400,24 @@ void tst_QTabWidget::cornerWidget()
// Test bad arguments
tw->setCornerWidget(NULL, Qt::TopRightCorner);
- QVERIFY(tw->cornerWidget(Qt::TopLeftCorner) == 0);
- QVERIFY(tw->cornerWidget(Qt::TopRightCorner) == 0);
- QVERIFY(tw->cornerWidget(Qt::BottomLeftCorner) == 0);
- QVERIFY(tw->cornerWidget(Qt::BottomRightCorner) == 0);
+ QVERIFY(!tw->cornerWidget(Qt::TopLeftCorner));
+ QVERIFY(!tw->cornerWidget(Qt::TopRightCorner));
+ QVERIFY(!tw->cornerWidget(Qt::BottomLeftCorner));
+ QVERIFY(!tw->cornerWidget(Qt::BottomRightCorner));
QWidget *w = new QWidget(0);
tw->setCornerWidget(w, Qt::TopLeftCorner);
QCOMPARE(w->parent(), (QObject *)tw);
- QVERIFY(tw->cornerWidget(Qt::TopLeftCorner) == w);
+ QCOMPARE(tw->cornerWidget(Qt::TopLeftCorner), w);
tw->setCornerWidget(w, Qt::TopRightCorner);
- QVERIFY(tw->cornerWidget(Qt::TopRightCorner) == w);
+ QCOMPARE(tw->cornerWidget(Qt::TopRightCorner), w);
tw->setCornerWidget(w, Qt::BottomLeftCorner);
- QVERIFY(tw->cornerWidget(Qt::BottomLeftCorner) == w);
+ QCOMPARE(tw->cornerWidget(Qt::BottomLeftCorner), w);
tw->setCornerWidget(w, Qt::BottomRightCorner);
- QVERIFY(tw->cornerWidget(Qt::BottomRightCorner) == w);
+ QCOMPARE(tw->cornerWidget(Qt::BottomRightCorner), w);
tw->setCornerWidget(0, Qt::TopRightCorner);
- QVERIFY(tw->cornerWidget(Qt::TopRightCorner) == 0);
+ QVERIFY(!tw->cornerWidget(Qt::TopRightCorner));
QCOMPARE(w->isHidden(), true);
}
diff --git a/tests/auto/widgets/widgets/qtextbrowser/tst_qtextbrowser.cpp b/tests/auto/widgets/widgets/qtextbrowser/tst_qtextbrowser.cpp
index aaa7348bdf..adc768f828 100644
--- a/tests/auto/widgets/widgets/qtextbrowser/tst_qtextbrowser.cpp
+++ b/tests/auto/widgets/widgets/qtextbrowser/tst_qtextbrowser.cpp
@@ -141,14 +141,14 @@ void tst_QTextBrowser::noReloadOnAnchorJump()
browser->setSource(url);
QCOMPARE(browser->htmlLoadAttempts, 1);
QVERIFY(!browser->toPlainText().isEmpty());
- QVERIFY(browser->source() == url);
+ QCOMPARE(browser->source(), url);
}
void tst_QTextBrowser::bgColorOnSourceChange()
{
browser->setSource(QUrl::fromLocalFile("pagewithbg.html"));
QVERIFY(browser->document()->rootFrame()->frameFormat().hasProperty(QTextFormat::BackgroundBrush));
- QVERIFY(browser->document()->rootFrame()->frameFormat().background().color() == Qt::blue);
+ QCOMPARE(browser->document()->rootFrame()->frameFormat().background().color(), QColor(Qt::blue));
browser->setSource(QUrl::fromLocalFile("pagewithoutbg.html"));
QVERIFY(!browser->document()->rootFrame()->frameFormat().hasProperty(QTextFormat::BackgroundBrush));
@@ -167,13 +167,13 @@ void tst_QTextBrowser::forwardButton()
QVERIFY(!forwardEmissions.isEmpty());
QVariant val = forwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == false);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(!val.toBool());
QVERIFY(!backwardEmissions.isEmpty());
val = backwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == false);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(!val.toBool());
QVERIFY(browser->historyTitle(-1).isEmpty());
QCOMPARE(browser->historyUrl(0), QUrl::fromLocalFile("pagewithbg.html"));
@@ -185,13 +185,13 @@ void tst_QTextBrowser::forwardButton()
QVERIFY(!forwardEmissions.isEmpty());
val = forwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == false);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(!val.toBool());
QVERIFY(!backwardEmissions.isEmpty());
val = backwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == true);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(val.toBool());
QCOMPARE(browser->historyTitle(-1), QString("Page With BG"));
QCOMPARE(browser->historyTitle(0), QString("Sample Anchor"));
@@ -201,13 +201,13 @@ void tst_QTextBrowser::forwardButton()
QVERIFY(!forwardEmissions.isEmpty());
val = forwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == true);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(val.toBool());
QVERIFY(!backwardEmissions.isEmpty());
val = backwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == false);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(!val.toBool());
QVERIFY(browser->historyTitle(-1).isEmpty());
QCOMPARE(browser->historyTitle(0), QString("Page With BG"));
@@ -217,13 +217,13 @@ void tst_QTextBrowser::forwardButton()
QVERIFY(!forwardEmissions.isEmpty());
val = forwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == false);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(!val.toBool());
QVERIFY(!backwardEmissions.isEmpty());
val = backwardEmissions.takeLast()[0];
- QVERIFY(val.type() == QVariant::Bool);
- QVERIFY(val.toBool() == true);
+ QCOMPARE(val.type(), QVariant::Bool);
+ QVERIFY(val.toBool());
}
void tst_QTextBrowser::viewportPositionInHistory()
@@ -244,29 +244,29 @@ void tst_QTextBrowser::relativeLinks()
QSignalSpy sourceChangedSpy(browser, SIGNAL(sourceChanged(QUrl)));
browser->setSource(QUrl("subdir/../qtextbrowser.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("subdir/../qtextbrowser.html"));
browser->setSource(QUrl("subdir/index.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("subdir/index.html"));
browser->setSource(QUrl("anchor.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("anchor.html"));
browser->setSource(QUrl("subdir/index.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("subdir/index.html"));
// using QUrl::fromLocalFile()
browser->setSource(QUrl::fromLocalFile("anchor.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("file:anchor.html"));
browser->setSource(QUrl("subdir/../qtextbrowser.html"));
QVERIFY(!browser->document()->isEmpty());
- QVERIFY(sourceChangedSpy.count() == 1);
+ QCOMPARE(sourceChangedSpy.count(), 1);
QCOMPARE(sourceChangedSpy.takeFirst()[0].toUrl(), QUrl("subdir/../qtextbrowser.html"));
}
@@ -446,13 +446,13 @@ void tst_QTextBrowser::sourceInsideLoadResource()
void tst_QTextBrowser::textInteractionFlags_vs_readOnly()
{
QVERIFY(browser->isReadOnly());
- QVERIFY(browser->textInteractionFlags() == Qt::TextBrowserInteraction);
+ QCOMPARE(browser->textInteractionFlags(), Qt::TextBrowserInteraction);
browser->setReadOnly(true);
- QVERIFY(browser->textInteractionFlags() == Qt::TextBrowserInteraction);
+ QCOMPARE(browser->textInteractionFlags(), Qt::TextBrowserInteraction);
browser->setReadOnly(false);
- QVERIFY(browser->textInteractionFlags() == Qt::TextEditorInteraction);
+ QCOMPARE(browser->textInteractionFlags(), Qt::TextEditorInteraction);
browser->setReadOnly(true);
- QVERIFY(browser->textInteractionFlags() == Qt::TextBrowserInteraction);
+ QCOMPARE(browser->textInteractionFlags(), Qt::TextBrowserInteraction);
}
void tst_QTextBrowser::anchorsWithSelfBuiltHtml()
@@ -525,7 +525,7 @@ void tst_QTextBrowser::loadResourceOnRelativeLocalFiles()
QVERIFY(!browser->toPlainText().isEmpty());
QVariant v = browser->loadResource(QTextDocument::HtmlResource, QUrl("../anchor.html"));
QVERIFY(v.isValid());
- QVERIFY(v.type() == QVariant::ByteArray);
+ QCOMPARE(v.type(), QVariant::ByteArray);
QVERIFY(!v.toByteArray().isEmpty());
}
@@ -658,7 +658,7 @@ void tst_QTextBrowser::urlEncoding()
QCOMPARE(spy.count(), 1);
QUrl url = spy.at(0).at(0).toUrl();
- QVERIFY(url.toEncoded() == QByteArray("http://www.google.com/q=%22"));
+ QCOMPARE(url.toEncoded(), QByteArray("http://www.google.com/q=%22"));
delete browser;
}
diff --git a/tests/auto/widgets/widgets/qtextedit/tst_qtextedit.cpp b/tests/auto/widgets/widgets/qtextedit/tst_qtextedit.cpp
index 35a6a8e4e0..0cc812cbca 100644
--- a/tests/auto/widgets/widgets/qtextedit/tst_qtextedit.cpp
+++ b/tests/auto/widgets/widgets/qtextedit/tst_qtextedit.cpp
@@ -398,12 +398,13 @@ void tst_QTextEdit::cleanup()
void tst_QTextEdit::inlineAttributesOnInsert()
{
- QVERIFY(ed->textCursor().charFormat().foreground().color() != Qt::blue);
+ const QColor blue(Qt::blue);
+ QVERIFY(ed->textCursor().charFormat().foreground().color() != blue);
- ed->setTextColor(Qt::blue);
+ ed->setTextColor(blue);
QTest::keyClick(ed, Qt::Key_A);
- QVERIFY(ed->textCursor().charFormat().foreground().color() == Qt::blue);
+ QCOMPARE(ed->textCursor().charFormat().foreground().color(), blue);
}
void tst_QTextEdit::inlineAttributesOnSelection()
@@ -457,7 +458,7 @@ void tst_QTextEdit::autoBulletList1()
QTest::keyClicks(ed, "*This should become a list");
QVERIFY(ed->textCursor().currentList());
- QVERIFY(ed->textCursor().currentList()->format().style() == QTextListFormat::ListDisc);
+ QCOMPARE(ed->textCursor().currentList()->format().style(), QTextListFormat::ListDisc);
}
void tst_QTextEdit::autoBulletList2()
@@ -582,7 +583,7 @@ void tst_QTextEdit::selectAllSetsNotSelection()
}
QApplication::clipboard()->setText(QString("foobar"), QClipboard::Selection);
- QVERIFY(QApplication::clipboard()->text(QClipboard::Selection) == QString("foobar"));
+ QCOMPARE(QApplication::clipboard()->text(QClipboard::Selection), QString("foobar"));
ed->insertPlainText("Hello World");
ed->selectAll();
@@ -867,11 +868,12 @@ void tst_QTextEdit::appendShouldUseCurrentFormat()
fmt.setFontItalic(true);
ed->setCurrentCharFormat(fmt);
ed->append("Hello");
+ const QColor blue(Qt::blue);
QTextCursor cursor(ed->document());
QVERIFY(cursor.movePosition(QTextCursor::NextCharacter));
- QVERIFY(cursor.charFormat().foreground().color() != Qt::blue);
+ QVERIFY(cursor.charFormat().foreground().color() != blue);
QVERIFY(!cursor.charFormat().fontItalic());
QVERIFY(cursor.movePosition(QTextCursor::NextBlock));
@@ -883,7 +885,7 @@ void tst_QTextEdit::appendShouldUseCurrentFormat()
}
QVERIFY(cursor.movePosition(QTextCursor::NextCharacter));
- QVERIFY(cursor.charFormat().foreground().color() == Qt::blue);
+ QCOMPARE(cursor.charFormat().foreground().color(), blue);
QVERIFY(cursor.charFormat().fontItalic());
}
@@ -1211,7 +1213,7 @@ void tst_QTextEdit::lineWrapModes()
{
ed->setLineWrapMode(QTextEdit::NoWrap);
// NoWrap at the same time as having all lines that are all left aligned means we optimize to only layout once. The effect is that the width is always 0
- QVERIFY(ed->document()->pageSize().width() == qreal(0));
+ QCOMPARE(ed->document()->pageSize().width(), qreal(0));
QTextCursor cursor = QTextCursor(ed->document());
cursor.insertText(QString("A simple line"));
@@ -1237,13 +1239,13 @@ void tst_QTextEdit::mouseCursorShape()
{
// always show an IBeamCursor, see change 170146
QVERIFY(!ed->isReadOnly());
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
ed->setReadOnly(true);
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
ed->setPlainText("Foo");
- QVERIFY(ed->viewport()->cursor().shape() == Qt::IBeamCursor);
+ QCOMPARE(ed->viewport()->cursor().shape(), Qt::IBeamCursor);
}
#endif
@@ -1661,7 +1663,7 @@ void tst_QTextEdit::preserveCharFormatAfterSetPlainText()
QTextBlock block = ed->document()->begin();
block = block.next();
QCOMPARE(block.text(), QString("This should still be blue"));
- QVERIFY(block.begin().fragment().charFormat().foreground().color() == QColor(Qt::blue));
+ QCOMPARE(block.begin().fragment().charFormat().foreground().color(), QColor(Qt::blue));
}
void tst_QTextEdit::extraSelections()
@@ -1796,25 +1798,25 @@ void tst_QTextEdit::wordWrapProperty()
QTextDocument *doc = new QTextDocument(&edit);
edit.setDocument(doc);
edit.setWordWrapMode(QTextOption::NoWrap);
- QVERIFY(doc->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(doc->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
{
QTextEdit edit;
QTextDocument *doc = new QTextDocument(&edit);
edit.setWordWrapMode(QTextOption::NoWrap);
edit.setDocument(doc);
- QVERIFY(doc->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(doc->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
}
void tst_QTextEdit::lineWrapProperty()
{
- QVERIFY(ed->wordWrapMode() == QTextOption::WrapAtWordBoundaryOrAnywhere);
- QVERIFY(ed->lineWrapMode() == QTextEdit::WidgetWidth);
+ QCOMPARE(ed->wordWrapMode(), QTextOption::WrapAtWordBoundaryOrAnywhere);
+ QCOMPARE(ed->lineWrapMode(), QTextEdit::WidgetWidth);
ed->setLineWrapMode(QTextEdit::NoWrap);
- QVERIFY(ed->lineWrapMode() == QTextEdit::NoWrap);
- QVERIFY(ed->wordWrapMode() == QTextOption::WrapAtWordBoundaryOrAnywhere);
- QVERIFY(ed->document()->defaultTextOption().wrapMode() == QTextOption::NoWrap);
+ QCOMPARE(ed->lineWrapMode(), QTextEdit::NoWrap);
+ QCOMPARE(ed->wordWrapMode(), QTextOption::WrapAtWordBoundaryOrAnywhere);
+ QCOMPARE(ed->document()->defaultTextOption().wrapMode(), QTextOption::NoWrap);
}
void tst_QTextEdit::selectionChanged()
@@ -2122,7 +2124,7 @@ void tst_QTextEdit::setDocumentPreservesPalette()
QTextDocument *newDoc = new QTextDocument(ed);
ed->setDocument(newDoc);
- QVERIFY(control->document() == newDoc);
+ QCOMPARE(control->document(), newDoc);
QVERIFY(whitePal.color(QPalette::Active, QPalette::Text)
== control->palette().color(QPalette::Active, QPalette::Text));
}
@@ -2525,7 +2527,7 @@ void tst_QTextEdit::findWithRegExp()
bool found = ed->find(rx);
- QVERIFY(found == true);
+ QVERIFY(found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("text"));
}
@@ -2539,7 +2541,7 @@ void tst_QTextEdit::findBackwardWithRegExp()
bool found = ed->find(rx, QTextDocument::FindBackward);
- QVERIFY(found == true);
+ QVERIFY(found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("arbit"));
}
@@ -2551,7 +2553,7 @@ void tst_QTextEdit::findWithRegExpReturnsFalseIfNoMoreResults()
bool found = ed->find(rx);
- QVERIFY(found == false);
+ QVERIFY(!found);
QCOMPARE(ed->textCursor().selectedText(), QStringLiteral("text"));
}
#endif
diff --git a/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp b/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
index 24de35ce89..e653a85d96 100644
--- a/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
+++ b/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
@@ -67,6 +67,7 @@ private slots:
void allowedAreas();
void orientation();
void addAction();
+ void addActionConnect();
void insertAction();
void addSeparator();
void insertSeparator();
@@ -361,6 +362,23 @@ void tst_QToolBar::addAction()
}
}
+static void testFunction() { }
+
+void tst_QToolBar::addActionConnect()
+{
+ QToolBar tb;
+ const QString text = QLatin1String("bla");
+ const QIcon icon;
+ tb.addAction(text, &tb, SLOT(deleteLater()));
+ tb.addAction(text, &tb, &QMenu::deleteLater);
+ tb.addAction(text, testFunction);
+ tb.addAction(text, &tb, testFunction);
+ tb.addAction(icon, text, &tb, SLOT(deleteLater()));
+ tb.addAction(icon, text, &tb, &QMenu::deleteLater);
+ tb.addAction(icon, text, testFunction);
+ tb.addAction(icon, text, &tb, testFunction);
+}
+
void tst_QToolBar::insertAction()
{
QToolBar tb;
@@ -495,13 +513,13 @@ void tst_QToolBar::insertWidget()
QToolBar tb;
QPointer<QWidget> widget = new QWidget;
QAction *action = tb.addWidget(widget);
- QVERIFY(action->parent() == &tb);
+ QCOMPARE(action->parent(), &tb);
QToolBar tb2;
tb.removeAction(action);
tb2.addAction(action);
QVERIFY(widget && widget->parent() == &tb2);
- QVERIFY(action->parent() == &tb2);
+ QCOMPARE(action->parent(), &tb2);
}
}
@@ -960,10 +978,10 @@ void tst_QToolBar::actionOwnership()
QToolBar *tb2 = new QToolBar;
QPointer<QAction> action = tb1->addAction("test");
- QVERIFY(action->parent() == tb1);
+ QCOMPARE(action->parent(), tb1);
tb2->addAction(action);
- QVERIFY(action->parent() == tb1);
+ QCOMPARE(action->parent(), tb1);
delete tb1;
QVERIFY(!action);
@@ -974,13 +992,13 @@ void tst_QToolBar::actionOwnership()
QToolBar *tb2 = new QToolBar;
QPointer<QAction> action = tb1->addAction("test");
- QVERIFY(action->parent() == tb1);
+ QCOMPARE(action->parent(), tb1);
tb1->removeAction(action);
- QVERIFY(action->parent() == tb1);
+ QCOMPARE(action->parent(), tb1);
tb2->addAction(action);
- QVERIFY(action->parent() == tb1);
+ QCOMPARE(action->parent(), tb1);
delete tb1;
QVERIFY(!action);
diff --git a/tests/auto/widgets/widgets/qtoolbutton/tst_qtoolbutton.cpp b/tests/auto/widgets/widgets/qtoolbutton/tst_qtoolbutton.cpp
index 03fbae2e57..0d1abe5032 100644
--- a/tests/auto/widgets/widgets/qtoolbutton/tst_qtoolbutton.cpp
+++ b/tests/auto/widgets/widgets/qtoolbutton/tst_qtoolbutton.cpp
@@ -170,10 +170,10 @@ void tst_QToolButton::collapseTextOnPriority()
QStyleOptionToolButton option;
button.initStyleOption(&option);
- QVERIFY(option.toolButtonStyle == Qt::ToolButtonTextBesideIcon);
+ QCOMPARE(option.toolButtonStyle, Qt::ToolButtonTextBesideIcon);
action.setPriority(QAction::LowPriority);
button.initStyleOption(&option);
- QVERIFY(option.toolButtonStyle == Qt::ToolButtonIconOnly);
+ QCOMPARE(option.toolButtonStyle, Qt::ToolButtonIconOnly);
}
diff --git a/tests/auto/xml/dom/qdom/tst_qdom.cpp b/tests/auto/xml/dom/qdom/tst_qdom.cpp
index 2ce32c7cf2..a4a3f1f6b3 100644
--- a/tests/auto/xml/dom/qdom/tst_qdom.cpp
+++ b/tests/auto/xml/dom/qdom/tst_qdom.cpp
@@ -1043,15 +1043,15 @@ void tst_QDom::browseElements()
QVERIFY(!bar.isNull());
QVERIFY(bar.previousSiblingElement("bar").isNull());
QVERIFY(bar.previousSiblingElement().isNull());
- QVERIFY(bar.nextSiblingElement("bar").tagName() == "bar");
+ QCOMPARE(bar.nextSiblingElement("bar").tagName(), QLatin1String("bar"));
QVERIFY(bar.nextSiblingElement("bar").nextSiblingElement("bar").isNull());
QDomElement bop = foo.firstChildElement("bop");
QVERIFY(!bop.isNull());
- QVERIFY(bar.nextSiblingElement() == bop);
- QVERIFY(bop.nextSiblingElement("bop") == foo.lastChildElement("bop"));
- QVERIFY(bop.previousSiblingElement("bar") == foo.firstChildElement("bar"));
- QVERIFY(bop.previousSiblingElement("bar") == foo.firstChildElement());
+ QCOMPARE(bar.nextSiblingElement(), bop);
+ QCOMPARE(bop.nextSiblingElement("bop"), foo.lastChildElement("bop"));
+ QCOMPARE(bop.previousSiblingElement("bar"), foo.firstChildElement("bar"));
+ QCOMPARE(bop.previousSiblingElement("bar"), foo.firstChildElement());
}
void tst_QDom::domNodeMapAndList()
diff --git a/tests/auto/xml/sax/qxmlinputsource/tst_qxmlinputsource.cpp b/tests/auto/xml/sax/qxmlinputsource/tst_qxmlinputsource.cpp
index 04f19f6a2b..a5ac58878e 100644
--- a/tests/auto/xml/sax/qxmlinputsource/tst_qxmlinputsource.cpp
+++ b/tests/auto/xml/sax/qxmlinputsource/tst_qxmlinputsource.cpp
@@ -147,7 +147,7 @@ public slots:
void requestFinished(QNetworkReply *reply)
{
- QVERIFY(reply->error() == QNetworkReply::NoError);
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
reply->deleteLater();
}
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/001.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/001.ent
index 1cff3fd44f..1cff3fd44f 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/001.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/001.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/002.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/002.ent
index 45f6d8e74e..45f6d8e74e 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/002.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/002.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/004.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/004.ent
index 3436f20001..3436f20001 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/004.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/004.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/005.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/005.ent
index c6e97f821f..c6e97f821f 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/005.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/005.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/006.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/006.ent
index 4df2f0c2ac..4df2f0c2ac 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/006.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/006.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/007.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/007.ent
index ab1d696dd7..ab1d696dd7 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/007.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/007.ent
Binary files differ
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/008.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/008.ent
index c6ca61f9c8..c6ca61f9c8 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/008.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/008.ent
Binary files differ
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/009.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/009.ent
index 67c3297611..67c3297611 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/009.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/009.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/011.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/011.ent
index b19be3a497..b19be3a497 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/011.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/011.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/012.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/012.ent
index 8eb1fb9c41..8eb1fb9c41 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/012.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/012.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/013.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/013.ent
index 7f25c502dd..7f25c502dd 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/013.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/013.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/014.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/014.ent
index 470fd6fe44..470fd6fe44 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/014.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/ext-sa/014.ent
Binary files differ
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/002.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/002.ent
index 67c3297611..67c3297611 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/002.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/002.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/003-1.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/003-1.ent
index 931f3ad6d8..931f3ad6d8 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/003-1.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/003-1.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-1.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-1.ent
index 40f7ff58a2..40f7ff58a2 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-1.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-1.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-2.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-2.ent
index 61def75cb7..61def75cb7 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-2.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/004-2.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-1.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-1.ent
index ade9599032..ade9599032 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-1.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-1.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-2.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-2.ent
index bef50b1f38..bef50b1f38 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-2.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/005-2.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/006.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/006.ent
index 8f305a82bd..8f305a82bd 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/006.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/006.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/007.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/007.ent
index fbf4ca4947..fbf4ca4947 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/007.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/007.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/008.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/008.ent
index fbf4ca4947..fbf4ca4947 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/008.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/008.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/009.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/009.ent
index fbf4ca4947..fbf4ca4947 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/009.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/009.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/010.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/010.ent
index 52a28f5deb..52a28f5deb 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/010.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/010.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/011.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/011.ent
index fbf4ca4947..fbf4ca4947 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/011.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/011.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/012.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/012.ent
index 7e372e65e9..7e372e65e9 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/012.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/012.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/013.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/013.ent
index a3691d9f08..a3691d9f08 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/013.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/013.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/014.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/014.ent
index 6eaf779329..6eaf779329 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/014.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/014.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/015.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/015.ent
index 00d2f30e1d..00d2f30e1d 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/015.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/015.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/016.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/016.ent
index bf77ef8336..bf77ef8336 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/016.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/016.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/017.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/017.ent
index ffd9adde61..ffd9adde61 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/017.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/017.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/018.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/018.ent
index 2d46f76fc3..2d46f76fc3 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/018.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/018.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/019.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/019.ent
index d18201a98b..d18201a98b 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/019.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/019.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/020.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/020.ent
index 815291c6d2..815291c6d2 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/020.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/020.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/021.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/021.ent
index 9f8f2afd2b..9f8f2afd2b 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/021.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/021.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/022.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/022.ent
index 26f2d8beb2..26f2d8beb2 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/022.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/022.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/023.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/023.ent
index e3268819f7..e3268819f7 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/023.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/023.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/024.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/024.ent
index aa6d0eccac..aa6d0eccac 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/024.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/024.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/025.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/025.ent
index 389d259eb1..389d259eb1 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/025.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/025.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/026.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/026.ent
index bdc93af639..bdc93af639 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/026.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/026.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/027.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/027.ent
index 712cce3700..712cce3700 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/027.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/027.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/028.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/028.ent
index ac249d7b2c..ac249d7b2c 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/028.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/028.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/029.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/029.ent
index df94df5560..df94df5560 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/029.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/029.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/030.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/030.ent
index e3864460df..e3864460df 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/030.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/030.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-1.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-1.ent
index f7f94ab152..f7f94ab152 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-1.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-1.ent
diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-2.ent b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-2.ent
index bef50b1f38..bef50b1f38 100755..100644
--- a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-2.ent
+++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/valid/not-sa/031-2.ent
diff --git a/tests/benchmarks/corelib/io/qdiriterator/main.cpp b/tests/benchmarks/corelib/io/qdiriterator/main.cpp
index 272bafc7dd..42d36a22f8 100644
--- a/tests/benchmarks/corelib/io/qdiriterator/main.cpp
+++ b/tests/benchmarks/corelib/io/qdiriterator/main.cpp
@@ -223,12 +223,12 @@ void tst_qdiriterator::fsiterator()
int c = 0;
dump && printf("\n\n\n\n");
- QFileSystemIterator dir(dirpath,
+ QDirIteratorTest::QFileSystemIterator dir(dirpath,
//QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot,
//QDir::AllEntries | QDir::Hidden,
//QDir::Files | QDir::NoDotAndDotDot,
QDir::Files,
- QFileSystemIterator::Subdirectories);
+ QDirIteratorTest::QFileSystemIterator::Subdirectories);
for (; !dir.atEnd(); dir.next()) {
dump && printf("%d %s\n",
diff --git a/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.cpp b/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.cpp
index 1b28f462aa..a4db21742d 100644
--- a/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.cpp
+++ b/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.cpp
@@ -99,6 +99,8 @@
QT_BEGIN_NAMESPACE
+namespace QDirIteratorTest {
+
class QFileSystemIteratorPrivate
{
public:
@@ -671,4 +673,6 @@ QString QFileSystemIterator::path() const
return QString::fromLocal8Bit(d->m_dirPaths.top());
}
+} // QDirIteratorTest::
+
QT_END_NAMESPACE
diff --git a/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.h b/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.h
index b940c0061b..96fa5177a0 100644
--- a/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.h
+++ b/tests/benchmarks/corelib/io/qdiriterator/qfilesystemiterator.h
@@ -38,6 +38,7 @@
QT_BEGIN_NAMESPACE
+namespace QDirIteratorTest {
class QFileSystemIteratorPrivate;
class //Q_CORE_EXPORT
@@ -81,6 +82,8 @@ private:
Q_DECLARE_OPERATORS_FOR_FLAGS(QFileSystemIterator::IteratorFlags)
+} // namespace QDirIteratorTest
+
QT_END_NAMESPACE
#endif
diff --git a/tests/benchmarks/corelib/tools/qringbuffer/main.cpp b/tests/benchmarks/corelib/tools/qringbuffer/main.cpp
index 6bb82a8056..cf55aeaee5 100644
--- a/tests/benchmarks/corelib/tools/qringbuffer/main.cpp
+++ b/tests/benchmarks/corelib/tools/qringbuffer/main.cpp
@@ -48,10 +48,10 @@ void tst_qringbuffer::reserveAndRead()
{
QRingBuffer ringBuffer;
QBENCHMARK {
- for (int i = 1; i < 256; ++i)
+ for (qint64 i = 1; i < 256; ++i)
ringBuffer.reserve(i);
- for (int i = 1; i < 256; ++i)
+ for (qint64 i = 1; i < 256; ++i)
ringBuffer.read(0, i);
}
}
diff --git a/tests/benchmarks/gui/text/qtext/main.cpp b/tests/benchmarks/gui/text/qtext/main.cpp
index 224d9619ec..f20b3f6cce 100644
--- a/tests/benchmarks/gui/text/qtext/main.cpp
+++ b/tests/benchmarks/gui/text/qtext/main.cpp
@@ -42,7 +42,7 @@
#include <QBuffer>
#include <qtest.h>
-Q_DECLARE_METATYPE(QList<QTextLayout::FormatRange>)
+Q_DECLARE_METATYPE(QVector<QTextLayout::FormatRange>)
class tst_QText: public QObject
{
@@ -324,13 +324,13 @@ void tst_QText::layout()
void tst_QText::formattedLayout_data()
{
QTest::addColumn<QString>("text");
- QTest::addColumn<QList<QTextLayout::FormatRange> >("ranges");
+ QTest::addColumn<QVector<QTextLayout::FormatRange> >("ranges");
QTextCharFormat format;
format.setForeground(QColor("steelblue"));
{
- QList<QTextLayout::FormatRange> ranges;
+ QVector<QTextLayout::FormatRange> ranges;
QTextLayout::FormatRange formatRange;
formatRange.format = format;
@@ -341,7 +341,7 @@ void tst_QText::formattedLayout_data()
QTest::newRow("short-single") << m_shortLorem << ranges;
}
{
- QList<QTextLayout::FormatRange> ranges;
+ QVector<QTextLayout::FormatRange> ranges;
QString text = m_lorem.repeated(100);
const int width = 1;
@@ -360,15 +360,15 @@ void tst_QText::formattedLayout_data()
void tst_QText::formattedLayout()
{
QFETCH(QString, text);
- QFETCH(QList<QTextLayout::FormatRange>, ranges);
+ QFETCH(QVector<QTextLayout::FormatRange>, ranges);
QTextLayout layout(text);
- layout.setAdditionalFormats(ranges);
+ layout.setFormats(ranges);
setupTextLayout(&layout);
QBENCHMARK {
QTextLayout layout(text);
- layout.setAdditionalFormats(ranges);
+ layout.setFormats(ranges);
setupTextLayout(&layout);
}
}
diff --git a/tests/benchmarks/sql/kernel/qsqlquery/main.cpp b/tests/benchmarks/sql/kernel/qsqlquery/main.cpp
index 63aa6f7250..b5937b76b0 100644
--- a/tests/benchmarks/sql/kernel/qsqlquery/main.cpp
+++ b/tests/benchmarks/sql/kernel/qsqlquery/main.cpp
@@ -55,6 +55,8 @@ public slots:
private slots:
void benchmark_data() { generic_data(); }
void benchmark();
+ void benchmarkSelectPrepared_data() { generic_data(); }
+ void benchmarkSelectPrepared();
private:
// returns all database connections
@@ -264,4 +266,42 @@ void tst_QSqlQuery::benchmark()
tst_Databases::safeDropTable( db, tableName );
}
+void tst_QSqlQuery::benchmarkSelectPrepared()
+{
+ QFETCH( QString, dbName );
+ QSqlDatabase db = QSqlDatabase::database(dbName);
+ CHECK_DATABASE(db);
+ if (tst_Databases::getMySqlVersion(db).section(QChar('.'), 0, 0).toInt() < 5)
+ QSKIP("Test requires MySQL >= 5.0");
+
+ QSqlQuery q(db);
+ const QString tableName(qTableName("benchmark", __FILE__, db));
+
+ tst_Databases::safeDropTable(db, tableName);
+
+ QVERIFY_SQL(q, exec("CREATE TABLE " + tableName + "(id INT NOT NULL)"));
+
+ const int NUM_ROWS = 1000;
+ int expectedSum = 0;
+ QString fillQuery = "INSERT INTO " + tableName + " VALUES (0)";
+ for (int i = 1; i < NUM_ROWS; ++i) {
+ fillQuery += ", (" + QString::number(i) + ")";
+ expectedSum += i;
+ }
+ QVERIFY_SQL(q, exec(fillQuery));
+
+ QVERIFY_SQL(q, prepare("SELECT id FROM "+tableName));
+ QBENCHMARK {
+ QVERIFY_SQL(q, exec());
+ int sum = 0;
+
+ while (q.next())
+ sum += q.value(0).toInt();
+
+ QCOMPARE(sum, expectedSum);
+ }
+
+ tst_Databases::safeDropTable(db, tableName);
+}
+
#include "main.moc"
diff --git a/tests/manual/cocoa/qt_on_cocoa/main.mm b/tests/manual/cocoa/qt_on_cocoa/main.mm
index 5dd546479e..23370b0305 100644
--- a/tests/manual/cocoa/qt_on_cocoa/main.mm
+++ b/tests/manual/cocoa/qt_on_cocoa/main.mm
@@ -31,123 +31,35 @@
**
****************************************************************************/
-#include <QtGui>
-#include <QtDeclarative>
+#include "rasterwindow.h"
+#include <QtGui>
#include <QtWidgets/QtWidgets>
-#include <private/qwidgetwindow_p.h>
-#include <QtGui/qpa/qplatformnativeinterface.h>
-
-#include <QtGui/QPixmap>
-
-#include "window.h"
#include <Cocoa/Cocoa.h>
-
-@interface FilledView : NSView
-{
-
+@interface AppDelegate : NSObject <NSApplicationDelegate> {
+ QGuiApplication *m_app;
+ QWindow *m_window;
}
+- (AppDelegate *) initWithArgc:(int)argc argv:(const char **)argv;
+- (void) applicationWillFinishLaunching: (NSNotification *)notification;
+- (void)applicationWillTerminate:(NSNotification *)notification;
@end
-@implementation FilledView
-
-- (void)drawRect:(NSRect)dirtyRect {
- // set any NSColor for filling, say white:
- [[NSColor redColor] setFill];
- NSRectFill(dirtyRect);
-}
-
-@end
-
-@interface QtMacToolbarDelegate : NSObject <NSToolbarDelegate>
+@implementation AppDelegate
+- (AppDelegate *) initWithArgc:(int)argc argv:(const char **)argv
{
-@public
- NSToolbar *toolbar;
-}
-
-- (id)init;
-- (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier: (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted;
-- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)tb;
-- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar;
-- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar;
-@end
-
-@implementation QtMacToolbarDelegate
-
-- (id)init
-{
- self = [super init];
- if (self) {
- }
+ m_app = new QGuiApplication(argc, const_cast<char **>(argv));
return self;
}
-- (void)dealloc
-{
- [super dealloc];
-}
-
-- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)tb
-{
- Q_UNUSED(tb);
- NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
-// [array addObject : NSToolbarPrintItemIdentifier];
-// [array addObject : NSToolbarShowColorsItemIdentifier];
- [array addObject : @"filledView"];
- return array;
-}
-
-- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)tb
-{
- Q_UNUSED(tb);
- NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
-// [array addObject : NSToolbarPrintItemIdentifier];
-// [array addObject : NSToolbarShowColorsItemIdentifier];
- [array addObject : @"filledView"];
- return array;
-}
-
-- (NSArray *)toolbarSelectableItemIdentifiers: (NSToolbar *)tb
-{
- Q_UNUSED(tb);
- NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
- return array;
-}
-
-- (IBAction)itemClicked:(id)sender
+- (void) applicationWillFinishLaunching: (NSNotification *)notification
{
+ Q_UNUSED(notification);
-}
-
-- (NSToolbarItem *) toolbar: (NSToolbar *)tb itemForItemIdentifier: (NSString *) itemIdentifier willBeInsertedIntoToolbar:(BOOL) willBeInserted
-{
- Q_UNUSED(tb);
- Q_UNUSED(willBeInserted);
- //const QString identifier = toQString(itemIdentifier);
- //NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
- //return toolbarItem;
-
- //NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
- NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
- FilledView *theView = [[FilledView alloc] init];
- [toolbarItem setView : theView];
- [toolbarItem setMinSize : NSMakeSize(400, 40)];
- [toolbarItem setMaxSize : NSMakeSize(4000, 40)];
- return toolbarItem;
-}
-@end
-
-@interface WindowAndViewAndQtCreator : NSObject {}
-- (void)createWindowAndViewAndQt;
-@end
-
-@implementation WindowAndViewAndQtCreator
-- (void)createWindowAndViewAndQt {
-
- // Create the window
+ // Create the NSWindow
NSRect frame = NSMakeRect(500, 500, 500, 500);
NSWindow* window = [[NSWindow alloc] initWithContentRect:frame
styleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask
@@ -156,49 +68,31 @@
NSString *title = @"This the NSWindow window";
[window setTitle:title];
-
[window setBackgroundColor:[NSColor blueColor]];
- // Create a tool bar, set Qt delegate
- NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier : @"foobartoolbar"];
- QtMacToolbarDelegate *delegate = [[QtMacToolbarDelegate alloc] init];
- [toolbar setDelegate : delegate];
- [window setToolbar : toolbar];
-
- // Create the QWindow, don't show it.
- Window *qtWindow = new Window();
- qtWindow->create();
-
- //QSGView *qtWindow = new QSGView();
- //qtWindow->setSource(QUrl::fromLocalFile("/Users/msorvig/code/qt5/qtdeclarative/examples/declarative/samegame/samegame.qml"));
- // qtWindow->setWindowFlags(Qt::WindowType(13)); // 13: NativeEmbeddedWindow
-
- // Get the nsview from the QWindow, set it as the content view
- // on the NSWindow created above.
- QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface();
- NSView *qtView = (NSView *)platformNativeInterface->nativeResourceForWindow("nsview", qtWindow);
- [window setContentView:qtView];
+ // Create the QWindow, use its NSView as the content view
+ m_window = new RasterWindow();
+ [window setContentView:reinterpret_cast<NSView *>(m_window->winId())];
+
+ // Show the NSWindow
[window makeKeyAndOrderFront:NSApp];
}
-@end
-int main(int argc, char *argv[])
+- (void)applicationWillTerminate:(NSNotification *)notification
{
- QGuiApplication app(argc, argv);
-
- // fake NSApplicationMain() implementation follows:
- NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
- [NSApplication sharedApplication];
+ Q_UNUSED(notification);
+ delete m_window;
+ delete m_app;
+}
- // schedule call to create the UI.
- WindowAndViewAndQtCreator *windowAndViewAndQtCreator= [WindowAndViewAndQtCreator alloc];
- [NSTimer scheduledTimerWithTimeInterval:0 target:windowAndViewAndQtCreator selector:@selector(createWindowAndViewAndQt) userInfo:nil repeats:NO];
+@end
- [(NSApplication *)NSApp run];
- [NSApp release];
- [pool release];
- exit(0);
- return 0;
+int main(int argc, const char *argv[])
+{
+ // Create NSApplicaiton with delgate
+ NSApplication *app =[NSApplication sharedApplication];
+ app.delegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
+ return NSApplicationMain (argc, argv);
}
diff --git a/tests/manual/cocoa/qt_on_cocoa/qt_on_cocoa.pro b/tests/manual/cocoa/qt_on_cocoa/qt_on_cocoa.pro
index 3d526909a5..97e4473e15 100644
--- a/tests/manual/cocoa/qt_on_cocoa/qt_on_cocoa.pro
+++ b/tests/manual/cocoa/qt_on_cocoa/qt_on_cocoa.pro
@@ -1,13 +1,11 @@
TEMPLATE = app
OBJECTIVE_SOURCES += main.mm
-HEADERS += window.h
-SOURCES += window.cpp
+HEADERS += rasterwindow.h
+SOURCES += rasterwindow.cpp
LIBS += -framework Cocoa
-QMAKE_INFO_PLIST = Info_mac.plist
-OTHER_FILES = Info_mac.plist
-QT += gui widgets widgets-private gui-private core-private
+QT += gui widgets quick
-QT += declarative
+QT += quick
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
diff --git a/tests/manual/cocoa/qt_on_cocoa/window.cpp b/tests/manual/cocoa/qt_on_cocoa/rasterwindow.cpp
index 9929a50065..9b8f5e63ce 100644
--- a/tests/manual/cocoa/qt_on_cocoa/window.cpp
+++ b/tests/manual/cocoa/qt_on_cocoa/rasterwindow.cpp
@@ -31,9 +31,9 @@
**
****************************************************************************/
-#include "window.h"
+#include "rasterwindow.h"
-#include <private/qguiapplication_p.h>
+//#include <private/qguiapplication_p.h>
#include <QBackingStore>
#include <QPainter>
@@ -48,21 +48,14 @@ QColor colorTable[] =
QColor("#c0ef8f")
};
-Window::Window(QScreen *screen)
- : QWindow(screen)
+RasterWindow::RasterWindow(QRasterWindow *parent)
+ : QRasterWindow(parent)
, m_backgroundColorIndex(colorIndexId++)
{
initialize();
}
-Window::Window(QWindow *parent)
- : QWindow(parent)
- , m_backgroundColorIndex(colorIndexId++)
-{
- initialize();
-}
-
-void Window::initialize()
+void RasterWindow::initialize()
{
if (parent())
setGeometry(QRect(160, 120, 320, 240));
@@ -85,12 +78,12 @@ void Window::initialize()
m_renderTimer = 0;
}
-void Window::mousePressEvent(QMouseEvent *event)
+void RasterWindow::mousePressEvent(QMouseEvent *event)
{
m_lastPos = event->pos();
}
-void Window::mouseMoveEvent(QMouseEvent *event)
+void RasterWindow::mouseMoveEvent(QMouseEvent *event)
{
if (m_lastPos != QPoint(-1, -1)) {
QPainter p(&m_image);
@@ -102,7 +95,7 @@ void Window::mouseMoveEvent(QMouseEvent *event)
scheduleRender();
}
-void Window::mouseReleaseEvent(QMouseEvent *event)
+void RasterWindow::mouseReleaseEvent(QMouseEvent *event)
{
if (m_lastPos != QPoint(-1, -1)) {
QPainter p(&m_image);
@@ -114,16 +107,16 @@ void Window::mouseReleaseEvent(QMouseEvent *event)
scheduleRender();
}
-void Window::exposeEvent(QExposeEvent *)
+void RasterWindow::exposeEvent(QExposeEvent *)
{
scheduleRender();
}
-void Window::resizeEvent(QResizeEvent *)
+void RasterWindow::resizeEvent(QResizeEvent *)
{
QImage old = m_image;
- //qDebug() << "Window::resizeEvent" << width << height;
+ //qDebug() << "RasterWindow::resizeEvent" << width << height;
int width = qMax(geometry().width(), old.width());
int height = qMax(geometry().height(), old.height());
@@ -139,7 +132,7 @@ void Window::resizeEvent(QResizeEvent *)
render();
}
-void Window::keyPressEvent(QKeyEvent *event)
+void RasterWindow::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Backspace:
@@ -156,20 +149,20 @@ void Window::keyPressEvent(QKeyEvent *event)
scheduleRender();
}
-void Window::scheduleRender()
+void RasterWindow::scheduleRender()
{
if (!m_renderTimer)
m_renderTimer = startTimer(1);
}
-void Window::timerEvent(QTimerEvent *)
+void RasterWindow::timerEvent(QTimerEvent *)
{
render();
killTimer(m_renderTimer);
m_renderTimer = 0;
}
-void Window::render()
+void RasterWindow::render()
{
QRect rect(QPoint(), geometry().size());
diff --git a/tests/manual/cocoa/qt_on_cocoa/window.h b/tests/manual/cocoa/qt_on_cocoa/rasterwindow.h
index a36180e0f3..1de66b5302 100644
--- a/tests/manual/cocoa/qt_on_cocoa/window.h
+++ b/tests/manual/cocoa/qt_on_cocoa/rasterwindow.h
@@ -31,14 +31,13 @@
**
****************************************************************************/
-#include <QWindow>
+#include <QRasterWindow>
#include <QImage>
-class Window : public QWindow
+class RasterWindow : public QRasterWindow
{
public:
- Window(QWindow *parent = 0);
- Window(QScreen *screen);
+ RasterWindow(QRasterWindow *parent = 0);
protected:
void mousePressEvent(QMouseEvent *);
diff --git a/tests/manual/highdpi/dragwidget.cpp b/tests/manual/highdpi/dragwidget.cpp
new file mode 100644
index 0000000000..b203566696
--- /dev/null
+++ b/tests/manual/highdpi/dragwidget.cpp
@@ -0,0 +1,223 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2015 The Qt Company Ltd.
+ ** Contact: http://www.qt.io/licensing/
+ **
+ ** This file is part of the test suite of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:LGPL21$
+ ** Commercial License Usage
+ ** Licensees holding valid commercial Qt licenses may use this file in
+ ** accordance with the commercial license agreement provided with the
+ ** Software or, alternatively, in accordance with the terms contained in
+ ** a written agreement between you and The Qt Company. For licensing terms
+ ** and conditions see http://www.qt.io/terms-conditions. For further
+ ** information use the contact form at http://www.qt.io/contact-us.
+ **
+ ** GNU Lesser General Public License Usage
+ ** Alternatively, this file may be used under the terms of the GNU Lesser
+ ** General Public License version 2.1 or version 3 as published by the Free
+ ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+ ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+ ** following information to ensure the GNU Lesser General Public License
+ ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+ ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+ **
+ ** As a special exception, The Qt Company gives you certain additional
+ ** rights. These rights are described in The Qt Company LGPL Exception
+ ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+ **
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+#include <QtWidgets>
+#include "dragwidget.h"
+
+class FramedLabel : public QLabel
+{
+public:
+ FramedLabel(const QString &text, QWidget *parent)
+ : QLabel(text, parent)
+ {
+ setAutoFillBackground(true);
+ setFrameShape(QFrame::Panel);
+ setFrameShadow(QFrame::Raised);
+ }
+};
+
+DragWidget::DragWidget(QString text, QWidget *parent)
+ : QWidget(parent), otherWindow(0)
+{
+ int x = 5;
+ int y = 5;
+
+ bool createChildWindow = text.isEmpty(); // OK, yes this is a hack...
+ if (text.isEmpty())
+ text = "You can drag from this window and drop text here";
+
+ QStringList words = text.split(' ');
+ foreach (QString word, words) {
+ if (!word.isEmpty()) {
+ FramedLabel *wordLabel = new FramedLabel(word, this);
+ wordLabel->move(x, y);
+ wordLabel->show();
+ x += wordLabel->width() + 2;
+ if (x >= 245) {
+ x = 5;
+ y += wordLabel->height() + 2;
+ }
+ }
+ }
+
+ /*
+ QPalette newPalette = palette();
+ newPalette.setColor(QPalette::Window, Qt::white);
+ setPalette(newPalette);
+ */
+
+ setAcceptDrops(true);
+ setMinimumSize(400, qMax(200, y));
+ setWindowTitle(tr("Draggable Text Window %1").arg(createChildWindow ? 1 : 2));
+ if (createChildWindow)
+ otherWindow = new DragWidget("Here is a second window that accepts drops");
+}
+
+void DragWidget::dragEnterEvent(QDragEnterEvent *event)
+{
+ if (event->mimeData()->hasText()) {
+ if (event->source() == this) {
+ event->setDropAction(Qt::MoveAction);
+ event->accept();
+ } else {
+ event->acceptProposedAction();
+ }
+ } else {
+ event->ignore();
+ }
+}
+
+void DragWidget::dragMoveEvent(QDragMoveEvent * event)
+{
+ dragPos = event->pos();
+ dragTimer.start(500, this);
+ update();
+}
+
+void DragWidget::dragLeaveEvent(QDragLeaveEvent *)
+{
+ dragTimer.stop();
+ update();
+}
+
+
+void DragWidget::dropEvent(QDropEvent *event)
+{
+ if (event->mimeData()->hasText()) {
+ const QMimeData *mime = event->mimeData();
+ QStringList pieces = mime->text().split(QRegExp("\\s+"),
+ QString::SkipEmptyParts);
+ QPoint position = event->pos();
+ QPoint hotSpot;
+
+ QList<QByteArray> hotSpotPos = mime->data("application/x-hotspot").split(' ');
+ if (hotSpotPos.size() == 2) {
+ hotSpot.setX(hotSpotPos.first().toInt());
+ hotSpot.setY(hotSpotPos.last().toInt());
+ }
+ dropPos = position - hotSpot;
+ dropTimer.start(500, this);
+ update();
+
+ foreach (QString piece, pieces) {
+ FramedLabel *newLabel = new FramedLabel(piece, this);
+ newLabel->move(position - hotSpot);
+ newLabel->show();
+
+ position += QPoint(newLabel->width(), 0);
+ }
+
+ if (event->source() == this) {
+ event->setDropAction(Qt::MoveAction);
+ event->accept();
+ } else {
+ event->acceptProposedAction();
+ }
+ } else {
+ event->ignore();
+ }
+ foreach (QObject *child, children()) {
+ if (child->inherits("QWidget")) {
+ QWidget *widget = static_cast<QWidget *>(child);
+ if (!widget->isVisible())
+ widget->deleteLater();
+ }
+ }
+}
+
+void DragWidget::mousePressEvent(QMouseEvent *event)
+{
+ QLabel *child = static_cast<QLabel*>(childAt(event->pos()));
+ if (!child)
+ return;
+
+ QPoint hotSpot = event->pos() - child->pos();
+
+ QMimeData *mimeData = new QMimeData;
+ mimeData->setText(child->text());
+ mimeData->setData("application/x-hotspot",
+ QByteArray::number(hotSpot.x()) + " " + QByteArray::number(hotSpot.y()));
+
+ QPixmap pixmap(child->size());
+ child->render(&pixmap);
+
+ QDrag *drag = new QDrag(this);
+ drag->setMimeData(mimeData);
+ drag->setPixmap(pixmap);
+ drag->setHotSpot(hotSpot);
+
+ Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction);
+
+ if (dropAction == Qt::MoveAction)
+ child->close();
+}
+
+void DragWidget::timerEvent(QTimerEvent *e)
+{
+ if (e->timerId() == dragTimer.timerId())
+ dragTimer.stop();
+ if (e->timerId() == dropTimer.timerId())
+ dropTimer.stop();
+ update();
+}
+
+void DragWidget::paintEvent(QPaintEvent *)
+{
+ QPainter p(this);
+ p.fillRect(rect(), Qt::white);
+
+ if (dropTimer.isActive()) {
+ p.setBrush(Qt::red);
+ p.drawEllipse(dropPos, 50, 50);
+ }
+
+ if (dragTimer.isActive()) {
+ p.setPen(QPen(Qt::blue, 5));
+ QPoint p1 = (rect().topLeft()*3 + rect().bottomRight())/4;
+ QPoint p2 = (rect().topLeft() + rect().bottomRight()*3)/4;
+ p.drawLine(p1, dragPos);
+ p.drawLine(p2, dragPos);
+ }
+}
+
+void DragWidget::showEvent(QShowEvent *)
+{
+ if (otherWindow)
+ otherWindow->show();
+}
+
+void DragWidget::hideEvent(QHideEvent *)
+{
+ if (otherWindow)
+ otherWindow->hide();
+}
diff --git a/tests/manual/highdpi/dragwidget.h b/tests/manual/highdpi/dragwidget.h
new file mode 100644
index 0000000000..0d9631e2f8
--- /dev/null
+++ b/tests/manual/highdpi/dragwidget.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2015 The Qt Company Ltd.
+ ** Contact: http://www.qt.io/licensing/
+ **
+ ** This file is part of the test suite of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:LGPL21$
+ ** Commercial License Usage
+ ** Licensees holding valid commercial Qt licenses may use this file in
+ ** accordance with the commercial license agreement provided with the
+ ** Software or, alternatively, in accordance with the terms contained in
+ ** a written agreement between you and The Qt Company. For licensing terms
+ ** and conditions see http://www.qt.io/terms-conditions. For further
+ ** information use the contact form at http://www.qt.io/contact-us.
+ **
+ ** GNU Lesser General Public License Usage
+ ** Alternatively, this file may be used under the terms of the GNU Lesser
+ ** General Public License version 2.1 or version 3 as published by the Free
+ ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+ ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+ ** following information to ensure the GNU Lesser General Public License
+ ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+ ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+ **
+ ** As a special exception, The Qt Company gives you certain additional
+ ** rights. These rights are described in The Qt Company LGPL Exception
+ ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+ **
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+#ifndef DRAGWIDGET_H
+#define DRAGWIDGET_H
+
+#include <QWidget>
+#include <QBasicTimer>
+
+QT_BEGIN_NAMESPACE
+class QDragEnterEvent;
+class QDropEvent;
+QT_END_NAMESPACE
+
+class DragWidget : public QWidget
+{
+public:
+ DragWidget(QString text = QString(), QWidget *parent = 0);
+
+protected:
+ void dragEnterEvent(QDragEnterEvent *event) Q_DECL_OVERRIDE;
+ void dragLeaveEvent(QDragLeaveEvent *event) Q_DECL_OVERRIDE;
+ void dropEvent(QDropEvent *event) Q_DECL_OVERRIDE;
+ void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
+ void dragMoveEvent(QDragMoveEvent * event) Q_DECL_OVERRIDE;
+ void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
+ void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE;
+ void showEvent(QShowEvent *event) Q_DECL_OVERRIDE;
+ void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE;
+private:
+ QPoint dragPos;
+ QPoint dropPos;
+ QBasicTimer dragTimer;
+ QBasicTimer dropTimer;
+ QWidget *otherWindow;
+};
+
+#endif // DRAGWIDGET_H
diff --git a/tests/manual/highdpi/highdpi.pro b/tests/manual/highdpi/highdpi.pro
index 7a2979c74c..7d6b42535e 100644
--- a/tests/manual/highdpi/highdpi.pro
+++ b/tests/manual/highdpi/highdpi.pro
@@ -1,10 +1,17 @@
TEMPLATE = app
TARGET = highdpi
INCLUDEPATH += .
-QT += widgets
-CONFIG+=console
+QT += widgets gui-private
+CONFIG +=console
+CONFIG -= app_bundle
+CONFIG += c++11
# Input
-SOURCES += main.cpp
+SOURCES += \
+ dragwidget.cpp \
+ main.cpp
+
+HEADERS += \
+ dragwidget.h
RESOURCES += \
highdpi.qrc
diff --git a/tests/manual/highdpi/main.cpp b/tests/manual/highdpi/main.cpp
index fd14523a97..692a60d511 100644
--- a/tests/manual/highdpi/main.cpp
+++ b/tests/manual/highdpi/main.cpp
@@ -32,6 +32,7 @@
****************************************************************************/
#include <QMainWindow>
+#include <QMenuBar>
#include <QLabel>
#include <QHBoxLayout>
#include <QApplication>
@@ -39,6 +40,7 @@
#include <QStyle>
#include <QToolBar>
#include <QPushButton>
+#include <QButtonGroup>
#include <QLineEdit>
#include <QScrollBar>
#include <QSlider>
@@ -49,10 +51,219 @@
#include <QWindow>
#include <QScreen>
#include <QFile>
+#include <QMouseEvent>
#include <QTemporaryDir>
+#include <QTimer>
#include <QCommandLineParser>
#include <QCommandLineOption>
+#include <QDebug>
+#include <private/qhighdpiscaling_p.h>
+#include "dragwidget.h"
+
+class DemoContainerBase
+{
+public:
+ DemoContainerBase() : m_widget(0) {}
+ virtual ~DemoContainerBase() {}
+ QString name() { return option().names().first(); }
+ virtual QCommandLineOption &option() = 0;
+ virtual void makeVisible(bool visible, QWidget *parent) = 0;
+ QWidget *widget() { return m_widget; }
+protected:
+ QWidget *m_widget;
+};
+
+typedef QList<DemoContainerBase*> DemoContainerList ;
+
+
+template <class T>
+class DemoContainer : public DemoContainerBase
+{
+public:
+ DemoContainer(const QString &optionName, const QString &description)
+ : m_option(optionName, description)
+ {
+ }
+ ~DemoContainer() { delete m_widget; }
+
+ QCommandLineOption &option() { return m_option; }
+
+ void makeVisible(bool visible, QWidget *parent) {
+ if (visible && !m_widget) {
+ m_widget = new T;
+ m_widget->installEventFilter(parent);
+ }
+ if (m_widget)
+ m_widget->setVisible(visible);
+ }
+private:
+ QCommandLineOption m_option;
+};
+
+class LabelSlider : public QObject
+{
+Q_OBJECT
+public:
+ LabelSlider(QObject *parent, const QString &text, QGridLayout *layout, int row)
+ : QObject(parent)
+ {
+ QLabel *textLabel = new QLabel(text);
+ m_slider = new QSlider();
+ m_slider->setOrientation(Qt::Horizontal);
+ m_slider->setMinimum(1);
+ m_slider->setMaximum(40);
+ m_slider->setValue(10);
+ m_slider->setTracking(false);
+ m_slider->setTickInterval(5);
+ m_slider->setTickPosition(QSlider::TicksBelow);
+ m_label = new QLabel("1.0");
+
+ // set up layouts
+ layout->addWidget(textLabel, row, 0);
+ layout->addWidget(m_slider, row, 1);
+ layout->addWidget(m_label, row, 2);
+
+ // handle slider position change
+ connect(m_slider, &QSlider::sliderMoved, this, &LabelSlider::updateLabel);
+ connect(m_slider, &QSlider::valueChanged, this, &LabelSlider::valueChanged);
+ }
+ void setValue(int scaleFactor) {
+ m_slider->setValue(scaleFactor);
+ updateLabel(scaleFactor);
+ }
+private slots:
+ void updateLabel(int scaleFactor) {
+ // slider value is scale factor times ten;
+ qreal scalefactorF = qreal(scaleFactor) / 10.0;
+
+ // update label, add ".0" if needed.
+ QString number = QString::number(scalefactorF);
+ if (!number.contains("."))
+ number.append(".0");
+ m_label->setText(number);
+ }
+signals:
+ void valueChanged(int scaleFactor);
+private:
+ QSlider *m_slider;
+ QLabel *m_label;
+};
+
+static qreal getScreenFactorWithoutPixelDensity(const QScreen *screen)
+{
+ // this is a hack that relies on knowing the internals of QHighDpiScaling
+ static const char *scaleFactorProperty = "_q_scaleFactor";
+ QVariant screenFactor = screen->property(scaleFactorProperty);
+ return screenFactor.isValid() ? screenFactor.toReal() : 1.0;
+}
+
+static inline qreal getGlobalScaleFactor()
+{
+ QScreen *noScreen = 0;
+ return QHighDpiScaling::factor(noScreen);
+}
+
+class DemoController : public QWidget
+{
+Q_OBJECT
+public:
+ DemoController(DemoContainerList *demos, QCommandLineParser *parser);
+ ~DemoController();
+protected:
+ bool eventFilter(QObject *object, QEvent *event);
+ void closeEvent(QCloseEvent *) { qApp->quit(); }
+private slots:
+ void handleButton(int id, bool toggled);
+private:
+ DemoContainerList *m_demos;
+ QButtonGroup *m_group;
+};
+
+DemoController::DemoController(DemoContainerList *demos, QCommandLineParser *parser)
+ : m_demos(demos)
+{
+ setWindowTitle("screen scale factors");
+ setObjectName("controller"); // make WindowScaleFactorSetter skip this window
+
+ QGridLayout *layout = new QGridLayout;
+ setLayout(layout);
+
+ int layoutRow = 0;
+ LabelSlider *globalScaleSlider = new LabelSlider(this, "Global scale factor", layout, layoutRow++);
+ globalScaleSlider->setValue(int(getGlobalScaleFactor() * 10));
+ connect(globalScaleSlider, &LabelSlider::valueChanged, [](int scaleFactor){
+ // slider value is scale factor times ten;
+ qreal scalefactorF = qreal(scaleFactor) / 10.0;
+ QHighDpiScaling::setGlobalFactor(scalefactorF);
+ });
+
+ // set up one scale control line per screen
+ QList<QScreen *> screens = QGuiApplication::screens();
+ foreach (QScreen *screen, screens) {
+ // create scale control line
+ QSize screenSize = screen->geometry().size();
+ QString screenId = screen->name() + " " + QString::number(screenSize.width())
+ + " " + QString::number(screenSize.height());
+ LabelSlider *slider = new LabelSlider(this, screenId, layout, layoutRow++);
+ slider->setValue(getScreenFactorWithoutPixelDensity(screen) * 10);
+
+ // handle slider value change
+ connect(slider, &LabelSlider::valueChanged, [screen](int scaleFactor){
+ // slider value is scale factor times ten;
+ qreal scalefactorF = qreal(scaleFactor) / 10.0;
+
+ // set scale factor for screen
+ qreal oldFactor = QHighDpiScaling::factor(screen);
+ QHighDpiScaling::setScreenFactor(screen, scalefactorF);
+ qreal newFactor = QHighDpiScaling::factor(screen);
+
+ qDebug() << "factor was / is" << oldFactor << newFactor;
+ });
+ }
+
+ m_group = new QButtonGroup(this);
+ m_group->setExclusive(false);
+
+ for (int i = 0; i < m_demos->size(); ++i) {
+ DemoContainerBase *demo = m_demos->at(i);
+ QPushButton *button = new QPushButton(demo->name());
+ button->setToolTip(demo->option().description());
+ button->setCheckable(true);
+ layout->addWidget(button, layoutRow++, 0, 1, -1);
+ m_group->addButton(button, i);
+
+ if (parser->isSet(demo->option())) {
+ demo->makeVisible(true, this);
+ button->setChecked(true);
+ }
+ }
+ connect(m_group, SIGNAL(buttonToggled(int, bool)), this, SLOT(handleButton(int, bool)));
+}
+
+DemoController::~DemoController()
+{
+ qDeleteAll(*m_demos);
+}
+
+bool DemoController::eventFilter(QObject *object, QEvent *event)
+{
+ if (event->type() == QEvent::Close) {
+ for (int i = 0; i < m_demos->size(); ++i) {
+ DemoContainerBase *demo = m_demos->at(i);
+ if (demo->widget() == object) {
+ m_group->button(i)->setChecked(false);
+ break;
+ }
+ }
+ }
+ return false;
+}
+
+void DemoController::handleButton(int id, bool toggled)
+{
+ m_demos->at(id)->makeVisible(toggled, this);
+}
class PixmapPainter : public QWidget
{
@@ -69,7 +280,6 @@ public:
QIcon qtIcon;
};
-
PixmapPainter::PixmapPainter()
{
pixmap1X = QPixmap(":/qticon32.png");
@@ -172,15 +382,18 @@ class MainWindow : public QMainWindow
{
public:
MainWindow();
+ QMenu *addNewMenu(const QString &title, int itemCount = 5);
QIcon qtIcon;
QIcon qtIcon1x;
QIcon qtIcon2x;
QToolBar *fileToolBar;
+ int menuCount;
};
MainWindow::MainWindow()
+ :menuCount(0)
{
// beware that QIcon auto-loads the @2x versions.
qtIcon1x.addFile(":/qticon16.png");
@@ -192,8 +405,33 @@ MainWindow::MainWindow()
// fileToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
fileToolBar->addAction(new QAction(qtIcon1x, QString("1x"), this));
fileToolBar->addAction(new QAction(qtIcon2x, QString("2x"), this));
+ addNewMenu("&Edit");
+ addNewMenu("&Build");
+ addNewMenu("&Debug", 4);
+ addNewMenu("&Transmogrify", 7);
+ addNewMenu("T&ools");
+ addNewMenu("&Help", 2);
}
+
+QMenu *MainWindow::addNewMenu(const QString &title, int itemCount)
+{
+ QMenu *menu = menuBar()->addMenu(title);
+ for (int i = 0; i < itemCount; i++) {
+ menuCount++;
+ QString s = "Menu item " + QString::number(menuCount);
+ if (i == 3) {
+ QMenu *subMenu = menu->addMenu(s);
+ for (int j = 1; j < 4; j++)
+ subMenu->addAction(QString::fromLatin1("SubMenu item %1.%2").arg(menuCount).arg(j));
+ } else {
+ menu->addAction(s);
+ }
+ }
+ return menu;
+}
+
+
class StandardIcons : public QWidget
{
public:
@@ -205,7 +443,7 @@ public:
int dy = 50;
int maxX = 500;
- for (int iconIndex = QStyle::SP_TitleBarMenuButton; iconIndex < QStyle::SP_MediaVolumeMuted; ++iconIndex) {
+ for (uint iconIndex = QStyle::SP_TitleBarMenuButton; iconIndex < QStyle::SP_MediaVolumeMuted; ++iconIndex) {
QIcon icon = qApp->style()->standardIcon(QStyle::StandardPixmap(iconIndex));
QPainter p(this);
p.drawPixmap(x, y, icon.pixmap(dx - 5, dy - 5));
@@ -295,14 +533,27 @@ public:
void paintEvent(QPaintEvent *)
{
QPainter painter(this);
- int y = 40;
- for (int fontSize = 2; fontSize < 18; fontSize += 2) {
+
+ // Points
+ int y = 10;
+ for (int fontSize = 6; fontSize < 18; fontSize += 2) {
QFont font;
font.setPointSize(fontSize);
- QString string = QString(QStringLiteral("%1 The quick brown fox jumped over the lazy Doug.")).arg(fontSize);
+ QString string = QString(QStringLiteral("This text is in point size %1")).arg(fontSize);
+ painter.setFont(font);
+ y += (painter.fontMetrics().lineSpacing());
+ painter.drawText(10, y, string);
+ }
+
+ // Pixels
+ y += painter.fontMetrics().lineSpacing();
+ for (int fontSize = 6; fontSize < 18; fontSize += 2) {
+ QFont font;
+ font.setPixelSize(fontSize);
+ QString string = QString(QStringLiteral("This text is in pixel size %1")).arg(fontSize);
painter.setFont(font);
+ y += (painter.fontMetrics().lineSpacing());
painter.drawText(10, y, string);
- y += (fontSize * 2.5);
}
}
};
@@ -461,97 +712,427 @@ public:
}
};
+class LinePainter : public QWidget
+{
+public:
+ void paintEvent(QPaintEvent *event);
+ void mousePressEvent(QMouseEvent *event);
+ void mouseReleaseEvent(QMouseEvent *event);
+ void mouseMoveEvent(QMouseEvent *event);
+
+ QPoint lastMousePoint;
+ QVector<QPoint> linePoints;
+};
-int main(int argc, char **argv)
+void LinePainter::paintEvent(QPaintEvent *)
{
- QApplication app(argc, argv);
- QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
- QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QPainter p(this);
+ p.fillRect(QRect(QPoint(0, 0), size()), QBrush(Qt::gray));
- QCommandLineParser parser;
- parser.setApplicationDescription("High DPI tester");
- parser.addHelpOption();
- parser.addVersionOption();
- QCommandLineOption pixmapPainterOption("pixmap", "Test pixmap painter");
- parser.addOption(pixmapPainterOption);
- QCommandLineOption labelOption("label", "Test Labels");
- parser.addOption(labelOption);
- QCommandLineOption mainWindowOption("mainwindow", "Test QMainWindow");
- parser.addOption(mainWindowOption);
- QCommandLineOption standardIconsOption("standard-icons", "Test standard icons");
- parser.addOption(standardIconsOption);
- QCommandLineOption cachingOption("caching", "Test caching");
- parser.addOption(cachingOption);
- QCommandLineOption styleOption("styles", "Test style");
- parser.addOption(styleOption);
- QCommandLineOption fontsOption("fonts", "Test fonts");
- parser.addOption(fontsOption);
- QCommandLineOption iconDrawingOption("icondrawing", "Test icon drawing");
- parser.addOption(iconDrawingOption);
- QCommandLineOption buttonsOption("buttons", "Test buttons");
- parser.addOption(buttonsOption);
+ // Default antialiased line
+ p.setRenderHint(QPainter::Antialiasing);
+ p.drawLines(linePoints);
+
+ // Cosmetic 1 antialiased line
+ QPen pen;
+ pen.setCosmetic(true);
+ pen.setWidth(1);
+ p.setPen(pen);
+ p.translate(3, 3);
+ p.drawLines(linePoints);
+
+ // Aliased cosmetic 1 line
+ p.setRenderHint(QPainter::Antialiasing, false);
+ p.translate(3, 3);
+ p.drawLines(linePoints);
+}
- parser.process(app);
+void LinePainter::mousePressEvent(QMouseEvent *event)
+{
+ lastMousePoint = event->pos();
+}
- QScopedPointer<PixmapPainter> pixmapPainter;
- if (parser.isSet(pixmapPainterOption)) {
- pixmapPainter.reset(new PixmapPainter);
- pixmapPainter->show();
+void LinePainter::mouseReleaseEvent(QMouseEvent *)
+{
+ lastMousePoint = QPoint();
+}
+
+void LinePainter::mouseMoveEvent(QMouseEvent *event)
+{
+ if (lastMousePoint.isNull())
+ return;
+
+ QPoint newMousePoint = event->pos();
+ if (lastMousePoint == newMousePoint)
+ return;
+ linePoints.append(lastMousePoint);
+ linePoints.append(newMousePoint);
+ lastMousePoint = newMousePoint;
+ update();
+}
+
+class CursorTester : public QWidget
+{
+public:
+ CursorTester()
+ :moveLabel(0), moving(false)
+ {
}
- QScopedPointer<Labels> label;
- if (parser.isSet(labelOption)) {
- label.reset(new Labels);
- label->resize(200, 200);
- label->show();
+ inline QRect getRect(int idx) const
+ {
+ int h = height() / 2;
+ return QRect(10, 10 + h * (idx - 1), width() - 20, h - 20);
+ }
+ void paintEvent(QPaintEvent *)
+ {
+ QPainter p(this);
+ QRect r1 = getRect(1);
+ QRect r2 = getRect(2);
+ p.fillRect(r1, QColor(200, 200, 250));
+ p.drawText(r1, "Drag from here to move a window based on QCursor::pos()");
+ p.fillRect(r2, QColor(250, 200, 200));
+ p.drawText(r2, "Drag from here to move a window based on mouse event position");
+
+ if (moving) {
+ p.setPen(Qt::darkGray);
+ QFont f = font();
+ f.setPointSize(8);
+ p.setFont(f);
+ p.drawEllipse(mousePos, 30,60);
+ QPoint pt = mousePos - QPoint(0, 60);
+ QPoint pt2 = pt - QPoint(30,10);
+ QPoint offs(30, 0);
+ p.drawLine(pt, pt2);
+ p.drawLine(pt2 - offs, pt2 + offs);
+ p.drawText(pt2 - offs, "mouse pos");
+
+ p.setPen(QColor(50,130,70));
+ QPoint cursorPos = mapFromGlobal(QCursor::pos());
+ pt = cursorPos - QPoint(0, 30);
+ pt2 = pt + QPoint(60, -20);
+ p.drawEllipse(cursorPos, 60, 30);
+ p.drawLine(pt, pt2);
+ p.drawLine(pt2 - offs, pt2 + offs);
+ p.drawText(pt2 - offs, "cursor pos");
+ }
}
- QScopedPointer<MainWindow> mainWindow;
- if (parser.isSet(mainWindowOption)) {
- mainWindow.reset(new MainWindow);
- mainWindow->show();
+ void mousePressEvent(QMouseEvent *e)
+ {
+ if (moving)
+ return;
+ QRect r1 = getRect(1);
+ QRect r2 = getRect(2);
+
+ moving = r1.contains(e->pos()) || r2.contains(e->pos());
+ if (!moving)
+ return;
+ useCursorPos = r1.contains(e->pos());
+
+ if (!moveLabel)
+ moveLabel = new QLabel(this,Qt::BypassWindowManagerHint|Qt::FramelessWindowHint|Qt::Window );
+
+ if (useCursorPos)
+ moveLabel->setText("I'm following QCursor::pos()");
+ else
+ moveLabel->setText("I'm following QMouseEvent::globalPos()");
+ moveLabel->adjustSize();
+ mouseMoveEvent(e);
+ moveLabel->show();
}
- QScopedPointer<StandardIcons> icons;
- if (parser.isSet(standardIconsOption)) {
- icons.reset(new StandardIcons);
- icons->resize(510, 510);
- icons->show();
+ void mouseReleaseEvent(QMouseEvent *)
+ {
+ if (moveLabel)
+ moveLabel->hide();
+ update();
+ moving = false;
}
- QScopedPointer<Caching> caching;
- if (parser.isSet(cachingOption)) {
- caching.reset(new Caching);
- caching->resize(300, 300);
- caching->show();
+ void mouseMoveEvent(QMouseEvent *e)
+ {
+ if (!moving)
+ return;
+ QPoint pos = useCursorPos ? QCursor::pos() : e->globalPos();
+ pos -= moveLabel->rect().center();
+ moveLabel->move(pos);
+ mousePos = e->pos();
+ update();
}
- QScopedPointer<Style> style;
- if (parser.isSet(styleOption)) {
- style.reset(new Style);
- style->show();
+private:
+ QLabel *moveLabel;
+ bool useCursorPos;
+ bool moving;
+ QPoint mousePos;
+};
+
+
+class ScreenDisplayer : public QWidget
+{
+public:
+ ScreenDisplayer()
+ : QWidget(), moveLabel(0), scaleFactor(1.0)
+ {
}
- QScopedPointer<Fonts> fonts;
- if (parser.isSet(fontsOption)) {
- fonts.reset(new Fonts);
- fonts->show();
+ void timerEvent(QTimerEvent *) {
+ update();
}
- QScopedPointer<IconDrawing> iconDrawing;
- if (parser.isSet(iconDrawingOption)) {
- iconDrawing.reset(new IconDrawing);
- iconDrawing->show();
+ void mousePressEvent(QMouseEvent *) {
+ if (!moveLabel)
+ moveLabel = new QLabel(this,Qt::BypassWindowManagerHint|Qt::FramelessWindowHint|Qt::Window );
+ moveLabel->setText("Hello, Qt this is a label\nwith some text");
+ moveLabel->show();
+ }
+ void mouseMoveEvent(QMouseEvent *e) {
+ if (!moveLabel)
+ return;
+ moveLabel->move(e->pos() / scaleFactor);
+ QString str;
+ QDebug dbg(&str);
+ dbg.setAutoInsertSpaces(false);
+ dbg << moveLabel->geometry();
+ moveLabel->setText(str);
+ }
+ void mouseReleaseEvent(QMouseEvent *) {
+ if (moveLabel)
+ moveLabel->hide();
+ }
+ void showEvent(QShowEvent *) {
+ refreshTimer.start(300, this);
}
+ void hideEvent(QHideEvent *) {
+ refreshTimer.stop();
+ }
+ void paintEvent(QPaintEvent *) {
+ QPainter p(this);
+ QRectF total;
+ QList<QScreen*> screens = qApp->screens();
+ foreach (QScreen *screen, screens) {
+ total |= screen->geometry();
+ }
+ if (total.isEmpty())
+ return;
+
+ scaleFactor = qMin(width()/total.width(), height()/total.height());
+
+ p.fillRect(rect(), Qt::black);
+ p.scale(scaleFactor, scaleFactor);
+ p.translate(-total.topLeft());
+ p.setPen(QPen(Qt::white, 10));
+ p.setBrush(Qt::gray);
+
- QScopedPointer<Buttons> buttons;
- if (parser.isSet(buttonsOption)) {
- buttons.reset(new Buttons);
- buttons->show();
+ foreach (QScreen *screen, screens) {
+ p.drawRect(screen->geometry());
+ QFont f = font();
+ f.setPixelSize(screen->geometry().height() / 8);
+ p.setFont(f);
+ p.drawText(screen->geometry(), Qt::AlignCenter, screen->name());
+ }
+ p.setBrush(QColor(200,220,255,127));
+ foreach (QWidget *widget, QApplication::topLevelWidgets()) {
+ if (!widget->isHidden())
+ p.drawRect(widget->geometry());
+ }
+
+ QPolygon cursorShape;
+ cursorShape << QPoint(0,0) << QPoint(20, 60)
+ << QPoint(30, 50) << QPoint(60, 80)
+ << QPoint(80, 60) << QPoint(50, 30)
+ << QPoint(60, 20);
+ cursorShape.translate(QCursor::pos());
+ p.drawPolygon(cursorShape);
}
+private:
+ QLabel *moveLabel;
+ QBasicTimer refreshTimer;
+ qreal scaleFactor;
+};
+
+class PhysicalSizeTest : public QWidget
+{
+Q_OBJECT
+public:
+ PhysicalSizeTest() : QWidget(), m_ignoreResize(false) {}
+ void paintEvent(QPaintEvent *event);
+ void resizeEvent(QResizeEvent *) {
+ qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
+ QSizeF s = size();
+ if (!m_ignoreResize)
+ m_physicalSize = s / ppi;
+ }
+ bool event(QEvent *event) {
+ if (event->type() == QEvent::ScreenChangeInternal) {
+ // we will get resize events when the scale factor changes
+ m_ignoreResize = true;
+ QTimer::singleShot(100, this, SLOT(handleScreenChange()));
+ }
+ return QWidget::event(event);
+ }
+public slots:
+ void handleScreenChange() {
+ qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
+ QSizeF newSize = m_physicalSize * ppi;
+ resize(newSize.toSize());
+ m_ignoreResize = false;
+ }
+private:
+ QSizeF m_physicalSize;
+ bool m_ignoreResize;
+};
+
+void PhysicalSizeTest::paintEvent(QPaintEvent *)
+{
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing);
+
+ qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
+ qreal ppmm = ppi / 25.4;
+ qreal h = 15 * ppmm;
+ QRectF rulerRect(0,0, width(), h);
+ rulerRect.moveCenter(rect().center());
+
+ QFont f = font();
+ f.setPixelSize(18);
+ p.setFont(f);
+
+ // draw a rectangle in (Qt) pixel coordinates, for comparison
+ QRect pixelRect(0, 0, 300, 50);
+ pixelRect.moveTopLeft(QPoint(5 * ppmm, rulerRect.bottom() + 5 * ppmm));
+ p.fillRect(pixelRect, QColor(199,222,255));
+ p.drawText(pixelRect, "This rectangle is 300x50 pixels");
+
+ f.setPixelSize(4 * ppmm);
+ p.setFont(f);
+
+ QRectF topRect(0, 0, width(), rulerRect.top());
+ p.drawText(topRect, Qt::AlignCenter, "The ruler is drawn in physical units.\nThis window tries to keep its physical size\nwhen moved between screens.");
+
+ // draw a ruler in real physical coordinates
+
+ p.fillRect(rulerRect, QColor(255, 222, 111));
+
+ QPen linePen(Qt::black, 0.3 * ppmm);
+ p.setPen(linePen);
+ f.setBold(true);
+ p.setFont(f);
+
+ qreal vCenter = rulerRect.center().y();
+ p.drawLine(0, vCenter, width(), vCenter);
+
+ // cm
+ for (int i = 0;;) {
+ i++;
+ qreal x = i * ppmm;
+ if (x > width())
+ break;
+ qreal y = rulerRect.bottom();
+ qreal len;
+ if (i % 5)
+ len = 2 * ppmm;
+ else if (i % 10)
+ len = 3 * ppmm;
+ else
+ len = h / 2;
+
+ p.drawLine(QPointF(x, y), QPointF(x, y - len));
+ if (i % 10 == 5) {
+ QRectF textR(0, 0, 5 * ppmm, h / 2 - 2 * ppmm);
+ textR.moveTopLeft(QPointF(x, vCenter));
+ int n = i / 10 + 1;
+ if (n % 10 == 0)
+ p.setPen(Qt::red);
+ p.drawText(textR, Qt::AlignCenter, QString::number(n));
+ p.setPen(linePen);
+ }
+ }
+
+ //inches
+ for (int i = 0;;) {
+ i++;
+ qreal x = i * ppi / 16;
+ if (x > width())
+ break;
+ qreal y = rulerRect.top();
+
+ qreal d = h / 10;
+ qreal len;
+ if (i % 2)
+ len = 1 * d;
+ else if (i % 4)
+ len = 2 * d;
+ else if (i % 8)
+ len = 3 * d;
+ else if (i % 16)
+ len = 4 * d;
+ else
+ len = h / 2;
+
+ p.drawLine(QPointF(x, y), QPointF(x, y + len));
+ if (i % 16 == 12) {
+ QRectF textR(0, 0, 0.25 * ppi, h / 2 - 2 * d);
+ textR.moveBottomLeft(QPointF(x, vCenter));
+ p.drawText(textR, Qt::AlignCenter, QString::number(1 + i/16));
+ }
+ }
+
+}
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+ QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+
+ int argumentCount = QCoreApplication::arguments().count();
+
+ QCommandLineParser parser;
+ parser.setApplicationDescription("High DPI tester. Pass one or more of the options to\n"
+ "test various high-dpi aspects. \n"
+ "--interactive is a special option and opens a configuration"
+ " window.");
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption controllerOption("interactive", "Show configuration window.");
+ parser.addOption(controllerOption);
+
+
+ DemoContainerList demoList;
+ demoList << new DemoContainer<PixmapPainter>("pixmap", "Test pixmap painter");
+ demoList << new DemoContainer<Labels>("label", "Test Labels");
+ demoList << new DemoContainer<MainWindow>("mainwindow", "Test QMainWindow");
+ demoList << new DemoContainer<StandardIcons>("standard-icons", "Test standard icons");
+ demoList << new DemoContainer<Caching>("caching", "Test caching");
+ demoList << new DemoContainer<Style>("styles", "Test style");
+ demoList << new DemoContainer<Fonts>("fonts", "Test fonts");
+ demoList << new DemoContainer<IconDrawing>("icondrawing", "Test icon drawing");
+ demoList << new DemoContainer<Buttons>("buttons", "Test buttons");
+ demoList << new DemoContainer<LinePainter>("linepainter", "Test line painting");
+ demoList << new DemoContainer<DragWidget>("draganddrop", "Test drag and drop");
+ demoList << new DemoContainer<CursorTester>("cursorpos", "Test cursor and window positioning");
+ demoList << new DemoContainer<ScreenDisplayer>("screens", "Test screen and window positioning");
+ demoList << new DemoContainer<PhysicalSizeTest>("physicalsize", "Test manual highdpi support using physicalDotsPerInch");
+
+
+ foreach (DemoContainerBase *demo, demoList)
+ parser.addOption(demo->option());
+
+ parser.process(app);
+
+ //controller takes ownership of all demos
+ DemoController controller(&demoList, &parser);
+
+ if (parser.isSet(controllerOption) || argumentCount <= 1)
+ controller.show();
if (QApplication::topLevelWidgets().isEmpty())
parser.showHelp(0);
return app.exec();
}
+
+#include "main.moc"
diff --git a/tests/manual/qscreen/main.cpp b/tests/manual/qscreen/main.cpp
index 1047ffcdfc..8ed9cebfb4 100644
--- a/tests/manual/qscreen/main.cpp
+++ b/tests/manual/qscreen/main.cpp
@@ -36,23 +36,118 @@
#include <QScreen>
#include <QWindow>
#include <QDebug>
+#include <QTextStream>
#include <QFormLayout>
+#include <QMainWindow>
+#include <QMenu>
+#include <QMenuBar>
+#include <QAction>
+#include <QStatusBar>
#include <QLineEdit>
#include <QDesktopWidget>
-int i = 0;
+class ScreenPropertyWatcher : public PropertyWatcher
+{
+ Q_OBJECT
+public:
+ ScreenPropertyWatcher(QWidget *wp = Q_NULLPTR) : PropertyWatcher(Q_NULLPTR, QString(), wp)
+ {
+ // workaround for the fact that virtualSiblings is not a property,
+ // thus there is no change notification:
+ // allow the user to update the field manually
+ connect(this, &PropertyWatcher::updatedAllFields, this, &ScreenPropertyWatcher::updateSiblings);
+ }
+
+ QScreen *screenSubject() const { return qobject_cast<QScreen *>(subject()); }
+ void setScreenSubject(QScreen *s, const QString &annotation = QString())
+ {
+ setSubject(s, annotation);
+ updateSiblings();
+ }
-typedef QHash<QScreen*, PropertyWatcher*> ScreensHash;
-Q_GLOBAL_STATIC(ScreensHash, props);
+public slots:
+ void updateSiblings();
+};
-void updateSiblings(PropertyWatcher* w)
+void ScreenPropertyWatcher::updateSiblings()
{
- QLineEdit *siblingsField = w->findChild<QLineEdit *>("siblings");
- QScreen* screen = (QScreen*)w->subject();
- QStringList siblingsList;
- foreach (QScreen *sibling, screen->virtualSiblings())
- siblingsList << sibling->name();
- siblingsField->setText(siblingsList.join(", "));
+ const QScreen *screen = screenSubject();
+ if (!screen)
+ return;
+ const QString objectName = QLatin1String("siblings");
+ QLineEdit *siblingsField = findChild<QLineEdit *>(objectName);
+ if (!siblingsField) {
+ siblingsField = new QLineEdit(this);
+ siblingsField->setObjectName(objectName);
+ siblingsField->setReadOnly(true);
+ formLayout()->insertRow(0, QLatin1String("virtualSiblings"), siblingsField);
+ }
+ QString text;
+ foreach (const QScreen *sibling, screen->virtualSiblings()) {
+ if (!text.isEmpty())
+ text += QLatin1String(", ");
+ text += sibling->name();
+ }
+ siblingsField->setText(text);
+}
+
+class ScreenWatcherMainWindow : public QMainWindow
+{
+ Q_OBJECT
+public:
+ explicit ScreenWatcherMainWindow(QScreen *screen);
+
+ QScreen *screenSubject() const { return m_watcher->screenSubject(); }
+
+protected:
+ bool event(QEvent *event) Q_DECL_OVERRIDE;
+
+private:
+ const QString m_annotation;
+ ScreenPropertyWatcher *m_watcher;
+};
+
+static int i = 0;
+
+ScreenWatcherMainWindow::ScreenWatcherMainWindow(QScreen *screen)
+ : m_annotation(QLatin1Char('#') + QString::number(i++))
+ , m_watcher(new ScreenPropertyWatcher(this))
+{
+ setAttribute(Qt::WA_DeleteOnClose);
+ setCentralWidget(m_watcher);
+ m_watcher->setScreenSubject(screen, m_annotation);
+
+ QMenu *fileMenu = menuBar()->addMenu(QLatin1String("&File"));
+ QAction *a = fileMenu->addAction(QLatin1String("Close"));
+ a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_W));
+ connect(a, SIGNAL(triggered()), this, SLOT(close()));
+ a = fileMenu->addAction(QLatin1String("Quit"));
+ a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
+ connect(a, SIGNAL(triggered()), qApp, SLOT(quit()));
+}
+
+static inline QString msgScreenChange(const QWidget *w, const QScreen *oldScreen, const QScreen *newScreen)
+{
+ QString result;
+ const QRect geometry = w->geometry();
+ const QPoint pos = QCursor::pos();
+ QTextStream(&result) << "Screen changed \"" << oldScreen->name() << "\" --> \""
+ << newScreen->name() << "\" at " << pos.x() << ',' << pos.y() << " geometry: "
+ << geometry.width() << 'x' << geometry.height() << forcesign << geometry.x()
+ << geometry.y() << '.';
+ return result;
+}
+
+bool ScreenWatcherMainWindow::event(QEvent *event)
+{
+ if (event->type() == QEvent::ScreenChangeInternal) {
+ QScreen *newScreen = windowHandle()->screen();
+ const QString message = msgScreenChange(this, m_watcher->screenSubject(), newScreen);
+ qDebug().noquote() << message;
+ statusBar()->showMessage(message);
+ m_watcher->setScreenSubject(newScreen, m_annotation);
+ }
+ return QMainWindow::event(event);
}
void screenAdded(QScreen* screen)
@@ -60,12 +155,7 @@ void screenAdded(QScreen* screen)
screen->setOrientationUpdateMask((Qt::ScreenOrientations)0x0F);
qDebug("\nscreenAdded %s siblings %d first %s", qPrintable(screen->name()), screen->virtualSiblings().count(),
(screen->virtualSiblings().isEmpty() ? "none" : qPrintable(screen->virtualSiblings().first()->name())));
- PropertyWatcher *w = new PropertyWatcher(screen, QString::number(i++));
- QLineEdit *siblingsField = new QLineEdit();
- siblingsField->setObjectName("siblings");
- siblingsField->setReadOnly(true);
- w->layout()->insertRow(0, "virtualSiblings", siblingsField);
- updateSiblings(w);
+ ScreenWatcherMainWindow *w = new ScreenWatcherMainWindow(screen);
// Set the screen via QDesktopWidget. This corresponds to setScreen() for the underlying
// QWindow. This is essential when having separate X screens since the the positioning below is
@@ -84,18 +174,17 @@ void screenAdded(QScreen* screen)
geom.setHeight(screen->geometry().height() * 9 / 10);
geom.moveCenter(screen->geometry().center());
w->setGeometry(geom);
-
- props->insert(screen, w);
-
- // workaround for the fact that virtualSiblings is not a property,
- // thus there is no change notification:
- // allow the user to update the field manually
- QObject::connect(w, &PropertyWatcher::updatedAllFields, &updateSiblings);
}
void screenRemoved(QScreen* screen)
{
- delete props->take(screen);
+ const QWidgetList topLevels = QApplication::topLevelWidgets();
+ for (int i = topLevels.size() - 1; i >= 0; --i) {
+ if (ScreenWatcherMainWindow *sw = qobject_cast<ScreenWatcherMainWindow *>(topLevels.at(i))) {
+ if (sw->screenSubject() == screen)
+ sw->close();
+ }
+ }
}
int main(int argc, char *argv[])
@@ -108,3 +197,5 @@ int main(int argc, char *argv[])
QObject::connect((const QGuiApplication*)QGuiApplication::instance(), &QGuiApplication::screenRemoved, &screenRemoved);
return a.exec();
}
+
+#include "main.moc"
diff --git a/tests/manual/qscreen/propertywatcher.cpp b/tests/manual/qscreen/propertywatcher.cpp
index cfb5ea272d..b745ef5125 100644
--- a/tests/manual/qscreen/propertywatcher.cpp
+++ b/tests/manual/qscreen/propertywatcher.cpp
@@ -35,33 +35,82 @@
#include <QMetaProperty>
#include <QFormLayout>
#include <QPushButton>
+#include <QLabel>
#include "propertyfield.h"
PropertyWatcher::PropertyWatcher(QObject *subject, QString annotation, QWidget *parent)
- : QWidget(parent), m_subject(subject), m_layout(new QFormLayout)
+ : QWidget(parent), m_subject(Q_NULLPTR), m_formLayout(new QFormLayout(this))
{
- setWindowTitle(QString("Properties of %1 %2 %3")
- .arg(subject->metaObject()->className()).arg(subject->objectName()).arg(annotation));
setMinimumSize(450, 300);
+ m_formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
+ setSubject(subject, annotation);
+}
+
+class UpdatesEnabledBlocker
+{
+ Q_DISABLE_COPY(UpdatesEnabledBlocker);
+public:
+ explicit UpdatesEnabledBlocker(QWidget *w) : m_widget(w)
+ {
+ m_widget->setUpdatesEnabled(false);
+ }
+ ~UpdatesEnabledBlocker()
+ {
+ m_widget->setUpdatesEnabled(true);
+ m_widget->update();
+ }
+
+private:
+ QWidget *m_widget;
+};
+
+void PropertyWatcher::setSubject(QObject *s, const QString &annotation)
+{
+ if (s == m_subject)
+ return;
+
+ UpdatesEnabledBlocker blocker(this);
+
+ if (m_subject) {
+ disconnect(m_subject, &QObject::destroyed, this, &PropertyWatcher::subjectDestroyed);
+ for (int i = m_formLayout->count() - 1; i >= 0; --i) {
+ QLayoutItem *item = m_formLayout->takeAt(i);
+ delete item->widget();
+ delete item;
+ }
+ window()->setWindowTitle(QString());
+ window()->setWindowIconText(QString());
+ }
+
+ m_subject = s;
+ if (!m_subject)
+ return;
+
const QMetaObject* meta = m_subject->metaObject();
+ QString title = QLatin1String("Properties ") + QLatin1String(meta->className());
+ if (!m_subject->objectName().isEmpty())
+ title += QLatin1Char(' ') + m_subject->objectName();
+ if (!annotation.isEmpty())
+ title += QLatin1Char(' ') + annotation;
+ window()->setWindowTitle(title);
- for (int i = 0; i < meta->propertyCount(); ++i) {
- QMetaProperty prop = meta->property(i);
+ for (int i = 0, count = meta->propertyCount(); i < count; ++i) {
+ const QMetaProperty prop = meta->property(i);
if (prop.isReadable()) {
- PropertyField* field = new PropertyField(m_subject, prop);
- m_layout->addRow(prop.name(), field);
+ QLabel *label = new QLabel(prop.name(), this);
+ PropertyField *field = new PropertyField(m_subject, prop, this);
+ m_formLayout->addRow(label, field);
+ if (!qstrcmp(prop.name(), "name"))
+ window()->setWindowIconText(prop.read(m_subject).toString());
+ label->setVisible(true);
+ field->setVisible(true);
}
}
- QPushButton *updateButton = new QPushButton("update");
- connect(updateButton, &QPushButton::clicked, this, &PropertyWatcher::updateAllFields);
- m_layout->addRow("", updateButton);
- m_layout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
- setLayout(m_layout);
- connect(subject, &QObject::destroyed, this, &PropertyWatcher::subjectDestroyed);
-}
+ connect(m_subject, &QObject::destroyed, this, &PropertyWatcher::subjectDestroyed);
-PropertyWatcher::~PropertyWatcher()
-{
+ QPushButton *updateButton = new QPushButton(QLatin1String("Update"), this);
+ connect(updateButton, &QPushButton::clicked, this, &PropertyWatcher::updateAllFields);
+ m_formLayout->addRow(QString(), updateButton);
}
void PropertyWatcher::updateAllFields()
diff --git a/tests/manual/qscreen/propertywatcher.h b/tests/manual/qscreen/propertywatcher.h
index 7dccfe3672..01e448845a 100644
--- a/tests/manual/qscreen/propertywatcher.h
+++ b/tests/manual/qscreen/propertywatcher.h
@@ -44,10 +44,12 @@ class PropertyWatcher : public QWidget
Q_OBJECT
public:
- PropertyWatcher(QObject* subject, QString annotation = QString(), QWidget *parent = 0);
- ~PropertyWatcher();
- QFormLayout *layout() { return m_layout; }
- QObject* subject() { return m_subject; }
+ explicit PropertyWatcher(QObject* subject = Q_NULLPTR, QString annotation = QString(), QWidget *parent = Q_NULLPTR);
+
+ QFormLayout *formLayout() { return m_formLayout; }
+
+ QObject *subject() const { return m_subject; }
+ void setSubject(QObject *s, const QString &annotation = QString());
public slots:
void updateAllFields();
@@ -56,9 +58,9 @@ public slots:
signals:
void updatedAllFields(PropertyWatcher* sender);
-protected:
+private:
QObject* m_subject;
- QFormLayout * m_layout;
+ QFormLayout * m_formLayout;
};
#endif // PROPERTY_WATCHER_H
diff --git a/tests/manual/qscreen/qscreen.pro b/tests/manual/qscreen/qscreen.pro
index cec8bbf245..5d587db3f4 100644
--- a/tests/manual/qscreen/qscreen.pro
+++ b/tests/manual/qscreen/qscreen.pro
@@ -1,4 +1,5 @@
QT += core gui widgets
+CONFIG += console
TARGET = qscreen
TEMPLATE = app
diff --git a/tests/manual/qsysinfo/main.cpp b/tests/manual/qsysinfo/main.cpp
index a3f21140cb..9456bd9b03 100644
--- a/tests/manual/qsysinfo/main.cpp
+++ b/tests/manual/qsysinfo/main.cpp
@@ -134,6 +134,7 @@ int main(int argc, char *argv[])
printf("QSysInfo::productType() = %s\n", qPrintable(QSysInfo::productType()));
printf("QSysInfo::productVersion() = %s\n", qPrintable(QSysInfo::productVersion()));
printf("QSysInfo::prettyProductName() = %s\n", qPrintable(QSysInfo::prettyProductName()));
+ printf("QSysInfo::machineHostName() = %s\n", qPrintable(QSysInfo::machineHostName()));
return 0;
}
diff --git a/tests/manual/qtabletevent/device_information/tabletwidget.cpp b/tests/manual/qtabletevent/device_information/tabletwidget.cpp
index 2e4cb6658f..f1d838f01d 100644
--- a/tests/manual/qtabletevent/device_information/tabletwidget.cpp
+++ b/tests/manual/qtabletevent/device_information/tabletwidget.cpp
@@ -73,6 +73,7 @@ bool TabletWidget::eventFilter(QObject *, QEvent *ev)
mRot = event->rotation();
mButton = event->button();
mButtons = event->buttons();
+ mTimestamp = event->timestamp();
if (isVisible())
update();
break;
@@ -84,6 +85,7 @@ bool TabletWidget::eventFilter(QObject *, QEvent *ev)
mType = event->type();
mPos = event->pos();
mGPos = event->globalPos();
+ mTimestamp = event->timestamp();
}
default:
break;
@@ -122,6 +124,7 @@ void TabletWidget::paintEvent(QPaintEvent *)
eventInfo << QString("Global position: %1 %2").arg(QString::number(mGPos.x()), QString::number(mGPos.y()));
eventInfo << QString("Local position: %1 %2").arg(QString::number(mPos.x()), QString::number(mPos.y()));
+ eventInfo << QString("Timestamp: %1").arg(QString::number(mTimestamp));
if (mType == QEvent::TabletEnterProximity || mType == QEvent::TabletLeaveProximity
|| mType == QEvent::TabletMove || mType == QEvent::TabletPress
|| mType == QEvent::TabletRelease) {
diff --git a/tests/manual/qtabletevent/device_information/tabletwidget.h b/tests/manual/qtabletevent/device_information/tabletwidget.h
index 2861eb4814..95631be57b 100644
--- a/tests/manual/qtabletevent/device_information/tabletwidget.h
+++ b/tests/manual/qtabletevent/device_information/tabletwidget.h
@@ -65,6 +65,7 @@ private:
qreal mPress, mTangential, mRot;
qint64 mUnique;
bool mMouseToo;
+ ulong mTimestamp;
};
#endif // TABLETWIDGET_H
diff --git a/tests/manual/qtabletevent/regular_widgets/main.cpp b/tests/manual/qtabletevent/regular_widgets/main.cpp
index 5a83decfa2..a6fddd4b18 100644
--- a/tests/manual/qtabletevent/regular_widgets/main.cpp
+++ b/tests/manual/qtabletevent/regular_widgets/main.cpp
@@ -39,6 +39,7 @@
#include <QMenuBar>
#include <QMenu>
#include <QAction>
+#include <QStatusBar>
#include <QVector>
#include <QPainter>
#include <QCursor>
@@ -72,6 +73,9 @@ public:
public slots:
void clearPoints() { m_points.clear(); update(); }
+signals:
+ void stats(QString s);
+
protected:
void mouseDoubleClickEvent(QMouseEvent *event) { outputMouseEvent(event); }
void mouseMoveEvent(QMouseEvent *event) { outputMouseEvent(event); }
@@ -81,6 +85,7 @@ protected:
void tabletEvent(QTabletEvent *);
void paintEvent(QPaintEvent *);
+ void timerEvent(QTimerEvent *);
private:
void outputMouseEvent(QMouseEvent *event);
@@ -89,28 +94,36 @@ private:
bool m_lastIsTabletMove;
Qt::MouseButton m_lastButton;
QVector<TabletPoint> m_points;
+ int m_tabletMoveCount;
+ int m_paintEventCount;
};
EventReportWidget::EventReportWidget()
: m_lastIsMouseMove(false)
, m_lastIsTabletMove(false)
, m_lastButton(Qt::NoButton)
-{ }
+ , m_tabletMoveCount(0)
+ , m_paintEventCount(0)
+{
+ startTimer(1000);
+}
void EventReportWidget::paintEvent(QPaintEvent *)
{
QPainter p(this);
+ int lineSpacing = fontMetrics().lineSpacing();
+ int halfLineSpacing = lineSpacing / 2;
const QRectF geom = QRectF(QPoint(0, 0), size());
p.fillRect(geom, Qt::white);
p.drawRect(QRectF(geom.topLeft(), geom.bottomRight() - QPointF(1,1)));
p.setPen(Qt::white);
QPainterPath ellipse;
- ellipse.addEllipse(0, 0, 50, 10);
+ ellipse.addEllipse(0, 0, halfLineSpacing * 5, halfLineSpacing);
foreach (const TabletPoint &t, m_points) {
if (geom.contains(t.pos)) {
QPainterPath pp;
- pp.addEllipse(t.pos, 8, 8);
- QRectF pointBounds(t.pos.x() - 10, t.pos.y() - 10, 20, 20);
+ pp.addEllipse(t.pos, halfLineSpacing, halfLineSpacing);
+ QRectF pointBounds(t.pos.x() - halfLineSpacing, t.pos.y() - halfLineSpacing, lineSpacing, lineSpacing);
switch (t.type) {
case TabletButtonPress:
p.fillPath(pp, Qt::darkGreen);
@@ -133,7 +146,7 @@ void EventReportWidget::paintEvent(QPaintEvent *)
p.drawPath(ellipse);
p.restore();
} else {
- p.drawEllipse(t.pos, t.pressure * 10.0, t.pressure * 10.0);
+ p.drawEllipse(t.pos, t.pressure * halfLineSpacing, t.pressure * halfLineSpacing);
}
p.setPen(Qt::white);
} else {
@@ -143,6 +156,7 @@ void EventReportWidget::paintEvent(QPaintEvent *)
}
}
}
+ ++m_paintEventCount;
}
void EventReportWidget::tabletEvent(QTabletEvent *event)
@@ -152,11 +166,13 @@ void EventReportWidget::tabletEvent(QTabletEvent *event)
switch (event->type()) {
case QEvent::TabletEnterProximity:
case QEvent::TabletLeaveProximity:
+ qDebug() << "proximity" << event;
break;
case QEvent::TabletMove:
m_points.push_back(TabletPoint(event->pos(), TabletMove, m_lastButton, event->pointerType(), event->pressure(), event->rotation()));
update();
isMove = true;
+ ++m_tabletMoveCount;
break;
case QEvent::TabletPress:
m_points.push_back(TabletPoint(event->pos(), TabletButtonPress, event->button(), event->pointerType(), event->rotation()));
@@ -192,6 +208,13 @@ void EventReportWidget::outputMouseEvent(QMouseEvent *event)
qDebug() << event;
}
+void EventReportWidget::timerEvent(QTimerEvent *)
+{
+ emit stats(QString("%1 moves/sec, %2 frames/sec").arg(m_tabletMoveCount).arg(m_paintEventCount));
+ m_tabletMoveCount = 0;
+ m_paintEventCount = 0;
+}
+
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
@@ -201,6 +224,7 @@ int main(int argc, char *argv[])
widget->setMinimumSize(640, 480);
QMenu *fileMenu = mainWindow.menuBar()->addMenu("File");
QObject::connect(fileMenu->addAction("Clear"), SIGNAL(triggered()), widget, SLOT(clearPoints()));
+ QObject::connect(widget, SIGNAL(stats(QString)), mainWindow.statusBar(), SLOT(showMessage(QString)));
QAction *quitAction = fileMenu->addAction("Quit");
QObject::connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
quitAction->setShortcut(Qt::CTRL + Qt::Key_Q);
diff --git a/tests/manual/touch/main.cpp b/tests/manual/touch/main.cpp
index e1114d7f57..b7029767c9 100644
--- a/tests/manual/touch/main.cpp
+++ b/tests/manual/touch/main.cpp
@@ -32,21 +32,187 @@
****************************************************************************/
#include <QApplication>
+#include <QGesture>
#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QMainWindow>
#include <QSplitter>
+#include <QToolBar>
#include <QVector>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QPlainTextEdit>
+#include <QPainter>
+#include <QPainterPath>
#include <QPaintEvent>
#include <QScreen>
+#include <QSharedPointer>
#include <QDebug>
#include <QTextStream>
+bool optIgnoreTouch = false;
+QVector<Qt::GestureType> optGestures;
+
+static inline void drawCircle(const QPointF &center, qreal radius, const QColor &color, QPainter &painter)
+{
+ const QPen oldPen = painter.pen();
+ QPen pen = oldPen;
+ pen.setColor(color);
+ painter.setPen(pen);
+ painter.drawEllipse(center, radius, radius);
+ painter.setPen(oldPen);
+}
+
+static inline void fillCircle(const QPointF &center, qreal radius, const QColor &color, QPainter &painter)
+{
+ QPainterPath painterPath;
+ painterPath.addEllipse(center, radius, radius);
+ painter.fillPath(painterPath, color);
+}
+
+// Draws an arrow assuming a mathematical coordinate system, Y axis pointing
+// upwards, angle counterclockwise (that is, 45' is pointing up/right).
+static void drawArrow(const QPointF &center, qreal length, qreal angleDegrees,
+ const QColor &color, int arrowSize, QPainter &painter)
+{
+ painter.save();
+ painter.translate(center); // Transform center to (0,0) rotate and draw arrow pointing right.
+ painter.rotate(-angleDegrees);
+ QPen pen = painter.pen();
+ pen.setColor(color);
+ pen.setWidth(2);
+ painter.setPen(pen);
+ const QPointF endPoint(length, 0);
+ painter.drawLine(QPointF(0, 0), endPoint);
+ painter.drawLine(endPoint, endPoint + QPoint(-arrowSize, -arrowSize));
+ painter.drawLine(endPoint, endPoint + QPoint(-arrowSize, arrowSize));
+ painter.restore();
+}
+
+QDebug operator<<(QDebug debug, const QTouchDevice *d)
+{
+ QDebugStateSaver saver(debug);
+ debug.nospace();
+ debug << "QTouchDevice(" << d->name() << ',';
+ switch (d->type()) {
+ case QTouchDevice::TouchScreen:
+ debug << "TouchScreen";
+ break;
+ case QTouchDevice::TouchPad:
+ debug << "TouchPad";
+ break;
+ }
+ debug << ", capabilities=" << d->capabilities()
+ << ", maximumTouchPoints=" << d->maximumTouchPoints() << ')';
+ return debug;
+}
+
+// Hierarchy of classes containing gesture parameters and drawing functionality.
+class Gesture {
+ Q_DISABLE_COPY(Gesture)
+public:
+ static Gesture *fromQGesture(const QWidget *w, const QGesture *source);
+ virtual ~Gesture() {}
+
+ virtual void draw(const QRectF &rect, QPainter &painter) const = 0;
+
+protected:
+ explicit Gesture(const QWidget *w, const QGesture *source) : m_type(source->gestureType())
+ , m_hotSpot(w->mapFromGlobal(source->hotSpot().toPoint()))
+ , m_hasHotSpot(source->hasHotSpot()) {}
+
+ QPointF drawHotSpot(const QRectF &rect, QPainter &painter) const
+ {
+ const QPointF h = m_hasHotSpot ? m_hotSpot : rect.center();
+ painter.drawEllipse(h, 15, 15);
+ return h;
+ }
+
+private:
+ Qt::GestureType m_type;
+ QPointF m_hotSpot;
+ bool m_hasHotSpot;
+};
+
+class PanGesture : public Gesture {
+public:
+ explicit PanGesture(const QWidget *w, const QPanGesture *source) : Gesture(w, source)
+ , m_offset(source->offset()) {}
+
+ void draw(const QRectF &rect, QPainter &painter) const Q_DECL_OVERRIDE
+ {
+ const QPointF hotSpot = drawHotSpot(rect, painter);
+ painter.drawLine(hotSpot, hotSpot + m_offset);
+ }
+
+private:
+ QPointF m_offset;
+};
+
+class SwipeGesture : public Gesture {
+public:
+ explicit SwipeGesture(const QWidget *w, const QSwipeGesture *source) : Gesture(w, source)
+ , m_horizontal(source->horizontalDirection()), m_vertical(source->verticalDirection())
+ , m_angle(source->swipeAngle()) {}
+
+ void draw(const QRectF &rect, QPainter &painter) const Q_DECL_OVERRIDE;
+
+private:
+ QSwipeGesture::SwipeDirection m_horizontal;
+ QSwipeGesture::SwipeDirection m_vertical;
+ qreal m_angle;
+};
+
+static qreal swipeDirectionAngle(QSwipeGesture::SwipeDirection d)
+{
+ switch (d) {
+ case QSwipeGesture::NoDirection:
+ case QSwipeGesture::Right:
+ break;
+ case QSwipeGesture::Left:
+ return 180;
+ case QSwipeGesture::Up:
+ return 90;
+ case QSwipeGesture::Down:
+ return 270;
+ }
+ return 0;
+}
+
+void SwipeGesture::draw(const QRectF &rect, QPainter &painter) const
+{
+ enum { arrowLength = 50, arrowHeadSize = 10 };
+ const QPointF hotSpot = drawHotSpot(rect, painter);
+ drawArrow(hotSpot, arrowLength, swipeDirectionAngle(m_horizontal), Qt::red, arrowHeadSize, painter);
+ drawArrow(hotSpot, arrowLength, swipeDirectionAngle(m_vertical), Qt::green, arrowHeadSize, painter);
+ drawArrow(hotSpot, arrowLength, m_angle, Qt::blue, arrowHeadSize, painter);
+}
+
+Gesture *Gesture::fromQGesture(const QWidget *w, const QGesture *source)
+{
+ Gesture *result = Q_NULLPTR;
+ switch (source->gestureType()) {
+ case Qt::TapGesture:
+ case Qt::TapAndHoldGesture:
+ case Qt::PanGesture:
+ result = new PanGesture(w, static_cast<const QPanGesture *>(source));
+ break;
+ case Qt::PinchGesture:
+ case Qt::CustomGesture:
+ case Qt::LastGestureType:
+ break;
+ case Qt::SwipeGesture:
+ result = new SwipeGesture(w, static_cast<const QSwipeGesture *>(source));
+ break;
+ }
+ return result;
+}
+
+typedef QSharedPointer<Gesture> GesturePtr;
+typedef QVector<GesturePtr> GesturePtrs;
+
typedef QVector<QEvent::Type> EventTypeVector;
class EventFilter : public QObject {
@@ -68,33 +234,189 @@ bool EventFilter::eventFilter(QObject *o, QEvent *e)
static int n = 0;
if (m_types.contains(e->type())) {
QString message;
- QDebug(&message) << '#' << n++ << ' ' << o->objectName() << ' ' << e;
+ QDebug debug(&message);
+ debug << '#' << n++ << ' ' << o->objectName() << ' ';
+ switch (e->type()) {
+ case QEvent::Gesture:
+ case QEvent::GestureOverride:
+ debug << static_cast<const QGestureEvent *>(e); // Special operator
+ break;
+ default:
+ debug << e;
+ break;
+ }
emit eventReceived(message);
}
return false;
}
+enum PointType {
+ TouchPoint,
+ MousePress,
+ MouseRelease
+};
+
+struct Point
+{
+ Point(const QPointF &p = QPoint(), PointType t = TouchPoint,
+ Qt::MouseEventSource s = Qt::MouseEventNotSynthesized) : pos(p), type(t), source(s) {}
+
+ QColor color() const;
+
+ QPointF pos;
+ PointType type;
+ Qt::MouseEventSource source;
+};
+
+QColor Point::color() const
+{
+ Qt::GlobalColor globalColor = Qt::black;
+ if (type != TouchPoint) {
+ switch (source) {
+ case Qt::MouseEventSynthesizedBySystem:
+ globalColor = Qt::red;
+ break;
+ case Qt::MouseEventSynthesizedByQt:
+ globalColor = Qt::blue;
+ break;
+ case Qt::MouseEventNotSynthesized:
+ break;
+ }
+ }
+ const QColor result(globalColor);
+ return type == MousePress ? result.lighter() : result;
+}
+
class TouchTestWidget : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool drawPoints READ drawPoints WRITE setDrawPoints)
public:
- explicit TouchTestWidget(QWidget *parent = 0) : QWidget(parent)
+ explicit TouchTestWidget(QWidget *parent = 0) : QWidget(parent), m_drawPoints(true)
{
setAttribute(Qt::WA_AcceptTouchEvents);
+ foreach (Qt::GestureType t, optGestures)
+ grabGesture(t);
}
- bool event(QEvent *event) Q_DECL_OVERRIDE
- {
- switch (event->type()) {
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
+ bool drawPoints() const { return m_drawPoints; }
+
+public slots:
+ void clearPoints();
+ void setDrawPoints(bool drawPoints);
+
+signals:
+ void logMessage(const QString &);
+
+protected:
+ bool event(QEvent *event) Q_DECL_OVERRIDE;
+ void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
+
+private:
+ void handleGestureEvent(QGestureEvent *gestureEvent);
+
+ QVector<Point> m_points;
+ GesturePtrs m_gestures;
+ bool m_drawPoints;
+};
+
+void TouchTestWidget::clearPoints()
+{
+ if (!m_points.isEmpty() || !m_gestures.isEmpty()) {
+ m_points.clear();
+ m_gestures.clear();
+ update();
+ }
+}
+
+void TouchTestWidget::setDrawPoints(bool drawPoints)
+{
+ if (m_drawPoints != drawPoints) {
+ clearPoints();
+ m_drawPoints = drawPoints;
+ }
+}
+
+bool TouchTestWidget::event(QEvent *event)
+{
+ const QEvent::Type type = event->type();
+ switch (type) {
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ if (m_drawPoints) {
+ const QMouseEvent *me = static_cast<const QMouseEvent *>(event);
+ m_points.append(Point(me->localPos(),
+ type == QEvent::MouseButtonPress ? MousePress : MouseRelease,
+ me->source()));
+ update();
+ }
+ break;
+ case QEvent::TouchBegin:
+ case QEvent::TouchUpdate:
+ if (m_drawPoints) {
+ foreach (const QTouchEvent::TouchPoint &p, static_cast<const QTouchEvent *>(event)->touchPoints())
+ m_points.append(Point(p.pos(), TouchPoint));
+ update();
+ }
+ case QEvent::TouchEnd:
+ if (optIgnoreTouch)
+ event->ignore();
+ else
event->accept();
- return true;
- default:
- break;
+ return true;
+ case QEvent::Gesture:
+ handleGestureEvent(static_cast<QGestureEvent *>(event));
+ break;
+ default:
+ break;
+ }
+ return QWidget::event(event);
+}
+
+void TouchTestWidget::handleGestureEvent(QGestureEvent *gestureEvent)
+{
+ foreach (QGesture *gesture, gestureEvent->gestures()) {
+ if (optGestures.contains(gesture->gestureType())) {
+ switch (gesture->state()) {
+ case Qt::NoGesture:
+ break;
+ case Qt::GestureStarted:
+ case Qt::GestureUpdated:
+ gestureEvent->accept(gesture);
+ break;
+ case Qt::GestureFinished:
+ gestureEvent->accept(gesture);
+ if (Gesture *g = Gesture::fromQGesture(this, gesture)) {
+ m_gestures.append(GesturePtr(g));
+ update();
+ }
+ break;
+ case Qt::GestureCanceled:
+ emit logMessage(QLatin1String("=== Qt::GestureCanceled ==="));
+ break;
+ }
}
- return QWidget::event(event);
}
-};
+}
+
+void TouchTestWidget::paintEvent(QPaintEvent *)
+{
+ // Draw touch points as dots, mouse press as light filled circles, mouse release as circles.
+ QPainter painter(this);
+ const QRectF geom = QRectF(QPointF(0, 0), QSizeF(size()));
+ painter.fillRect(geom, Qt::white);
+ painter.drawRect(QRectF(geom.topLeft(), geom.bottomRight() - QPointF(1, 1)));
+ foreach (const Point &point, m_points) {
+ if (geom.contains(point.pos)) {
+ const qreal radius = point.type == TouchPoint ? 1 : 4;
+ if (point.type == MouseRelease) {
+ drawCircle(point.pos, radius, point.color(), painter);
+ } else
+ fillCircle(point.pos, radius, point.color(), painter);
+ }
+ }
+ foreach (const GesturePtr &gp, m_gestures)
+ gp->draw(geom, painter);
+}
class MainWindow : public QMainWindow
{
@@ -108,7 +430,7 @@ public slots:
void dumpTouchDevices();
private:
- QWidget *m_touchWidget;
+ TouchTestWidget *m_touchWidget;
QPlainTextEdit *m_logTextEdit;
};
@@ -119,23 +441,38 @@ MainWindow::MainWindow()
setWindowTitle(QStringLiteral("Touch Event Tester ") + QT_VERSION_STR);
setObjectName("MainWin");
+ QToolBar *toolBar = new QToolBar(this);
+ addToolBar(Qt::TopToolBarArea, toolBar);
QMenu *fileMenu = menuBar()->addMenu("File");
- QAction *da = fileMenu->addAction(QStringLiteral("Dump devices"));
- da->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
- connect(da, SIGNAL(triggered()), this, SLOT(dumpTouchDevices()));
- QAction *qa = fileMenu->addAction(QStringLiteral("Quit"));
- qa->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
- connect(qa, SIGNAL(triggered()), this, SLOT(close()));
+ QAction *dumpDeviceAction = fileMenu->addAction(QStringLiteral("Dump devices"));
+ dumpDeviceAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
+ connect(dumpDeviceAction, SIGNAL(triggered()), this, SLOT(dumpTouchDevices()));
+ toolBar->addAction(dumpDeviceAction);
+ QAction *clearLogAction = fileMenu->addAction(QStringLiteral("Clear Log"));
+ clearLogAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
+ connect(clearLogAction, SIGNAL(triggered()), m_logTextEdit, SLOT(clear()));
+ toolBar->addAction(clearLogAction);
+ QAction *toggleDrawPointAction = fileMenu->addAction(QStringLiteral("Draw Points"));
+ toggleDrawPointAction->setCheckable(true);
+ toggleDrawPointAction->setChecked(m_touchWidget->drawPoints());
+ connect(toggleDrawPointAction, SIGNAL(toggled(bool)), m_touchWidget, SLOT(setDrawPoints(bool)));
+ toolBar->addAction(toggleDrawPointAction);
+ QAction *clearPointAction = fileMenu->addAction(QStringLiteral("Clear Points"));
+ clearPointAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P));
+ connect(clearPointAction, SIGNAL(triggered()), m_touchWidget, SLOT(clearPoints()));
+ toolBar->addAction(clearPointAction);
+ QAction *quitAction = fileMenu->addAction(QStringLiteral("Quit"));
+ quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
+ connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
+ toolBar->addAction(quitAction);
- QSplitter *mainSplitter = new QSplitter(Qt::Vertical);
+ QSplitter *mainSplitter = new QSplitter(Qt::Vertical, this);
m_touchWidget->setObjectName(QStringLiteral("TouchWidget"));
- const QSize screenSize = QGuiApplication::primaryScreen()->availableGeometry().size();
- m_touchWidget->setMinimumSize(screenSize / 2);
mainSplitter->addWidget(m_touchWidget);
+ connect(m_touchWidget, &TouchTestWidget::logMessage, this, &MainWindow::appendToLog);
m_logTextEdit->setObjectName(QStringLiteral("LogTextEdit"));
- m_logTextEdit->setMinimumHeight(screenSize.height() / 4);
mainSplitter->addWidget(m_logTextEdit);
setCentralWidget(mainSplitter);
@@ -165,19 +502,57 @@ int main(int argc, char *argv[])
const QCommandLineOption globalFilterOption(QStringLiteral("global"),
QStringLiteral("Global event filter"));
parser.addOption(globalFilterOption);
+
+ const QCommandLineOption ignoreTouchOption(QStringLiteral("ignore"),
+ QStringLiteral("Ignore touch events (for testing mouse emulation)."));
+ parser.addOption(ignoreTouchOption);
+ const QCommandLineOption noTouchLogOption(QStringLiteral("notouchlog"),
+ QStringLiteral("Do not log touch events (for testing gestures)."));
+ parser.addOption(noTouchLogOption);
+ const QCommandLineOption noMouseLogOption(QStringLiteral("nomouselog"),
+ QStringLiteral("Do not log mouse events (for testing gestures)."));
+ parser.addOption(noMouseLogOption);
+
+ const QCommandLineOption tapGestureOption(QStringLiteral("tap"), QStringLiteral("Grab tap gesture."));
+ parser.addOption(tapGestureOption);
+ const QCommandLineOption tapAndHoldGestureOption(QStringLiteral("tap-and-hold"),
+ QStringLiteral("Grab tap-and-hold gesture."));
+ parser.addOption(tapAndHoldGestureOption);
+ const QCommandLineOption panGestureOption(QStringLiteral("pan"), QStringLiteral("Grab pan gesture."));
+ parser.addOption(panGestureOption);
+ const QCommandLineOption pinchGestureOption(QStringLiteral("pinch"), QStringLiteral("Grab pinch gesture."));
+ parser.addOption(pinchGestureOption);
+ const QCommandLineOption swipeGestureOption(QStringLiteral("swipe"), QStringLiteral("Grab swipe gesture."));
+ parser.addOption(swipeGestureOption);
parser.process(QApplication::arguments());
+ optIgnoreTouch = parser.isSet(ignoreTouchOption);
+ if (parser.isSet(tapGestureOption))
+ optGestures.append(Qt::TapGesture);
+ if (parser.isSet(tapAndHoldGestureOption))
+ optGestures.append(Qt::TapAndHoldGesture);
+ if (parser.isSet(panGestureOption))
+ optGestures.append(Qt::PanGesture);
+ if (parser.isSet(pinchGestureOption))
+ optGestures.append(Qt::PinchGesture);
+ if (parser.isSet(swipeGestureOption))
+ optGestures.append(Qt::SwipeGesture);
MainWindow w;
+ const QSize screenSize = QGuiApplication::primaryScreen()->availableGeometry().size();
+ w.resize(screenSize / 2);
+ const QSize sizeDiff = screenSize - w.size();
+ w.move(sizeDiff.width() / 2, sizeDiff.height() / 2);
w.show();
- const QSize pos = QGuiApplication::primaryScreen()->availableGeometry().size() - w.size();
- w.move(pos.width() / 2, pos.height() / 2);
EventTypeVector eventTypes;
- eventTypes << QEvent::MouseButtonPress << QEvent::MouseButtonRelease
- << QEvent::MouseButtonDblClick
- << QEvent::TouchBegin << QEvent::TouchUpdate << QEvent::TouchEnd;
+ if (!parser.isSet(noMouseLogOption))
+ eventTypes << QEvent::MouseButtonPress << QEvent::MouseButtonRelease << QEvent::MouseButtonDblClick;
if (parser.isSet(mouseMoveOption))
eventTypes << QEvent::MouseMove;
+ if (!parser.isSet(noTouchLogOption))
+ eventTypes << QEvent::TouchBegin << QEvent::TouchUpdate << QEvent::TouchEnd;
+ if (!optGestures.isEmpty())
+ eventTypes << QEvent::Gesture << QEvent::GestureOverride;
QObject *filterTarget = parser.isSet(globalFilterOption)
? static_cast<QObject *>(&a)
: static_cast<QObject *>(w.touchWidget());
diff --git a/tools/configure/Makefile.mingw b/tools/configure/Makefile.mingw
index 9ac99fd678..539664e7d6 100644
--- a/tools/configure/Makefile.mingw
+++ b/tools/configure/Makefile.mingw
@@ -48,6 +48,7 @@ OBJECTS = \
qfsfileengine_win.o \
qfsfileengine_iterator.o \
qiodevice.o \
+ qringbuffer.o \
qdebug.o \
qtextstream.o \
qlogging.o \
diff --git a/tools/configure/Makefile.win32 b/tools/configure/Makefile.win32
index 8c6d213e42..da5b430bb1 100644
--- a/tools/configure/Makefile.win32
+++ b/tools/configure/Makefile.win32
@@ -47,6 +47,7 @@ OBJECTS = \
qfsfileengine_win.obj \
qfsfileengine_iterator.obj \
qiodevice.obj \
+ qringbuffer.obj \
qdebug.obj \
qtextstream.obj \
qlogging.obj \
@@ -122,6 +123,7 @@ qfsfileengine.obj: $(CORESRC)\io\qfsfileengine.cpp $(PCH)
qfsfileengine_win.obj: $(CORESRC)\io\qfsfileengine_win.cpp $(PCH)
qfsfileengine_iterator.obj: $(CORESRC)\io\qfsfileengine_iterator.cpp $(PCH)
qiodevice.obj: $(CORESRC)\io\qiodevice.cpp $(PCH)
+qringbuffer.obj: $(CORESRC)\tools\qringbuffer.cpp $(PCH)
qdebug.obj: $(CORESRC)\io\qdebug.cpp $(PCH)
qtextstream.obj: $(CORESRC)\io\qtextstream.cpp $(PCH)
qtemporaryfile.obj: $(CORESRC)\io\qtemporaryfile.cpp $(PCH)
diff --git a/tools/configure/configure.pro b/tools/configure/configure.pro
index e4901bacde..939c9ea5ab 100644
--- a/tools/configure/configure.pro
+++ b/tools/configure/configure.pro
@@ -68,6 +68,7 @@ HEADERS = configureapp.h environment.h tools.h\
$$QT_SOURCE_TREE/src/corelib/tools/qdatetime.h \
$$QT_SOURCE_TREE/src/corelib/tools/qmap.h \
$$QT_SOURCE_TREE/src/corelib/tools/qregexp.h \
+ $$QT_SOURCE_TREE/src/corelib/tools/qringbuffer_p.h \
$$QT_SOURCE_TREE/src/corelib/tools/qstring.h \
$$QT_SOURCE_TREE/src/corelib/tools/qstringlist.h \
$$QT_SOURCE_TREE/src/corelib/tools/qstringmatcher.h \
@@ -119,6 +120,7 @@ SOURCES = main.cpp configureapp.cpp environment.cpp tools.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qdatetime.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qmap.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qregexp.cpp \
+ $$QT_SOURCE_TREE/src/corelib/tools/qringbuffer.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qstring.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qstring_compat.cpp \
$$QT_SOURCE_TREE/src/corelib/tools/qstringlist.cpp \
diff --git a/tools/configure/configureapp.cpp b/tools/configure/configureapp.cpp
index 3bf0546ac1..6a7a217446 100644
--- a/tools/configure/configureapp.cpp
+++ b/tools/configure/configureapp.cpp
@@ -169,7 +169,7 @@ Configure::Configure(int& argc, char** argv)
dictionary[ "WMSDK" ] = "auto";
dictionary[ "QML_DEBUG" ] = "yes";
dictionary[ "PLUGIN_MANIFESTS" ] = "no";
- dictionary[ "DIRECTWRITE" ] = "no";
+ dictionary[ "DIRECTWRITE" ] = "auto";
dictionary[ "DIRECT2D" ] = "no";
dictionary[ "NIS" ] = "no";
dictionary[ "NEON" ] = "auto";
@@ -2010,8 +2010,8 @@ bool Configure::displayHelp()
desc("WMF_BACKEND", "yes","-wmf-backend", "Compile in the windows media foundation backend into Qt Multimedia.\n");
desc("QML_DEBUG", "no", "-no-qml-debug", "Do not build the in-process QML debugging support.");
desc("QML_DEBUG", "yes", "-qml-debug", "Build the in-process QML debugging support.\n");
- desc("DIRECTWRITE", "no", "-no-directwrite", "Do not build support for DirectWrite font rendering.");
- desc("DIRECTWRITE", "yes", "-directwrite", "Build support for DirectWrite font rendering (requires DirectWrite availability on target systems, e.g. Windows Vista with Platform Update, Windows 7, etc.)\n");
+ desc("DIRECTWRITE", "no", "-no-directwrite", "Do not build support for DirectWrite font rendering.");
+ desc("DIRECTWRITE", "yes", "-directwrite", "Build support for DirectWrite font rendering.\n");
desc("DIRECT2D", "no", "-no-direct2d", "Do not build the Direct2D platform plugin.");
desc("DIRECT2D", "yes", "-direct2d", "Build the Direct2D platform plugin (experimental,\n"
@@ -2291,7 +2291,7 @@ bool Configure::checkAvailability(const QString &part)
} else if (part == "WMF_BACKEND") {
available = findFile("mfapi.h") && findFile("mf.lib");
} else if (part == "DIRECTWRITE") {
- available = findFile("dwrite.h") && findFile("d2d1.h") && findFile("dwrite.lib");
+ available = tryCompileProject("win/directwrite");
} else if (part == "DIRECT2D") {
available = tryCompileProject("qpa/direct2d");
} else if (part == "ICONV") {
@@ -2343,6 +2343,22 @@ void Configure::autoDetection()
dictionary["C++11"] = tryCompileProject("common/c++11") ? "yes" : "no";
}
+ if (!dictionary["QMAKESPEC"].contains("msvc")) {
+ if (tryCompileProject("common/c++default", QString(), false)) {
+ QFile iiFile(buildPath + "/config.tests/common/c++default/c++default.ii");
+ if (iiFile.open(QIODevice::ReadOnly)) {
+ QString content = QString::fromUtf8(iiFile.readAll());
+ QRegExp expr("\\b([0-9]+)L\\b");
+ if (expr.indexIn(content) != -1)
+ dictionary["CFG_STDCXX_DEFAULT"] = expr.cap(1);
+ }
+ }
+ if (dictionary["CFG_STDCXX_DEFAULT"].isEmpty()) {
+ cout << "Could not determine the C++ standard the compiler uses by default, assuming C++98." << endl;
+ dictionary["CFG_STDCXX_DEFAULT"] = "199711";
+ }
+ }
+
// Style detection
if (dictionary["STYLE_WINDOWSXP"] == "auto")
dictionary["STYLE_WINDOWSXP"] = checkAvailability("STYLE_WINDOWSXP") ? defaultTo("STYLE_WINDOWSXP") : "no";
@@ -2510,6 +2526,9 @@ void Configure::autoDetection()
if (dictionary["FONT_CONFIG"] == "auto")
dictionary["FONT_CONFIG"] = checkAvailability("FONT_CONFIG") ? "yes" : "no";
+ if (dictionary["DIRECTWRITE"] == "auto")
+ dictionary["DIRECTWRITE"] = checkAvailability("DIRECTWRITE") ? "yes" : "no";
+
// Mark all unknown "auto" to the default value..
for (QMap<QString,QString>::iterator i = dictionary.begin(); i != dictionary.end(); ++i) {
if (i.value() == "auto")
@@ -2678,6 +2697,8 @@ void Configure::generateOutputVars()
if (dictionary[ "C++11" ] == "yes")
qtConfig += "c++11";
+ if (!dictionary[ "CFG_STDCXX_DEFAULT" ].isEmpty())
+ qmakeVars += "QT_COMPILER_STDCXX = " + dictionary[ "CFG_STDCXX_DEFAULT" ];
if (dictionary[ "USE_GOLD_LINKER" ] == "yes")
qmakeConfig += "use_gold_linker";
@@ -2907,6 +2928,9 @@ void Configure::generateOutputVars()
if (dictionary["AUDIO_BACKEND"] == "yes")
qtConfig += "audio-backend";
+ if (dictionary["QML_DEBUG"] == "no")
+ qtConfig += "no-qml-debug";
+
if (dictionary["WMF_BACKEND"] == "yes")
qtConfig += "wmf-backend";
@@ -3283,7 +3307,8 @@ void Configure::detectArch()
QDir::setCurrent(oldpwd);
}
-bool Configure::tryCompileProject(const QString &projectPath, const QString &extraOptions)
+bool Configure::tryCompileProject(const QString &projectPath, const QString &extraOptions,
+ bool distClean)
{
QString oldpwd = QDir::currentPath();
@@ -3326,7 +3351,8 @@ bool Configure::tryCompileProject(const QString &projectPath, const QString &ext
//cout << output << endl;
// clean up
- Environment::execute(command + " distclean 2>&1");
+ if (distClean)
+ Environment::execute(command + " distclean 2>&1");
}
QDir::setCurrent(oldpwd);
@@ -3621,7 +3647,6 @@ void Configure::generateConfigfiles()
if (dictionary["OPENSSL"] == "no") qconfigList += "QT_NO_OPENSSL";
if (dictionary["OPENSSL"] == "linked") qconfigList += "QT_LINKED_OPENSSL";
if (dictionary["DBUS"] == "no") qconfigList += "QT_NO_DBUS";
- if (dictionary["QML_DEBUG"] == "no") qconfigList += "QT_NO_QML_DEBUGGER";
if (dictionary["FREETYPE"] == "no") qconfigList += "QT_NO_FREETYPE";
if (dictionary["HARFBUZZ"] == "no") qconfigList += "QT_NO_HARFBUZZ";
if (dictionary["NATIVE_GESTURES"] == "no") qconfigList += "QT_NO_NATIVE_GESTURES";
diff --git a/tools/configure/configureapp.h b/tools/configure/configureapp.h
index e58a0feb2b..de8d1a2469 100644
--- a/tools/configure/configureapp.h
+++ b/tools/configure/configureapp.h
@@ -158,7 +158,8 @@ private:
void saveCmdLine();
void addSysroot(QString *command);
- bool tryCompileProject(const QString &projectPath, const QString &extraOptions = QString());
+ bool tryCompileProject(const QString &projectPath, const QString &extraOptions = QString(),
+ bool distClean = true);
bool compilerSupportsFlag(const QString &compilerAndArgs);
void desc(const char *description, int startingAt = 0, int wrapIndent = 0);