summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.qmake.conf2
-rw-r--r--config_help.txt3
-rwxr-xr-xconfigure1
-rw-r--r--configure.json1
-rw-r--r--configure.pri3
-rw-r--r--dependencies.yaml1
-rw-r--r--doc/src/portingguide-5-to-6.qdoc54
-rw-r--r--examples/opengl/2dpainting/2dpainting.pro2
-rw-r--r--examples/opengl/cube/cube.pro2
-rw-r--r--examples/opengl/hellogl2/hellogl2.pro2
-rw-r--r--examples/opengl/qopenglwidget/qopenglwidget.pro2
-rw-r--r--examples/opengl/textures/textures.pro2
-rw-r--r--examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro2
-rw-r--r--examples/widgets/animation/sub-attaq/mainwindow.cpp13
-rw-r--r--examples/widgets/animation/sub-attaq/sub-attaq.pro1
-rw-r--r--examples/widgets/graphicsview/boxes/3rdparty/fbm.c207
-rw-r--r--examples/widgets/graphicsview/boxes/3rdparty/fbm.h40
-rw-r--r--examples/widgets/graphicsview/boxes/basic.fsh82
-rw-r--r--examples/widgets/graphicsview/boxes/basic.vsh70
-rw-r--r--examples/widgets/graphicsview/boxes/boxes.pro27
-rw-r--r--examples/widgets/graphicsview/boxes/boxes.qrc25
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negx.jpgbin41060 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negy.jpgbin15520 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negz.jpgbin68911 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posx.jpgbin74915 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posy.jpgbin24193 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posz.jpgbin57881 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/dotted.fsh75
-rw-r--r--examples/widgets/graphicsview/boxes/fresnel.fsh88
-rw-r--r--examples/widgets/graphicsview/boxes/glass.fsh85
-rw-r--r--examples/widgets/graphicsview/boxes/glbuffers.cpp406
-rw-r--r--examples/widgets/graphicsview/boxes/glbuffers.h372
-rw-r--r--examples/widgets/graphicsview/boxes/glextensions.cpp107
-rw-r--r--examples/widgets/graphicsview/boxes/glextensions.h204
-rw-r--r--examples/widgets/graphicsview/boxes/gltrianglemesh.h99
-rw-r--r--examples/widgets/graphicsview/boxes/granite.fsh85
-rw-r--r--examples/widgets/graphicsview/boxes/main.cpp157
-rw-r--r--examples/widgets/graphicsview/boxes/marble.fsh80
-rw-r--r--examples/widgets/graphicsview/boxes/parameters.par5
-rw-r--r--examples/widgets/graphicsview/boxes/qt-logo.jpgbin20316 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/qt-logo.pngbin12167 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/qtbox.cpp470
-rw-r--r--examples/widgets/graphicsview/boxes/qtbox.h126
-rw-r--r--examples/widgets/graphicsview/boxes/reflection.fsh63
-rw-r--r--examples/widgets/graphicsview/boxes/refraction.fsh79
-rw-r--r--examples/widgets/graphicsview/boxes/roundedbox.cpp170
-rw-r--r--examples/widgets/graphicsview/boxes/roundedbox.h77
-rw-r--r--examples/widgets/graphicsview/boxes/scene.cpp1028
-rw-r--r--examples/widgets/graphicsview/boxes/scene.h247
-rw-r--r--examples/widgets/graphicsview/boxes/smiley.pngbin14508 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/square.jpgbin14542 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/trackball.cpp159
-rw-r--r--examples/widgets/graphicsview/boxes/trackball.h87
-rw-r--r--examples/widgets/graphicsview/boxes/wood.fsh79
-rw-r--r--examples/widgets/graphicsview/chip/chip.pro1
-rw-r--r--examples/widgets/graphicsview/chip/view.cpp21
-rw-r--r--examples/widgets/graphicsview/chip/view.h2
-rw-r--r--examples/widgets/graphicsview/graphicsview.pro4
-rw-r--r--mkspecs/features/java.prf2
-rw-r--r--qmake/Makefile.unix6
-rw-r--r--qmake/Makefile.win321
-rw-r--r--qmake/generators/makefiledeps.cpp11
-rw-r--r--qmake/generators/makefiledeps.h8
-rw-r--r--qmake/property.cpp1
-rw-r--r--src/corelib/configure.json6
-rw-r--r--src/corelib/doc/snippets/code/src_corelib_tools_qbytearray.cpp8
-rw-r--r--src/corelib/doc/snippets/qstring/main.cpp8
-rw-r--r--src/corelib/doc/src/containers.qdoc134
-rw-r--r--src/corelib/doc/src/datastreamformat.qdoc1
-rw-r--r--src/corelib/doc/src/dontdocument.qdoc2
-rw-r--r--src/corelib/global/qcompilerdetection.h22
-rw-r--r--src/corelib/global/qconfig-bootstrapped.h1
-rw-r--r--src/corelib/global/qendian.cpp2
-rw-r--r--src/corelib/global/qglobal.cpp16
-rw-r--r--src/corelib/global/qglobal.h58
-rw-r--r--src/corelib/global/qlibraryinfo.cpp2
-rw-r--r--src/corelib/global/qlibraryinfo.h1
-rw-r--r--src/corelib/global/qlogging.cpp2
-rw-r--r--src/corelib/global/qnamespace.h200
-rw-r--r--src/corelib/global/qnumeric_p.h6
-rw-r--r--src/corelib/global/qrandom.cpp4
-rw-r--r--src/corelib/global/qrandom.h2
-rw-r--r--src/corelib/global/qtypeinfo.h1
-rw-r--r--src/corelib/io/qdebug.h6
-rw-r--r--src/corelib/io/qfileselector.cpp7
-rw-r--r--src/corelib/io/qfilesystemiterator_unix.cpp2
-rw-r--r--src/corelib/io/qfilesystemwatcher_win.cpp2
-rw-r--r--src/corelib/io/qresource.cpp10
-rw-r--r--src/corelib/io/qsettings.cpp5
-rw-r--r--src/corelib/io/qstandardpaths.cpp2
-rw-r--r--src/corelib/io/qurl.cpp2
-rw-r--r--src/corelib/itemmodels/qabstractitemmodel.cpp32
-rw-r--r--src/corelib/itemmodels/qabstractitemmodel.h1
-rw-r--r--src/corelib/itemmodels/qabstractproxymodel.h6
-rw-r--r--src/corelib/itemmodels/qitemselectionmodel.h2
-rw-r--r--src/corelib/kernel/qcoreapplication.cpp6
-rw-r--r--src/corelib/kernel/qcoreapplication_win.cpp2
-rw-r--r--src/corelib/kernel/qmetaobject.cpp55
-rw-r--r--src/corelib/kernel/qmetaobject.h3
-rw-r--r--src/corelib/kernel/qmetaobject_moc_p.h3
-rw-r--r--src/corelib/kernel/qmetaobjectbuilder.cpp22
-rw-r--r--src/corelib/kernel/qmetatype.cpp51
-rw-r--r--src/corelib/kernel/qmetatype.h48
-rw-r--r--src/corelib/kernel/qmetatype_p.h3
-rw-r--r--src/corelib/kernel/qobject.cpp68
-rw-r--r--src/corelib/kernel/qobject.h30
-rw-r--r--src/corelib/kernel/qobject_p.h12
-rw-r--r--src/corelib/kernel/qobjectdefs.h192
-rw-r--r--src/corelib/kernel/qtmetamacros.h233
-rw-r--r--src/corelib/kernel/qtranslator.cpp8
-rw-r--r--src/corelib/kernel/qvariant.cpp154
-rw-r--r--src/corelib/kernel/qvariant.h16
-rw-r--r--src/corelib/mimetypes/qmimedatabase.cpp4
-rw-r--r--src/corelib/mimetypes/qmimedatabase_p.h1
-rw-r--r--src/corelib/plugin/qlibrary.cpp4
-rw-r--r--src/corelib/serialization/qbinaryjsonvalue.cpp18
-rw-r--r--src/corelib/serialization/qbinaryjsonvalue_p.h4
-rw-r--r--src/corelib/serialization/qcborvalue_p.h17
-rw-r--r--src/corelib/serialization/qdatastream.h19
-rw-r--r--src/corelib/serialization/qjsonarray.h1
-rw-r--r--src/corelib/serialization/qjsoncbor.cpp22
-rw-r--r--src/corelib/serialization/qjsonparser.cpp12
-rw-r--r--src/corelib/serialization/qjsonvalue.cpp92
-rw-r--r--src/corelib/serialization/qjsonvalue.h1
-rw-r--r--src/corelib/serialization/qjsonwriter.cpp14
-rw-r--r--src/corelib/statemachine/qsignaleventgenerator_p.h7
-rw-r--r--src/corelib/statemachine/qstatemachine.cpp92
-rw-r--r--src/corelib/text/qbytearray.cpp606
-rw-r--r--src/corelib/text/qbytearray.h240
-rw-r--r--src/corelib/text/qbytearray_p.h2
-rw-r--r--src/corelib/text/qbytearraylist.h19
-rw-r--r--src/corelib/text/qbytearraymatcher.h2
-rw-r--r--src/corelib/text/qchar.h1
-rw-r--r--src/corelib/text/qstring.cpp520
-rw-r--r--src/corelib/text/qstring.h274
-rw-r--r--src/corelib/text/qstringbuilder.cpp4
-rw-r--r--src/corelib/text/qstringbuilder.h10
-rw-r--r--src/corelib/text/qstringlist.h74
-rw-r--r--src/corelib/text/qstringliteral.h44
-rw-r--r--src/corelib/thread/qfutureinterface.cpp7
-rw-r--r--src/corelib/thread/qfutureinterface.h13
-rw-r--r--src/corelib/thread/qthread.cpp2
-rw-r--r--src/corelib/thread/qthread.h33
-rw-r--r--src/corelib/thread/qthread_unix.cpp28
-rw-r--r--src/corelib/thread/qthread_win.cpp2
-rw-r--r--src/corelib/time/qdatetimeparser_p.h4
-rw-r--r--src/corelib/tools/qarraydata.cpp111
-rw-r--r--src/corelib/tools/qarraydata.h231
-rw-r--r--src/corelib/tools/qarraydataops.h413
-rw-r--r--src/corelib/tools/qarraydatapointer.h169
-rw-r--r--src/corelib/tools/qbitarray.cpp32
-rw-r--r--src/corelib/tools/qbitarray.h4
-rw-r--r--src/corelib/tools/qcontainerfwd.h2
-rw-r--r--src/corelib/tools/qcontiguouscache.h5
-rw-r--r--src/corelib/tools/qeasingcurve.cpp5
-rw-r--r--src/corelib/tools/qeasingcurve.h7
-rw-r--r--src/corelib/tools/qflatmap_p.h982
-rw-r--r--src/corelib/tools/qhash.h25
-rw-r--r--src/corelib/tools/qlinkedlist.h3
-rw-r--r--src/corelib/tools/qlist.cpp2025
-rw-r--r--src/corelib/tools/qlist.h1151
-rw-r--r--src/corelib/tools/qmap.h36
-rw-r--r--src/corelib/tools/qrefcount.h25
-rw-r--r--src/corelib/tools/qset.h33
-rw-r--r--src/corelib/tools/qvector.h1229
-rw-r--r--src/corelib/tools/qvector_msvc.cpp7
-rw-r--r--src/corelib/tools/tools.pri2
-rw-r--r--src/dbus/doc/snippets/code/doc_src_qdbusadaptors.cpp1
-rw-r--r--src/dbus/doc/src/dbus-adaptors.qdoc3
-rw-r--r--src/dbus/qdbusabstractadaptor.cpp118
-rw-r--r--src/dbus/qdbusabstractadaptor_p.h9
-rw-r--r--src/dbus/qdbusmetaobject.cpp2
-rw-r--r--src/dbus/qdbusmisc.cpp5
-rw-r--r--src/gui/configure.json10
-rw-r--r--src/gui/doc/snippets/picture/picture.cpp79
-rw-r--r--src/gui/doc/src/dontdocument.qdoc2
-rw-r--r--src/gui/image/image.pri5
-rw-r--r--src/gui/image/qimage.cpp155
-rw-r--r--src/gui/image/qimage.h156
-rw-r--r--src/gui/image/qimage_p.h2
-rw-r--r--src/gui/image/qpicture.cpp832
-rw-r--r--src/gui/image/qpicture.h78
-rw-r--r--src/gui/image/qpictureformatplugin.cpp135
-rw-r--r--src/gui/itemmodels/qstandarditemmodel.h9
-rw-r--r--src/gui/kernel/kernel.pri30
-rw-r--r--src/gui/kernel/qevent.cpp37
-rw-r--r--src/gui/kernel/qevent.h37
-rw-r--r--src/gui/kernel/qguiaction.cpp1214
-rw-r--r--src/gui/kernel/qguiaction.h198
-rw-r--r--src/gui/kernel/qguiaction_p.h (renamed from src/opengl/qglpaintdevice_p.h)125
-rw-r--r--src/gui/kernel/qguiactiongroup.cpp346
-rw-r--r--src/gui/kernel/qguiactiongroup.h (renamed from src/gui/image/qpictureformatplugin.h)74
-rw-r--r--src/gui/kernel/qguiactiongroup_p.h (renamed from src/opengl/qgraphicsshadereffect_p.h)59
-rw-r--r--src/gui/kernel/qguiapplication.cpp8
-rw-r--r--src/gui/kernel/qguiapplication_p.h7
-rw-r--r--src/gui/kernel/qguishortcut.cpp354
-rw-r--r--src/gui/kernel/qguishortcut.h (renamed from src/gui/image/qimage_compat.cpp)68
-rw-r--r--src/gui/kernel/qguishortcut_p.h (renamed from src/opengl/gl2paintengineex/qglcustomshaderstage_p.h)60
-rw-r--r--src/gui/kernel/qguivariant.cpp10
-rw-r--r--src/gui/kernel/qkeymapper_p.h1
-rw-r--r--src/gui/kernel/qkeysequence.cpp5
-rw-r--r--src/gui/kernel/qkeysequence.h16
-rw-r--r--src/gui/kernel/qkeysequence_p.h4
-rw-r--r--src/gui/kernel/qpalette.cpp204
-rw-r--r--src/gui/kernel/qpalette.h24
-rw-r--r--src/gui/kernel/qplatformmenu.h6
-rw-r--r--src/gui/kernel/qplatformtheme.cpp8
-rw-r--r--src/gui/kernel/qplatformtheme.h8
-rw-r--r--src/gui/kernel/qplatformtheme_p.h6
-rw-r--r--src/gui/kernel/qshortcutmap.cpp4
-rw-r--r--src/gui/kernel/qshortcutmap_p.h6
-rw-r--r--src/gui/kernel/qwindowdefs.h2
-rw-r--r--src/gui/kernel/qwindowsysteminterface.cpp4
-rw-r--r--src/gui/opengl/opengl.pri9
-rw-r--r--src/gui/opengl/qopengltexture.cpp2
-rw-r--r--src/gui/opengl/qopengltexture.h2
-rw-r--r--src/gui/painting/qcolor.cpp52
-rw-r--r--src/gui/painting/qcolor.h19
-rw-r--r--src/gui/painting/qdrawhelper_ssse3.cpp2
-rw-r--r--src/gui/text/qfontdatabase.h1
-rw-r--r--src/gui/text/qfontengine_qpf2.cpp2
-rw-r--r--src/gui/text/qtextoption.h2
-rw-r--r--src/gui/util/qgridlayoutengine.cpp2
-rw-r--r--src/gui/util/qtexturefiledata.cpp12
-rw-r--r--src/network/access/access.pri7
-rw-r--r--src/network/access/qabstractnetworkcache.h1
-rw-r--r--src/network/access/qhsts_p.h1
-rw-r--r--src/network/access/qhttp2protocolhandler.cpp12
-rw-r--r--src/network/access/qhttpnetworkconnection.cpp54
-rw-r--r--src/network/access/qhttpnetworkconnection_p.h2
-rw-r--r--src/network/access/qhttpnetworkconnectionchannel.cpp76
-rw-r--r--src/network/access/qhttpnetworkconnectionchannel_p.h7
-rw-r--r--src/network/access/qhttpnetworkreply.cpp14
-rw-r--r--src/network/access/qhttpnetworkreply_p.h12
-rw-r--r--src/network/access/qhttpnetworkrequest.cpp14
-rw-r--r--src/network/access/qhttpnetworkrequest_p.h4
-rw-r--r--src/network/access/qhttpthreaddelegate.cpp19
-rw-r--r--src/network/access/qhttpthreaddelegate_p.h2
-rw-r--r--src/network/access/qnetworkaccessmanager.cpp6
-rw-r--r--src/network/access/qnetworkaccessmanager.h1
-rw-r--r--src/network/access/qnetworkreplyhttpimpl.cpp20
-rw-r--r--src/network/access/qnetworkrequest.cpp18
-rw-r--r--src/network/access/qnetworkrequest.h8
-rw-r--r--src/network/access/qspdyprotocolhandler_p.h232
-rw-r--r--src/network/bearer/bearer.pri3
-rw-r--r--src/network/bearer/qbearerengine_impl_p.h (renamed from src/plugins/bearer/qbearerengine_impl.h)6
-rw-r--r--src/network/bearer/qnetworksession_impl.cpp (renamed from src/plugins/bearer/qnetworksession_impl.cpp)8
-rw-r--r--src/network/bearer/qnetworksession_impl_p.h (renamed from src/plugins/bearer/qnetworksession_impl.h)8
-rw-r--r--src/network/kernel/qnetworkinterface.h1
-rw-r--r--src/network/socket/qlocalserver_p.h9
-rw-r--r--src/network/socket/qlocalserver_win.cpp38
-rw-r--r--src/network/ssl/qssl.cpp3
-rw-r--r--src/network/ssl/qssl.h10
-rw-r--r--src/network/ssl/qsslconfiguration.cpp102
-rw-r--r--src/network/ssl/qsslconfiguration.h8
-rw-r--r--src/network/ssl/qsslconfiguration_p.h8
-rw-r--r--src/network/ssl/qsslcontext_openssl.cpp78
-rw-r--r--src/network/ssl/qsslsocket.cpp153
-rw-r--r--src/network/ssl/qsslsocket.h47
-rw-r--r--src/network/ssl/qsslsocket_mac.cpp54
-rw-r--r--src/network/ssl/qsslsocket_openssl.cpp290
-rw-r--r--src/network/ssl/qsslsocket_openssl_p.h13
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols.cpp8
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols_p.h4
-rw-r--r--src/network/ssl/qsslsocket_p.h1
-rw-r--r--src/network/ssl/qsslsocket_schannel.cpp6
-rw-r--r--src/network/ssl/qsslsocket_winrt.cpp12
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qgl.cpp182
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qglbuffer.cpp60
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qglcolormap.cpp71
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qglfunctions.cpp86
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qglpixelbuffer.cpp69
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qglshaderprogram.cpp104
-rw-r--r--src/opengl/doc/snippets/code/src_opengl_qgraphicsshadereffect.cpp95
-rw-r--r--src/opengl/doc/src/qtopengl-examples.qdoc9
-rw-r--r--src/opengl/doc/src/qtopengl-module.qdoc13
-rw-r--r--src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp173
-rw-r--r--src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h167
-rw-r--r--src/opengl/gl2paintengineex/qglcustomshaderstage.cpp137
-rw-r--r--src/opengl/gl2paintengineex/qglengineshadermanager.cpp875
-rw-r--r--src/opengl/gl2paintengineex/qglengineshadermanager_p.h508
-rw-r--r--src/opengl/gl2paintengineex/qglengineshadersource_p.h523
-rw-r--r--src/opengl/gl2paintengineex/qglgradientcache.cpp225
-rw-r--r--src/opengl/gl2paintengineex/qglgradientcache_p.h103
-rw-r--r--src/opengl/gl2paintengineex/qglshadercache_p.h86
-rw-r--r--src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp2515
-rw-r--r--src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h334
-rw-r--r--src/opengl/gl2paintengineex/qtextureglyphcache_gl.cpp414
-rw-r--r--src/opengl/gl2paintengineex/qtextureglyphcache_gl_p.h171
-rw-r--r--src/opengl/opengl.pro65
-rw-r--r--src/opengl/qgl.cpp5558
-rw-r--r--src/opengl/qgl.h524
-rw-r--r--src/opengl/qgl_p.h556
-rw-r--r--src/opengl/qglbuffer.cpp568
-rw-r--r--src/opengl/qglbuffer.h125
-rw-r--r--src/opengl/qglcolormap.cpp296
-rw-r--r--src/opengl/qglcolormap.h99
-rw-r--r--src/opengl/qglframebufferobject.cpp1466
-rw-r--r--src/opengl/qglframebufferobject.h149
-rw-r--r--src/opengl/qglframebufferobject_p.h157
-rw-r--r--src/opengl/qglfunctions.cpp1330
-rw-r--r--src/opengl/qglfunctions.h1688
-rw-r--r--src/opengl/qglpaintdevice.cpp239
-rw-r--r--src/opengl/qglpixelbuffer.cpp654
-rw-r--r--src/opengl/qglpixelbuffer.h104
-rw-r--r--src/opengl/qglpixelbuffer_p.h107
-rw-r--r--src/opengl/qglshaderprogram.cpp3237
-rw-r--r--src/opengl/qglshaderprogram.h303
-rw-r--r--src/opengl/qgraphicsshadereffect.cpp272
-rw-r--r--src/opengl/qopengldebug.cpp (renamed from src/gui/opengl/qopengldebug.cpp)6
-rw-r--r--src/opengl/qopengldebug.h (renamed from src/gui/opengl/qopengldebug.h)16
-rw-r--r--src/opengl/qopenglqueryhelper_p.h (renamed from src/gui/opengl/qopenglqueryhelper_p.h)2
-rw-r--r--src/opengl/qopengltimerquery.cpp (renamed from src/gui/opengl/qopengltimerquery.cpp)6
-rw-r--r--src/opengl/qopengltimerquery.h (renamed from src/gui/opengl/qopengltimerquery.h)8
-rw-r--r--src/opengl/qopenglwidget.cpp (renamed from src/widgets/kernel/qopenglwidget.cpp)4
-rw-r--r--src/opengl/qopenglwidget.h (renamed from src/widgets/kernel/qopenglwidget.h)6
-rw-r--r--src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp77
-rw-r--r--src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h19
-rw-r--r--src/platformsupport/kmsconvenience/qkmsdevice.cpp2
-rw-r--r--src/platformsupport/linuxofono/linuxofono.pro15
-rw-r--r--src/platformsupport/linuxofono/qofonoservice_linux.cpp (renamed from src/plugins/bearer/linux_common/qofonoservice_linux.cpp)2
-rw-r--r--src/platformsupport/linuxofono/qofonoservice_linux_p.h (renamed from src/plugins/bearer/linux_common/qofonoservice_linux_p.h)0
-rw-r--r--src/platformsupport/platformsupport.pro4
-rw-r--r--src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp4
-rw-r--r--src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h4
-rw-r--r--src/plugins/bearer/android/src/qandroidbearerengine.cpp2
-rw-r--r--src/plugins/bearer/android/src/qandroidbearerengine.h2
-rw-r--r--src/plugins/bearer/android/src/src.pro7
-rw-r--r--src/plugins/bearer/connman/connman.pro11
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.cpp2
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.h4
-rw-r--r--src/plugins/bearer/corewlan/corewlan.pro7
-rw-r--r--src/plugins/bearer/corewlan/qcorewlanengine.h2
-rw-r--r--src/plugins/bearer/corewlan/qcorewlanengine.mm2
-rw-r--r--src/plugins/bearer/generic/generic.pro3
-rw-r--r--src/plugins/bearer/generic/qgenericengine.cpp2
-rw-r--r--src/plugins/bearer/generic/qgenericengine.h2
-rw-r--r--src/plugins/bearer/nativewifi/nativewifi.pro7
-rw-r--r--src/plugins/bearer/nativewifi/qnativewifiengine.cpp2
-rw-r--r--src/plugins/bearer/nativewifi/qnativewifiengine.h2
-rw-r--r--src/plugins/bearer/networkmanager/networkmanager.pro11
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp3
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.h4
-rw-r--r--src/plugins/bearer/nla/nla.pro7
-rw-r--r--src/plugins/bearer/nla/qnlaengine.cpp2
-rw-r--r--src/plugins/bearer/nla/qnlaengine.h2
-rw-r--r--src/plugins/platforms/android/android.pro1
-rw-r--r--src/plugins/platforms/android/androidplatformplugin.cpp64
-rw-r--r--src/plugins/platforms/android/main.cpp1
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.h2
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.mm13
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.h1
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.mm17
-rw-r--r--src/plugins/platforms/windows/qwindowsglcontext.cpp2
-rw-r--r--src/plugins/platforms/windows/qwindowswindow.cpp4
-rw-r--r--src/plugins/platforms/xcb/qxcbeventqueue.h3
-rw-r--r--src/plugins/sqldrivers/psql/qsql_psql.cpp6
-rw-r--r--src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp9
-rw-r--r--src/plugins/styles/android/qandroidstyle.cpp2
-rw-r--r--src/plugins/styles/mac/qmacstyle_mac.mm2
-rw-r--r--src/sql/kernel/qsqlcachedresult.cpp8
-rw-r--r--src/sql/kernel/qsqlcachedresult_p.h9
-rw-r--r--src/sql/kernel/qsqldriver.cpp5
-rw-r--r--src/sql/kernel/qsqldriver.h16
-rw-r--r--src/sql/kernel/qsqldriver_p.h17
-rw-r--r--src/sql/kernel/qsqlindex.cpp3
-rw-r--r--src/sql/kernel/qsqlquery.cpp6
-rw-r--r--src/sql/kernel/qsqlquery.h4
-rw-r--r--src/sql/kernel/qsqlresult_p.h35
-rw-r--r--src/sql/models/qsqlrelationaltablemodel.cpp6
-rw-r--r--src/sql/models/qsqlrelationaltablemodel.h2
-rw-r--r--src/sql/models/qsqltablemodel.cpp4
-rw-r--r--src/sql/models/qsqltablemodel.h4
-rw-r--r--src/testlib/qtestblacklist.cpp10
-rw-r--r--src/testlib/qtestkeyboard.h4
-rw-r--r--src/tools/androiddeployqt/main.cpp25
-rw-r--r--src/tools/bootstrap/bootstrap.pro1
-rw-r--r--src/tools/moc/collectjson.cpp4
-rw-r--r--src/tools/moc/generator.cpp52
-rw-r--r--src/tools/moc/moc.cpp5
-rw-r--r--src/tools/moc/moc.h1
-rw-r--r--src/tools/qdbusxml2cpp/qdbusxml2cpp.cpp3
-rw-r--r--src/tools/uic/cpp/cppwriteinitialization.h2
-rw-r--r--src/tools/uic/main.cpp7
-rw-r--r--src/tools/uic/qclass_lib_map.h4
-rw-r--r--src/tools/uic/ui4.cpp30
-rw-r--r--src/tools/uic/ui4.h90
-rw-r--r--src/tools/uic/utils.h2
-rw-r--r--src/widgets/accessible/qaccessiblewidget.cpp1
-rw-r--r--src/widgets/configure.json10
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp8
-rw-r--r--src/widgets/dialogs/qprogressdialog.cpp4
-rw-r--r--src/widgets/doc/snippets/javastyle.cpp2
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/styles.qdoc2
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.cpp9
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.h1
-rw-r--r--src/widgets/graphicsview/qgraphicssceneindex_p.h1
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.h3
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp4
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp2
-rw-r--r--src/widgets/kernel/kernel.pri29
-rw-r--r--src/widgets/kernel/qaction.cpp1071
-rw-r--r--src/widgets/kernel/qaction.h132
-rw-r--r--src/widgets/kernel/qaction_p.h49
-rw-r--r--src/widgets/kernel/qactiongroup.cpp309
-rw-r--r--src/widgets/kernel/qactiongroup.h44
-rw-r--r--src/widgets/kernel/qapplication.h1
-rw-r--r--src/widgets/kernel/qshortcut.cpp320
-rw-r--r--src/widgets/kernel/qshortcut.h46
-rw-r--r--src/widgets/kernel/qt_widgets_pch.h4
-rw-r--r--src/widgets/kernel/qwidget.cpp17
-rw-r--r--src/widgets/kernel/qwidget.h4
-rw-r--r--src/widgets/kernel/qwidget_p.h4
-rw-r--r--src/widgets/kernel/qwidgetaction.cpp3
-rw-r--r--src/widgets/kernel/qwidgetaction.h7
-rw-r--r--src/widgets/kernel/qwidgetaction_p.h2
-rw-r--r--src/widgets/styles/qfusionstyle.cpp2
-rw-r--r--src/widgets/styles/qstyle.cpp1
-rw-r--r--src/widgets/styles/qstyle.h6
-rw-r--r--src/widgets/styles/qstyleoption.cpp2
-rw-r--r--src/widgets/styles/qstylesheetstyle_p.h2
-rw-r--r--src/widgets/util/qundostack.cpp4
-rw-r--r--src/widgets/util/qundostack_p.h4
-rw-r--r--src/widgets/widgets/qabstractbutton.cpp1
-rw-r--r--src/widgets/widgets/qabstractbutton.h4
-rw-r--r--src/widgets/widgets/qcombobox.h2
-rw-r--r--src/widgets/widgets/qdatetimeedit.cpp60
-rw-r--r--src/widgets/widgets/qdatetimeedit_p.h2
-rw-r--r--src/widgets/widgets/qlabel.cpp1
-rw-r--r--src/widgets/widgets/qlineedit.cpp6
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp18
-rw-r--r--src/widgets/widgets/qlineedit_p.h8
-rw-r--r--src/widgets/widgets/qmdisubwindow.cpp8
-rw-r--r--src/widgets/widgets/qmenu.cpp38
-rw-r--r--src/widgets/widgets/qmenu.h54
-rw-r--r--src/widgets/widgets/qmenubar.cpp17
-rw-r--r--src/widgets/widgets/qsplitter.h1
-rw-r--r--src/widgets/widgets/qtoolbar.cpp2
-rw-r--r--src/widgets/widgets/qtoolbarlayout.cpp2
-rw-r--r--src/widgets/widgets/qtoolbarlayout_p.h2
-rw-r--r--src/widgets/widgets/qtoolbutton.cpp2
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp2
-rw-r--r--src/xml/dom/qdom.cpp14
-rw-r--r--src/xml/dom/qdom.h14
-rw-r--r--sync.profile2
-rw-r--r--tests/auto/auto.pro4
-rw-r--r--tests/auto/concurrent/qtconcurrentfilter/qtconcurrentfilter.pro1
-rw-r--r--tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp40
-rw-r--r--tests/auto/concurrent/qtconcurrentmap/qtconcurrentmap.pro1
-rw-r--r--tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp41
-rw-r--r--tests/auto/concurrent/qtconcurrentmedian/qtconcurrentmedian.pro1
-rw-r--r--tests/auto/corelib/global/qglobal/tst_qglobal.cpp101
-rw-r--r--tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp2
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+mac/test50
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+osx/test40
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+ios/test (renamed from tests/auto/corelib/io/qfileselector/platforms/+mac/test)0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+ios/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+macos/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/+macos/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/test0
-rw-r--r--tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+macos/test (renamed from tests/auto/corelib/io/qfileselector/platforms/+osx/test)0
-rw-r--r--tests/auto/corelib/io/qfileselector/qfileselector.qrc114
-rw-r--r--tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp8
-rw-r--r--tests/auto/corelib/io/qsettings/tst_qsettings.cpp6
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp24
-rw-r--r--tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp7
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp62
-rw-r--r--tests/auto/corelib/kernel/qobject/tst_qobject.cpp53
-rw-r--r--tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp426
-rw-r--r--tests/auto/corelib/serialization/json/tst_qtjson.cpp78
-rw-r--r--tests/auto/corelib/serialization/qcborvalue_json/tst_qcborvalue_json.cpp15
-rw-r--r--tests/auto/corelib/serialization/qdatastream/tst_qdatastream.cpp2
-rw-r--r--tests/auto/corelib/text/qbytearray/tst_qbytearray.cpp76
-rw-r--r--tests/auto/corelib/text/qstring/tst_qstring.cpp37
-rw-r--r--tests/auto/corelib/text/qstringref/tst_qstringref.cpp13
-rw-r--r--tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp17
-rw-r--r--tests/auto/corelib/thread/qatomicpointer/tst_qatomicpointer.cpp6
-rw-r--r--tests/auto/corelib/thread/qfuture/qfuture.pro1
-rw-r--r--tests/auto/corelib/thread/qresultstore/qresultstore.pro1
-rw-r--r--tests/auto/corelib/tools/collections/collections.pro1
-rw-r--r--tests/auto/corelib/tools/collections/tst_collections.cpp64
-rw-r--r--tests/auto/corelib/tools/containerapisymmetry/containerapisymmetry.pro2
-rw-r--r--tests/auto/corelib/tools/containerapisymmetry/tst_containerapisymmetry.cpp5
-rw-r--r--tests/auto/corelib/tools/qarraydata/simplevector.h53
-rw-r--r--tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp634
-rw-r--r--tests/auto/corelib/tools/qarraydata_strictiterators/qarraydata_strictiterators.pro3
-rw-r--r--tests/auto/corelib/tools/qbitarray/tst_qbitarray.cpp93
-rw-r--r--tests/auto/corelib/tools/qflatmap/qflatmap.pro4
-rw-r--r--tests/auto/corelib/tools/qflatmap/tst_qflatmap.cpp453
-rw-r--r--tests/auto/corelib/tools/qhash/tst_qhash.cpp7
-rw-r--r--tests/auto/corelib/tools/qhash_strictiterators/qhash_strictiterators.pro3
-rw-r--r--tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp61
-rw-r--r--tests/auto/corelib/tools/qlist/.gitignore1
-rw-r--r--tests/auto/corelib/tools/qlist/qlist.pro6
-rw-r--r--tests/auto/corelib/tools/qlist/tst_qlist.cpp2115
-rw-r--r--tests/auto/corelib/tools/qlist_strictiterators/qlist_strictiterators.pro3
-rw-r--r--tests/auto/corelib/tools/qmap/tst_qmap.cpp82
-rw-r--r--tests/auto/corelib/tools/qmap_strictiterators/qmap_strictiterators.pro3
-rw-r--r--tests/auto/corelib/tools/qset/tst_qset.cpp2
-rw-r--r--tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp2
-rw-r--r--tests/auto/corelib/tools/qvector/tst_qvector.cpp425
-rw-r--r--tests/auto/corelib/tools/qvector_strictiterators/qvector_strictiterators.pro3
-rw-r--r--tests/auto/corelib/tools/tools.pro7
-rw-r--r--tests/auto/dbus/qdbusinterface/tst_qdbusinterface.cpp11
-rw-r--r--tests/auto/dbus/qdbusmetatype/tst_qdbusmetatype.cpp2
-rw-r--r--tests/auto/gui/image/qpicture/tst_qpicture.cpp31
-rw-r--r--tests/auto/gui/kernel/kernel.pro13
-rw-r--r--tests/auto/gui/kernel/qguiaction/.gitignore (renamed from tests/auto/widgets/kernel/qaction/.gitignore)0
-rw-r--r--tests/auto/gui/kernel/qguiaction/qguiaction.pro4
-rw-r--r--tests/auto/gui/kernel/qguiaction/tst_qguiaction.cpp210
-rw-r--r--tests/auto/gui/kernel/qguiactiongroup/.gitignore1
-rw-r--r--tests/auto/gui/kernel/qguiactiongroup/qguiactiongroup.pro4
-rw-r--r--tests/auto/gui/kernel/qguiactiongroup/tst_qguiactiongroup.cpp235
-rw-r--r--tests/auto/gui/kernel/qguimetatype/tst_qguimetatype.cpp26
-rw-r--r--tests/auto/gui/kernel/qguishortcut/qguishortcut.pro4
-rw-r--r--tests/auto/gui/kernel/qguishortcut/tst_qguishortcut.cpp82
-rw-r--r--tests/auto/gui/kernel/qkeyevent/tst_qkeyevent.cpp6
-rw-r--r--tests/auto/gui/kernel/qpalette/tst_qpalette.cpp63
-rw-r--r--tests/auto/gui/painting/qcolor/tst_qcolor.cpp37
-rw-r--r--tests/auto/network/access/access.pro1
-rw-r--r--tests/auto/network/access/http2/tst_http2.cpp7
-rw-r--r--tests/auto/network/access/qnetworkreply/BLACKLIST2
-rw-r--r--tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp4
-rw-r--r--tests/auto/network/access/spdy/BLACKLIST7
-rw-r--r--tests/auto/network/access/spdy/spdy.pro7
-rw-r--r--tests/auto/network/access/spdy/tst_spdy.cpp693
-rw-r--r--tests/auto/network/ssl/qdtls/tst_qdtls.cpp1
-rw-r--r--tests/auto/network/ssl/qocsp/tst_qocsp.cpp1
-rw-r--r--tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp177
-rw-r--r--tests/auto/opengl/opengl.pro8
-rw-r--r--tests/auto/opengl/qgl/.gitignore1
-rw-r--r--tests/auto/opengl/qgl/BLACKLIST8
-rw-r--r--tests/auto/opengl/qgl/qgl.pro11
-rw-r--r--tests/auto/opengl/qgl/qgl.qrc5
-rw-r--r--tests/auto/opengl/qgl/tst_qgl.cpp2524
-rw-r--r--tests/auto/opengl/qglbuffer/qglbuffer.pro10
-rw-r--r--tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp257
-rw-r--r--tests/auto/opengl/qglfunctions/qglfunctions.pro6
-rw-r--r--tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp233
-rw-r--r--tests/auto/opengl/qglthreads/qglthreads.pro7
-rw-r--r--tests/auto/opengl/qglthreads/tst_qglthreads.cpp687
-rw-r--r--tests/auto/opengl/qglthreads/tst_qglthreads.h51
-rw-r--r--tests/auto/other/compiler/tst_compiler.cpp4
-rw-r--r--tests/auto/other/qaccessibility/tst_qaccessibility.cpp18
-rw-r--r--tests/auto/other/qfocusevent/tst_qfocusevent.cpp6
-rw-r--r--tests/auto/other/toolsupport/tst_toolsupport.cpp8
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.lightxml2
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.tap2
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.teamcity2
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.txt2
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.xml2
-rw-r--r--tests/auto/testlib/selftests/expected_signaldumper.xunitxml4
-rw-r--r--tests/auto/tools/moc/allmocs_baseline_in.json2167
-rw-r--r--tests/auto/tools/moc/moc.pro2
-rw-r--r--tests/auto/tools/moc/task189996.h47
-rw-r--r--tests/auto/tools/moc/tst_moc.cpp31
-rw-r--r--tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp7
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp6
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsview/qgraphicsview.pro1
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp8
-rw-r--r--tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp2
-rw-r--r--tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp6
-rw-r--r--tests/auto/widgets/kernel/kernel.pro11
-rw-r--r--tests/auto/widgets/kernel/qaction/tst_qaction.cpp160
-rw-r--r--tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp192
-rw-r--r--tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp20
-rw-r--r--tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp22
-rw-r--r--tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp8
-rw-r--r--tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp50
-rw-r--r--tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp6
-rw-r--r--tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp16
-rw-r--r--tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp30
-rw-r--r--tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp24
-rw-r--r--tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp9
-rw-r--r--tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp12
-rw-r--r--tests/auto/widgets/widgets/qopenglwidget/qopenglwidget.pro2
-rw-r--r--tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp2
-rw-r--r--tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp14
-rw-r--r--tests/auto/widgets/widgets/qradiobutton/tst_qradiobutton.cpp5
-rw-r--r--tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp11
-rw-r--r--tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp4
-rw-r--r--tests/auto/widgets/widgets/widgets.pro3
-rw-r--r--tests/auto/xml/dom/qdom/tst_qdom.cpp8
-rw-r--r--tests/benchmarks/corelib/io/qdiriterator/main.cpp35
-rw-r--r--tests/benchmarks/corelib/io/qdiriterator/qdiriterator.pro2
-rw-r--r--tests/benchmarks/corelib/kernel/qobject/main.cpp47
-rw-r--r--tests/benchmarks/corelib/tools/qvector/outofline.cpp2
-rw-r--r--tests/benchmarks/corelib/tools/qvector/qrawvector.h75
-rw-r--r--tests/benchmarks/network/access/qfile_vs_qnetworkaccessmanager/main.cpp6
-rw-r--r--tests/benchmarks/network/access/qnetworkreply/tst_qnetworkreply.cpp34
-rw-r--r--tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.cpp7
-rw-r--r--tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.h1
-rw-r--r--tests/benchmarks/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp21
-rw-r--r--tests/manual/cocoa/menurama/menurama.pro4
-rw-r--r--tests/manual/corelib/tools/qhash/main.cpp1
-rw-r--r--tests/manual/corelib/tools/qlist/main.cpp3
-rw-r--r--tests/manual/corelib/tools/qset/main.cpp1
-rw-r--r--tests/manual/corelib/tools/qvarlengtharray/main.cpp1
-rw-r--r--tests/manual/corelib/tools/qvector/main.cpp1
-rw-r--r--tests/manual/diaglib/debugproxystyle.cpp4
-rw-r--r--tests/manual/diaglib/diaglib.pri27
-rw-r--r--tests/manual/diaglib/qwidgetdump.cpp6
-rw-r--r--tests/manual/diaglib/qwindowdump.cpp9
-rw-r--r--tests/manual/diaglib/textdump.cpp6
-rw-r--r--tests/manual/dialogs/dialogs.pro8
-rw-r--r--tests/manual/dialogs/messageboxpanel.cpp4
-rw-r--r--tests/manual/dialogs/printdialogpanel.cpp3
-rw-r--r--tests/manual/gestures/graphicsview/graphicsview.pro2
-rw-r--r--tests/manual/highdpi/main.cpp2
-rw-r--r--tests/manual/manual.pro4
-rw-r--r--tests/manual/qcursor/childwidget/childwidget.pro2
-rw-r--r--tests/manual/qcursor/qcursorhighdpi/qcursorhighdpi.pro3
-rw-r--r--tests/manual/qdesktopservices/qdesktopservices.pro2
-rw-r--r--tests/manual/qhttpnetworkconnection/main.cpp2
-rw-r--r--tests/manual/qhttpnetworkconnection/qhttpnetworkconnection.pro2
-rw-r--r--tests/manual/qnetworkaccessmanager/qget/qget.cpp52
-rw-r--r--tests/manual/qnetworkconfiguration/qnetworkconfiguration.pro2
-rw-r--r--tests/manual/qnetworkconfigurationmanager/qnetworkconfigurationmanager.pro2
-rw-r--r--tests/manual/qnetworkreply/main.cpp204
-rw-r--r--tests/manual/qnetworkreply/qnetworkreply.pro2
-rw-r--r--tests/manual/qscreen/main.cpp14
-rw-r--r--tests/manual/qssloptions/main.cpp14
-rw-r--r--tests/manual/qsslsocket/qsslsocket.pro2
-rw-r--r--tests/manual/qtexteditlist/qtexteditlist.pro2
-rw-r--r--tests/manual/qtexttableborders/qtexttableborders.pro3
-rw-r--r--tests/manual/qtouchevent/qtouchevent.pro3
-rw-r--r--tests/manual/repaint/mainwindow/mainwindow.pro1
-rw-r--r--tests/manual/repaint/scrollarea/scrollarea.pro1
-rw-r--r--tests/manual/repaint/toplevel/toplevel.pro1
-rw-r--r--tests/manual/touch/main.cpp2
-rw-r--r--tests/manual/touch/touch.pro3
-rw-r--r--tests/manual/unc/unc.pro3
-rw-r--r--tests/manual/widgetgrab/widgetgrab.pro6
-rw-r--r--tests/manual/widgets/styles/styles.pro1
-rw-r--r--tests/manual/widgets/widgets.pro3
-rw-r--r--tests/manual/widgets/widgets/bigmenucreator/bigmenucreator.pro4
-rw-r--r--tests/manual/windowchildgeometry/windowchildgeometry.pro3
-rw-r--r--tests/manual/windowflags/previewwindow.cpp8
-rw-r--r--tests/manual/windowflags/windowflags.pro4
-rw-r--r--tests/manual/windowgeometry/windowgeometry.pro3
-rw-r--r--tests/manual/windowmodality/windowmodality.pro2
-rw-r--r--tests/manual/xembed-raster/xembed-raster.pro2
-rw-r--r--tests/manual/xembed-widgets/xembed-widgets.pro2
644 files changed, 11108 insertions, 51751 deletions
diff --git a/.qmake.conf b/.qmake.conf
index 8cc650fc21..de7af300dc 100644
--- a/.qmake.conf
+++ b/.qmake.conf
@@ -6,4 +6,4 @@ DEFINES += QT_NO_JAVA_STYLE_ITERATORS
QT_SOURCE_TREE = $$PWD
QT_BUILD_TREE = $$shadowed($$PWD)
-MODULE_VERSION = 5.15.0
+MODULE_VERSION = 6.0.0
diff --git a/config_help.txt b/config_help.txt
index 5cba7316b1..52f6730ce8 100644
--- a/config_help.txt
+++ b/config_help.txt
@@ -38,8 +38,7 @@ except -sysconfdir should be located under -prefix/-hostprefix:
-plugindir <dir> ...... Plugins [ARCHDATADIR/plugins]
-libexecdir <dir> ..... Helper programs [ARCHDATADIR/bin on Windows,
ARCHDATADIR/libexec otherwise]
- -importdir <dir> ...... QML1 imports [ARCHDATADIR/imports]
- -qmldir <dir> ......... QML2 imports [ARCHDATADIR/qml]
+ -qmldir <dir> ......... QML imports [ARCHDATADIR/qml]
-datadir <dir> ........ Arch-independent data [PREFIX]
-docdir <dir> ......... Documentation [DATADIR/doc]
-translationdir <dir> . Translations [DATADIR/translations]
diff --git a/configure b/configure
index 6657870e4b..c0c0227b63 100755
--- a/configure
+++ b/configure
@@ -417,7 +417,6 @@ while [ "$#" -gt 0 ]; do
-docdir| \
-headerdir| \
-plugindir| \
- -importdir| \
-qmldir| \
-archdatadir| \
-datadir| \
diff --git a/configure.json b/configure.json
index 1e8506f54d..d94dea850b 100644
--- a/configure.json
+++ b/configure.json
@@ -40,7 +40,6 @@
"hostbindir": "string",
"hostdatadir": "string",
"hostlibdir": "string",
- "importdir": "string",
"libdir": "string",
"libexecdir": "string",
"plugindir": "string",
diff --git a/configure.pri b/configure.pri
index 57a813023e..ddc69b3faf 100644
--- a/configure.pri
+++ b/configure.pri
@@ -704,7 +704,6 @@ defineReplace(printInstallPaths) {
$$printInstallPath(LibraryExecutables, libexecdir, $$DEFAULT_LIBEXEC) \
$$printInstallPath(Binaries, bindir, bin) \
$$printInstallPath(Plugins, plugindir, plugins) \
- $$printInstallPath(Imports, importdir, imports) \
$$printInstallPath(Qml2Imports, qmldir, qml) \
$$printInstallPath(ArchData, archdatadir, .) \
$$printInstallPath(Data, datadir, .) \
@@ -805,7 +804,6 @@ defineTest(qtConfOutput_preparePaths) {
archdata_pfx = $$config.rel_input.archdatadir/
processQtPath("", libexecdir, $${archdata_pfx}$$DEFAULT_LIBEXEC)
processQtPath("", plugindir, $${archdata_pfx}plugins)
- processQtPath("", importdir, $${archdata_pfx}imports)
processQtPath("", qmldir, $${archdata_pfx}qml)
processQtPath("", sysconfdir, $$DEFAULT_SYSCONFDIR)
$$have_hostprefix {
@@ -851,7 +849,6 @@ defineTest(qtConfOutput_preparePaths) {
addConfStr($$config.rel_input.libexecdir)
addConfStr($$config.rel_input.bindir)
addConfStr($$config.rel_input.plugindir)
- addConfStr($$config.rel_input.importdir)
addConfStr($$config.rel_input.qmldir)
addConfStr($$config.rel_input.archdatadir)
addConfStr($$config.rel_input.datadir)
diff --git a/dependencies.yaml b/dependencies.yaml
new file mode 100644
index 0000000000..c093387ce0
--- /dev/null
+++ b/dependencies.yaml
@@ -0,0 +1 @@
+dependencies: {}
diff --git a/doc/src/portingguide-5-to-6.qdoc b/doc/src/portingguide-5-to-6.qdoc
new file mode 100644
index 0000000000..8a6ea34b56
--- /dev/null
+++ b/doc/src/portingguide-5-to-6.qdoc
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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: https://www.gnu.org/licenses/fdl-1.3.html.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+/*!
+\page portingguide.html
+\title Porting Qt5 to Qt6 Guide
+\brief Provides guidance to migrate your Qt 5 application to Qt 6.
+
+Qt 6 is a result of the conscious effort to make this C++ framework more
+efficient and easy to use. This release replaces quite a few legacy APIs with
+more meaningful ones, such as the newer version of Qt Quick.
+
+We try to maintain binary and source compatibility for all the public APIs in
+each release, but some changes were inevitable in an effort to make Qt a
+better framework. In this topic, we try to summarize those changes and
+provide guidance to handle them.
+
+The following list summarizes the changes in Qt 6:
+\list
+ \li The major version number.
+\endlist
+
+\section1 Related Topics
+\list
+\li \l {C++ API Changes}
+\li \l {Porting C++ Applications to Qt 6}
+\li \l {Porting QML Applications to Qt 6}
+\li \l {Porting QML Applications to Qt 6 Example}
+\endlist
+*/
diff --git a/examples/opengl/2dpainting/2dpainting.pro b/examples/opengl/2dpainting/2dpainting.pro
index b9611f5b40..20fe4739a5 100644
--- a/examples/opengl/2dpainting/2dpainting.pro
+++ b/examples/opengl/2dpainting/2dpainting.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
HEADERS = glwidget.h \
helper.h \
diff --git a/examples/opengl/cube/cube.pro b/examples/opengl/cube/cube.pro
index b9416f1a9d..07724e247e 100644
--- a/examples/opengl/cube/cube.pro
+++ b/examples/opengl/cube/cube.pro
@@ -1,4 +1,4 @@
-QT += core gui widgets
+QT += core gui widgets opengl
TARGET = cube
TEMPLATE = app
diff --git a/examples/opengl/hellogl2/hellogl2.pro b/examples/opengl/hellogl2/hellogl2.pro
index 3a52e04d74..834ae82e1f 100644
--- a/examples/opengl/hellogl2/hellogl2.pro
+++ b/examples/opengl/hellogl2/hellogl2.pro
@@ -8,7 +8,7 @@ SOURCES = glwidget.cpp \
mainwindow.cpp \
logo.cpp
-QT += widgets
+QT += widgets opengl
# install
target.path = $$[QT_INSTALL_EXAMPLES]/opengl/hellogl2
diff --git a/examples/opengl/qopenglwidget/qopenglwidget.pro b/examples/opengl/qopenglwidget/qopenglwidget.pro
index 0165285c02..1df3de1290 100644
--- a/examples/opengl/qopenglwidget/qopenglwidget.pro
+++ b/examples/opengl/qopenglwidget/qopenglwidget.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
SOURCES += main.cpp \
glwidget.cpp \
diff --git a/examples/opengl/textures/textures.pro b/examples/opengl/textures/textures.pro
index 7a7d19bee6..ae1ae4d34c 100644
--- a/examples/opengl/textures/textures.pro
+++ b/examples/opengl/textures/textures.pro
@@ -6,7 +6,7 @@ SOURCES = glwidget.cpp \
RESOURCES = textures.qrc
-QT += widgets
+QT += widgets opengl
# install
target.path = $$[QT_INSTALL_EXAMPLES]/opengl/textures
diff --git a/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro b/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
index 4e941b28c4..70694459b2 100644
--- a/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
+++ b/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
SOURCES += main.cpp \
glwidget.cpp \
diff --git a/examples/widgets/animation/sub-attaq/mainwindow.cpp b/examples/widgets/animation/sub-attaq/mainwindow.cpp
index f9617a22eb..0c152c9180 100644
--- a/examples/widgets/animation/sub-attaq/mainwindow.cpp
+++ b/examples/widgets/animation/sub-attaq/mainwindow.cpp
@@ -59,10 +59,6 @@
#include <QMenuBar>
#include <QLayout>
-#ifndef QT_NO_OPENGL
-# include <QtOpenGL>
-#endif
-
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
@@ -84,14 +80,5 @@ MainWindow::MainWindow(QWidget *parent)
view = new QGraphicsView(scene, this);
view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
scene->setupScene(newAction, quitAction);
-#ifndef QT_NO_OPENGL
- QGLWidget *glWidget = new QGLWidget(QGLFormat(QGL::SampleBuffers));
- if (glWidget->context()->isValid()) {
- view->setViewport(glWidget);
- } else {
- qWarning("Unable to create an Open GL context with sample buffers, not using Open GL.");
- delete glWidget;
- }
-#endif
setCentralWidget(view);
}
diff --git a/examples/widgets/animation/sub-attaq/sub-attaq.pro b/examples/widgets/animation/sub-attaq/sub-attaq.pro
index ac79fd4249..ea44253fa1 100644
--- a/examples/widgets/animation/sub-attaq/sub-attaq.pro
+++ b/examples/widgets/animation/sub-attaq/sub-attaq.pro
@@ -1,5 +1,4 @@
QT += widgets
-qtHaveModule(opengl): QT += opengl
HEADERS += boat.h \
bomb.h \
mainwindow.h \
diff --git a/examples/widgets/graphicsview/boxes/3rdparty/fbm.c b/examples/widgets/graphicsview/boxes/3rdparty/fbm.c
deleted file mode 100644
index 3eebaabfba..0000000000
--- a/examples/widgets/graphicsview/boxes/3rdparty/fbm.c
+++ /dev/null
@@ -1,207 +0,0 @@
-/*****************************************************************
-
- Implementation of the fractional Brownian motion algorithm. These
- functions were originally the work of F. Kenton Musgrave.
- For documentation of the different functions please refer to the
- book:
- "Texturing and modeling: a procedural approach"
- by David S. Ebert et. al.
-
-******************************************************************/
-
-#if defined (_MSC_VER)
-#include <qglobal.h>
-#endif
-
-#include <time.h>
-#include <stdlib.h>
-#include "fbm.h"
-
-#if defined(Q_CC_MSVC)
-#pragma warning(disable:4244)
-#endif
-
-/* Definitions used by the noise2() functions */
-
-//#define B 0x100
-//#define BM 0xff
-#define B 0x20
-#define BM 0x1f
-
-#define N 0x1000
-#define NP 12 /* 2^N */
-#define NM 0xfff
-
-static int p[B + B + 2];
-static float g3[B + B + 2][3];
-static float g2[B + B + 2][2];
-static float g1[B + B + 2];
-static int start = 1;
-
-static void init(void);
-
-#define s_curve(t) ( t * t * (3. - 2. * t) )
-
-#define lerp(t, a, b) ( a + t * (b - a) )
-
-#define setup(i,b0,b1,r0,r1)\
- t = vec[i] + N;\
- b0 = ((int)t) & BM;\
- b1 = (b0+1) & BM;\
- r0 = t - (int)t;\
- r1 = r0 - 1.;
-#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )
-
-/* Fractional Brownian Motion function */
-
-double fBm( Vector point, double H, double lacunarity, double octaves,
- int init )
-{
-
- double value, frequency, remainder;
- int i;
- static double exponent_array[10];
- float vec[3];
-
- /* precompute and store spectral weights */
- if ( init ) {
- start = 1;
- srand( time(0) );
- /* seize required memory for exponent_array */
- frequency = 1.0;
- for (i=0; i<=octaves; i++) {
- /* compute weight for each frequency */
- exponent_array[i] = pow( frequency, -H );
- frequency *= lacunarity;
- }
- }
-
- value = 0.0; /* initialize vars to proper values */
- frequency = 1.0;
- vec[0]=point.x;
- vec[1]=point.y;
- vec[2]=point.z;
-
-
- /* inner loop of spectral construction */
- for (i=0; i<octaves; i++) {
- /* value += noise3( vec ) * exponent_array[i];*/
- value += noise3( vec ) * exponent_array[i];
- vec[0] *= lacunarity;
- vec[1] *= lacunarity;
- vec[2] *= lacunarity;
- } /* for */
-
- remainder = octaves - (int)octaves;
- if ( remainder ) /* add in ``octaves'' remainder */
- /* ``i'' and spatial freq. are preset in loop above */
- value += remainder * noise3( vec ) * exponent_array[i];
-
- return( value );
-
-} /* fBm() */
-
-
-float noise3(float vec[3])
-{
- int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
- float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
- int i, j;
-
- if (start) {
- start = 0;
- init();
- }
-
- setup(0, bx0,bx1, rx0,rx1);
- setup(1, by0,by1, ry0,ry1);
- setup(2, bz0,bz1, rz0,rz1);
-
- i = p[ bx0 ];
- j = p[ bx1 ];
-
- b00 = p[ i + by0 ];
- b10 = p[ j + by0 ];
- b01 = p[ i + by1 ];
- b11 = p[ j + by1 ];
-
- t = s_curve(rx0);
- sy = s_curve(ry0);
- sz = s_curve(rz0);
-
-
- q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
- q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
- a = lerp(t, u, v);
-
- q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
- q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
- b = lerp(t, u, v);
-
- c = lerp(sy, a, b);
-
- q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
- q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
- a = lerp(t, u, v);
-
- q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
- q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
- b = lerp(t, u, v);
-
- d = lerp(sy, a, b);
-
- return lerp(sz, c, d);
-}
-
-static void normalize2(float v[2])
-{
- float s;
-
- s = sqrt(v[0] * v[0] + v[1] * v[1]);
- v[0] = v[0] / s;
- v[1] = v[1] / s;
-}
-
-static void normalize3(float v[3])
-{
- float s;
-
- s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
- v[0] = v[0] / s;
- v[1] = v[1] / s;
- v[2] = v[2] / s;
-}
-
-static void init(void)
-{
- int i, j, k;
-
- for (i = 0 ; i < B ; i++) {
- p[i] = i;
-
- g1[i] = (float)((rand() % (B + B)) - B) / B;
-
- for (j = 0 ; j < 2 ; j++)
- g2[i][j] = (float)((rand() % (B + B)) - B) / B;
- normalize2(g2[i]);
-
- for (j = 0 ; j < 3 ; j++)
- g3[i][j] = (float)((rand() % (B + B)) - B) / B;
- normalize3(g3[i]);
- }
-
- while (--i) {
- k = p[i];
- p[i] = p[j = rand() % B];
- p[j] = k;
- }
-
- for (i = 0 ; i < B + 2 ; i++) {
- p[B + i] = p[i];
- g1[B + i] = g1[i];
- for (j = 0 ; j < 2 ; j++)
- g2[B + i][j] = g2[i][j];
- for (j = 0 ; j < 3 ; j++)
- g3[B + i][j] = g3[i][j];
- }
-}
diff --git a/examples/widgets/graphicsview/boxes/3rdparty/fbm.h b/examples/widgets/graphicsview/boxes/3rdparty/fbm.h
deleted file mode 100644
index b8a4a99ae4..0000000000
--- a/examples/widgets/graphicsview/boxes/3rdparty/fbm.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*****************************************************************
-
- Prototypes for the fractional Brownian motion algorithm. These
- functions were originally the work of F. Kenton Musgrave. For
- documentation of the different functions please refer to the book:
- "Texturing and modeling: a procedural approach"
- by David S. Ebert et. al.
-
-******************************************************************/
-
-#ifndef _fbm_h
-#define _fbm_h
-
-#include <math.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//#define TRUE 1
-//#define FALSE 0
-
-typedef struct {
- double x;
- double y;
- double z;
-} Vector;
-
-float noise3(float vec[]);
-double fBm( Vector point, double H, double lacunarity, double octaves,
- int init );
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-
-
-
diff --git a/examples/widgets/graphicsview/boxes/basic.fsh b/examples/widgets/graphicsview/boxes/basic.fsh
deleted file mode 100644
index 327daeef54..0000000000
--- a/examples/widgets/graphicsview/boxes/basic.fsh
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform vec4 basicColor;
-
-void main()
-{
- vec3 N = normalize(normal);
- // assume directional light
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- vec3 absN = abs(gl_TexCoord[1].xyz);
- vec3 texCoord;
- if (absN.x > absN.y && absN.x > absN.z)
- texCoord = gl_TexCoord[1].yzx;
- else if (absN.y > absN.z)
- texCoord = gl_TexCoord[1].zxy;
- else
- texCoord = gl_TexCoord[1].xyz;
- texCoord.y *= -sign(texCoord.z);
- texCoord += 0.5;
-
- vec4 texColor = texture2D(tex, texCoord.xy);
- vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w);
- gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-}
diff --git a/examples/widgets/graphicsview/boxes/basic.vsh b/examples/widgets/graphicsview/boxes/basic.vsh
deleted file mode 100644
index 454e0bd903..0000000000
--- a/examples/widgets/graphicsview/boxes/basic.vsh
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform mat4 view;
-
-void main()
-{
- gl_TexCoord[0] = gl_MultiTexCoord0;
- gl_TexCoord[1] = gl_Vertex;
- specular = gl_LightSource[0].specular;
- ambient = gl_LightSource[0].ambient;
- diffuse = gl_LightSource[0].diffuse;
- lightDirection = view * gl_LightSource[0].position;
-
- normal = gl_NormalMatrix * gl_Normal;
- position = (gl_ModelViewMatrix * gl_Vertex).xyz;
-
- gl_FrontColor = gl_Color;
- gl_Position = ftransform();
-}
diff --git a/examples/widgets/graphicsview/boxes/boxes.pro b/examples/widgets/graphicsview/boxes/boxes.pro
deleted file mode 100644
index 601edd6883..0000000000
--- a/examples/widgets/graphicsview/boxes/boxes.pro
+++ /dev/null
@@ -1,27 +0,0 @@
-QT += opengl widgets
-requires(qtConfig(combobox))
-
-qtConfig(opengles.|angle|dynamicgl): error("This example requires Qt to be configured with -opengl desktop")
-
-HEADERS += 3rdparty/fbm.h \
- glbuffers.h \
- glextensions.h \
- gltrianglemesh.h \
- qtbox.h \
- roundedbox.h \
- scene.h \
- trackball.h
-SOURCES += 3rdparty/fbm.c \
- glbuffers.cpp \
- glextensions.cpp \
- main.cpp \
- qtbox.cpp \
- roundedbox.cpp \
- scene.cpp \
- trackball.cpp
-
-RESOURCES += boxes.qrc
-
-# install
-target.path = $$[QT_INSTALL_EXAMPLES]/widgets/graphicsview/boxes
-INSTALLS += target
diff --git a/examples/widgets/graphicsview/boxes/boxes.qrc b/examples/widgets/graphicsview/boxes/boxes.qrc
deleted file mode 100644
index d27506dc5a..0000000000
--- a/examples/widgets/graphicsview/boxes/boxes.qrc
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/res/boxes">
- <file>cubemap_negx.jpg</file>
- <file>cubemap_negy.jpg</file>
- <file>cubemap_negz.jpg</file>
- <file>cubemap_posx.jpg</file>
- <file>cubemap_posy.jpg</file>
- <file>cubemap_posz.jpg</file>
- <file>square.jpg</file>
- <file>basic.vsh</file>
- <file>basic.fsh</file>
- <file>dotted.fsh</file>
- <file>fresnel.fsh</file>
- <file>glass.fsh</file>
- <file>granite.fsh</file>
- <file>marble.fsh</file>
- <file>reflection.fsh</file>
- <file>refraction.fsh</file>
- <file>wood.fsh</file>
- <file>parameters.par</file>
- <file>qt-logo.png</file>
- <file>smiley.png</file>
- <file>qt-logo.jpg</file>
-</qresource>
-</RCC>
diff --git a/examples/widgets/graphicsview/boxes/cubemap_negx.jpg b/examples/widgets/graphicsview/boxes/cubemap_negx.jpg
deleted file mode 100644
index 07c282eab9..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negx.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_negy.jpg b/examples/widgets/graphicsview/boxes/cubemap_negy.jpg
deleted file mode 100644
index 46cd2f9cf3..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negy.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_negz.jpg b/examples/widgets/graphicsview/boxes/cubemap_negz.jpg
deleted file mode 100644
index 40c01ddff3..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negz.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posx.jpg b/examples/widgets/graphicsview/boxes/cubemap_posx.jpg
deleted file mode 100644
index 0b42e8a1b1..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posx.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posy.jpg b/examples/widgets/graphicsview/boxes/cubemap_posy.jpg
deleted file mode 100644
index 2aca9b1e98..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posy.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posz.jpg b/examples/widgets/graphicsview/boxes/cubemap_posz.jpg
deleted file mode 100644
index 2e49173848..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posz.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/dotted.fsh b/examples/widgets/graphicsview/boxes/dotted.fsh
deleted file mode 100644
index 5cbf590e21..0000000000
--- a/examples/widgets/graphicsview/boxes/dotted.fsh
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-
-void main()
-{
- vec3 N = normalize(normal);
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- // assume directional light
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- float r1 = length(fract(7.0 * gl_TexCoord[1].xyz) - 0.5);
- float r2 = length(fract(5.0 * gl_TexCoord[1].xyz + 0.2) - 0.5);
- float r3 = length(fract(11.0 * gl_TexCoord[1].xyz + 0.7) - 0.5);
- vec4 rs = vec4(r1, r2, r3, 0.0);
-
- vec4 unlitColor = gl_Color * (0.8 - clamp(10.0 * (0.4 - rs), 0.0, 0.2));
- unlitColor.w = 1.0;
- gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-}
diff --git a/examples/widgets/graphicsview/boxes/fresnel.fsh b/examples/widgets/graphicsview/boxes/fresnel.fsh
deleted file mode 100644
index 6758ad5770..0000000000
--- a/examples/widgets/graphicsview/boxes/fresnel.fsh
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform samplerCube env;
-uniform mat4 view;
-uniform vec4 basicColor;
-
-void main()
-{
- vec3 N = normalize(normal);
- // assume directional light
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- vec3 absN = abs(gl_TexCoord[1].xyz);
- vec3 texCoord;
- if (absN.x > absN.y && absN.x > absN.z)
- texCoord = gl_TexCoord[1].yzx;
- else if (absN.y > absN.z)
- texCoord = gl_TexCoord[1].zxy;
- else
- texCoord = gl_TexCoord[1].xyz;
- texCoord.y *= -sign(texCoord.z);
- texCoord += 0.5;
-
- vec4 texColor = texture2D(tex, texCoord.xy);
- vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w);
- vec4 litColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-
- vec3 R = 2.0 * dot(-position, N) * N + position;
- vec4 reflectedColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz));
- gl_FragColor = mix(litColor, reflectedColor, 0.2 + 0.8 * pow(1.0 + dot(N, normalize(position)), 2.0));
-}
diff --git a/examples/widgets/graphicsview/boxes/glass.fsh b/examples/widgets/graphicsview/boxes/glass.fsh
deleted file mode 100644
index 528d04e4d3..0000000000
--- a/examples/widgets/graphicsview/boxes/glass.fsh
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform samplerCube env;
-uniform mat4 view;
-
-// Some arbitrary values
-// Arrays don't work here on glsl < 120, apparently.
-//const float coeffs[6] = float[6](1.0/4.0, 1.0/4.1, 1.0/4.2, 1.0/4.3, 1.0/4.4, 1.0/4.5);
-float coeffs(int i)
-{
- return 1.0 / (3.0 + 0.1 * float(i));
-}
-
-void main()
-{
- vec3 N = normalize(normal);
- vec3 I = -normalize(position);
- mat3 V = mat3(view[0].xyz, view[1].xyz, view[2].xyz);
- float IdotN = dot(I, N);
- float scales[6];
- vec3 C[6];
- for (int i = 0; i < 6; ++i) {
- scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN)));
- C[i] = textureCube(env, (-I + coeffs(i) * N) * V).xyz;
- }
- vec4 refractedColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y,
- C[3].z + 2.0*C[4].z + C[5].z, 4.0);
-
- vec3 R = 2.0 * dot(-position, N) * N + position;
- vec4 reflectedColor = textureCube(env, R * V);
-
- gl_FragColor = mix(refractedColor, reflectedColor, 0.4 + 0.6 * pow(1.0 - IdotN, 2.0));
-}
diff --git a/examples/widgets/graphicsview/boxes/glbuffers.cpp b/examples/widgets/graphicsview/boxes/glbuffers.cpp
deleted file mode 100644
index 91de336af3..0000000000
--- a/examples/widgets/graphicsview/boxes/glbuffers.cpp
+++ /dev/null
@@ -1,406 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "glbuffers.h"
-
-void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
-{
- const GLdouble ymax = zNear * tan(qDegreesToRadians(fovy) / 2.0);
- const GLdouble ymin = -ymax;
- const GLdouble xmin = ymin * aspect;
- const GLdouble xmax = ymax * aspect;
- glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
-}
-
-//============================================================================//
-// GLTexture //
-//============================================================================//
-
-GLTexture::GLTexture()
-{
- glGenTextures(1, &m_texture);
-}
-
-GLTexture::~GLTexture()
-{
- glDeleteTextures(1, &m_texture);
-}
-
-//============================================================================//
-// GLTexture2D //
-//============================================================================//
-
-GLTexture2D::GLTexture2D(int width, int height)
-{
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, nullptr);
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
- glBindTexture(GL_TEXTURE_2D, 0);
-}
-
-
-GLTexture2D::GLTexture2D(const QString &fileName, int width, int height)
-{
- // TODO: Add error handling.
- QImage image(fileName);
-
- if (image.isNull()) {
- m_failed = true;
- return;
- }
-
- image = image.convertToFormat(QImage::Format_ARGB32);
-
- //qDebug() << "Image size:" << image.width() << "x" << image.height();
- if (width <= 0)
- width = image.width();
- if (height <= 0)
- height = image.height();
- if (width != image.width() || height != image.height())
- image = image.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
-
- glBindTexture(GL_TEXTURE_2D, m_texture);
-
- // Works on x86, so probably works on all little-endian systems.
- // Does it work on big-endian systems?
- glTexImage2D(GL_TEXTURE_2D, 0, 4, image.width(), image.height(), 0,
- GL_BGRA, GL_UNSIGNED_BYTE, image.bits());
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
- glBindTexture(GL_TEXTURE_2D, 0);
-}
-
-void GLTexture2D::load(int width, int height, QRgb *data)
-{
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, data);
- glBindTexture(GL_TEXTURE_2D, 0);
-}
-
-void GLTexture2D::bind()
-{
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glEnable(GL_TEXTURE_2D);
-}
-
-void GLTexture2D::unbind()
-{
- glBindTexture(GL_TEXTURE_2D, 0);
- glDisable(GL_TEXTURE_2D);
-}
-
-
-//============================================================================//
-// GLTexture3D //
-//============================================================================//
-
-GLTexture3D::GLTexture3D(int width, int height, int depth)
-{
- GLBUFFERS_ASSERT_OPENGL("GLTexture3D::GLTexture3D", glTexImage3D, return)
-
- glBindTexture(GL_TEXTURE_3D, m_texture);
- glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, nullptr);
-
- glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- //glTexParameteri(GL_TEXTURE_3D, GL_GENERATE_MIPMAP, GL_TRUE);
- glBindTexture(GL_TEXTURE_3D, 0);
-}
-
-void GLTexture3D::load(int width, int height, int depth, QRgb *data)
-{
- GLBUFFERS_ASSERT_OPENGL("GLTexture3D::load", glTexImage3D, return)
-
- glBindTexture(GL_TEXTURE_3D, m_texture);
- glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, data);
- glBindTexture(GL_TEXTURE_3D, 0);
-}
-
-void GLTexture3D::bind()
-{
- glBindTexture(GL_TEXTURE_3D, m_texture);
- glEnable(GL_TEXTURE_3D);
-}
-
-void GLTexture3D::unbind()
-{
- glBindTexture(GL_TEXTURE_3D, 0);
- glDisable(GL_TEXTURE_3D);
-}
-
-//============================================================================//
-// GLTextureCube //
-//============================================================================//
-
-GLTextureCube::GLTextureCube(int size)
-{
- glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
-
- for (int i = 0; i < 6; ++i)
- glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 4, size, size, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, nullptr);
-
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE);
- glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
-}
-
-GLTextureCube::GLTextureCube(const QStringList &fileNames, int size)
-{
- // TODO: Add error handling.
-
- glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
-
- int index = 0;
- for (const QString &file : fileNames) {
- QImage image(file);
- if (image.isNull()) {
- m_failed = true;
- break;
- }
-
- image = image.convertToFormat(QImage::Format_ARGB32);
-
- //qDebug() << "Image size:" << image.width() << "x" << image.height();
- if (size <= 0)
- size = image.width();
- if (size != image.width() || size != image.height())
- image = image.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
-
- // Works on x86, so probably works on all little-endian systems.
- // Does it work on big-endian systems?
- glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, image.width(), image.height(), 0,
- GL_BGRA, GL_UNSIGNED_BYTE, image.bits());
-
- if (++index == 6)
- break;
- }
-
- // Clear remaining faces.
- while (index < 6) {
- glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, size, size, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, nullptr);
- ++index;
- }
-
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE);
- glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
-}
-
-void GLTextureCube::load(int size, int face, QRgb *data)
-{
- glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
- glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, 4, size, size, 0,
- GL_BGRA, GL_UNSIGNED_BYTE, data);
- glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
-}
-
-void GLTextureCube::bind()
-{
- glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
- glEnable(GL_TEXTURE_CUBE_MAP);
-}
-
-void GLTextureCube::unbind()
-{
- glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
- glDisable(GL_TEXTURE_CUBE_MAP);
-}
-
-//============================================================================//
-// GLFrameBufferObject //
-//============================================================================//
-
-GLFrameBufferObject::GLFrameBufferObject(int width, int height)
- : m_width(width)
- , m_height(height)
-{
- GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::GLFrameBufferObject",
- glGenFramebuffersEXT && glGenRenderbuffersEXT && glBindRenderbufferEXT && glRenderbufferStorageEXT, return)
-
- // TODO: share depth buffers of same size
- glGenFramebuffersEXT(1, &m_fbo);
- //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glGenRenderbuffersEXT(1, &m_depthBuffer);
- glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer);
- glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, m_width, m_height);
- //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer);
- //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-}
-
-GLFrameBufferObject::~GLFrameBufferObject()
-{
- GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::~GLFrameBufferObject",
- glDeleteFramebuffersEXT && glDeleteRenderbuffersEXT, return)
-
- glDeleteFramebuffersEXT(1, &m_fbo);
- glDeleteRenderbuffersEXT(1, &m_depthBuffer);
-}
-
-void GLFrameBufferObject::setAsRenderTarget(bool state)
-{
- GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::setAsRenderTarget", glBindFramebufferEXT, return)
-
- if (state) {
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glPushAttrib(GL_VIEWPORT_BIT);
- glViewport(0, 0, m_width, m_height);
- } else {
- glPopAttrib();
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
- }
-}
-
-bool GLFrameBufferObject::isComplete()
-{
- GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::isComplete", glCheckFramebufferStatusEXT, return false)
-
- return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
-}
-
-//============================================================================//
-// GLRenderTargetCube //
-//============================================================================//
-
-GLRenderTargetCube::GLRenderTargetCube(int size)
- : GLTextureCube(size)
- , m_fbo(size, size)
-{
-}
-
-void GLRenderTargetCube::begin(int face)
-{
- GLBUFFERS_ASSERT_OPENGL("GLRenderTargetCube::begin",
- glFramebufferTexture2DEXT && glFramebufferRenderbufferEXT, return)
-
- m_fbo.setAsRenderTarget(true);
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
- GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, m_texture, 0);
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_fbo.m_depthBuffer);
-}
-
-void GLRenderTargetCube::end()
-{
- m_fbo.setAsRenderTarget(false);
-}
-
-void GLRenderTargetCube::getViewMatrix(QMatrix4x4& mat, int face)
-{
- if (face < 0 || face >= 6) {
- qWarning("GLRenderTargetCube::getViewMatrix: 'face' must be in the range [0, 6). (face == %d)", face);
- return;
- }
-
- static constexpr int perm[6][3] = {
- {2, 1, 0},
- {2, 1, 0},
- {0, 2, 1},
- {0, 2, 1},
- {0, 1, 2},
- {0, 1, 2},
- };
-
- static constexpr float signs[6][3] = {
- {-1.0f, -1.0f, -1.0f},
- {+1.0f, -1.0f, +1.0f},
- {+1.0f, +1.0f, -1.0f},
- {+1.0f, -1.0f, +1.0f},
- {+1.0f, -1.0f, -1.0f},
- {-1.0f, -1.0f, +1.0f},
- };
-
- mat.fill(0.0f);
- for (int i = 0; i < 3; ++i)
- mat(i, perm[face][i]) = signs[face][i];
- mat(3, 3) = 1.0f;
-}
-
-void GLRenderTargetCube::getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ)
-{
- static const QMatrix4x4 reference(
- 1.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, -1.0f, 0.0f);
-
- mat = reference;
- mat(2, 2) = (nearZ+farZ)/(nearZ-farZ);
- mat(2, 3) = 2.0f*nearZ*farZ/(nearZ-farZ);
-}
diff --git a/examples/widgets/graphicsview/boxes/glbuffers.h b/examples/widgets/graphicsview/boxes/glbuffers.h
deleted file mode 100644
index 4318e8ac24..0000000000
--- a/examples/widgets/graphicsview/boxes/glbuffers.h
+++ /dev/null
@@ -1,372 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 GLBUFFERS_H
-#define GLBUFFERS_H
-
-//#include <GL/glew.h>
-#include "glextensions.h"
-
-#include <QtWidgets>
-#include <QtOpenGL>
-
-#define BUFFER_OFFSET(i) ((char*)0 + (i))
-#define SIZE_OF_MEMBER(cls, member) sizeof(static_cast<cls *>(nullptr)->member)
-
-#define GLBUFFERS_ASSERT_OPENGL(prefix, assertion, returnStatement) \
-if (m_failed || !(assertion)) { \
- if (!m_failed) qCritical(prefix ": The necessary OpenGL functions are not available."); \
- m_failed = true; \
- returnStatement; \
-}
-
-void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
-
-QT_BEGIN_NAMESPACE
-class QMatrix4x4;
-QT_END_NAMESPACE
-
-class GLTexture
-{
-public:
- GLTexture();
- virtual ~GLTexture();
- virtual void bind() = 0;
- virtual void unbind() = 0;
- virtual bool failed() const {return m_failed;}
-protected:
- GLuint m_texture = 0;
- bool m_failed = false;
-};
-
-class GLFrameBufferObject
-{
-public:
- friend class GLRenderTargetCube;
- // friend class GLRenderTarget2D;
-
- GLFrameBufferObject(int width, int height);
- virtual ~GLFrameBufferObject();
- bool isComplete();
- virtual bool failed() const {return m_failed;}
-protected:
- void setAsRenderTarget(bool state = true);
- GLuint m_fbo = 0;
- GLuint m_depthBuffer = 0;
- int m_width, m_height;
- bool m_failed = false;
-};
-
-class GLTexture2D : public GLTexture
-{
-public:
- GLTexture2D(int width, int height);
- explicit GLTexture2D(const QString &fileName, int width = 0, int height = 0);
- void load(int width, int height, QRgb *data);
- void bind() override;
- void unbind() override;
-};
-
-class GLTexture3D : public GLTexture
-{
-public:
- GLTexture3D(int width, int height, int depth);
- // TODO: Implement function below
- //GLTexture3D(const QString& fileName, int width = 0, int height = 0);
- void load(int width, int height, int depth, QRgb *data);
- void bind() override;
- void unbind() override;
-};
-
-class GLTextureCube : public GLTexture
-{
-public:
- GLTextureCube(int size);
- explicit GLTextureCube(const QStringList &fileNames, int size = 0);
- void load(int size, int face, QRgb *data);
- void bind() override;
- void unbind() override;
-};
-
-// TODO: Define and implement class below
-//class GLRenderTarget2D : public GLTexture2D
-
-class GLRenderTargetCube : public GLTextureCube
-{
-public:
- GLRenderTargetCube(int size);
- // begin rendering to one of the cube's faces. 0 <= face < 6
- void begin(int face);
- // end rendering
- void end();
- bool failed() const override { return m_failed || m_fbo.failed(); }
-
- static void getViewMatrix(QMatrix4x4& mat, int face);
- static void getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ);
-private:
- GLFrameBufferObject m_fbo;
-};
-
-struct VertexDescription
-{
- enum
- {
- Null = 0, // Terminates a VertexDescription array
- Position,
- TexCoord,
- Normal,
- Color,
- };
- int field; // Position, TexCoord, Normal, Color
- int type; // GL_FLOAT, GL_UNSIGNED_BYTE
- int count; // number of elements
- int offset; // field's offset into vertex struct
- int index; // 0 (unused at the moment)
-};
-
-// Implementation of interleaved buffers.
-// 'T' is a struct which must include a null-terminated static array
-// 'VertexDescription* description'.
-// Example:
-/*
-struct Vertex
-{
- GLfloat position[3];
- GLfloat texCoord[2];
- GLfloat normal[3];
- GLbyte color[4];
- static VertexDescription description[];
-};
-
-VertexDescription Vertex::description[] = {
- {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(Vertex, position) / sizeof(GLfloat), offsetof(Vertex, position), 0},
- {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(Vertex, texCoord) / sizeof(GLfloat), offsetof(Vertex, texCoord), 0},
- {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(Vertex, normal) / sizeof(GLfloat), offsetof(Vertex, normal), 0},
- {VertexDescription::Color, GL_BYTE, SIZE_OF_MEMBER(Vertex, color) / sizeof(GLbyte), offsetof(Vertex, color), 0},
- {VertexDescription::Null, 0, 0, 0, 0},
-};
-*/
-template<class T>
-class GLVertexBuffer
-{
-public:
- GLVertexBuffer(int length, const T *data = nullptr, int mode = GL_STATIC_DRAW)
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::GLVertexBuffer", glGenBuffers && glBindBuffer && glBufferData, return)
-
- glGenBuffers(1, &m_buffer);
- glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
- glBufferData(GL_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode);
- }
-
- ~GLVertexBuffer()
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::~GLVertexBuffer", glDeleteBuffers, return)
-
- glDeleteBuffers(1, &m_buffer);
- }
-
- void bind()
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::bind", glBindBuffer, return)
-
- glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
- for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) {
- switch (desc->field) {
- case VertexDescription::Position:
- glVertexPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset));
- glEnableClientState(GL_VERTEX_ARRAY);
- break;
- case VertexDescription::TexCoord:
- glTexCoordPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset));
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- break;
- case VertexDescription::Normal:
- glNormalPointer(desc->type, sizeof(T), BUFFER_OFFSET(desc->offset));
- glEnableClientState(GL_NORMAL_ARRAY);
- break;
- case VertexDescription::Color:
- glColorPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset));
- glEnableClientState(GL_COLOR_ARRAY);
- break;
- default:
- break;
- }
- }
- }
-
- void unbind()
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unbind", glBindBuffer, return)
-
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) {
- switch (desc->field) {
- case VertexDescription::Position:
- glDisableClientState(GL_VERTEX_ARRAY);
- break;
- case VertexDescription::TexCoord:
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- break;
- case VertexDescription::Normal:
- glDisableClientState(GL_NORMAL_ARRAY);
- break;
- case VertexDescription::Color:
- glDisableClientState(GL_COLOR_ARRAY);
- break;
- default:
- break;
- }
- }
- }
-
- int length() const {return m_length;}
-
- T *lock()
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::lock", glBindBuffer && glMapBuffer, return nullptr)
-
- glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
- //glBufferData(GL_ARRAY_BUFFER, m_length, NULL, m_mode);
- GLvoid* buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);
- m_failed = (buffer == nullptr);
- return reinterpret_cast<T *>(buffer);
- }
-
- void unlock()
- {
- GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unlock", glBindBuffer && glUnmapBuffer, return)
-
- glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
- glUnmapBuffer(GL_ARRAY_BUFFER);
- }
-
- bool failed()
- {
- return m_failed;
- }
-
-private:
- int m_length = 0;
- int m_mode = 0;
- GLuint m_buffer = 0;
- bool m_failed = false;
-};
-
-template<class T>
-class GLIndexBuffer
-{
-public:
- GLIndexBuffer(int length, const T *data = nullptr, int mode = GL_STATIC_DRAW)
- : m_length(0)
- , m_mode(mode)
- , m_buffer(0)
- , m_failed(false)
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::GLIndexBuffer", glGenBuffers && glBindBuffer && glBufferData, return)
-
- glGenBuffers(1, &m_buffer);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode);
- }
-
- ~GLIndexBuffer()
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::~GLIndexBuffer", glDeleteBuffers, return)
-
- glDeleteBuffers(1, &m_buffer);
- }
-
- void bind()
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::bind", glBindBuffer, return)
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
- }
-
- void unbind()
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unbind", glBindBuffer, return)
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- }
-
- int length() const {return m_length;}
-
- T *lock()
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::lock", glBindBuffer && glMapBuffer, return nullptr)
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
- GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE);
- m_failed = (buffer == nullptr);
- return reinterpret_cast<T *>(buffer);
- }
-
- void unlock()
- {
- GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unlock", glBindBuffer && glUnmapBuffer, return)
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
- glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
- }
-
- bool failed()
- {
- return m_failed;
- }
-
-private:
- int m_length, m_mode;
- GLuint m_buffer;
- bool m_failed;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/glextensions.cpp b/examples/widgets/graphicsview/boxes/glextensions.cpp
deleted file mode 100644
index ac89911046..0000000000
--- a/examples/widgets/graphicsview/boxes/glextensions.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "glextensions.h"
-
-#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f))));
-
-bool GLExtensionFunctions::resolve(const QGLContext *context)
-{
- bool ok = true;
-
- RESOLVE_GL_FUNC(GenFramebuffersEXT)
- RESOLVE_GL_FUNC(GenRenderbuffersEXT)
- RESOLVE_GL_FUNC(BindRenderbufferEXT)
- RESOLVE_GL_FUNC(RenderbufferStorageEXT)
- RESOLVE_GL_FUNC(DeleteFramebuffersEXT)
- RESOLVE_GL_FUNC(DeleteRenderbuffersEXT)
- RESOLVE_GL_FUNC(BindFramebufferEXT)
- RESOLVE_GL_FUNC(FramebufferTexture2DEXT)
- RESOLVE_GL_FUNC(FramebufferRenderbufferEXT)
- RESOLVE_GL_FUNC(CheckFramebufferStatusEXT)
-
- RESOLVE_GL_FUNC(ActiveTexture)
- RESOLVE_GL_FUNC(TexImage3D)
-
- RESOLVE_GL_FUNC(GenBuffers)
- RESOLVE_GL_FUNC(BindBuffer)
- RESOLVE_GL_FUNC(BufferData)
- RESOLVE_GL_FUNC(DeleteBuffers)
- RESOLVE_GL_FUNC(MapBuffer)
- RESOLVE_GL_FUNC(UnmapBuffer)
-
- return ok;
-}
-
-bool GLExtensionFunctions::fboSupported() {
- return GenFramebuffersEXT
- && GenRenderbuffersEXT
- && BindRenderbufferEXT
- && RenderbufferStorageEXT
- && DeleteFramebuffersEXT
- && DeleteRenderbuffersEXT
- && BindFramebufferEXT
- && FramebufferTexture2DEXT
- && FramebufferRenderbufferEXT
- && CheckFramebufferStatusEXT;
-}
-
-bool GLExtensionFunctions::openGL15Supported() {
- return ActiveTexture
- && TexImage3D
- && GenBuffers
- && BindBuffer
- && BufferData
- && DeleteBuffers
- && MapBuffer
- && UnmapBuffer;
-}
-
-#undef RESOLVE_GL_FUNC
diff --git a/examples/widgets/graphicsview/boxes/glextensions.h b/examples/widgets/graphicsview/boxes/glextensions.h
deleted file mode 100644
index 685700d866..0000000000
--- a/examples/widgets/graphicsview/boxes/glextensions.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 GLEXTENSIONS_H
-#define GLEXTENSIONS_H
-
-#include <QtOpenGL>
-
-/*
-Functions resolved:
-
-glGenFramebuffersEXT
-glGenRenderbuffersEXT
-glBindRenderbufferEXT
-glRenderbufferStorageEXT
-glDeleteFramebuffersEXT
-glDeleteRenderbuffersEXT
-glBindFramebufferEXT
-glFramebufferTexture2DEXT
-glFramebufferRenderbufferEXT
-glCheckFramebufferStatusEXT
-
-glActiveTexture
-glTexImage3D
-
-glGenBuffers
-glBindBuffer
-glBufferData
-glDeleteBuffers
-glMapBuffer
-glUnmapBuffer
-*/
-
-#ifndef APIENTRY
-# define APIENTRY
-#endif
-#ifndef APIENTRYP
-# define APIENTRYP APIENTRY *
-#endif
-
-#ifndef GL_VERSION_1_2
-#define GL_TEXTURE_3D 0x806F
-#define GL_TEXTURE_WRAP_R 0x8072
-#define GL_CLAMP_TO_EDGE 0x812F
-#define GL_BGRA 0x80E1
-#endif
-
-#ifndef GL_VERSION_1_3
-#define GL_TEXTURE0 0x84C0
-#define GL_TEXTURE1 0x84C1
-#define GL_TEXTURE2 0x84C2
-#define GL_TEXTURE_CUBE_MAP 0x8513
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
-//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
-//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
-//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
-//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
-//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-typedef ptrdiff_t GLsizeiptrARB;
-#endif
-
-#ifndef GL_VERSION_1_5
-#define GL_ARRAY_BUFFER 0x8892
-#define GL_ELEMENT_ARRAY_BUFFER 0x8893
-#define GL_READ_WRITE 0x88BA
-#define GL_STATIC_DRAW 0x88E4
-#endif
-
-#ifndef GL_EXT_framebuffer_object
-#define GL_RENDERBUFFER_EXT 0x8D41
-#define GL_FRAMEBUFFER_EXT 0x8D40
-#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5
-#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
-#define GL_DEPTH_ATTACHMENT_EXT 0x8D00
-#endif
-
-typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei, GLuint *);
-typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei, GLuint *);
-typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum, GLuint);
-typedef void (APIENTRY *_glRenderbufferStorageEXT) (GLenum, GLenum, GLsizei, GLsizei);
-typedef void (APIENTRY *_glDeleteFramebuffersEXT) (GLsizei, const GLuint*);
-typedef void (APIENTRY *_glDeleteRenderbuffersEXT) (GLsizei, const GLuint*);
-typedef void (APIENTRY *_glBindFramebufferEXT) (GLenum, GLuint);
-typedef void (APIENTRY *_glFramebufferTexture2DEXT) (GLenum, GLenum, GLenum, GLuint, GLint);
-typedef void (APIENTRY *_glFramebufferRenderbufferEXT) (GLenum, GLenum, GLenum, GLuint);
-typedef GLenum (APIENTRY *_glCheckFramebufferStatusEXT) (GLenum);
-
-typedef void (APIENTRY *_glActiveTexture) (GLenum);
-typedef void (APIENTRY *_glTexImage3D) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-
-typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *);
-typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint);
-typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
-typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *);
-typedef void *(APIENTRY *_glMapBuffer) (GLenum, GLenum);
-typedef GLboolean (APIENTRY *_glUnmapBuffer) (GLenum);
-
-struct GLExtensionFunctions
-{
- bool resolve(const QGLContext *context);
-
- bool fboSupported();
- bool openGL15Supported(); // the rest: multi-texture, 3D-texture, vertex buffer objects
-
- _glGenFramebuffersEXT GenFramebuffersEXT;
- _glGenRenderbuffersEXT GenRenderbuffersEXT;
- _glBindRenderbufferEXT BindRenderbufferEXT;
- _glRenderbufferStorageEXT RenderbufferStorageEXT;
- _glDeleteFramebuffersEXT DeleteFramebuffersEXT;
- _glDeleteRenderbuffersEXT DeleteRenderbuffersEXT;
- _glBindFramebufferEXT BindFramebufferEXT;
- _glFramebufferTexture2DEXT FramebufferTexture2DEXT;
- _glFramebufferRenderbufferEXT FramebufferRenderbufferEXT;
- _glCheckFramebufferStatusEXT CheckFramebufferStatusEXT;
-
- _glActiveTexture ActiveTexture;
- _glTexImage3D TexImage3D;
-
- _glGenBuffers GenBuffers;
- _glBindBuffer BindBuffer;
- _glBufferData BufferData;
- _glDeleteBuffers DeleteBuffers;
- _glMapBuffer MapBuffer;
- _glUnmapBuffer UnmapBuffer;
-};
-
-inline GLExtensionFunctions &getGLExtensionFunctions()
-{
- static GLExtensionFunctions funcs;
- return funcs;
-}
-
-#define glGenFramebuffersEXT getGLExtensionFunctions().GenFramebuffersEXT
-#define glGenRenderbuffersEXT getGLExtensionFunctions().GenRenderbuffersEXT
-#define glBindRenderbufferEXT getGLExtensionFunctions().BindRenderbufferEXT
-#define glRenderbufferStorageEXT getGLExtensionFunctions().RenderbufferStorageEXT
-#define glDeleteFramebuffersEXT getGLExtensionFunctions().DeleteFramebuffersEXT
-#define glDeleteRenderbuffersEXT getGLExtensionFunctions().DeleteRenderbuffersEXT
-#define glBindFramebufferEXT getGLExtensionFunctions().BindFramebufferEXT
-#define glFramebufferTexture2DEXT getGLExtensionFunctions().FramebufferTexture2DEXT
-#define glFramebufferRenderbufferEXT getGLExtensionFunctions().FramebufferRenderbufferEXT
-#define glCheckFramebufferStatusEXT getGLExtensionFunctions().CheckFramebufferStatusEXT
-
-#define glActiveTexture getGLExtensionFunctions().ActiveTexture
-#define glTexImage3D getGLExtensionFunctions().TexImage3D
-
-#define glGenBuffers getGLExtensionFunctions().GenBuffers
-#define glBindBuffer getGLExtensionFunctions().BindBuffer
-#define glBufferData getGLExtensionFunctions().BufferData
-#define glDeleteBuffers getGLExtensionFunctions().DeleteBuffers
-#define glMapBuffer getGLExtensionFunctions().MapBuffer
-#define glUnmapBuffer getGLExtensionFunctions().UnmapBuffer
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/gltrianglemesh.h b/examples/widgets/graphicsview/boxes/gltrianglemesh.h
deleted file mode 100644
index e5c4f51514..0000000000
--- a/examples/widgets/graphicsview/boxes/gltrianglemesh.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 GLTRIANGLEMESH_H
-#define GLTRIANGLEMESH_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-
-#include <QtWidgets>
-#include <QtOpenGL>
-
-
-template<class TVertex, class TIndex>
-class GLTriangleMesh
-{
-public:
- GLTriangleMesh(int vertexCount, int indexCount) : m_vb(vertexCount), m_ib(indexCount)
- {
- }
-
- virtual ~GLTriangleMesh()
- {
- }
-
- virtual void draw()
- {
- if (failed())
- return;
-
- int type = GL_UNSIGNED_INT;
- if (sizeof(TIndex) == sizeof(char)) type = GL_UNSIGNED_BYTE;
- if (sizeof(TIndex) == sizeof(short)) type = GL_UNSIGNED_SHORT;
-
- m_vb.bind();
- m_ib.bind();
- glDrawElements(GL_TRIANGLES, m_ib.length(), type, BUFFER_OFFSET(0));
- m_vb.unbind();
- m_ib.unbind();
- }
-
- bool failed()
- {
- return m_vb.failed() || m_ib.failed();
- }
-protected:
- GLVertexBuffer<TVertex> m_vb;
- GLIndexBuffer<TIndex> m_ib;
-};
-
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/granite.fsh b/examples/widgets/graphicsview/boxes/granite.fsh
deleted file mode 100644
index 5dcde5d2b1..0000000000
--- a/examples/widgets/graphicsview/boxes/granite.fsh
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform sampler3D noise;
-
-//const vec4 graniteColors[3] = {vec4(0.0, 0.0, 0.0, 1), vec4(0.30, 0.15, 0.10, 1), vec4(0.80, 0.70, 0.75, 1)};
-uniform vec4 graniteColors[3];
-
-float steep(float x)
-{
- return clamp(5.0 * x - 2.0, 0.0, 1.0);
-}
-
-void main()
-{
- vec2 turbulence = vec2(0, 0);
- float scale = 1.0;
- for (int i = 0; i < 4; ++i) {
- turbulence += scale * (texture3D(noise, gl_TexCoord[1].xyz / scale).xy - 0.5);
- scale *= 0.5;
- }
-
- vec3 N = normalize(normal);
- // assume directional light
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- vec4 unlitColor = mix(graniteColors[1], mix(graniteColors[0], graniteColors[2], steep(0.5 + turbulence.y)), 4.0 * abs(turbulence.x));
- gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-}
diff --git a/examples/widgets/graphicsview/boxes/main.cpp b/examples/widgets/graphicsview/boxes/main.cpp
deleted file mode 100644
index 2b3e6d3389..0000000000
--- a/examples/widgets/graphicsview/boxes/main.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "glextensions.h"
-#include "scene.h"
-
-#include <QGLWidget>
-#include <QtWidgets>
-
-class GraphicsView : public QGraphicsView
-{
-public:
- GraphicsView()
- {
- setWindowTitle(tr("Boxes"));
- setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
- //setRenderHints(QPainter::SmoothPixmapTransform);
- }
-
-protected:
- void resizeEvent(QResizeEvent *event) override {
- if (scene())
- scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));
- QGraphicsView::resizeEvent(event);
- }
-};
-
-inline bool matchString(const char *extensionString, const char *subString)
-{
- int subStringLength = strlen(subString);
- return (strncmp(extensionString, subString, subStringLength) == 0)
- && ((extensionString[subStringLength] == ' ') || (extensionString[subStringLength] == '\0'));
-}
-
-bool necessaryExtensionsSupported()
-{
- const char *extensionString = reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS));
- const char *p = extensionString;
-
- const int GL_EXT_FBO = 1;
- const int GL_ARB_VS = 2;
- const int GL_ARB_FS = 4;
- const int GL_ARB_SO = 8;
- int extensions = 0;
-
- while (*p) {
- if (matchString(p, "GL_EXT_framebuffer_object"))
- extensions |= GL_EXT_FBO;
- else if (matchString(p, "GL_ARB_vertex_shader"))
- extensions |= GL_ARB_VS;
- else if (matchString(p, "GL_ARB_fragment_shader"))
- extensions |= GL_ARB_FS;
- else if (matchString(p, "GL_ARB_shader_objects"))
- extensions |= GL_ARB_SO;
- while ((*p != ' ') && (*p != '\0'))
- ++p;
- if (*p == ' ')
- ++p;
- }
- return (extensions == 15);
-}
-
-int main(int argc, char **argv)
-{
- QApplication app(argc, argv);
-
- if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_5) == 0) {
- QMessageBox::critical(nullptr, "OpenGL features missing",
- "OpenGL version 1.5 or higher is required to run this demo.\n"
- "The program will now exit.");
- return -1;
- }
-
- int maxTextureSize = 1024;
- QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers));
- widget->makeCurrent();
-
- if (!necessaryExtensionsSupported()) {
- QMessageBox::critical(nullptr, "OpenGL features missing",
- "The OpenGL extensions required to run this demo are missing.\n"
- "The program will now exit.");
- delete widget;
- return -2;
- }
-
- // Check if all the necessary functions are resolved.
- if (!getGLExtensionFunctions().resolve(widget->context())) {
- QMessageBox::critical(nullptr, "OpenGL features missing",
- "Failed to resolve OpenGL functions required to run this demo.\n"
- "The program will now exit.");
- delete widget;
- return -3;
- }
-
- // TODO: Make conditional for final release
- QMessageBox::information(nullptr, "For your information",
- "This demo can be GPU and CPU intensive and may\n"
- "work poorly or not at all on your system.");
-
- widget->makeCurrent(); // The current context must be set before calling Scene's constructor
- Scene scene(1024, 768, maxTextureSize);
- GraphicsView view;
- view.setViewport(widget);
- view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
- view.setScene(&scene);
- view.show();
-
- return app.exec();
-}
-
diff --git a/examples/widgets/graphicsview/boxes/marble.fsh b/examples/widgets/graphicsview/boxes/marble.fsh
deleted file mode 100644
index c0b1980a67..0000000000
--- a/examples/widgets/graphicsview/boxes/marble.fsh
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform sampler3D noise;
-
-//const vec4 marbleColors[2] = {vec4(0.9, 0.9, 0.9, 1), vec4(0.6, 0.5, 0.5, 1)};
-uniform vec4 marbleColors[2];
-
-void main()
-{
- float turbulence = 0.0;
- float scale = 1.0;
- for (int i = 0; i < 4; ++i) {
- turbulence += scale * (texture3D(noise, 0.125 * gl_TexCoord[1].xyz / scale).x - 0.5);
- scale *= 0.5;
- }
-
- vec3 N = normalize(normal);
- // assume directional light
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- vec4 unlitColor = mix(marbleColors[0], marbleColors[1], exp(-4.0 * abs(turbulence)));
- gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-}
diff --git a/examples/widgets/graphicsview/boxes/parameters.par b/examples/widgets/graphicsview/boxes/parameters.par
deleted file mode 100644
index 50e20739b9..0000000000
--- a/examples/widgets/graphicsview/boxes/parameters.par
+++ /dev/null
@@ -1,5 +0,0 @@
-color basicColor ff0e3d0e
-color woodColors ff5e3d33 ffcc9966
-float woodTubulence 0.1
-color graniteColors ff000000 ff4d261a ffccb3bf
-color marbleColors ffe6e6e6 ff998080
diff --git a/examples/widgets/graphicsview/boxes/qt-logo.jpg b/examples/widgets/graphicsview/boxes/qt-logo.jpg
deleted file mode 100644
index 8d7fab052a..0000000000
--- a/examples/widgets/graphicsview/boxes/qt-logo.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/qt-logo.png b/examples/widgets/graphicsview/boxes/qt-logo.png
deleted file mode 100644
index 0b0b15480c..0000000000
--- a/examples/widgets/graphicsview/boxes/qt-logo.png
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/qtbox.cpp b/examples/widgets/graphicsview/boxes/qtbox.cpp
deleted file mode 100644
index 8713aac05d..0000000000
--- a/examples/widgets/graphicsview/boxes/qtbox.cpp
+++ /dev/null
@@ -1,470 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "qtbox.h"
-
-constexpr qreal ROTATE_SPEED_X = 30.0 / 1000.0;
-constexpr qreal ROTATE_SPEED_Y = 20.0 / 1000.0;
-constexpr qreal ROTATE_SPEED_Z = 40.0 / 1000.0;
-constexpr int MAX_ITEM_SIZE = 512;
-constexpr int MIN_ITEM_SIZE = 16;
-
-//============================================================================//
-// ItemBase //
-//============================================================================//
-
-ItemBase::ItemBase(int size, int x, int y) : m_size(size), m_startTime(QTime::currentTime())
-{
- setFlag(QGraphicsItem::ItemIsMovable, true);
- setFlag(QGraphicsItem::ItemIsSelectable, true);
- setFlag(QGraphicsItem::ItemIsFocusable, true);
- setAcceptHoverEvents(true);
- setPos(x, y);
-}
-
-QRectF ItemBase::boundingRect() const
-{
- return QRectF(-m_size / 2, -m_size / 2, m_size, m_size);
-}
-
-void ItemBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
-{
- if (option->state & QStyle::State_Selected) {
- painter->setRenderHint(QPainter::Antialiasing, true);
- if (option->state & QStyle::State_HasFocus)
- painter->setPen(Qt::yellow);
- else
- painter->setPen(Qt::white);
- painter->drawRect(boundingRect());
-
- painter->drawLine(m_size / 2 - 9, m_size / 2, m_size / 2, m_size / 2 - 9);
- painter->drawLine(m_size / 2 - 6, m_size / 2, m_size / 2, m_size / 2 - 6);
- painter->drawLine(m_size / 2 - 3, m_size / 2, m_size / 2, m_size / 2 - 3);
-
- painter->setRenderHint(QPainter::Antialiasing, false);
- }
-}
-
-void ItemBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
-{
- if (!isSelected() && scene()) {
- scene()->clearSelection();
- setSelected(true);
- }
-
- QMenu menu;
- QAction *delAction = menu.addAction("Delete");
- QAction *newAction = menu.addAction("New");
- QAction *growAction = menu.addAction("Grow");
- QAction *shrinkAction = menu.addAction("Shrink");
-
- QAction *selectedAction = menu.exec(event->screenPos());
-
- if (selectedAction == delAction)
- deleteSelectedItems(scene());
- else if (selectedAction == newAction)
- duplicateSelectedItems(scene());
- else if (selectedAction == growAction)
- growSelectedItems(scene());
- else if (selectedAction == shrinkAction)
- shrinkSelectedItems(scene());
-}
-
-void ItemBase::duplicateSelectedItems(QGraphicsScene *scene)
-{
- if (!scene)
- return;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (QGraphicsItem *item : selected) {
- ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
- if (itemBase)
- scene->addItem(itemBase->createNew(itemBase->m_size, itemBase->pos().x() + itemBase->m_size, itemBase->pos().y()));
- }
-}
-
-void ItemBase::deleteSelectedItems(QGraphicsScene *scene)
-{
- if (!scene)
- return;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (QGraphicsItem *item : selected) {
- ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
- if (itemBase)
- delete itemBase;
- }
-}
-
-void ItemBase::growSelectedItems(QGraphicsScene *scene)
-{
- if (!scene)
- return;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (QGraphicsItem *item : selected) {
- ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
- if (itemBase) {
- itemBase->prepareGeometryChange();
- itemBase->m_size *= 2;
- if (itemBase->m_size > MAX_ITEM_SIZE)
- itemBase->m_size = MAX_ITEM_SIZE;
- }
- }
-}
-
-void ItemBase::shrinkSelectedItems(QGraphicsScene *scene)
-{
- if (!scene)
- return;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (QGraphicsItem *item : selected) {
- ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
- if (itemBase) {
- itemBase->prepareGeometryChange();
- itemBase->m_size /= 2;
- if (itemBase->m_size < MIN_ITEM_SIZE)
- itemBase->m_size = MIN_ITEM_SIZE;
- }
- }
-}
-
-void ItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- if (m_isResizing) {
- int dx = int(2.0 * event->pos().x());
- int dy = int(2.0 * event->pos().y());
- prepareGeometryChange();
- m_size = (dx > dy ? dx : dy);
- if (m_size < MIN_ITEM_SIZE)
- m_size = MIN_ITEM_SIZE;
- else if (m_size > MAX_ITEM_SIZE)
- m_size = MAX_ITEM_SIZE;
- } else {
- QGraphicsItem::mouseMoveEvent(event);
- }
-}
-
-void ItemBase::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- if (m_isResizing || (isInResizeArea(event->pos()) && isSelected()))
- setCursor(Qt::SizeFDiagCursor);
- else
- setCursor(Qt::ArrowCursor);
- QGraphicsItem::hoverMoveEvent(event);
-}
-
-void ItemBase::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- static qreal z = 0.0;
- setZValue(z += 1.0);
- if (event->button() == Qt::LeftButton && isInResizeArea(event->pos())) {
- m_isResizing = true;
- } else {
- QGraphicsItem::mousePressEvent(event);
- }
-}
-
-void ItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton && m_isResizing) {
- m_isResizing = false;
- } else {
- QGraphicsItem::mouseReleaseEvent(event);
- }
-}
-
-void ItemBase::keyPressEvent(QKeyEvent *event)
-{
- switch (event->key()) {
- case Qt::Key_Delete:
- deleteSelectedItems(scene());
- break;
- case Qt::Key_Insert:
- duplicateSelectedItems(scene());
- break;
- case Qt::Key_Plus:
- growSelectedItems(scene());
- break;
- case Qt::Key_Minus:
- shrinkSelectedItems(scene());
- break;
- default:
- QGraphicsItem::keyPressEvent(event);
- break;
- }
-}
-
-void ItemBase::wheelEvent(QGraphicsSceneWheelEvent *event)
-{
- prepareGeometryChange();
- m_size = int(m_size * qExp(-event->delta() / 600.0));
- m_size = qBound(MIN_ITEM_SIZE, m_size, MAX_ITEM_SIZE);
-}
-
-int ItemBase::type() const
-{
- return Type;
-}
-
-
-bool ItemBase::isInResizeArea(const QPointF &pos)
-{
- return (-pos.y() < pos.x() - m_size + 9);
-}
-
-//============================================================================//
-// QtBox //
-//============================================================================//
-
-QtBox::QtBox(int size, int x, int y) : ItemBase(size, x, y)
-{
- for (int i = 0; i < 8; ++i) {
- m_vertices[i].setX(i & 1 ? 0.5f : -0.5f);
- m_vertices[i].setY(i & 2 ? 0.5f : -0.5f);
- m_vertices[i].setZ(i & 4 ? 0.5f : -0.5f);
- }
- for (int i = 0; i < 4; ++i) {
- m_texCoords[i].setX(i & 1 ? 1.0f : 0.0f);
- m_texCoords[i].setY(i & 2 ? 1.0f : 0.0f);
- }
- m_normals[0] = QVector3D(-1.0f, 0.0f, 0.0f);
- m_normals[1] = QVector3D(1.0f, 0.0f, 0.0f);
- m_normals[2] = QVector3D(0.0f, -1.0f, 0.0f);
- m_normals[3] = QVector3D(0.0f, 1.0f, 0.0f);
- m_normals[4] = QVector3D(0.0f, 0.0f, -1.0f);
- m_normals[5] = QVector3D(0.0f, 0.0f, 1.0f);
-}
-
-QtBox::~QtBox()
-{
- delete m_texture;
-}
-
-ItemBase *QtBox::createNew(int size, int x, int y)
-{
- return new QtBox(size, x, y);
-}
-
-void QtBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- QRectF rect = boundingRect().translated(pos());
- float width = float(painter->device()->width());
- float height = float(painter->device()->height());
-
- float left = 2.0f * float(rect.left()) / width - 1.0f;
- float right = 2.0f * float(rect.right()) / width - 1.0f;
- float top = 1.0f - 2.0f * float(rect.top()) / height;
- float bottom = 1.0f - 2.0f * float(rect.bottom()) / height;
- float moveToRectMatrix[] = {
- 0.5f * (right - left), 0.0f, 0.0f, 0.0f,
- 0.0f, 0.5f * (bottom - top), 0.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.0f,
- 0.5f * (right + left), 0.5f * (bottom + top), 0.0f, 1.0f
- };
-
- painter->beginNativePainting();
-
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadMatrixf(moveToRectMatrix);
- qgluPerspective(60.0, 1.0, 0.01, 10.0);
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- glLoadIdentity();
-
- //glEnable(GL_DEPTH_TEST);
- glEnable(GL_CULL_FACE);
- glEnable(GL_LIGHTING);
- glEnable(GL_COLOR_MATERIAL);
- glEnable(GL_NORMALIZE);
-
- if (m_texture == nullptr)
- m_texture = new GLTexture2D(":/res/boxes/qt-logo.jpg", 64, 64);
- m_texture->bind();
- glEnable(GL_TEXTURE_2D);
-
- glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
- float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f};
- float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f};
- glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour);
- glLightfv(GL_LIGHT0, GL_POSITION, lightDir);
- glEnable(GL_LIGHT0);
-
- glTranslatef(0.0f, 0.0f, -1.5f);
- glRotatef(ROTATE_SPEED_X * m_startTime.msecsTo(QTime::currentTime()), 1.0f, 0.0f, 0.0f);
- glRotatef(ROTATE_SPEED_Y * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 1.0f, 0.0f);
- glRotatef(ROTATE_SPEED_Z * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 0.0f, 1.0f);
- int dt = m_startTime.msecsTo(QTime::currentTime());
- if (dt < 500)
- glScalef(dt / 500.0f, dt / 500.0f, dt / 500.0f);
-
- for (int dir = 0; dir < 3; ++dir) {
- glColor4f(1.0f, 1.0f, 1.0f, 1.0);
-
- glBegin(GL_TRIANGLE_STRIP);
- glNormal3fv(reinterpret_cast<float *>(&m_normals[2 * dir + 0]));
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 2; ++j) {
- glTexCoord2fv(reinterpret_cast<float *>(&m_texCoords[(j << 1) | i]));
- glVertex3fv(reinterpret_cast<float *>(&m_vertices[(i << ((dir + 2) % 3)) | (j << ((dir + 1) % 3))]));
- }
- }
- glEnd();
-
- glBegin(GL_TRIANGLE_STRIP);
- glNormal3fv(reinterpret_cast<float *>(&m_normals[2 * dir + 1]));
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 2; ++j) {
- glTexCoord2fv(reinterpret_cast<float *>(&m_texCoords[(j << 1) | i]));
- glVertex3fv(reinterpret_cast<float *>(&m_vertices[(1 << dir) | (i << ((dir + 1) % 3)) | (j << ((dir + 2) % 3))]));
- }
- }
- glEnd();
- }
- m_texture->unbind();
-
- //glDisable(GL_DEPTH_TEST);
- glDisable(GL_CULL_FACE);
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
- glDisable(GL_TEXTURE_2D);
- glDisable(GL_LIGHT0);
- glDisable(GL_NORMALIZE);
-
- glPopMatrix();
-
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
-
- painter->endNativePainting();
-
- ItemBase::paint(painter, option, widget);
-}
-
-//============================================================================//
-// CircleItem //
-//============================================================================//
-
-CircleItem::CircleItem(int size, int x, int y) : ItemBase(size, x, y)
- , m_color(QColor::fromHsv(QRandomGenerator::global()->bounded(360), 255, 255))
-{}
-
-void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- int dt = m_startTime.msecsTo(QTime::currentTime());
-
- qreal r0 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 3800) % 4000)));
- qreal r1 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 0) % 4000)));
- qreal r2 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 1800) % 4000)));
- qreal r3 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 2000) % 4000)));
-
- if (r0 > r1)
- r0 = 0.0;
- if (r2 > r3)
- r2 = 0.0;
-
- QPainterPath path;
- path.moveTo(r1, 0.0);
- path.arcTo(-r1, -r1, 2 * r1, 2 * r1, 0.0, 360.0);
- path.lineTo(r0, 0.0);
- path.arcTo(-r0, -r0, 2 * r0, 2 * r0, 0.0, -360.0);
- path.closeSubpath();
- path.moveTo(r3, 0.0);
- path.arcTo(-r3, -r3, 2 * r3, 2 * r3, 0.0, 360.0);
- path.lineTo(r0, 0.0);
- path.arcTo(-r2, -r2, 2 * r2, 2 * r2, 0.0, -360.0);
- path.closeSubpath();
- painter->setRenderHint(QPainter::Antialiasing, true);
- painter->setBrush(QBrush(m_color));
- painter->setPen(Qt::NoPen);
- painter->drawPath(path);
- painter->setBrush(Qt::NoBrush);
- painter->setPen(Qt::SolidLine);
- painter->setRenderHint(QPainter::Antialiasing, false);
-
- ItemBase::paint(painter, option, widget);
-}
-
-ItemBase *CircleItem::createNew(int size, int x, int y)
-{
- return new CircleItem(size, x, y);
-}
-
-//============================================================================//
-// SquareItem //
-//============================================================================//
-
-SquareItem::SquareItem(int size, int x, int y) : ItemBase(size, x, y)
- , m_image(QPixmap(":/res/boxes/square.jpg"))
-{}
-
-void SquareItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- int dt = m_startTime.msecsTo(QTime::currentTime());
- QTransform oldTransform = painter->worldTransform();
- int dtMod = dt % 2000;
- qreal amp = 0.002 * (dtMod < 1000 ? dtMod : 2000 - dtMod) - 1.0;
-
- qreal scale = 0.6 + 0.2 * amp * amp;
- painter->setWorldTransform(QTransform().rotate(15.0 * amp).scale(scale, scale), true);
-
- painter->drawPixmap(-m_size / 2, -m_size / 2, m_size, m_size, m_image);
-
- painter->setWorldTransform(oldTransform, false);
- ItemBase::paint(painter, option, widget);
-}
-
-ItemBase *SquareItem::createNew(int size, int x, int y)
-{
- return new SquareItem(size, x, y);
-}
diff --git a/examples/widgets/graphicsview/boxes/qtbox.h b/examples/widgets/graphicsview/boxes/qtbox.h
deleted file mode 100644
index 84c8cb1d93..0000000000
--- a/examples/widgets/graphicsview/boxes/qtbox.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 QTBOX_H
-#define QTBOX_H
-
-#include "glbuffers.h"
-
-#include <QtWidgets>
-#include <QVector3D>
-
-class ItemBase : public QGraphicsItem
-{
-public:
- enum { Type = UserType + 1 };
-
- ItemBase(int size, int x, int y);
- QRectF boundingRect() const override;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- virtual ItemBase *createNew(int size, int x, int y) = 0;
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
- void keyPressEvent(QKeyEvent *event) override;
- void wheelEvent(QGraphicsSceneWheelEvent *event) override;
- int type() const override;
- bool isInResizeArea(const QPointF &pos);
-
- static void duplicateSelectedItems(QGraphicsScene *scene);
- static void deleteSelectedItems(QGraphicsScene *scene);
- static void growSelectedItems(QGraphicsScene *scene);
- static void shrinkSelectedItems(QGraphicsScene *scene);
-
- int m_size;
- QTime m_startTime;
- bool m_isResizing = false;
-};
-
-class QtBox : public ItemBase
-{
-public:
- QtBox(int size, int x, int y);
- virtual ~QtBox();
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-private:
- QVector3D m_vertices[8];
- QVector3D m_texCoords[4];
- QVector3D m_normals[6];
- GLTexture *m_texture = nullptr;
-};
-
-class CircleItem : public ItemBase
-{
-public:
- CircleItem(int size, int x, int y);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-
- QColor m_color;
-};
-
-class SquareItem : public ItemBase
-{
-public:
- SquareItem(int size, int x, int y);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-
- QPixmap m_image;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/reflection.fsh b/examples/widgets/graphicsview/boxes/reflection.fsh
deleted file mode 100644
index 0f0a26476f..0000000000
--- a/examples/widgets/graphicsview/boxes/reflection.fsh
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform samplerCube env;
-uniform mat4 view;
-
-void main()
-{
- vec3 N = normalize(normal);
- vec3 R = 2.0 * dot(-position, N) * N + position;
- gl_FragColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz));
-}
diff --git a/examples/widgets/graphicsview/boxes/refraction.fsh b/examples/widgets/graphicsview/boxes/refraction.fsh
deleted file mode 100644
index 8ba2d36329..0000000000
--- a/examples/widgets/graphicsview/boxes/refraction.fsh
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform samplerCube env;
-uniform mat4 view;
-
-// Arrays don't work here on glsl < 120, apparently.
-//const float coeffs[6] = float[6](1.0/2.0, 1.0/2.1, 1.0/2.2, 1.0/2.3, 1.0/2.4, 1.0/2.5);
-float coeffs(int i)
-{
- return 1.0 / (2.0 + 0.1 * float(i));
-}
-
-void main()
-{
- vec3 N = normalize(normal);
- vec3 I = -normalize(position);
- float IdotN = dot(I, N);
- float scales[6];
- vec3 C[6];
- for (int i = 0; i < 6; ++i) {
- scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN)));
- C[i] = textureCube(env, (-I + coeffs(i) * N) * mat3(view[0].xyz, view[1].xyz, view[2].xyz)).xyz;
- }
-
- gl_FragColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y,
- C[3].z + 2.0*C[4].z + C[5].z, 4.0);
-}
diff --git a/examples/widgets/graphicsview/boxes/roundedbox.cpp b/examples/widgets/graphicsview/boxes/roundedbox.cpp
deleted file mode 100644
index be96223b9f..0000000000
--- a/examples/widgets/graphicsview/boxes/roundedbox.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "roundedbox.h"
-
-//============================================================================//
-// P3T2N3Vertex //
-//============================================================================//
-
-VertexDescription P3T2N3Vertex::description[] = {
- {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, position) / sizeof(float), 0, 0},
- {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, texCoord) / sizeof(float), sizeof(QVector3D), 0},
- {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, normal) / sizeof(float), sizeof(QVector3D) + sizeof(QVector2D), 0},
-
- {VertexDescription::Null, 0, 0, 0, 0},
-};
-
-//============================================================================//
-// GLRoundedBox //
-//============================================================================//
-
-float lerp(float a, float b, float t)
-{
- return a * (1.0f - t) + b * t;
-}
-
-GLRoundedBox::GLRoundedBox(float r, float scale, int n)
- : GLTriangleMesh<P3T2N3Vertex, unsigned short>((n+2)*(n+3)*4, (n+1)*(n+1)*24+36+72*(n+1))
-{
- int vidx = 0, iidx = 0;
- int vertexCountPerCorner = (n + 2) * (n + 3) / 2;
-
- P3T2N3Vertex *vp = m_vb.lock();
- unsigned short *ip = m_ib.lock();
-
- if (!vp || !ip) {
- qWarning("GLRoundedBox::GLRoundedBox: Failed to lock vertex buffer and/or index buffer.");
- m_ib.unlock();
- m_vb.unlock();
- return;
- }
-
- for (int corner = 0; corner < 8; ++corner) {
- QVector3D centre(corner & 1 ? 1.0f : -1.0f,
- corner & 2 ? 1.0f : -1.0f,
- corner & 4 ? 1.0f : -1.0f);
- int winding = (corner & 1) ^ ((corner >> 1) & 1) ^ (corner >> 2);
- int offsX = ((corner ^ 1) - corner) * vertexCountPerCorner;
- int offsY = ((corner ^ 2) - corner) * vertexCountPerCorner;
- int offsZ = ((corner ^ 4) - corner) * vertexCountPerCorner;
-
- // Face polygons
- if (winding) {
- ip[iidx++] = vidx;
- ip[iidx++] = vidx + offsX;
- ip[iidx++] = vidx + offsY;
-
- ip[iidx++] = vidx + vertexCountPerCorner - n - 2;
- ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsY;
- ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsZ;
-
- ip[iidx++] = vidx + vertexCountPerCorner - 1;
- ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsZ;
- ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsX;
- }
-
- for (int i = 0; i < n + 2; ++i) {
-
- // Edge polygons
- if (winding && i < n + 1) {
- ip[iidx++] = vidx + i + 1;
- ip[iidx++] = vidx;
- ip[iidx++] = vidx + offsY + i + 1;
- ip[iidx++] = vidx + offsY;
- ip[iidx++] = vidx + offsY + i + 1;
- ip[iidx++] = vidx;
-
- ip[iidx++] = vidx + i;
- ip[iidx++] = vidx + 2 * i + 2;
- ip[iidx++] = vidx + i + offsX;
- ip[iidx++] = vidx + 2 * i + offsX + 2;
- ip[iidx++] = vidx + i + offsX;
- ip[iidx++] = vidx + 2 * i + 2;
-
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i;
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i;
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ;
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i + offsZ;
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ;
- ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i;
- }
-
- for (int j = 0; j <= i; ++j) {
- QVector3D normal = QVector3D(i - j, j, n + 1 - i).normalized();
- QVector3D offset(0.5f - r, 0.5f - r, 0.5f - r);
- QVector3D pos = centre * (offset + r * normal);
-
- vp[vidx].position = scale * pos;
- vp[vidx].normal = centre * normal;
- vp[vidx].texCoord = QVector2D(pos.x() + 0.5f, pos.y() + 0.5f);
-
- // Corner polygons
- if (i < n + 1) {
- ip[iidx++] = vidx;
- ip[iidx++] = vidx + i + 2 - winding;
- ip[iidx++] = vidx + i + 1 + winding;
- }
- if (i < n) {
- ip[iidx++] = vidx + i + 1 + winding;
- ip[iidx++] = vidx + i + 2 - winding;
- ip[iidx++] = vidx + 2 * i + 4;
- }
-
- ++vidx;
- }
- }
-
- }
-
- m_ib.unlock();
- m_vb.unlock();
-}
-
diff --git a/examples/widgets/graphicsview/boxes/roundedbox.h b/examples/widgets/graphicsview/boxes/roundedbox.h
deleted file mode 100644
index a1f15cd631..0000000000
--- a/examples/widgets/graphicsview/boxes/roundedbox.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 ROUNDEDBOX_H
-#define ROUNDEDBOX_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-#include "gltrianglemesh.h"
-
-#include <QVector2D>
-#include <QVector3D>
-
-struct P3T2N3Vertex
-{
- QVector3D position;
- QVector2D texCoord;
- QVector3D normal;
- static VertexDescription description[];
-};
-
-class GLRoundedBox : public GLTriangleMesh<P3T2N3Vertex, unsigned short>
-{
-public:
- // 0 < r < 0.5, 0 <= n <= 125
- explicit GLRoundedBox(float r = 0.25f, float scale = 1.0f, int n = 10);
-};
-
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp
deleted file mode 100644
index b344f65561..0000000000
--- a/examples/widgets/graphicsview/boxes/scene.cpp
+++ /dev/null
@@ -1,1028 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "scene.h"
-
-#include <QMatrix4x4>
-#include <QRandomGenerator>
-#include <QVector3D>
-#include <qmath.h>
-
-#include "3rdparty/fbm.h"
-
-//============================================================================//
-// ColorEdit //
-//============================================================================//
-
-ColorEdit::ColorEdit(QRgb initialColor, int id)
- : m_color(initialColor), m_id(id)
-{
- QHBoxLayout *layout = new QHBoxLayout;
- setLayout(layout);
- layout->setContentsMargins(0, 0, 0, 0);
-
- m_lineEdit = new QLineEdit(QString::number(m_color, 16));
- layout->addWidget(m_lineEdit);
-
- m_button = new QFrame;
- QPalette palette = m_button->palette();
- palette.setColor(QPalette::Window, QColor(m_color));
- m_button->setPalette(palette);
- m_button->setAutoFillBackground(true);
- m_button->setMinimumSize(32, 0);
- m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
- m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
- layout->addWidget(m_button);
-
- connect(m_lineEdit, &QLineEdit::editingFinished, this, &ColorEdit::editDone);
-}
-
-void ColorEdit::editDone()
-{
- bool ok;
- QRgb newColor = m_lineEdit->text().toUInt(&ok, 16);
- if (ok)
- setColor(newColor);
-}
-
-void ColorEdit::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton) {
- QColor color(m_color);
- QColorDialog dialog(color, nullptr);
- dialog.setOption(QColorDialog::ShowAlphaChannel, true);
- dialog.move(280, 120);
- if (dialog.exec() == QDialog::Rejected)
- return;
- QRgb newColor = dialog.selectedColor().rgba();
- if (newColor == m_color)
- return;
- setColor(newColor);
- }
-}
-
-void ColorEdit::setColor(QRgb color)
-{
- m_color = color;
- m_lineEdit->setText(QString::number(m_color, 16)); // "Clean up" text
- QPalette palette = m_button->palette();
- palette.setColor(QPalette::Window, QColor(m_color));
- m_button->setPalette(palette);
- emit colorChanged(m_color, m_id);
-}
-
-//============================================================================//
-// FloatEdit //
-//============================================================================//
-
-FloatEdit::FloatEdit(float initialValue, int id)
- : m_value(initialValue), m_id(id)
-{
- QHBoxLayout *layout = new QHBoxLayout;
- setLayout(layout);
- layout->setContentsMargins(0, 0, 0, 0);
-
- m_lineEdit = new QLineEdit(QString::number(m_value));
- layout->addWidget(m_lineEdit);
-
- connect(m_lineEdit, &QLineEdit::editingFinished, this, &FloatEdit::editDone);
-}
-
-void FloatEdit::editDone()
-{
- bool ok;
- float newValue = m_lineEdit->text().toFloat(&ok);
- if (ok) {
- m_value = newValue;
- m_lineEdit->setText(QString::number(m_value)); // "Clean up" text
- emit valueChanged(m_value, m_id);
- }
-}
-
-//============================================================================//
-// TwoSidedGraphicsWidget //
-//============================================================================//
-void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget)
-{
- if (index < 0 || index >= 2)
- {
- qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index);
- return;
- }
-
- GraphicsWidget *proxy = new GraphicsWidget;
- proxy->setWidget(widget);
-
- delete m_proxyWidgets[index];
- m_proxyWidgets[index] = proxy;
-
- proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache);
- proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items
-
- if (index != m_current)
- proxy->setVisible(false);
-
- qobject_cast<QGraphicsScene *>(parent())->addItem(proxy);
-}
-
-QWidget *TwoSidedGraphicsWidget::widget(int index)
-{
- if (index < 0 || index >= 2)
- {
- qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index);
- return nullptr;
- }
- return m_proxyWidgets[index]->widget();
-}
-
-void TwoSidedGraphicsWidget::flip()
-{
- m_delta = (m_current == 0 ? 9 : -9);
- animateFlip();
-}
-
-void TwoSidedGraphicsWidget::animateFlip()
-{
- m_angle += m_delta;
- if (m_angle == 90) {
- int old = m_current;
- m_current ^= 1;
- m_proxyWidgets[old]->setVisible(false);
- m_proxyWidgets[m_current]->setVisible(true);
- m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry());
- }
-
- QRectF r = m_proxyWidgets[m_current]->boundingRect();
- m_proxyWidgets[m_current]->setTransform(QTransform()
- .translate(r.width() / 2, r.height() / 2)
- .rotate(m_angle - 180 * m_current, Qt::YAxis)
- .translate(-r.width() / 2, -r.height() / 2));
-
- if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180))
- QTimer::singleShot(25, this, &TwoSidedGraphicsWidget::animateFlip);
-}
-
-QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value)
-{
- if (change == ItemPositionChange && scene()) {
- QRectF rect = boundingRect();
- QPointF pos = value.toPointF();
- QRectF sceneRect = scene()->sceneRect();
- if (pos.x() + rect.left() < sceneRect.left())
- pos.setX(sceneRect.left() - rect.left());
- else if (pos.x() + rect.right() >= sceneRect.right())
- pos.setX(sceneRect.right() - rect.right());
- if (pos.y() + rect.top() < sceneRect.top())
- pos.setY(sceneRect.top() - rect.top());
- else if (pos.y() + rect.bottom() >= sceneRect.bottom())
- pos.setY(sceneRect.bottom() - rect.bottom());
- return pos;
- }
- return QGraphicsProxyWidget::itemChange(change, value);
-}
-
-void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
-{
- setCacheMode(QGraphicsItem::NoCache);
- setCacheMode(QGraphicsItem::ItemCoordinateCache);
- QGraphicsProxyWidget::resizeEvent(event);
-}
-
-void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- painter->setRenderHint(QPainter::Antialiasing, false);
- QGraphicsProxyWidget::paint(painter, option, widget);
- //painter->setRenderHint(QPainter::Antialiasing, true);
-}
-
-//============================================================================//
-// RenderOptionsDialog //
-//============================================================================//
-
-RenderOptionsDialog::RenderOptionsDialog()
- : QDialog(nullptr, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
-{
- setWindowOpacity(0.75);
- setWindowTitle(tr("Options (double click to flip)"));
- QGridLayout *layout = new QGridLayout;
- setLayout(layout);
- layout->setColumnStretch(1, 1);
-
- int row = 0;
-
- QCheckBox *check = new QCheckBox(tr("Dynamic cube map"));
- check->setCheckState(Qt::Unchecked);
- // Dynamic cube maps are only enabled when multi-texturing and render to texture are available.
- check->setEnabled(glActiveTexture && glGenFramebuffersEXT);
- connect(check, &QCheckBox::stateChanged, this, &RenderOptionsDialog::dynamicCubemapToggled);
- layout->addWidget(check, 0, 0, 1, 2);
- ++row;
-
- // Load all .par files
- // .par files have a simple syntax for specifying user adjustable uniform variables.
- const QList<QFileInfo> files = QDir(QStringLiteral(":/res/boxes/"))
- .entryInfoList({ QStringLiteral("*.par") },
- QDir::Files | QDir::Readable);
-
- for (const QFileInfo &fileInfo : files) {
- QFile file(fileInfo.absoluteFilePath());
- if (file.open(QIODevice::ReadOnly)) {
- while (!file.atEnd()) {
- QList<QByteArray> tokens = file.readLine().simplified().split(' ');
- QList<QByteArray>::const_iterator it = tokens.begin();
- if (it == tokens.end())
- continue;
- QByteArray type = *it;
- if (++it == tokens.end())
- continue;
- QByteArray name = *it;
- bool singleElement = (tokens.size() == 3); // type, name and one value
- char counter[10] = "000000000";
- int counterPos = 8; // position of last digit
- while (++it != tokens.end()) {
- m_parameterNames << name;
- if (!singleElement) {
- m_parameterNames.back() += '[';
- m_parameterNames.back() += counter + counterPos;
- m_parameterNames.back() += ']';
- int j = 8; // position of last digit
- ++counter[j];
- while (j > 0 && counter[j] > '9') {
- counter[j] = '0';
- ++counter[--j];
- }
- if (j < counterPos)
- counterPos = j;
- }
-
- if (type == "color") {
- layout->addWidget(new QLabel(m_parameterNames.back()));
- bool ok;
- ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1);
- m_parameterEdits << colorEdit;
- layout->addWidget(colorEdit);
- connect(colorEdit, &ColorEdit::colorChanged, this, &RenderOptionsDialog::setColorParameter);
- ++row;
- } else if (type == "float") {
- layout->addWidget(new QLabel(m_parameterNames.back()));
- bool ok;
- FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1);
- m_parameterEdits << floatEdit;
- layout->addWidget(floatEdit);
- connect(floatEdit, &FloatEdit::valueChanged, this, &RenderOptionsDialog::setFloatParameter);
- ++row;
- }
- }
- }
- file.close();
- }
- }
-
- layout->addWidget(new QLabel(tr("Texture:")));
- m_textureCombo = new QComboBox;
- connect(m_textureCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &RenderOptionsDialog::textureChanged);
- layout->addWidget(m_textureCombo);
- ++row;
-
- layout->addWidget(new QLabel(tr("Shader:")));
- m_shaderCombo = new QComboBox;
- connect(m_shaderCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &RenderOptionsDialog::shaderChanged);
- layout->addWidget(m_shaderCombo);
- ++row;
-
- layout->setRowStretch(row, 1);
-}
-
-int RenderOptionsDialog::addTexture(const QString &name)
-{
- m_textureCombo->addItem(name);
- return m_textureCombo->count() - 1;
-}
-
-int RenderOptionsDialog::addShader(const QString &name)
-{
- m_shaderCombo->addItem(name);
- return m_shaderCombo->count() - 1;
-}
-
-void RenderOptionsDialog::emitParameterChanged()
-{
- for (ParameterEdit *edit : qAsConst(m_parameterEdits))
- edit->emitChange();
-}
-
-void RenderOptionsDialog::setColorParameter(QRgb color, int id)
-{
- emit colorParameterChanged(m_parameterNames[id], color);
-}
-
-void RenderOptionsDialog::setFloatParameter(float value, int id)
-{
- emit floatParameterChanged(m_parameterNames[id], value);
-}
-
-void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton)
- emit doubleClicked();
-}
-
-//============================================================================//
-// ItemDialog //
-//============================================================================//
-
-ItemDialog::ItemDialog()
- : QDialog(nullptr, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
-{
- setWindowTitle(tr("Items (double click to flip)"));
- setWindowOpacity(0.75);
- resize(160, 100);
-
- QVBoxLayout *layout = new QVBoxLayout;
- setLayout(layout);
- QPushButton *button;
-
- button = new QPushButton(tr("Add Qt box"));
- layout->addWidget(button);
- connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewQtBox);
-
- button = new QPushButton(tr("Add circle"));
- layout->addWidget(button);
- connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewCircleItem);
-
- button = new QPushButton(tr("Add square"));
- layout->addWidget(button);
- connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewSquareItem);
-
- layout->addStretch(1);
-}
-
-void ItemDialog::triggerNewQtBox()
-{
- emit newItemTriggered(QtBoxItem);
-}
-
-void ItemDialog::triggerNewCircleItem()
-{
- emit newItemTriggered(CircleItem);
-}
-
-void ItemDialog::triggerNewSquareItem()
-{
- emit newItemTriggered(SquareItem);
-}
-
-void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton)
- emit doubleClicked();
-}
-
-//============================================================================//
-// Scene //
-//============================================================================//
-
-const static char environmentShaderText[] =
- "uniform samplerCube env;"
- "void main() {"
- "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);"
- "}";
-
-Scene::Scene(int width, int height, int maxTextureSize)
- : m_distExp(600)
- , m_frame(0)
- , m_maxTextureSize(maxTextureSize)
- , m_currentShader(0)
- , m_currentTexture(0)
- , m_dynamicCubemap(false)
- , m_updateAllCubemaps(true)
- , m_box(nullptr)
- , m_vertexShader(nullptr)
- , m_environmentShader(nullptr)
- , m_environmentProgram(nullptr)
-{
- setSceneRect(0, 0, width, height);
-
- m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere);
- m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere);
- m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane);
-
- m_renderOptions = new RenderOptionsDialog;
- m_renderOptions->move(20, 120);
- m_renderOptions->resize(m_renderOptions->sizeHint());
-
- connect(m_renderOptions, &RenderOptionsDialog::dynamicCubemapToggled, this, &Scene::toggleDynamicCubemap);
- connect(m_renderOptions, &RenderOptionsDialog::colorParameterChanged, this, &Scene::setColorParameter);
- connect(m_renderOptions, &RenderOptionsDialog::floatParameterChanged, this, &Scene::setFloatParameter);
- connect(m_renderOptions, &RenderOptionsDialog::textureChanged, this, &Scene::setTexture);
- connect(m_renderOptions, &RenderOptionsDialog::shaderChanged, this, &Scene::setShader);
-
- m_itemDialog = new ItemDialog;
- connect(m_itemDialog, &ItemDialog::newItemTriggered, this, &Scene::newItem);
-
- TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this);
- twoSided->setWidget(0, m_renderOptions);
- twoSided->setWidget(1, m_itemDialog);
-
- connect(m_renderOptions, &RenderOptionsDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::flip);
- connect(m_itemDialog, &ItemDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::flip);
-
- addItem(new QtBox(64, width - 64, height - 64));
- addItem(new QtBox(64, width - 64, 64));
- addItem(new QtBox(64, 64, height - 64));
- addItem(new QtBox(64, 64, 64));
-
- initGL();
-
- m_timer = new QTimer(this);
- m_timer->setInterval(20);
- connect(m_timer, &QTimer::timeout, this, [this](){ update(); });
- m_timer->start();
-}
-
-Scene::~Scene()
-{
- delete m_box;
- qDeleteAll(m_textures);
- delete m_mainCubemap;
- qDeleteAll(m_programs);
- delete m_vertexShader;
- qDeleteAll(m_fragmentShaders);
- qDeleteAll(m_cubemaps);
- delete m_environmentShader;
- delete m_environmentProgram;
-}
-
-void Scene::initGL()
-{
- m_box = new GLRoundedBox(0.25f, 1.0f, 10);
-
- m_vertexShader = new QGLShader(QGLShader::Vertex);
- m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh"));
-
- QStringList list;
- list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg"
- << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg";
- m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize));
- m_environmentShader = new QGLShader(QGLShader::Fragment);
- m_environmentShader->compileSourceCode(environmentShaderText);
- m_environmentProgram = new QGLShaderProgram;
- m_environmentProgram->addShader(m_vertexShader);
- m_environmentProgram->addShader(m_environmentShader);
- m_environmentProgram->link();
-
- const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed
- m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE);
- QVector<QRgb> data(NOISE_SIZE * NOISE_SIZE * NOISE_SIZE, QRgb(0));
- QRgb *p = data.data();
- float pos[3];
- for (int k = 0; k < NOISE_SIZE; ++k) {
- pos[2] = k * (0x20 / (float)NOISE_SIZE);
- for (int j = 0; j < NOISE_SIZE; ++j) {
- for (int i = 0; i < NOISE_SIZE; ++i) {
- for (int byte = 0; byte < 4; ++byte) {
- pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE);
- pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE);
- *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8);
- }
- ++p;
- }
- }
- }
- m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data.data());
-
- m_mainCubemap = new GLRenderTargetCube(512);
-
- QList<QFileInfo> files;
-
- // Load all .png files as textures
- m_currentTexture = 0;
- files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.png") }, QDir::Files | QDir::Readable);
-
- for (const QFileInfo &file : qAsConst(files)) {
- GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize));
- if (texture->failed()) {
- delete texture;
- continue;
- }
- m_textures << texture;
- m_renderOptions->addTexture(file.baseName());
- }
-
- if (m_textures.size() == 0)
- m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize));
-
- // Load all .fsh files as fragment shaders
- m_currentShader = 0;
- files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.fsh") }, QDir::Files | QDir::Readable);
- for (const QFileInfo &file : qAsConst(files)) {
- QGLShaderProgram *program = new QGLShaderProgram;
- QGLShader* shader = new QGLShader(QGLShader::Fragment);
- shader->compileSourceFile(file.absoluteFilePath());
- // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards.
- program->addShader(m_vertexShader);
- program->addShader(shader);
- if (!program->link()) {
- qWarning("Failed to compile and link shader program");
- qWarning("Vertex shader log:");
- qWarning() << m_vertexShader->log();
- qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):";
- qWarning() << shader->log();
- qWarning("Shader program log:");
- qWarning() << program->log();
-
- delete shader;
- delete program;
- continue;
- }
-
- m_fragmentShaders << shader;
- m_programs << program;
- m_renderOptions->addShader(file.baseName());
-
- program->bind();
- m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : nullptr);
- program->release();
- }
-
- if (m_programs.size() == 0)
- m_programs << new QGLShaderProgram;
-
- m_renderOptions->emitParameterChanged();
-}
-
-static void loadMatrix(const QMatrix4x4 &m)
-{
- // static to prevent glLoadMatrixf to fail on certain drivers
- static GLfloat mat[16];
- const float *data = m.constData();
- for (int index = 0; index < 16; ++index)
- mat[index] = data[index];
- glLoadMatrixf(mat);
-}
-
-// If one of the boxes should not be rendered, set excludeBox to its index.
-// If the main box should not be rendered, set excludeBox to -1.
-void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox)
-{
- QMatrix4x4 invView = view.inverted();
-
- // If multi-texturing is supported, use three saplers.
- if (glActiveTexture) {
- glActiveTexture(GL_TEXTURE0);
- m_textures[m_currentTexture]->bind();
- glActiveTexture(GL_TEXTURE2);
- m_noise->bind();
- glActiveTexture(GL_TEXTURE1);
- } else {
- m_textures[m_currentTexture]->bind();
- }
-
- glDisable(GL_LIGHTING);
- glDisable(GL_CULL_FACE);
-
- QMatrix4x4 viewRotation(view);
- viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f;
- viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f;
- viewRotation(3, 3) = 1.0f;
- loadMatrix(viewRotation);
- glScalef(20.0f, 20.0f, 20.0f);
-
- // Don't render the environment if the environment texture can't be set for the correct sampler.
- if (glActiveTexture) {
- m_environment->bind();
- m_environmentProgram->bind();
- m_environmentProgram->setUniformValue("tex", GLint(0));
- m_environmentProgram->setUniformValue("env", GLint(1));
- m_environmentProgram->setUniformValue("noise", GLint(2));
- m_box->draw();
- m_environmentProgram->release();
- m_environment->unbind();
- }
-
- loadMatrix(view);
-
- glEnable(GL_CULL_FACE);
- glEnable(GL_LIGHTING);
-
- for (int i = 0; i < m_programs.size(); ++i) {
- if (i == excludeBox)
- continue;
-
- glPushMatrix();
- QMatrix4x4 m;
- m.rotate(m_trackBalls[1].rotation());
- glMultMatrixf(m.constData());
-
- glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f);
- glTranslatef(2.0f, 0.0f, 0.0f);
- glScalef(0.3f, 0.6f, 0.6f);
-
- if (glActiveTexture) {
- if (m_dynamicCubemap && m_cubemaps[i])
- m_cubemaps[i]->bind();
- else
- m_environment->bind();
- }
- m_programs[i]->bind();
- m_programs[i]->setUniformValue("tex", GLint(0));
- m_programs[i]->setUniformValue("env", GLint(1));
- m_programs[i]->setUniformValue("noise", GLint(2));
- m_programs[i]->setUniformValue("view", view);
- m_programs[i]->setUniformValue("invView", invView);
- m_box->draw();
- m_programs[i]->release();
-
- if (glActiveTexture) {
- if (m_dynamicCubemap && m_cubemaps[i])
- m_cubemaps[i]->unbind();
- else
- m_environment->unbind();
- }
- glPopMatrix();
- }
-
- if (-1 != excludeBox) {
- QMatrix4x4 m;
- m.rotate(m_trackBalls[0].rotation());
- glMultMatrixf(m.constData());
-
- if (glActiveTexture) {
- if (m_dynamicCubemap)
- m_mainCubemap->bind();
- else
- m_environment->bind();
- }
-
- m_programs[m_currentShader]->bind();
- m_programs[m_currentShader]->setUniformValue("tex", GLint(0));
- m_programs[m_currentShader]->setUniformValue("env", GLint(1));
- m_programs[m_currentShader]->setUniformValue("noise", GLint(2));
- m_programs[m_currentShader]->setUniformValue("view", view);
- m_programs[m_currentShader]->setUniformValue("invView", invView);
- m_box->draw();
- m_programs[m_currentShader]->release();
-
- if (glActiveTexture) {
- if (m_dynamicCubemap)
- m_mainCubemap->unbind();
- else
- m_environment->unbind();
- }
- }
-
- if (glActiveTexture) {
- glActiveTexture(GL_TEXTURE2);
- m_noise->unbind();
- glActiveTexture(GL_TEXTURE0);
- }
- m_textures[m_currentTexture]->unbind();
-}
-
-void Scene::setStates()
-{
- //glClearColor(0.25f, 0.25f, 0.5f, 1.0f);
-
- glEnable(GL_DEPTH_TEST);
- glEnable(GL_CULL_FACE);
- glEnable(GL_LIGHTING);
- //glEnable(GL_COLOR_MATERIAL);
- glEnable(GL_TEXTURE_2D);
- glEnable(GL_NORMALIZE);
-
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- glLoadIdentity();
-
- setLights();
-
- float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f};
- glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
- glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f);
-}
-
-void Scene::setLights()
-{
- glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
- //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f};
- float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f};
- //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour);
- //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour);
- glLightfv(GL_LIGHT0, GL_POSITION, lightDir);
- glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f);
- glEnable(GL_LIGHT0);
-}
-
-void Scene::defaultStates()
-{
- //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-
- glDisable(GL_DEPTH_TEST);
- glDisable(GL_CULL_FACE);
- glDisable(GL_LIGHTING);
- //glDisable(GL_COLOR_MATERIAL);
- glDisable(GL_TEXTURE_2D);
- glDisable(GL_LIGHT0);
- glDisable(GL_NORMALIZE);
-
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
-
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
-
- glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f);
- float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f};
- glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular);
- glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f);
-}
-
-void Scene::renderCubemaps()
-{
- // To speed things up, only update the cubemaps for the small cubes every N frames.
- const int N = (m_updateAllCubemaps ? 1 : 3);
-
- QMatrix4x4 mat;
- GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f);
-
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- loadMatrix(mat);
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
-
- QVector3D center;
-
- const float eachAngle = 2 * M_PI / m_cubemaps.size();
- for (int i = m_frame % N; i < m_cubemaps.size(); i += N) {
- if (0 == m_cubemaps[i])
- continue;
-
- float angle = i * eachAngle;
-
- center = m_trackBalls[1].rotation().rotatedVector(QVector3D(std::cos(angle), std::sin(angle), 0.0f));
-
- for (int face = 0; face < 6; ++face) {
- m_cubemaps[i]->begin(face);
-
- GLRenderTargetCube::getViewMatrix(mat, face);
- QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0);
- mat.setColumn(3, mat * v);
-
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- renderBoxes(mat, i);
-
- m_cubemaps[i]->end();
- }
- }
-
- for (int face = 0; face < 6; ++face) {
- m_mainCubemap->begin(face);
- GLRenderTargetCube::getViewMatrix(mat, face);
-
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- renderBoxes(mat, -1);
-
- m_mainCubemap->end();
- }
-
- glPopMatrix();
-
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
-
- m_updateAllCubemaps = false;
-}
-
-void Scene::drawBackground(QPainter *painter, const QRectF &)
-{
- float width = float(painter->device()->width());
- float height = float(painter->device()->height());
-
- painter->beginNativePainting();
- setStates();
-
- if (m_dynamicCubemap)
- renderCubemaps();
-
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- glMatrixMode(GL_PROJECTION);
- qgluPerspective(60.0, width / height, 0.01, 15.0);
-
- glMatrixMode(GL_MODELVIEW);
-
- QMatrix4x4 view;
- view.rotate(m_trackBalls[2].rotation());
- view(2, 3) -= 2.0f * std::exp(m_distExp / 1200.0f);
- renderBoxes(view);
-
- defaultStates();
- ++m_frame;
-
- painter->endNativePainting();
-}
-
-QPointF Scene::pixelPosToViewPos(const QPointF& p)
-{
- return QPointF(2.0 * float(p.x()) / width() - 1.0,
- 1.0 - 2.0 * float(p.y()) / height());
-}
-
-void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- QGraphicsScene::mouseMoveEvent(event);
- if (event->isAccepted())
- return;
-
- if (event->buttons() & Qt::LeftButton) {
- m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- } else {
- m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- }
-
- if (event->buttons() & Qt::RightButton) {
- m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- } else {
- m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- }
-
- if (event->buttons() & Qt::MidButton) {
- m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion());
- event->accept();
- } else {
- m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
- }
-}
-
-void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- QGraphicsScene::mousePressEvent(event);
- if (event->isAccepted())
- return;
-
- if (event->buttons() & Qt::LeftButton) {
- m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- }
-
- if (event->buttons() & Qt::RightButton) {
- m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- }
-
- if (event->buttons() & Qt::MidButton) {
- m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion());
- event->accept();
- }
-}
-
-void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- QGraphicsScene::mouseReleaseEvent(event);
- if (event->isAccepted())
- return;
-
- if (event->button() == Qt::LeftButton) {
- m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- }
-
- if (event->button() == Qt::RightButton) {
- m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- }
-
- if (event->button() == Qt::MidButton) {
- m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
- event->accept();
- }
-}
-
-void Scene::wheelEvent(QGraphicsSceneWheelEvent * event)
-{
- QGraphicsScene::wheelEvent(event);
- if (!event->isAccepted()) {
- m_distExp += event->delta();
- if (m_distExp < -8 * 120)
- m_distExp = -8 * 120;
- if (m_distExp > 10 * 120)
- m_distExp = 10 * 120;
- event->accept();
- }
-}
-
-void Scene::setShader(int index)
-{
- if (index >= 0 && index < m_fragmentShaders.size())
- m_currentShader = index;
-}
-
-void Scene::setTexture(int index)
-{
- if (index >= 0 && index < m_textures.size())
- m_currentTexture = index;
-}
-
-void Scene::toggleDynamicCubemap(int state)
-{
- if ((m_dynamicCubemap = (state == Qt::Checked)))
- m_updateAllCubemaps = true;
-}
-
-void Scene::setColorParameter(const QString &name, QRgb color)
-{
- // set the color in all programs
- for (QGLShaderProgram *program : qAsConst(m_programs)) {
- program->bind();
- program->setUniformValue(program->uniformLocation(name), QColor(color));
- program->release();
- }
-}
-
-void Scene::setFloatParameter(const QString &name, float value)
-{
- // set the color in all programs
- for (QGLShaderProgram *program : qAsConst(m_programs)) {
- program->bind();
- program->setUniformValue(program->uniformLocation(name), value);
- program->release();
- }
-}
-
-void Scene::newItem(ItemDialog::ItemType type)
-{
- QSize size = sceneRect().size().toSize();
- switch (type) {
- case ItemDialog::QtBoxItem:
- addItem(new QtBox(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- case ItemDialog::CircleItem:
- addItem(new CircleItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- case ItemDialog::SquareItem:
- addItem(new SquareItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- default:
- break;
- }
-}
diff --git a/examples/widgets/graphicsview/boxes/scene.h b/examples/widgets/graphicsview/boxes/scene.h
deleted file mode 100644
index 5d65dc71e2..0000000000
--- a/examples/widgets/graphicsview/boxes/scene.h
+++ /dev/null
@@ -1,247 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 SCENE_H
-#define SCENE_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-#include "gltrianglemesh.h"
-#include "qtbox.h"
-#include "roundedbox.h"
-#include "trackball.h"
-
-QT_BEGIN_NAMESPACE
-class QMatrix4x4;
-QT_END_NAMESPACE
-
-class ParameterEdit : public QWidget
-{
-public:
- virtual void emitChange() = 0;
-};
-
-class ColorEdit : public ParameterEdit
-{
- Q_OBJECT
-public:
- ColorEdit(QRgb initialColor, int id);
- QRgb color() const {return m_color;}
- void emitChange() override { emit colorChanged(m_color, m_id); }
-public slots:
- void editDone();
-signals:
- void colorChanged(QRgb color, int id);
-protected:
- void mousePressEvent(QMouseEvent *event) override;
- void setColor(QRgb color); // also emits colorChanged()
-private:
- QGraphicsScene *m_dialogParentScene;
- QLineEdit *m_lineEdit;
- QFrame *m_button;
- QRgb m_color;
- int m_id;
-};
-
-class FloatEdit : public ParameterEdit
-{
- Q_OBJECT
-public:
- FloatEdit(float initialValue, int id);
- float value() const {return m_value;}
- void emitChange() override { emit valueChanged(m_value, m_id); }
-public slots:
- void editDone();
-signals:
- void valueChanged(float value, int id);
-private:
- QGraphicsScene *m_dialogParentScene;
- QLineEdit *m_lineEdit;
- float m_value;
- int m_id;
-};
-
-class GraphicsWidget : public QGraphicsProxyWidget
-{
-public:
- GraphicsWidget() : QGraphicsProxyWidget(nullptr, Qt::Window) {}
-protected:
- QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
- void resizeEvent(QGraphicsSceneResizeEvent *event) override;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-};
-
-class TwoSidedGraphicsWidget : public QObject
-{
- Q_OBJECT
-public:
- using QObject::QObject;
- void setWidget(int index, QWidget *widget);
- QWidget *widget(int index);
-public slots:
- void flip();
-protected slots:
- void animateFlip();
-private:
- GraphicsWidget *m_proxyWidgets[2] = {nullptr, nullptr};
- int m_current = 0;
- int m_angle = 0; // angle in degrees
- int m_delta = 0;
-};
-
-class RenderOptionsDialog : public QDialog
-{
- Q_OBJECT
-public:
- RenderOptionsDialog();
- int addTexture(const QString &name);
- int addShader(const QString &name);
- void emitParameterChanged();
-protected slots:
- void setColorParameter(QRgb color, int id);
- void setFloatParameter(float value, int id);
-signals:
- void dynamicCubemapToggled(int);
- void colorParameterChanged(const QString &, QRgb);
- void floatParameterChanged(const QString &, float);
- void textureChanged(int);
- void shaderChanged(int);
- void doubleClicked();
-protected:
- void mouseDoubleClickEvent(QMouseEvent *event) override;
-
- QVector<QByteArray> m_parameterNames;
- QComboBox *m_textureCombo;
- QComboBox *m_shaderCombo;
- QVector<ParameterEdit *> m_parameterEdits;
-};
-
-class ItemDialog : public QDialog
-{
- Q_OBJECT
-public:
- enum ItemType {
- QtBoxItem,
- CircleItem,
- SquareItem,
- };
-
- ItemDialog();
-public slots:
- void triggerNewQtBox();
- void triggerNewCircleItem();
- void triggerNewSquareItem();
-signals:
- void doubleClicked();
- void newItemTriggered(ItemDialog::ItemType type);
-protected:
- void mouseDoubleClickEvent(QMouseEvent *event) override;
-};
-
-class Scene : public QGraphicsScene
-{
- Q_OBJECT
-public:
- Scene(int width, int height, int maxTextureSize);
- ~Scene();
- void drawBackground(QPainter *painter, const QRectF &rect) override;
-
-public slots:
- void setShader(int index);
- void setTexture(int index);
- void toggleDynamicCubemap(int state);
- void setColorParameter(const QString &name, QRgb color);
- void setFloatParameter(const QString &name, float value);
- void newItem(ItemDialog::ItemType type);
-protected:
- void renderBoxes(const QMatrix4x4 &view, int excludeBox = -2);
- void setStates();
- void setLights();
- void defaultStates();
- void renderCubemaps();
-
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void wheelEvent(QGraphicsSceneWheelEvent * event) override;
-private:
- void initGL();
- QPointF pixelPosToViewPos(const QPointF& p);
-
- QTime m_time; // ### Qt 6: remove (unused)
- int m_lastTime;
- int m_mouseEventTime;
- int m_distExp;
- int m_frame;
- int m_maxTextureSize;
-
- int m_currentShader;
- int m_currentTexture;
- bool m_dynamicCubemap;
- bool m_updateAllCubemaps;
-
- RenderOptionsDialog *m_renderOptions;
- ItemDialog *m_itemDialog;
- QTimer *m_timer;
- GLRoundedBox *m_box;
- TrackBall m_trackBalls[3];
- QVector<GLTexture *> m_textures;
- GLTextureCube *m_environment;
- GLTexture3D *m_noise;
- GLRenderTargetCube *m_mainCubemap;
- QVector<GLRenderTargetCube *> m_cubemaps;
- QVector<QGLShaderProgram *> m_programs;
- QGLShader *m_vertexShader;
- QVector<QGLShader *> m_fragmentShaders;
- QGLShader *m_environmentShader;
- QGLShaderProgram *m_environmentProgram;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/smiley.png b/examples/widgets/graphicsview/boxes/smiley.png
deleted file mode 100644
index 41cfda6b23..0000000000
--- a/examples/widgets/graphicsview/boxes/smiley.png
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/square.jpg b/examples/widgets/graphicsview/boxes/square.jpg
deleted file mode 100644
index 03f53bd530..0000000000
--- a/examples/widgets/graphicsview/boxes/square.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/trackball.cpp b/examples/widgets/graphicsview/boxes/trackball.cpp
deleted file mode 100644
index b9dfc1fc7f..0000000000
--- a/examples/widgets/graphicsview/boxes/trackball.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 "trackball.h"
-#include "scene.h"
-
-//============================================================================//
-// TrackBall //
-//============================================================================//
-
-TrackBall::TrackBall(TrackMode mode)
- : TrackBall(0, QVector3D(0, 1, 0), mode)
-{
-}
-
-TrackBall::TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode)
- : m_axis(axis)
- , m_angularVelocity(angularVelocity)
- , m_mode(mode)
-{}
-
-void TrackBall::push(const QPointF& p, const QQuaternion &)
-{
- m_rotation = rotation();
- m_pressed = true;
- m_lastTime = QTime::currentTime();
- m_lastPos = p;
- m_angularVelocity = 0.0f;
-}
-
-void TrackBall::move(const QPointF& p, const QQuaternion &transformation)
-{
- if (!m_pressed)
- return;
-
- QTime currentTime = QTime::currentTime();
- int msecs = m_lastTime.msecsTo(currentTime);
- if (msecs <= 20)
- return;
-
- switch (m_mode) {
- case Plane:
- {
- QLineF delta(m_lastPos, p);
- const float angleDelta = qRadiansToDegrees(float(delta.length()));
- m_angularVelocity = angleDelta / msecs;
- m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized();
- m_axis = transformation.rotatedVector(m_axis);
- m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angleDelta) * m_rotation;
- }
- break;
- case Sphere:
- {
- QVector3D lastPos3D = QVector3D(m_lastPos.x(), m_lastPos.y(), 0.0f);
- float sqrZ = 1 - QVector3D::dotProduct(lastPos3D, lastPos3D);
- if (sqrZ > 0)
- lastPos3D.setZ(std::sqrt(sqrZ));
- else
- lastPos3D.normalize();
-
- QVector3D currentPos3D = QVector3D(p.x(), p.y(), 0.0f);
- sqrZ = 1 - QVector3D::dotProduct(currentPos3D, currentPos3D);
- if (sqrZ > 0)
- currentPos3D.setZ(std::sqrt(sqrZ));
- else
- currentPos3D.normalize();
-
- m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D);
- float angle = qRadiansToDegrees(std::asin(m_axis.length()));
-
- m_angularVelocity = angle / msecs;
- m_axis.normalize();
- m_axis = transformation.rotatedVector(m_axis);
- m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation;
- }
- break;
- }
-
-
- m_lastPos = p;
- m_lastTime = currentTime;
-}
-
-void TrackBall::release(const QPointF& p, const QQuaternion &transformation)
-{
- // Calling move() caused the rotation to stop if the framerate was too low.
- move(p, transformation);
- m_pressed = false;
-}
-
-void TrackBall::start()
-{
- m_lastTime = QTime::currentTime();
- m_paused = false;
-}
-
-void TrackBall::stop()
-{
- m_rotation = rotation();
- m_paused = true;
-}
-
-QQuaternion TrackBall::rotation() const
-{
- if (m_paused || m_pressed)
- return m_rotation;
-
- QTime currentTime = QTime::currentTime();
- float angle = m_angularVelocity * m_lastTime.msecsTo(currentTime);
- return QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation;
-}
-
diff --git a/examples/widgets/graphicsview/boxes/trackball.h b/examples/widgets/graphicsview/boxes/trackball.h
deleted file mode 100644
index af90e4d842..0000000000
--- a/examples/widgets/graphicsview/boxes/trackball.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 TRACKBALL_H
-#define TRACKBALL_H
-
-#include <QQuaternion>
-#include <QTime>
-#include <QVector3D>
-
-class TrackBall
-{
-public:
- enum TrackMode
- {
- Plane,
- Sphere,
- };
- TrackBall(TrackMode mode = Sphere);
- TrackBall(float angularVelocity, const QVector3D &axis, TrackMode mode = Sphere);
- // coordinates in [-1,1]x[-1,1]
- void push(const QPointF &p, const QQuaternion &transformation);
- void move(const QPointF &p, const QQuaternion &transformation);
- void release(const QPointF &p, const QQuaternion &transformation);
- void start(); // starts clock
- void stop(); // stops clock
- QQuaternion rotation() const;
-private:
- QQuaternion m_rotation;
- QVector3D m_axis = QVector3D(0, 1, 0);
- float m_angularVelocity = 0;
-
- QPointF m_lastPos;
- QTime m_lastTime = QTime::currentTime();
- TrackMode m_mode;
- bool m_paused = false;
- bool m_pressed = false;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/wood.fsh b/examples/widgets/graphicsview/boxes/wood.fsh
deleted file mode 100644
index fbb5195f3a..0000000000
--- a/examples/widgets/graphicsview/boxes/wood.fsh
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-varying vec3 position, normal;
-varying vec4 specular, ambient, diffuse, lightDirection;
-
-uniform sampler2D tex;
-uniform sampler3D noise;
-
-//const vec4 woodColors[2] = {vec4(0.37,0.24,0.20,1), vec4(0.8,0.6,0.4,1)};
-uniform vec4 woodColors[2];
-//const float woodTubulence = 0.1;
-uniform float woodTubulence;
-
-void main()
-{
- float r = length(gl_TexCoord[1].yz);
- r += woodTubulence * texture3D(noise, 0.25 * gl_TexCoord[1].xyz).x;
-
- vec3 N = normalize(normal);
- // assume directional light
-
- gl_MaterialParameters M = gl_FrontMaterial;
-
- float NdotL = dot(N, lightDirection.xyz);
- float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz);
-
- float f = fract(16.0 * r);
- vec4 unlitColor = mix(woodColors[0], woodColors[1], min(1.25 * f, 5.0 - 5.0 * f));
- gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor +
- M.specular * specular * pow(max(RdotL, 0.0), M.shininess);
-}
diff --git a/examples/widgets/graphicsview/chip/chip.pro b/examples/widgets/graphicsview/chip/chip.pro
index a46f07ce35..508928d026 100644
--- a/examples/widgets/graphicsview/chip/chip.pro
+++ b/examples/widgets/graphicsview/chip/chip.pro
@@ -6,7 +6,6 @@ SOURCES += mainwindow.cpp view.cpp chip.cpp
QT += widgets
qtHaveModule(printsupport): QT += printsupport
-qtHaveModule(opengl): QT += opengl
build_all:!build_pass {
CONFIG -= build_all
diff --git a/examples/widgets/graphicsview/chip/view.cpp b/examples/widgets/graphicsview/chip/view.cpp
index 21998dc2df..77a6310778 100644
--- a/examples/widgets/graphicsview/chip/view.cpp
+++ b/examples/widgets/graphicsview/chip/view.cpp
@@ -57,11 +57,7 @@
#include <QPrintDialog>
#endif
#endif
-#ifndef QT_NO_OPENGL
-#include <QtOpenGL>
-#else
#include <QtWidgets>
-#endif
#include <QtMath>
#if QT_CONFIG(wheelevent)
@@ -156,14 +152,6 @@ View::View(const QString &name, QWidget *parent)
antialiasButton->setText(tr("Antialiasing"));
antialiasButton->setCheckable(true);
antialiasButton->setChecked(false);
- openGlButton = new QToolButton;
- openGlButton->setText(tr("OpenGL"));
- openGlButton->setCheckable(true);
-#ifndef QT_NO_OPENGL
- openGlButton->setEnabled(QGLFormat::hasOpenGL());
-#else
- openGlButton->setEnabled(false);
-#endif
printButton = new QToolButton;
printButton->setIcon(QIcon(QPixmap(":/fileprint.png")));
@@ -179,7 +167,6 @@ View::View(const QString &name, QWidget *parent)
labelLayout->addWidget(dragModeButton);
labelLayout->addStretch();
labelLayout->addWidget(antialiasButton);
- labelLayout->addWidget(openGlButton);
labelLayout->addWidget(printButton);
QGridLayout *topLayout = new QGridLayout;
@@ -200,7 +187,6 @@ View::View(const QString &name, QWidget *parent)
connect(selectModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode);
connect(dragModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode);
connect(antialiasButton, &QAbstractButton::toggled, this, &View::toggleAntialiasing);
- connect(openGlButton, &QAbstractButton::toggled, this, &View::toggleOpenGL);
connect(rotateLeftIcon, &QAbstractButton::clicked, this, &View::rotateLeft);
connect(rotateRightIcon, &QAbstractButton::clicked, this, &View::rotateRight);
connect(zoomInIcon, &QAbstractButton::clicked, this, &View::zoomIn);
@@ -250,13 +236,6 @@ void View::togglePointerMode()
graphicsView->setInteractive(selectModeButton->isChecked());
}
-void View::toggleOpenGL()
-{
-#ifndef QT_NO_OPENGL
- graphicsView->setViewport(openGlButton->isChecked() ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget);
-#endif
-}
-
void View::toggleAntialiasing()
{
graphicsView->setRenderHint(QPainter::Antialiasing, antialiasButton->isChecked());
diff --git a/examples/widgets/graphicsview/chip/view.h b/examples/widgets/graphicsview/chip/view.h
index ea7bd414f5..b780702c34 100644
--- a/examples/widgets/graphicsview/chip/view.h
+++ b/examples/widgets/graphicsview/chip/view.h
@@ -94,7 +94,6 @@ private slots:
void setResetButtonEnabled();
void setupMatrix();
void togglePointerMode();
- void toggleOpenGL();
void toggleAntialiasing();
void print();
void rotateLeft();
@@ -106,7 +105,6 @@ private:
QLabel *label2;
QToolButton *selectModeButton;
QToolButton *dragModeButton;
- QToolButton *openGlButton;
QToolButton *antialiasButton;
QToolButton *printButton;
QToolButton *resetButton;
diff --git a/examples/widgets/graphicsview/graphicsview.pro b/examples/widgets/graphicsview/graphicsview.pro
index b9bef70a0e..d591450559 100644
--- a/examples/widgets/graphicsview/graphicsview.pro
+++ b/examples/widgets/graphicsview/graphicsview.pro
@@ -14,7 +14,3 @@ SUBDIRS = \
weatheranchorlayout
contains(DEFINES, QT_NO_CURSOR)|!qtConfig(draganddrop): SUBDIRS -= dragdroprobot
-
-qtHaveModule(opengl):!qtConfig(opengles.):!qtConfig(dynamicgl) {
- SUBDIRS += boxes
-}
diff --git a/mkspecs/features/java.prf b/mkspecs/features/java.prf
index f1f5e4c10c..1d52f05e52 100644
--- a/mkspecs/features/java.prf
+++ b/mkspecs/features/java.prf
@@ -20,7 +20,7 @@ CONFIG += plugin no_plugin_name_prefix
javac.input = JAVASOURCES
javac.output = $$CLASS_DIR
javac.CONFIG += combine
-javac.commands = javac -source 6 -target 6 -Xlint:unchecked -bootclasspath $$ANDROID_JAR_FILE -cp $$shell_quote($$system_path($$join(JAVACLASSPATH, $$DIRLIST_SEPARATOR))) -d $$shell_quote($$CLASS_DIR) ${QMAKE_FILE_IN}
+javac.commands = javac -source 7 -target 7 -Xlint:unchecked -bootclasspath $$ANDROID_JAR_FILE -cp $$shell_quote($$system_path($$join(JAVACLASSPATH, $$DIRLIST_SEPARATOR))) -d $$shell_quote($$CLASS_DIR) ${QMAKE_FILE_IN}
# Force rebuild every time, because we don't know the paths of the destination files
# as they depend on the code.
javac.depends = FORCE
diff --git a/qmake/Makefile.unix b/qmake/Makefile.unix
index 325a8548cf..4024231b70 100644
--- a/qmake/Makefile.unix
+++ b/qmake/Makefile.unix
@@ -30,7 +30,7 @@ QOBJS = \
quuid.o \
qarraydata.o qbitarray.o qbytearray.o qbytearraylist.o qbytearraymatcher.o \
qcalendar.o qgregoriancalendar.o qromancalendar.o \
- qcryptographichash.o qdatetime.o qhash.o qlist.o \
+ qcryptographichash.o qdatetime.o qhash.o \
qlocale.o qlocale_tools.o qmap.o qregexp.o qringbuffer.o \
qstringbuilder.o qstring.o qstringlist.o qversionnumber.o \
qvsnprintf.o qxmlstream.o qxmlutils.o \
@@ -127,7 +127,6 @@ DEPEND_SRC = \
$(SOURCE_PATH)/src/corelib/tools/qbitarray.cpp \
$(SOURCE_PATH)/src/corelib/tools/qcryptographichash.cpp \
$(SOURCE_PATH)/src/corelib/tools/qhash.cpp \
- $(SOURCE_PATH)/src/corelib/tools/qlist.cpp \
$(SOURCE_PATH)/src/corelib/tools/qmap.cpp \
$(SOURCE_PATH)/src/corelib/tools/qringbuffer.cpp \
$(SOURCE_PATH)/src/corelib/tools/qversionnumber.cpp \
@@ -374,9 +373,6 @@ qversionnumber.o: $(SOURCE_PATH)/src/corelib/tools/qversionnumber.cpp
qbuffer.o: $(SOURCE_PATH)/src/corelib/io/qbuffer.cpp
$(CXX) -c -o $@ $(CXXFLAGS) $<
-qlist.o: $(SOURCE_PATH)/src/corelib/tools/qlist.cpp
- $(CXX) -c -o $@ $(CXXFLAGS) $<
-
qfile.o: $(SOURCE_PATH)/src/corelib/io/qfile.cpp
$(CXX) -c -o $@ $(CXXFLAGS) $<
diff --git a/qmake/Makefile.win32 b/qmake/Makefile.win32
index 6c8d5ec922..6f27b735d4 100644
--- a/qmake/Makefile.win32
+++ b/qmake/Makefile.win32
@@ -91,7 +91,6 @@ QTOBJS= \
qiodevice.obj \
qringbuffer.obj \
qdebug.obj \
- qlist.obj \
qlocale.obj \
qlocale_tools.obj \
qlocale_win.obj \
diff --git a/qmake/generators/makefiledeps.cpp b/qmake/generators/makefiledeps.cpp
index d68539814e..7c4be64aa8 100644
--- a/qmake/generators/makefiledeps.cpp
+++ b/qmake/generators/makefiledeps.cpp
@@ -60,19 +60,14 @@ QT_BEGIN_NAMESPACE
inline bool qmake_endOfLine(const char &c) { return (c == '\r' || c == '\n'); }
#endif
-QMakeLocalFileName::QMakeLocalFileName(const QString &name) : is_null(name.isNull())
+QMakeLocalFileName::QMakeLocalFileName(const QString &name)
+ : real_name(name)
{
- if(!name.isEmpty()) {
- if(name.at(0) == QLatin1Char('"') && name.at(name.length()-2) == QLatin1Char('"'))
- real_name = name.mid(1, name.length()-2);
- else
- real_name = name;
- }
}
const QString
&QMakeLocalFileName::local() const
{
- if(!is_null && local_name.isNull())
+ if (!isNull() && local_name.isNull())
local_name = Option::normalizePath(real_name);
return local_name;
}
diff --git a/qmake/generators/makefiledeps.h b/qmake/generators/makefiledeps.h
index 66b87bf470..7e39396754 100644
--- a/qmake/generators/makefiledeps.h
+++ b/qmake/generators/makefiledeps.h
@@ -41,14 +41,14 @@ struct SourceFile;
struct SourceDependChildren;
class SourceFiles;
-class QMakeLocalFileName {
- bool is_null;
+class QMakeLocalFileName
+{
QString real_name;
mutable QString local_name;
public:
- QMakeLocalFileName() : is_null(true) {}
+ QMakeLocalFileName() = default;
QMakeLocalFileName(const QString &);
- bool isNull() const { return is_null; }
+ bool isNull() const { return real_name.isNull(); }
inline const QString &real() const { return real_name; }
const QString &local() const;
diff --git a/qmake/property.cpp b/qmake/property.cpp
index 432ff55664..31d6cdc9d6 100644
--- a/qmake/property.cpp
+++ b/qmake/property.cpp
@@ -54,7 +54,6 @@ static const struct {
{ "QT_INSTALL_BINS", QLibraryInfo::BinariesPath, false, false },
{ "QT_INSTALL_TESTS", QLibraryInfo::TestsPath, false, false },
{ "QT_INSTALL_PLUGINS", QLibraryInfo::PluginsPath, false, false },
- { "QT_INSTALL_IMPORTS", QLibraryInfo::ImportsPath, false, false },
{ "QT_INSTALL_QML", QLibraryInfo::Qml2ImportsPath, false, false },
{ "QT_INSTALL_TRANSLATIONS", QLibraryInfo::TranslationsPath, false, false },
{ "QT_INSTALL_CONFIGURATION", QLibraryInfo::SettingsPath, false, false },
diff --git a/src/corelib/configure.json b/src/corelib/configure.json
index eb60ad213c..c8e650ca9f 100644
--- a/src/corelib/configure.json
+++ b/src/corelib/configure.json
@@ -826,6 +826,12 @@
],
"output": [ "publicFeature", "feature" ]
},
+ "shortcut": {
+ "label": "QShortcut",
+ "purpose": "Provides keyboard accelerators and shortcuts.",
+ "section": "Kernel",
+ "output": [ "publicFeature", "feature" ]
+ },
"systemsemaphore": {
"label": "QSystemSemaphore",
"purpose": "Provides a general counting system semaphore.",
diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qbytearray.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qbytearray.cpp
index 01f620cf08..9c07a2e92c 100644
--- a/src/corelib/doc/snippets/code/src_corelib_tools_qbytearray.cpp
+++ b/src/corelib/doc/snippets/code/src_corelib_tools_qbytearray.cpp
@@ -372,16 +372,13 @@ a = str.toFloat(&ok); // a == 0, ok == false
//! [39]
QByteArray text("Qt is great!");
text.toBase64(); // returns "UXQgaXMgZ3JlYXQh"
-//! [39]
-//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64Encoding | QByteArray::OmitTrailingEquals); // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64Encoding); // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64UrlEncoding); // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); // returns "PHA-SGVsbG8_PC9wPg"
-//! [39bis]
-
+//! [39]
//! [40]
QByteArray ba;
@@ -422,9 +419,7 @@ QDataStream in(&data, QIODevice::ReadOnly);
//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data(); // returns "Qt is great!"
-//! [44]
-//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]
@@ -442,7 +437,6 @@ if (result.decodingStatus == QByteArray::Base64DecodingStatus::Ok)
process(result.decoded);
//! [44quater]
-
//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data(); // returns "Qt is great!"
diff --git a/src/corelib/doc/snippets/qstring/main.cpp b/src/corelib/doc/snippets/qstring/main.cpp
index ac7fc7d078..f797890e5d 100644
--- a/src/corelib/doc/snippets/qstring/main.cpp
+++ b/src/corelib/doc/snippets/qstring/main.cpp
@@ -433,14 +433,12 @@ void Widget::firstIndexOfFunction()
//! [93]
QString str = "the minimum";
str.indexOf(QRegularExpression("m[aeiou]"), 0); // returns 4
- //! [93]
- //! [99]
QString str = "the minimum";
QRegularExpressionMatch match;
str.indexOf(QRegularExpression("m[aeiou]"), 0, &match); // returns 4
// match.captured() == mi
- //! [99]
+ //! [93]
}
void Widget::insertFunction()
@@ -490,14 +488,12 @@ void Widget::lastIndexOfFunction()
//! [94]
QString str = "the minimum";
str.lastIndexOf(QRegularExpression("m[aeiou]")); // returns 8
- //! [94]
- //! [100]
QString str = "the minimum";
QRegularExpressionMatch match;
str.lastIndexOf(QRegularExpression("m[aeiou]"), -1, &match); // returns 8
// match.captured() == mu
- //! [100]
+ //! [94]
}
void Widget::leftFunction()
diff --git a/src/corelib/doc/src/containers.qdoc b/src/corelib/doc/src/containers.qdoc
index d0bb251e81..8373ad4b4e 100644
--- a/src/corelib/doc/src/containers.qdoc
+++ b/src/corelib/doc/src/containers.qdoc
@@ -74,12 +74,10 @@
\section1 The Container Classes
- Qt provides the following sequential containers: QList,
- QLinkedList, QVector, QStack, and QQueue. For most
- applications, QList is the best type to use. Although it is
- implemented as an array-list, it provides very fast prepends and
- appends. If you really need a linked-list, use QLinkedList; if you
- want your items to occupy consecutive memory locations, use QVector.
+ Qt provides the following sequential containers: QVector,
+ QLinkedList, QStack, and QQueue. For most
+ applications, QVector is the best type to use. It provides very fast
+ appends. If you really need a linked-list, use QLinkedList.
QStack and QQueue are convenience classes that provide LIFO and
FIFO semantics.
@@ -95,30 +93,19 @@
\table
\header \li Class \li Summary
- \row \li \l{QList}<T>
- \li This is by far the most commonly used container class. It
- stores a list of values of a given type (T) that can be accessed
- by index. Internally, the QList is implemented using an array,
- ensuring that index-based access is very fast.
-
- Items can be added at either end of the list using
- QList::append() and QList::prepend(), or they can be inserted in
- the middle using QList::insert(). More than any other container
- class, QList is highly optimized to expand to as little code as
- possible in the executable. QStringList inherits from
- QList<QString>.
-
\row \li \l{QLinkedList}<T>
- \li This is similar to QList, except that it uses
- iterators rather than integer indexes to access items. It also
- provides better performance than QList when inserting in the
+ \li This class implements a doubly linked list. It
+ provides better performance than QVector when inserting in the
middle of a huge list, and it has nicer iterator semantics.
(Iterators pointing to an item in a QLinkedList remain valid as
- long as the item exists, whereas iterators to a QList can become
+ long as the item exists, whereas iterators to a QVector can become
invalid after any insertion or removal.)
\row \li \l{QVector}<T>
- \li This stores an array of values of a given type at adjacent
+ \li This is by far the most commonly used container class. It
+ stores a list of values of a given type (T) that can be accessed
+ by index. Internally, it stores an array of values of a
+ given type at adjacent
positions in memory. Inserting at the front or in the middle of
a vector can be quite slow, because it can lead to large numbers
of items having to be moved by one position in memory.
@@ -131,9 +118,9 @@
and \l{QStack::top()}{top()}.
\row \li \l{QQueue}<T>
- \li This is a convenience subclass of QList that provides
+ \li This is a convenience subclass of QVector that provides
"first in, first out" (FIFO) semantics. It adds the following
- functions to those already present in QList:
+ functions to those already present in QQVector:
\l{QQueue::enqueue()}{enqueue()},
\l{QQueue::dequeue()}{dequeue()}, and \l{QQueue::head()}{head()}.
@@ -164,8 +151,8 @@
\endtable
Containers can be nested. For example, it is perfectly possible
- to use a QMap<QString, QList<int>>, where the key type is
- QString and the value type QList<int>.
+ to use a QMap<QString, QVector<int>>, where the key type is
+ QString and the value type QVector<int>.
The containers are defined in individual header files with the
same name as the container (e.g., \c <QLinkedList>). For
@@ -184,10 +171,10 @@
double, pointer types, and Qt data types such as QString, QDate,
and QTime, but it doesn't cover QObject or any QObject subclass
(QWidget, QDialog, QTimer, etc.). If you attempt to instantiate a
- QList<QWidget>, the compiler will complain that QWidget's copy
+ QVector<QWidget>, the compiler will complain that QWidget's copy
constructor and assignment operators are disabled. If you want to
store these kinds of objects in a container, store them as
- pointers, for example as QList<QWidget *>.
+ pointers, for example as QVector<QWidget *>.
Here's an example custom data type that meets the requirement of
an assignable data type:
@@ -260,11 +247,10 @@
\table
\header \li Containers \li Read-only iterator
\li Read-write iterator
- \row \li QList<T>, QQueue<T> \li QListIterator<T>
\li QMutableListIterator<T>
\row \li QLinkedList<T> \li QLinkedListIterator<T>
\li QMutableLinkedListIterator<T>
- \row \li QVector<T>, QStack<T> \li QVectorIterator<T>
+ \row \li QVector<T>, QStack<T>, QQueue<T> \li QVectorIterator<T>
\li QMutableVectorIterator<T>
\row \li QSet<T> \li QSetIterator<T>
\li QMutableSetIterator<T>
@@ -274,9 +260,9 @@
\li QMutableHashIterator<Key, T>
\endtable
- In this discussion, we will concentrate on QList and QMap. The
+ In this discussion, we will concentrate on QVector and QMap. The
iterator types for QLinkedList, QVector, and QSet have exactly
- the same interface as QList's iterators; similarly, the iterator
+ the same interface as QVector's iterators; similarly, the iterator
types for QHash have the same interface as QMap's iterators.
Unlike STL-style iterators (covered \l{STL-style
@@ -291,59 +277,59 @@
\image javaiterators1.png
Here's a typical loop for iterating through all the elements of a
- QList<QString> in order and printing them to the console:
+ QVector<QString> in order and printing them to the console:
\snippet code/doc_src_containers.cpp 1
- It works as follows: The QList to iterate over is passed to the
- QListIterator constructor. At that point, the iterator is located
+ It works as follows: The QVector to iterate over is passed to the
+ QVectorIterator constructor. At that point, the iterator is located
just in front of the first item in the list (before item "A").
- Then we call \l{QListIterator::hasNext()}{hasNext()} to
+ Then we call \l{QVectorIterator::hasNext()}{hasNext()} to
check whether there is an item after the iterator. If there is, we
- call \l{QListIterator::next()}{next()} to jump over that
+ call \l{QVectorIterator::next()}{next()} to jump over that
item. The next() function returns the item that it jumps over. For
- a QList<QString>, that item is of type QString.
+ a QVector<QString>, that item is of type QString.
- Here's how to iterate backward in a QList:
+ Here's how to iterate backward in a QVector:
\snippet code/doc_src_containers.cpp 2
The code is symmetric with iterating forward, except that we
- start by calling \l{QListIterator::toBack()}{toBack()}
+ start by calling \l{QVectorIterator::toBack()}{toBack()}
to move the iterator after the last item in the list.
The diagram below illustrates the effect of calling
- \l{QListIterator::next()}{next()} and
- \l{QListIterator::previous()}{previous()} on an iterator:
+ \l{QVectorIterator::next()}{next()} and
+ \l{QVectorIterator::previous()}{previous()} on an iterator:
\image javaiterators2.png
- The following table summarizes the QListIterator API:
+ The following table summarizes the QVectorIterator API:
\table
\header \li Function \li Behavior
- \row \li \l{QListIterator::toFront()}{toFront()}
+ \row \li \l{QVectorIterator::toFront()}{toFront()}
\li Moves the iterator to the front of the list (before the first item)
- \row \li \l{QListIterator::toBack()}{toBack()}
+ \row \li \l{QVectorIterator::toBack()}{toBack()}
\li Moves the iterator to the back of the list (after the last item)
- \row \li \l{QListIterator::hasNext()}{hasNext()}
+ \row \li \l{QVectorIterator::hasNext()}{hasNext()}
\li Returns \c true if the iterator isn't at the back of the list
- \row \li \l{QListIterator::next()}{next()}
+ \row \li \l{QVectorIterator::next()}{next()}
\li Returns the next item and advances the iterator by one position
- \row \li \l{QListIterator::peekNext()}{peekNext()}
+ \row \li \l{QVectorIterator::peekNext()}{peekNext()}
\li Returns the next item without moving the iterator
- \row \li \l{QListIterator::hasPrevious()}{hasPrevious()}
+ \row \li \l{QVectorIterator::hasPrevious()}{hasPrevious()}
\li Returns \c true if the iterator isn't at the front of the list
- \row \li \l{QListIterator::previous()}{previous()}
+ \row \li \l{QVectorIterator::previous()}{previous()}
\li Returns the previous item and moves the iterator back by one position
- \row \li \l{QListIterator::peekPrevious()}{peekPrevious()}
+ \row \li \l{QVectorIterator::peekPrevious()}{peekPrevious()}
\li Returns the previous item without moving the iterator
\endtable
- QListIterator provides no functions to insert or remove items
+ QVectorIterator provides no functions to insert or remove items
from the list as we iterate. To accomplish this, you must use
QMutableListIterator. Here's an example where we remove all
- odd numbers from a QList<int> using QMutableListIterator:
+ odd numbers from a QVector<int> using QMutableListIterator:
\snippet code/doc_src_containers.cpp 3
@@ -377,11 +363,11 @@
\snippet code/doc_src_containers.cpp 6
As mentioned above, QLinkedList's, QVector's, and QSet's iterator
- classes have exactly the same API as QList's. We will now turn to
+ classes have exactly the same API as QVector's. We will now turn to
QMapIterator, which is somewhat different because it iterates on
(key, value) pairs.
- Like QListIterator, QMapIterator provides
+ Like QVectorIterator, QMapIterator provides
\l{QMapIterator::toFront()}{toFront()},
\l{QMapIterator::toBack()}{toBack()},
\l{QMapIterator::hasNext()}{hasNext()},
@@ -429,11 +415,9 @@
\table
\header \li Containers \li Read-only iterator
\li Read-write iterator
- \row \li QList<T>, QQueue<T> \li QList<T>::const_iterator
- \li QList<T>::iterator
\row \li QLinkedList<T> \li QLinkedList<T>::const_iterator
\li QLinkedList<T>::iterator
- \row \li QVector<T>, QStack<T> \li QVector<T>::const_iterator
+ \row \li QVector<T>, QStack<T>, QQueue<T> \li QVector<T>::const_iterator
\li QVector<T>::iterator
\row \li QSet<T> \li QSet<T>::const_iterator
\li QSet<T>::iterator
@@ -452,24 +436,24 @@
and the \l{QVector::iterator}{const_iterator} type is
just a typedef for \c{const T *}.
- In this discussion, we will concentrate on QList and QMap. The
+ In this discussion, we will concentrate on QVector and QMap. The
iterator types for QLinkedList, QVector, and QSet have exactly
- the same interface as QList's iterators; similarly, the iterator
+ the same interface as QVector's iterators; similarly, the iterator
types for QHash have the same interface as QMap's iterators.
Here's a typical loop for iterating through all the elements of a
- QList<QString> in order and converting them to lowercase:
+ QVector<QString> in order and converting them to lowercase:
\snippet code/doc_src_containers.cpp 10
Unlike \l{Java-style iterators}, STL-style iterators point
- directly at items. The \l{QList::begin()}{begin()} function of a container returns an
+ directly at items. The \l{QVector::begin()}{begin()} function of a container returns an
iterator that points to the first item in the container. The
- \l{QList::end()}{end()} function of a container returns an iterator to the
+ \l{QVector::end()}{end()} function of a container returns an iterator to the
imaginary item one position past the last item in the container.
- \l {QList::end()}{end()} marks an invalid position; it must never be dereferenced.
+ \l {QVector::end()}{end()} marks an invalid position; it must never be dereferenced.
It is typically used in a loop's break condition. If the list is
- empty, \l{QList::begin}{begin()} equals \l{QList::end()}{end()}, so we never execute the loop.
+ empty, \l{QVector::begin}{begin()} equals \l{QVector::end()}{end()}, so we never execute the loop.
The diagram below shows the valid iterator positions as red
arrows for a vector containing four items:
@@ -486,8 +470,8 @@
compilers also allow us to write \c{i->toLower()}, but some
don't.
- For read-only access, you can use const_iterator, \l{QList::constBegin}{constBegin()},
- and \l{QList::constEnd()}{constEnd()}. For example:
+ For read-only access, you can use const_iterator, \l{QVector::constBegin}{constBegin()},
+ and \l{QVector::constEnd()}{constEnd()}. For example:
\snippet code/doc_src_containers.cpp 12
@@ -525,7 +509,7 @@
Thanks to \l{implicit sharing}, it is very inexpensive for a
function to return a container per value. The Qt API contains
- dozens of functions that return a QList or QStringList per value
+ dozens of functions that return a QVector or QStringList per value
(e.g., QSplitter::sizes()). If you want to iterate over these
using an STL iterator, you should always take a copy of the
container and iterate over the copy. For example:
@@ -695,7 +679,6 @@
\table
\header \li \li Index lookup \li Insertion \li Prepending \li Appending
\row \li QLinkedList<T> \li O(\e n) \li O(1) \li O(1) \li O(1)
- \row \li QList<T> \li O(1) \li O(n) \li Amort. O(1) \li Amort. O(1)
\row \li QVector<T> \li O(1) \li O(n) \li O(n) \li Amort. O(1)
\endtable
@@ -726,11 +709,8 @@
\section1 Growth Strategies
QVector<T>, QString, and QByteArray store their items
- contiguously in memory; QList<T> maintains an array of pointers
- to the items it stores to provide fast index-based access (unless
- T is a pointer type or a basic type of the size of a pointer, in
- which case the value itself is stored in the array); QHash<Key,
- T> keeps a hash table whose size is proportional to the number
+ contiguously in memory; QHash<Key, T> keeps a
+ hash table whose size is proportional to the number
of items in the hash. To avoid reallocating the data every single
time an item is added at the end of the container, these classes
typically allocate more memory than necessary.
@@ -764,7 +744,7 @@
on the first and last pages actually needs to be copied.
\endlist
- QByteArray and QList<T> use more or less the same algorithm as
+ QByteArray uses more or less the same algorithm as
QString.
QVector<T> also uses that algorithm for data types that can be
diff --git a/src/corelib/doc/src/datastreamformat.qdoc b/src/corelib/doc/src/datastreamformat.qdoc
index d6b60f10ce..def9021350 100644
--- a/src/corelib/doc/src/datastreamformat.qdoc
+++ b/src/corelib/doc/src/datastreamformat.qdoc
@@ -67,7 +67,6 @@
\li QImage
\li QKeySequence
\li QLinkedList<T>
- \li QList<T>
\li QMap<Key, T>
\li QMargins
\li QMatrix4x4
diff --git a/src/corelib/doc/src/dontdocument.qdoc b/src/corelib/doc/src/dontdocument.qdoc
index 19ca7db299..d7859a45af 100644
--- a/src/corelib/doc/src/dontdocument.qdoc
+++ b/src/corelib/doc/src/dontdocument.qdoc
@@ -29,7 +29,7 @@
\dontdocument (QMacAutoReleasePool QIncompatibleFlag QGenericAtomicOps QAtomicTraits
QAtomicOps QBasicAtomicInteger QBasicAtomicPointer QBasicMutex QInternal
QArgument QReturnArgument QArrayData QTypedArrayData QStaticByteArrayData
- QByteRef QStaticStringData QListSpecialMethods QListData QScopedPointerDeleter
+ QStaticStringData QListSpecialMethods QListData QScopedPointerDeleter
QScopedPointerArrayDeleter QScopedPointerPodDeleter QScopedPointerObjectDeleteLater
QMetaTypeId2 QObjectData QObjectUserData QMapNodeBase QMapNode QMapDataBase
QMapData QHashData QHashNode QArrayDataPointer QTextStreamManipulator
diff --git a/src/corelib/global/qcompilerdetection.h b/src/corelib/global/qcompilerdetection.h
index aa38ef18c0..99a30e941b 100644
--- a/src/corelib/global/qcompilerdetection.h
+++ b/src/corelib/global/qcompilerdetection.h
@@ -91,8 +91,6 @@
# define Q_OUTOFLINE_TEMPLATE inline
# define Q_COMPILER_MANGLES_RETURN_TYPE
# define Q_FUNC_INFO __FUNCSIG__
-# define Q_ALIGNOF(type) __alignof(type)
-# define Q_DECL_ALIGN(n) __declspec(align(n))
# define Q_ASSUME_IMPL(expr) __assume(expr)
# define Q_UNREACHABLE_IMPL() __assume(0)
# define Q_NORETURN __declspec(noreturn)
@@ -222,10 +220,8 @@
# endif
# define Q_FUNC_INFO __PRETTY_FUNCTION__
-# define Q_ALIGNOF(type) __alignof__(type)
# define Q_TYPEOF(expr) __typeof__(expr)
# define Q_DECL_DEPRECATED __attribute__ ((__deprecated__))
-# define Q_DECL_ALIGN(n) __attribute__((__aligned__(n)))
# define Q_DECL_UNUSED __attribute__((__unused__))
# define Q_LIKELY(expr) __builtin_expect(!!(expr), true)
# define Q_UNLIKELY(expr) __builtin_expect(!!(expr), false)
@@ -272,9 +268,7 @@
# if __xlC__ < 0x400
# error "Compiler not supported"
# elif __xlC__ >= 0x0600
-# define Q_ALIGNOF(type) __alignof__(type)
# define Q_TYPEOF(expr) __typeof__(expr)
-# define Q_DECL_ALIGN(n) __attribute__((__aligned__(n)))
# define Q_PACKED __attribute__((__packed__))
# endif
@@ -352,7 +346,6 @@
# define Q_PACKED __attribute__ ((__packed__))
# define Q_FUNC_INFO __PRETTY_FUNCTION__
# define Q_TYPEOF(expr) __typeof__(expr)
-# define Q_ALIGNOF(type) __alignof__(type)
# define Q_UNREACHABLE_IMPL()
# if defined(__cplusplus)
# define Q_COMPILER_AUTO_TYPE
@@ -449,9 +442,7 @@
# define QT_NO_TEMPLATE_TEMPLATE_PARAMETERS
/* see http://developers.sun.com/sunstudio/support/Ccompare.html */
# if __SUNPRO_CC >= 0x590
-# define Q_ALIGNOF(type) __alignof__(type)
# define Q_TYPEOF(expr) __typeof__(expr)
-# define Q_DECL_ALIGN(n) __attribute__((__aligned__(n)))
# endif
# if __SUNPRO_CC >= 0x550
# define Q_DECL_EXPORT __global
@@ -488,9 +479,6 @@
# define Q_DECL_EXPORT __declspec(dllexport)
# define Q_DECL_IMPORT __declspec(dllimport)
# endif
-# if __HP_aCC-0 >= 061200
-# define Q_DECL_ALIGN(n) __attribute__((aligned(n)))
-# endif
# if __HP_aCC-0 >= 062000
# define Q_DECL_EXPORT __attribute__((visibility("default")))
# define Q_DECL_HIDDEN __attribute__((visibility("hidden")))
@@ -1133,14 +1121,12 @@
#endif
#define Q_DECL_NOTHROW Q_DECL_NOEXCEPT
-#if defined(Q_COMPILER_ALIGNOF)
-# undef Q_ALIGNOF
-# define Q_ALIGNOF(x) alignof(x)
+#ifndef Q_ALIGNOF
+# define Q_ALIGNOF(x) alignof(x)
#endif
-#if defined(Q_COMPILER_ALIGNAS)
-# undef Q_DECL_ALIGN
-# define Q_DECL_ALIGN(n) alignas(n)
+#ifndef Q_DECL_ALIGN
+# define Q_DECL_ALIGN(n) alignas(n)
#endif
#if __has_cpp_attribute(nodiscard) && !defined(Q_CC_CLANG) // P0188R1
diff --git a/src/corelib/global/qconfig-bootstrapped.h b/src/corelib/global/qconfig-bootstrapped.h
index b3daf43c04..4a8a4598a0 100644
--- a/src/corelib/global/qconfig-bootstrapped.h
+++ b/src/corelib/global/qconfig-bootstrapped.h
@@ -112,6 +112,7 @@
# define QT_FEATURE_renameat2 -1
#endif
#define QT_FEATURE_sharedmemory -1
+#define QT_FEATURE_shortcut -1
#define QT_FEATURE_signaling_nan -1
#define QT_FEATURE_slog2 -1
#ifdef __GLIBC_PREREQ
diff --git a/src/corelib/global/qendian.cpp b/src/corelib/global/qendian.cpp
index 98dc6a9a4b..f1c39f3c62 100644
--- a/src/corelib/global/qendian.cpp
+++ b/src/corelib/global/qendian.cpp
@@ -765,7 +765,7 @@ QT_BEGIN_NAMESPACE
#if defined(__SSSE3__)
using ShuffleMask = uchar[16];
-Q_DECL_ALIGN(16) static const ShuffleMask shuffleMasks[3] = {
+alignas(16) static const ShuffleMask shuffleMasks[3] = {
// 16-bit
{1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14},
// 32-bit
diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp
index 20046e3fcf..f9f005a83f 100644
--- a/src/corelib/global/qglobal.cpp
+++ b/src/corelib/global/qglobal.cpp
@@ -1213,11 +1213,14 @@ bool qSharedBuild() noexcept
the application is compiled (32 or 64).
*/
+#if QT_DEPRECATED_SINCE(5, 9)
/*!
\deprecated
\variable QSysInfo::WindowsVersion
\brief the version of the Windows operating system on which the
application is run.
+
+ Use QOperatingSystemVersion::current() instead.
*/
/*!
@@ -1225,6 +1228,8 @@ bool qSharedBuild() noexcept
\fn QSysInfo::WindowsVersion QSysInfo::windowsVersion()
\since 4.4
+ Use QOperatingSystemVersion::current() instead.
+
Returns the version of the Windows operating system on which the
application is run, or WV_None if the operating system is not
Windows.
@@ -1235,16 +1240,21 @@ bool qSharedBuild() noexcept
\variable QSysInfo::MacintoshVersion
\brief the version of the Macintosh operating system on which
the application is run.
+
+ Use QOperatingSystemVersion::current() instead.
*/
/*!
\deprecated
\fn QSysInfo::MacVersion QSysInfo::macVersion()
+ Use QOperatingSystemVersion::current() instead.
+
Returns the version of Darwin (\macos or iOS) on which the
application is run, or MV_None if the operating system
is not a version of Darwin.
*/
+#endif
/*!
\enum QSysInfo::Endian
@@ -1255,10 +1265,13 @@ bool qSharedBuild() noexcept
the platform's byte order.
*/
+#if QT_DEPRECATED_SINCE(5, 9)
/*!
\deprecated
\enum QSysInfo::WinVersion
+ Use the versions defined in QOperatingSystemVersion instead.
+
This enum provides symbolic names for the various versions of the
Windows operating system. On Windows, the
QSysInfo::WindowsVersion variable gives the version of the system
@@ -1316,6 +1329,8 @@ bool qSharedBuild() noexcept
\deprecated
\enum QSysInfo::MacVersion
+ Use the versions defined in QOperatingSystemVersion instead.
+
This enum provides symbolic names for the various versions of the
Darwin operating system, covering both \macos and iOS. The
QSysInfo::MacintoshVersion variable gives the version of the
@@ -1386,6 +1401,7 @@ bool qSharedBuild() noexcept
\sa WinVersion
*/
+#endif
/*!
\macro Q_OS_DARWIN
diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h
index 1bfe2c1615..d508716024 100644
--- a/src/corelib/global/qglobal.h
+++ b/src/corelib/global/qglobal.h
@@ -86,14 +86,9 @@
#define QT_CONFIG(feature) (1/QT_FEATURE_##feature == 1)
#define QT_REQUIRE_CONFIG(feature) Q_STATIC_ASSERT_X(QT_FEATURE_##feature == 1, "Required feature " #feature " for file " __FILE__ " not available.")
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
-# define QT_NO_UNSHARABLE_CONTAINERS
-# define QT6_VIRTUAL virtual
-# define QT6_NOT_VIRTUAL
-#else
-# define QT6_VIRTUAL
-# define QT6_NOT_VIRTUAL virtual
-#endif
+// ### Clean those up, once all code is adjusted
+#define QT6_VIRTUAL virtual
+#define QT6_NOT_VIRTUAL
/* These two macros makes it possible to turn the builtin line expander into a
* string literal. */
@@ -498,53 +493,6 @@ Q_CORE_EXPORT Q_DECL_CONST_FUNCTION const char *qVersion(void) Q_DECL_NOEXCEPT;
# define Q_DESTRUCTOR_FUNCTION(AFUNC) Q_DESTRUCTOR_FUNCTION0(AFUNC)
#endif
-namespace QtPrivate {
- template <class T>
- struct AlignOfHelper
- {
- char c;
- T type;
-
- AlignOfHelper();
- ~AlignOfHelper();
- };
-
- template <class T>
- struct AlignOf_Default
- {
- enum { Value = sizeof(AlignOfHelper<T>) - sizeof(T) };
- };
-
- template <class T> struct AlignOf : AlignOf_Default<T> { };
- template <class T> struct AlignOf<T &> : AlignOf<T> {};
- template <class T> struct AlignOf<T &&> : AlignOf<T> {};
- template <size_t N, class T> struct AlignOf<T[N]> : AlignOf<T> {};
-
-#if defined(Q_PROCESSOR_X86_32) && !defined(Q_OS_WIN)
- template <class T> struct AlignOf_WorkaroundForI386Abi { enum { Value = sizeof(T) }; };
-
- // x86 ABI weirdness
- // Alignment of naked type is 8, but inside struct has alignment 4.
- template <> struct AlignOf<double> : AlignOf_WorkaroundForI386Abi<double> {};
- template <> struct AlignOf<qint64> : AlignOf_WorkaroundForI386Abi<qint64> {};
- template <> struct AlignOf<quint64> : AlignOf_WorkaroundForI386Abi<quint64> {};
-#ifdef Q_CC_CLANG
- // GCC and Clang seem to disagree wrt to alignment of arrays
- template <size_t N> struct AlignOf<double[N]> : AlignOf_Default<double> {};
- template <size_t N> struct AlignOf<qint64[N]> : AlignOf_Default<qint64> {};
- template <size_t N> struct AlignOf<quint64[N]> : AlignOf_Default<quint64> {};
-#endif
-#endif
-} // namespace QtPrivate
-
-#define QT_EMULATED_ALIGNOF(T) \
- (size_t(QT_PREPEND_NAMESPACE(QtPrivate)::AlignOf<T>::Value))
-
-#ifndef Q_ALIGNOF
-#define Q_ALIGNOF(T) QT_EMULATED_ALIGNOF(T)
-#endif
-
-
/*
quintptr and qptrdiff is guaranteed to be the same size as a pointer, i.e.
diff --git a/src/corelib/global/qlibraryinfo.cpp b/src/corelib/global/qlibraryinfo.cpp
index fa2098c757..9fab49a73e 100644
--- a/src/corelib/global/qlibraryinfo.cpp
+++ b/src/corelib/global/qlibraryinfo.cpp
@@ -419,7 +419,6 @@ static const struct {
#endif
{ "Binaries", "bin" },
{ "Plugins", "plugins" }, // should be ${ArchData}/plugins
- { "Imports", "imports" }, // should be ${ArchData}/imports
{ "Qml2Imports", "qml" }, // should be ${ArchData}/qml
{ "ArchData", "." },
{ "Data", "." },
@@ -886,7 +885,6 @@ QStringList QLibraryInfo::platformPluginArguments(const QString &platformName)
\value LibraryExecutablesPath The location of installed executables required by libraries at runtime.
\value BinariesPath The location of installed Qt binaries (tools and applications).
\value PluginsPath The location of installed Qt plugins.
- \value ImportsPath The location of installed QML extensions to import (QML 1.x).
\value Qml2ImportsPath The location of installed QML extensions to import (QML 2.x).
\value ArchDataPath The location of general architecture-dependent Qt data.
\value DataPath The location of general architecture-independent Qt data.
diff --git a/src/corelib/global/qlibraryinfo.h b/src/corelib/global/qlibraryinfo.h
index ed60b170a5..031dfe37e2 100644
--- a/src/corelib/global/qlibraryinfo.h
+++ b/src/corelib/global/qlibraryinfo.h
@@ -79,7 +79,6 @@ public:
LibraryExecutablesPath,
BinariesPath,
PluginsPath,
- ImportsPath,
Qml2ImportsPath,
ArchDataPath,
DataPath,
diff --git a/src/corelib/global/qlogging.cpp b/src/corelib/global/qlogging.cpp
index c1a45476f9..ca4d8dbd11 100644
--- a/src/corelib/global/qlogging.cpp
+++ b/src/corelib/global/qlogging.cpp
@@ -1307,7 +1307,7 @@ static QStringList backtraceFramesForLogMessage(int frameCount)
QString function = m.captured(2);
// skip the trace from QtCore that are because of the qDebug itself
- if (!numberPrinted && library.contains(QLatin1String("Qt5Core"))
+ if (!numberPrinted && library.contains(QLatin1String("Qt6Core"))
&& (function.isEmpty() || function.contains(QLatin1String("Message"), Qt::CaseInsensitive)
|| function.contains(QLatin1String("QDebug")))) {
continue;
diff --git a/src/corelib/global/qnamespace.h b/src/corelib/global/qnamespace.h
index 5b63daec69..b9e981b4a6 100644
--- a/src/corelib/global/qnamespace.h
+++ b/src/corelib/global/qnamespace.h
@@ -41,6 +41,7 @@
#define QNAMESPACE_H
#include <QtCore/qglobal.h>
+#include <QtCore/qtmetamacros.h>
#if defined(__OBJC__) && !defined(__cplusplus)
# warning "File built in Objective-C mode (.m), but using Qt requires Objective-C++ (.mm)"
@@ -48,29 +49,10 @@
QT_BEGIN_NAMESPACE
-#if !defined(Q_QDOC) && !defined(Q_MOC_RUN)
struct QMetaObject;
-const QMetaObject *qt_getQtMetaObject() noexcept; // defined in qobject.h (which can't be included here)
-#define QT_Q_ENUM(ENUM) \
- inline const QMetaObject *qt_getEnumMetaObject(ENUM) noexcept { return qt_getQtMetaObject(); } \
- inline Q_DECL_CONSTEXPR const char *qt_getEnumName(ENUM) noexcept { return #ENUM; }
-#define QT_Q_FLAG(ENUM) QT_Q_ENUM(ENUM)
-#else
-#define QT_Q_ENUM Q_ENUM
-#define QT_Q_FLAG Q_FLAG
-#endif
-
-#ifndef Q_MOC_RUN
-namespace
-#else
-class Q_CORE_EXPORT
-#endif
-Qt {
-#if defined(Q_MOC_RUN)
- Q_OBJECT
-public:
-#endif
+namespace Qt {
+ Q_NAMESPACE_EXPORT(Q_CORE_EXPORT)
enum GlobalColor {
color0,
@@ -1768,102 +1750,96 @@ public:
};
#ifndef Q_QDOC
- // NOTE: Generally, do not add QT_Q_ENUM if a corresponding Q_Q_FLAG exists.
- QT_Q_ENUM(ScrollBarPolicy)
- QT_Q_ENUM(FocusPolicy)
- QT_Q_ENUM(ContextMenuPolicy)
- QT_Q_ENUM(ArrowType)
- QT_Q_ENUM(ToolButtonStyle)
- QT_Q_ENUM(PenStyle)
- QT_Q_ENUM(PenCapStyle)
- QT_Q_ENUM(PenJoinStyle)
- QT_Q_ENUM(BrushStyle)
- QT_Q_ENUM(FillRule)
- QT_Q_ENUM(MaskMode)
- QT_Q_ENUM(BGMode)
- QT_Q_ENUM(ClipOperation)
- QT_Q_ENUM(SizeMode)
- QT_Q_ENUM(Axis)
- QT_Q_ENUM(Corner)
- QT_Q_ENUM(Edge)
- QT_Q_ENUM(LayoutDirection)
- QT_Q_ENUM(SizeHint)
- QT_Q_ENUM(Orientation)
- QT_Q_ENUM(DropAction)
- QT_Q_FLAG(Alignment)
- QT_Q_ENUM(TextFlag)
- QT_Q_FLAG(Orientations)
- QT_Q_FLAG(SplitBehavior)
- QT_Q_FLAG(DropActions)
- QT_Q_FLAG(Edges)
- QT_Q_FLAG(DockWidgetAreas)
- QT_Q_FLAG(ToolBarAreas)
- QT_Q_ENUM(DockWidgetArea)
- QT_Q_ENUM(ToolBarArea)
- QT_Q_ENUM(TextFormat)
- QT_Q_ENUM(TextElideMode)
- QT_Q_ENUM(DateFormat)
- QT_Q_ENUM(TimeSpec)
- QT_Q_ENUM(DayOfWeek)
- QT_Q_ENUM(CursorShape)
- QT_Q_ENUM(GlobalColor)
- QT_Q_ENUM(AspectRatioMode)
- QT_Q_ENUM(TransformationMode)
- QT_Q_FLAG(ImageConversionFlags)
- QT_Q_ENUM(Key)
- QT_Q_ENUM(ShortcutContext)
- QT_Q_ENUM(TextInteractionFlag)
- QT_Q_FLAG(TextInteractionFlags)
- QT_Q_ENUM(ItemSelectionMode)
- QT_Q_ENUM(ItemSelectionOperation)
- QT_Q_FLAG(ItemFlags)
- QT_Q_ENUM(CheckState)
- QT_Q_ENUM(ItemDataRole)
- QT_Q_ENUM(SortOrder)
- QT_Q_ENUM(CaseSensitivity)
- QT_Q_FLAG(MatchFlags)
- QT_Q_FLAG(KeyboardModifiers)
- QT_Q_FLAG(MouseButtons)
- QT_Q_ENUM(WindowType)
- QT_Q_ENUM(WindowState)
- QT_Q_ENUM(WindowModality)
- QT_Q_ENUM(WidgetAttribute)
- QT_Q_ENUM(ApplicationAttribute)
- QT_Q_FLAG(WindowFlags)
- QT_Q_FLAG(WindowStates)
- QT_Q_ENUM(FocusReason)
- 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)
- QT_Q_FLAG(ScreenOrientations)
- QT_Q_ENUM(ConnectionType)
- QT_Q_ENUM(ApplicationState)
+ // NOTE: Generally, do not add Q_ENUM_NS if a corresponding Q_FLAG_NS exists.
+ Q_ENUM_NS(ScrollBarPolicy)
+ Q_ENUM_NS(FocusPolicy)
+ Q_ENUM_NS(ContextMenuPolicy)
+ Q_ENUM_NS(ArrowType)
+ Q_ENUM_NS(ToolButtonStyle)
+ Q_ENUM_NS(PenStyle)
+ Q_ENUM_NS(PenCapStyle)
+ Q_ENUM_NS(PenJoinStyle)
+ Q_ENUM_NS(BrushStyle)
+ Q_ENUM_NS(FillRule)
+ Q_ENUM_NS(MaskMode)
+ Q_ENUM_NS(BGMode)
+ Q_ENUM_NS(ClipOperation)
+ Q_ENUM_NS(SizeMode)
+ Q_ENUM_NS(Axis)
+ Q_ENUM_NS(Corner)
+ Q_ENUM_NS(Edge)
+ Q_ENUM_NS(LayoutDirection)
+ Q_ENUM_NS(SizeHint)
+ Q_ENUM_NS(Orientation)
+ Q_ENUM_NS(DropAction)
+ Q_FLAG_NS(Alignment)
+ Q_ENUM_NS(TextFlag)
+ Q_FLAG_NS(Orientations)
+ Q_FLAG_NS(SplitBehavior)
+ Q_FLAG_NS(DropActions)
+ Q_FLAG_NS(Edges)
+ Q_FLAG_NS(DockWidgetAreas)
+ Q_FLAG_NS(ToolBarAreas)
+ Q_ENUM_NS(DockWidgetArea)
+ Q_ENUM_NS(ToolBarArea)
+ Q_ENUM_NS(TextFormat)
+ Q_ENUM_NS(TextElideMode)
+ Q_ENUM_NS(DateFormat)
+ Q_ENUM_NS(TimeSpec)
+ Q_ENUM_NS(DayOfWeek)
+ Q_ENUM_NS(CursorShape)
+ Q_ENUM_NS(GlobalColor)
+ Q_ENUM_NS(AspectRatioMode)
+ Q_ENUM_NS(TransformationMode)
+ Q_FLAG_NS(ImageConversionFlags)
+ Q_ENUM_NS(Key)
+ Q_ENUM_NS(ShortcutContext)
+ Q_ENUM_NS(TextInteractionFlag)
+ Q_FLAG_NS(TextInteractionFlags)
+ Q_ENUM_NS(ItemSelectionMode)
+ Q_ENUM_NS(ItemSelectionOperation)
+ Q_FLAG_NS(ItemFlags)
+ Q_ENUM_NS(CheckState)
+ Q_ENUM_NS(ItemDataRole)
+ Q_ENUM_NS(SortOrder)
+ Q_ENUM_NS(CaseSensitivity)
+ Q_FLAG_NS(MatchFlags)
+ Q_FLAG_NS(KeyboardModifiers)
+ Q_FLAG_NS(MouseButtons)
+ Q_ENUM_NS(WindowType)
+ Q_ENUM_NS(WindowState)
+ Q_ENUM_NS(WindowModality)
+ Q_ENUM_NS(WidgetAttribute)
+ Q_ENUM_NS(ApplicationAttribute)
+ Q_FLAG_NS(WindowFlags)
+ Q_FLAG_NS(WindowStates)
+ Q_ENUM_NS(FocusReason)
+ Q_ENUM_NS(InputMethodHint)
+ Q_ENUM_NS(InputMethodQuery)
+ Q_FLAG_NS(InputMethodHints)
+ Q_ENUM_NS(EnterKeyType)
+ Q_FLAG_NS(InputMethodQueries)
+ Q_FLAG_NS(TouchPointStates)
+ Q_ENUM_NS(ScreenOrientation)
+ Q_FLAG_NS(ScreenOrientations)
+ Q_ENUM_NS(ConnectionType)
+ Q_ENUM_NS(ApplicationState)
#ifndef QT_NO_GESTURES
- QT_Q_ENUM(GestureState)
- QT_Q_ENUM(GestureType)
- QT_Q_ENUM(NativeGestureType)
+ Q_ENUM_NS(GestureState)
+ Q_ENUM_NS(GestureType)
+ Q_ENUM_NS(NativeGestureType)
#endif
- QT_Q_ENUM(CursorMoveStyle)
- QT_Q_ENUM(TimerType)
- QT_Q_ENUM(ScrollPhase)
- QT_Q_ENUM(MouseEventSource)
- QT_Q_FLAG(MouseEventFlag)
- QT_Q_ENUM(ChecksumType)
- QT_Q_ENUM(HighDpiScaleFactorRoundingPolicy)
- QT_Q_ENUM(TabFocusBehavior)
+ Q_ENUM_NS(CursorMoveStyle)
+ Q_ENUM_NS(TimerType)
+ Q_ENUM_NS(ScrollPhase)
+ Q_ENUM_NS(MouseEventSource)
+ Q_FLAG_NS(MouseEventFlag)
+ Q_ENUM_NS(ChecksumType)
+ Q_ENUM_NS(HighDpiScaleFactorRoundingPolicy)
+ Q_ENUM_NS(TabFocusBehavior)
#endif // Q_DOC
}
-#ifdef Q_MOC_RUN
- ;
-#endif
-
-#undef QT_Q_ENUM
-#undef QT_Q_FLAG
typedef bool (*qInternalCallback)(void **);
diff --git a/src/corelib/global/qnumeric_p.h b/src/corelib/global/qnumeric_p.h
index fdfcbda6ca..376da66e31 100644
--- a/src/corelib/global/qnumeric_p.h
+++ b/src/corelib/global/qnumeric_p.h
@@ -202,7 +202,7 @@ namespace {
This function works for v containing infinities, but not NaN. It's the
caller's responsibility to exclude that possibility before calling it.
*/
-template <typename T> static inline bool convertDoubleTo(double v, T *value)
+template <typename T> static inline bool convertDoubleTo(double v, T *value, bool allow_precision_upgrade = true)
{
Q_STATIC_ASSERT(std::numeric_limits<T>::is_integer);
@@ -227,6 +227,10 @@ template <typename T> static inline bool convertDoubleTo(double v, T *value)
supremum = -2.0 * std::numeric_limits<ST>::min(); // -2 * (-2^63) = 2^64, exact (for T = quint64)
v = fabs(v);
}
+ if (std::is_integral<T>::value && sizeof(T) > 4 && !allow_precision_upgrade) {
+ if (v > double(Q_INT64_C(1)<<53) || v < double(-((Q_INT64_C(1)<<53) + 1)))
+ return false;
+ }
*value = std::numeric_limits<T>::max();
if (v >= supremum)
diff --git a/src/corelib/global/qrandom.cpp b/src/corelib/global/qrandom.cpp
index 10672c1f92..3dc024e301 100644
--- a/src/corelib/global/qrandom.cpp
+++ b/src/corelib/global/qrandom.cpp
@@ -355,7 +355,7 @@ struct QRandomGenerator::SystemAndGlobalGenerators
// the state in case another thread tries to lock the mutex. It's not
// a common scenario, but since sizeof(QRandomGenerator) >= 2560, the
// overhead is actually acceptable.
- // 2) We use both Q_DECL_ALIGN and std::aligned_storage<..., 64> because
+ // 2) We use both alignas and std::aligned_storage<..., 64> because
// some implementations of std::aligned_storage can't align to more
// than a primitive type's alignment.
// 3) We don't store the entire system QRandomGenerator, only the space
@@ -364,7 +364,7 @@ struct QRandomGenerator::SystemAndGlobalGenerators
QBasicMutex globalPRNGMutex;
struct ShortenedSystem { uint type; } system_;
SystemGenerator sys;
- Q_DECL_ALIGN(64) std::aligned_storage<sizeof(QRandomGenerator64), 64>::type global_;
+ alignas(64) std::aligned_storage<sizeof(QRandomGenerator64), 64>::type global_;
#ifdef Q_COMPILER_CONSTEXPR
constexpr SystemAndGlobalGenerators()
diff --git a/src/corelib/global/qrandom.h b/src/corelib/global/qrandom.h
index 445b520c76..e1494ab523 100644
--- a/src/corelib/global/qrandom.h
+++ b/src/corelib/global/qrandom.h
@@ -196,7 +196,7 @@ private:
RandomEngine &engine() { return twister; }
const RandomEngine &engine() const { return twister; }
#else
- std::aligned_storage<sizeof(RandomEngine), Q_ALIGNOF(RandomEngine)>::type buffer;
+ std::aligned_storage<sizeof(RandomEngine), alignof(RandomEngine)>::type buffer;
RandomEngine &engine() { return reinterpret_cast<RandomEngine &>(buffer); }
const RandomEngine &engine() const { return reinterpret_cast<const RandomEngine &>(buffer); }
#endif
diff --git a/src/corelib/global/qtypeinfo.h b/src/corelib/global/qtypeinfo.h
index 30be47296e..34cf1de4f5 100644
--- a/src/corelib/global/qtypeinfo.h
+++ b/src/corelib/global/qtypeinfo.h
@@ -209,7 +209,6 @@ public: \
}; \
}
-Q_DECLARE_MOVABLE_CONTAINER(QList);
Q_DECLARE_MOVABLE_CONTAINER(QVector);
Q_DECLARE_MOVABLE_CONTAINER(QQueue);
Q_DECLARE_MOVABLE_CONTAINER(QStack);
diff --git a/src/corelib/io/qdebug.h b/src/corelib/io/qdebug.h
index 421c5d933b..2314b36bda 100644
--- a/src/corelib/io/qdebug.h
+++ b/src/corelib/io/qdebug.h
@@ -234,12 +234,6 @@ inline QDebug printSequentialContainer(QDebug debug, const char *which, const Se
} // namespace QtPrivate
-template <class T>
-inline QDebug operator<<(QDebug debug, const QList<T> &list)
-{
- return QtPrivate::printSequentialContainer(debug, "" /*for historical reasons*/, list);
-}
-
template <typename T>
inline QDebug operator<<(QDebug debug, const QVector<T> &vec)
{
diff --git a/src/corelib/io/qfileselector.cpp b/src/corelib/io/qfileselector.cpp
index 31c490de66..7adaafea18 100644
--- a/src/corelib/io/qfileselector.cpp
+++ b/src/corelib/io/qfileselector.cpp
@@ -342,7 +342,6 @@ void QFileSelectorPrivate::updateSelectors()
QStringList QFileSelectorPrivate::platformSelectors()
{
// similar, but not identical to QSysInfo::osType
- // ### Qt6: remove macOS fallbacks to "mac" and the future compatibility
QStringList ret;
#if defined(Q_OS_WIN)
ret << QStringLiteral("windows");
@@ -355,16 +354,10 @@ QStringList QFileSelectorPrivate::platformSelectors()
# if !defined(Q_OS_ANDROID) && !defined(Q_OS_QNX)
// we don't want "linux" for Android or two instances of "qnx" for QNX
ret << QSysInfo::kernelType();
-# ifdef Q_OS_MAC
- ret << QStringLiteral("mac"); // compatibility, since kernelType() is "darwin"
-# endif
# endif
QString productName = QSysInfo::productType();
if (productName != QLatin1String("unknown"))
ret << productName; // "opensuse", "fedora", "osx", "ios", "android"
-# if defined(Q_OS_MACOS)
- ret << QStringLiteral("macos"); // future compatibility
-# endif
#endif
return ret;
}
diff --git a/src/corelib/io/qfilesystemiterator_unix.cpp b/src/corelib/io/qfilesystemiterator_unix.cpp
index 74b7e820d9..ad6dbaba11 100644
--- a/src/corelib/io/qfilesystemiterator_unix.cpp
+++ b/src/corelib/io/qfilesystemiterator_unix.cpp
@@ -86,6 +86,8 @@ static bool checkNameDecodable(const char *d_name, qsizetype len)
return cs.invalidChars == 0 && cs.remainingChars == 0;
#else
// if we have no text codecs, then QString::fromLocal8Bit is fromLatin1
+ Q_UNUSED(d_name)
+ Q_UNUSED(len)
return true;
#endif
}
diff --git a/src/corelib/io/qfilesystemwatcher_win.cpp b/src/corelib/io/qfilesystemwatcher_win.cpp
index 5f91ce5e3d..1d42dbfc70 100644
--- a/src/corelib/io/qfilesystemwatcher_win.cpp
+++ b/src/corelib/io/qfilesystemwatcher_win.cpp
@@ -81,7 +81,7 @@ static Qt::HANDLE createChangeNotification(const QString &path, uint flags)
nativePath.append(QLatin1Char('\\'));
const HANDLE result = FindFirstChangeNotification(reinterpret_cast<const wchar_t *>(nativePath.utf16()),
FALSE, flags);
- DEBUG() << __FUNCTION__ << nativePath << Qt::hex <<showbase << flags << "returns" << result;
+ DEBUG() << __FUNCTION__ << nativePath << Qt::hex << Qt::showbase << flags << "returns" << result;
return result;
}
diff --git a/src/corelib/io/qresource.cpp b/src/corelib/io/qresource.cpp
index 43df284d50..0d75faa234 100644
--- a/src/corelib/io/qresource.cpp
+++ b/src/corelib/io/qresource.cpp
@@ -1111,14 +1111,8 @@ bool QDynamicFileResourceRoot::registerSelf(const QString &f)
uchar *data = nullptr;
qsizetype data_len = 0;
-#ifdef QT_USE_MMAP
- int fd = QT_OPEN(QFile::encodeName(f), O_RDONLY,
-#if defined(Q_OS_WIN)
- _S_IREAD | _S_IWRITE
-#else
- 0666
-#endif
- );
+#if defined(QT_USE_MMAP)
+ int fd = QT_OPEN(QFile::encodeName(f), O_RDONLY, 0666);
if (fd >= 0) {
QT_STATBUF st;
if (!QT_FSTAT(fd, &st) && st.st_size <= std::numeric_limits<qsizetype>::max()) {
diff --git a/src/corelib/io/qsettings.cpp b/src/corelib/io/qsettings.cpp
index 9fc45e307d..779b6f72de 100644
--- a/src/corelib/io/qsettings.cpp
+++ b/src/corelib/io/qsettings.cpp
@@ -416,7 +416,10 @@ QString QSettingsPrivate::variantToString(const QVariant &v)
case QVariant::UInt:
case QVariant::Bool:
case QVariant::Double:
- case QVariant::KeySequence: {
+#if QT_CONFIG(shortcut)
+ case QVariant::KeySequence:
+#endif
+ {
result = v.toString();
if (result.contains(QChar::Null))
result = QLatin1String("@String(") + result + QLatin1Char(')');
diff --git a/src/corelib/io/qstandardpaths.cpp b/src/corelib/io/qstandardpaths.cpp
index bca454fc7a..a5128a868b 100644
--- a/src/corelib/io/qstandardpaths.cpp
+++ b/src/corelib/io/qstandardpaths.cpp
@@ -345,6 +345,8 @@ QT_BEGIN_NAMESPACE
\note On Android, applications with open files on the external storage (<USER> locations),
will be killed if the external storage is unmounted.
+ \note On Android, reading/writing to GenericDataLocation needs the READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE permission granted.
+
\note On iOS, if you do pass \c {QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).last()}
as argument to \l{QFileDialog::setDirectory()},
a native image picker dialog will be used for accessing the user's photo album.
diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp
index 659552b72f..0a5f9256eb 100644
--- a/src/corelib/io/qurl.cpp
+++ b/src/corelib/io/qurl.cpp
@@ -979,7 +979,7 @@ inline bool QUrlPrivate::setScheme(const QString &value, int len, bool doSetErro
// validate it:
int needsLowercasing = -1;
- const ushort *p = reinterpret_cast<const ushort *>(value.constData());
+ const ushort *p = value.utf16();
for (int i = 0; i < len; ++i) {
if (p[i] >= 'a' && p[i] <= 'z')
continue;
diff --git a/src/corelib/itemmodels/qabstractitemmodel.cpp b/src/corelib/itemmodels/qabstractitemmodel.cpp
index 46ac703615..3bcd81bcdf 100644
--- a/src/corelib/itemmodels/qabstractitemmodel.cpp
+++ b/src/corelib/itemmodels/qabstractitemmodel.cpp
@@ -63,7 +63,7 @@ QPersistentModelIndexData *QPersistentModelIndexData::create(const QModelIndex &
Q_ASSERT(index.isValid()); // we will _never_ insert an invalid index in the list
QPersistentModelIndexData *d = nullptr;
QAbstractItemModel *model = const_cast<QAbstractItemModel *>(index.model());
- QHash<QModelIndex, QPersistentModelIndexData *> &indexes = model->d_func()->persistent.indexes;
+ QMultiHash<QModelIndex, QPersistentModelIndexData *> &indexes = model->d_func()->persistent.indexes;
const auto it = indexes.constFind(index);
if (it != indexes.cend()) {
d = (*it);
@@ -662,8 +662,7 @@ void QAbstractItemModelPrivate::rowsAboutToBeInserted(const QModelIndex &parent,
Q_UNUSED(last);
QVector<QPersistentModelIndexData *> persistent_moved;
if (first < q->rowCount(parent)) {
- for (QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it = persistent.indexes.constBegin();
- it != persistent.indexes.constEnd(); ++it) {
+ for (auto it = persistent.indexes.constBegin(); it != persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
const QModelIndex &index = data->index;
if (index.row() >= first && index.isValid() && index.parent() == parent) {
@@ -699,14 +698,13 @@ void QAbstractItemModelPrivate::itemsAboutToBeMoved(const QModelIndex &srcParent
QVector<QPersistentModelIndexData *> persistent_moved_in_source;
QVector<QPersistentModelIndexData *> persistent_moved_in_destination;
- QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it;
- const QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator begin = persistent.indexes.constBegin();
- const QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator end = persistent.indexes.constEnd();
+ const auto begin = persistent.indexes.constBegin();
+ const auto end = persistent.indexes.constEnd();
const bool sameParent = (srcParent == destinationParent);
const bool movingUp = (srcFirst > destinationChild);
- for ( it = begin; it != end; ++it) {
+ for (auto it = begin; it != end; ++it) {
QPersistentModelIndexData *data = *it;
const QModelIndex &index = data->index;
const QModelIndex &parent = index.parent();
@@ -811,8 +809,7 @@ void QAbstractItemModelPrivate::rowsAboutToBeRemoved(const QModelIndex &parent,
QVector<QPersistentModelIndexData *> persistent_invalidated;
// find the persistent indexes that are affected by the change, either by being in the removed subtree
// or by being on the same level and below the removed rows
- for (QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it = persistent.indexes.constBegin();
- it != persistent.indexes.constEnd(); ++it) {
+ for (auto it = persistent.indexes.constBegin(); it != persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
bool level_changed = false;
QModelIndex current = data->index;
@@ -867,8 +864,7 @@ void QAbstractItemModelPrivate::columnsAboutToBeInserted(const QModelIndex &pare
Q_UNUSED(last);
QVector<QPersistentModelIndexData *> persistent_moved;
if (first < q->columnCount(parent)) {
- for (QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it = persistent.indexes.constBegin();
- it != persistent.indexes.constEnd(); ++it) {
+ for (auto it = persistent.indexes.constBegin(); it != persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
const QModelIndex &index = data->index;
if (index.column() >= first && index.isValid() && index.parent() == parent)
@@ -904,8 +900,7 @@ void QAbstractItemModelPrivate::columnsAboutToBeRemoved(const QModelIndex &paren
QVector<QPersistentModelIndexData *> persistent_invalidated;
// find the persistent indexes that are affected by the change, either by being in the removed subtree
// or by being on the same level and to the right of the removed columns
- for (QHash<QModelIndex, QPersistentModelIndexData *>::const_iterator it = persistent.indexes.constBegin();
- it != persistent.indexes.constEnd(); ++it) {
+ for (auto it = persistent.indexes.constBegin(); it != persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
bool level_changed = false;
QModelIndex current = data->index;
@@ -3294,7 +3289,11 @@ void QAbstractItemModel::endResetModel()
{
Q_D(QAbstractItemModel);
d->invalidatePersistentIndexes();
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ resetInternalData();
+#else
QMetaObject::invokeMethod(this, "resetInternalData");
+#endif
emit modelReset(QPrivateSignal());
}
@@ -3372,8 +3371,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) {
+ for (auto it = d->persistent.indexes.constBegin(); it != d->persistent.indexes.constEnd(); ++it) {
QPersistentModelIndexData *data = *it;
result.append(data->index);
}
@@ -3991,8 +3989,8 @@ bool QAbstractListModel::dropMimeData(const QMimeData *data, Qt::DropAction acti
*/
void QAbstractItemModelPrivate::Persistent::insertMultiAtEnd(const QModelIndex& key, QPersistentModelIndexData *data)
{
- QHash<QModelIndex,QPersistentModelIndexData *>::iterator newIt = indexes.insert(key, data);
- QHash<QModelIndex,QPersistentModelIndexData *>::iterator it = newIt;
+ auto newIt = indexes.insert(key, data);
+ auto it = newIt;
++it;
while (it != indexes.end() && it.key() == key) {
qSwap(*newIt,*it);
diff --git a/src/corelib/itemmodels/qabstractitemmodel.h b/src/corelib/itemmodels/qabstractitemmodel.h
index 43649cf79b..2cc1bd8ce6 100644
--- a/src/corelib/itemmodels/qabstractitemmodel.h
+++ b/src/corelib/itemmodels/qabstractitemmodel.h
@@ -156,7 +156,6 @@ inline uint qHash(const QPersistentModelIndex &index, uint seed) noexcept
Q_CORE_EXPORT QDebug operator<<(QDebug, const QPersistentModelIndex &);
#endif
-template<typename T> class QList;
typedef QList<QModelIndex> QModelIndexList;
class QMimeData;
diff --git a/src/corelib/itemmodels/qabstractproxymodel.h b/src/corelib/itemmodels/qabstractproxymodel.h
index c9a73b6a31..f6f6e45c1a 100644
--- a/src/corelib/itemmodels/qabstractproxymodel.h
+++ b/src/corelib/itemmodels/qabstractproxymodel.h
@@ -103,7 +103,11 @@ Q_SIGNALS:
void sourceModelChanged(QPrivateSignal);
protected Q_SLOTS:
- void resetInternalData();
+ void resetInternalData()
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ override
+#endif
+ ;
protected:
QAbstractProxyModel(QAbstractProxyModelPrivate &, QObject *parent);
diff --git a/src/corelib/itemmodels/qitemselectionmodel.h b/src/corelib/itemmodels/qitemselectionmodel.h
index 5820695592..5421eb2afa 100644
--- a/src/corelib/itemmodels/qitemselectionmodel.h
+++ b/src/corelib/itemmodels/qitemselectionmodel.h
@@ -241,7 +241,7 @@ inline uint qHash(const QItemSelectionRange &) { return 0; }
# define Q_TEMPLATE_EXTERN extern
# endif
# endif
-Q_TEMPLATE_EXTERN template class Q_CORE_EXPORT QList<QItemSelectionRange>;
+Q_TEMPLATE_EXTERN template class Q_CORE_EXPORT QVector<QItemSelectionRange>;
#endif // Q_CC_MSVC
class Q_CORE_EXPORT QItemSelection : public QList<QItemSelectionRange>
diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp
index 34f54d8f94..dc46695f80 100644
--- a/src/corelib/kernel/qcoreapplication.cpp
+++ b/src/corelib/kernel/qcoreapplication.cpp
@@ -138,10 +138,10 @@ QT_BEGIN_NAMESPACE
extern QString qAppFileName();
#endif
-#if QT_VERSION >= 0x060000
-# error "Bump QCoreApplicatoinPrivate::app_compile_version to 0x060000"
+#if QT_VERSION >= 0x070000
+# error "Bump QCoreApplicatoinPrivate::app_compile_version to 0x070000"
#endif
-int QCoreApplicationPrivate::app_compile_version = 0x050000; //we don't know exactly, but it's at least 5.0.0
+int QCoreApplicationPrivate::app_compile_version = 0x060000; //we don't know exactly, but it's at least 6.0.0
bool QCoreApplicationPrivate::setuidAllowed = false;
diff --git a/src/corelib/kernel/qcoreapplication_win.cpp b/src/corelib/kernel/qcoreapplication_win.cpp
index 765f129758..824c0535ed 100644
--- a/src/corelib/kernel/qcoreapplication_win.cpp
+++ b/src/corelib/kernel/qcoreapplication_win.cpp
@@ -772,7 +772,7 @@ QString decodeMSG(const MSG& msg)
auto rect = reinterpret_cast<const RECT *>(lParam);
QTextStream(&parameters) << "DPI: " << HIWORD(wParam) << ','
<< LOWORD(wParam) << ' ' << (rect->right - rect->left) << 'x'
- << (rect->bottom - rect->top) << forcesign << rect->left << rect->top;
+ << (rect->bottom - rect->top) << Qt::forcesign << rect->left << rect->top;
}
break;
case WM_IME_NOTIFY:
diff --git a/src/corelib/kernel/qmetaobject.cpp b/src/corelib/kernel/qmetaobject.cpp
index fad47eee13..3883613d49 100644
--- a/src/corelib/kernel/qmetaobject.cpp
+++ b/src/corelib/kernel/qmetaobject.cpp
@@ -154,20 +154,29 @@ QT_BEGIN_NAMESPACE
static inline const QMetaObjectPrivate *priv(const uint* data)
{ return reinterpret_cast<const QMetaObjectPrivate*>(data); }
+static inline const char *rawStringData(const QMetaObject *mo, int index)
+{
+ Q_ASSERT(priv(mo->d.data)->revision >= 7);
+ uint offset = mo->d.stringdata[2*index];
+ return reinterpret_cast<const char *>(mo->d.stringdata) + offset;
+}
+
static inline const QByteArray stringData(const QMetaObject *mo, int index)
{
Q_ASSERT(priv(mo->d.data)->revision >= 7);
- const QByteArrayDataPtr data = { const_cast<QByteArrayData*>(&mo->d.stringdata[index]) };
- Q_ASSERT(data.ptr->ref.isStatic());
- Q_ASSERT(data.ptr->alloc == 0);
- Q_ASSERT(data.ptr->capacityReserved == 0);
- Q_ASSERT(data.ptr->size >= 0);
- return data;
+ uint offset = mo->d.stringdata[2*index];
+ uint length = mo->d.stringdata[2*index + 1];
+ const char *string = reinterpret_cast<const char *>(mo->d.stringdata) + offset;
+ return QByteArray::fromRawData(string, length);
}
-static inline const char *rawStringData(const QMetaObject *mo, int index)
+static inline const char *rawTypeNameFromTypeInfo(const QMetaObject *mo, uint typeInfo)
{
- return stringData(mo, index).data();
+ if (typeInfo & IsUnresolvedType) {
+ return rawStringData(mo, typeInfo & TypeNameIndexMask);
+ } else {
+ return QMetaType::typeName(typeInfo);
+ }
}
static inline QByteArray typeNameFromTypeInfo(const QMetaObject *mo, uint typeInfo)
@@ -181,16 +190,11 @@ static inline QByteArray typeNameFromTypeInfo(const QMetaObject *mo, uint typeIn
}
}
-static inline const char *rawTypeNameFromTypeInfo(const QMetaObject *mo, uint typeInfo)
-{
- return typeNameFromTypeInfo(mo, typeInfo).constData();
-}
-
static inline int typeFromTypeInfo(const QMetaObject *mo, uint typeInfo)
{
if (!(typeInfo & IsUnresolvedType))
return typeInfo;
- return QMetaType::type(stringData(mo, typeInfo & TypeNameIndexMask));
+ return QMetaType::type(rawStringData(mo, typeInfo & TypeNameIndexMask));
}
class QMetaMethodPrivate : public QMetaMethod
@@ -577,7 +581,7 @@ static bool methodMatch(const QMetaObject *m, int handle,
if (int(m->d.data[handle + 1]) != argc)
return false;
- if (stringData(m, m->d.data[handle]) != name)
+ if (rawStringData(m, m->d.data[handle]) != name)
return false;
int paramsIndex = m->d.data[handle + 2] + 1;
@@ -682,7 +686,9 @@ static void argumentTypesFromString(const char *str, const char *end,
--level;
++str;
}
- types += QArgumentType(QByteArray(begin, str - begin));
+ QByteArray argType(begin, str - begin);
+ argType.replace("QList<", "QVector<");
+ types += QArgumentType(std::move(argType));
}
}
@@ -1161,7 +1167,7 @@ QMetaProperty QMetaObject::property(int index) const
const QMetaObject *scope = nullptr;
if (qstrcmp(scope_name, "Qt") == 0)
- scope = &QObject::staticQtMetaObject;
+ scope = &Qt::staticMetaObject;
else
scope = QMetaObject_findMetaObject(this, scope_name);
if (scope)
@@ -3655,6 +3661,21 @@ const char* QMetaClassInfo::value() const
}
/*!
+ \class QMethodRawArguments
+ \internal
+
+ A wrapper class for the void ** arguments array used by the meta
+ object system. If a slot uses a single argument of this type,
+ the meta object system will pass the raw arguments array directly
+ to the slot and set the arguments count in the slot description to
+ zero, so that any signal can connect to it.
+
+ This is used internally to implement signal relay functionality in
+ our state machine and dbus.
+*/
+
+
+/*!
\macro QGenericArgument Q_ARG(Type, const Type &value)
\relates QMetaObject
diff --git a/src/corelib/kernel/qmetaobject.h b/src/corelib/kernel/qmetaobject.h
index fcd92afd89..31fecd0b07 100644
--- a/src/corelib/kernel/qmetaobject.h
+++ b/src/corelib/kernel/qmetaobject.h
@@ -46,9 +46,6 @@
QT_BEGIN_NAMESPACE
-
-template <typename T> class QList;
-
#define Q_METAMETHOD_INVOKE_MAX_ARGS 10
class Q_CORE_EXPORT QMetaMethod
diff --git a/src/corelib/kernel/qmetaobject_moc_p.h b/src/corelib/kernel/qmetaobject_moc_p.h
index 8c7900767b..471e43f85b 100644
--- a/src/corelib/kernel/qmetaobject_moc_p.h
+++ b/src/corelib/kernel/qmetaobject_moc_p.h
@@ -213,6 +213,9 @@ static QByteArray normalizeTypeInternal(const char *t, const char *e, bool fixSc
}
}
+ // Qt 5 compatibility, make sure we use the correct type name for QList
+ result.replace("QList<", "QVector<");
+
return result;
}
diff --git a/src/corelib/kernel/qmetaobjectbuilder.cpp b/src/corelib/kernel/qmetaobjectbuilder.cpp
index 4ecc340787..d02708540a 100644
--- a/src/corelib/kernel/qmetaobjectbuilder.cpp
+++ b/src/corelib/kernel/qmetaobjectbuilder.cpp
@@ -1103,13 +1103,13 @@ int QMetaStringTable::enter(const QByteArray &value)
int QMetaStringTable::preferredAlignment()
{
- return Q_ALIGNOF(QByteArrayData);
+ return alignof(uint);
}
// Returns the size (in bytes) required for serializing this string table.
int QMetaStringTable::blobSize() const
{
- int size = m_entries.size() * sizeof(QByteArrayData);
+ int size = m_entries.size() * 2*sizeof(uint);
Entries::const_iterator it;
for (it = m_entries.constBegin(); it != m_entries.constEnd(); ++it)
size += it.key().size() + 1;
@@ -1120,14 +1120,12 @@ static void writeString(char *out, int i, const QByteArray &str,
const int offsetOfStringdataMember, int &stringdataOffset)
{
int size = str.size();
- qptrdiff offset = offsetOfStringdataMember + stringdataOffset
- - i * sizeof(QByteArrayData);
- const QByteArrayData data =
- Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset);
+ int offset = offsetOfStringdataMember + stringdataOffset;
+ uint offsetLen[2] = { uint(offset), uint(size) };
- memcpy(out + i * sizeof(QByteArrayData), &data, sizeof(QByteArrayData));
+ memcpy(out + 2 * i * sizeof(uint), &offsetLen, 2*sizeof(uint));
- memcpy(out + offsetOfStringdataMember + stringdataOffset, str.constData(), size);
+ memcpy(out + offset, str.constData(), size);
out[offsetOfStringdataMember + stringdataOffset + size] = '\0';
stringdataOffset += size + 1;
@@ -1141,7 +1139,7 @@ void QMetaStringTable::writeBlob(char *out) const
{
Q_ASSERT(!(reinterpret_cast<quintptr>(out) & (preferredAlignment()-1)));
- int offsetOfStringdataMember = m_entries.size() * sizeof(QByteArrayData);
+ int offsetOfStringdataMember = m_entries.size() * 2*sizeof(uint);
int stringdataOffset = 0;
// qt_metacast expects the first string in the string table to be the class name.
@@ -1282,10 +1280,10 @@ static int buildMetaObject(QMetaObjectBuilderPrivate *d, char *buf,
char *str = reinterpret_cast<char *>(buf + size);
if (buf) {
if (relocatable) {
- meta->d.stringdata = reinterpret_cast<const QByteArrayData *>((quintptr)size);
+ meta->d.stringdata = reinterpret_cast<const uint *>((quintptr)size);
meta->d.data = reinterpret_cast<uint *>((quintptr)pmetaSize);
} else {
- meta->d.stringdata = reinterpret_cast<const QByteArrayData *>(str);
+ meta->d.stringdata = reinterpret_cast<const uint *>(str);
meta->d.data = reinterpret_cast<uint *>(data);
}
}
@@ -1553,7 +1551,7 @@ void QMetaObjectBuilder::fromRelocatableData(QMetaObject *output,
quintptr dataOffset = (quintptr)dataMo->d.data;
output->d.superdata = superclass;
- output->d.stringdata = reinterpret_cast<const QByteArrayData *>(buf + stringdataOffset);
+ output->d.stringdata = reinterpret_cast<const uint *>(buf + stringdataOffset);
output->d.data = reinterpret_cast<const uint *>(buf + dataOffset);
output->d.extradata = nullptr;
output->d.relatedMetaObjects = nullptr;
diff --git a/src/corelib/kernel/qmetatype.cpp b/src/corelib/kernel/qmetatype.cpp
index af9a2e0dd2..79d6d0aa93 100644
--- a/src/corelib/kernel/qmetatype.cpp
+++ b/src/corelib/kernel/qmetatype.cpp
@@ -37,6 +37,8 @@
**
****************************************************************************/
+#include <bitset>
+
#include "qmetatype.h"
#include "qmetatype_p.h"
#include "qobjectdefs.h"
@@ -537,13 +539,12 @@ struct DefinedTypesFilter {
#define QT_ADD_STATIC_METATYPE_ALIASES_ITER(MetaTypeName, MetaTypeId, AliasingName, RealNameStr) \
{ RealNameStr, sizeof(RealNameStr) - 1, QMetaType::MetaTypeName },
-#define QT_ADD_STATIC_METATYPE_HACKS_ITER(MetaTypeName, TypeId, Name) \
- QT_ADD_STATIC_METATYPE(MetaTypeName, MetaTypeName, Name)
+
static const struct { const char * typeName; int typeNameLength; int type; } types[] = {
QT_FOR_EACH_STATIC_TYPE(QT_ADD_STATIC_METATYPE)
QT_FOR_EACH_STATIC_ALIAS_TYPE(QT_ADD_STATIC_METATYPE_ALIASES_ITER)
- QT_FOR_EACH_STATIC_HACKS_TYPE(QT_ADD_STATIC_METATYPE_HACKS_ITER)
+ QT_ADD_STATIC_METATYPE(_, QMetaTypeId2<qreal>::MetaType, qreal)
{nullptr, 0, QMetaType::UnknownType}
};
@@ -2457,6 +2458,50 @@ const QMetaObject *metaObjectForQWidget()
return nullptr;
return qMetaObjectWidgetsHelper;
}
+
+void qt5CompatibilityHookPostRegister(int id, const QByteArray &normalizedTypeName)
+{
+ // In Qt6 QList got typedef'ed to QVector. To keep runtime behavior compatibility
+ // with Qt5 we install corresponding aliases. For example if one register
+ // QVector<QVector<int>>
+ // we need to register the type plus all possible aliases:
+ // QVector<QList<int>>
+ // QList<QVector<int>>
+ // QList<QList<int>>
+ // ### Qt6 TODO This is slow, as it allocates couple of strings we would need to
+ // if def this call with something like QT_NO_QLIST
+ const char *vectorName = "QVector<";
+ const char *listName = "QList<";
+
+ auto isSubstringOfAType = [](char c) { return c != ' ' && c != ',' && c != '<'; };
+ QVarLengthArray<int> indexes;
+
+ for (auto containerName: {vectorName, listName}) {
+ for (int i = normalizedTypeName.indexOf(containerName, 0); i != -1; i = normalizedTypeName.indexOf(containerName, i + 1)) {
+ if (!i || (i > 0 && !isSubstringOfAType(normalizedTypeName[i - 1])))
+ indexes.append(i);
+ }
+ }
+ // To avoid problems with the constantly changing size we start replacements
+ // from the end of normalizedTypeName
+ std::sort(indexes.rbegin(), indexes.rend());
+
+ for (quint64 combination = 1; ; ++combination) {
+ std::bitset<64> bits(combination);
+ QByteArray name = normalizedTypeName;
+ for (auto j = 0; j < indexes.size(); ++j) {
+ if (bits.test(j)) {
+ auto i = indexes[j];
+ auto replaceFrom = normalizedTypeName[i + 1] == 'V' ? vectorName : listName;
+ auto replaceTo = normalizedTypeName[i + 1] == 'V' ? listName : vectorName;
+ name.replace(i, sizeof(replaceFrom), replaceTo);
+ }
+ }
+ QMetaType::registerNormalizedTypedef(name, id);
+ if (bits.count() >= size_t(indexes.size()))
+ break;
+ }
+}
}
namespace QtMetaTypePrivate {
diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h
index 825f767425..7628f5f6b3 100644
--- a/src/corelib/kernel/qmetatype.h
+++ b/src/corelib/kernel/qmetatype.h
@@ -151,6 +151,13 @@ inline Q_DECL_CONSTEXPR int qMetaTypeId();
F(QVariantHash, 28, QVariantHash) \
F(QByteArrayList, 49, QByteArrayList) \
+#if QT_CONFIG(shortcut)
+#define QT_FOR_EACH_STATIC_KEYSEQUENCE_CLASS(F)\
+ F(QKeySequence, 75, QKeySequence)
+#else
+#define QT_FOR_EACH_STATIC_KEYSEQUENCE_CLASS(F)
+#endif
+
#define QT_FOR_EACH_STATIC_GUI_CLASS(F)\
F(QFont, 64, QFont) \
F(QPixmap, 65, QPixmap) \
@@ -163,7 +170,7 @@ inline Q_DECL_CONSTEXPR int qMetaTypeId();
F(QRegion, 72, QRegion) \
F(QBitmap, 73, QBitmap) \
F(QCursor, 74, QCursor) \
- F(QKeySequence, 75, QKeySequence) \
+ QT_FOR_EACH_STATIC_KEYSEQUENCE_CLASS(F) \
F(QPen, 76, QPen) \
F(QTextLength, 77, QTextLength) \
F(QTextFormat, 78, QTextFormat) \
@@ -180,10 +187,6 @@ inline Q_DECL_CONSTEXPR int qMetaTypeId();
#define QT_FOR_EACH_STATIC_WIDGETS_CLASS(F)\
F(QSizePolicy, 121, QSizePolicy) \
-// ### FIXME kill that set
-#define QT_FOR_EACH_STATIC_HACKS_TYPE(F)\
- F(QMetaTypeId2<qreal>::MetaType, -1, qreal)
-
// F is a tuple: (QMetaType::TypeName, QMetaType::TypeNameID, AliasingType, "RealType")
#define QT_FOR_EACH_STATIC_ALIAS_TYPE(F)\
F(ULong, -1, ulong, "unsigned long") \
@@ -200,10 +203,11 @@ inline Q_DECL_CONSTEXPR int qMetaTypeId();
F(UInt, -1, uint, "quint32") \
F(LongLong, -1, qlonglong, "qint64") \
F(ULongLong, -1, qulonglong, "quint64") \
+ F(QVariantList, -1, QVariantList, "QVector<QVariant>") \
F(QVariantList, -1, QVariantList, "QList<QVariant>") \
F(QVariantMap, -1, QVariantMap, "QMap<QString,QVariant>") \
F(QVariantHash, -1, QVariantHash, "QHash<QString,QVariant>") \
- F(QByteArrayList, -1, QByteArrayList, "QList<QByteArray>") \
+ F(QByteArrayList, -1, QByteArrayList, "QVector<QByteArray>") \
#define QT_FOR_EACH_STATIC_TYPE(F)\
QT_FOR_EACH_STATIC_PRIMITIVE_TYPE(F)\
@@ -218,7 +222,6 @@ inline Q_DECL_CONSTEXPR int qMetaTypeId();
TypeName = Id,
#define QT_FOR_EACH_AUTOMATIC_TEMPLATE_1ARG(F) \
- F(QList) \
F(QVector) \
F(QQueue) \
F(QStack) \
@@ -500,7 +503,7 @@ public:
typedef void (*Deleter)(void *);
typedef void *(*Creator)(const void *);
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+#if 1 || QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt6: fix this
typedef void (*Destructor)(void *);
typedef void *(*Constructor)(void *, const void *); // TODO Qt6: remove me
#endif
@@ -748,8 +751,6 @@ private:
static bool registerDebugStreamOperatorFunction(const QtPrivate::AbstractDebugStreamFunction *f, int type);
#endif
-// ### Qt6: FIXME: Remove the special Q_CC_MSVC handling, it was introduced to maintain BC.
-#if !defined(Q_NO_TEMPLATE_FRIENDS) && !defined(Q_CC_MSVC)
#ifndef Q_CLANG_QDOC
template<typename, bool> friend struct QtPrivate::ValueTypeIsMetaType;
template<typename, typename> friend struct QtPrivate::ConverterMemberFunction;
@@ -759,9 +760,6 @@ private:
template<typename, bool> friend struct QtPrivate::IsMetaTypePair;
template<typename, typename> friend struct QtPrivate::MetaTypeSmartPointerHelper;
#endif
-#else
-public:
-#endif
static bool registerConverterFunction(const QtPrivate::AbstractConverterFunction *f, int from, int to);
static void unregisterConverterFunction(int from, int to);
private:
@@ -1009,10 +1007,6 @@ struct ContainerAPI : CapabilitiesImpl<T>
};
template<typename T>
-struct ContainerAPI<QList<T> > : CapabilitiesImpl<QList<T> >
-{ static int size(const QList<T> *t) { return t->size(); } };
-
-template<typename T>
struct ContainerAPI<QVector<T> > : CapabilitiesImpl<QVector<T> >
{ static int size(const QVector<T> *t) { return t->size(); } };
@@ -1658,6 +1652,23 @@ namespace QtPrivate
static bool registerConverter(int) { return false; }
};
+ template<class T>
+ struct Qt5CompatibilityHook
+ {
+ static inline void postRegister(int, const QByteArray &) {};
+ };
+
+ Q_CORE_EXPORT void qt5CompatibilityHookPostRegister(int id, const QByteArray &normalizedTypeName);
+
+ template<class T>
+ struct Qt5CompatibilityHook<QVector<T>>
+ {
+ static inline void postRegister(int id, const QByteArray &normalizedTypeName)
+ {
+ qt5CompatibilityHookPostRegister(id, normalizedTypeName);
+ }
+ };
+
Q_CORE_EXPORT bool isBuiltinType(const QByteArray &type);
} // namespace QtPrivate
@@ -1784,6 +1795,7 @@ int qRegisterNormalizedMetaType(const QT_PREPEND_NAMESPACE(QByteArray) &normaliz
QtPrivate::AssociativeContainerConverterHelper<T>::registerConverter(id);
QtPrivate::MetaTypePairHelper<T>::registerConverter(id);
QtPrivate::MetaTypeSmartPointerHelper<T>::registerConverter(id);
+ QtPrivate::Qt5CompatibilityHook<T>::postRegister(id, normalizedTypeName);
}
return id;
@@ -2007,7 +2019,7 @@ typedef QHash<QString, QVariant> QVariantHash;
#ifdef Q_CLANG_QDOC
class QByteArrayList;
#else
-typedef QList<QByteArray> QByteArrayList;
+typedef QVector<QByteArray> QByteArrayList;
#endif
#define Q_DECLARE_METATYPE_TEMPLATE_1ARG(SINGLE_ARG_TEMPLATE) \
diff --git a/src/corelib/kernel/qmetatype_p.h b/src/corelib/kernel/qmetatype_p.h
index d743d5a5c7..f2057e25b4 100644
--- a/src/corelib/kernel/qmetatype_p.h
+++ b/src/corelib/kernel/qmetatype_p.h
@@ -232,9 +232,6 @@ template<> struct TypeDefinition<QRegExp> { static const bool IsAvailable = fals
#if !QT_CONFIG(regularexpression)
template<> struct TypeDefinition<QRegularExpression> { static const bool IsAvailable = false; };
#endif
-#ifdef QT_NO_SHORTCUT
-template<> struct TypeDefinition<QKeySequence> { static const bool IsAvailable = false; };
-#endif
#ifdef QT_NO_CURSOR
template<> struct TypeDefinition<QCursor> { static const bool IsAvailable = false; };
#endif
diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp
index a51b794604..133ccc88d9 100644
--- a/src/corelib/kernel/qobject.cpp
+++ b/src/corelib/kernel/qobject.cpp
@@ -161,7 +161,6 @@ extern "C" Q_CORE_EXPORT void qt_removeObject(QObject *)
#endif
void (*QAbstractDeclarativeData::destroyed)(QAbstractDeclarativeData *, QObject *) = nullptr;
-void (*QAbstractDeclarativeData::destroyed_qml1)(QAbstractDeclarativeData *, QObject *) = nullptr;
void (*QAbstractDeclarativeData::parentChanged)(QAbstractDeclarativeData *, QObject *, QObject *) = nullptr;
void (*QAbstractDeclarativeData::signalEmitted)(QAbstractDeclarativeData *, QObject *, int, void **) = nullptr;
int (*QAbstractDeclarativeData::receivers)(QAbstractDeclarativeData *, const QObject *, int) = nullptr;
@@ -234,10 +233,6 @@ QObjectPrivate::~QObjectPrivate()
if (metaObject) metaObject->objectDestroyed(q_ptr);
-#ifndef QT_NO_USERDATA
- if (extraData)
- qDeleteAll(extraData->userData);
-#endif
delete extraData;
}
@@ -997,15 +992,8 @@ QObject::~QObject()
emit destroyed(this);
}
- if (d->declarativeData) {
- if (static_cast<QAbstractDeclarativeDataImpl*>(d->declarativeData)->ownedByQml1) {
- if (QAbstractDeclarativeData::destroyed_qml1)
- QAbstractDeclarativeData::destroyed_qml1(d->declarativeData, this);
- } else {
- if (QAbstractDeclarativeData::destroyed)
- QAbstractDeclarativeData::destroyed(d->declarativeData, this);
- }
- }
+ if (d->declarativeData && QAbstractDeclarativeData::destroyed)
+ QAbstractDeclarativeData::destroyed(d->declarativeData, this);
QObjectPrivate::ConnectionData *cd = d->connections.loadRelaxed();
if (cd) {
@@ -4249,58 +4237,6 @@ void QObject::dumpObjectInfo() const
}
}
-#ifndef QT_NO_USERDATA
-static QBasicAtomicInteger<uint> user_data_registration = Q_BASIC_ATOMIC_INITIALIZER(0);
-
-/*!
- \internal
- */
-uint QObject::registerUserData()
-{
- return user_data_registration.fetchAndAddRelaxed(1);
-}
-
-/*!
- \fn QObjectUserData::QObjectUserData()
- \internal
- */
-
-/*!
- \internal
- */
-QObjectUserData::~QObjectUserData()
-{
-}
-
-/*!
- \internal
- */
-void QObject::setUserData(uint id, QObjectUserData* data)
-{
- Q_D(QObject);
- if (!d->extraData)
- d->extraData = new QObjectPrivate::ExtraData;
-
- if (d->extraData->userData.size() <= (int) id)
- d->extraData->userData.resize((int) id + 1);
- d->extraData->userData[id] = data;
-}
-
-/*!
- \internal
- */
-QObjectUserData* QObject::userData(uint id) const
-{
- Q_D(const QObject);
- if (!d->extraData)
- return nullptr;
- if ((int)id < d->extraData->userData.size())
- return d->extraData->userData.at(id);
- return nullptr;
-}
-
-#endif // QT_NO_USERDATA
-
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QObject *o)
diff --git a/src/corelib/kernel/qobject.h b/src/corelib/kernel/qobject.h
index f5d7c22e3a..8d9cc3ab83 100644
--- a/src/corelib/kernel/qobject.h
+++ b/src/corelib/kernel/qobject.h
@@ -78,12 +78,6 @@ class QRegExp;
#if QT_CONFIG(regularexpression)
class QRegularExpression;
#endif
-#if !QT_DEPRECATED_SINCE(5, 14) || QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
-# define QT_NO_USERDATA
-#endif
-#ifndef QT_NO_USERDATA
-class QObjectUserData;
-#endif
struct QDynamicMetaObjectData;
typedef QList<QObject*> QObjectList;
@@ -408,15 +402,6 @@ public:
QList<QByteArray> dynamicPropertyNames() const;
#endif // QT_NO_PROPERTIES
-#ifndef QT_NO_USERDATA
- QT_DEPRECATED_VERSION_5_14
- static uint registerUserData();
- QT_DEPRECATED_VERSION_X_5_14("Use setProperty()")
- void setUserData(uint id, QObjectUserData* data);
- QT_DEPRECATED_VERSION_X_5_14("Use property()")
- QObjectUserData* userData(uint id) const;
-#endif // QT_NO_USERDATA
-
Q_SIGNALS:
void destroyed(QObject * = nullptr);
void objectNameChanged(const QString &objectName, QPrivateSignal);
@@ -449,9 +434,6 @@ protected:
protected:
QScopedPointer<QObjectData> d_ptr;
- static const QMetaObject staticQtMetaObject;
- friend inline const QMetaObject *qt_getQtMetaObject() noexcept;
-
friend struct QMetaObject;
friend struct QMetaObjectPrivate;
friend class QMetaCallEvent;
@@ -482,18 +464,6 @@ inline QMetaObject::Connection QObject::connect(const QObject *asender, const ch
const char *amember, Qt::ConnectionType atype) const
{ return connect(asender, asignal, this, amember, atype); }
-inline const QMetaObject *qt_getQtMetaObject() noexcept
-{ return &QObject::staticQtMetaObject; }
-
-#ifndef QT_NO_USERDATA
-class Q_CORE_EXPORT QObjectUserData {
- Q_DISABLE_COPY(QObjectUserData)
-public:
- QObjectUserData() = default;
- virtual ~QObjectUserData();
-};
-#endif
-
#if QT_DEPRECATED_SINCE(5, 0)
template<typename T>
inline QT_DEPRECATED T qFindChild(const QObject *o, const QString &name = QString())
diff --git a/src/corelib/kernel/qobject_p.h b/src/corelib/kernel/qobject_p.h
index 838a9aa8c5..d6e73fbefc 100644
--- a/src/corelib/kernel/qobject_p.h
+++ b/src/corelib/kernel/qobject_p.h
@@ -89,7 +89,6 @@ class Q_CORE_EXPORT QAbstractDeclarativeData
{
public:
static void (*destroyed)(QAbstractDeclarativeData *, QObject *);
- static void (*destroyed_qml1)(QAbstractDeclarativeData *, QObject *);
static void (*parentChanged)(QAbstractDeclarativeData *, QObject *, QObject *);
static void (*signalEmitted)(QAbstractDeclarativeData *, QObject *, int, void **);
static int (*receivers)(QAbstractDeclarativeData *, const QObject *, int);
@@ -97,14 +96,6 @@ public:
static void (*setWidgetParent)(QObject *, QObject *); // Used by the QML engine to specify parents for widgets. Set by QtWidgets.
};
-// This is an implementation of QAbstractDeclarativeData that is identical with
-// the implementation in QtDeclarative and QtQml for the first bit
-struct QAbstractDeclarativeDataImpl : public QAbstractDeclarativeData
-{
- quint32 ownedByQml1:1;
- quint32 unused: 31;
-};
-
class Q_CORE_EXPORT QObjectPrivate : public QObjectData
{
Q_DECLARE_PUBLIC(QObject)
@@ -113,9 +104,6 @@ public:
struct ExtraData
{
ExtraData() {}
- #ifndef QT_NO_USERDATA
- QVector<QObjectUserData *> userData;
- #endif
QList<QByteArray> propertyNames;
QVector<QVariant> propertyValues;
QVector<int> runningTimers;
diff --git a/src/corelib/kernel/qobjectdefs.h b/src/corelib/kernel/qobjectdefs.h
index dc2d832fe5..657cb9940b 100644
--- a/src/corelib/kernel/qobjectdefs.h
+++ b/src/corelib/kernel/qobjectdefs.h
@@ -46,199 +46,15 @@
#endif
#include <QtCore/qnamespace.h>
-
#include <QtCore/qobjectdefs_impl.h>
+#include <QtCore/qtmetamacros.h>
QT_BEGIN_NAMESPACE
-
class QByteArray;
struct QArrayData;
-typedef QArrayData QByteArrayData;
class QString;
-#ifndef Q_MOC_OUTPUT_REVISION
-#define Q_MOC_OUTPUT_REVISION 67
-#endif
-
-// The following macros can be defined by tools that understand Qt
-// to have the information from the macro.
-#ifndef QT_ANNOTATE_CLASS
-# define QT_ANNOTATE_CLASS(type, ...)
-#endif
-#ifndef QT_ANNOTATE_CLASS2
-# define QT_ANNOTATE_CLASS2(type, a1, a2)
-#endif
-#ifndef QT_ANNOTATE_FUNCTION
-# define QT_ANNOTATE_FUNCTION(x)
-#endif
-#ifndef QT_ANNOTATE_ACCESS_SPECIFIER
-# define QT_ANNOTATE_ACCESS_SPECIFIER(x)
-#endif
-
-// The following macros are our "extensions" to C++
-// They are used, strictly speaking, only by the moc.
-
-#ifndef Q_MOC_RUN
-#ifndef QT_NO_META_MACROS
-# if defined(QT_NO_KEYWORDS)
-# define QT_NO_EMIT
-# else
-# ifndef QT_NO_SIGNALS_SLOTS_KEYWORDS
-# define slots Q_SLOTS
-# define signals Q_SIGNALS
-# endif
-# endif
-# define Q_SLOTS QT_ANNOTATE_ACCESS_SPECIFIER(qt_slot)
-# define Q_SIGNALS public QT_ANNOTATE_ACCESS_SPECIFIER(qt_signal)
-# define Q_PRIVATE_SLOT(d, signature) QT_ANNOTATE_CLASS2(qt_private_slot, d, signature)
-# define Q_EMIT
-#ifndef QT_NO_EMIT
-# define emit
-#endif
-#ifndef Q_CLASSINFO
-# define Q_CLASSINFO(name, value)
-#endif
-#define Q_PLUGIN_METADATA(x) QT_ANNOTATE_CLASS(qt_plugin_metadata, x)
-#define Q_INTERFACES(x) QT_ANNOTATE_CLASS(qt_interfaces, x)
-#define Q_PROPERTY(...) QT_ANNOTATE_CLASS(qt_property, __VA_ARGS__)
-#define Q_PRIVATE_PROPERTY(d, text) QT_ANNOTATE_CLASS2(qt_private_property, d, text)
-#ifndef Q_REVISION
-# define Q_REVISION(v)
-#endif
-#define Q_OVERRIDE(text) QT_ANNOTATE_CLASS(qt_override, text)
-#define QDOC_PROPERTY(text) QT_ANNOTATE_CLASS(qt_qdoc_property, text)
-#define Q_ENUMS(x) QT_ANNOTATE_CLASS(qt_enums, x)
-#define Q_FLAGS(x) QT_ANNOTATE_CLASS(qt_enums, x)
-#define Q_ENUM_IMPL(ENUM) \
- friend Q_DECL_CONSTEXPR const QMetaObject *qt_getEnumMetaObject(ENUM) noexcept { return &staticMetaObject; } \
- friend Q_DECL_CONSTEXPR const char *qt_getEnumName(ENUM) noexcept { return #ENUM; }
-#define Q_ENUM(x) Q_ENUMS(x) Q_ENUM_IMPL(x)
-#define Q_FLAG(x) Q_FLAGS(x) Q_ENUM_IMPL(x)
-#define Q_ENUM_NS_IMPL(ENUM) \
- inline Q_DECL_CONSTEXPR const QMetaObject *qt_getEnumMetaObject(ENUM) noexcept { return &staticMetaObject; } \
- inline Q_DECL_CONSTEXPR const char *qt_getEnumName(ENUM) noexcept { return #ENUM; }
-#define Q_ENUM_NS(x) Q_ENUMS(x) Q_ENUM_NS_IMPL(x)
-#define Q_FLAG_NS(x) Q_FLAGS(x) Q_ENUM_NS_IMPL(x)
-#define Q_SCRIPTABLE QT_ANNOTATE_FUNCTION(qt_scriptable)
-#define Q_INVOKABLE QT_ANNOTATE_FUNCTION(qt_invokable)
-#define Q_SIGNAL QT_ANNOTATE_FUNCTION(qt_signal)
-#define Q_SLOT QT_ANNOTATE_FUNCTION(qt_slot)
-#endif // QT_NO_META_MACROS
-
-#ifndef QT_NO_TRANSLATION
-// full set of tr functions
-# define QT_TR_FUNCTIONS \
- static inline QString tr(const char *s, const char *c = nullptr, int n = -1) \
- { return staticMetaObject.tr(s, c, n); } \
- QT_DEPRECATED static inline QString trUtf8(const char *s, const char *c = nullptr, int n = -1) \
- { return staticMetaObject.tr(s, c, n); }
-#else
-// inherit the ones from QObject
-# define QT_TR_FUNCTIONS
-#endif
-
-#ifdef Q_CLANG_QDOC
-#define QT_TR_FUNCTIONS
-#endif
-
-// ### Qt6: remove
-#define Q_OBJECT_CHECK /* empty, unused since Qt 5.2 */
-
-#if defined(Q_CC_INTEL)
-// Cannot redefine the visibility of a method in an exported class
-# define Q_DECL_HIDDEN_STATIC_METACALL
-#else
-# define Q_DECL_HIDDEN_STATIC_METACALL Q_DECL_HIDDEN
-#endif
-
-#if defined(Q_CC_CLANG) && Q_CC_CLANG >= 306
-# define Q_OBJECT_NO_OVERRIDE_WARNING QT_WARNING_DISABLE_CLANG("-Winconsistent-missing-override")
-#elif defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && Q_CC_GNU >= 501
-# define Q_OBJECT_NO_OVERRIDE_WARNING QT_WARNING_DISABLE_GCC("-Wsuggest-override")
-#else
-# define Q_OBJECT_NO_OVERRIDE_WARNING
-#endif
-
-#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && Q_CC_GNU >= 600
-# define Q_OBJECT_NO_ATTRIBUTES_WARNING QT_WARNING_DISABLE_GCC("-Wattributes")
-#else
-# define Q_OBJECT_NO_ATTRIBUTES_WARNING
-#endif
-
-/* qmake ignore Q_OBJECT */
-#define Q_OBJECT \
-public: \
- QT_WARNING_PUSH \
- Q_OBJECT_NO_OVERRIDE_WARNING \
- static const QMetaObject staticMetaObject; \
- virtual const QMetaObject *metaObject() const; \
- virtual void *qt_metacast(const char *); \
- virtual int qt_metacall(QMetaObject::Call, int, void **); \
- QT_TR_FUNCTIONS \
-private: \
- Q_OBJECT_NO_ATTRIBUTES_WARNING \
- Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \
- QT_WARNING_POP \
- struct QPrivateSignal {}; \
- QT_ANNOTATE_CLASS(qt_qobject, "")
-
-/* qmake ignore Q_OBJECT */
-#define Q_OBJECT_FAKE Q_OBJECT QT_ANNOTATE_CLASS(qt_fake, "")
-
-#ifndef QT_NO_META_MACROS
-/* qmake ignore Q_GADGET */
-#define Q_GADGET \
-public: \
- static const QMetaObject staticMetaObject; \
- void qt_check_for_QGADGET_macro(); \
- typedef void QtGadgetHelper; \
-private: \
- QT_WARNING_PUSH \
- Q_OBJECT_NO_ATTRIBUTES_WARNING \
- Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \
- QT_WARNING_POP \
- QT_ANNOTATE_CLASS(qt_qgadget, "") \
- /*end*/
-
-/* qmake ignore Q_NAMESPACE_EXPORT */
-#define Q_NAMESPACE_EXPORT(...) \
- extern __VA_ARGS__ const QMetaObject staticMetaObject; \
- QT_ANNOTATE_CLASS(qt_qnamespace, "") \
- /*end*/
-
-/* qmake ignore Q_NAMESPACE */
-#define Q_NAMESPACE Q_NAMESPACE_EXPORT() \
- /*end*/
-
-#endif // QT_NO_META_MACROS
-
-#else // Q_MOC_RUN
-#define slots slots
-#define signals signals
-#define Q_SLOTS Q_SLOTS
-#define Q_SIGNALS Q_SIGNALS
-#define Q_CLASSINFO(name, value) Q_CLASSINFO(name, value)
-#define Q_INTERFACES(x) Q_INTERFACES(x)
-#define Q_PROPERTY(text) Q_PROPERTY(text)
-#define Q_PRIVATE_PROPERTY(d, text) Q_PRIVATE_PROPERTY(d, text)
-#define Q_REVISION(v) Q_REVISION(v)
-#define Q_OVERRIDE(text) Q_OVERRIDE(text)
-#define Q_ENUMS(x) Q_ENUMS(x)
-#define Q_FLAGS(x) Q_FLAGS(x)
-#define Q_ENUM(x) Q_ENUM(x)
-#define Q_FLAGS(x) Q_FLAGS(x)
- /* qmake ignore Q_OBJECT */
-#define Q_OBJECT Q_OBJECT
- /* qmake ignore Q_OBJECT */
-#define Q_OBJECT_FAKE Q_OBJECT_FAKE
- /* qmake ignore Q_GADGET */
-#define Q_GADGET Q_GADGET
-#define Q_SCRIPTABLE Q_SCRIPTABLE
-#define Q_INVOKABLE Q_INVOKABLE
-#define Q_SIGNAL Q_SIGNAL
-#define Q_SLOT Q_SLOT
-#endif //Q_MOC_RUN
#ifndef QT_NO_META_MACROS
// macro for onaming members
@@ -285,6 +101,10 @@ class QMetaEnum;
class QMetaProperty;
class QMetaClassInfo;
+struct QMethodRawArguments
+{
+ void **arguments;
+};
class Q_CORE_EXPORT QGenericArgument
{
@@ -603,7 +423,7 @@ struct Q_CORE_EXPORT QMetaObject
struct { // private data
SuperData superdata;
- const QByteArrayData *stringdata;
+ const uint *stringdata;
const uint *data;
typedef void (*StaticMetacallFunction)(QObject *, QMetaObject::Call, int, void **);
StaticMetacallFunction static_metacall;
diff --git a/src/corelib/kernel/qtmetamacros.h b/src/corelib/kernel/qtmetamacros.h
new file mode 100644
index 0000000000..19b6bfa358
--- /dev/null
+++ b/src/corelib/kernel/qtmetamacros.h
@@ -0,0 +1,233 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Copyright (C) 2019 Olivier Goffart <ogoffart@woboq.com>
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTMETAMACROS_H
+#define QTMETAMACROS_H
+
+#include <QtCore/qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+#ifndef Q_MOC_OUTPUT_REVISION
+#define Q_MOC_OUTPUT_REVISION 67
+#endif
+
+// The following macros can be defined by tools that understand Qt
+// to have the information from the macro.
+#ifndef QT_ANNOTATE_CLASS
+# define QT_ANNOTATE_CLASS(type, ...)
+#endif
+#ifndef QT_ANNOTATE_CLASS2
+# define QT_ANNOTATE_CLASS2(type, a1, a2)
+#endif
+#ifndef QT_ANNOTATE_FUNCTION
+# define QT_ANNOTATE_FUNCTION(x)
+#endif
+#ifndef QT_ANNOTATE_ACCESS_SPECIFIER
+# define QT_ANNOTATE_ACCESS_SPECIFIER(x)
+#endif
+
+// The following macros are our "extensions" to C++
+// They are used, strictly speaking, only by the moc.
+
+#ifndef Q_MOC_RUN
+#ifndef QT_NO_META_MACROS
+# if defined(QT_NO_KEYWORDS)
+# define QT_NO_EMIT
+# else
+# ifndef QT_NO_SIGNALS_SLOTS_KEYWORDS
+# define slots Q_SLOTS
+# define signals Q_SIGNALS
+# endif
+# endif
+# define Q_SLOTS QT_ANNOTATE_ACCESS_SPECIFIER(qt_slot)
+# define Q_SIGNALS public QT_ANNOTATE_ACCESS_SPECIFIER(qt_signal)
+# define Q_PRIVATE_SLOT(d, signature) QT_ANNOTATE_CLASS2(qt_private_slot, d, signature)
+# define Q_EMIT
+#ifndef QT_NO_EMIT
+# define emit
+#endif
+#ifndef Q_CLASSINFO
+# define Q_CLASSINFO(name, value)
+#endif
+#define Q_PLUGIN_METADATA(x) QT_ANNOTATE_CLASS(qt_plugin_metadata, x)
+#define Q_INTERFACES(x) QT_ANNOTATE_CLASS(qt_interfaces, x)
+#define Q_PROPERTY(...) QT_ANNOTATE_CLASS(qt_property, __VA_ARGS__)
+#define Q_PRIVATE_PROPERTY(d, text) QT_ANNOTATE_CLASS2(qt_private_property, d, text)
+#ifndef Q_REVISION
+# define Q_REVISION(v)
+#endif
+#define Q_OVERRIDE(text) QT_ANNOTATE_CLASS(qt_override, text)
+#define QDOC_PROPERTY(text) QT_ANNOTATE_CLASS(qt_qdoc_property, text)
+#define Q_ENUMS(x) QT_ANNOTATE_CLASS(qt_enums, x)
+#define Q_FLAGS(x) QT_ANNOTATE_CLASS(qt_enums, x)
+#define Q_ENUM_IMPL(ENUM) \
+ friend Q_DECL_CONSTEXPR const QMetaObject *qt_getEnumMetaObject(ENUM) noexcept { return &staticMetaObject; } \
+ friend Q_DECL_CONSTEXPR const char *qt_getEnumName(ENUM) noexcept { return #ENUM; }
+#define Q_ENUM(x) Q_ENUMS(x) Q_ENUM_IMPL(x)
+#define Q_FLAG(x) Q_FLAGS(x) Q_ENUM_IMPL(x)
+#define Q_ENUM_NS_IMPL(ENUM) \
+ inline Q_DECL_CONSTEXPR const QMetaObject *qt_getEnumMetaObject(ENUM) noexcept { return &staticMetaObject; } \
+ inline Q_DECL_CONSTEXPR const char *qt_getEnumName(ENUM) noexcept { return #ENUM; }
+#define Q_ENUM_NS(x) Q_ENUMS(x) Q_ENUM_NS_IMPL(x)
+#define Q_FLAG_NS(x) Q_FLAGS(x) Q_ENUM_NS_IMPL(x)
+#define Q_SCRIPTABLE QT_ANNOTATE_FUNCTION(qt_scriptable)
+#define Q_INVOKABLE QT_ANNOTATE_FUNCTION(qt_invokable)
+#define Q_SIGNAL QT_ANNOTATE_FUNCTION(qt_signal)
+#define Q_SLOT QT_ANNOTATE_FUNCTION(qt_slot)
+#endif // QT_NO_META_MACROS
+
+#ifndef QT_NO_TRANSLATION
+// full set of tr functions
+# define QT_TR_FUNCTIONS \
+ static inline QString tr(const char *s, const char *c = nullptr, int n = -1) \
+ { return staticMetaObject.tr(s, c, n); } \
+ QT_DEPRECATED static inline QString trUtf8(const char *s, const char *c = nullptr, int n = -1) \
+ { return staticMetaObject.tr(s, c, n); }
+#else
+// inherit the ones from QObject
+# define QT_TR_FUNCTIONS
+#endif
+
+#ifdef Q_CLANG_QDOC
+#define QT_TR_FUNCTIONS
+#endif
+
+// ### Qt6: remove
+#define Q_OBJECT_CHECK /* empty, unused since Qt 5.2 */
+
+#if defined(Q_CC_INTEL)
+// Cannot redefine the visibility of a method in an exported class
+# define Q_DECL_HIDDEN_STATIC_METACALL
+#else
+# define Q_DECL_HIDDEN_STATIC_METACALL Q_DECL_HIDDEN
+#endif
+
+#if defined(Q_CC_CLANG) && Q_CC_CLANG >= 306
+# define Q_OBJECT_NO_OVERRIDE_WARNING QT_WARNING_DISABLE_CLANG("-Winconsistent-missing-override")
+#elif defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && Q_CC_GNU >= 501
+# define Q_OBJECT_NO_OVERRIDE_WARNING QT_WARNING_DISABLE_GCC("-Wsuggest-override")
+#else
+# define Q_OBJECT_NO_OVERRIDE_WARNING
+#endif
+
+#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && Q_CC_GNU >= 600
+# define Q_OBJECT_NO_ATTRIBUTES_WARNING QT_WARNING_DISABLE_GCC("-Wattributes")
+#else
+# define Q_OBJECT_NO_ATTRIBUTES_WARNING
+#endif
+
+/* qmake ignore Q_OBJECT */
+#define Q_OBJECT \
+public: \
+ QT_WARNING_PUSH \
+ Q_OBJECT_NO_OVERRIDE_WARNING \
+ static const QMetaObject staticMetaObject; \
+ virtual const QMetaObject *metaObject() const; \
+ virtual void *qt_metacast(const char *); \
+ virtual int qt_metacall(QMetaObject::Call, int, void **); \
+ QT_TR_FUNCTIONS \
+private: \
+ Q_OBJECT_NO_ATTRIBUTES_WARNING \
+ Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \
+ QT_WARNING_POP \
+ struct QPrivateSignal {}; \
+ QT_ANNOTATE_CLASS(qt_qobject, "")
+
+/* qmake ignore Q_OBJECT */
+#define Q_OBJECT_FAKE Q_OBJECT QT_ANNOTATE_CLASS(qt_fake, "")
+
+#ifndef QT_NO_META_MACROS
+/* qmake ignore Q_GADGET */
+#define Q_GADGET \
+public: \
+ static const QMetaObject staticMetaObject; \
+ void qt_check_for_QGADGET_macro(); \
+ typedef void QtGadgetHelper; \
+private: \
+ QT_WARNING_PUSH \
+ Q_OBJECT_NO_ATTRIBUTES_WARNING \
+ Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \
+ QT_WARNING_POP \
+ QT_ANNOTATE_CLASS(qt_qgadget, "") \
+ /*end*/
+
+/* qmake ignore Q_NAMESPACE_EXPORT */
+#define Q_NAMESPACE_EXPORT(...) \
+ extern __VA_ARGS__ const QMetaObject staticMetaObject; \
+ QT_ANNOTATE_CLASS(qt_qnamespace, "") \
+ /*end*/
+
+/* qmake ignore Q_NAMESPACE */
+#define Q_NAMESPACE Q_NAMESPACE_EXPORT() \
+ /*end*/
+
+#endif // QT_NO_META_MACROS
+
+#else // Q_MOC_RUN
+#define slots slots
+#define signals signals
+#define Q_SLOTS Q_SLOTS
+#define Q_SIGNALS Q_SIGNALS
+#define Q_CLASSINFO(name, value) Q_CLASSINFO(name, value)
+#define Q_INTERFACES(x) Q_INTERFACES(x)
+#define Q_PROPERTY(text) Q_PROPERTY(text)
+#define Q_PRIVATE_PROPERTY(d, text) Q_PRIVATE_PROPERTY(d, text)
+#define Q_REVISION(v) Q_REVISION(v)
+#define Q_OVERRIDE(text) Q_OVERRIDE(text)
+#define Q_ENUMS(x) Q_ENUMS(x)
+#define Q_FLAGS(x) Q_FLAGS(x)
+#define Q_ENUM(x) Q_ENUM(x)
+#define Q_FLAGS(x) Q_FLAGS(x)
+ /* qmake ignore Q_OBJECT */
+#define Q_OBJECT Q_OBJECT
+ /* qmake ignore Q_OBJECT */
+#define Q_OBJECT_FAKE Q_OBJECT_FAKE
+ /* qmake ignore Q_GADGET */
+#define Q_GADGET Q_GADGET
+#define Q_SCRIPTABLE Q_SCRIPTABLE
+#define Q_INVOKABLE Q_INVOKABLE
+#define Q_SIGNAL Q_SIGNAL
+#define Q_SLOT Q_SLOT
+#endif //Q_MOC_RUN
+
+QT_END_NAMESPACE
+
+#endif // QTMETAMACROS_H
diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp
index 93d75feafa..4bd8874630 100644
--- a/src/corelib/kernel/qtranslator.cpp
+++ b/src/corelib/kernel/qtranslator.cpp
@@ -58,11 +58,11 @@
#include "qendian.h"
#include "qresource.h"
-#if defined(Q_OS_UNIX) && !defined(Q_OS_INTEGRITY)
-#define QT_USE_MMAP
-#include "private/qcore_unix_p.h"
+#if defined(Q_OS_UNIX) && !defined(Q_OS_NACL) && !defined(Q_OS_INTEGRITY)
+# define QT_USE_MMAP
+# include "private/qcore_unix_p.h"
// for mmap
-#include <sys/mman.h>
+# include <sys/mman.h>
#endif
#include <stdlib.h>
diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp
index f3ac3fcdba..888da17a98 100644
--- a/src/corelib/kernel/qvariant.cpp
+++ b/src/corelib/kernel/qvariant.cpp
@@ -1470,7 +1470,7 @@ static void customConstruct(QVariant::Private *d, const void *copy)
} else {
// Private::Data contains long long, and long double is the biggest standard type.
const size_t maxAlignment =
- qMax(Q_ALIGNOF(QVariant::Private::Data), Q_ALIGNOF(long double));
+ qMax(alignof(QVariant::Private::Data), alignof(long double));
const size_t s = sizeof(QVariant::PrivateShared);
const size_t offset = s + ((s * maxAlignment - s) % maxAlignment);
void *data = operator new(offset + size);
@@ -2469,7 +2469,9 @@ static const ushort mapIdFromQt3ToCurrent[MapFromThreeCount] =
QVariant::DateTime,
QVariant::ByteArray,
QVariant::BitArray,
+#if QT_CONFIG(shortcut)
QVariant::KeySequence,
+#endif
QVariant::Pen,
QVariant::LongLong,
QVariant::ULongLong,
@@ -2574,7 +2576,11 @@ void QVariant::save(QDataStream &s) const
typeId += 97;
} else if (typeId == QMetaType::QSizePolicy) {
typeId = 75;
+#if QT_CONFIG(shortcut)
} else if (typeId >= QMetaType::QKeySequence && typeId <= QMetaType::QQuaternion) {
+#else
+ } else if (typeId >= QMetaType::QPen && typeId <= QMetaType::QQuaternion) {
+#endif
// and as a result these types received lower ids too
typeId +=1;
} else if (typeId == QMetaType::QPolygonF || typeId == QMetaType::QUuid) {
@@ -3647,9 +3653,11 @@ bool QVariant::canConvert(int targetTypeId) const
if (currentType > int(QMetaType::QUuid) || targetTypeId > int(QMetaType::QUuid)) {
switch (uint(targetTypeId)) {
case QVariant::Int:
+#if QT_CONFIG(shortcut)
if (currentType == QVariant::KeySequence)
return true;
Q_FALLTHROUGH();
+#endif
case QVariant::UInt:
case QVariant::LongLong:
case QVariant::ULongLong:
@@ -3672,11 +3680,16 @@ bool QVariant::canConvert(int targetTypeId) const
return currentType == QVariant::Color || currentType == QMetaType::Nullptr
|| ((QMetaType::typeFlags(currentType) & QMetaType::IsEnumeration) && QMetaType::metaObjectForType(currentType));
case QVariant::String:
- return currentType == QVariant::KeySequence || currentType == QVariant::Font
- || currentType == QVariant::Color || currentType == QMetaType::Nullptr
- || ((QMetaType::typeFlags(currentType) & QMetaType::IsEnumeration) && QMetaType::metaObjectForType(currentType));
+ return currentType == QVariant::Font
+ || currentType == QVariant::Color || currentType == QMetaType::Nullptr
+#if QT_CONFIG(shortcut)
+ || currentType == QVariant::KeySequence
+#endif
+ || ((QMetaType::typeFlags(currentType) & QMetaType::IsEnumeration) && QMetaType::metaObjectForType(currentType));
+#if QT_CONFIG(shortcut)
case QVariant::KeySequence:
return currentType == QVariant::String || currentType == QVariant::Int;
+#endif
case QVariant::Font:
return currentType == QVariant::String;
case QVariant::Color:
@@ -3827,72 +3840,6 @@ bool QVariant::convert(const int type, void *ptr) const
QMetaType::registerComparators().
*/
-/*!
- \fn bool QVariant::operator<(const QVariant &v) const
- \obsolete
-
- Compares this QVariant with \a v and returns \c true if this is less than \a v.
-
- \note Comparability might not be availabe for the type stored in this QVariant
- or in \a v.
-
- \warning To make this function work with a custom type registered with
- qRegisterMetaType(), its comparison operator must be registered using
- QMetaType::registerComparators().
-
- This operator is deprecated as it cannot establish a total order required
- for most use of this operator, which is the reason you cannot use QVariant
- as the key of a QMap.
-*/
-
-/*!
- \fn bool QVariant::operator<=(const QVariant &v) const
- \obsolete
-
- Compares this QVariant with \a v and returns \c true if this is less or equal than \a v.
-
- \note Comparability might not be available for the type stored in this QVariant
- or in \a v.
-
- \warning To make this function work with a custom type registered with
- qRegisterMetaType(), its comparison operator must be registered using
- QMetaType::registerComparators().
-
- This operator is deprecated as it cannot establish a total order.
-*/
-
-/*!
- \fn bool QVariant::operator>(const QVariant &v) const
- \obsolete
-
- Compares this QVariant with \a v and returns \c true if this is larger than \a v.
-
- \note Comparability might not be available for the type stored in this QVariant
- or in \a v.
-
- \warning To make this function work with a custom type registered with
- qRegisterMetaType(), its comparison operator must be registered using
- QMetaType::registerComparators().
-
- This operator is deprecated as it cannot establish a total order.
-*/
-
-/*!
- \fn bool QVariant::operator>=(const QVariant &v) const
- \obsolete
-
- Compares this QVariant with \a v and returns \c true if this is larger or equal than \a v.
-
- \note Comparability might not be available for the type stored in this QVariant
- or in \a v.
-
- \warning To make this function work with a custom type registered with
- qRegisterMetaType(), its comparison operator must be registered using
- QMetaType::registerComparators().
-
- This operator is deprecated as it cannot establish a total order.
-*/
-
static bool qIsNumericType(uint tp)
{
static const qulonglong numericTypeBits =
@@ -4073,73 +4020,6 @@ bool QVariant::cmp(const QVariant &v) const
/*!
\internal
*/
-int QVariant::compare(const QVariant &v) const
-{
- // try numerics first, with C++ type promotion rules (no conversion)
- if (qIsNumericType(d.type) && qIsNumericType(v.d.type))
- return numericCompare(&d, &v.d);
-
- // check for equality next, as more types implement operator== than operator<
- if (cmp(v))
- return 0;
-
- const QVariant *v1 = this;
- const QVariant *v2 = &v;
- QVariant converted1;
- QVariant converted2;
-
- if (d.type != v.d.type) {
- // if both types differ, try to convert
- if (v2->canConvert(v1->d.type)) {
- converted2 = *v2;
- if (converted2.convert(v1->d.type))
- v2 = &converted2;
- }
- if (v1->d.type != v2->d.type && v1->canConvert(v2->d.type)) {
- converted1 = *v1;
- if (converted1.convert(v2->d.type))
- v1 = &converted1;
- }
- if (v1->d.type != v2->d.type) {
- // if conversion fails, default to toString
- int r = v1->toString().compare(v2->toString(), Qt::CaseInsensitive);
- if (r == 0) {
- // cmp(v) returned false, so we should try to agree with it.
- return (v1->d.type < v2->d.type) ? -1 : 1;
- }
- return r;
- }
-
- // did we end up with two numerics? If so, restart
- if (qIsNumericType(v1->d.type) && qIsNumericType(v2->d.type))
- return v1->compare(*v2);
- }
- if (v1->d.type >= QMetaType::User) {
- int result;
- if (QMetaType::compare(QT_PREPEND_NAMESPACE(constData(d)), QT_PREPEND_NAMESPACE(constData(v2->d)), d.type, &result))
- return result;
- }
- switch (v1->d.type) {
- case QVariant::Date:
- return v1->toDate() < v2->toDate() ? -1 : 1;
- case QVariant::Time:
- return v1->toTime() < v2->toTime() ? -1 : 1;
- case QVariant::DateTime:
- return v1->toDateTime() < v2->toDateTime() ? -1 : 1;
- case QVariant::StringList:
- return v1->toStringList() < v2->toStringList() ? -1 : 1;
- }
- int r = v1->toString().compare(v2->toString(), Qt::CaseInsensitive);
- if (r == 0) {
- // cmp(v) returned false, so we should try to agree with it.
- return (d.type < v.d.type) ? -1 : 1;
- }
- return r;
-}
-
-/*!
- \internal
- */
const void *QVariant::constData() const
{
diff --git a/src/corelib/kernel/qvariant.h b/src/corelib/kernel/qvariant.h
index 24657818c5..353bfa7ce7 100644
--- a/src/corelib/kernel/qvariant.h
+++ b/src/corelib/kernel/qvariant.h
@@ -184,7 +184,9 @@ class Q_CORE_EXPORT QVariant
Region = QMetaType::QRegion,
Bitmap = QMetaType::QBitmap,
Cursor = QMetaType::QCursor,
+#if QT_CONFIG(shortcut)
KeySequence = QMetaType::QKeySequence,
+#endif
Pen = QMetaType::QPen,
TextLength = QMetaType::QTextLength,
TextFormat = QMetaType::QTextFormat,
@@ -394,7 +396,7 @@ class Q_CORE_EXPORT QVariant
struct Private
{
inline Private() noexcept : type(Invalid), is_shared(false), is_null(true)
- { data.ptr = nullptr; }
+ {}
// Internal constructor for initialized variants.
explicit inline Private(uint variantType) noexcept
@@ -410,6 +412,7 @@ class Q_CORE_EXPORT QVariant
#endif
union Data
{
+ void *threeptr[3] = { nullptr, nullptr, nullptr };
char c;
uchar uc;
short s;
@@ -463,16 +466,6 @@ class Q_CORE_EXPORT QVariant
{ return cmp(v); }
inline bool operator!=(const QVariant &v) const
{ return !cmp(v); }
-#if QT_DEPRECATED_SINCE(5, 15)
- QT_DEPRECATED inline bool operator<(const QVariant &v) const
- { return compare(v) < 0; }
- QT_DEPRECATED inline bool operator<=(const QVariant &v) const
- { return compare(v) <= 0; }
- QT_DEPRECATED inline bool operator>(const QVariant &v) const
- { return compare(v) > 0; }
- QT_DEPRECATED inline bool operator>=(const QVariant &v) const
- { return compare(v) >= 0; }
-#endif
protected:
friend inline bool operator==(const QVariant &, const QVariantComparisonHelper &);
@@ -491,7 +484,6 @@ public:
Private d;
void create(int type, const void *copy);
bool cmp(const QVariant &other) const;
- int compare(const QVariant &other) const;
bool convert(const int t, void *ptr) const; // ### Qt6: drop const
private:
diff --git a/src/corelib/mimetypes/qmimedatabase.cpp b/src/corelib/mimetypes/qmimedatabase.cpp
index 10b2190966..f1d0dc859e 100644
--- a/src/corelib/mimetypes/qmimedatabase.cpp
+++ b/src/corelib/mimetypes/qmimedatabase.cpp
@@ -91,8 +91,8 @@ bool QMimeDatabasePrivate::shouldCheck()
return true;
}
-#if defined(Q_OS_UNIX) && !defined(Q_OS_INTEGRITY)
-#define QT_USE_MMAP
+#if defined(Q_OS_UNIX) && !defined(Q_OS_NACL) && !defined(Q_OS_INTEGRITY)
+# define QT_USE_MMAP
#endif
void QMimeDatabasePrivate::loadProviders()
diff --git a/src/corelib/mimetypes/qmimedatabase_p.h b/src/corelib/mimetypes/qmimedatabase_p.h
index d9cf446d44..831390de1f 100644
--- a/src/corelib/mimetypes/qmimedatabase_p.h
+++ b/src/corelib/mimetypes/qmimedatabase_p.h
@@ -63,6 +63,7 @@ QT_REQUIRE_CONFIG(mimetype);
#include <QtCore/qmutex.h>
#include <QtCore/qvector.h>
+#include <vector>
#include <memory>
QT_BEGIN_NAMESPACE
diff --git a/src/corelib/plugin/qlibrary.cpp b/src/corelib/plugin/qlibrary.cpp
index b3a95d4f26..406a83c7dd 100644
--- a/src/corelib/plugin/qlibrary.cpp
+++ b/src/corelib/plugin/qlibrary.cpp
@@ -692,7 +692,7 @@ static bool qt_get_metadata(QLibraryPrivate *priv, QString *errMsg)
};
#else
auto getMetaData = [](QFunctionPointer fptr) {
- auto f = reinterpret_cast<QPair<const char *, size_t> (*)()>(fptr);
+ auto f = reinterpret_cast<QPluginMetaData (*)()>(fptr);
return f();
};
#endif
@@ -702,7 +702,7 @@ static bool qt_get_metadata(QLibraryPrivate *priv, QString *errMsg)
return false;
auto metaData = getMetaData(pfn);
- QJsonDocument doc = qJsonFromRawLibraryMetaData(metaData.first, metaData.second, errMsg);
+ QJsonDocument doc = qJsonFromRawLibraryMetaData(reinterpret_cast<const char *>(metaData.data), metaData.size, errMsg);
if (doc.isNull())
return false;
priv->metaData = doc.object();
diff --git a/src/corelib/serialization/qbinaryjsonvalue.cpp b/src/corelib/serialization/qbinaryjsonvalue.cpp
index 5e3a01ad38..7d0bc3d366 100644
--- a/src/corelib/serialization/qbinaryjsonvalue.cpp
+++ b/src/corelib/serialization/qbinaryjsonvalue.cpp
@@ -63,12 +63,9 @@ QBinaryJsonValue::QBinaryJsonValue(QBinaryJsonPrivate::MutableData *data,
case QJsonValue::Double:
dbl = v.toDouble(parent);
break;
- case QJsonValue::String: {
- QString s = v.toString(parent);
- stringData = s.data_ptr();
- stringData->ref.ref();
+ case QJsonValue::String:
+ stringData = v.toString(parent);
break;
- }
case QJsonValue::Array:
case QJsonValue::Object:
d = data;
@@ -80,9 +77,9 @@ QBinaryJsonValue::QBinaryJsonValue(QBinaryJsonPrivate::MutableData *data,
}
QBinaryJsonValue::QBinaryJsonValue(QString string)
- : stringData(*reinterpret_cast<QStringData **>(&string)), t(QJsonValue::String)
+ : d(nullptr), t(QJsonValue::String)
{
- stringData->ref.ref();
+ stringData = std::move(string);
}
QBinaryJsonValue::QBinaryJsonValue(const QBinaryJsonArray &a)
@@ -101,9 +98,6 @@ QBinaryJsonValue::QBinaryJsonValue(const QBinaryJsonObject &o)
QBinaryJsonValue::~QBinaryJsonValue()
{
- if (t == QJsonValue::String && stringData && !stringData->ref.deref())
- free(stringData);
-
if (d && !d->ref.deref())
delete d;
}
@@ -134,9 +128,7 @@ QString QBinaryJsonValue::toString() const
{
if (t != QJsonValue::String)
return QString();
- stringData->ref.ref(); // the constructor below doesn't add a ref.
- QStringDataPtr holder = { stringData };
- return QString(holder);
+ return stringData;
}
void QBinaryJsonValue::detach()
diff --git a/src/corelib/serialization/qbinaryjsonvalue_p.h b/src/corelib/serialization/qbinaryjsonvalue_p.h
index 498fc62ecd..c3b943250c 100644
--- a/src/corelib/serialization/qbinaryjsonvalue_p.h
+++ b/src/corelib/serialization/qbinaryjsonvalue_p.h
@@ -86,6 +86,7 @@ public:
QBinaryJsonValue(QBinaryJsonValue &&other) noexcept
: ui(other.ui),
+ stringData(std::move(other.stringData)),
d(other.d),
t(other.t)
{
@@ -96,6 +97,7 @@ public:
QBinaryJsonValue &operator =(QBinaryJsonValue &&other) noexcept
{
+ qSwap(stringData, other.stringData);
qSwap(ui, other.ui);
qSwap(d, other.d);
qSwap(t, other.t);
@@ -122,9 +124,9 @@ private:
quint64 ui;
bool b;
double dbl;
- QStringData *stringData;
const QBinaryJsonPrivate::Base *base;
};
+ QString stringData;
QBinaryJsonPrivate::MutableData *d = nullptr; // needed for Objects and Arrays
QJsonValue::Type t = QJsonValue::Null;
};
diff --git a/src/corelib/serialization/qcborvalue_p.h b/src/corelib/serialization/qcborvalue_p.h
index 48818e4c63..53ba81fa18 100644
--- a/src/corelib/serialization/qcborvalue_p.h
+++ b/src/corelib/serialization/qcborvalue_p.h
@@ -147,8 +147,8 @@ public:
qptrdiff offset = data.size();
// align offset
- offset += Q_ALIGNOF(QtCbor::ByteData) - 1;
- offset &= ~(Q_ALIGNOF(QtCbor::ByteData) - 1);
+ offset += alignof(QtCbor::ByteData) - 1;
+ offset &= ~(alignof(QtCbor::ByteData) - 1);
qptrdiff increment = qptrdiff(sizeof(QtCbor::ByteData)) + len;
@@ -170,7 +170,7 @@ public:
return nullptr;
size_t offset = size_t(e.value);
- Q_ASSERT((offset % Q_ALIGNOF(QtCbor::ByteData)) == 0);
+ Q_ASSERT((offset % alignof(QtCbor::ByteData)) == 0);
Q_ASSERT(offset + sizeof(QtCbor::ByteData) <= size_t(data.size()));
auto b = reinterpret_cast<const QtCbor::ByteData *>(data.constData() + offset);
@@ -214,7 +214,7 @@ public:
}
void insertAt(qsizetype idx, const QCborValue &value, ContainerDisposition disp = CopyContainer)
{
- replaceAt_internal(*elements.insert(elements.begin() + idx, {}), value, disp);
+ replaceAt_internal(*elements.insert(elements.begin() + int(idx), {}), value, disp);
}
void append(QtCbor::Undefined)
@@ -235,6 +235,15 @@ public:
elements.append(QtCbor::Element(addByteData(data, len), type,
QtCbor::Element::HasByteData | extraFlags));
}
+ void appendAsciiString(const QString &s);
+ void appendAsciiString(const char *str, qsizetype len)
+ {
+ appendByteData(str, len, QCborValue::String, QtCbor::Element::StringIsAscii);
+ }
+ void appendUtf8String(const char *str, qsizetype len)
+ {
+ appendByteData(str, len, QCborValue::String);
+ }
void append(QLatin1String s)
{
if (!QtPrivate::isAscii(s))
diff --git a/src/corelib/serialization/qdatastream.h b/src/corelib/serialization/qdatastream.h
index 4d827772c8..b7c16018d5 100644
--- a/src/corelib/serialization/qdatastream.h
+++ b/src/corelib/serialization/qdatastream.h
@@ -43,6 +43,7 @@
#include <QtCore/qscopedpointer.h>
#include <QtCore/qiodevice.h>
#include <QtCore/qpair.h>
+#include <QtCore/qcontainerfwd.h>
#ifdef Status
#error qdatastream.h must be included before any header file that defines Status
@@ -54,12 +55,6 @@ class qfloat16;
class QByteArray;
class QIODevice;
-template <typename T> class QList;
-template <typename T> class QVector;
-template <typename T> class QSet;
-template <class Key, class T> class QHash;
-template <class Key, class T> class QMap;
-
#if !defined(QT_NO_DATASTREAM) || defined(QT_BOOTSTRAPPED)
class QDataStreamPrivate;
namespace QtPrivate {
@@ -414,18 +409,6 @@ typename std::enable_if<std::is_enum<T>::value, QDataStream &>::type&
operator>>(QDataStream &s, T &t)
{ return s >> reinterpret_cast<typename std::underlying_type<T>::type &>(t); }
-template <typename T>
-inline QDataStream &operator>>(QDataStream &s, QList<T> &l)
-{
- return QtPrivate::readArrayBasedContainer(s, l);
-}
-
-template <typename T>
-inline QDataStream &operator<<(QDataStream &s, const QList<T> &l)
-{
- return QtPrivate::writeSequentialContainer(s, l);
-}
-
template<typename T>
inline QDataStream &operator>>(QDataStream &s, QVector<T> &v)
{
diff --git a/src/corelib/serialization/qjsonarray.h b/src/corelib/serialization/qjsonarray.h
index 22aa996a3e..9b7e10766f 100644
--- a/src/corelib/serialization/qjsonarray.h
+++ b/src/corelib/serialization/qjsonarray.h
@@ -49,7 +49,6 @@ QT_BEGIN_NAMESPACE
class QDebug;
class QStringList;
-template <typename T> class QList;
typedef QList<QVariant> QVariantList;
class Q_CORE_EXPORT QJsonArray
diff --git a/src/corelib/serialization/qjsoncbor.cpp b/src/corelib/serialization/qjsoncbor.cpp
index 5097f4eb81..fbea84fe73 100644
--- a/src/corelib/serialization/qjsoncbor.cpp
+++ b/src/corelib/serialization/qjsoncbor.cpp
@@ -262,8 +262,7 @@ QJsonValue qt_convertToJson(QCborContainerPrivate *d, qsizetype idx)
const auto &e = d->elements.at(idx);
switch (e.type) {
case QCborValue::Integer:
- return QJsonPrivate::Value::fromTrustedCbor(e.value);
-
+ return QJsonValue(e.value);
case QCborValue::ByteArray:
case QCborValue::String:
case QCborValue::SimpleType:
@@ -370,7 +369,7 @@ QJsonValue QCborValue::toJsonValue() const
return false;
case Integer:
- return QJsonPrivate::Value::fromTrustedCbor(n);
+ return QJsonPrivate::Value::fromTrustedCbor(*this);
case True:
return true;
@@ -615,11 +614,9 @@ QCborValue QCborValue::fromJsonValue(const QJsonValue &v)
case QJsonValue::Bool:
return v.toBool();
case QJsonValue::Double: {
- qint64 i;
- const double dbl = v.toDouble();
- if (convertDoubleTo(dbl, &i))
- return i;
- return dbl;
+ if (v.t == Integer)
+ return v.toInteger();
+ return v.toDouble();
}
case QJsonValue::String:
return v.toString();
@@ -667,9 +664,7 @@ static void appendVariant(QCborContainerPrivate *d, const QVariant &variant)
\row \li \c bool \li Bool
\row \li \c std::nullptr_t \li Null
\row \li \c short, \c ushort, \c int, \c uint, \l qint64 \li Integer
- \row \li \l quint64 \li Integer, but they are cast to \c qint64 first so
- values higher than 2\sup{63}-1 (\c INT64_MAX) will
- be wrapped to negative
+ \row \li \l quint64 \li Integer, or Double if outside the range of qint64
\row \li \c float, \c double \li Double
\row \li \l QByteArray \li ByteArray
\row \li \l QDateTime \li DateTime
@@ -713,9 +708,12 @@ QCborValue QCborValue::fromVariant(const QVariant &variant)
case QMetaType::UShort:
case QVariant::Int:
case QVariant::LongLong:
- case QVariant::ULongLong:
case QVariant::UInt:
return variant.toLongLong();
+ case QVariant::ULongLong:
+ if (variant.toULongLong() <= static_cast<uint64_t>(std::numeric_limits<qint64>::max()))
+ return variant.toLongLong();
+ Q_FALLTHROUGH();
case QMetaType::Float:
case QVariant::Double:
return variant.toDouble();
diff --git a/src/corelib/serialization/qjsonparser.cpp b/src/corelib/serialization/qjsonparser.cpp
index 6d0a92e094..d7ce702ff7 100644
--- a/src/corelib/serialization/qjsonparser.cpp
+++ b/src/corelib/serialization/qjsonparser.cpp
@@ -709,10 +709,11 @@ bool Parser::parseNumber()
// frac = decimal-point 1*DIGIT
if (json < end && *json == '.') {
- isInt = false;
++json;
- while (json < end && *json >= '0' && *json <= '9')
+ while (json < end && *json >= '0' && *json <= '9') {
+ isInt = isInt && *json == '0';
++json;
+ }
}
// exp = e [ minus / plus ] 1*DIGIT
@@ -893,9 +894,10 @@ bool Parser::parseString()
// no escape sequences, we are done
if (isUtf8) {
- container->appendByteData(start, json - start - 1, QCborValue::String,
- isAscii ? QtCbor::Element::StringIsAscii
- : QtCbor::Element::ValueFlags {});
+ if (isAscii)
+ container->appendAsciiString(start, json - start - 1);
+ else
+ container->appendUtf8String(start, json - start - 1);
END;
return true;
}
diff --git a/src/corelib/serialization/qjsonvalue.cpp b/src/corelib/serialization/qjsonvalue.cpp
index 7b6728d525..4a7fab21d7 100644
--- a/src/corelib/serialization/qjsonvalue.cpp
+++ b/src/corelib/serialization/qjsonvalue.cpp
@@ -154,7 +154,9 @@ QJsonValue::QJsonValue(bool b)
QJsonValue::QJsonValue(double v)
: d(nullptr)
{
- if (convertDoubleTo(v, &n)) {
+ // Convert to integer if the number is an integer and changing wouldn't
+ // introduce additional digit precision not present in the double.
+ if (convertDoubleTo<qint64>(v, &n, false /* allow_precision_upgrade */)) {
t = QCborValue::Integer;
} else {
memcpy(&n, &v, sizeof(n));
@@ -449,12 +451,18 @@ QJsonValue QJsonValue::fromVariant(const QVariant &variant)
return QJsonValue(Null);
case QVariant::Bool:
return QJsonValue(variant.toBool());
+ case QMetaType::Short:
+ case QMetaType::UShort:
case QVariant::Int:
- case QMetaType::Float:
- case QVariant::Double:
+ case QVariant::UInt:
case QVariant::LongLong:
+ return QJsonValue(variant.toLongLong());
case QVariant::ULongLong:
- case QVariant::UInt:
+ if (variant.toULongLong() <= static_cast<uint64_t>(std::numeric_limits<qint64>::max()))
+ return QJsonValue(variant.toLongLong());
+ Q_FALLTHROUGH();
+ case QMetaType::Float:
+ case QVariant::Double:
return QJsonValue(variant.toDouble());
case QVariant::String:
return QJsonValue(variant.toString());
@@ -504,7 +512,7 @@ QJsonValue QJsonValue::fromVariant(const QVariant &variant)
\value Null QMetaType::Nullptr
\value Bool QMetaType::Bool
- \value Double QMetaType::Double
+ \value Double QMetaType::Double or QMetaType::LongLong
\value String QString
\value Array QVariantList
\value Object QVariantMap
@@ -520,6 +528,7 @@ QVariant QJsonValue::toVariant() const
case QCborValue::False:
return false;
case QCborValue::Integer:
+ return toInteger();
case QCborValue::Double:
return toDouble();
case QCborValue::String:
@@ -548,7 +557,8 @@ QVariant QJsonValue::toVariant() const
\value Null A Null value
\value Bool A boolean value. Use toBool() to convert to a bool.
- \value Double A double. Use toDouble() to convert to a double.
+ \value Double A number value. Use toDouble() to convert to a double,
+ or toInteger() to convert to a qint64.
\value String A string. Use toString() to convert to a QString.
\value Array An array. Use toArray() to convert to a QJsonArray.
\value Object An object. Use toObject() to convert to a QJsonObject.
@@ -613,18 +623,43 @@ int QJsonValue::toInt(int defaultValue) const
{
switch (t) {
case QCborValue::Double: {
- const double dbl = toDouble();
int dblInt;
- convertDoubleTo<int>(dbl, &dblInt);
- return dbl == dblInt ? dblInt : defaultValue;
+ if (convertDoubleTo<int>(toDouble(), &dblInt))
+ return dblInt;
+ break;
}
case QCborValue::Integer:
- return (n <= qint64(std::numeric_limits<int>::max())
- && n >= qint64(std::numeric_limits<int>::min()))
- ? n : defaultValue;
+ if (qint64(int(n)) == n)
+ return int(n);
+ break;
default:
- return defaultValue;
+ break;
}
+ return defaultValue;
+}
+
+/*!
+ \since 6.0
+ Converts the value to an integer and returns it.
+
+ If type() is not Double or the value is not a whole number
+ representable as qint64, the \a defaultValue will be returned.
+ */
+qint64 QJsonValue::toInteger(qint64 defaultValue) const
+{
+ switch (t) {
+ case QCborValue::Integer:
+ return n;
+ case QCborValue::Double: {
+ qint64 dblInt;
+ if (convertDoubleTo<qint64>(toDouble(), &dblInt))
+ return dblInt;
+ break;
+ }
+ default:
+ break;
+ }
+ return defaultValue;
}
/*!
@@ -641,7 +676,7 @@ double QJsonValue::toDouble(double defaultValue) const
return d;
}
case QCborValue::Integer:
- return n;
+ return double(n);
default:
return defaultValue;
}
@@ -787,8 +822,13 @@ const QJsonValue QJsonValue::operator[](int i) const
*/
bool QJsonValue::operator==(const QJsonValue &other) const
{
- if (t != other.t)
+ if (t != other.t) {
+ if (isDouble() && other.isDouble()) {
+ // One value Cbor integer, one Cbor double, should interact as doubles.
+ return toDouble() == other.toDouble();
+ }
return false;
+ }
switch (t) {
case QCborValue::Undefined:
@@ -929,32 +969,38 @@ uint qHash(const QJsonValue &value, uint seed)
QDebug operator<<(QDebug dbg, const QJsonValue &o)
{
QDebugStateSaver saver(dbg);
- switch (o.type()) {
- case QJsonValue::Undefined:
+ switch (o.t) {
+ case QCborValue::Undefined:
dbg << "QJsonValue(undefined)";
break;
- case QJsonValue::Null:
+ case QCborValue::Null:
dbg << "QJsonValue(null)";
break;
- case QJsonValue::Bool:
+ case QCborValue::True:
+ case QCborValue::False:
dbg.nospace() << "QJsonValue(bool, " << o.toBool() << ')';
break;
- case QJsonValue::Double:
+ case QCborValue::Integer:
+ dbg.nospace() << "QJsonValue(double, " << o.toInteger() << ')';
+ break;
+ case QCborValue::Double:
dbg.nospace() << "QJsonValue(double, " << o.toDouble() << ')';
break;
- case QJsonValue::String:
+ case QCborValue::String:
dbg.nospace() << "QJsonValue(string, " << o.toString() << ')';
break;
- case QJsonValue::Array:
+ case QCborValue::Array:
dbg.nospace() << "QJsonValue(array, ";
dbg << o.toArray();
dbg << ')';
break;
- case QJsonValue::Object:
+ case QCborValue::Map:
dbg.nospace() << "QJsonValue(object, ";
dbg << o.toObject();
dbg << ')';
break;
+ default:
+ Q_UNREACHABLE();
}
return dbg;
}
diff --git a/src/corelib/serialization/qjsonvalue.h b/src/corelib/serialization/qjsonvalue.h
index 5adcd64176..bd8bf14baf 100644
--- a/src/corelib/serialization/qjsonvalue.h
+++ b/src/corelib/serialization/qjsonvalue.h
@@ -112,6 +112,7 @@ public:
bool toBool(bool defaultValue = false) const;
int toInt(int defaultValue = 0) const;
+ qint64 toInteger(qint64 defaultValue = 0) const;
double toDouble(double defaultValue = 0) const;
QString toString() const;
QString toString(const QString &defaultValue) const;
diff --git a/src/corelib/serialization/qjsonwriter.cpp b/src/corelib/serialization/qjsonwriter.cpp
index 627d1bbd62..590b59f09c 100644
--- a/src/corelib/serialization/qjsonwriter.cpp
+++ b/src/corelib/serialization/qjsonwriter.cpp
@@ -60,7 +60,8 @@ static inline uchar hexdig(uint u)
static QByteArray escapedString(const QString &s)
{
- QByteArray ba(s.length(), Qt::Uninitialized);
+ // give it a minimum size to ensure the resize() below always adds enough space
+ QByteArray ba(qMax(s.length(), 16), Qt::Uninitialized);
uchar *cursor = reinterpret_cast<uchar *>(const_cast<char *>(ba.constData()));
const uchar *ba_end = cursor + ba.length();
@@ -138,15 +139,14 @@ static void valueToJson(const QCborValue &v, QByteArray &json, int indent, bool
json += "false";
break;
case QCborValue::Integer:
+ json += QByteArray::number(v.toInteger());
+ break;
case QCborValue::Double: {
const double d = v.toDouble();
- if (qIsFinite(d)) {
- quint64 absInt;
- json += QByteArray::number(d, convertDoubleTo(std::abs(d), &absInt) ? 'f' : 'g',
- QLocale::FloatingPointShortest);
- } else {
+ if (qIsFinite(d))
+ json += QByteArray::number(d, 'g', QLocale::FloatingPointShortest);
+ else
json += "null"; // +INF || -INF || NaN (see RFC4627#section2.4)
- }
break;
}
case QCborValue::String:
diff --git a/src/corelib/statemachine/qsignaleventgenerator_p.h b/src/corelib/statemachine/qsignaleventgenerator_p.h
index 72592b8731..a9d5b96920 100644
--- a/src/corelib/statemachine/qsignaleventgenerator_p.h
+++ b/src/corelib/statemachine/qsignaleventgenerator_p.h
@@ -62,13 +62,12 @@ class QStateMachine;
class QSignalEventGenerator : public QObject
{
- Q_OBJECT_FAKE
+ Q_OBJECT
public:
QSignalEventGenerator(QStateMachine *parent);
-private:
-// slots
- void execute(void **_a);
+private Q_SLOTS:
+ void execute(QMethodRawArguments a);
private:
Q_DISABLE_COPY_MOVE(QSignalEventGenerator)
diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp
index 9d2505ba2e..fb551d5197 100644
--- a/src/corelib/statemachine/qstatemachine.cpp
+++ b/src/corelib/statemachine/qstatemachine.cpp
@@ -3045,102 +3045,14 @@ void QStateMachine::removeDefaultAnimation(QAbstractAnimation *animation)
#endif // animation
-
-// Begin moc-generated code -- modify carefully (check "HAND EDIT" parts)!
-struct qt_meta_stringdata_QSignalEventGenerator_t {
- QByteArrayData data[3];
- char stringdata[32];
-};
-#define QT_MOC_LITERAL(idx, ofs, len) \
- Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
- offsetof(qt_meta_stringdata_QSignalEventGenerator_t, stringdata) + ofs \
- - idx * sizeof(QByteArrayData) \
- )
-static const qt_meta_stringdata_QSignalEventGenerator_t qt_meta_stringdata_QSignalEventGenerator = {
- {
-QT_MOC_LITERAL(0, 0, 21),
-QT_MOC_LITERAL(1, 22, 7),
-QT_MOC_LITERAL(2, 30, 0)
- },
- "QSignalEventGenerator\0execute\0\0"
-};
-#undef QT_MOC_LITERAL
-
-static const uint qt_meta_data_QSignalEventGenerator[] = {
-
- // content:
- 7, // revision
- 0, // classname
- 0, 0, // classinfo
- 1, 14, // methods
- 0, 0, // properties
- 0, 0, // enums/sets
- 0, 0, // constructors
- 0, // flags
- 0, // signalCount
-
- // slots: name, argc, parameters, tag, flags
- 1, 0, 19, 2, 0x0a,
-
- // slots: parameters
- QMetaType::Void,
-
- 0 // eod
-};
-
-void QSignalEventGenerator::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
-{
- if (_c == QMetaObject::InvokeMetaMethod) {
- Q_ASSERT(staticMetaObject.cast(_o));
- QSignalEventGenerator *_t = static_cast<QSignalEventGenerator *>(_o);
- switch (_id) {
- case 0: _t->execute(_a); break; // HAND EDIT: add the _a parameter
- default: ;
- }
- }
- Q_UNUSED(_a);
-}
-
-const QMetaObject QSignalEventGenerator::staticMetaObject = {
- { &QObject::staticMetaObject, qt_meta_stringdata_QSignalEventGenerator.data,
- qt_meta_data_QSignalEventGenerator, qt_static_metacall, nullptr, nullptr }
-};
-
-const QMetaObject *QSignalEventGenerator::metaObject() const
-{
- return &staticMetaObject;
-}
-
-void *QSignalEventGenerator::qt_metacast(const char *_clname)
-{
- if (!_clname) return nullptr;
- if (!strcmp(_clname, qt_meta_stringdata_QSignalEventGenerator.stringdata))
- return static_cast<void*>(const_cast< QSignalEventGenerator*>(this));
- return QObject::qt_metacast(_clname);
-}
-
-int QSignalEventGenerator::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
-{
- _id = QObject::qt_metacall(_c, _id, _a);
- if (_id < 0)
- return _id;
- if (_c == QMetaObject::InvokeMetaMethod) {
- if (_id < 1)
- qt_static_metacall(this, _c, _id, _a);
- _id -= 1;
- }
- return _id;
-}
-// End moc-generated code
-
-void QSignalEventGenerator::execute(void **_a)
+void QSignalEventGenerator::execute(QMethodRawArguments a)
{
auto machinePrivate = QStateMachinePrivate::get(qobject_cast<QStateMachine*>(parent()));
if (machinePrivate->state != QStateMachinePrivate::Running)
return;
int signalIndex = senderSignalIndex();
Q_ASSERT(signalIndex != -1);
- machinePrivate->handleTransitionSignal(sender(), signalIndex, _a);
+ machinePrivate->handleTransitionSignal(sender(), signalIndex, a.arguments);
}
QSignalEventGenerator::QSignalEventGenerator(QStateMachine *parent)
diff --git a/src/corelib/text/qbytearray.cpp b/src/corelib/text/qbytearray.cpp
index 27e0d56225..ac5f2afb57 100644
--- a/src/corelib/text/qbytearray.cpp
+++ b/src/corelib/text/qbytearray.cpp
@@ -65,7 +65,7 @@
#include <string.h>
#include <stdlib.h>
-#define IS_RAW_DATA(d) ((d)->offset != sizeof(QByteArrayData))
+#define IS_RAW_DATA(d) ((d)->flags() & QArrayData::RawDataType)
QT_BEGIN_NAMESPACE
@@ -558,28 +558,13 @@ static const quint16 crc_tbl[16] = {
/*!
\relates QByteArray
-
- Returns the CRC-16 checksum of the first \a len bytes of \a data.
-
- The checksum is independent of the byte order (endianness) and will be
- calculated accorded to the algorithm published in ISO 3309 (Qt::ChecksumIso3309).
-
- \note This function is a 16-bit cache conserving (16 entry table)
- implementation of the CRC-16-CCITT algorithm.
-*/
-quint16 qChecksum(const char *data, uint len)
-{
- return qChecksum(data, len, Qt::ChecksumIso3309);
-}
-
-/*!
- \relates QByteArray
\since 5.9
Returns the CRC-16 checksum of the first \a len bytes of \a data.
The checksum is independent of the byte order (endianness) and will
be calculated accorded to the algorithm published in \a standard.
+ By default the algorithm published in ISO 3309 (Qt::ChecksumIso3309) is used.
\note This function is a 16-bit cache conserving (16 entry table)
implementation of the CRC-16-CCITT algorithm.
@@ -748,27 +733,25 @@ QByteArray qUncompress(const uchar* data, int nbytes)
return invalidCompressedData();
}
- QScopedPointer<QByteArray::Data, QByteArrayDataDeleter> d(QByteArray::Data::allocate(expectedSize + 1));
+ QPair<QByteArray::Data *, char *> pair = QByteArray::Data::allocate(expectedSize + 1);
+ QScopedPointer<QByteArray::Data, QByteArrayDataDeleter> d(pair.first);
if (Q_UNLIKELY(d.data() == nullptr))
return invalidCompressedData();
- d->size = expectedSize;
forever {
ulong alloc = len;
- int res = ::uncompress((uchar*)d->data(), &len,
+ int res = ::uncompress((uchar*)pair.second, &len,
data+4, nbytes-4);
switch (res) {
- case Z_OK:
+ case Z_OK: {
Q_ASSERT(len <= alloc);
Q_UNUSED(alloc);
- d->size = len;
- d->data()[len] = 0;
- {
- QByteArrayDataPtr dataPtr = { d.take() };
- return QByteArray(dataPtr);
- }
+ QByteArray::DataPointer dataPtr = { d.take(), pair.second, uint(len) };
+ pair.second[len] = '\0';
+ return QByteArray(dataPtr);
+ }
case Z_MEM_ERROR:
qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
@@ -781,11 +764,12 @@ QByteArray qUncompress(const uchar* data, int nbytes)
return invalidCompressedData();
} else {
// grow the block
- QByteArray::Data *p = QByteArray::Data::reallocateUnaligned(d.data(), len + 1);
- if (Q_UNLIKELY(p == nullptr))
+ pair = QByteArray::Data::reallocateUnaligned(d.data(), pair.second, len + 1);
+ Q_CHECK_PTR(pair.first);
+ if (Q_UNLIKELY(pair.first == nullptr))
return invalidCompressedData();
d.take(); // don't free
- d.reset(p);
+ d.reset(pair.first);
}
continue;
@@ -1211,9 +1195,6 @@ QByteArray qUncompress(const uchar* data, int nbytes)
*/
QByteArray &QByteArray::operator=(const QByteArray & other) noexcept
{
- other.d->ref.ref();
- if (!d->ref.deref())
- Data::deallocate(d);
d = other.d;
return *this;
}
@@ -1227,25 +1208,23 @@ QByteArray &QByteArray::operator=(const QByteArray & other) noexcept
QByteArray &QByteArray::operator=(const char *str)
{
- Data *x;
- if (!str) {
- x = Data::sharedNull();
- } else if (!*str) {
- x = Data::allocate(0);
+ if (!str || !*str) {
+ QPair<Data *, char *> pair;
+ if (!str) {
+ pair = qMakePair(Data::sharedNull(), Data::sharedNullData());
+ } else {
+ pair = Data::allocate(0);
+ }
+ d = QByteArrayData(pair.first, pair.second, 0);
} else {
const int len = int(strlen(str));
- const uint fullLen = len + 1;
- if (d->ref.isShared() || fullLen > d->alloc
- || (len < d->size && fullLen < uint(d->alloc >> 1)))
+ const uint fullLen = uint(len) + 1;
+ if (d->needsDetach() || fullLen > d->allocatedCapacity()
+ || (len < size() && fullLen < (d->allocatedCapacity() >> 1)))
reallocData(fullLen, d->detachFlags());
- x = d;
- memcpy(x->data(), str, fullLen); // include null terminator
- x->size = len;
+ memcpy(d.data(), str, fullLen); // include null terminator
+ d.size = len;
}
- x->ref.ref();
- if (!d->ref.deref())
- Data::deallocate(d);
- d = x;
return *this;
}
@@ -1448,7 +1427,7 @@ QByteArray &QByteArray::operator=(const char *str)
\sa operator[]()
*/
-/*! \fn QByteRef QByteArray::operator[](int i)
+/*! \fn char &QByteArray::operator[](int i)
Returns the byte at index position \a i as a modifiable reference.
@@ -1459,21 +1438,6 @@ QByteArray &QByteArray::operator=(const char *str)
Example:
\snippet code/src_corelib_tools_qbytearray.cpp 9
- The return value is of type QByteRef, a helper class for
- QByteArray. When you get an object of type QByteRef, you can use
- it as if it were a char &. If you assign to it, the assignment
- will apply to the character in the QByteArray from which you got
- the reference.
-
- \note Before Qt 5.14 it was possible to use this operator to access
- a character at an out-of-bounds position in the byte array, and
- then assign to such a position, causing the byte array to be
- automatically resized. Furthermore, assigning a value to the
- returned QByteRef would cause a detach of the byte array, even if the
- byte array has been copied in the meanwhile (and the QByteRef kept
- alive while the copy was taken). These behaviors are deprecated,
- and will be changed in a future version of Qt.
-
\sa at()
*/
@@ -1484,16 +1448,6 @@ QByteArray &QByteArray::operator=(const char *str)
Same as at(\a i).
*/
-/*! \fn QByteRef QByteArray::operator[](uint i)
-
- \overload
-*/
-
-/*! \fn char QByteArray::operator[](uint i) const
-
- \overload
-*/
-
/*!
\fn char QByteArray::front() const
\since 5.10
@@ -1525,7 +1479,7 @@ QByteArray &QByteArray::operator=(const char *str)
*/
/*!
- \fn QByteRef QByteArray::front()
+ \fn char &QByteArray::front()
\since 5.10
Returns a reference to the first character in the byte array.
@@ -1540,7 +1494,7 @@ QByteArray &QByteArray::operator=(const char *str)
*/
/*!
- \fn QByteRef QByteArray::back()
+ \fn char &QByteArray::back()
\since 5.10
Returns a reference to the last character in the byte array.
@@ -1591,7 +1545,7 @@ QByteArray &QByteArray::operator=(const char *str)
*/
void QByteArray::truncate(int pos)
{
- if (pos < d->size)
+ if (pos < size())
resize(pos);
}
@@ -1611,7 +1565,7 @@ void QByteArray::truncate(int pos)
void QByteArray::chop(int n)
{
if (n > 0)
- resize(d->size - n);
+ resize(size() - n);
}
@@ -1715,19 +1669,13 @@ void QByteArray::chop(int n)
QByteArray::QByteArray(const char *data, int size)
{
if (!data) {
- d = Data::sharedNull();
+ d = DataPointer();
} else {
if (size < 0)
size = int(strlen(data));
- if (!size) {
- d = Data::allocate(0);
- } else {
- d = Data::allocate(uint(size) + 1u);
- Q_CHECK_PTR(d);
- d->size = size;
- memcpy(d->data(), data, size);
- d->data()[size] = '\0';
- }
+ d = DataPointer(Data::allocate(uint(size) + 1u), size);
+ memcpy(d.data(), data, size);
+ d.data()[size] = '\0';
}
}
@@ -1741,13 +1689,11 @@ QByteArray::QByteArray(const char *data, int size)
QByteArray::QByteArray(int size, char ch)
{
if (size <= 0) {
- d = Data::allocate(0);
+ d = DataPointer(Data::allocate(0), 0);
} else {
- d = Data::allocate(uint(size) + 1u);
- Q_CHECK_PTR(d);
- d->size = size;
- memset(d->data(), ch, size);
- d->data()[size] = '\0';
+ d = DataPointer(Data::allocate(uint(size) + 1u), size);
+ memset(d.data(), ch, size);
+ d.data()[size] = '\0';
}
}
@@ -1759,10 +1705,8 @@ QByteArray::QByteArray(int size, char ch)
QByteArray::QByteArray(int size, Qt::Initialization)
{
- d = Data::allocate(uint(size) + 1u);
- Q_CHECK_PTR(d);
- d->size = size;
- d->data()[size] = '\0';
+ d = DataPointer(Data::allocate(uint(size) + 1u), size);
+ d.data()[size] = '\0';
}
/*!
@@ -1782,31 +1726,21 @@ void QByteArray::resize(int size)
if (size < 0)
size = 0;
- if (IS_RAW_DATA(d) && !d->ref.isShared() && size < d->size) {
- d->size = size;
+ if (!d->isShared() && !d->isMutable() && size < int(d.size)) {
+ d.size = size;
return;
}
- if (d->size == 0 && d->ref.isStatic()) {
- //
- // Optimize the idiom:
- // QByteArray a;
- // a.resize(sz);
- // ...
- // which is used in place of the Qt 3 idiom:
- // QByteArray a(sz);
- //
- Data *x = Data::allocate(uint(size) + 1u);
- Q_CHECK_PTR(x);
- x->size = size;
- x->data()[size] = '\0';
- d = x;
+ if (size == 0 && !(d->flags() & Data::CapacityReserved)) {
+ d = DataPointer(Data::allocate(0), 0);
} else {
- if (d->ref.isShared() || uint(size) + 1u > d->alloc)
- reallocData(uint(size) + 1u, d->detachFlags() | Data::Grow);
- if (d->alloc) {
- d->size = size;
- d->data()[size] = '\0';
+ if (d->needsDetach() || size > capacity()
+ || (!(d->flags() & Data::CapacityReserved) && size < int(d.size)
+ && size < (capacity() >> 1)))
+ reallocData(uint(size) + 1u, d->detachFlags() | Data::GrowsForward);
+ d.size = size;
+ if (d->isMutable()) {
+ d.data()[size] = '\0';
}
}
}
@@ -1824,33 +1758,27 @@ void QByteArray::resize(int size)
QByteArray &QByteArray::fill(char ch, int size)
{
- resize(size < 0 ? d->size : size);
- if (d->size)
- memset(d->data(), ch, d->size);
+ resize(size < 0 ? this->size() : size);
+ if (this->size())
+ memset(d.data(), ch, this->size());
return *this;
}
-void QByteArray::reallocData(uint alloc, Data::AllocationOptions options)
+void QByteArray::reallocData(uint alloc, Data::ArrayOptions options)
{
- if (d->ref.isShared() || IS_RAW_DATA(d)) {
- Data *x = Data::allocate(alloc, options);
- Q_CHECK_PTR(x);
- x->size = qMin(int(alloc) - 1, d->size);
- ::memcpy(x->data(), d->data(), x->size);
- x->data()[x->size] = '\0';
- if (!d->ref.deref())
- Data::deallocate(d);
- d = x;
+ if (d->needsDetach()) {
+ DataPointer dd(Data::allocate(alloc, options), qMin(int(alloc) - 1, d.size));
+ ::memcpy(dd.data(), d.data(), dd.size);
+ dd.data()[dd.size] = 0;
+ d = dd;
} else {
- Data *x = Data::reallocateUnaligned(d, alloc, options);
- Q_CHECK_PTR(x);
- d = x;
+ d.reallocate(alloc, options);
}
}
void QByteArray::expand(int i)
{
- resize(qMax(i + 1, d->size));
+ resize(qMax(i + 1, size()));
}
/*!
@@ -1896,9 +1824,9 @@ QByteArray QByteArray::nulTerminated() const
QByteArray &QByteArray::prepend(const QByteArray &ba)
{
- if (d->size == 0 && d->ref.isStatic() && !IS_RAW_DATA(ba.d)) {
+ if (size() == 0 && d->isStatic() && !IS_RAW_DATA(ba.d)) {
*this = ba;
- } else if (ba.d->size != 0) {
+ } else if (ba.size() != 0) {
QByteArray tmp = *this;
*this = ba;
append(tmp);
@@ -1927,12 +1855,12 @@ QByteArray &QByteArray::prepend(const char *str)
QByteArray &QByteArray::prepend(const char *str, int len)
{
if (str) {
- if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
- reallocData(uint(d->size + len) + 1u, d->detachFlags() | Data::Grow);
- memmove(d->data()+len, d->data(), d->size);
- memcpy(d->data(), str, len);
- d->size += len;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + len > capacity())
+ reallocData(uint(size() + len) + 1u, d->detachFlags() | Data::GrowsForward);
+ memmove(d.data()+len, d.data(), d.size);
+ memcpy(d.data(), str, len);
+ d.size += len;
+ d.data()[d.size] = '\0';
}
return *this;
}
@@ -1953,12 +1881,12 @@ QByteArray &QByteArray::prepend(const char *str, int len)
QByteArray &QByteArray::prepend(char ch)
{
- if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
- reallocData(uint(d->size) + 2u, d->detachFlags() | Data::Grow);
- memmove(d->data()+1, d->data(), d->size);
- d->data()[0] = ch;
- ++d->size;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + 1 > capacity())
+ reallocData(uint(size()) + 2u, d->detachFlags() | Data::GrowsForward);
+ memmove(d.data()+1, d.data(), d.size);
+ d.data()[0] = ch;
+ ++d.size;
+ d.data()[d.size] = '\0';
return *this;
}
@@ -1988,14 +1916,14 @@ QByteArray &QByteArray::prepend(char ch)
QByteArray &QByteArray::append(const QByteArray &ba)
{
- if (d->size == 0 && d->ref.isStatic() && !IS_RAW_DATA(ba.d)) {
+ if (size() == 0 && d->isStatic() && !IS_RAW_DATA(ba.d)) {
*this = ba;
- } else if (ba.d->size != 0) {
- if (d->ref.isShared() || uint(d->size + ba.d->size) + 1u > d->alloc)
- reallocData(uint(d->size + ba.d->size) + 1u, d->detachFlags() | Data::Grow);
- memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
- d->size += ba.d->size;
- d->data()[d->size] = '\0';
+ } else if (ba.size() != 0) {
+ if (d->needsDetach() || size() + ba.size() > capacity())
+ reallocData(uint(size() + ba.size()) + 1u, d->detachFlags() | Data::GrowsForward);
+ memcpy(d.data() + d.size, ba.data(), ba.size());
+ d.size += ba.size();
+ d.data()[d.size] = '\0';
}
return *this;
}
@@ -2023,10 +1951,10 @@ QByteArray& QByteArray::append(const char *str)
{
if (str) {
const int len = int(strlen(str));
- if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
- reallocData(uint(d->size + len) + 1u, d->detachFlags() | Data::Grow);
- memcpy(d->data() + d->size, str, len + 1); // include null terminator
- d->size += len;
+ if (d->needsDetach() || size() + len > capacity())
+ reallocData(uint(size() + len) + 1u, d->detachFlags() | Data::GrowsForward);
+ memcpy(d.data() + d.size, str, len + 1); // include null terminator
+ d.size += len;
}
return *this;
}
@@ -2048,11 +1976,11 @@ QByteArray &QByteArray::append(const char *str, int len)
if (len < 0)
len = qstrlen(str);
if (str && len) {
- if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
- reallocData(uint(d->size + len) + 1u, d->detachFlags() | Data::Grow);
- memcpy(d->data() + d->size, str, len); // include null terminator
- d->size += len;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + len > capacity())
+ reallocData(uint(size() + len) + 1u, d->detachFlags() | Data::GrowsForward);
+ memcpy(d.data() + d.size, str, len);
+ d.size += len;
+ d.data()[d.size] = '\0';
}
return *this;
}
@@ -2076,10 +2004,10 @@ QByteArray &QByteArray::append(const char *str, int len)
QByteArray& QByteArray::append(char ch)
{
- if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
- reallocData(uint(d->size) + 2u, d->detachFlags() | Data::Grow);
- d->data()[d->size++] = ch;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + 1 > capacity())
+ reallocData(uint(size()) + 2u, d->detachFlags() | Data::GrowsForward);
+ d.data()[d.size++] = ch;
+ d.data()[d.size] = '\0';
return *this;
}
@@ -2120,7 +2048,7 @@ static inline QByteArray &qbytearray_insert(QByteArray *ba,
QByteArray &QByteArray::insert(int i, const QByteArray &ba)
{
QByteArray copy(ba);
- return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
+ return qbytearray_insert(this, i, copy.constData(), copy.size());
}
/*!
@@ -2202,7 +2130,7 @@ QByteArray &QByteArray::insert(int i, int count, char ch)
int oldsize = size();
resize(qMax(i, oldsize) + count);
- char *dst = d->data();
+ char *dst = d.data();
if (i > oldsize)
::memset(dst + oldsize, 0x20, i - oldsize);
else if (i < oldsize)
@@ -2227,14 +2155,14 @@ QByteArray &QByteArray::insert(int i, int count, char ch)
QByteArray &QByteArray::remove(int pos, int len)
{
- if (len <= 0 || uint(pos) >= uint(d->size))
+ if (len <= 0 || uint(pos) >= uint(size()))
return *this;
detach();
- if (len >= d->size - pos) {
+ if (len >= size() - pos) {
resize(pos);
} else {
- memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
- resize(d->size - len);
+ memmove(d.data() + pos, d.data() + pos + len, size() - pos - len);
+ resize(size() - len);
}
return *this;
}
@@ -2251,9 +2179,9 @@ QByteArray &QByteArray::remove(int pos, int len)
QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
{
- if (len == after.d->size && (pos + len <= d->size)) {
+ if (len == after.size() && (pos + len <= size())) {
detach();
- memmove(d->data() + pos, after.d->data(), len*sizeof(char));
+ memmove(d.data() + pos, after.data(), len*sizeof(char));
return *this;
} else {
QByteArray copy(after);
@@ -2288,9 +2216,9 @@ QByteArray &QByteArray::replace(int pos, int len, const char *after)
*/
QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
{
- if (len == alen && (pos + len <= d->size)) {
+ if (len == alen && (pos + len <= size())) {
detach();
- memcpy(d->data() + pos, after, len*sizeof(char));
+ memcpy(d.data() + pos, after, len*sizeof(char));
return *this;
} else {
remove(pos, len);
@@ -2313,14 +2241,7 @@ QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
{
- if (isNull() || before.d == after.d)
- return *this;
-
- QByteArray aft = after;
- if (after.d == d)
- aft.detach();
-
- return replace(before.constData(), before.size(), aft.constData(), aft.size());
+ return replace(before.constData(), before.size(), after.constData(), after.size());
}
/*!
@@ -2333,11 +2254,7 @@ QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &afte
QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
{
- QByteArray aft = after;
- if (after.d == d)
- aft.detach();
-
- return replace(c, qstrlen(c), aft.constData(), aft.size());
+ return replace(c, qstrlen(c), after.constData(), after.size());
}
/*!
@@ -2357,13 +2274,13 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
// protect against before or after being part of this
const char *a = after;
const char *b = before;
- if (after >= d->data() && after < d->data() + d->size) {
+ if (after >= constBegin() && after < constEnd()) {
char *copy = (char *)malloc(asize);
Q_CHECK_PTR(copy);
memcpy(copy, after, asize);
a = copy;
}
- if (before >= d->data() && before < d->data() + d->size) {
+ if (before >= constBegin() && before < constEnd()) {
char *copy = (char *)malloc(bsize);
Q_CHECK_PTR(copy);
memcpy(copy, before, bsize);
@@ -2372,13 +2289,13 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
QByteArrayMatcher matcher(before, bsize);
int index = 0;
- int len = d->size;
- char *d = data();
+ int len = size();
+ char *d = data(); // detaches
if (bsize == asize) {
if (bsize) {
while ((index = matcher.indexIn(*this, index)) != -1) {
- memcpy(d + index, after, asize);
+ memcpy(d + index, a, asize);
index += bsize;
}
}
@@ -2397,7 +2314,7 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
to = index;
}
if (asize) {
- memcpy(d + to, after, asize);
+ memcpy(d + to, a, asize);
to += asize;
}
index += bsize;
@@ -2440,7 +2357,7 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
resize(newlen);
len = newlen;
}
- d = this->d->data();
+ d = this->d.data(); // data(), without the detach() check
while(pos) {
pos--;
@@ -2449,7 +2366,7 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
int moveto = insertstart + asize;
memmove(d + moveto, d + movestart, (moveend - movestart));
if (asize)
- memcpy(d + insertstart, after, asize);
+ memcpy(d + insertstart, a, asize);
moveend = movestart - bsize;
}
}
@@ -2512,8 +2429,7 @@ QByteArray &QByteArray::replace(const char *before, int bsize, const char *after
QByteArray &QByteArray::replace(char before, const QByteArray &after)
{
char b[2] = { before, '\0' };
- QByteArray cb = fromRawData(b, 1);
- return replace(cb, after);
+ return replace(b, 1, after.constData(), after.size());
}
/*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
@@ -2547,9 +2463,9 @@ QByteArray &QByteArray::replace(char before, const QByteArray &after)
QByteArray &QByteArray::replace(char before, char after)
{
- if (d->size) {
+ if (!isEmpty()) {
char *i = data();
- char *e = i + d->size;
+ char *e = i + size();
for (; i != e; ++i)
if (*i == before)
* i = after;
@@ -2590,7 +2506,7 @@ QList<QByteArray> QByteArray::split(char sep) const
*/
QByteArray QByteArray::repeated(int times) const
{
- if (d->size == 0)
+ if (isEmpty())
return *this;
if (times <= 1) {
@@ -2599,27 +2515,27 @@ QByteArray QByteArray::repeated(int times) const
return QByteArray();
}
- const int resultSize = times * d->size;
+ const int resultSize = times * size();
QByteArray result;
result.reserve(resultSize);
- if (result.d->alloc != uint(resultSize) + 1u)
+ if (result.capacity() != resultSize)
return QByteArray(); // not enough memory
- memcpy(result.d->data(), d->data(), d->size);
+ memcpy(result.d.data(), data(), size());
- int sizeSoFar = d->size;
- char *end = result.d->data() + sizeSoFar;
+ int sizeSoFar = size();
+ char *end = result.d.data() + sizeSoFar;
const int halfResultSize = resultSize >> 1;
while (sizeSoFar <= halfResultSize) {
- memcpy(end, result.d->data(), sizeSoFar);
+ memcpy(end, result.d.data(), sizeSoFar);
end += sizeSoFar;
sizeSoFar <<= 1;
}
- memcpy(end, result.d->data(), resultSize - sizeSoFar);
- result.d->data()[resultSize] = '\0';
- result.d->size = resultSize;
+ memcpy(end, result.d.data(), resultSize - sizeSoFar);
+ result.d.data()[resultSize] = '\0';
+ result.d.size = resultSize;
return result;
}
@@ -2641,17 +2557,17 @@ QByteArray QByteArray::repeated(int times) const
int QByteArray::indexOf(const QByteArray &ba, int from) const
{
- const int ol = ba.d->size;
+ const int ol = ba.size();
if (ol == 0)
return from;
if (ol == 1)
- return indexOf(*ba.d->data(), from);
+ return indexOf(ba[0], from);
- const int l = d->size;
- if (from > d->size || ol + from > l)
+ const int l = size();
+ if (from > l || ol + from > l)
return -1;
- return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
+ return qFindByteArray(data(), size(), from, ba.data(), ol);
}
/*! \fn int QByteArray::indexOf(const QString &str, int from) const
@@ -2685,13 +2601,13 @@ int QByteArray::indexOf(const char *c, int from) const
if (ol == 1)
return indexOf(*c, from);
- const int l = d->size;
- if (from > d->size || ol + from > l)
+ const int l = size();
+ if (from > l || ol + from > l)
return -1;
if (ol == 0)
return from;
- return qFindByteArray(d->data(), d->size, from, c, ol);
+ return qFindByteArray(data(), size(), from, c, ol);
}
/*!
@@ -2710,13 +2626,13 @@ int QByteArray::indexOf(const char *c, int from) const
int QByteArray::indexOf(char ch, int from) const
{
if (from < 0)
- from = qMax(from + d->size, 0);
- if (from < d->size) {
- const char *n = d->data() + from - 1;
- const char *e = d->data() + d->size;
+ from = qMax(from + size(), 0);
+ if (from < size()) {
+ const char *n = data() + from - 1;
+ const char *e = end();
while (++n != e)
if (*n == ch)
- return n - d->data();
+ return n - data();
}
return -1;
}
@@ -2771,11 +2687,11 @@ static int lastIndexOfHelper(const char *haystack, int l, const char *needle, in
int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
{
- const int ol = ba.d->size;
+ const int ol = ba.size();
if (ol == 1)
- return lastIndexOf(*ba.d->data(), from);
+ return lastIndexOf(ba[0], from);
- return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
+ return lastIndexOfHelper(data(), size(), ba.data(), ol, from);
}
/*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
@@ -2810,7 +2726,7 @@ int QByteArray::lastIndexOf(const char *str, int from) const
if (ol == 1)
return lastIndexOf(*str, from);
- return lastIndexOfHelper(d->data(), d->size, str, ol, from);
+ return lastIndexOfHelper(data(), size(), str, ol, from);
}
/*!
@@ -2830,12 +2746,12 @@ int QByteArray::lastIndexOf(const char *str, int from) const
int QByteArray::lastIndexOf(char ch, int from) const
{
if (from < 0)
- from += d->size;
- else if (from > d->size)
- from = d->size-1;
+ from += size();
+ else if (from > size())
+ from = size()-1;
if (from >= 0) {
- const char *b = d->data();
- const char *n = d->data() + from + 1;
+ const char *b = data();
+ const char *n = b + from + 1;
while (n-- != b)
if (*n == ch)
return n - b;
@@ -2854,7 +2770,7 @@ int QByteArray::count(const QByteArray &ba) const
{
int num = 0;
int i = -1;
- if (d->size > 500 && ba.d->size > 5) {
+ if (size() > 500 && ba.size() > 5) {
QByteArrayMatcher matcher(ba);
while ((i = matcher.indexIn(*this, i + 1)) != -1)
++num;
@@ -2889,8 +2805,8 @@ int QByteArray::count(const char *str) const
int QByteArray::count(char ch) const
{
int num = 0;
- const char *i = d->data() + d->size;
- const char *b = d->data();
+ const char *i = end();
+ const char *b = begin();
while (i != b)
if (*--i == ch)
++num;
@@ -2940,11 +2856,11 @@ int QByteArray::count(char ch) const
*/
bool QByteArray::startsWith(const QByteArray &ba) const
{
- if (d == ba.d || ba.d->size == 0)
- return true;
- if (d->size < ba.d->size)
+ if (size() < ba.size())
return false;
- return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
+ if (data() == ba.data() || ba.size() == 0)
+ return true;
+ return memcmp(data(), ba.data(), ba.size()) == 0;
}
/*! \overload
@@ -2957,9 +2873,9 @@ bool QByteArray::startsWith(const char *str) const
if (!str || !*str)
return true;
const int len = int(strlen(str));
- if (d->size < len)
+ if (size() < len)
return false;
- return qstrncmp(d->data(), str, len) == 0;
+ return qstrncmp(data(), str, len) == 0;
}
/*! \overload
@@ -2969,9 +2885,9 @@ bool QByteArray::startsWith(const char *str) const
*/
bool QByteArray::startsWith(char ch) const
{
- if (d->size == 0)
+ if (size() == 0)
return false;
- return d->data()[0] == ch;
+ return data()[0] == ch;
}
/*!
@@ -2985,11 +2901,11 @@ bool QByteArray::startsWith(char ch) const
*/
bool QByteArray::endsWith(const QByteArray &ba) const
{
- if (d == ba.d || ba.d->size == 0)
- return true;
- if (d->size < ba.d->size)
+ if (size() < ba.size())
return false;
- return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
+ if (end() == ba.end() || ba.size() == 0)
+ return true;
+ return memcmp(end() - ba.size(), ba.data(), ba.size()) == 0;
}
/*! \overload
@@ -3002,9 +2918,9 @@ bool QByteArray::endsWith(const char *str) const
if (!str || !*str)
return true;
const int len = int(strlen(str));
- if (d->size < len)
+ if (size() < len)
return false;
- return qstrncmp(d->data() + d->size - len, str, len) == 0;
+ return qstrncmp(end() - len, str, len) == 0;
}
/*
@@ -3086,9 +3002,9 @@ bool QByteArray::isLower() const
*/
bool QByteArray::endsWith(char ch) const
{
- if (d->size == 0)
+ if (size() == 0)
return false;
- return d->data()[d->size - 1] == ch;
+ return data()[size() - 1] == ch;
}
/*!
@@ -3106,11 +3022,11 @@ bool QByteArray::endsWith(char ch) const
QByteArray QByteArray::left(int len) const
{
- if (len >= d->size)
+ if (len >= size())
return *this;
if (len < 0)
len = 0;
- return QByteArray(d->data(), len);
+ return QByteArray(data(), len);
}
/*!
@@ -3128,11 +3044,11 @@ QByteArray QByteArray::left(int len) const
QByteArray QByteArray::right(int len) const
{
- if (len >= d->size)
+ if (len >= size())
return *this;
if (len < 0)
len = 0;
- return QByteArray(d->data() + d->size - len, len);
+ return QByteArray(end() - len, len);
}
/*!
@@ -3157,13 +3073,14 @@ QByteArray QByteArray::mid(int pos, int len) const
return QByteArray();
case QContainerImplHelper::Empty:
{
- QByteArrayDataPtr empty = { Data::allocate(0) };
+ auto alloc = Data::allocate(0);
+ QByteArray::DataPointer empty = { alloc.first, alloc.second, 0 };
return QByteArray(empty);
}
case QContainerImplHelper::Full:
return *this;
case QContainerImplHelper::Subset:
- return QByteArray(d->data() + pos, len);
+ return QByteArray(d.data() + pos, len);
}
Q_UNREACHABLE();
return QByteArray();
@@ -3266,9 +3183,7 @@ QByteArray QByteArray::toUpper_helper(QByteArray &a)
void QByteArray::clear()
{
- if (!d->ref.deref())
- Data::deallocate(d);
- d = Data::sharedNull();
+ d.clear();
}
#if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
@@ -3745,13 +3660,13 @@ QByteArray QByteArray::trimmed_helper(QByteArray &a)
QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
{
QByteArray result;
- int len = d->size;
+ int len = size();
int padlen = width - len;
if (padlen > 0) {
result.resize(len+padlen);
if (len)
- memcpy(result.d->data(), d->data(), len);
- memset(result.d->data()+len, fill, padlen);
+ memcpy(result.d.data(), data(), len);
+ memset(result.d.data()+len, fill, padlen);
} else {
if (truncate)
result = left(width);
@@ -3782,13 +3697,13 @@ QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
{
QByteArray result;
- int len = d->size;
+ int len = size();
int padlen = width - len;
if (padlen > 0) {
result.resize(len+padlen);
if (len)
- memcpy(result.d->data()+padlen, data(), len);
- memset(result.d->data(), fill, padlen);
+ memcpy(result.d.data()+padlen, data(), len);
+ memset(result.d.data(), fill, padlen);
} else {
if (truncate)
result = left(width);
@@ -3798,7 +3713,10 @@ QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
return result;
}
-bool QByteArray::isNull() const { return d == QArrayData::sharedNull(); }
+bool QByteArray::isNull() const
+{
+ return d->isNull();
+}
static qlonglong toIntegral_helper(const char *data, bool *ok, int base, qlonglong)
{
@@ -4105,26 +4023,11 @@ float QByteArray::toFloat(bool *ok) const
}
/*!
- Returns a copy of the byte array, encoded as Base64.
-
- \snippet code/src_corelib_tools_qbytearray.cpp 39
-
- The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
-
- \sa fromBase64()
-*/
-QByteArray QByteArray::toBase64() const
-{
- return toBase64(Base64Encoding);
-}
-
-/*!
\since 5.2
- \overload
Returns a copy of the byte array, encoded using the options \a options.
- \snippet code/src_corelib_tools_qbytearray.cpp 39bis
+ \snippet code/src_corelib_tools_qbytearray.cpp 39
The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
@@ -4140,19 +4043,19 @@ QByteArray QByteArray::toBase64(Base64Options options) const
const char padchar = '=';
int padlen = 0;
- QByteArray tmp((d->size + 2) / 3 * 4, Qt::Uninitialized);
+ QByteArray tmp((size() + 2) / 3 * 4, Qt::Uninitialized);
int i = 0;
char *out = tmp.data();
- while (i < d->size) {
+ while (i < size()) {
// encode 3 bytes at a time
int chunk = 0;
- chunk |= int(uchar(d->data()[i++])) << 16;
- if (i == d->size) {
+ chunk |= int(uchar(data()[i++])) << 16;
+ if (i == size()) {
padlen = 2;
} else {
- chunk |= int(uchar(d->data()[i++])) << 8;
- if (i == d->size)
+ chunk |= int(uchar(data()[i++])) << 8;
+ if (i == size())
padlen = 1;
else
chunk |= int(uchar(data()[i++]));
@@ -4482,17 +4385,14 @@ QByteArray QByteArray::number(double n, char f, int prec)
QByteArray QByteArray::fromRawData(const char *data, int size)
{
- Data *x;
+ QByteArray::DataPointer x;
if (!data) {
- x = Data::sharedNull();
} else if (!size) {
- x = Data::allocate(0);
+ x = DataPointer(Data::allocate(0), 0);
} else {
x = Data::fromRawData(data, size);
- Q_CHECK_PTR(x);
}
- QByteArrayDataPtr dataPtr = { x };
- return QByteArray(dataPtr);
+ return QByteArray(x);
}
/*!
@@ -4511,17 +4411,15 @@ QByteArray QByteArray::fromRawData(const char *data, int size)
*/
QByteArray &QByteArray::setRawData(const char *data, uint size)
{
- if (d->ref.isShared() || d->alloc) {
- *this = fromRawData(data, size);
- } else {
- if (data) {
- d->size = size;
- d->offset = data - reinterpret_cast<char *>(d);
- } else {
- d->offset = sizeof(QByteArrayData);
- d->size = 0;
- }
+ if (!data || !size) {
+ clear();
}
+// else if (d->isShared() || (d->flags() & Data::RawDataType) == 0) {
+ *this = fromRawData(data, size);
+// } else {
+// d.size = size;
+// d.data() = const_cast<char *>(data);
+// }
return *this;
}
@@ -4657,32 +4555,7 @@ QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &ba
}
/*!
- \overload
-
- Returns a decoded copy of the Base64 array \a base64. Input is not checked
- for validity; invalid characters in the input are skipped, enabling the
- decoding process to continue with subsequent characters.
-
- For example:
-
- \snippet code/src_corelib_tools_qbytearray.cpp 44
-
- The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
-
- \note The fromBase64Encoding() function is recommended in new code.
-
- \sa toBase64(), fromBase64Encoding()
-*/
-QByteArray QByteArray::fromBase64(const QByteArray &base64)
-{
- if (auto result = fromBase64Encoding(base64, Base64Encoding))
- return std::move(result.decoded);
- return QByteArray();
-}
-
-/*!
\since 5.2
- \overload
Returns a decoded copy of the Base64 array \a base64, using the options
defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
@@ -4694,7 +4567,7 @@ QByteArray QByteArray::fromBase64(const QByteArray &base64)
For example:
- \snippet code/src_corelib_tools_qbytearray.cpp 44bis
+ \snippet code/src_corelib_tools_qbytearray.cpp 44
The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
@@ -4748,21 +4621,7 @@ QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
return res;
}
-/*!
- Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
- the letters a-f.
-
- \sa fromHex()
-*/
-QByteArray QByteArray::toHex() const
-{
- return toHex('\0');
-}
-
-/*! \overload
- \since 5.9
-
- Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
+/*! Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
the letters a-f.
If \a separator is not '\0', the separator character is inserted between the hex bytes.
@@ -4770,18 +4629,19 @@ QByteArray QByteArray::toHex() const
Example:
\snippet code/src_corelib_tools_qbytearray.cpp 50
+ \since 5.9
\sa fromHex()
*/
QByteArray QByteArray::toHex(char separator) const
{
- if (!d->size)
+ if (isEmpty())
return QByteArray();
- const int length = separator ? (d->size * 3 - 1) : (d->size * 2);
+ const int length = separator ? (size() * 3 - 1) : (size() * 2);
QByteArray hex(length, Qt::Uninitialized);
char *hexData = hex.data();
- const uchar *data = (const uchar *)d->data();
- for (int i = 0, o = 0; i < d->size; ++i) {
+ const uchar *data = (const uchar *)this->data();
+ for (int i = 0, o = 0; i < size(); ++i) {
hexData[o++] = QtMiscUtils::toHexLower(data[i] >> 4);
hexData[o++] = QtMiscUtils::toHexLower(data[i] & 0xf);
@@ -5093,42 +4953,6 @@ QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteA
\sa QStringLiteral
*/
-namespace QtPrivate {
-namespace DeprecatedRefClassBehavior {
-void warn(WarningType w, EmittingClass c)
-{
- static const char deprecatedBehaviorString[] =
- "The corresponding behavior is deprecated, and will be changed"
- " in a future version of Qt.";
-
- const char *emittingClassName = nullptr;
- const char *containerClassName = nullptr;
-
- switch (c) {
- case EmittingClass::QByteRef:
- emittingClassName = "QByteRef";
- containerClassName = "QByteArray";
- break;
- case EmittingClass::QCharRef:
- emittingClassName = "QCharRef";
- containerClassName = "QString";
- break;
- }
-
- switch (w) {
- case WarningType::OutOfRange:
- qWarning("Using %s with an index pointing outside the valid range of a %s. %s",
- emittingClassName, containerClassName, deprecatedBehaviorString);
- break;
- case WarningType::DelayedDetach:
- qWarning("Using %s with on a %s that is not already detached. %s",
- emittingClassName, containerClassName, deprecatedBehaviorString);
- break;
- }
-}
-} // namespace DeprecatedRefClassBehavior
-} // namespace QtPrivate
-
/*!
\class QByteArray::FromBase64Result
\inmodule QtCore
diff --git a/src/corelib/text/qbytearray.h b/src/corelib/text/qbytearray.h
index 36cf580cd9..e3fec1e62c 100644
--- a/src/corelib/text/qbytearray.h
+++ b/src/corelib/text/qbytearray.h
@@ -44,6 +44,8 @@
#include <QtCore/qrefcount.h>
#include <QtCore/qnamespace.h>
#include <QtCore/qarraydata.h>
+#include <QtCore/qarraydatapointer.h>
+#include <QtCore/qcontainerfwd.h>
#include <stdlib.h>
#include <string.h>
@@ -106,48 +108,23 @@ Q_CORE_EXPORT int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap);
Q_CORE_EXPORT int qsnprintf(char *str, size_t n, const char *fmt, ...);
// qChecksum: Internet checksum
-Q_CORE_EXPORT quint16 qChecksum(const char *s, uint len); // ### Qt 6: Remove
-Q_CORE_EXPORT quint16 qChecksum(const char *s, uint len, Qt::ChecksumType standard); // ### Qt 6: Use Qt::ChecksumType standard = Qt::ChecksumIso3309
+Q_CORE_EXPORT quint16 qChecksum(const char *s, uint len,
+ Qt::ChecksumType standard = Qt::ChecksumIso3309);
-class QByteRef;
class QString;
class QDataStream;
-template <typename T> class QList;
-typedef QArrayData QByteArrayData;
-
-template<int N> struct QStaticByteArrayData
-{
- QByteArrayData ba;
- char data[N + 1];
-
- QByteArrayData *data_ptr() const
- {
- Q_ASSERT(ba.ref.isStatic());
- return const_cast<QByteArrayData *>(&ba);
- }
-};
-
-struct QByteArrayDataPtr
-{
- QByteArrayData *ptr;
-};
-
-#define Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset) \
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset)
- /**/
-
-#define Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(size) \
- Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, sizeof(QByteArrayData)) \
- /**/
+using QByteArrayData = QArrayDataPointer<char>;
# define QByteArrayLiteral(str) \
([]() -> QByteArray { \
enum { Size = sizeof(str) - 1 }; \
- static const QStaticByteArrayData<Size> qbytearray_literal = { \
- Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(Size), \
- str }; \
- QByteArrayDataPtr holder = { qbytearray_literal.data_ptr() }; \
+ static const QArrayData qbytearray_literal = { \
+ Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 }; \
+ QByteArrayData holder = { \
+ static_cast<QTypedArrayData<char> *>(const_cast<QArrayData *>(&qbytearray_literal)), \
+ const_cast<char *>(str), \
+ Size }; \
const QByteArray ba(holder); \
return ba; \
}()) \
@@ -155,10 +132,14 @@ struct QByteArrayDataPtr
class Q_CORE_EXPORT QByteArray
{
+public:
+ using DataPointer = QByteArrayData;
private:
typedef QTypedArrayData<char> Data;
+ DataPointer d;
public:
+
enum Base64Option {
Base64Encoding = 0,
Base64UrlEncoding = 1,
@@ -187,14 +168,13 @@ public:
QByteArray &operator=(const QByteArray &) noexcept;
QByteArray &operator=(const char *str);
- inline QByteArray(QByteArray && other) noexcept : d(other.d) { other.d = Data::sharedNull(); }
+ inline QByteArray(QByteArray && other) noexcept
+ { qSwap(d, other.d); }
inline QByteArray &operator=(QByteArray &&other) noexcept
{ qSwap(d, other.d); return *this; }
-
inline void swap(QByteArray &other) noexcept
{ qSwap(d, other.d); }
- inline int size() const;
inline bool isEmpty() const;
void resize(int size);
@@ -213,18 +193,17 @@ public:
inline const char *constData() const;
inline void detach();
inline bool isDetached() const;
- inline bool isSharedWith(const QByteArray &other) const { return d == other.d; }
+ inline bool isSharedWith(const QByteArray &other) const
+ { return data() == other.data() && size() == other.size(); }
void clear();
inline char at(int i) const;
inline char operator[](int i) const;
- inline char operator[](uint i) const;
- Q_REQUIRED_RESULT inline QByteRef operator[](int i);
- Q_REQUIRED_RESULT inline QByteRef operator[](uint i);
+ Q_REQUIRED_RESULT inline char &operator[](int i);
Q_REQUIRED_RESULT char front() const { return at(0); }
- Q_REQUIRED_RESULT inline QByteRef front();
+ Q_REQUIRED_RESULT inline char &front();
Q_REQUIRED_RESULT char back() const { return at(size() - 1); }
- Q_REQUIRED_RESULT inline QByteRef back();
+ Q_REQUIRED_RESULT inline char &back();
int indexOf(char c, int from = 0) const;
int indexOf(const char *c, int from = 0) const;
@@ -365,10 +344,8 @@ public:
qulonglong toULongLong(bool *ok = nullptr, int base = 10) const;
float toFloat(bool *ok = nullptr) const;
double toDouble(bool *ok = nullptr) const;
- QByteArray toBase64(Base64Options options) const;
- QByteArray toBase64() const; // ### Qt6 merge with previous
- QByteArray toHex() const;
- QByteArray toHex(char separator) const; // ### Qt6 merge with previous
+ QByteArray toBase64(Base64Options options = Base64Encoding) const;
+ QByteArray toHex(char separator = '\0') const;
QByteArray toPercentEncoding(const QByteArray &exclude = QByteArray(),
const QByteArray &include = QByteArray(),
char percent = '%') const;
@@ -393,8 +370,7 @@ public:
class FromBase64Result;
Q_REQUIRED_RESULT static FromBase64Result fromBase64Encoding(QByteArray &&base64, Base64Options options = Base64Encoding);
Q_REQUIRED_RESULT static FromBase64Result fromBase64Encoding(const QByteArray &base64, Base64Options options = Base64Encoding);
- Q_REQUIRED_RESULT static QByteArray fromBase64(const QByteArray &base64, Base64Options options);
- Q_REQUIRED_RESULT static QByteArray fromBase64(const QByteArray &base64); // ### Qt6 merge with previous
+ Q_REQUIRED_RESULT static QByteArray fromBase64(const QByteArray &base64, Base64Options options = Base64Encoding);
Q_REQUIRED_RESULT static QByteArray fromHex(const QByteArray &hexEncoded);
Q_REQUIRED_RESULT static QByteArray fromPercentEncoding(const QByteArray &pctEncoded, char percent = '%');
@@ -449,19 +425,20 @@ public:
static inline QByteArray fromStdString(const std::string &s);
inline std::string toStdString() const;
- inline int count() const { return d->size; }
- int length() const { return d->size; }
+ inline int size() const { return d->size; }
+ inline int count() const { return size(); }
+ inline int length() const { return size(); }
bool isNull() const;
- inline QByteArray(QByteArrayDataPtr dd)
- : d(static_cast<Data *>(dd.ptr))
+ inline DataPointer &data_ptr() { return d; }
+ explicit inline QByteArray(const DataPointer &dd)
+ : d(dd)
{
}
private:
operator QNoImplicitBoolCast() const;
- Data *d;
- void reallocData(uint alloc, Data::AllocationOptions options);
+ void reallocData(uint alloc, Data::ArrayOptions options);
void expand(int i);
QByteArray nulTerminated() const;
@@ -474,171 +451,86 @@ private:
static QByteArray simplified_helper(const QByteArray &a);
static QByteArray simplified_helper(QByteArray &a);
- friend class QByteRef;
friend class QString;
friend Q_CORE_EXPORT QByteArray qUncompress(const uchar *data, int nbytes);
-public:
- typedef Data * DataPtr;
- inline DataPtr &data_ptr() { return d; }
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QByteArray::Base64Options)
-inline QByteArray::QByteArray() noexcept : d(Data::sharedNull()) { }
-inline QByteArray::~QByteArray() { if (!d->ref.deref()) Data::deallocate(d); }
-inline int QByteArray::size() const
-{ return d->size; }
+inline QByteArray::QByteArray() noexcept {}
+inline QByteArray::~QByteArray() {}
inline char QByteArray::at(int i) const
-{ Q_ASSERT(uint(i) < uint(size())); return d->data()[i]; }
+{ Q_ASSERT(uint(i) < uint(size())); return d.data()[i]; }
inline char QByteArray::operator[](int i) const
-{ Q_ASSERT(uint(i) < uint(size())); return d->data()[i]; }
-inline char QByteArray::operator[](uint i) const
-{ Q_ASSERT(i < uint(size())); return d->data()[i]; }
+{ Q_ASSERT(uint(i) < uint(size())); return d.data()[i]; }
inline bool QByteArray::isEmpty() const
-{ return d->size == 0; }
+{ return size() == 0; }
#ifndef QT_NO_CAST_FROM_BYTEARRAY
inline QByteArray::operator const char *() const
-{ return d->data(); }
+{ return data(); }
inline QByteArray::operator const void *() const
-{ return d->data(); }
+{ return data(); }
#endif
inline char *QByteArray::data()
-{ detach(); return d->data(); }
+{ detach(); return d.data(); }
inline const char *QByteArray::data() const
-{ return d->data(); }
+{ return d.data(); }
inline const char *QByteArray::constData() const
-{ return d->data(); }
+{ return d.data(); }
inline void QByteArray::detach()
-{ if (d->ref.isShared() || (d->offset != sizeof(QByteArrayData))) reallocData(uint(d->size) + 1u, d->detachFlags()); }
+{ if (d->needsDetach()) reallocData(uint(size()) + 1u, d->detachFlags()); }
inline bool QByteArray::isDetached() const
-{ return !d->ref.isShared(); }
+{ return !d->isShared(); }
inline QByteArray::QByteArray(const QByteArray &a) noexcept : d(a.d)
-{ d->ref.ref(); }
+{}
inline int QByteArray::capacity() const
-{ return d->alloc ? d->alloc - 1 : 0; }
+{ const auto realCapacity = d->constAllocatedCapacity(); return realCapacity ? int(realCapacity) - 1 : 0; }
inline void QByteArray::reserve(int asize)
{
- if (d->ref.isShared() || uint(asize) + 1u > d->alloc) {
+ if (d->needsDetach() || asize > capacity()) {
reallocData(qMax(uint(size()), uint(asize)) + 1u, d->detachFlags() | Data::CapacityReserved);
} else {
- // cannot set unconditionally, since d could be the shared_null or
- // otherwise static
- d->capacityReserved = true;
+ d->flags() |= Data::CapacityReserved;
}
}
inline void QByteArray::squeeze()
{
- if (d->ref.isShared() || uint(d->size) + 1u < d->alloc) {
- reallocData(uint(d->size) + 1u, d->detachFlags() & ~Data::CapacityReserved);
+ if ((d->flags() & Data::CapacityReserved) == 0)
+ return;
+ if (d->needsDetach() || size() < capacity()) {
+ reallocData(uint(size()) + 1u, d->detachFlags() & ~Data::CapacityReserved);
} else {
- // cannot set unconditionally, since d could be shared_null or
- // otherwise static.
- d->capacityReserved = false;
+ d->flags() &= uint(~Data::CapacityReserved);
}
}
-namespace QtPrivate {
-namespace DeprecatedRefClassBehavior {
- enum class EmittingClass {
- QByteRef,
- QCharRef,
- };
-
- enum class WarningType {
- OutOfRange,
- DelayedDetach,
- };
-
- Q_CORE_EXPORT Q_DECL_COLD_FUNCTION void warn(WarningType w, EmittingClass c);
-} // namespace DeprecatedAssignmentOperatorBehavior
-} // namespace QtPrivate
-
-class
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-Q_CORE_EXPORT
-#endif
-QByteRef { // ### Qt 7: remove
- QByteArray &a;
- int i;
- inline QByteRef(QByteArray &array, int idx)
- : a(array),i(idx) {}
- friend class QByteArray;
-public:
- inline operator char() const
- {
- using namespace QtPrivate::DeprecatedRefClassBehavior;
- if (Q_LIKELY(i < a.d->size))
- return a.d->data()[i];
-#ifdef QT_DEBUG
- warn(WarningType::OutOfRange, EmittingClass::QByteRef);
-#endif
- return char(0);
- }
- inline QByteRef &operator=(char c)
- {
- using namespace QtPrivate::DeprecatedRefClassBehavior;
- if (Q_UNLIKELY(i >= a.d->size)) {
-#ifdef QT_DEBUG
- warn(WarningType::OutOfRange, EmittingClass::QByteRef);
-#endif
- a.expand(i);
- } else {
-#ifdef QT_DEBUG
- if (Q_UNLIKELY(!a.isDetached()))
- warn(WarningType::DelayedDetach, EmittingClass::QByteRef);
-#endif
- a.detach();
- }
- a.d->data()[i] = c;
- return *this;
- }
- inline QByteRef &operator=(const QByteRef &c)
- {
- return operator=(char(c));
- }
- inline bool operator==(char c) const
- { return a.d->data()[i] == c; }
- inline bool operator!=(char c) const
- { return a.d->data()[i] != c; }
- inline bool operator>(char c) const
- { return a.d->data()[i] > c; }
- inline bool operator>=(char c) const
- { return a.d->data()[i] >= c; }
- inline bool operator<(char c) const
- { return a.d->data()[i] < c; }
- inline bool operator<=(char c) const
- { return a.d->data()[i] <= c; }
-};
-
-inline QByteRef QByteArray::operator[](int i)
-{ Q_ASSERT(i >= 0); detach(); return QByteRef(*this, i); }
-inline QByteRef QByteArray::operator[](uint i)
-{ detach(); return QByteRef(*this, i); }
-inline QByteRef QByteArray::front() { return operator[](0); }
-inline QByteRef QByteArray::back() { return operator[](size() - 1); }
+inline char &QByteArray::operator[](int i)
+{ Q_ASSERT(i >= 0 && i < size()); return data()[i]; }
+inline char &QByteArray::front() { return operator[](0); }
+inline char &QByteArray::back() { return operator[](size() - 1); }
inline QByteArray::iterator QByteArray::begin()
-{ detach(); return d->data(); }
+{ return data(); }
inline QByteArray::const_iterator QByteArray::begin() const
-{ return d->data(); }
+{ return data(); }
inline QByteArray::const_iterator QByteArray::cbegin() const
-{ return d->data(); }
+{ return data(); }
inline QByteArray::const_iterator QByteArray::constBegin() const
-{ return d->data(); }
+{ return data(); }
inline QByteArray::iterator QByteArray::end()
-{ detach(); return d->data() + d->size; }
+{ return data() + size(); }
inline QByteArray::const_iterator QByteArray::end() const
-{ return d->data() + d->size; }
+{ return data() + size(); }
inline QByteArray::const_iterator QByteArray::cend() const
-{ return d->data() + d->size; }
+{ return data() + size(); }
inline QByteArray::const_iterator QByteArray::constEnd() const
-{ return d->data() + d->size; }
+{ return data() + size(); }
inline QByteArray &QByteArray::append(int n, char ch)
-{ return insert(d->size, n, ch); }
+{ return insert(size(), n, ch); }
inline QByteArray &QByteArray::prepend(int n, char ch)
{ return insert(0, n, ch); }
inline QByteArray &QByteArray::operator+=(char c)
diff --git a/src/corelib/text/qbytearray_p.h b/src/corelib/text/qbytearray_p.h
index 3c6257f786..d6a5e277b3 100644
--- a/src/corelib/text/qbytearray_p.h
+++ b/src/corelib/text/qbytearray_p.h
@@ -58,7 +58,7 @@ QT_BEGIN_NAMESPACE
enum {
// Define as enum to force inlining. Don't expose MaxAllocSize in a public header.
- MaxByteArraySize = MaxAllocSize - sizeof(std::remove_pointer<QByteArray::DataPtr>::type)
+ MaxByteArraySize = MaxAllocSize - sizeof(std::remove_pointer<QByteArray::DataPointer>::type)
};
QT_END_NAMESPACE
diff --git a/src/corelib/text/qbytearraylist.h b/src/corelib/text/qbytearraylist.h
index 0250b649b8..d02fa6d20f 100644
--- a/src/corelib/text/qbytearraylist.h
+++ b/src/corelib/text/qbytearraylist.h
@@ -39,7 +39,7 @@
**
****************************************************************************/
-#include <QtCore/qlist.h>
+#include <QtCore/qvector.h>
#ifndef QBYTEARRAYLIST_H
#define QBYTEARRAYLIST_H
@@ -49,12 +49,12 @@
QT_BEGIN_NAMESPACE
#if !defined(QT_NO_JAVA_STYLE_ITERATORS)
-typedef QListIterator<QByteArray> QByteArrayListIterator;
-typedef QMutableListIterator<QByteArray> QMutableByteArrayListIterator;
+typedef QVectorIterator<QByteArray> QByteArrayListIterator;
+typedef QMutableVectorIterator<QByteArray> QMutableByteArrayListIterator;
#endif
#ifndef Q_CLANG_QDOC
-typedef QList<QByteArray> QByteArrayList;
+typedef QVector<QByteArray> QByteArrayList;
namespace QtPrivate {
QByteArray Q_CORE_EXPORT QByteArrayList_join(const QByteArrayList *that, const char *separator, int separatorLength);
@@ -63,14 +63,14 @@ namespace QtPrivate {
#endif
#ifdef Q_CLANG_QDOC
-class QByteArrayList : public QList<QByteArray>
+class QByteArrayList : public QVector<QByteArray>
#else
-template <> struct QListSpecialMethods<QByteArray>
+template <> struct QVectorSpecialMethods<QByteArray>
#endif
{
#ifndef Q_CLANG_QDOC
protected:
- ~QListSpecialMethods() = default;
+ ~QVectorSpecialMethods() = default;
#endif
public:
inline QByteArray join() const
@@ -80,11 +80,8 @@ public:
inline QByteArray join(char sep) const
{ return QtPrivate::QByteArrayList_join(self(), &sep, 1); }
- inline int indexOf(const char *needle, int from = 0) const
- { return QtPrivate::QByteArrayList_indexOf(self(), needle, from); }
-
private:
- typedef QList<QByteArray> Self;
+ typedef QVector<QByteArray> Self;
Self *self() { return static_cast<Self *>(this); }
const Self *self() const { return static_cast<const Self *>(this); }
};
diff --git a/src/corelib/text/qbytearraymatcher.h b/src/corelib/text/qbytearraymatcher.h
index 0eedfc1d20..7cc5037095 100644
--- a/src/corelib/text/qbytearraymatcher.h
+++ b/src/corelib/text/qbytearraymatcher.h
@@ -85,7 +85,7 @@ private:
class QStaticByteArrayMatcherBase
{
- Q_DECL_ALIGN(16)
+ alignas(16)
struct Skiptable {
uchar data[256];
} m_skiptable;
diff --git a/src/corelib/text/qchar.h b/src/corelib/text/qchar.h
index a3d5d7a65e..9d0741af8b 100644
--- a/src/corelib/text/qchar.h
+++ b/src/corelib/text/qchar.h
@@ -439,7 +439,6 @@ public:
Unicode_12_0,
Unicode_12_1
};
- // ****** WHEN ADDING FUNCTIONS, CONSIDER ADDING TO QCharRef TOO
inline Category category() const noexcept { return QChar::category(ucs); }
inline Direction direction() const noexcept { return QChar::direction(ucs); }
diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp
index 5788f000a1..ff1152b4e9 100644
--- a/src/corelib/text/qstring.cpp
+++ b/src/corelib/text/qstring.cpp
@@ -100,7 +100,7 @@
#define ULLONG_MAX quint64_C(18446744073709551615)
#endif
-#define IS_RAW_DATA(d) ((d)->offset != sizeof(QStringData))
+#define IS_RAW_DATA(d) ((d.d)->flags & QArrayData::RawDataType)
QT_BEGIN_NAMESPACE
@@ -163,7 +163,7 @@ qsizetype QtPrivate::qustrlen(const ushort *str) noexcept
{
qsizetype result = 0;
-#ifdef __SSE2__
+#if defined(__SSE2__) && !(defined(__SANITIZE_ADDRESS__) || QT_HAS_FEATURE(address_sanitizer))
// find the 16-byte alignment immediately prior or equal to str
quintptr misalignment = quintptr(str) & 0xf;
Q_ASSERT((misalignment & 1) == 0);
@@ -1377,28 +1377,6 @@ const QString::Null QString::null = { };
*/
/*!
- \class QCharRef
- \inmodule QtCore
- \reentrant
- \brief The QCharRef class is a helper class for QString.
-
- \internal
-
- \ingroup string-processing
-
- When you get an object of type QCharRef, if you can assign to it,
- the assignment will apply to the character in the string from
- which you got the reference. That is its whole purpose in life.
- The QCharRef becomes invalid once modifications are made to the
- string: if you want to keep the character, copy it into a QChar.
-
- Most of the QChar member functions also exist in QCharRef.
- However, they are not explicitly documented here.
-
- \sa QString::operator[](), QString::at(), QChar
-*/
-
-/*!
\class QString
\inmodule QtCore
\reentrant
@@ -2117,8 +2095,8 @@ int QString::toUcs4_helper(const ushort *uc, int length, uint *out)
*/
QString::QString(const QChar *unicode, int size)
{
- if (!unicode) {
- d = Data::sharedNull();
+ if (!unicode) {
+ d.clear();
} else {
if (size < 0) {
size = 0;
@@ -2126,13 +2104,11 @@ QString::QString(const QChar *unicode, int size)
++size;
}
if (!size) {
- d = Data::allocate(0);
+ d = DataPointer(Data::allocate(0), 0);
} else {
- d = Data::allocate(size + 1);
- Q_CHECK_PTR(d);
- d->size = size;
- memcpy(d->data(), unicode, size * sizeof(QChar));
- d->data()[size] = '\0';
+ d = DataPointer(Data::allocate(size + 1), size);
+ memcpy(d.data(), unicode, size * sizeof(QChar));
+ d.data()[size] = '\0';
}
}
}
@@ -2145,15 +2121,13 @@ QString::QString(const QChar *unicode, int size)
*/
QString::QString(int size, QChar ch)
{
- if (size <= 0) {
- d = Data::allocate(0);
+ if (size <= 0) {
+ d = DataPointer(Data::allocate(0), 0);
} else {
- d = Data::allocate(size + 1);
- Q_CHECK_PTR(d);
- d->size = size;
- d->data()[size] = '\0';
- ushort *i = d->data() + size;
- ushort *b = d->data();
+ d = DataPointer(Data::allocate(size + 1), size);
+ d.data()[size] = '\0';
+ ushort *i = d.data() + size;
+ ushort *b = d.data();
const ushort value = ch.unicode();
while (i != b)
*--i = value;
@@ -2168,10 +2142,8 @@ QString::QString(int size, QChar ch)
*/
QString::QString(int size, Qt::Initialization)
{
- d = Data::allocate(size + 1);
- Q_CHECK_PTR(d);
- d->size = size;
- d->data()[size] = '\0';
+ d = DataPointer(Data::allocate(size + 1), size);
+ d.data()[size] = '\0';
}
/*! \fn QString::QString(QLatin1String str)
@@ -2186,11 +2158,9 @@ QString::QString(int size, Qt::Initialization)
*/
QString::QString(QChar ch)
{
- d = Data::allocate(2);
- Q_CHECK_PTR(d);
- d->size = 1;
- d->data()[0] = ch.unicode();
- d->data()[1] = '\0';
+ d = DataPointer(Data::allocate(2), 1);
+ d.data()[0] = ch.unicode();
+ d.data()[1] = '\0';
}
/*! \fn QString::QString(const QByteArray &ba)
@@ -2212,7 +2182,7 @@ QString::QString(QChar ch)
\internal
*/
-/*! \fn QString::QString(QStringDataPtr)
+/*! \fn QString::QString(QStringPrivate)
\internal
*/
@@ -2282,16 +2252,16 @@ void QString::resize(int size)
if (size < 0)
size = 0;
- if (IS_RAW_DATA(d) && !d->ref.isShared() && size < d->size) {
- d->size = size;
+ if (!d->isShared() && !d->isMutable() && size < int(d.size)) {
+ d.size = size;
return;
}
- if (d->ref.isShared() || uint(size) + 1u > d->alloc)
+ if (d->needsDetach() || size > capacity())
reallocData(uint(size) + 1u, true);
- if (d->alloc) {
- d->size = size;
- d->data()[size] = '\0';
+ d.size = size;
+ if (d->isMutable()) {
+ d.data()[size] = '\0';
}
}
@@ -2311,7 +2281,7 @@ void QString::resize(int size, QChar fillChar)
resize(size);
const int difference = length() - oldSize;
if (difference > 0)
- std::fill_n(d->begin() + oldSize, difference, fillChar.unicode());
+ std::fill_n(d.data() + oldSize, difference, fillChar.unicode());
}
/*! \fn int QString::capacity() const
@@ -2368,28 +2338,22 @@ void QString::reallocData(uint alloc, bool grow)
{
auto allocOptions = d->detachFlags();
if (grow)
- allocOptions |= QArrayData::Grow;
-
- if (d->ref.isShared() || IS_RAW_DATA(d)) {
- Data *x = Data::allocate(alloc, allocOptions);
- Q_CHECK_PTR(x);
- x->size = qMin(int(alloc) - 1, d->size);
- ::memcpy(x->data(), d->data(), x->size * sizeof(QChar));
- x->data()[x->size] = 0;
- if (!d->ref.deref())
- Data::deallocate(d);
- d = x;
+ allocOptions |= QArrayData::GrowsForward;
+
+ if (d->needsDetach()) {
+ DataPointer dd(Data::allocate(alloc, allocOptions), qMin(int(alloc) - 1, d.size));
+ ::memcpy(dd.data(), d.data(), dd.size * sizeof(QChar));
+ dd.data()[dd.size] = 0;
+ d = dd;
} else {
- Data *p = Data::reallocateUnaligned(d, alloc, allocOptions);
- Q_CHECK_PTR(p);
- d = p;
+ d.reallocate(alloc, allocOptions);
}
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
void QString::expand(int i)
{
- resize(qMax(i + 1, d->size), QLatin1Char(' '));
+ resize(qMax(i + 1, size()), QLatin1Char(' '));
}
#endif
@@ -2408,9 +2372,6 @@ void QString::expand(int i)
QString &QString::operator=(const QString &other) noexcept
{
- other.d->ref.ref();
- if (!d->ref.deref())
- Data::deallocate(d);
d = other.d;
return *this;
}
@@ -2432,9 +2393,9 @@ QString &QString::operator=(const QString &other) noexcept
QString &QString::operator=(QLatin1String other)
{
if (isDetached() && other.size() <= capacity()) { // assumes d->alloc == 0 -> !isDetached() (sharedNull)
- d->size = other.size();
- d->data()[other.size()] = 0;
- qt_from_latin1(d->data(), other.latin1(), other.size());
+ d.size = other.size();
+ d.data()[other.size()] = 0;
+ qt_from_latin1(d.data(), other.latin1(), other.size());
} else {
*this = fromLatin1(other.latin1(), other.size());
}
@@ -2497,10 +2458,9 @@ QString &QString::operator=(QChar ch)
{
if (isDetached() && capacity() >= 1) { // assumes d->alloc == 0 -> !isDetached() (sharedNull)
// re-use existing capacity:
- ushort *dat = d->data();
- dat[0] = ch.unicode();
- dat[1] = 0;
- d->size = 1;
+ d.data()[0] = ch.unicode();
+ d.data()[1] = 0;
+ d.size = 1;
} else {
operator=(QString(ch));
}
@@ -2586,13 +2546,13 @@ QString &QString::insert(int i, QLatin1String str)
return *this;
int len = str.size();
- if (Q_UNLIKELY(i > d->size))
+ if (Q_UNLIKELY(i > size()))
resize(i + len, QLatin1Char(' '));
else
- resize(d->size + len);
+ resize(size() + len);
- ::memmove(d->data() + i + len, d->data() + i, (d->size - i - len) * sizeof(QChar));
- qt_from_latin1(d->data() + i, s, uint(len));
+ ::memmove(d.data() + i + len, d.data() + i, (d.size - i - len) * sizeof(QChar));
+ qt_from_latin1(d.data() + i, s, uint(len));
return *this;
}
@@ -2609,7 +2569,7 @@ QString& QString::insert(int i, const QChar *unicode, int size)
return *this;
const ushort *s = (const ushort *)unicode;
- if (s >= d->data() && s < d->data() + d->alloc) {
+ if (s >= d.data() && s < d.data() + d.size) {
// Part of me - take a copy
ushort *tmp = static_cast<ushort *>(::malloc(size * sizeof(QChar)));
Q_CHECK_PTR(tmp);
@@ -2619,13 +2579,13 @@ QString& QString::insert(int i, const QChar *unicode, int size)
return *this;
}
- if (Q_UNLIKELY(i > d->size))
+ if (Q_UNLIKELY(i > int(d.size)))
resize(i + size, QLatin1Char(' '));
else
- resize(d->size + size);
+ resize(d.size + size);
- ::memmove(d->data() + i + size, d->data() + i, (d->size - i - size) * sizeof(QChar));
- memcpy(d->data() + i, s, size * sizeof(QChar));
+ ::memmove(d.data() + i + size, d.data() + i, (d.size - i - size) * sizeof(QChar));
+ memcpy(d.data() + i, s, size * sizeof(QChar));
return *this;
}
@@ -2639,15 +2599,15 @@ QString& QString::insert(int i, const QChar *unicode, int size)
QString& QString::insert(int i, QChar ch)
{
if (i < 0)
- i += d->size;
+ i += d.size;
if (i < 0)
return *this;
- if (Q_UNLIKELY(i > d->size))
+ if (Q_UNLIKELY(i > size()))
resize(i + 1, QLatin1Char(' '));
else
- resize(d->size + 1);
- ::memmove(d->data() + i + 1, d->data() + i, (d->size - i - 1) * sizeof(QChar));
- d->data()[i] = ch.unicode();
+ resize(d.size + 1);
+ ::memmove(d.data() + i + 1, d.data() + i, (d.size - i - 1) * sizeof(QChar));
+ d.data()[i] = ch.unicode();
return *this;
}
@@ -2671,15 +2631,15 @@ QString& QString::insert(int i, QChar ch)
*/
QString &QString::append(const QString &str)
{
- if (str.d != Data::sharedNull()) {
- if (d == Data::sharedNull()) {
+ if (!str.isNull()) {
+ if (isNull()) {
operator=(str);
} else {
- if (d->ref.isShared() || uint(d->size + str.d->size) + 1u > d->alloc)
- reallocData(uint(d->size + str.d->size) + 1u, true);
- memcpy(d->data() + d->size, str.d->data(), str.d->size * sizeof(QChar));
- d->size += str.d->size;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + str.size() > capacity())
+ reallocData(uint(size() + str.size()) + 1u, true);
+ memcpy(d.data() + d.size, str.d.data(), str.d.size * sizeof(QChar));
+ d.size += str.d.size;
+ d.data()[d.size] = '\0';
}
}
return *this;
@@ -2694,11 +2654,11 @@ QString &QString::append(const QString &str)
QString &QString::append(const QChar *str, int len)
{
if (str && len > 0) {
- if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
- reallocData(uint(d->size + len) + 1u, true);
- memcpy(d->data() + d->size, str, len * sizeof(QChar));
- d->size += len;
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + len > capacity())
+ reallocData(uint(size() + len) + 1u, true);
+ memcpy(d.data() + d.size, str, len * sizeof(QChar));
+ d.size += len;
+ d.data()[d.size] = '\0';
}
return *this;
}
@@ -2713,12 +2673,12 @@ QString &QString::append(QLatin1String str)
const char *s = str.latin1();
if (s) {
int len = str.size();
- if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
- reallocData(uint(d->size + len) + 1u, true);
- ushort *i = d->data() + d->size;
+ if (d->needsDetach() || size() + len > capacity())
+ reallocData(uint(size() + len) + 1u, true);
+ ushort *i = d.data() + d.size;
qt_from_latin1(i, s, uint(len));
i[len] = '\0';
- d->size += len;
+ d.size += len;
}
return *this;
}
@@ -2760,10 +2720,10 @@ QString &QString::append(QLatin1String str)
*/
QString &QString::append(QChar ch)
{
- if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
- reallocData(uint(d->size) + 2u, true);
- d->data()[d->size++] = ch.unicode();
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || size() + 1 > capacity())
+ reallocData(uint(d.size) + 2u, true);
+ d.data()[d.size++] = ch.unicode();
+ d.data()[d.size] = '\0';
return *this;
}
@@ -2856,16 +2816,16 @@ QString &QString::append(QChar ch)
QString &QString::remove(int pos, int len)
{
if (pos < 0) // count from end of string
- pos += d->size;
- if (uint(pos) >= uint(d->size)) {
+ pos += size();
+ if (uint(pos) >= uint(size())) {
// range problems
- } else if (len >= d->size - pos) {
+ } else if (len >= size() - pos) {
resize(pos); // truncate
} else if (len > 0) {
detach();
- memmove(d->data() + pos, d->data() + pos + len,
- (d->size - pos - len + 1) * sizeof(ushort));
- d->size -= len;
+ memmove(d.data() + pos, d.data() + pos + len,
+ (d.size - pos - len + 1) * sizeof(ushort));
+ d.size -= len;
}
return *this;
}
@@ -3010,10 +2970,10 @@ QString &QString::replace(int pos, int len, const QString &after)
*/
QString &QString::replace(int pos, int len, const QChar *unicode, int size)
{
- if (uint(pos) > uint(d->size))
+ if (uint(pos) > uint(this->size()))
return *this;
- if (len > d->size - pos)
- len = d->size - pos;
+ if (len > this->size() - pos)
+ len = this->size() - pos;
uint index = pos;
replace_helper(&index, 1, len, unicode, size);
@@ -3077,10 +3037,10 @@ bool pointsIntoRange(const QChar *ptr, const ushort *base, int len)
*/
void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar *after, int alen)
{
- // Copy after if it lies inside our own d->data() area (which we could
+ // Copy after if it lies inside our own d.b area (which we could
// possibly invalidate via a realloc or modify by replacement).
QChar *afterBuffer = nullptr;
- if (pointsIntoRange(after, d->data(), d->size)) // Use copy in place of vulnerable original:
+ if (pointsIntoRange(after, d.data(), d.size)) // Use copy in place of vulnerable original:
after = afterBuffer = textCopy(after, alen);
QT_TRY {
@@ -3088,36 +3048,36 @@ void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar
// replace in place
detach();
for (int i = 0; i < nIndices; ++i)
- memcpy(d->data() + indices[i], after, alen * sizeof(QChar));
+ memcpy(d.data() + indices[i], after, alen * sizeof(QChar));
} else if (alen < blen) {
// replace from front
detach();
uint to = indices[0];
if (alen)
- memcpy(d->data()+to, after, alen*sizeof(QChar));
+ memcpy(d.data()+to, after, alen*sizeof(QChar));
to += alen;
uint movestart = indices[0] + blen;
for (int i = 1; i < nIndices; ++i) {
int msize = indices[i] - movestart;
if (msize > 0) {
- memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
+ memmove(d.data() + to, d.data() + movestart, msize * sizeof(QChar));
to += msize;
}
if (alen) {
- memcpy(d->data() + to, after, alen * sizeof(QChar));
+ memcpy(d.data() + to, after, alen * sizeof(QChar));
to += alen;
}
movestart = indices[i] + blen;
}
- int msize = d->size - movestart;
+ int msize = d.size - movestart;
if (msize > 0)
- memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
- resize(d->size - nIndices*(blen-alen));
+ memmove(d.data() + to, d.data() + movestart, msize * sizeof(QChar));
+ resize(d.size - nIndices*(blen-alen));
} else {
// replace from back
int adjust = nIndices*(alen-blen);
- int newLen = d->size + adjust;
- int moveend = d->size;
+ int newLen = d.size + adjust;
+ int moveend = d.size;
resize(newLen);
while (nIndices) {
@@ -3125,9 +3085,9 @@ void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar
int movestart = indices[nIndices] + blen;
int insertstart = indices[nIndices] + nIndices*(alen-blen);
int moveto = insertstart + alen;
- memmove(d->data() + moveto, d->data() + movestart,
+ memmove(d.data() + moveto, d.data() + movestart,
(moveend - movestart)*sizeof(QChar));
- memcpy(d->data() + insertstart, after, alen * sizeof(QChar));
+ memcpy(d.data() + insertstart, after, alen * sizeof(QChar));
moveend = movestart-blen;
}
}
@@ -3153,7 +3113,7 @@ QString &QString::replace(const QChar *before, int blen,
const QChar *after, int alen,
Qt::CaseSensitivity cs)
{
- if (d->size == 0) {
+ if (d.size == 0) {
if (blen)
return *this;
} else {
@@ -3188,10 +3148,10 @@ QString &QString::replace(const QChar *before, int blen,
We're about to change data, that before and after might point
into, and we'll need that data for our next batch of indices.
*/
- if (!afterBuffer && pointsIntoRange(after, d->data(), d->size))
+ if (!afterBuffer && pointsIntoRange(after, d.data(), d.size))
after = afterBuffer = textCopy(after, alen);
- if (!beforeBuffer && pointsIntoRange(before, d->data(), d->size)) {
+ if (!beforeBuffer && pointsIntoRange(before, d.data(), d.size)) {
beforeBuffer = textCopy(before, blen);
matcher = QStringMatcher(beforeBuffer, blen, cs);
}
@@ -3220,13 +3180,13 @@ QString &QString::replace(const QChar *before, int blen,
*/
QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
{
- if (after.d->size == 0)
+ if (after.size() == 0)
return remove(ch, cs);
- if (after.d->size == 1)
+ if (after.size() == 1)
return replace(ch, after.front(), cs);
- if (d->size == 0)
+ if (size() == 0)
return *this;
ushort cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
@@ -3236,14 +3196,14 @@ QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs
uint indices[1024];
uint pos = 0;
if (cs == Qt::CaseSensitive) {
- while (pos < 1024 && index < d->size) {
- if (d->data()[index] == cc)
+ while (pos < 1024 && index < size()) {
+ if (d.data()[index] == cc)
indices[pos++] = index;
index++;
}
} else {
- while (pos < 1024 && index < d->size) {
- if (QChar::toCaseFolded(d->data()[index]) == cc)
+ while (pos < 1024 && index < size()) {
+ if (QChar::toCaseFolded(d.data()[index]) == cc)
indices[pos++] = index;
index++;
}
@@ -3251,12 +3211,12 @@ QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs
if (!pos) // Nothing to replace
break;
- replace_helper(indices, pos, 1, after.constData(), after.d->size);
+ replace_helper(indices, pos, 1, after.constData(), after.size());
if (Q_LIKELY(index == -1)) // Nothing left to replace
break;
// The call to replace_helper just moved what index points at:
- index += pos*(after.d->size - 1);
+ index += pos*(after.size() - 1);
}
return *this;
}
@@ -3271,13 +3231,13 @@ QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs
*/
QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
{
- if (d->size) {
+ if (d.size) {
const int idx = indexOf(before, 0, cs);
if (idx != -1) {
detach();
const ushort a = after.unicode();
- ushort *i = d->data();
- const ushort *e = i + d->size;
+ ushort *i = d.data();
+ ushort *const e = i + d.size;
i += idx;
*i = a;
if (cs == Qt::CaseSensitive) {
@@ -3338,7 +3298,7 @@ QString &QString::replace(QLatin1String before, const QString &after, Qt::CaseSe
int blen = before.size();
QVarLengthArray<ushort> b(blen);
qt_from_latin1(b.data(), before.latin1(), blen);
- return replace((const QChar *)b.data(), blen, after.constData(), after.d->size, cs);
+ return replace((const QChar *)b.data(), blen, after.constData(), after.d.size, cs);
}
/*!
@@ -3358,7 +3318,7 @@ QString &QString::replace(const QString &before, QLatin1String after, Qt::CaseSe
int alen = after.size();
QVarLengthArray<ushort> a(alen);
qt_from_latin1(a.data(), after.latin1(), alen);
- return replace(before.constData(), before.d->size, (const QChar *)a.data(), alen, cs);
+ return replace(before.constData(), before.d.size, (const QChar *)a.data(), alen, cs);
}
/*!
@@ -3394,7 +3354,7 @@ QString &QString::replace(QChar c, QLatin1String after, Qt::CaseSensitivity cs)
*/
bool operator==(const QString &s1, const QString &s2) noexcept
{
- if (s1.d->size != s2.d->size)
+ if (s1.d.size != s2.d.size)
return false;
return qt_compare_strings(s1, s2, Qt::CaseSensitive) == 0;
@@ -3407,7 +3367,7 @@ bool operator==(const QString &s1, const QString &s2) noexcept
*/
bool QString::operator==(QLatin1String other) const noexcept
{
- if (d->size != other.size())
+ if (size() != other.size())
return false;
return qt_compare_strings(*this, other, Qt::CaseSensitive) == 0;
@@ -3953,7 +3913,7 @@ QString& QString::replace(const QRegExp &rx, const QString &after)
if (isEmpty() && rx2.indexIn(*this) == -1)
return *this;
- reallocData(uint(d->size) + 1u);
+ reallocData(uint(d.size) + 1u);
int index = 0;
int numCaptures = rx2.captureCount();
@@ -4052,8 +4012,8 @@ QString& QString::replace(const QRegExp &rx, const QString &after)
}
if (!pos)
break;
- replacements[pos].pos = d->size;
- int newlen = d->size + adjust;
+ replacements[pos].pos = d.size;
+ int newlen = d.size + adjust;
// to continue searching at the right position after we did
// the first round of replacements
@@ -4068,14 +4028,14 @@ QString& QString::replace(const QRegExp &rx, const QString &after)
while (i < pos) {
int copyend = replacements[i].pos;
int size = copyend - copystart;
- memcpy(static_cast<void*>(uc), static_cast<const void *>(d->data() + copystart), size * sizeof(QChar));
+ memcpy(static_cast<void*>(uc), static_cast<const void *>(d.data() + copystart), size * sizeof(QChar));
uc += size;
- memcpy(static_cast<void *>(uc), static_cast<const void *>(after.d->data()), al * sizeof(QChar));
+ memcpy(static_cast<void *>(uc), static_cast<const void *>(after.d.data()), al * sizeof(QChar));
uc += al;
copystart = copyend + replacements[i].length;
i++;
}
- memcpy(static_cast<void *>(uc), static_cast<const void *>(d->data() + copystart), (d->size - copystart) * sizeof(QChar));
+ memcpy(static_cast<void *>(uc), static_cast<const void *>(d.data() + copystart), (d.size - copystart) * sizeof(QChar));
newstring.resize(newlen);
*this = newstring;
caretMode = QRegExp::CaretWontMatch;
@@ -4115,7 +4075,7 @@ QString &QString::replace(const QRegularExpression &re, const QString &after)
if (!iterator.hasNext()) // no matches at all
return *this;
- reallocData(uint(d->size) + 1u);
+ reallocData(uint(d.size) + 1u);
int numCaptures = re.captureCount();
@@ -4448,24 +4408,6 @@ int QString::count(const QRegExp& rx) const
#if QT_CONFIG(regularexpression)
/*!
- \overload indexOf()
- \since 5.0
-
- Returns the index position of the first match of the regular
- expression \a re in the string, searching forward from index
- position \a from. Returns -1 if \a re didn't match anywhere.
-
- Example:
-
- \snippet qstring/main.cpp 93
-*/
-int QString::indexOf(const QRegularExpression& re, int from) const
-{
- return indexOf(re, from, nullptr);
-}
-
-/*!
- \overload
\since 5.5
Returns the index position of the first match of the regular
@@ -4478,7 +4420,7 @@ int QString::indexOf(const QRegularExpression& re, int from) const
Example:
- \snippet qstring/main.cpp 99
+ \snippet qstring/main.cpp 93
*/
int QString::indexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const
{
@@ -4499,24 +4441,6 @@ int QString::indexOf(const QRegularExpression &re, int from, QRegularExpressionM
}
/*!
- \overload lastIndexOf()
- \since 5.0
-
- Returns the index position of the last match of the regular
- expression \a re in the string, which starts before the index
- position \a from. Returns -1 if \a re didn't match anywhere.
-
- Example:
-
- \snippet qstring/main.cpp 94
-*/
-int QString::lastIndexOf(const QRegularExpression &re, int from) const
-{
- return lastIndexOf(re, from, nullptr);
-}
-
-/*!
- \overload
\since 5.5
Returns the index position of the last match of the regular
@@ -4529,7 +4453,7 @@ int QString::lastIndexOf(const QRegularExpression &re, int from) const
Example:
- \snippet qstring/main.cpp 100
+ \snippet qstring/main.cpp 94
*/
int QString::lastIndexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const
{
@@ -4556,19 +4480,7 @@ int QString::lastIndexOf(const QRegularExpression &re, int from, QRegularExpress
return lastIndex;
}
-/*! \overload contains()
- \since 5.0
-
- Returns \c true if the regular expression \a re matches somewhere in
- this string; otherwise returns \c false.
-*/
-bool QString::contains(const QRegularExpression &re) const
-{
- return contains(re, nullptr);
-}
-
/*!
- \overload contains()
\since 5.1
Returns \c true if the regular expression \a re matches somewhere in this
@@ -4915,9 +4827,9 @@ QString QString::section(const QRegularExpression &re, int start, int end, Secti
*/
QString QString::left(int n) const
{
- if (uint(n) >= uint(d->size))
+ if (uint(n) >= uint(size()))
return *this;
- return QString((const QChar*) d->data(), n);
+ return QString((const QChar*) d.data(), n);
}
/*!
@@ -4933,9 +4845,9 @@ QString QString::left(int n) const
*/
QString QString::right(int n) const
{
- if (uint(n) >= uint(d->size))
+ if (uint(n) >= uint(size()))
return *this;
- return QString((const QChar*) d->data() + d->size - n, n);
+ return QString(constData() + size() - n, n);
}
/*!
@@ -4958,18 +4870,19 @@ QString QString::right(int n) const
QString QString::mid(int position, int n) const
{
using namespace QtPrivate;
- switch (QContainerImplHelper::mid(d->size, &position, &n)) {
+ switch (QContainerImplHelper::mid(size(), &position, &n)) {
case QContainerImplHelper::Null:
return QString();
case QContainerImplHelper::Empty:
{
- QStringDataPtr empty = { Data::allocate(0) };
+ QPair<Data *, ushort *> pair = Data::allocate(0);
+ DataPointer empty = { pair.first, pair.second, 0 };
return QString(empty);
}
case QContainerImplHelper::Full:
return *this;
case QContainerImplHelper::Subset:
- return QString((const QChar*)d->data() + position, n);
+ return QString(constData() + position, n);
}
Q_UNREACHABLE();
return QString();
@@ -5211,29 +5124,29 @@ QByteArray QString::toLatin1_helper_inplace(QString &s)
// We can return our own buffer to the caller.
// Conversion to Latin-1 always shrinks the buffer by half.
- const ushort *data = reinterpret_cast<const ushort *>(s.constData());
- uint length = s.size();
+ const ushort *data = s.d.data();
+ int length = s.d.size;
- // Swap the d pointers.
+ // Move the d pointer over to the bytearray.
// Kids, avert your eyes. Don't try this at home.
- QArrayData *ba_d = s.d;
- // multiply the allocated capacity by sizeof(ushort)
- ba_d->alloc *= sizeof(ushort);
+ // this relies on the fact that we use QArrayData for everything behind the scenes which has the same layout
+ static_assert(sizeof(QByteArray::DataPointer) == sizeof(QString::DataPointer), "sizes have to be equal");
+ QByteArray::DataPointer ba_d(reinterpret_cast<QByteArray::Data *>(s.d.d_ptr()), reinterpret_cast<char *>(s.d.data()), length);
+ ba_d.ref();
+ s.clear();
- // reset ourselves to QString()
- s.d = QString().d;
+ char *ddata = ba_d.data();
- // do the in-place conversion
- uchar *dst = reinterpret_cast<uchar *>(ba_d->data());
- qt_to_latin1(dst, data, length);
- dst[length] = '\0';
+ // multiply the allocated capacity by sizeof(ushort)
+ ba_d.d_ptr()->alloc *= sizeof(ushort);
- QByteArrayDataPtr badptr = { ba_d };
- return QByteArray(badptr);
+ // do the in-place conversion
+ qt_to_latin1(reinterpret_cast<uchar *>(ddata), data, length);
+ ddata[length] = '\0';
+ return QByteArray(ba_d);
}
-
/*!
\fn QByteArray QString::toLatin1() const
@@ -5413,34 +5326,25 @@ QVector<uint> QtPrivate::convertToUcs4(QStringView string)
return qt_convert_to_ucs4(string);
}
-QString::Data *QString::fromLatin1_helper(const char *str, int size)
+QString::DataPointer QString::fromLatin1_helper(const char *str, int size)
{
- Data *d;
+ DataPointer d;
if (!str) {
- d = Data::sharedNull();
+ // nothing to do
} else if (size == 0 || (!*str && size < 0)) {
- d = Data::allocate(0);
+ d = DataPointer(Data::allocate(0), 0);
} else {
if (size < 0)
size = qstrlen(str);
- d = Data::allocate(size + 1);
- Q_CHECK_PTR(d);
- d->size = size;
- d->data()[size] = '\0';
- ushort *dst = d->data();
+ d = DataPointer(Data::allocate(size + 1), size);
+ d.data()[size] = '\0';
+ ushort *dst = d.data();
qt_from_latin1(dst, str, uint(size));
}
return d;
}
-QString::Data *QString::fromAscii_helper(const char *str, int size)
-{
- QString s = fromUtf8(str, size);
- s.d->ref.ref();
- return s.d;
-}
-
/*! \fn QString QString::fromLatin1(const char *str, int size)
Returns a QString initialized with the first \a size characters
of the Latin-1 string \a str.
@@ -5483,7 +5387,8 @@ QString QString::fromLocal8Bit_helper(const char *str, int size)
if (!str)
return QString();
if (size == 0 || (!*str && size < 0)) {
- QStringDataPtr empty = { Data::allocate(0) };
+ QPair<Data *, ushort *> pair = Data::allocate(0);
+ QString::DataPointer empty = { pair.first, pair.second, 0 };
return QString(empty);
}
#if QT_CONFIG(textcodec)
@@ -5653,7 +5558,7 @@ QString& QString::setUnicode(const QChar *unicode, int size)
{
resize(size);
if (unicode && size)
- memcpy(d->data(), unicode, size * sizeof(QChar));
+ memcpy(d.data(), unicode, size * sizeof(QChar));
return *this;
}
@@ -5775,7 +5680,7 @@ QString QString::trimmed_helper(QString &str)
*/
/*!
- \fn QCharRef QString::operator[](int position)
+ \fn QChar &QString::operator[](int position)
Returns the character at the specified \a position in the string as a
modifiable reference.
@@ -5784,20 +5689,6 @@ QString QString::trimmed_helper(QString &str)
\snippet qstring/main.cpp 85
- The return value is of type QCharRef, a helper class for QString.
- When you get an object of type QCharRef, you can use it as if it
- were a reference to a QChar. If you assign to it, the assignment will apply to
- the character in the QString from which you got the reference.
-
- \note Before Qt 5.14 it was possible to use this operator to access
- a character at an out-of-bounds position in the string, and
- then assign to such a position, causing the string to be
- automatically resized. Furthermore, assigning a value to the
- returned QCharRef would cause a detach of the string, even if the
- string has been copied in the meanwhile (and the QCharRef kept
- alive while the copy was taken). These behaviors are deprecated,
- and will be changed in a future version of Qt.
-
\sa at()
*/
@@ -5807,19 +5698,6 @@ QString QString::trimmed_helper(QString &str)
\overload operator[]()
*/
-/*! \fn QCharRef QString::operator[](uint position)
-
-\overload operator[]()
-
-Returns the character at the specified \a position in the string as a
-modifiable reference.
-*/
-
-/*! \fn const QChar QString::operator[](uint position) const
- Equivalent to \c at(position).
-\overload operator[]()
-*/
-
/*!
\fn QChar QString::front() const
\since 5.10
@@ -5851,7 +5729,7 @@ modifiable reference.
*/
/*!
- \fn QCharRef QString::front()
+ \fn QChar &QString::front()
\since 5.10
Returns a reference to the first character in the string.
@@ -5866,7 +5744,7 @@ modifiable reference.
*/
/*!
- \fn QCharRef QString::back()
+ \fn QChar &QString::back()
\since 5.10
Returns a reference to the last character in the string.
@@ -5899,7 +5777,7 @@ modifiable reference.
void QString::truncate(int pos)
{
- if (pos < d->size)
+ if (pos < size())
resize(pos);
}
@@ -5921,7 +5799,7 @@ void QString::truncate(int pos)
void QString::chop(int n)
{
if (n > 0)
- resize(d->size - n);
+ resize(d.size - n);
}
/*!
@@ -5938,10 +5816,10 @@ void QString::chop(int n)
QString& QString::fill(QChar ch, int size)
{
- resize(size < 0 ? d->size : size);
- if (d->size) {
- QChar *i = (QChar*)d->data() + d->size;
- QChar *b = (QChar*)d->data();
+ resize(size < 0 ? d.size : size);
+ if (d.size) {
+ QChar *i = (QChar*)d.data() + d.size;
+ QChar *b = (QChar*)d.data();
while (i != b)
*--i = ch;
}
@@ -6522,11 +6400,11 @@ int QString::localeAwareCompare_helper(const QChar *data1, int length1,
const ushort *QString::utf16() const
{
- if (IS_RAW_DATA(d)) {
+ if (!d->isMutable()) {
// ensure '\0'-termination for ::fromRawData strings
- const_cast<QString*>(this)->reallocData(uint(d->size) + 1u);
+ const_cast<QString*>(this)->reallocData(uint(d.size) + 1u);
}
- return d->data();
+ return d.data();
}
/*!
@@ -6555,8 +6433,8 @@ QString QString::leftJustified(int width, QChar fill, bool truncate) const
if (padlen > 0) {
result.resize(len+padlen);
if (len)
- memcpy(result.d->data(), d->data(), sizeof(QChar)*len);
- QChar *uc = (QChar*)result.d->data() + len;
+ memcpy(result.d.data(), d.data(), sizeof(QChar)*len);
+ QChar *uc = (QChar*)result.d.data() + len;
while (padlen--)
* uc++ = fill;
} else {
@@ -6593,11 +6471,11 @@ QString QString::rightJustified(int width, QChar fill, bool truncate) const
int padlen = width - len;
if (padlen > 0) {
result.resize(len+padlen);
- QChar *uc = (QChar*)result.d->data();
+ QChar *uc = (QChar*)result.d.data();
while (padlen--)
* uc++ = fill;
if (len)
- memcpy(static_cast<void *>(uc), static_cast<const void *>(d->data()), sizeof(QChar)*len);
+ memcpy(static_cast<void *>(uc), static_cast<const void *>(d.data()), sizeof(QChar)*len);
} else {
if (truncate)
result = left(width);
@@ -8006,7 +7884,7 @@ QVector<QStringRef> QString::splitRef(const QRegularExpression &re, SplitBehavio
*/
QString QString::repeated(int times) const
{
- if (d->size == 0)
+ if (d.size == 0)
return *this;
if (times <= 1) {
@@ -8015,27 +7893,27 @@ QString QString::repeated(int times) const
return QString();
}
- const int resultSize = times * d->size;
+ const int resultSize = times * d.size;
QString result;
result.reserve(resultSize);
- if (result.d->alloc != uint(resultSize) + 1u)
+ if (result.capacity() != resultSize)
return QString(); // not enough memory
- memcpy(result.d->data(), d->data(), d->size * sizeof(ushort));
+ memcpy(result.d.data(), d.data(), d.size * sizeof(ushort));
- int sizeSoFar = d->size;
- ushort *end = result.d->data() + sizeSoFar;
+ int sizeSoFar = d.size;
+ ushort *end = result.d.data() + sizeSoFar;
const int halfResultSize = resultSize >> 1;
while (sizeSoFar <= halfResultSize) {
- memcpy(end, result.d->data(), sizeSoFar * sizeof(ushort));
+ memcpy(end, result.d.data(), sizeSoFar * sizeof(ushort));
end += sizeSoFar;
sizeSoFar <<= 1;
}
- memcpy(end, result.d->data(), (resultSize - sizeSoFar) * sizeof(ushort));
- result.d->data()[resultSize] = '\0';
- result.d->size = resultSize;
+ memcpy(end, result.d.data(), (resultSize - sizeSoFar) * sizeof(ushort));
+ result.d.data()[resultSize] = '\0';
+ result.d.size = resultSize;
return result;
}
@@ -9035,8 +8913,8 @@ QString QtPrivate::argToQString(QLatin1String pattern, size_t n, const ArgBase *
*/
bool QString::isSimpleText() const
{
- const ushort *p = d->data();
- const ushort * const end = p + d->size;
+ const ushort *p = d.data();
+ const ushort * const end = p + d.size;
while (p < end) {
ushort uc = *p;
// sort out regions of complex text formatting
@@ -9200,17 +9078,14 @@ bool QString::isRightToLeft() const
*/
QString QString::fromRawData(const QChar *unicode, int size)
{
- Data *x;
+ QString::DataPointer x;
if (!unicode) {
- x = Data::sharedNull();
} else if (!size) {
- x = Data::allocate(0);
+ x = DataPointer(Data::allocate(0), 0);
} else {
x = Data::fromRawData(reinterpret_cast<const ushort *>(unicode), size);
- Q_CHECK_PTR(x);
}
- QStringDataPtr dataPtr = { x };
- return QString(dataPtr);
+ return QString(x);
}
/*!
@@ -9229,17 +9104,10 @@ QString QString::fromRawData(const QChar *unicode, int size)
*/
QString &QString::setRawData(const QChar *unicode, int size)
{
- if (d->ref.isShared() || d->alloc) {
- *this = fromRawData(unicode, size);
- } else {
- if (unicode) {
- d->size = size;
- d->offset = reinterpret_cast<const char *>(unicode) - reinterpret_cast<char *>(d);
- } else {
- d->offset = sizeof(QStringData);
- d->size = 0;
- }
+ if (!unicode || !size) {
+ clear();
}
+ *this = fromRawData(unicode, size);
return *this;
}
@@ -10538,7 +10406,7 @@ ownership of it, no memory is freed when instances are destroyed.
*/
QString QStringRef::toString() const {
- if (!m_string)
+ if (isNull())
return QString();
if (m_size && m_position == 0 && m_size == m_string->size())
return *m_string;
diff --git a/src/corelib/text/qstring.h b/src/corelib/text/qstring.h
index 1f4e856660..65d702ff1c 100644
--- a/src/corelib/text/qstring.h
+++ b/src/corelib/text/qstring.h
@@ -1,7 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
+** Copyright (C) 2019 Intel Corporation.
** Copyright (C) 2019 Mail.ru Group.
** Contact: https://www.qt.io/licensing/
**
@@ -48,7 +48,7 @@
#include <QtCore/qchar.h>
#include <QtCore/qbytearray.h>
-#include <QtCore/qrefcount.h>
+#include <QtCore/qarraydata.h>
#include <QtCore/qnamespace.h>
#include <QtCore/qstringliteral.h>
#include <QtCore/qstringalgorithms.h>
@@ -70,7 +70,6 @@ Q_FORWARD_DECLARE_OBJC_CLASS(NSString);
QT_BEGIN_NAMESPACE
-class QCharRef;
class QRegExp;
class QRegularExpression;
class QRegularExpressionMatch;
@@ -246,8 +245,9 @@ qsizetype QStringView::lastIndexOf(QLatin1String s, qsizetype from, Qt::CaseSens
class Q_CORE_EXPORT QString
{
+ typedef QTypedArrayData<ushort> Data;
public:
- typedef QStringData Data;
+ typedef QStringPrivate DataPointer;
inline QString() noexcept;
explicit QString(const QChar *unicode, int size = -1);
@@ -259,12 +259,13 @@ public:
QString &operator=(QChar c);
QString &operator=(const QString &) noexcept;
QString &operator=(QLatin1String latin1);
- inline QString(QString && other) noexcept : d(other.d) { other.d = Data::sharedNull(); }
+ inline QString(QString &&other) noexcept
+ { qSwap(d, other.d); }
inline QString &operator=(QString &&other) noexcept
{ qSwap(d, other.d); return *this; }
inline void swap(QString &other) noexcept { qSwap(d, other.d); }
- inline int size() const { return d->size; }
- inline int count() const { return d->size; }
+ inline int size() const { return int(d.size); }
+ inline int count() const { return int(d.size); }
inline int length() const;
inline bool isEmpty() const;
void resize(int size);
@@ -274,7 +275,7 @@ public:
void truncate(int pos);
void chop(int n);
- int capacity() const;
+ inline int capacity() const;
inline void reserve(int size);
inline void squeeze();
@@ -285,19 +286,17 @@ public:
inline void detach();
inline bool isDetached() const;
- inline bool isSharedWith(const QString &other) const { return d == other.d; }
+ inline bool isSharedWith(const QString &other) const { return d.isSharedWith(other.d); }
void clear();
inline const QChar at(int i) const;
const QChar operator[](int i) const;
- Q_REQUIRED_RESULT QCharRef operator[](int i);
- const QChar operator[](uint i) const;
- Q_REQUIRED_RESULT QCharRef operator[](uint i);
+ Q_REQUIRED_RESULT QChar &operator[](int i);
Q_REQUIRED_RESULT inline QChar front() const { return at(0); }
- Q_REQUIRED_RESULT inline QCharRef front();
+ Q_REQUIRED_RESULT inline QChar &front();
Q_REQUIRED_RESULT inline QChar back() const { return at(size() - 1); }
- Q_REQUIRED_RESULT inline QCharRef back();
+ Q_REQUIRED_RESULT inline QChar &back();
Q_REQUIRED_RESULT QString arg(qlonglong a, int fieldwidth=0, int base=10,
QChar fillChar = QLatin1Char(' ')) const;
@@ -425,12 +424,11 @@ public:
#endif
#if QT_CONFIG(regularexpression)
- int indexOf(const QRegularExpression &re, int from = 0) const;
- int indexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const; // ### Qt 6: merge overloads
- int lastIndexOf(const QRegularExpression &re, int from = -1) const;
- int lastIndexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const; // ### Qt 6: merge overloads
- bool contains(const QRegularExpression &re) const;
- bool contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch) const; // ### Qt 6: merge overloads
+ int indexOf(const QRegularExpression &re, int from = 0,
+ QRegularExpressionMatch *rmatch = nullptr) const;
+ int lastIndexOf(const QRegularExpression &re, int from = -1,
+ QRegularExpressionMatch *rmatch = nullptr) const;
+ bool contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const;
int count(const QRegularExpression &re) const;
#endif
@@ -543,10 +541,10 @@ public:
inline QString &prepend(QLatin1String s) { return insert(0, s); }
inline QString &operator+=(QChar c) {
- if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
- reallocData(uint(d->size) + 2u, true);
- d->data()[d->size++] = c.unicode();
- d->data()[d->size] = '\0';
+ if (d->needsDetach() || int(d.size + 1) > capacity())
+ reallocData(uint(d.size) + 2u, true);
+ d->data()[d.size++] = c.unicode();
+ d->data()[d.size] = '\0';
return *this;
}
@@ -659,8 +657,7 @@ public:
// note - this are all inline so we can benefit from strlen() compile time optimizations
static inline QString fromLatin1(const char *str, int size = -1)
{
- QStringDataPtr dataPtr = { fromLatin1_helper(str, (str && size == -1) ? int(strlen(str)) : size) };
- return QString(dataPtr);
+ return QString(fromLatin1_helper(str, (str && size == -1) ? int(strlen(str)) : size));
}
static inline QString fromUtf8(const char *str, int size = -1)
{
@@ -792,10 +789,10 @@ public:
#endif
#if !defined(QT_NO_CAST_FROM_ASCII) && !defined(QT_RESTRICTED_CAST_FROM_ASCII)
inline QT_ASCII_CAST_WARN QString(const char *ch)
- : d(fromAscii_helper(ch, ch ? int(strlen(ch)) : -1))
+ : QString(fromUtf8(ch))
{}
inline QT_ASCII_CAST_WARN QString(const QByteArray &a)
- : d(fromAscii_helper(a.constData(), qstrnlen(a.constData(), a.size())))
+ : QString(fromUtf8(a))
{}
inline QT_ASCII_CAST_WARN QString &operator=(const char *ch)
{ return (*this = fromUtf8(ch)); }
@@ -911,10 +908,10 @@ public:
struct Null { };
QT_DEPRECATED_X("use QString()")
static const Null null;
- inline QString(const Null &): d(Data::sharedNull()) {}
+ inline QString(const Null &) {}
inline QString &operator=(const Null &) { *this = QString(); return *this; }
#endif
- inline bool isNull() const { return d == Data::sharedNull(); }
+ inline bool isNull() const { return d->isNull(); }
bool isSimpleText() const;
@@ -923,7 +920,7 @@ public:
{ return QStringView(*this).isValidUtf16(); }
QString(int size, Qt::Initialization);
- Q_DECL_CONSTEXPR inline QString(QStringDataPtr dd) : d(dd.ptr) {}
+ explicit QString(DataPointer dd) : d(dd) {}
private:
#if defined(QT_NO_CAST_FROM_ASCII)
@@ -935,7 +932,7 @@ private:
QString &operator=(const QByteArray &a);
#endif
- Data *d;
+ DataPointer d;
friend inline bool operator==(QChar, const QString &) noexcept;
friend inline bool operator< (QChar, const QString &) noexcept;
@@ -973,8 +970,7 @@ private:
static QString trimmed_helper(QString &str);
static QString simplified_helper(const QString &str);
static QString simplified_helper(QString &str);
- static Data *fromLatin1_helper(const char *str, int size = -1);
- static Data *fromAscii_helper(const char *str, int size = -1);
+ static DataPointer fromLatin1_helper(const char *str, int size = -1);
static QString fromUtf8_helper(const char *str, int size);
static QString fromLocal8Bit_helper(const char *, int size);
static QByteArray toLatin1_helper(const QString &);
@@ -985,7 +981,6 @@ private:
static qlonglong toIntegral_helper(const QChar *data, int len, bool *ok, int base);
static qulonglong toIntegral_helper(const QChar *data, uint len, bool *ok, int base);
void replace_helper(uint *indices, int nIndices, int blen, const QChar *after, int alen);
- friend class QCharRef;
friend class QTextCodec;
friend class QStringRef;
friend class QStringView;
@@ -1010,8 +1005,7 @@ private:
}
public:
- typedef Data * DataPtr;
- inline DataPtr &data_ptr() { return d; }
+ inline DataPointer &data_ptr() { return d; }
};
//
@@ -1026,33 +1020,31 @@ QString QStringView::toString() const
inline QString::QString(QLatin1String aLatin1) : d(fromLatin1_helper(aLatin1.latin1(), aLatin1.size()))
{ }
inline int QString::length() const
-{ return d->size; }
+{ return int(d.size); }
inline const QChar QString::at(int i) const
-{ Q_ASSERT(uint(i) < uint(size())); return QChar(d->data()[i]); }
+{ Q_ASSERT(uint(i) < uint(size())); return QChar(d.data()[i]); }
inline const QChar QString::operator[](int i) const
-{ Q_ASSERT(uint(i) < uint(size())); return QChar(d->data()[i]); }
-inline const QChar QString::operator[](uint i) const
-{ Q_ASSERT(i < uint(size())); return QChar(d->data()[i]); }
+{ Q_ASSERT(uint(i) < uint(size())); return QChar(d.data()[i]); }
inline bool QString::isEmpty() const
-{ return d->size == 0; }
+{ return d.size == 0; }
inline const QChar *QString::unicode() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline const QChar *QString::data() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline QChar *QString::data()
-{ detach(); return reinterpret_cast<QChar*>(d->data()); }
+{ detach(); return reinterpret_cast<QChar*>(d.data()); }
inline const QChar *QString::constData() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline void QString::detach()
-{ if (d->ref.isShared() || (d->offset != sizeof(QStringData))) reallocData(uint(d->size) + 1u); }
+{ if (d->needsDetach()) reallocData(d.size + 1u); }
inline bool QString::isDetached() const
-{ return !d->ref.isShared(); }
+{ return !d->isShared(); }
inline void QString::clear()
{ if (!isNull()) *this = QString(); }
inline QString::QString(const QString &other) noexcept : d(other.d)
-{ Q_ASSERT(&other != this); d->ref.ref(); }
+{ }
inline int QString::capacity() const
-{ return d->alloc ? d->alloc - 1 : 0; }
+{ const auto realCapacity = d->constAllocatedCapacity(); return realCapacity ? int(realCapacity) - 1 : 0; }
inline QString &QString::setNum(short n, int base)
{ return setNum(qlonglong(n), base); }
inline QString &QString::setNum(ushort n, int base)
@@ -1139,178 +1131,51 @@ inline QString QString::fromWCharArray(const wchar_t *string, int size)
: fromUcs4(reinterpret_cast<const uint *>(string), size);
}
-class
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-Q_CORE_EXPORT
-#endif
-QCharRef { // ### Qt 7: remove
- QString &s;
- int i;
- inline QCharRef(QString &str, int idx)
- : s(str),i(idx) {}
- friend class QString;
-public:
-
- // most QChar operations repeated here
-
- // all this is not documented: We just say "like QChar" and let it be.
- inline operator QChar() const
- {
- using namespace QtPrivate::DeprecatedRefClassBehavior;
- if (Q_LIKELY(i < s.d->size))
- return QChar(s.d->data()[i]);
-#ifdef QT_DEBUG
- warn(WarningType::OutOfRange, EmittingClass::QCharRef);
-#endif
- return QChar();
- }
- inline QCharRef &operator=(QChar c)
- {
- using namespace QtPrivate::DeprecatedRefClassBehavior;
- if (Q_UNLIKELY(i >= s.d->size)) {
-#ifdef QT_DEBUG
- warn(WarningType::OutOfRange, EmittingClass::QCharRef);
-#endif
- s.resize(i + 1, QLatin1Char(' '));
- } else {
-#ifdef QT_DEBUG
- if (Q_UNLIKELY(!s.isDetached()))
- warn(WarningType::DelayedDetach, EmittingClass::QCharRef);
-#endif
- s.detach();
- }
- s.d->data()[i] = c.unicode();
- return *this;
- }
-
- // An operator= for each QChar cast constructors
-#ifndef QT_NO_CAST_FROM_ASCII
- inline QT_ASCII_CAST_WARN QCharRef &operator=(char c)
- { return operator=(QChar::fromLatin1(c)); }
- inline QT_ASCII_CAST_WARN QCharRef &operator=(uchar c)
- { return operator=(QChar::fromLatin1(c)); }
-#endif
- inline QCharRef &operator=(const QCharRef &c) { return operator=(QChar(c)); }
- inline QCharRef &operator=(ushort rc) { return operator=(QChar(rc)); }
- inline QCharRef &operator=(short rc) { return operator=(QChar(rc)); }
- inline QCharRef &operator=(uint rc) { return operator=(QChar(rc)); }
- inline QCharRef &operator=(int rc) { return operator=(QChar(rc)); }
-
- // each function...
- inline bool isNull() const { return QChar(*this).isNull(); }
- inline bool isPrint() const { return QChar(*this).isPrint(); }
- inline bool isPunct() const { return QChar(*this).isPunct(); }
- inline bool isSpace() const { return QChar(*this).isSpace(); }
- inline bool isMark() const { return QChar(*this).isMark(); }
- inline bool isLetter() const { return QChar(*this).isLetter(); }
- inline bool isNumber() const { return QChar(*this).isNumber(); }
- inline bool isLetterOrNumber() { return QChar(*this).isLetterOrNumber(); }
- inline bool isDigit() const { return QChar(*this).isDigit(); }
- inline bool isLower() const { return QChar(*this).isLower(); }
- inline bool isUpper() const { return QChar(*this).isUpper(); }
- inline bool isTitleCase() const { return QChar(*this).isTitleCase(); }
-
- inline int digitValue() const { return QChar(*this).digitValue(); }
- QChar toLower() const { return QChar(*this).toLower(); }
- QChar toUpper() const { return QChar(*this).toUpper(); }
- QChar toTitleCase () const { return QChar(*this).toTitleCase(); }
-
- QChar::Category category() const { return QChar(*this).category(); }
- QChar::Direction direction() const { return QChar(*this).direction(); }
- QChar::JoiningType joiningType() const { return QChar(*this).joiningType(); }
-#if QT_DEPRECATED_SINCE(5, 3)
- QT_DEPRECATED QChar::Joining joining() const
- {
- switch (QChar(*this).joiningType()) {
- case QChar::Joining_Causing: return QChar::Center;
- case QChar::Joining_Dual: return QChar::Dual;
- case QChar::Joining_Right: return QChar::Right;
- case QChar::Joining_None:
- case QChar::Joining_Left:
- case QChar::Joining_Transparent:
- default: return QChar::OtherJoining;
- }
- }
-#endif
- bool hasMirrored() const { return QChar(*this).hasMirrored(); }
- QChar mirroredChar() const { return QChar(*this).mirroredChar(); }
- QString decomposition() const { return QChar(*this).decomposition(); }
- QChar::Decomposition decompositionTag() const { return QChar(*this).decompositionTag(); }
- uchar combiningClass() const { return QChar(*this).combiningClass(); }
-
- inline QChar::Script script() const { return QChar(*this).script(); }
-
- QChar::UnicodeVersion unicodeVersion() const { return QChar(*this).unicodeVersion(); }
-
- inline uchar cell() const { return QChar(*this).cell(); }
- inline uchar row() const { return QChar(*this).row(); }
- inline void setCell(uchar cell);
- inline void setRow(uchar row);
-
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED char toAscii() const { return QChar(*this).toLatin1(); }
-#endif
- char toLatin1() const { return QChar(*this).toLatin1(); }
- ushort unicode() const { return QChar(*this).unicode(); }
- ushort& unicode() { return s.data()[i].unicode(); }
-
-};
-Q_DECLARE_TYPEINFO(QCharRef, Q_MOVABLE_TYPE);
-
-inline void QCharRef::setRow(uchar arow) { QChar(*this).setRow(arow); }
-inline void QCharRef::setCell(uchar acell) { QChar(*this).setCell(acell); }
-
-
-inline QString::QString() noexcept : d(Data::sharedNull()) {}
-inline QString::~QString() { if (!d->ref.deref()) Data::deallocate(d); }
+inline QString::QString() noexcept {}
+inline QString::~QString() {}
inline void QString::reserve(int asize)
{
- if (d->ref.isShared() || uint(asize) >= d->alloc)
- reallocData(qMax(asize, d->size) + 1u);
+ if (d->needsDetach() || asize >= capacity())
+ reallocData(uint(qMax(asize, size())) + 1u);
- if (!d->capacityReserved) {
- // cannot set unconditionally, since d could be the shared_null/shared_empty (which is const)
- d->capacityReserved = true;
- }
+ // we're not shared anymore, for sure
+ d->flags() |= Data::CapacityReserved;
}
inline void QString::squeeze()
{
- if (d->ref.isShared() || uint(d->size) + 1u < d->alloc)
- reallocData(uint(d->size) + 1u);
+ if ((d->flags() & Data::CapacityReserved) == 0)
+ return;
+ if (d->needsDetach() || int(d.size) < capacity())
+ reallocData(uint(d.size) + 1u);
- if (d->capacityReserved) {
- // cannot set unconditionally, since d could be shared_null or
- // otherwise static.
- d->capacityReserved = false;
- }
+ // we're not shared anymore, for sure
+ d->flags() &= uint(~Data::CapacityReserved);
}
inline QString &QString::setUtf16(const ushort *autf16, int asize)
{ return setUnicode(reinterpret_cast<const QChar *>(autf16), asize); }
-inline QCharRef QString::operator[](int i)
-{ Q_ASSERT(i >= 0); detach(); return QCharRef(*this, i); }
-inline QCharRef QString::operator[](uint i)
-{ detach(); return QCharRef(*this, i); }
-inline QCharRef QString::front() { return operator[](0); }
-inline QCharRef QString::back() { return operator[](size() - 1); }
+inline QChar &QString::operator[](int i)
+{ Q_ASSERT(i >= 0 && i < size()); return data()[i]; }
+inline QChar &QString::front() { return operator[](0); }
+inline QChar &QString::back() { return operator[](size() - 1); }
inline QString::iterator QString::begin()
-{ detach(); return reinterpret_cast<QChar*>(d->data()); }
+{ detach(); return reinterpret_cast<QChar*>(d.data()); }
inline QString::const_iterator QString::begin() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline QString::const_iterator QString::cbegin() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline QString::const_iterator QString::constBegin() const
-{ return reinterpret_cast<const QChar*>(d->data()); }
+{ return reinterpret_cast<const QChar*>(d.data()); }
inline QString::iterator QString::end()
-{ detach(); return reinterpret_cast<QChar*>(d->data() + d->size); }
+{ detach(); return reinterpret_cast<QChar*>(d.data() + d.size); }
inline QString::const_iterator QString::end() const
-{ return reinterpret_cast<const QChar*>(d->data() + d->size); }
+{ return reinterpret_cast<const QChar*>(d.data() + d.size); }
inline QString::const_iterator QString::cend() const
-{ return reinterpret_cast<const QChar*>(d->data() + d->size); }
+{ return reinterpret_cast<const QChar*>(d.data() + d.size); }
inline QString::const_iterator QString::constEnd() const
-{ return reinterpret_cast<const QChar*>(d->data() + d->size); }
+{ return reinterpret_cast<const QChar*>(d.data() + d.size); }
#if QT_STRINGVIEW_LEVEL < 2
inline bool QString::contains(const QString &s, Qt::CaseSensitivity cs) const
{ return indexOf(s, 0, cs) != -1; }
@@ -1537,7 +1402,8 @@ inline QString QString::fromStdU32String(const std::u32string &s)
inline std::u32string QString::toStdU32String() const
{
std::u32string u32str(length(), char32_t(0));
- int len = toUcs4_helper(d->data(), length(), reinterpret_cast<uint*>(&u32str[0]));
+ int len = toUcs4_helper(reinterpret_cast<const ushort *>(constData()), length(),
+ reinterpret_cast<uint*>(&u32str[0]));
u32str.resize(len);
return u32str;
}
@@ -1669,7 +1535,7 @@ public:
inline const QChar *unicode() const
{
if (!m_string)
- return reinterpret_cast<const QChar *>(QString::Data::sharedNull()->data());
+ return reinterpret_cast<const QChar *>(QString::Data::sharedNullData());
return m_string->unicode() + m_position;
}
inline const QChar *data() const { return unicode(); }
diff --git a/src/corelib/text/qstringbuilder.cpp b/src/corelib/text/qstringbuilder.cpp
index cf443ec369..29bd216e80 100644
--- a/src/corelib/text/qstringbuilder.cpp
+++ b/src/corelib/text/qstringbuilder.cpp
@@ -73,7 +73,7 @@ QT_BEGIN_NAMESPACE
\list
\li QString, QStringRef, (since 5.10:) QStringView
- \li QChar, QCharRef, QLatin1Char, (since 5.10:) \c char16_t,
+ \li QChar, QLatin1Char, (since 5.10:) \c char16_t,
\li QLatin1String,
\li (since 5.10:) \c{const char16_t[]} (\c{u"foo"}),
\li QByteArray, \c char, \c{const char[]}.
@@ -108,7 +108,7 @@ QT_BEGIN_NAMESPACE
This function is usable with arguments of type \c QString,
\c QLatin1String, \c QStringRef,
- \c QChar, \c QCharRef, \c QLatin1Char, and \c char.
+ \c QChar, \c QLatin1Char, and \c char.
*/
/* \fn template <typename A, typename B> QByteArray QStringBuilder<A, B>::toLatin1() const
diff --git a/src/corelib/text/qstringbuilder.h b/src/corelib/text/qstringbuilder.h
index 288d98d633..45fd270b66 100644
--- a/src/corelib/text/qstringbuilder.h
+++ b/src/corelib/text/qstringbuilder.h
@@ -231,16 +231,6 @@ template <> struct QConcatenable<QChar::SpecialCharacter> : private QAbstractCon
{ *out++ = c; }
};
-template <> struct QConcatenable<QCharRef> : private QAbstractConcatenable
-{
- typedef QCharRef type;
- typedef QString ConvertTo;
- enum { ExactSize = true };
- static int size(QCharRef) { return 1; }
- static inline void appendTo(QCharRef c, QChar *&out)
- { *out++ = QChar(c); }
-};
-
template <> struct QConcatenable<QLatin1String> : private QAbstractConcatenable
{
typedef QLatin1String type;
diff --git a/src/corelib/text/qstringlist.h b/src/corelib/text/qstringlist.h
index a464d443dc..6e0940c488 100644
--- a/src/corelib/text/qstringlist.h
+++ b/src/corelib/text/qstringlist.h
@@ -38,7 +38,7 @@
**
****************************************************************************/
-#include <QtCore/qlist.h>
+#include <QtCore/qvector.h>
#ifndef QSTRINGLIST_H
#define QSTRINGLIST_H
@@ -55,21 +55,21 @@ class QRegExp;
class QRegularExpression;
#if !defined(QT_NO_JAVA_STYLE_ITERATORS)
-typedef QListIterator<QString> QStringListIterator;
-typedef QMutableListIterator<QString> QMutableStringListIterator;
+typedef QVectorIterator<QString> QStringListIterator;
+typedef QMutableVectorIterator<QString> QMutableStringListIterator;
#endif
class QStringList;
#ifdef Q_QDOC
-class QStringList : public QList<QString>
+class QStringList : public QVector<QString>
#else
-template <> struct QListSpecialMethods<QString>
+template <> struct QVectorSpecialMethods<QString>
#endif
{
#ifndef Q_QDOC
protected:
- ~QListSpecialMethods() = default;
+ ~QVectorSpecialMethods() = default;
#endif
public:
inline void sort(Qt::CaseSensitivity cs = Qt::CaseSensitive);
@@ -108,23 +108,23 @@ private:
};
// ### Qt6: check if there's a better way
-class QStringList : public QList<QString>
+class QStringList : public QVector<QString>
{
#endif
public:
inline QStringList() noexcept { }
inline explicit QStringList(const QString &i) { append(i); }
- inline QStringList(const QList<QString> &l) : QList<QString>(l) { }
- inline QStringList(QList<QString> &&l) noexcept : QList<QString>(std::move(l)) { }
- inline QStringList(std::initializer_list<QString> args) : QList<QString>(args) { }
+ inline QStringList(const QVector<QString> &l) : QVector<QString>(l) { }
+ inline QStringList(QVector<QString> &&l) noexcept : QVector<QString>(std::move(l)) { }
+ inline QStringList(std::initializer_list<QString> args) : QVector<QString>(args) { }
template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator> = true>
inline QStringList(InputIterator first, InputIterator last)
- : QList<QString>(first, last) { }
+ : QVector<QString>(first, last) { }
- QStringList &operator=(const QList<QString> &other)
- { QList<QString>::operator=(other); return *this; }
- QStringList &operator=(QList<QString> &&other) noexcept
- { QList<QString>::operator=(std::move(other)); return *this; }
+ QStringList &operator=(const QVector<QString> &other)
+ { QVector<QString>::operator=(other); return *this; }
+ QStringList &operator=(QVector<QString> &&other) noexcept
+ { QVector<QString>::operator=(std::move(other)); return *this; }
#if QT_STRINGVIEW_LEVEL < 2
inline bool contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
@@ -138,7 +138,7 @@ public:
{ append(str); return *this; }
inline QStringList &operator<<(const QStringList &l)
{ *this += l; return *this; }
- inline QStringList &operator<<(const QList<QString> &l)
+ inline QStringList &operator<<(const QVector<QString> &l)
{ *this += l; return *this; }
inline int indexOf(QStringView str, int from = 0) const;
@@ -159,16 +159,16 @@ public:
inline int lastIndexOf(const QRegularExpression &re, int from = -1) const;
#endif // QT_CONFIG(regularexpression)
- using QList<QString>::indexOf;
- using QList<QString>::lastIndexOf;
+ using QVector<QString>::indexOf;
+ using QVector<QString>::lastIndexOf;
};
Q_DECLARE_TYPEINFO(QStringList, Q_MOVABLE_TYPE);
#ifndef Q_QDOC
-inline QStringList *QListSpecialMethods<QString>::self()
+inline QStringList *QVectorSpecialMethods<QString>::self()
{ return static_cast<QStringList *>(this); }
-inline const QStringList *QListSpecialMethods<QString>::self() const
+inline const QStringList *QVectorSpecialMethods<QString>::self() const
{ return static_cast<const QStringList *>(this); }
namespace QtPrivate {
@@ -213,45 +213,45 @@ namespace QtPrivate {
#endif // QT_CONFIG(regularexpression)
}
-inline void QListSpecialMethods<QString>::sort(Qt::CaseSensitivity cs)
+inline void QVectorSpecialMethods<QString>::sort(Qt::CaseSensitivity cs)
{
QtPrivate::QStringList_sort(self(), cs);
}
-inline int QListSpecialMethods<QString>::removeDuplicates()
+inline int QVectorSpecialMethods<QString>::removeDuplicates()
{
return QtPrivate::QStringList_removeDuplicates(self());
}
#if QT_STRINGVIEW_LEVEL < 2
-inline QString QListSpecialMethods<QString>::join(const QString &sep) const
+inline QString QVectorSpecialMethods<QString>::join(const QString &sep) const
{
return QtPrivate::QStringList_join(self(), sep.constData(), sep.length());
}
#endif
-inline QString QListSpecialMethods<QString>::join(QStringView sep) const
+inline QString QVectorSpecialMethods<QString>::join(QStringView sep) const
{
return QtPrivate::QStringList_join(self(), sep);
}
-QString QListSpecialMethods<QString>::join(QLatin1String sep) const
+QString QVectorSpecialMethods<QString>::join(QLatin1String sep) const
{
return QtPrivate::QStringList_join(*self(), sep);
}
-inline QString QListSpecialMethods<QString>::join(QChar sep) const
+inline QString QVectorSpecialMethods<QString>::join(QChar sep) const
{
return QtPrivate::QStringList_join(self(), &sep, 1);
}
-inline QStringList QListSpecialMethods<QString>::filter(QStringView str, Qt::CaseSensitivity cs) const
+inline QStringList QVectorSpecialMethods<QString>::filter(QStringView str, Qt::CaseSensitivity cs) const
{
return QtPrivate::QStringList_filter(self(), str, cs);
}
#if QT_STRINGVIEW_LEVEL < 2
-inline QStringList QListSpecialMethods<QString>::filter(const QString &str, Qt::CaseSensitivity cs) const
+inline QStringList QVectorSpecialMethods<QString>::filter(const QString &str, Qt::CaseSensitivity cs) const
{
return QtPrivate::QStringList_filter(self(), str, cs);
}
@@ -274,33 +274,33 @@ inline bool QStringList::contains(QStringView str, Qt::CaseSensitivity cs) const
return QtPrivate::QStringList_contains(this, str, cs);
}
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(QStringView before, QStringView after, Qt::CaseSensitivity cs)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(QStringView before, QStringView after, Qt::CaseSensitivity cs)
{
QtPrivate::QStringList_replaceInStrings(self(), before, after, cs);
return *self();
}
#if QT_STRINGVIEW_LEVEL < 2
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(const QString &before, const QString &after, Qt::CaseSensitivity cs)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(const QString &before, const QString &after, Qt::CaseSensitivity cs)
{
QtPrivate::QStringList_replaceInStrings(self(), before, after, cs);
return *self();
}
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(QStringView before, const QString &after, Qt::CaseSensitivity cs)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(QStringView before, const QString &after, Qt::CaseSensitivity cs)
{
QtPrivate::QStringList_replaceInStrings(self(), before, qToStringViewIgnoringNull(after), cs);
return *self();
}
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(const QString &before, QStringView after, Qt::CaseSensitivity cs)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(const QString &before, QStringView after, Qt::CaseSensitivity cs)
{
QtPrivate::QStringList_replaceInStrings(self(), QStringView(before), after, cs);
return *self();
}
#endif
-inline QStringList operator+(const QList<QString> &one, const QStringList &other)
+inline QStringList operator+(const QVector<QString> &one, const QStringList &other)
{
QStringList n = one;
n += other;
@@ -328,13 +328,13 @@ inline int QStringList::lastIndexOf(QLatin1String string, int from) const
}
#ifndef QT_NO_REGEXP
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(const QRegExp &rx, const QString &after)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(const QRegExp &rx, const QString &after)
{
QtPrivate::QStringList_replaceInStrings(self(), rx, after);
return *self();
}
-inline QStringList QListSpecialMethods<QString>::filter(const QRegExp &rx) const
+inline QStringList QVectorSpecialMethods<QString>::filter(const QRegExp &rx) const
{
return QtPrivate::QStringList_filter(self(), rx);
}
@@ -361,13 +361,13 @@ inline int QStringList::lastIndexOf(QRegExp &rx, int from) const
#endif
#if QT_CONFIG(regularexpression)
-inline QStringList &QListSpecialMethods<QString>::replaceInStrings(const QRegularExpression &rx, const QString &after)
+inline QStringList &QVectorSpecialMethods<QString>::replaceInStrings(const QRegularExpression &rx, const QString &after)
{
QtPrivate::QStringList_replaceInStrings(self(), rx, after);
return *self();
}
-inline QStringList QListSpecialMethods<QString>::filter(const QRegularExpression &rx) const
+inline QStringList QVectorSpecialMethods<QString>::filter(const QRegularExpression &rx) const
{
return QtPrivate::QStringList_filter(self(), rx);
}
diff --git a/src/corelib/text/qstringliteral.h b/src/corelib/text/qstringliteral.h
index 2a7e607c63..742d38de7d 100644
--- a/src/corelib/text/qstringliteral.h
+++ b/src/corelib/text/qstringliteral.h
@@ -42,6 +42,7 @@
#define QSTRINGLITERAL_H
#include <QtCore/qarraydata.h>
+#include <QtCore/qarraydatapointer.h>
#if 0
#pragma qt_class(QStringLiteral)
@@ -49,8 +50,6 @@
QT_BEGIN_NAMESPACE
-typedef QTypedArrayData<ushort> QStringData;
-
// all our supported compilers support Unicode string literals,
// even if their Q_COMPILER_UNICODE_STRING has been revoked due
// to lacking stdlib support. But QStringLiteral only needs the
@@ -65,44 +64,23 @@ Q_STATIC_ASSERT_X(sizeof(qunicodechar) == 2,
#define QStringLiteral(str) \
([]() noexcept -> QString { \
enum { Size = sizeof(QT_UNICODE_LITERAL(str))/2 - 1 }; \
- static const QStaticStringData<Size> qstring_literal = { \
- Q_STATIC_STRING_DATA_HEADER_INITIALIZER(Size), \
- QT_UNICODE_LITERAL(str) }; \
- QStringDataPtr holder = { qstring_literal.data_ptr() }; \
- const QString qstring_literal_temp(holder); \
- return qstring_literal_temp; \
+ static const QArrayData qstring_literal = { \
+ Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 \
+ }; \
+ QStringPrivate holder = { \
+ static_cast<QTypedArrayData<ushort> *>(const_cast<QArrayData *>(&qstring_literal)), \
+ reinterpret_cast<ushort *>(const_cast<qunicodechar *>(QT_UNICODE_LITERAL(str))), \
+ Size \
+ }; \
+ return QString(holder); \
}()) \
/**/
-#define Q_STATIC_STRING_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset) \
- { Q_REFCOUNT_INITIALIZE_STATIC, size, 0, 0, offset } \
- /**/
-
-#define Q_STATIC_STRING_DATA_HEADER_INITIALIZER(size) \
- Q_STATIC_STRING_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, sizeof(QStringData)) \
- /**/
-
#if QT_DEPRECATED_SINCE(5, 14)
# define QStringViewLiteral(str) QStringView(QT_UNICODE_LITERAL(str), QtPrivate::Deprecated)
#endif
-template <int N>
-struct QStaticStringData
-{
- QArrayData str;
- qunicodechar data[N + 1];
-
- QStringData *data_ptr() const
- {
- Q_ASSERT(str.ref.isStatic());
- return const_cast<QStringData *>(static_cast<const QStringData*>(&str));
- }
-};
-
-struct QStringDataPtr
-{
- QStringData *ptr;
-};
+using QStringPrivate = QArrayDataPointer<ushort>;
QT_END_NAMESPACE
diff --git a/src/corelib/thread/qfutureinterface.cpp b/src/corelib/thread/qfutureinterface.cpp
index f1fd40e7b6..e6380a8732 100644
--- a/src/corelib/thread/qfutureinterface.cpp
+++ b/src/corelib/thread/qfutureinterface.cpp
@@ -424,12 +424,7 @@ void QFutureInterfaceBase::setProgressValueAndText(int progressValue,
}
}
-QMutex *QFutureInterfaceBase::mutex() const
-{
- return &d->m_mutex;
-}
-
-QMutex &QFutureInterfaceBase::mutex(int) const
+QMutex &QFutureInterfaceBase::mutex() const
{
return d->m_mutex;
}
diff --git a/src/corelib/thread/qfutureinterface.h b/src/corelib/thread/qfutureinterface.h
index bcdae24833..43dfd6bac4 100644
--- a/src/corelib/thread/qfutureinterface.h
+++ b/src/corelib/thread/qfutureinterface.h
@@ -119,8 +119,7 @@ public:
void waitForResult(int resultIndex);
void waitForResume();
- QMutex *mutex() const;
- QMutex &mutex(int) const;
+ QMutex &mutex() const;
QtPrivate::ExceptionStore &exceptionStore();
QtPrivate::ResultStoreBase &resultStoreBase();
const QtPrivate::ResultStoreBase &resultStoreBase() const;
@@ -191,7 +190,7 @@ public:
template <typename T>
inline void QFutureInterface<T>::reportResult(const T *result, int index)
{
- std::lock_guard<QMutex> locker(mutex(0));
+ std::lock_guard<QMutex> locker{mutex()};
if (this->queryState(Canceled) || this->queryState(Finished)) {
return;
}
@@ -217,7 +216,7 @@ inline void QFutureInterface<T>::reportResult(const T &result, int index)
template <typename T>
inline void QFutureInterface<T>::reportResults(const QVector<T> &_results, int beginIndex, int count)
{
- std::lock_guard<QMutex> locker(mutex(0));
+ std::lock_guard<QMutex> locker{mutex()};
if (this->queryState(Canceled) || this->queryState(Finished)) {
return;
}
@@ -245,14 +244,14 @@ inline void QFutureInterface<T>::reportFinished(const T *result)
template <typename T>
inline const T &QFutureInterface<T>::resultReference(int index) const
{
- std::lock_guard<QMutex> locker(mutex(0));
+ std::lock_guard<QMutex> locker{mutex()};
return resultStoreBase().resultAt(index).template value<T>();
}
template <typename T>
inline const T *QFutureInterface<T>::resultPointer(int index) const
{
- std::lock_guard<QMutex> locker(mutex(0));
+ std::lock_guard<QMutex> locker{mutex()};
return resultStoreBase().resultAt(index).template pointer<T>();
}
@@ -266,7 +265,7 @@ inline QList<T> QFutureInterface<T>::results()
QFutureInterfaceBase::waitForResult(-1);
QList<T> res;
- std::lock_guard<QMutex> locker(mutex(0));
+ std::lock_guard<QMutex> locker{mutex()};
QtPrivate::ResultIteratorBase it = resultStoreBase().begin();
while (it != resultStoreBase().end()) {
diff --git a/src/corelib/thread/qthread.cpp b/src/corelib/thread/qthread.cpp
index d3bb372b00..1437768f1c 100644
--- a/src/corelib/thread/qthread.cpp
+++ b/src/corelib/thread/qthread.cpp
@@ -849,7 +849,7 @@ bool QThread::event(QEvent* event)
return QObject::event(event);
}
-Qt::HANDLE QThread::currentThreadId() noexcept
+Qt::HANDLE QThread::currentThreadIdImpl() noexcept
{
return Qt::HANDLE(currentThread());
}
diff --git a/src/corelib/thread/qthread.h b/src/corelib/thread/qthread.h
index 2072e22340..635dd94522 100644
--- a/src/corelib/thread/qthread.h
+++ b/src/corelib/thread/qthread.h
@@ -161,6 +161,7 @@ private:
#if QT_CONFIG(cxx11_future)
static QThread *createThreadImpl(std::future<void> &&future);
#endif
+ static Qt::HANDLE currentThreadIdImpl() noexcept Q_DECL_PURE_FUNCTION;
friend class QCoreApplication;
friend class QThreadData;
@@ -236,6 +237,38 @@ QThread *QThread::create(Function &&f)
#endif // QT_CONFIG(cxx11_future)
+/*
+ On architectures and platforms we know, interpret the thread control
+ block (TCB) as a unique identifier for a thread within a process. Otherwise,
+ fall back to a slower but safe implementation.
+
+ As per the documentation of currentThreadId, we return an opaque handle
+ as a thread identifier, and application code is not supposed to use that
+ value for anything. In Qt we use the handle to check if threads are identical,
+ for which the TCB is sufficient.
+
+ So we use the fastest possible way, rathern than spend time on returning
+ some pseudo-interoperable value.
+*/
+inline Qt::HANDLE QThread::currentThreadId() noexcept
+{
+ Qt::HANDLE tid; // typedef to void*
+ Q_STATIC_ASSERT(sizeof(tid) == sizeof(void*));
+ // See https://akkadia.org/drepper/tls.pdf for x86 ABI
+#if defined(Q_PROCESSOR_X86_32) && defined(Q_OS_LINUX) // x86 32-bit always uses GS
+ __asm__("movl %%gs:0, %0" : "=r" (tid) : : );
+#elif defined(Q_PROCESSOR_X86_64) && defined(Q_OS_DARWIN64)
+ // 64bit macOS uses GS, see https://github.com/apple/darwin-xnu/blob/master/libsyscall/os/tsd.h
+ __asm__("movq %%gs:0, %0" : "=r" (tid) : : );
+#elif defined(Q_PROCESSOR_X86_64) && (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD))
+ // x86_64 Linux, BSD uses FS
+ __asm__("movq %%fs:0, %0" : "=r" (tid) : : );
+#else
+ tid = currentThreadIdImpl();
+#endif
+ return tid;
+}
+
QT_END_NAMESPACE
#endif // QTHREAD_H
diff --git a/src/corelib/thread/qthread_unix.cpp b/src/corelib/thread/qthread_unix.cpp
index 1da68b3130..727d72a334 100644
--- a/src/corelib/thread/qthread_unix.cpp
+++ b/src/corelib/thread/qthread_unix.cpp
@@ -415,16 +415,36 @@ void QThreadPrivate::finish(void *arg)
}
-
-
/**************************************************************************
** QThread
*************************************************************************/
-Qt::HANDLE QThread::currentThreadId() noexcept
+/*
+ Since each thread is guaranteed to have its own copy of
+ currenThreadData, the address is guaranteed to be unique for each
+ running thread (but likely to be reused for newly started threads).
+
+ CI tests fails on ARM architectures if we try to use the assembler,
+ or the address of the thread_local (even with a recent gcc version), so
+ stick to the pthread version there. The assembler would be
+
+ // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0344k/Babeihid.html
+ asm volatile ("mrc p15, 0, %0, c13, c0, 3" : "=r" (tid));
+
+ and
+
+ // see glibc/sysdeps/aarch64/nptl/tls.h
+ asm volatile ("mrs %0, tpidr_el0" : "=r" (tid));
+
+ for 32 and 64bit versions, respectively.
+*/
+Qt::HANDLE QThread::currentThreadIdImpl() noexcept
{
- // requires a C cast here otherwise we run into trouble on AIX
+#if defined(Q_PROCESSOR_ARM)
return to_HANDLE(pthread_self());
+#else
+ return &currentThreadData;
+#endif
}
#if defined(QT_LINUXBASE) && !defined(_SC_NPROCESSORS_ONLN)
diff --git a/src/corelib/thread/qthread_win.cpp b/src/corelib/thread/qthread_win.cpp
index 3df7080caf..44cb5653bf 100644
--- a/src/corelib/thread/qthread_win.cpp
+++ b/src/corelib/thread/qthread_win.cpp
@@ -449,7 +449,7 @@ void QThreadPrivate::finish(void *arg, bool lockAnyway) noexcept
** QThread
*************************************************************************/
-Qt::HANDLE QThread::currentThreadId() noexcept
+Qt::HANDLE QThread::currentThreadIdImpl() noexcept
{
return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
}
diff --git a/src/corelib/time/qdatetimeparser_p.h b/src/corelib/time/qdatetimeparser_p.h
index ec4e4e4df2..ff8da956f0 100644
--- a/src/corelib/time/qdatetimeparser_p.h
+++ b/src/corelib/time/qdatetimeparser_p.h
@@ -77,7 +77,6 @@ QT_BEGIN_NAMESPACE
class Q_CORE_EXPORT QDateTimeParser
{
- Q_DECLARE_TR_FUNCTIONS(QDateTimeParser)
public:
enum Context {
FromString,
@@ -267,10 +266,11 @@ protected: // for the benefit of QDateTimeEditPrivate
return skipToNextSection(section, current, QStringRef(&sectionText));
}
QString stateName(State s) const;
+ QString getAmPmText(AmPm ap, Case cs) const;
+
virtual QDateTime getMinimum() const;
virtual QDateTime getMaximum() const;
virtual int cursorPosition() const { return -1; }
- virtual QString getAmPmText(AmPm ap, Case cs) const;
virtual QLocale locale() const { return defaultLocale; }
mutable int currentSectionIndex;
diff --git a/src/corelib/tools/qarraydata.cpp b/src/corelib/tools/qarraydata.cpp
index 3879b48cbb..497eae1f7f 100644
--- a/src/corelib/tools/qarraydata.cpp
+++ b/src/corelib/tools/qarraydata.cpp
@@ -153,18 +153,16 @@ QT_WARNING_PUSH
QT_WARNING_DISABLE_GCC("-Wmissing-field-initializers")
const QArrayData QArrayData::shared_null[2] = {
- { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, 0, sizeof(QArrayData) }, // shared null
+ { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 }, // shared null
/* zero initialized terminator */};
-static const QArrayData qt_array[3] = {
- { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, 0, sizeof(QArrayData) }, // shared empty
- { { Q_BASIC_ATOMIC_INITIALIZER(0) }, 0, 0, 0, sizeof(QArrayData) }, // unsharable empty
+static const QArrayData emptyNotNullShared[2] = {
+ { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 }, // shared empty
/* zero initialized terminator */};
QT_WARNING_POP
-static const QArrayData &qt_array_empty = qt_array[0];
-static const QArrayData &qt_array_unsharable_empty = qt_array[1];
+static const QArrayData &qt_array_empty = emptyNotNullShared[0];
static inline size_t calculateBlockSize(size_t &capacity, size_t objectSize, size_t headerSize,
uint options)
@@ -172,7 +170,7 @@ static inline size_t calculateBlockSize(size_t &capacity, size_t objectSize, siz
// Calculate the byte size
// allocSize = objectSize * capacity + headerSize, but checked for overflow
// plus padded to grow in size
- if (options & QArrayData::Grow) {
+ if (options & QArrayData::GrowsForward) {
auto r = qCalculateGrowingBlockSize(capacity, objectSize, headerSize);
capacity = r.elementCount;
return r.size;
@@ -181,91 +179,104 @@ static inline size_t calculateBlockSize(size_t &capacity, size_t objectSize, siz
}
}
+static QArrayData *allocateData(size_t allocSize, uint options)
+{
+ QArrayData *header = static_cast<QArrayData *>(::malloc(allocSize));
+ if (header) {
+ header->ref_.storeRelaxed(1);
+ header->flags = options;
+ header->alloc = 0;
+ }
+ return header;
+}
+
static QArrayData *reallocateData(QArrayData *header, size_t allocSize, uint options)
{
header = static_cast<QArrayData *>(::realloc(header, allocSize));
if (header)
- header->capacityReserved = bool(options & QArrayData::CapacityReserved);
+ header->flags = options;
return header;
}
-QArrayData *QArrayData::allocate(size_t objectSize, size_t alignment,
- size_t capacity, AllocationOptions options) noexcept
+void *QArrayData::allocate(QArrayData **dptr, size_t objectSize, size_t alignment,
+ size_t capacity, ArrayOptions options) noexcept
{
+ Q_ASSERT(dptr);
// Alignment is a power of two
- Q_ASSERT(alignment >= Q_ALIGNOF(QArrayData)
+ Q_ASSERT(alignment >= alignof(QArrayData)
&& !(alignment & (alignment - 1)));
- // Don't allocate empty headers
- if (!(options & RawData) && !capacity) {
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- if (options & Unsharable)
- return const_cast<QArrayData *>(&qt_array_unsharable_empty);
-#endif
- return const_cast<QArrayData *>(&qt_array_empty);
+ if (capacity == 0) {
+ // optimization for empty headers
+ *dptr = const_cast<QArrayData *>(&qt_array_empty);
+ return sharedNullData();
}
size_t headerSize = sizeof(QArrayData);
- // Allocate extra (alignment - Q_ALIGNOF(QArrayData)) padding bytes so we
- // can properly align the data array. This assumes malloc is able to
- // provide appropriate alignment for the header -- as it should!
- // Padding is skipped when allocating a header for RawData.
- if (!(options & RawData))
- headerSize += (alignment - Q_ALIGNOF(QArrayData));
+ if (alignment > alignof(QArrayData)) {
+ // Allocate extra (alignment - Q_ALIGNOF(QArrayData)) padding bytes so we
+ // can properly align the data array. This assumes malloc is able to
+ // provide appropriate alignment for the header -- as it should!
+ headerSize += alignment - alignof(QArrayData);
+ }
if (headerSize > size_t(MaxAllocSize))
return nullptr;
size_t allocSize = calculateBlockSize(capacity, objectSize, headerSize, options);
- QArrayData *header = static_cast<QArrayData *>(::malloc(allocSize));
+ options |= AllocatedDataType | MutableData;
+ options &= ~ImmutableHeader;
+ QArrayData *header = allocateData(allocSize, options);
+ quintptr data = 0;
if (header) {
- quintptr data = (quintptr(header) + sizeof(QArrayData) + alignment - 1)
+ // find where offset should point to so that data() is aligned to alignment bytes
+ data = (quintptr(header) + sizeof(QArrayData) + alignment - 1)
& ~(alignment - 1);
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- header->ref.atomic.storeRelaxed(bool(!(options & Unsharable)));
-#else
- header->ref.atomic.storeRelaxed(1);
-#endif
- header->size = 0;
- header->alloc = capacity;
- header->capacityReserved = bool(options & CapacityReserved);
- header->offset = data - quintptr(header);
+ header->alloc = uint(capacity);
}
+ *dptr = header;
+ return reinterpret_cast<void *>(data);
+}
+
+QArrayData *QArrayData::prepareRawData(ArrayOptions options) Q_DECL_NOTHROW
+{
+ QArrayData *header = allocateData(sizeof(QArrayData), (options & ~DataTypeBits) | RawDataType);
+ if (header)
+ header->alloc = 0;
return header;
}
-QArrayData *QArrayData::reallocateUnaligned(QArrayData *data, size_t objectSize, size_t capacity,
- AllocationOptions options) noexcept
+QPair<QArrayData *, void *>
+QArrayData::reallocateUnaligned(QArrayData *data, void *dataPointer,
+ size_t objectSize, size_t capacity, ArrayOptions options) noexcept
{
Q_ASSERT(data);
Q_ASSERT(data->isMutable());
- Q_ASSERT(!data->ref.isShared());
+ Q_ASSERT(!data->isShared());
size_t headerSize = sizeof(QArrayData);
size_t allocSize = calculateBlockSize(capacity, objectSize, headerSize, options);
- QArrayData *header = static_cast<QArrayData *>(reallocateData(data, allocSize, options));
- if (header)
- header->alloc = capacity;
- return header;
+ qptrdiff offset = reinterpret_cast<char *>(dataPointer) - reinterpret_cast<char *>(data);
+ options |= AllocatedDataType | MutableData;
+ QArrayData *header = reallocateData(data, allocSize, options);
+ if (header) {
+ header->alloc = uint(capacity);
+ dataPointer = reinterpret_cast<char *>(header) + offset;
+ }
+ return qMakePair(static_cast<QArrayData *>(header), dataPointer);
}
void QArrayData::deallocate(QArrayData *data, size_t objectSize,
size_t alignment) noexcept
{
// Alignment is a power of two
- Q_ASSERT(alignment >= Q_ALIGNOF(QArrayData)
+ Q_ASSERT(alignment >= alignof(QArrayData)
&& !(alignment & (alignment - 1)));
Q_UNUSED(objectSize) Q_UNUSED(alignment)
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- if (data == &qt_array_unsharable_empty)
- return;
-#endif
-
- Q_ASSERT_X(data == nullptr || !data->ref.isStatic(), "QArrayData::deallocate",
+ Q_ASSERT_X(data == nullptr || !data->isStatic(), "QArrayData::deallocate",
"Static data cannot be deleted");
::free(data);
}
diff --git a/src/corelib/tools/qarraydata.h b/src/corelib/tools/qarraydata.h
index dcd95924c1..483f6d5edb 100644
--- a/src/corelib/tools/qarraydata.h
+++ b/src/corelib/tools/qarraydata.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
@@ -40,32 +41,64 @@
#ifndef QARRAYDATA_H
#define QARRAYDATA_H
-#include <QtCore/qrefcount.h>
+#include <QtCore/qpair.h>
+#include <QtCore/qatomic.h>
#include <string.h>
QT_BEGIN_NAMESPACE
+template <class T> struct QTypedArrayData;
+
struct Q_CORE_EXPORT QArrayData
{
- QtPrivate::RefCount ref;
- int size;
- uint alloc : 31;
- uint capacityReserved : 1;
+ enum ArrayOption {
+ RawDataType = 0x0001, //!< this class is really a QArrayData
+ AllocatedDataType = 0x0002, //!< this class is really a QArrayAllocatedData
+ DataTypeBits = 0x000f,
+
+ CapacityReserved = 0x0010, //!< the capacity was reserved by the user, try to keep it
+ GrowsForward = 0x0020, //!< allocate with eyes towards growing through append()
+ GrowsBackwards = 0x0040, //!< allocate with eyes towards growing through prepend()
+ MutableData = 0x0080, //!< the data can be changed; doesn't say anything about the header
+ ImmutableHeader = 0x0100, //!< the header is static, it can't be changed
+
+ /// this option is used by the Q_ARRAY_LITERAL and similar macros
+ StaticDataFlags = RawDataType | ImmutableHeader,
+ /// this option is used by the allocate() function
+ DefaultAllocationFlags = MutableData,
+ /// this option is used by the prepareRawData() function
+ DefaultRawFlags = 0
+ };
+ Q_DECLARE_FLAGS(ArrayOptions, ArrayOption)
- qptrdiff offset; // in bytes from beginning of header
+ QBasicAtomicInt ref_;
+ uint flags;
+ uint alloc;
+
+ inline size_t allocatedCapacity()
+ {
+ return alloc;
+ }
+
+ inline size_t constAllocatedCapacity() const
+ {
+ return alloc;
+ }
- void *data()
+ /// Returns true if sharing took place
+ bool ref()
{
- Q_ASSERT(size == 0
- || offset < 0 || size_t(offset) >= sizeof(QArrayData));
- return reinterpret_cast<char *>(this) + offset;
+ if (!isStatic())
+ ref_.ref();
+ return true;
}
- const void *data() const
+ /// Returns false if deallocation is necessary
+ bool deref()
{
- Q_ASSERT(size == 0
- || offset < 0 || size_t(offset) >= sizeof(QArrayData));
- return reinterpret_cast<const char *>(this) + offset;
+ if (isStatic())
+ return true;
+ return ref_.deref();
}
// This refers to array data mutability, not "header data" represented by
@@ -73,57 +106,93 @@ struct Q_CORE_EXPORT QArrayData
// follow COW principles.
bool isMutable() const
{
- return alloc != 0;
+ return flags & MutableData;
}
- enum AllocationOption {
- CapacityReserved = 0x1,
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Unsharable = 0x2,
-#endif
- RawData = 0x4,
- Grow = 0x8,
+ bool isStatic() const
+ {
+ return flags & ImmutableHeader;
+ }
- Default = 0
- };
+ bool isShared() const
+ {
+ return ref_.loadRelaxed() != 1;
+ }
- Q_DECLARE_FLAGS(AllocationOptions, AllocationOption)
+ // Returns true if a detach is necessary before modifying the data
+ // This method is intentionally not const: if you want to know whether
+ // detaching is necessary, you should be in a non-const function already
+ bool needsDetach()
+ {
+ // requires two conditionals
+ return !isMutable() || isShared();
+ }
size_t detachCapacity(size_t newSize) const
{
- if (capacityReserved && newSize < alloc)
- return alloc;
+ if (flags & CapacityReserved && newSize < constAllocatedCapacity())
+ return constAllocatedCapacity();
return newSize;
}
- AllocationOptions detachFlags() const
+ ArrayOptions detachFlags() const
{
- AllocationOptions result;
- if (capacityReserved)
+ ArrayOptions result = DefaultAllocationFlags;
+ if (flags & CapacityReserved)
result |= CapacityReserved;
return result;
}
- AllocationOptions cloneFlags() const
+ ArrayOptions cloneFlags() const
{
- AllocationOptions result;
- if (capacityReserved)
+ ArrayOptions result = DefaultAllocationFlags;
+ if (flags & CapacityReserved)
result |= CapacityReserved;
return result;
}
- Q_REQUIRED_RESULT static QArrayData *allocate(size_t objectSize, size_t alignment,
- size_t capacity, AllocationOptions options = Default) noexcept;
+ Q_REQUIRED_RESULT
+#if defined(Q_CC_GNU)
+ __attribute__((__malloc__))
+#endif
+ static void *allocate(QArrayData **pdata, size_t objectSize, size_t alignment,
+ size_t capacity, ArrayOptions options = DefaultAllocationFlags) noexcept;
Q_REQUIRED_RESULT static QArrayData *reallocateUnaligned(QArrayData *data, size_t objectSize,
- size_t newCapacity, AllocationOptions newOptions = Default) noexcept;
+ size_t newCapacity, ArrayOptions newOptions = DefaultAllocationFlags) noexcept;
+ Q_REQUIRED_RESULT static QPair<QArrayData *, void *> reallocateUnaligned(QArrayData *data, void *dataPointer,
+ size_t objectSize, size_t newCapacity, ArrayOptions newOptions = DefaultAllocationFlags) Q_DECL_NOTHROW;
+ Q_REQUIRED_RESULT static QArrayData *prepareRawData(ArrayOptions options = ArrayOptions(RawDataType))
+ Q_DECL_NOTHROW;
static void deallocate(QArrayData *data, size_t objectSize,
size_t alignment) noexcept;
static const QArrayData shared_null[2];
static QArrayData *sharedNull() noexcept { return const_cast<QArrayData*>(shared_null); }
+ static void *sharedNullData()
+ {
+ QArrayData *const null = const_cast<QArrayData *>(&shared_null[1]);
+ return null;
+ }
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(QArrayData::ArrayOptions)
+
+template <class T, size_t N>
+struct QStaticArrayData
+{
+ // static arrays are of type RawDataType
+ QArrayData header;
+ T data[N];
};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QArrayData::AllocationOptions)
+// Support for returning QArrayDataPointer<T> from functions
+template <class T>
+struct QArrayDataPointerRef
+{
+ QTypedArrayData<T> *ptr;
+ T *data;
+ uint size;
+};
template <class T>
struct QTypedArrayData
@@ -205,51 +274,45 @@ struct QTypedArrayData
typedef const T* const_iterator;
#endif
- T *data() { return static_cast<T *>(QArrayData::data()); }
- const T *data() const { return static_cast<const T *>(QArrayData::data()); }
-
- iterator begin(iterator = iterator()) { return data(); }
- iterator end(iterator = iterator()) { return data() + size; }
- const_iterator begin(const_iterator = const_iterator()) const { return data(); }
- const_iterator end(const_iterator = const_iterator()) const { return data() + size; }
- const_iterator constBegin(const_iterator = const_iterator()) const { return data(); }
- const_iterator constEnd(const_iterator = const_iterator()) const { return data() + size; }
-
class AlignmentDummy { QArrayData header; T data; };
- Q_REQUIRED_RESULT static QTypedArrayData *allocate(size_t capacity,
- AllocationOptions options = Default)
+ Q_REQUIRED_RESULT static QPair<QTypedArrayData *, T *> allocate(size_t capacity,
+ ArrayOptions options = DefaultAllocationFlags)
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
- return static_cast<QTypedArrayData *>(QArrayData::allocate(sizeof(T),
- Q_ALIGNOF(AlignmentDummy), capacity, options));
+ QArrayData *d;
+ void *result = QArrayData::allocate(&d, sizeof(T), alignof(AlignmentDummy), capacity, options);
+#if (defined(Q_CC_GNU) && Q_CC_GNU >= 407) || QT_HAS_BUILTIN(__builtin_assume_aligned)
+ result = __builtin_assume_aligned(result, Q_ALIGNOF(AlignmentDummy));
+#endif
+ return qMakePair(static_cast<QTypedArrayData *>(d), static_cast<T *>(result));
}
- static QTypedArrayData *reallocateUnaligned(QTypedArrayData *data, size_t capacity,
- AllocationOptions options = Default)
+ static QPair<QTypedArrayData *, T *>
+ reallocateUnaligned(QTypedArrayData *data, T *dataPointer, size_t capacity,
+ ArrayOptions options = DefaultAllocationFlags)
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
- return static_cast<QTypedArrayData *>(QArrayData::reallocateUnaligned(data, sizeof(T),
- capacity, options));
+ QPair<QArrayData *, void *> pair =
+ QArrayData::reallocateUnaligned(data, dataPointer, sizeof(T), capacity, options);
+ return qMakePair(static_cast<QTypedArrayData *>(pair.first), static_cast<T *>(pair.second));
}
static void deallocate(QArrayData *data)
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
- QArrayData::deallocate(data, sizeof(T), Q_ALIGNOF(AlignmentDummy));
+ QArrayData::deallocate(data, sizeof(T), alignof(AlignmentDummy));
}
- static QTypedArrayData *fromRawData(const T *data, size_t n,
- AllocationOptions options = Default)
+ static QArrayDataPointerRef<T> fromRawData(const T *data, size_t n,
+ ArrayOptions options = DefaultRawFlags)
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
- QTypedArrayData *result = allocate(0, options | RawData);
- if (result) {
- Q_ASSERT(!result->ref.isShared()); // No shared empty, please!
-
- result->offset = reinterpret_cast<const char *>(data)
- - reinterpret_cast<const char *>(result);
- result->size = int(n);
+ QArrayDataPointerRef<T> result = {
+ static_cast<QTypedArrayData *>(prepareRawData(options)), const_cast<T *>(data), uint(n)
+ };
+ if (result.ptr) {
+ Q_ASSERT(!result.ptr->isShared()); // No shared empty, please!
}
return result;
}
@@ -266,38 +329,13 @@ struct QTypedArrayData
return allocate(/* capacity */ 0);
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- static QTypedArrayData *unsharableEmpty()
+ static T *sharedNullData()
{
Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData));
- return allocate(/* capacity */ 0, Unsharable);
+ return static_cast<T *>(QArrayData::sharedNullData());
}
-#endif
-};
-
-template <class T, size_t N>
-struct QStaticArrayData
-{
- QArrayData header;
- T data[N];
-};
-
-// Support for returning QArrayDataPointer<T> from functions
-template <class T>
-struct QArrayDataPointerRef
-{
- QTypedArrayData<T> *ptr;
};
-#define Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset) \
- { Q_REFCOUNT_INITIALIZE_STATIC, size, 0, 0, offset } \
- /**/
-
-#define Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(type, size) \
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size,\
- ((sizeof(QArrayData) + (Q_ALIGNOF(type) - 1)) & ~(Q_ALIGNOF(type) - 1) )) \
- /**/
-
////////////////////////////////////////////////////////////////////////////////
// Q_ARRAY_LITERAL
@@ -333,15 +371,16 @@ struct QArrayDataPointerRef
Q_ARRAY_LITERAL_CHECK_LITERAL_TYPE(Type); \
\
/* Portable compile-time array size computation */ \
- Q_CONSTEXPR Type data[] = { __VA_ARGS__ }; Q_UNUSED(data); \
+ static Type const data[] = { __VA_ARGS__ }; \
enum { Size = sizeof(data) / sizeof(data[0]) }; \
\
- static const QStaticArrayData<Type, Size> literal = { \
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(Type, Size), { __VA_ARGS__ } }; \
+ static const QArrayData literal = { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 }; \
\
QArrayDataPointerRef<Type> ref = \
{ static_cast<QTypedArrayData<Type> *>( \
- const_cast<QArrayData *>(&literal.header)) }; \
+ const_cast<QArrayData *>(&literal)), \
+ const_cast<Type *>(data), \
+ Size }; \
/**/
namespace QtPrivate {
diff --git a/src/corelib/tools/qarraydataops.h b/src/corelib/tools/qarraydataops.h
index 8e19525f07..0d2be5d51c 100644
--- a/src/corelib/tools/qarraydataops.h
+++ b/src/corelib/tools/qarraydataops.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2016 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
@@ -41,12 +42,15 @@
#define QARRAYDATAOPS_H
#include <QtCore/qarraydata.h>
+#include <QtCore/qcontainertools_impl.h>
#include <new>
#include <string.h>
QT_BEGIN_NAMESPACE
+template <class T> struct QArrayDataPointer;
+
namespace QtPrivate {
QT_WARNING_PUSH
@@ -56,48 +60,67 @@ QT_WARNING_DISABLE_GCC("-Wstringop-overflow")
template <class T>
struct QPodArrayOps
- : QTypedArrayData<T>
+ : public QArrayDataPointer<T>
{
+ typedef typename QArrayDataPointer<T>::parameter_type parameter_type;
+
void appendInitialize(size_t newSize)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(newSize > uint(this->size));
- Q_ASSERT(newSize <= this->alloc);
+ Q_ASSERT(newSize <= this->allocatedCapacity());
::memset(static_cast<void *>(this->end()), 0, (newSize - this->size) * sizeof(T));
this->size = int(newSize);
}
+ template<typename iterator>
+ void copyAppend(iterator b, iterator e, QtPrivate::IfIsForwardIterator<iterator> = true)
+ {
+ Q_ASSERT(this->isMutable() || b == e);
+ Q_ASSERT(!this->isShared() || b == e);
+ Q_ASSERT(std::distance(b, e) >= 0 && size_t(std::distance(b, e)) <= this->allocatedCapacity() - this->size);
+
+ T *iter = this->end();
+ for (; b != e; ++iter, ++b) {
+ new (iter) T(*b);
+ ++this->size;
+ }
+ }
+
void copyAppend(const T *b, const T *e)
{
- Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
- Q_ASSERT(b < e);
- Q_ASSERT(size_t(e - b) <= this->alloc - uint(this->size));
+ Q_ASSERT(this->isMutable() || b == e);
+ Q_ASSERT(!this->isShared() || b == e);
+ Q_ASSERT(b <= e);
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
::memcpy(static_cast<void *>(this->end()), static_cast<const void *>(b),
(e - b) * sizeof(T));
this->size += e - b;
}
- void copyAppend(size_t n, const T &t)
+ void moveAppend(T *b, T *e)
+ { copyAppend(b, e); }
+
+ void copyAppend(size_t n, parameter_type t)
{
- Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
- Q_ASSERT(n <= this->alloc - uint(this->size));
+ Q_ASSERT(this->isMutable() || n == 0);
+ Q_ASSERT(!this->isShared() || n == 0);
+ Q_ASSERT(n <= uint(this->allocatedCapacity() - this->size));
T *iter = this->end();
const T *const end = iter + n;
for (; iter != end; ++iter)
- ::memcpy(iter, &t, sizeof(T));
+ *iter = t;
this->size += int(n);
}
void truncate(size_t newSize)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(newSize < size_t(this->size));
this->size = int(newSize);
@@ -106,7 +129,7 @@ struct QPodArrayOps
void destroyAll() // Call from destructors, ONLY!
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(this->ref.atomic.loadRelaxed() == 0);
+ Q_ASSERT(this->d->ref_.loadRelaxed() == 0);
// As this is to be called only from destructor, it doesn't need to be
// exception safe; size not updated.
@@ -115,11 +138,11 @@ struct QPodArrayOps
void insert(T *where, const T *b, const T *e)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(where >= this->begin() && where < this->end()); // Use copyAppend at end
- Q_ASSERT(b < e);
+ Q_ASSERT(b <= e);
Q_ASSERT(e <= where || b > this->end()); // No overlap
- Q_ASSERT(size_t(e - b) <= this->alloc - uint(this->size));
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
::memmove(static_cast<void *>(where + (e - b)), static_cast<void *>(where),
(static_cast<const T*>(this->end()) - where) * sizeof(T));
@@ -127,43 +150,97 @@ struct QPodArrayOps
this->size += (e - b);
}
+ void insert(T *where, size_t n, parameter_type t)
+ {
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(where >= this->begin() && where < this->end()); // Use copyAppend at end
+ Q_ASSERT(this->allocatedCapacity() - this->size >= n);
+
+ ::memmove(static_cast<void *>(where + n), static_cast<void *>(where),
+ (static_cast<const T*>(this->end()) - where) * sizeof(T));
+ this->size += int(n); // PODs can't throw on copy
+ while (n--)
+ *where++ = t;
+ }
+
+ void insert(T *where, T &&t)
+ {
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(where >= this->begin() && where <= this->end());
+ Q_ASSERT(this->allocatedCapacity() - this->size >= 1);
+
+ ::memmove(static_cast<void *>(where + 1), static_cast<void *>(where),
+ (static_cast<const T*>(this->end()) - where) * sizeof(T));
+ this->size += 1;
+ new (where) T(std::move(t));
+ }
+
+
void erase(T *b, T *e)
{
Q_ASSERT(this->isMutable());
Q_ASSERT(b < e);
Q_ASSERT(b >= this->begin() && b < this->end());
- Q_ASSERT(e > this->begin() && e < this->end());
+ Q_ASSERT(e > this->begin() && e <= this->end());
::memmove(static_cast<void *>(b), static_cast<void *>(e),
(static_cast<T *>(this->end()) - e) * sizeof(T));
this->size -= (e - b);
}
+
+ void assign(T *b, T *e, parameter_type t)
+ {
+ Q_ASSERT(b <= e);
+ Q_ASSERT(b >= this->begin() && e <= this->end());
+
+ while (b != e)
+ ::memcpy(static_cast<void *>(b++), static_cast<const void *>(&t), sizeof(T));
+ }
+
+ bool compare(const T *begin1, const T *begin2, size_t n) const
+ {
+ // only use memcmp for fundamental types or pointers.
+ // Other types could have padding in the data structure or custom comparison
+ // operators that would break the comparison using memcmp
+ if (QArrayDataPointer<T>::pass_parameter_by_value)
+ return ::memcmp(begin1, begin2, n * sizeof(T)) == 0;
+ const T *end1 = begin1 + n;
+ while (begin1 != end1) {
+ if (*begin1 == *begin2)
+ ++begin1, ++begin2;
+ else
+ return false;
+ }
+ return true;
+ }
};
QT_WARNING_POP
template <class T>
struct QGenericArrayOps
- : QTypedArrayData<T>
+ : public QArrayDataPointer<T>
{
+ typedef typename QArrayDataPointer<T>::parameter_type parameter_type;
+
void appendInitialize(size_t newSize)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(newSize > uint(this->size));
- Q_ASSERT(newSize <= this->alloc);
+ Q_ASSERT(newSize <= this->allocatedCapacity());
- T *const begin = this->begin();
+ T *const b = this->begin();
do {
- new (begin + this->size) T;
+ new (b + this->size) T;
} while (uint(++this->size) != newSize);
}
- void copyAppend(const T *b, const T *e)
+ template<typename iterator>
+ void copyAppend(iterator b, iterator e, QtPrivate::IfIsForwardIterator<iterator> = true)
{
- Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
- Q_ASSERT(b < e);
- Q_ASSERT(size_t(e - b) <= this->alloc - uint(this->size));
+ Q_ASSERT(this->isMutable() || b == e);
+ Q_ASSERT(!this->isShared() || b == e);
+ Q_ASSERT(std::distance(b, e) >= 0 && size_t(std::distance(b, e)) <= this->allocatedCapacity() - this->size);
T *iter = this->end();
for (; b != e; ++iter, ++b) {
@@ -172,11 +249,37 @@ struct QGenericArrayOps
}
}
- void copyAppend(size_t n, const T &t)
+ void copyAppend(const T *b, const T *e)
{
- Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
- Q_ASSERT(n <= this->alloc - uint(this->size));
+ Q_ASSERT(this->isMutable() || b == e);
+ Q_ASSERT(!this->isShared() || b == e);
+ Q_ASSERT(std::distance(b, e) >= 0 && size_t(std::distance(b, e)) <= this->allocatedCapacity() - this->size);
+
+ T *iter = this->end();
+ this->size += e - b;
+ for (; b != e; ++iter, ++b)
+ new (iter) T(*b);
+ }
+
+ void moveAppend(T *b, T *e)
+ {
+ Q_ASSERT(this->isMutable() || b == e);
+ Q_ASSERT(!this->isShared() || b == e);
+ Q_ASSERT(b <= e);
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
+
+ T *iter = this->end();
+ for (; b != e; ++iter, ++b) {
+ new (iter) T(std::move(*b));
+ ++this->size;
+ }
+ }
+
+ void copyAppend(size_t n, parameter_type t)
+ {
+ Q_ASSERT(this->isMutable() || n == 0);
+ Q_ASSERT(!this->isShared() || n == 0);
+ Q_ASSERT(n <= size_t(this->allocatedCapacity() - this->size));
T *iter = this->end();
const T *const end = iter + n;
@@ -189,7 +292,7 @@ struct QGenericArrayOps
void truncate(size_t newSize)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(newSize < size_t(this->size));
const T *const b = this->begin();
@@ -204,7 +307,7 @@ struct QGenericArrayOps
// As this is to be called only from destructor, it doesn't need to be
// exception safe; size not updated.
- Q_ASSERT(this->ref.atomic.loadRelaxed() == 0);
+ Q_ASSERT(this->d->ref_.loadRelaxed() == 0);
const T *const b = this->begin();
const T *i = this->end();
@@ -216,11 +319,11 @@ struct QGenericArrayOps
void insert(T *where, const T *b, const T *e)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(where >= this->begin() && where < this->end()); // Use copyAppend at end
- Q_ASSERT(b < e);
+ Q_ASSERT(b <= e);
Q_ASSERT(e <= where || b > this->end()); // No overlap
- Q_ASSERT(size_t(e - b) <= this->alloc - uint(this->size));
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
// Array may be truncated at where in case of exceptions
@@ -279,25 +382,139 @@ struct QGenericArrayOps
}
}
+ void insert(T *where, size_t n, parameter_type t)
+ {
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(where >= this->begin() && where <= this->end());
+ Q_ASSERT(this->allocatedCapacity() - this->size >= n);
+
+ // Array may be truncated at where in case of exceptions
+ T *const end = this->end();
+ const T *readIter = end;
+ T *writeIter = end + n;
+
+ const T *const step1End = where + qMax<size_t>(n, end - where);
+
+ struct Destructor
+ {
+ Destructor(T *&it)
+ : iter(&it)
+ , end(it)
+ {
+ }
+
+ void commit()
+ {
+ iter = &end;
+ }
+
+ ~Destructor()
+ {
+ for (; *iter != end; --*iter)
+ (*iter)->~T();
+ }
+
+ T **iter;
+ T *end;
+ } destroyer(writeIter);
+
+ // Construct new elements in array
+ do {
+ --readIter, --writeIter;
+ new (writeIter) T(*readIter);
+ } while (writeIter != step1End);
+
+ while (writeIter != end) {
+ --n, --writeIter;
+ new (writeIter) T(t);
+ }
+
+ destroyer.commit();
+ this->size += destroyer.end - end;
+
+ // Copy assign over existing elements
+ while (readIter != where) {
+ --readIter, --writeIter;
+ *writeIter = *readIter;
+ }
+
+ while (writeIter != where) {
+ --n, --writeIter;
+ *writeIter = t;
+ }
+ }
+
+ void insert(T *where, T &&t)
+ {
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(where >= this->begin() && where <= this->end());
+ Q_ASSERT(this->allocatedCapacity() - this->size >= 1);
+
+ // Array may be truncated at where in case of exceptions
+ T *const end = this->end();
+
+ if (where != end) {
+ // Move elements in array
+ T *readIter = end - 1;
+ T *writeIter = end;
+ new (writeIter) T(std::move(*readIter));
+ while (readIter > where) {
+ --readIter;
+ --writeIter;
+ *writeIter = std::move(*readIter);
+ }
+ *where = std::move(t);
+ } else {
+ new (where) T(std::move(t));
+ }
+
+ ++this->size;
+ }
+
void erase(T *b, T *e)
{
Q_ASSERT(this->isMutable());
Q_ASSERT(b < e);
Q_ASSERT(b >= this->begin() && b < this->end());
- Q_ASSERT(e > this->begin() && e < this->end());
+ Q_ASSERT(e > this->begin() && e <= this->end());
const T *const end = this->end();
- do {
+ // move (by assignment) the elements from e to end
+ // onto b to the new end
+ while (e != end) {
*b = *e;
++b, ++e;
- } while (e != end);
+ }
+ // destroy the final elements at the end
+ // here, b points to the new end and e to the actual end
do {
(--e)->~T();
--this->size;
} while (e != b);
}
+
+ void assign(T *b, T *e, parameter_type t)
+ {
+ Q_ASSERT(b <= e);
+ Q_ASSERT(b >= this->begin() && e <= this->end());
+
+ while (b != e)
+ *b++ = t;
+ }
+
+ bool compare(const T *begin1, const T *begin2, size_t n) const
+ {
+ const T *end1 = begin1 + n;
+ while (begin1 != end1) {
+ if (*begin1 == *begin2)
+ ++begin1, ++begin2;
+ else
+ return false;
+ }
+ return true;
+ }
};
template <class T>
@@ -308,15 +525,16 @@ struct QMovableArrayOps
// using QGenericArrayOps<T>::copyAppend;
// using QGenericArrayOps<T>::truncate;
// using QGenericArrayOps<T>::destroyAll;
+ typedef typename QGenericArrayOps<T>::parameter_type parameter_type;
void insert(T *where, const T *b, const T *e)
{
Q_ASSERT(this->isMutable());
- Q_ASSERT(!this->ref.isShared());
+ Q_ASSERT(!this->isShared());
Q_ASSERT(where >= this->begin() && where < this->end()); // Use copyAppend at end
- Q_ASSERT(b < e);
+ Q_ASSERT(b <= e);
Q_ASSERT(e <= where || b > this->end()); // No overlap
- Q_ASSERT(size_t(e - b) <= this->alloc - uint(this->size));
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
// Provides strong exception safety guarantee,
// provided T::~T() nothrow
@@ -376,12 +594,79 @@ struct QMovableArrayOps
this->size += (e - b);
}
+ void insert(T *where, size_t n, parameter_type t)
+ {
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(where >= this->begin() && where <= this->end());
+ Q_ASSERT(this->allocatedCapacity() - this->size >= n);
+
+ // Provides strong exception safety guarantee,
+ // provided T::~T() nothrow
+
+ struct ReversibleDisplace
+ {
+ ReversibleDisplace(T *start, T *finish, size_t diff)
+ : begin(start)
+ , end(finish)
+ , displace(diff)
+ {
+ ::memmove(static_cast<void *>(begin + displace), static_cast<void *>(begin),
+ (end - begin) * sizeof(T));
+ }
+
+ void commit() { displace = 0; }
+
+ ~ReversibleDisplace()
+ {
+ if (displace)
+ ::memmove(static_cast<void *>(begin), static_cast<void *>(begin + displace),
+ (end - begin) * sizeof(T));
+ }
+
+ T *const begin;
+ T *const end;
+ size_t displace;
+
+ } displace(where, this->end(), n);
+
+ struct CopyConstructor
+ {
+ CopyConstructor(T *w) : where(w) {}
+
+ void copy(size_t count, parameter_type proto)
+ {
+ n = 0;
+ while (count--) {
+ new (where + n) T(proto);
+ ++n;
+ }
+ n = 0;
+ }
+
+ ~CopyConstructor()
+ {
+ while (n)
+ where[--n].~T();
+ }
+
+ T *const where;
+ size_t n;
+ } copier(where);
+
+ copier.copy(n, t);
+ displace.commit();
+ this->size += int(n);
+ }
+
+ // use moving insert
+ using QGenericArrayOps<T>::insert;
+
void erase(T *b, T *e)
{
Q_ASSERT(this->isMutable());
Q_ASSERT(b < e);
Q_ASSERT(b >= this->begin() && b < this->end());
- Q_ASSERT(e > this->begin() && e < this->end());
+ Q_ASSERT(e > this->begin() && e <= this->end());
struct Mover
{
@@ -405,11 +690,51 @@ struct QMovableArrayOps
int &size;
} mover(e, this->end(), this->size);
+ // destroy the elements we're erasing
do {
// Exceptions or not, dtor called once per instance
(--e)->~T();
} while (e != b);
}
+
+ void moveAppend(T *b, T *e)
+ {
+ Q_ASSERT(this->isMutable());
+ Q_ASSERT(!this->isShared());
+ Q_ASSERT(b <= e);
+ Q_ASSERT(e <= this->begin() || b > this->end()); // No overlap
+ Q_ASSERT(size_t(e - b) <= this->allocatedCapacity() - this->size);
+
+ // Provides strong exception safety guarantee,
+ // provided T::~T() nothrow
+
+ struct CopyConstructor
+ {
+ CopyConstructor(T *w) : where(w) {}
+
+ void copy(T *src, const T *const srcEnd)
+ {
+ n = 0;
+ for (; src != srcEnd; ++src) {
+ new (where + n) T(std::move(*src));
+ ++n;
+ }
+ n = 0;
+ }
+
+ ~CopyConstructor()
+ {
+ while (n)
+ where[--n].~T();
+ }
+
+ T *const where;
+ size_t n;
+ } copier(this->end());
+
+ copier.copy(b, e);
+ this->size += (e - b);
+ }
};
template <class T, class = void>
diff --git a/src/corelib/tools/qarraydatapointer.h b/src/corelib/tools/qarraydatapointer.h
index af5173c9ad..a17cf4a101 100644
--- a/src/corelib/tools/qarraydatapointer.h
+++ b/src/corelib/tools/qarraydatapointer.h
@@ -41,6 +41,7 @@
#define QARRAYDATAPOINTER_H
#include <QtCore/qarraydataops.h>
+#include <QtCore/qcontainertools_impl.h>
QT_BEGIN_NAMESPACE
@@ -52,30 +53,40 @@ private:
typedef QArrayDataOps<T> DataOps;
public:
+ typedef typename Data::iterator iterator;
+ typedef typename Data::const_iterator const_iterator;
+ enum { pass_parameter_by_value = std::is_fundamental<T>::value || std::is_pointer<T>::value };
+
+ typedef typename std::conditional<pass_parameter_by_value, T, const T &>::type parameter_type;
+
QArrayDataPointer() noexcept
- : d(Data::sharedNull())
+ : d(Data::sharedNull()), ptr(Data::sharedNullData()), size(0)
{
}
- QArrayDataPointer(const QArrayDataPointer &other)
- : d(other.d->ref.ref()
- ? other.d
- : other.clone(other.d->cloneFlags()))
+ QArrayDataPointer(const QArrayDataPointer &other) noexcept
+ : d(other.d), ptr(other.ptr), size(other.size)
{
+ other.d->ref();
}
- explicit QArrayDataPointer(QTypedArrayData<T> *ptr)
- : d(ptr)
+ QArrayDataPointer(Data *header, T *adata, size_t n = 0) noexcept
+ : d(header), ptr(adata), size(int(n))
{
- Q_CHECK_PTR(ptr);
}
- QArrayDataPointer(QArrayDataPointerRef<T> ref)
- : d(ref.ptr)
+ explicit QArrayDataPointer(QPair<QTypedArrayData<T> *, T *> adata, size_t n = 0)
+ : d(adata.first), ptr(adata.second), size(int(n))
{
+ Q_CHECK_PTR(d);
}
- QArrayDataPointer &operator=(const QArrayDataPointer &other)
+ QArrayDataPointer(QArrayDataPointerRef<T> dd) noexcept
+ : d(dd.ptr), ptr(dd.data), size(dd.size)
+ {
+ }
+
+ QArrayDataPointer &operator=(const QArrayDataPointer &other) noexcept
{
QArrayDataPointer tmp(other);
this->swap(tmp);
@@ -83,9 +94,11 @@ public:
}
QArrayDataPointer(QArrayDataPointer &&other) noexcept
- : d(other.d)
+ : d(other.d), ptr(other.ptr), size(other.size)
{
other.d = Data::sharedNull();
+ other.ptr = Data::sharedNullData();
+ other.size = 0;
}
QArrayDataPointer &operator=(QArrayDataPointer &&other) noexcept
@@ -95,114 +108,142 @@ public:
return *this;
}
- DataOps &operator*() const
+ DataOps &operator*() noexcept
{
Q_ASSERT(d);
- return *static_cast<DataOps *>(d);
+ return *static_cast<DataOps *>(this);
}
- DataOps *operator->() const
+ DataOps *operator->() noexcept
{
Q_ASSERT(d);
- return static_cast<DataOps *>(d);
+ return static_cast<DataOps *>(this);
}
- ~QArrayDataPointer()
+ const DataOps &operator*() const noexcept
{
- if (!d->ref.deref()) {
- if (d->isMutable())
- (*this)->destroyAll();
- Data::deallocate(d);
- }
+ Q_ASSERT(d);
+ return *static_cast<const DataOps *>(this);
}
- bool isNull() const
+ const DataOps *operator->() const noexcept
{
- return d == Data::sharedNull();
+ Q_ASSERT(d);
+ return static_cast<const DataOps *>(this);
}
- Data *data() const
+ ~QArrayDataPointer()
{
- return d;
+ if (!deref()) {
+ if (isMutable())
+ (*this)->destroyAll();
+ Data::deallocate(d);
+ }
}
- bool needsDetach() const
+ bool isNull() const noexcept
{
- return (!d->isMutable() || d->ref.isShared());
+ return d == Data::sharedNull();
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- void setSharable(bool sharable)
- {
- if (needsDetach()) {
- Data *detached = clone(sharable
- ? d->detachFlags() & ~QArrayData::Unsharable
- : d->detachFlags() | QArrayData::Unsharable);
- QArrayDataPointer old(d);
- d = detached;
- } else {
- d->ref.setSharable(sharable);
- }
- }
+ T *data() noexcept { return ptr; }
+ const T *data() const noexcept { return ptr; }
- bool isSharable() const { return d->isSharable(); }
-#endif
+ iterator begin(iterator = iterator()) noexcept { return data(); }
+ iterator end(iterator = iterator()) noexcept { return data() + size; }
+ const_iterator begin(const_iterator = const_iterator()) const noexcept { return data(); }
+ const_iterator end(const_iterator = const_iterator()) const noexcept { return data() + size; }
+ const_iterator constBegin(const_iterator = const_iterator()) const noexcept { return data(); }
+ const_iterator constEnd(const_iterator = const_iterator()) const noexcept { return data() + size; }
void swap(QArrayDataPointer &other) noexcept
{
qSwap(d, other.d);
+ qSwap(ptr, other.ptr);
+ qSwap(size, other.size);
}
- void clear()
+ void clear() Q_DECL_NOEXCEPT_EXPR(std::is_nothrow_destructible<T>::value)
{
- QArrayDataPointer tmp(d);
- d = Data::sharedNull();
+ QArrayDataPointer tmp;
+ swap(tmp);
}
bool detach()
{
- if (needsDetach()) {
- Data *copy = clone(d->detachFlags());
- QArrayDataPointer old(d);
- d = copy;
+ if (d->needsDetach()) {
+ QPair<Data *, T *> copy = clone(d->detachFlags());
+ QArrayDataPointer old(d, ptr, size);
+ d = copy.first;
+ ptr = copy.second;
return true;
}
return false;
}
-private:
- Q_REQUIRED_RESULT Data *clone(QArrayData::AllocationOptions options) const
+ // forwards from QArrayData
+ size_t allocatedCapacity() noexcept { return d->allocatedCapacity(); }
+ size_t constAllocatedCapacity() const noexcept { return d->constAllocatedCapacity(); }
+ int refCounterValue() const noexcept { return d->refCounterValue(); }
+ bool ref() noexcept { return d->ref(); }
+ bool deref() noexcept { return d->deref(); }
+ bool isMutable() const noexcept { return d->isMutable(); }
+ bool isStatic() const noexcept { return d->isStatic(); }
+ bool isShared() const noexcept { return d->isShared(); }
+ bool isSharedWith(const QArrayDataPointer &other) const noexcept { return d && d == other.d; }
+ bool needsDetach() const noexcept { return d->needsDetach(); }
+ size_t detachCapacity(size_t newSize) const noexcept { return d->detachCapacity(newSize); }
+ typename Data::ArrayOptions &flags() noexcept { return reinterpret_cast<typename Data::ArrayOptions &>(d->flags); }
+ typename Data::ArrayOptions flags() const noexcept { return typename Data::ArrayOption(d->flags); }
+ typename Data::ArrayOptions detachFlags() const noexcept { return d->detachFlags(); }
+ typename Data::ArrayOptions cloneFlags() const noexcept { return d->cloneFlags(); }
+
+ void reallocate(uint alloc, typename Data::ArrayOptions options)
{
- Data *x = Data::allocate(d->detachCapacity(d->size), options);
- Q_CHECK_PTR(x);
- QArrayDataPointer copy(x);
+ auto pair = Data::reallocateUnaligned(d, ptr, alloc, options);
+ d = pair.first;
+ ptr = pair.second;
+ }
+ Data *d_ptr() { return d; }
- if (d->size)
- copy->copyAppend(d->begin(), d->end());
+private:
+ Q_REQUIRED_RESULT QPair<Data *, T *> clone(QArrayData::ArrayOptions options) const
+ {
+ QPair<Data *, T *> pair = Data::allocate(d->detachCapacity(size),
+ options);
+ Q_CHECK_PTR(pair.first);
+ QArrayDataPointer copy(pair.first, pair.second, 0);
+ if (size)
+ copy->copyAppend(begin(), end());
- Data *result = copy.d;
+ pair.first = copy.d;
copy.d = Data::sharedNull();
- return result;
+ return pair;
}
+protected:
Data *d;
+ T *ptr;
+
+public:
+ int size;
};
template <class T>
-inline bool operator==(const QArrayDataPointer<T> &lhs, const QArrayDataPointer<T> &rhs)
+inline bool operator==(const QArrayDataPointer<T> &lhs, const QArrayDataPointer<T> &rhs) noexcept
{
- return lhs.data() == rhs.data();
+ return lhs.data() == rhs.data() && lhs.size == rhs.size;
}
template <class T>
-inline bool operator!=(const QArrayDataPointer<T> &lhs, const QArrayDataPointer<T> &rhs)
+inline bool operator!=(const QArrayDataPointer<T> &lhs, const QArrayDataPointer<T> &rhs) noexcept
{
- return lhs.data() != rhs.data();
+ return lhs.data() != rhs.data() || lhs.size != rhs.size;
}
template <class T>
-inline void swap(QArrayDataPointer<T> &p1, QArrayDataPointer<T> &p2)
+inline void qSwap(QArrayDataPointer<T> &p1, QArrayDataPointer<T> &p2) noexcept
{
p1.swap(p2);
}
diff --git a/src/corelib/tools/qbitarray.cpp b/src/corelib/tools/qbitarray.cpp
index f0b81cce66..a1dd537d4d 100644
--- a/src/corelib/tools/qbitarray.cpp
+++ b/src/corelib/tools/qbitarray.cpp
@@ -342,6 +342,38 @@ QBitArray QBitArray::fromBits(const char *data, qsizetype size)
return result;
}
+/*!
+ \since 6.0
+
+ Returns the array of bit converted to an int. The conversion is based on \a endianness.
+ Converts up to the first 32 bits of the array to \c quint32 and returns it,
+ obeying \a endianness. If \a ok is not a null pointer, and the array has more
+ than 32 bits, \a ok is set to false and this function returns zero; otherwise,
+ it's set to true.
+*/
+quint32 QBitArray::toUInt32(QSysInfo::Endian endianness, bool *ok) const noexcept
+{
+ const qsizetype _size = size();
+ if (_size > 32) {
+ if (ok)
+ *ok = false;
+ return 0;
+ }
+
+ if (ok)
+ *ok = true;
+
+ quint32 factor = 1;
+ quint32 total = 0;
+ for (qsizetype i = 0; i < _size; ++i, factor *= 2) {
+ const auto index = endianness == QSysInfo::Endian::LittleEndian ? i : (_size - i - 1);
+ if (testBit(index))
+ total += factor;
+ }
+
+ return total;
+}
+
/*! \fn bool QBitArray::isDetached() const
\internal
diff --git a/src/corelib/tools/qbitarray.h b/src/corelib/tools/qbitarray.h
index 9b0e931aca..ac3a8771d9 100644
--- a/src/corelib/tools/qbitarray.h
+++ b/src/corelib/tools/qbitarray.h
@@ -105,8 +105,10 @@ public:
const char *bits() const { return isEmpty() ? nullptr : d.constData() + 1; }
static QBitArray fromBits(const char *data, qsizetype len);
+ quint32 toUInt32(QSysInfo::Endian endianness, bool *ok = nullptr) const noexcept;
+
public:
- typedef QByteArray::DataPtr DataPtr;
+ typedef QByteArray::DataPointer DataPtr;
inline DataPtr &data_ptr() { return d.data_ptr(); }
};
diff --git a/src/corelib/tools/qcontainerfwd.h b/src/corelib/tools/qcontainerfwd.h
index 532b4c95ce..f6efa99b6a 100644
--- a/src/corelib/tools/qcontainerfwd.h
+++ b/src/corelib/tools/qcontainerfwd.h
@@ -50,7 +50,6 @@ template <class Key, class T> class QHash;
#ifndef QT_NO_LINKED_LIST
template <class T> class QLinkedList;
#endif
-template <class T> class QList;
template <class Key, class T> class QMap;
template <class Key, class T> class QMultiHash;
template <class Key, class T> class QMultiMap;
@@ -60,6 +59,7 @@ template <class T> class QSet;
template <class T> class QStack;
template<class T, int Prealloc = 256> class QVarLengthArray;
template <class T> class QVector;
+template<typename T> using QList = QVector<T>;
QT_END_NAMESPACE
diff --git a/src/corelib/tools/qcontiguouscache.h b/src/corelib/tools/qcontiguouscache.h
index 7b74b4f526..8cae7d1651 100644
--- a/src/corelib/tools/qcontiguouscache.h
+++ b/src/corelib/tools/qcontiguouscache.h
@@ -102,9 +102,6 @@ public:
inline void detach() { if (d->ref.loadRelaxed() != 1) detach_helper(); }
inline bool isDetached() const { return d->ref.loadRelaxed() == 1; }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
-#endif
QContiguousCache<T> &operator=(const QContiguousCache<T> &other);
inline QContiguousCache<T> &operator=(QContiguousCache<T> &&other) noexcept
@@ -166,7 +163,7 @@ private:
}
int alignOfTypedData() const
{
- return qMax<int>(sizeof(void*), Q_ALIGNOF(Data));
+ return qMax<int>(sizeof(void*), alignof(Data));
}
};
diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp
index 84430ae49a..1207ce0659 100644
--- a/src/corelib/tools/qeasingcurve.cpp
+++ b/src/corelib/tools/qeasingcurve.cpp
@@ -1382,11 +1382,6 @@ void QEasingCurve::addTCBSegment(const QPointF &nextPoint, qreal t, qreal c, qre
}
/*!
- \fn QList<QPointF> QEasingCurve::cubicBezierSpline() const
- \obsolete Use toCubicSpline() instead.
- */
-
-/*!
\since 5.0
Returns the cubicBezierSpline that defines a custom easing curve.
diff --git a/src/corelib/tools/qeasingcurve.h b/src/corelib/tools/qeasingcurve.h
index d3a468bb22..81833a758f 100644
--- a/src/corelib/tools/qeasingcurve.h
+++ b/src/corelib/tools/qeasingcurve.h
@@ -46,10 +46,6 @@ QT_REQUIRE_CONFIG(easingcurve);
#include <QtCore/qobjectdefs.h>
#include <QtCore/qvector.h>
-#if QT_DEPRECATED_SINCE(5, 0)
-# include <QtCore/qlist.h>
-# include <QtCore/qpoint.h>
-#endif
QT_BEGIN_NAMESPACE
@@ -105,9 +101,6 @@ public:
void addCubicBezierSegment(const QPointF & c1, const QPointF & c2, const QPointF & endPoint);
void addTCBSegment(const QPointF &nextPoint, qreal t, qreal c, qreal b);
QVector<QPointF> toCubicSpline() const;
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED QList<QPointF> cubicBezierSpline() const { return toCubicSpline().toList(); }
-#endif
Type type() const;
void setType(Type type);
diff --git a/src/corelib/tools/qflatmap_p.h b/src/corelib/tools/qflatmap_p.h
new file mode 100644
index 0000000000..590b0d942f
--- /dev/null
+++ b/src/corelib/tools/qflatmap_p.h
@@ -0,0 +1,982 @@
+/****************************************************************************
+**
+** Copyright (C) 2020 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFLATMAP_P_H
+#define QFLATMAP_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of a number of Qt sources files. This header file may change from
+// version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qvector.h"
+
+#include <algorithm>
+#include <functional>
+#include <initializer_list>
+#include <iterator>
+#include <numeric>
+#include <type_traits>
+#include <utility>
+
+QT_BEGIN_NAMESPACE
+
+/*
+ QFlatMap provides an associative container backed by sorted sequential
+ containers. By default, QVector is used.
+
+ Keys and values are stored in two separate containers. This provides improved
+ cache locality for key iteration and makes keys() and values() fast
+ operations.
+
+ One can customize the underlying container type by passing the KeyContainer
+ and MappedContainer template arguments:
+ QFlatMap<float, int, std::less<float>, std::vector<float>, std::vector<int>>
+*/
+
+namespace Qt {
+
+struct OrderedUniqueRange_t {};
+constexpr OrderedUniqueRange_t OrderedUniqueRange = {};
+
+} // namespace Qt
+
+template <class Key, class T, class Compare>
+class QFlatMapValueCompare : protected Compare
+{
+public:
+ QFlatMapValueCompare() = default;
+ QFlatMapValueCompare(const Compare &key_compare)
+ : Compare(key_compare)
+ {
+ }
+
+ using value_type = std::pair<const Key, T>;
+ static constexpr bool is_comparator_noexcept = noexcept(
+ std::declval<Compare>()(std::declval<Key>(), std::declval<Key>()));
+
+ bool operator()(const value_type &lhs, const value_type &rhs) const
+ noexcept(is_comparator_noexcept)
+ {
+ return Compare::operator()(lhs.first, rhs.first);
+ }
+};
+
+template <class Key, class T,
+ class Compare = std::less<Key>,
+ class KeyContainer = QVector<Key>,
+ class MappedContainer = QVector<T>>
+class QFlatMap : private QFlatMapValueCompare<Key, T, Compare>
+{
+ using full_map_t = QFlatMap<Key, T, Compare, KeyContainer, MappedContainer>;
+
+ template <class U>
+ class mock_pointer
+ {
+ U ref;
+ public:
+ mock_pointer(U r)
+ : ref(r)
+ {
+ }
+
+ U *operator->()
+ {
+ return &ref;
+ }
+ };
+
+public:
+ using key_type = Key;
+ using mapped_type = T;
+ using value_compare = QFlatMapValueCompare<Key, T, Compare>;
+ using value_type = typename value_compare::value_type;
+ using key_container_type = KeyContainer;
+ using mapped_container_type = MappedContainer;
+ using size_type = typename key_container_type::size_type;
+ using key_compare = Compare;
+
+ struct containers
+ {
+ key_container_type keys;
+ mapped_container_type values;
+ };
+
+ class iterator
+ {
+ public:
+ using difference_type = ptrdiff_t;
+ using value_type = std::pair<const Key, T>;
+ using reference = std::pair<const Key &, T &>;
+ using pointer = mock_pointer<reference>;
+ using iterator_category = std::random_access_iterator_tag;
+
+ iterator() = default;
+
+ iterator(containers *ac, size_type ai)
+ : c(ac), i(ai)
+ {
+ }
+
+ reference operator*()
+ {
+ return { c->keys[i], c->values[i] };
+ }
+
+ pointer operator->()
+ {
+ return { operator*() };
+ }
+
+ bool operator==(const iterator &o) const
+ {
+ return c == o.c && i == o.i;
+ }
+
+ bool operator!=(const iterator &o) const
+ {
+ return !operator==(o);
+ }
+
+ iterator &operator++()
+ {
+ ++i;
+ return *this;
+ }
+
+ iterator operator++(int)
+ {
+
+ iterator r = *this;
+ i++;
+ return r;
+ }
+
+ iterator &operator--()
+ {
+ --i;
+ return *this;
+ }
+
+ iterator operator--(int)
+ {
+ iterator r = *this;
+ i--;
+ return r;
+ }
+
+ iterator &operator+=(size_type n)
+ {
+ i += n;
+ return *this;
+ }
+
+ friend iterator operator+(size_type n, const iterator a)
+ {
+ iterator ret = a;
+ return ret += n;
+ }
+
+ friend iterator operator+(const iterator a, size_type n)
+ {
+ return n + a;
+ }
+
+ iterator &operator-=(size_type n)
+ {
+ i -= n;
+ return *this;
+ }
+
+ friend iterator operator-(const iterator a, size_type n)
+ {
+ iterator ret = a;
+ return ret -= n;
+ }
+
+ friend difference_type operator-(const iterator b, const iterator a)
+ {
+ return b.i - a.i;
+ }
+
+ reference operator[](size_type n)
+ {
+ size_type k = i + n;
+ return { c->keys[k], c->values[k] };
+ }
+
+ bool operator<(const iterator &other) const
+ {
+ return i < other.i;
+ }
+
+ bool operator>(const iterator &other) const
+ {
+ return i > other.i;
+ }
+
+ bool operator<=(const iterator &other) const
+ {
+ return i <= other.i;
+ }
+
+ bool operator>=(const iterator &other) const
+ {
+ return i >= other.i;
+ }
+
+ const Key &key() const { return c->keys[i]; }
+ T &value() { return c->values[i]; }
+
+ private:
+ containers *c = nullptr;
+ size_type i = 0;
+ friend full_map_t;
+ };
+
+ class const_iterator
+ {
+ public:
+ using difference_type = ptrdiff_t;
+ using value_type = std::pair<const Key, const T>;
+ using reference = std::pair<const Key &, const T &>;
+ using pointer = mock_pointer<reference>;
+ using iterator_category = std::random_access_iterator_tag;
+
+ const_iterator() = default;
+
+ const_iterator(const containers *ac, size_type ai)
+ : c(ac), i(ai)
+ {
+ }
+
+ const_iterator(iterator o)
+ : c(o.c), i(o.i)
+ {
+ }
+
+ reference operator*()
+ {
+ return { c->keys[i], c->values[i] };
+ }
+
+ pointer operator->()
+ {
+ return { operator*() };
+ }
+
+ bool operator==(const const_iterator &o) const
+ {
+ return c == o.c && i == o.i;
+ }
+
+ bool operator!=(const const_iterator &o) const
+ {
+ return !operator==(o);
+ }
+
+ const_iterator &operator++()
+ {
+ ++i;
+ return *this;
+ }
+
+ const_iterator operator++(int)
+ {
+
+ const_iterator r = *this;
+ i++;
+ return r;
+ }
+
+ const_iterator &operator--()
+ {
+ --i;
+ return *this;
+ }
+
+ const_iterator operator--(int)
+ {
+ const_iterator r = *this;
+ i--;
+ return r;
+ }
+
+ const_iterator &operator+=(size_type n)
+ {
+ i += n;
+ return *this;
+ }
+
+ friend const_iterator operator+(size_type n, const const_iterator a)
+ {
+ const_iterator ret = a;
+ return ret += n;
+ }
+
+ friend const_iterator operator+(const const_iterator a, size_type n)
+ {
+ return n + a;
+ }
+
+ const_iterator &operator-=(size_type n)
+ {
+ i -= n;
+ return *this;
+ }
+
+ friend const_iterator operator-(const const_iterator a, size_type n)
+ {
+ const_iterator ret = a;
+ return ret -= n;
+ }
+
+ friend difference_type operator-(const const_iterator b, const const_iterator a)
+ {
+ return b.i - a.i;
+ }
+
+ reference operator[](size_type n)
+ {
+ size_type k = i + n;
+ return { c->keys[k], c->values[k] };
+ }
+
+ bool operator<(const const_iterator &other) const
+ {
+ return i < other.i;
+ }
+
+ bool operator>(const const_iterator &other) const
+ {
+ return i > other.i;
+ }
+
+ bool operator<=(const const_iterator &other) const
+ {
+ return i <= other.i;
+ }
+
+ bool operator>=(const const_iterator &other) const
+ {
+ return i >= other.i;
+ }
+
+ const Key &key() const { return c->keys[i]; }
+ const T &value() { return c->values[i]; }
+
+ private:
+ const containers *c = nullptr;
+ size_type i = 0;
+ friend full_map_t;
+ };
+
+private:
+ template <class, class = void>
+ struct is_marked_transparent_type : std::false_type { };
+
+ template <class X>
+ struct is_marked_transparent_type<X, typename X::is_transparent> : std::true_type { };
+
+ template <class X>
+ using is_marked_transparent = typename std::enable_if<
+ is_marked_transparent_type<X>::value>::type *;
+
+ template <typename It>
+ using is_compatible_iterator = typename std::enable_if<
+ std::is_same<value_type, typename std::iterator_traits<It>::value_type>::value>::type *;
+
+public:
+ QFlatMap() = default;
+
+ explicit QFlatMap(const key_container_type &keys, const mapped_container_type &values)
+ : c{keys, values}
+ {
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(key_container_type &&keys, const mapped_container_type &values)
+ {
+ c.keys = std::move(keys);
+ c.values = values;
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(const key_container_type &keys, mapped_container_type &&values)
+ {
+ c.keys = keys;
+ c.values = std::move(values);
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(key_container_type &&keys, mapped_container_type &&values)
+ {
+ c.keys = std::move(keys);
+ c.values = std::move(values);
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(std::initializer_list<value_type> lst)
+ : QFlatMap(lst.begin(), lst.end())
+ {
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ explicit QFlatMap(InputIt first, InputIt last)
+ {
+ initWithRange(first, last);
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, const key_container_type &keys,
+ const mapped_container_type &values)
+ {
+ c.keys = keys;
+ c.values = values;
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, key_container_type &&keys,
+ const mapped_container_type &values)
+ {
+ c.keys = std::move(keys);
+ c.values = values;
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, const key_container_type &keys,
+ mapped_container_type &&values)
+ {
+ c.keys = keys;
+ c.values = std::move(values);
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, key_container_type &&keys,
+ mapped_container_type &&values)
+ {
+ c.keys = std::move(keys);
+ c.values = std::move(values);
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, std::initializer_list<value_type> lst)
+ : QFlatMap(lst.begin(), lst.end())
+ {
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, InputIt first, InputIt last)
+ {
+ initWithRange(first, last);
+ }
+
+ explicit QFlatMap(const Compare &compare)
+ : value_compare(compare)
+ {
+ }
+
+ explicit QFlatMap(const key_container_type &keys, const mapped_container_type &values,
+ const Compare &compare)
+ : value_compare(compare), c{keys, values}
+ {
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(key_container_type &&keys, const mapped_container_type &values,
+ const Compare &compare)
+ : value_compare(compare), c{std::move(keys), values}
+ {
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(const key_container_type &keys, mapped_container_type &&values,
+ const Compare &compare)
+ : value_compare(compare), c{keys, std::move(values)}
+ {
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(key_container_type &&keys, mapped_container_type &&values,
+ const Compare &compare)
+ : value_compare(compare), c{std::move(keys), std::move(values)}
+ {
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(std::initializer_list<value_type> lst, const Compare &compare)
+ : QFlatMap(lst.begin(), lst.end(), compare)
+ {
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ explicit QFlatMap(InputIt first, InputIt last, const Compare &compare)
+ : value_compare(compare)
+ {
+ initWithRange(first, last);
+ ensureOrderedUnique();
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, const key_container_type &keys,
+ const mapped_container_type &values, const Compare &compare)
+ : value_compare(compare), c{keys, values}
+ {
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, key_container_type &&keys,
+ const mapped_container_type &values, const Compare &compare)
+ : value_compare(compare), c{std::move(keys), values}
+ {
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, const key_container_type &keys,
+ mapped_container_type &&values, const Compare &compare)
+ : value_compare(compare), c{keys, std::move(values)}
+ {
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, key_container_type &&keys,
+ mapped_container_type &&values, const Compare &compare)
+ : value_compare(compare), c{std::move(keys), std::move(values)}
+ {
+ }
+
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, std::initializer_list<value_type> lst,
+ const Compare &compare)
+ : QFlatMap(Qt::OrderedUniqueRange, lst.begin(), lst.end(), compare)
+ {
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ explicit QFlatMap(Qt::OrderedUniqueRange_t, InputIt first, InputIt last, const Compare &compare)
+ : value_compare(compare)
+ {
+ initWithRange(first, last);
+ }
+
+ size_type count() const noexcept { return c.keys.size(); }
+ size_type size() const noexcept { return c.keys.size(); }
+ size_type capacity() const noexcept { return c.keys.capacity(); }
+ bool isEmpty() const noexcept { return c.keys.empty(); }
+ bool empty() const noexcept { return c.keys.empty(); }
+ containers extract() && { return std::move(c); }
+ const key_container_type &keys() const noexcept { return c.keys; }
+ const mapped_container_type &values() const noexcept { return c.values; }
+
+ void reserve(size_type s)
+ {
+ c.keys.reserve(s);
+ c.values.reserve(s);
+ }
+
+ void clear()
+ {
+ c.keys.clear();
+ c.values.clear();
+ }
+
+ bool remove(const Key &key)
+ {
+ auto it = binary_find(key);
+ if (it != end()) {
+ c.keys.erase(toKeysIterator(it));
+ c.values.erase(toValuesIterator(it));
+ return true;
+ }
+ return false;
+ }
+
+ iterator erase(iterator it)
+ {
+ c.values.erase(toValuesIterator(it));
+ return fromKeysIterator(c.keys.erase(toKeysIterator(it)));
+ }
+
+ T take(const Key &key)
+ {
+ auto it = binary_find(key);
+ if (it != end()) {
+ T result = std::move(it.value());
+ erase(it);
+ return result;
+ }
+ return {};
+ }
+
+ bool contains(const Key &key) const
+ {
+ return binary_find(key) != end();
+ }
+
+ T value(const Key &key, const T &defaultValue) const
+ {
+ auto it = binary_find(key);
+ return it == end() ? defaultValue : it.value();
+ }
+
+ T value(const Key &key) const
+ {
+ auto it = binary_find(key);
+ return it == end() ? T() : it.value();
+ }
+
+ T &operator[](const Key &key)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.keys.insert(toKeysIterator(it), key);
+ return *c.values.insert(toValuesIterator(it), T());
+ }
+ return it.value();
+ }
+
+ T &operator[](Key &&key)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.keys.insert(toKeysIterator(it), key);
+ return *c.values.insert(toValuesIterator(it), T());
+ }
+ return it.value();
+ }
+
+ T operator[](const Key &key) const
+ {
+ return value(key);
+ }
+
+ std::pair<iterator, bool> insert(const Key &key, const T &value)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.values.insert(toValuesIterator(it), value);
+ auto k = c.keys.insert(toKeysIterator(it), key);
+ return { fromKeysIterator(k), true };
+ } else {
+ it.value() = value;
+ return {it, false};
+ }
+ }
+
+ std::pair<iterator, bool> insert(Key &&key, const T &value)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.values.insert(toValuesIterator(it), value);
+ return { c.keys.insert(it, std::move(key)), true };
+ } else {
+ *toValuesIterator(it) = value;
+ return {it, false};
+ }
+ }
+
+ std::pair<iterator, bool> insert(const Key &key, T &&value)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.values.insert(toValuesIterator(it), std::move(value));
+ return { c.keys.insert(it, key), true };
+ } else {
+ *toValuesIterator(it) = std::move(value);
+ return {it, false};
+ }
+ }
+
+ std::pair<iterator, bool> insert(Key &&key, T &&value)
+ {
+ auto it = lower_bound(key);
+ if (it == end() || key_compare::operator()(key, it.key())) {
+ c.values.insert(toValuesIterator(it), std::move(value));
+ return { fromKeysIterator(c.keys.insert(toKeysIterator(it), std::move(key))), true };
+ } else {
+ *toValuesIterator(it) = std::move(value);
+ return {it, false};
+ }
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ void insert(InputIt first, InputIt last)
+ {
+ insertRange(first, last);
+ }
+
+ // ### Merge with the templated version above
+ // once we can use std::disjunction in is_compatible_iterator.
+ void insert(const value_type *first, const value_type *last)
+ {
+ insertRange(first, last);
+ }
+
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ void insert(Qt::OrderedUniqueRange_t, InputIt first, InputIt last)
+ {
+ insertOrderedUniqueRange(first, last);
+ }
+
+ // ### Merge with the templated version above
+ // once we can use std::disjunction in is_compatible_iterator.
+ void insert(Qt::OrderedUniqueRange_t, const value_type *first, const value_type *last)
+ {
+ insertOrderedUniqueRange(first, last);
+ }
+
+ iterator begin() { return { &c, 0 }; }
+ const_iterator begin() const { return { &c, 0 }; }
+ const_iterator cbegin() const { return begin(); }
+ const_iterator constBegin() const { return cbegin(); }
+ iterator end() { return { &c, c.keys.size() }; }
+ const_iterator end() const { return { &c, c.keys.size() }; }
+ const_iterator cend() const { return end(); }
+ const_iterator constEnd() const { return cend(); }
+ std::reverse_iterator<iterator> rbegin() { return std::reverse_iterator<iterator>(end()); }
+ std::reverse_iterator<const_iterator> rbegin() const
+ {
+ return std::reverse_iterator<const_iterator>(end());
+ }
+ std::reverse_iterator<const_iterator> crbegin() const { return rbegin(); }
+ std::reverse_iterator<iterator> rend() {
+ return std::reverse_iterator<iterator>(begin());
+ }
+ std::reverse_iterator<const_iterator> rend() const
+ {
+ return std::reverse_iterator<const_iterator>(begin());
+ }
+ std::reverse_iterator<const_iterator> crend() const { return rend(); }
+
+ iterator lower_bound(const Key &key)
+ {
+ auto cit = const_cast<const full_map_t *>(this)->lower_bound(key);
+ return { &c, cit.i };
+ }
+
+ template <class X, class Y = Compare, is_marked_transparent<Y> = nullptr>
+ iterator lower_bound(const X &key)
+ {
+ auto cit = const_cast<const full_map_t *>(this)->lower_bound(key);
+ return { &c, cit.i };
+ }
+
+ const_iterator lower_bound(const Key &key) const
+ {
+ return fromKeysIterator(std::lower_bound(c.keys.begin(), c.keys.end(), key, key_comp()));
+ }
+
+ template <class X, class Y = Compare, is_marked_transparent<Y> = nullptr>
+ const_iterator lower_bound(const X &key) const
+ {
+ return fromKeysIterator(std::lower_bound(c.keys.begin(), c.keys.end(), key, key_comp()));
+ }
+
+ iterator find(const key_type &k)
+ {
+ return binary_find(k);
+ }
+
+ const_iterator find(const key_type &k) const
+ {
+ return binary_find(k);
+ }
+
+ key_compare key_comp() const noexcept
+ {
+ return static_cast<key_compare>(*this);
+ }
+
+ value_compare value_comp() const noexcept
+ {
+ return static_cast<value_compare>(*this);
+ }
+
+private:
+ template <class InputIt, is_compatible_iterator<InputIt> = nullptr>
+ void initWithRange(InputIt first, InputIt last)
+ {
+ QtPrivate::reserveIfForwardIterator(this, first, last);
+ while (first != last) {
+ c.keys.push_back(first->first);
+ c.values.push_back(first->second);
+ ++first;
+ }
+ }
+
+ iterator fromKeysIterator(typename key_container_type::iterator kit)
+ {
+ return { &c, static_cast<size_type>(std::distance(c.keys.begin(), kit)) };
+ }
+
+ const_iterator fromKeysIterator(typename key_container_type::const_iterator kit) const
+ {
+ return { &c, static_cast<size_type>(std::distance(c.keys.begin(), kit)) };
+ }
+
+ typename key_container_type::iterator toKeysIterator(iterator it)
+ {
+ return c.keys.begin() + it.i;
+ }
+
+ typename mapped_container_type::iterator toValuesIterator(iterator it)
+ {
+ return c.values.begin() + it.i;
+ }
+
+ template <class InputIt>
+ void insertRange(InputIt first, InputIt last)
+ {
+ size_type i = c.keys.size();
+ c.keys.resize(i + std::distance(first, last));
+ c.values.resize(c.keys.size());
+ for (; first != last; ++first, ++i) {
+ c.keys[i] = first->first;
+ c.values[i] = first->second;
+ }
+ ensureOrderedUnique();
+ }
+
+ class IndexedKeyComparator
+ {
+ public:
+ IndexedKeyComparator(const full_map_t *am)
+ : m(am)
+ {
+ }
+
+ bool operator()(size_type i, size_type k) const
+ {
+ return m->key_comp()(m->c.keys[i], m->c.keys[k]);
+ }
+
+ private:
+ const full_map_t *m;
+ };
+
+ template <class InputIt>
+ void insertOrderedUniqueRange(InputIt first, InputIt last)
+ {
+ const size_type s = c.keys.size();
+ c.keys.resize(s + std::distance(first, last));
+ c.values.resize(c.keys.size());
+ for (size_type i = s; first != last; ++first, ++i) {
+ c.keys[i] = first->first;
+ c.values[i] = first->second;
+ }
+
+ std::vector<size_type> p(size_t(c.keys.size()));
+ std::iota(p.begin(), p.end(), 0);
+ std::inplace_merge(p.begin(), p.begin() + s, p.end(), IndexedKeyComparator(this));
+ applyPermutation(p);
+ makeUnique();
+ }
+
+ iterator binary_find(const Key &key)
+ {
+ return { &c, const_cast<const full_map_t *>(this)->binary_find(key).i };
+ }
+
+ const_iterator binary_find(const Key &key) const
+ {
+ auto it = lower_bound(key);
+ if (it != end()) {
+ if (!key_compare::operator()(key, it.key()))
+ return it;
+ it = end();
+ }
+ return it;
+ }
+
+ void ensureOrderedUnique()
+ {
+ std::vector<size_type> p(size_t(c.keys.size()));
+ std::iota(p.begin(), p.end(), 0);
+ std::stable_sort(p.begin(), p.end(), IndexedKeyComparator(this));
+ applyPermutation(p);
+ makeUnique();
+ }
+
+ void applyPermutation(const std::vector<size_type> &p)
+ {
+ const size_type s = c.keys.size();
+ std::vector<bool> done(s);
+ for (size_type i = 0; i < s; ++i) {
+ if (done[i])
+ continue;
+ done[i] = true;
+ size_type j = i;
+ size_type k = p[i];
+ while (i != k) {
+ qSwap(c.keys[j], c.keys[k]);
+ qSwap(c.values[j], c.values[k]);
+ done[k] = true;
+ j = k;
+ k = p[j];
+ }
+ }
+ }
+
+ void makeUnique()
+ {
+ if (c.keys.size() < 2)
+ return;
+ auto k = std::end(c.keys) - 1;
+ auto i = k - 1;
+ for (;;) {
+ if (key_compare::operator()(*i, *k) || key_compare::operator()(*k, *i)) {
+ if (i == std::begin(c.keys))
+ break;
+ --i;
+ --k;
+ } else {
+ c.values.erase(std::begin(c.values) + std::distance(std::begin(c.keys), i));
+ i = c.keys.erase(i);
+ if (i == std::begin(c.keys))
+ break;
+ k = i + 1;
+ }
+ }
+ c.keys.shrink_to_fit();
+ c.values.shrink_to_fit();
+ }
+
+ containers c;
+};
+
+QT_END_NAMESPACE
+
+#endif // QFLATMAP_P_H
diff --git a/src/corelib/tools/qhash.h b/src/corelib/tools/qhash.h
index 0b8a0b283d..c56324eef7 100644
--- a/src/corelib/tools/qhash.h
+++ b/src/corelib/tools/qhash.h
@@ -235,7 +235,7 @@ class QHash
return reinterpret_cast<Node *>(node);
}
- static inline int alignOfNode() { return qMax<int>(sizeof(void*), Q_ALIGNOF(Node)); }
+ static inline int alignOfNode() { return qMax<int>(sizeof(void*), alignof(Node)); }
public:
inline QHash() noexcept : d(const_cast<QHashData *>(&QHashData::shared_null)) { }
@@ -290,9 +290,6 @@ public:
inline void detach() { if (d->ref.isShared()) detach_helper(); }
inline bool isDetached() const { return !d->ref.isShared(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable) { if (!sharable) detach(); if (d != &QHashData::shared_null) d->sharable = sharable; }
-#endif
bool isSharedWith(const QHash &other) const { return d == other.d; }
void clear();
@@ -376,13 +373,8 @@ public:
friend inline QT_DEPRECATED iterator operator+(int j, iterator k) { return k + j; }
#endif
-#ifndef QT_STRICT_ITERATORS
- public:
- inline bool operator==(const const_iterator &o) const
- { return i == o.i; }
- inline bool operator!=(const const_iterator &o) const
- { return i != o.i; }
-#endif
+ inline bool operator==(const const_iterator &o) const { return i == o.i; }
+ inline bool operator!=(const const_iterator &o) const { return i != o.i; }
};
friend class iterator;
@@ -408,11 +400,7 @@ public:
Q_DECL_CONSTEXPR inline const_iterator() : i(nullptr) { }
explicit inline const_iterator(void *node)
: i(reinterpret_cast<QHashData::Node *>(node)) { }
-#ifdef QT_STRICT_ITERATORS
- explicit inline const_iterator(const iterator &o)
-#else
inline const_iterator(const iterator &o)
-#endif
{ i = o.i; }
inline const Key &key() const { return concrete(i)->key; }
@@ -453,13 +441,6 @@ public:
return k + j;
}
#endif
-
- // ### Qt 5: not sure this is necessary anymore
-#ifdef QT_STRICT_ITERATORS
- private:
- inline bool operator==(const iterator &o) const { return operator==(const_iterator(o)); }
- inline bool operator!=(const iterator &o) const { return operator!=(const_iterator(o)); }
-#endif
};
friend class const_iterator;
diff --git a/src/corelib/tools/qlinkedlist.h b/src/corelib/tools/qlinkedlist.h
index 8970d39be0..e3713d2c1c 100644
--- a/src/corelib/tools/qlinkedlist.h
+++ b/src/corelib/tools/qlinkedlist.h
@@ -107,9 +107,6 @@ public:
inline void detach()
{ if (d->ref.isShared()) detach_helper2(this->e); }
inline bool isDetached() const { return !d->ref.isShared(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable) { if (!sharable) detach(); if (d != &QLinkedListData::shared_null) d->sharable = sharable; }
-#endif
inline bool isSharedWith(const QLinkedList<T> &other) const { return d == other.d; }
inline bool isEmpty() const { return d->size == 0; }
diff --git a/src/corelib/tools/qlist.cpp b/src/corelib/tools/qlist.cpp
index 5d5da20752..62201fd5d6 100644
--- a/src/corelib/tools/qlist.cpp
+++ b/src/corelib/tools/qlist.cpp
@@ -63,2029 +63,4 @@ template class Q_CORE_EXPORT QVector<QPointF>;
template class Q_CORE_EXPORT QVector<QPoint>;
#endif
-
-/*
- QList as an array-list combines the easy-of-use of a random
- access interface with fast list operations and the low memory
- management overhead of an array. Accessing elements by index,
- appending, prepending, and removing elements from both the front
- and the back all happen in constant time O(1). Inserting or
- removing elements at random index positions \ai happens in linear
- time, or more precisly in O(min{i,n-i}) <= O(n/2), with n being
- the number of elements in the list.
-*/
-
-const QListData::Data QListData::shared_null = { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, 0, { nullptr } };
-
-/*!
- * Detaches the QListData by allocating new memory for a list which will be bigger
- * than the copied one and is expected to grow further.
- * *idx is the desired insertion point and is clamped to the actual size of the list.
- * num is the number of new elements to insert at the insertion point.
- * Returns the old (shared) data, it is up to the caller to deref() and free().
- * For the new data node_copy needs to be called.
- *
- * \internal
- */
-QListData::Data *QListData::detach_grow(int *idx, int num)
-{
- Data *x = d;
- int l = x->end - x->begin;
- int nl = l + num;
- auto blockInfo = qCalculateGrowingBlockSize(nl, sizeof(void *), DataHeaderSize);
- Data* t = static_cast<Data *>(::malloc(blockInfo.size));
- Q_CHECK_PTR(t);
- t->alloc = int(uint(blockInfo.elementCount));
-
- t->ref.initializeOwned();
- // The space reservation algorithm's optimization is biased towards appending:
- // Something which looks like an append will put the data at the beginning,
- // while something which looks like a prepend will put it in the middle
- // instead of at the end. That's based on the assumption that prepending
- // is uncommon and even an initial prepend will eventually be followed by
- // at least some appends.
- int bg;
- if (*idx < 0) {
- *idx = 0;
- bg = (t->alloc - nl) >> 1;
- } else if (*idx > l) {
- *idx = l;
- bg = 0;
- } else if (*idx < (l >> 1)) {
- bg = (t->alloc - nl) >> 1;
- } else {
- bg = 0;
- }
- t->begin = bg;
- t->end = bg + nl;
- d = t;
-
- return x;
-}
-
-/*!
- * Detaches the QListData by allocating new memory for a list which possibly
- * has a different size than the copied one.
- * Returns the old (shared) data, it is up to the caller to deref() and free()
- * For the new data node_copy needs to be called.
- *
- * \internal
- */
-QListData::Data *QListData::detach(int alloc)
-{
- Data *x = d;
- Data* t = static_cast<Data *>(::malloc(qCalculateBlockSize(alloc, sizeof(void*), DataHeaderSize)));
- Q_CHECK_PTR(t);
-
- t->ref.initializeOwned();
- t->alloc = alloc;
- if (!alloc) {
- t->begin = 0;
- t->end = 0;
- } else {
- t->begin = x->begin;
- t->end = x->end;
- }
- d = t;
-
- return x;
-}
-
-void QListData::realloc(int alloc)
-{
- Q_ASSERT(!d->ref.isShared());
- Data *x = static_cast<Data *>(::realloc(d, qCalculateBlockSize(alloc, sizeof(void *), DataHeaderSize)));
- Q_CHECK_PTR(x);
-
- d = x;
- d->alloc = alloc;
- if (!alloc)
- d->begin = d->end = 0;
-}
-
-void QListData::realloc_grow(int growth)
-{
- Q_ASSERT(!d->ref.isShared());
- auto r = qCalculateGrowingBlockSize(d->alloc + growth, sizeof(void *), DataHeaderSize);
- Data *x = static_cast<Data *>(::realloc(d, r.size));
- Q_CHECK_PTR(x);
-
- d = x;
- d->alloc = int(uint(r.elementCount));
-}
-
-void QListData::dispose(Data *d)
-{
- Q_ASSERT(!d->ref.isShared());
- free(d);
-}
-
-// ensures that enough space is available to append n elements
-void **QListData::append(int n)
-{
- Q_ASSERT(!d->ref.isShared());
- int e = d->end;
- if (e + n > d->alloc) {
- int b = d->begin;
- if (b - n >= 2 * d->alloc / 3) {
- // we have enough space. Just not at the end -> move it.
- e -= b;
- ::memcpy(d->array, d->array + b, e * sizeof(void *));
- d->begin = 0;
- } else {
- realloc_grow(n);
- }
- }
- d->end = e + n;
- return d->array + e;
-}
-
-// ensures that enough space is available to append one element
-void **QListData::append()
-{
- return append(1);
-}
-
-// ensures that enough space is available to append the list
-void **QListData::append(const QListData& l)
-{
- return append(l.d->end - l.d->begin);
-}
-
-void **QListData::prepend()
-{
- Q_ASSERT(!d->ref.isShared());
- if (d->begin == 0) {
- if (d->end >= d->alloc / 3)
- realloc_grow(1);
-
- if (d->end < d->alloc / 3)
- d->begin = d->alloc - 2 * d->end;
- else
- d->begin = d->alloc - d->end;
-
- ::memmove(d->array + d->begin, d->array, d->end * sizeof(void *));
- d->end += d->begin;
- }
- return d->array + --d->begin;
-}
-
-void **QListData::insert(int i)
-{
- Q_ASSERT(!d->ref.isShared());
- if (i <= 0)
- return prepend();
- int size = d->end - d->begin;
- if (i >= size)
- return append();
-
- bool leftward = false;
-
- if (d->begin == 0) {
- if (d->end == d->alloc) {
- // If the array is full, we expand it and move some items rightward
- realloc_grow(1);
- } else {
- // If there is free space at the end of the array, we move some items rightward
- }
- } else {
- if (d->end == d->alloc) {
- // If there is free space at the beginning of the array, we move some items leftward
- leftward = true;
- } else {
- // If there is free space at both ends, we move as few items as possible
- leftward = (i < size - i);
- }
- }
-
- if (leftward) {
- --d->begin;
- ::memmove(d->array + d->begin, d->array + d->begin + 1, i * sizeof(void *));
- } else {
- ::memmove(d->array + d->begin + i + 1, d->array + d->begin + i,
- (size - i) * sizeof(void *));
- ++d->end;
- }
- return d->array + d->begin + i;
-}
-
-void QListData::remove(int i)
-{
- Q_ASSERT(!d->ref.isShared());
- i += d->begin;
- if (i - d->begin < d->end - i) {
- if (int offset = i - d->begin)
- ::memmove(d->array + d->begin + 1, d->array + d->begin, offset * sizeof(void *));
- d->begin++;
- } else {
- if (int offset = d->end - i - 1)
- ::memmove(d->array + i, d->array + i + 1, offset * sizeof(void *));
- d->end--;
- }
-}
-
-void QListData::remove(int i, int n)
-{
- Q_ASSERT(!d->ref.isShared());
- i += d->begin;
- int middle = i + n/2;
- if (middle - d->begin < d->end - middle) {
- ::memmove(d->array + d->begin + n, d->array + d->begin,
- (i - d->begin) * sizeof(void*));
- d->begin += n;
- } else {
- ::memmove(d->array + i, d->array + i + n,
- (d->end - i - n) * sizeof(void*));
- d->end -= n;
- }
-}
-
-void QListData::move(int from, int to)
-{
- Q_ASSERT(!d->ref.isShared());
- if (from == to)
- return;
-
- from += d->begin;
- to += d->begin;
- void *t = d->array[from];
-
- if (from < to) {
- if (d->end == d->alloc || 3 * (to - from) < 2 * (d->end - d->begin)) {
- ::memmove(d->array + from, d->array + from + 1, (to - from) * sizeof(void *));
- } else {
- // optimization
- if (int offset = from - d->begin)
- ::memmove(d->array + d->begin + 1, d->array + d->begin, offset * sizeof(void *));
- if (int offset = d->end - (to + 1))
- ::memmove(d->array + to + 2, d->array + to + 1, offset * sizeof(void *));
- ++d->begin;
- ++d->end;
- ++to;
- }
- } else {
- if (d->begin == 0 || 3 * (from - to) < 2 * (d->end - d->begin)) {
- ::memmove(d->array + to + 1, d->array + to, (from - to) * sizeof(void *));
- } else {
- // optimization
- if (int offset = to - d->begin)
- ::memmove(d->array + d->begin - 1, d->array + d->begin, offset * sizeof(void *));
- if (int offset = d->end - (from + 1))
- ::memmove(d->array + from, d->array + from + 1, offset * sizeof(void *));
- --d->begin;
- --d->end;
- --to;
- }
- }
- d->array[to] = t;
-}
-
-void **QListData::erase(void **xi)
-{
- Q_ASSERT(!d->ref.isShared());
- int i = xi - (d->array + d->begin);
- remove(i);
- return d->array + d->begin + i;
-}
-
-/*! \class QList
- \inmodule QtCore
- \brief The QList class is a template class that provides lists.
-
- \ingroup tools
- \ingroup shared
-
- \reentrant
-
- QList\<T\> is one of Qt's generic \l{container classes}. It
- 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
- APIs and functionality. They are often interchangeable, but there
- are performance consequences. Here is an overview of use cases:
-
- \list
- \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 as 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 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
- by the destructor and by the assignment operator, when one list
- is assigned to another.
-
- Here's an example of a QList that stores integers and
- a QList that stores QDate values:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 0
-
- Qt includes a QStringList class that inherits QList\<QString\>
- and adds a few convenience functions, such as QStringList::join()
- and QStringList::filter(). QString::split() creates QStringLists
- from strings.
-
- QList stores a list of items. The default constructor creates an
- empty list. You can use the initializer-list constructor to create
- a list with elements:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 1a
-
- QList provides these basic functions to add, move, and remove
- items: insert(), replace(), removeAt(), move(), and swap(). In
- addition, it provides the following convenience functions:
- append(), \l{operator<<()}, \l{operator+=()}, prepend(), removeFirst(),
- and removeLast().
-
- \l{operator<<()} allows to conveniently add multiple elements to a list:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 1b
-
- QList uses 0-based indexes, just like C++ arrays. To access the
- item at a particular index position, you can use operator[](). On
- non-const lists, operator[]() returns a reference to the item and
- can be used on the left side of an assignment:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 2
-
- 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
-
- at() can be faster than operator[](), because it never causes a
- \l{deep copy} to occur.
-
- A common requirement is to remove an item from a list and do
- something with it. For this, QList provides takeAt(), takeFirst(),
- and takeLast(). Here's a loop that removes the items from a list
- one at a time and calls \c delete on them:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 4
-
- 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
- starting from a given index position, the latter searches
- backward. Both return the index of a matching item if they find
- it; otherwise, they return -1. For example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 5
-
- If you simply want to check whether a list contains a particular
- value, use contains(). If you want to find out how many times a
- particular value occurs in the list, use count(). If you want to
- replace all occurrences of a particular value with another, use
- replace().
-
- QList's value type must be an \l{assignable data type}. This
- covers most data types that are commonly used, but the compiler
- won't let you, for example, store a QWidget as a value; instead,
- store a QWidget *. A few functions have additional requirements;
- for example, indexOf() and lastIndexOf() expect the value type to
- support \c operator==(). These requirements are documented on a
- per-function basis.
-
- Like the other container classes, QList provides \l{Java-style
- iterators} (QListIterator and QMutableListIterator) and
- \l{STL-style iterators} (QList::const_iterator and
- QList::iterator). In practice, these are rarely used, because you
- can use indexes into the QList. QList is implemented in such a way
- that direct index-based access is just as fast as using iterators.
-
- QList does \e not support inserting, prepending, appending or
- replacing with references to its own values. Doing so will cause
- your application to abort with an error message.
-
- To make QList as efficient as possible, its member functions don't
- validate their input before using it. Except for isEmpty(), member
- functions always assume the list is \e not empty. Member functions
- that take index values as parameters always assume their index
- value parameters are in the valid range. This means QList member
- functions can fail. If you define QT_NO_DEBUG when you compile,
- failures will not be detected. If you \e don't define QT_NO_DEBUG,
- failures will be detected using Q_ASSERT() or Q_ASSERT_X() with an
- appropriate message.
-
- To avoid failures when your list can be empty, call isEmpty()
- before calling other member functions. If you must pass an index
- value that might not be in the valid range, check that it is less
- than the value returned by size() but \e not less than 0.
-
- \section1 More Members
-
- If T is a QByteArray, this class has a couple more members that can be
- used. See the documentation for QByteArrayList for more information.
-
- If T is QString, this class has the following additional members:
- \l{QStringList::filter()}{filter},
- \l{QStringList::join()}{join},
- \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
-*/
-
-/*!
- \fn template <class T> QList<T>::QList(QList<T> &&other)
-
- Move-constructs a QList instance, making it point at the same
- object that \a other was pointing to.
-
- \since 5.2
-*/
-
-/*! \fn template <class T> template<typename InputIterator> QList<T>::QList(InputIterator first, InputIterator last)
- \since 5.14
-
- Constructs a QList with the contents in the iterator range [\a first, \a last).
-
- The value type of \c InputIterator must be convertible to \c T.
-*/
-
-/*!
- \fn template <class T> QList<T> QList<T>::mid(int pos, int length) const
-
- Returns a sub-list which includes elements from this list,
- starting at position \a pos. If \a length is -1 (the default), all
- elements from \a pos are included; otherwise \a length elements (or
- all remaining elements if there are less than \a length elements)
- are included.
-*/
-
-/*! \fn template <class T> QList<T>::QList()
-
- Constructs an empty list.
-*/
-
-/*! \fn template <class T> QList<T>::QList(const QList<T> &other)
-
- Constructs a copy of \a other.
-
- 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=()
-*/
-
-/*! \fn template <class T> QList<T>::QList(std::initializer_list<T> args)
- \since 4.8
-
- Construct a list from the std::initializer_list specified by \a args.
-
- This constructor is only enabled if the compiler supports C++11 initializer
- lists.
-*/
-
-/*! \fn template <class T> QList<T>::~QList()
-
- Destroys the list. References to the values in the list and all
- iterators of this list become invalid.
-*/
-
-/*! \fn template <class T> QList<T> &QList<T>::operator=(const QList<T> &other)
-
- Assigns \a other to this list and returns a reference to this
- list.
-*/
-
-/*!
- \fn template <class T> QList &QList<T>::operator=(QList<T> &&other)
-
- Move-assigns \a other to this QList instance.
-
- \since 5.2
-*/
-
-/*! \fn template <class T> void QList<T>::swap(QList<T> &other)
- \since 4.8
-
- Swaps list \a other with this list. This operation is very
- fast and never fails.
-*/
-
-/*! \fn template <class T> bool QList<T>::operator==(const QList<T> &other) const
-
- Returns \c true if \a other is equal to this list; otherwise returns
- false.
-
- Two lists are considered equal if they contain the same values in
- the same order.
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa operator!=()
-*/
-
-/*! \fn template <class T> bool QList<T>::operator!=(const QList<T> &other) const
-
- Returns \c true if \a other is not equal to this list; otherwise
- returns \c false.
-
- Two lists are considered equal if they contain the same values in
- the same order.
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa operator==()
-*/
-
-/*! \fn template <class T> 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 template <class T> 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 template <class T> 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 template <class T> 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 template <class T> 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 template <class T> int QList<T>::size() const
-
- Returns the number of items in the list.
-
- \sa isEmpty(), count()
-*/
-
-/*! \fn template <class T> void QList<T>::detach()
-
- \internal
-*/
-
-/*! \fn template <class T> void QList<T>::detachShared()
-
- \internal
-
- like detach(), but does nothing if we're shared_null.
- This prevents needless mallocs, and makes QList more exception safe
- in case of cleanup work done in destructors on empty lists.
-*/
-
-/*! \fn template <class T> bool QList<T>::isDetached() const
-
- \internal
-*/
-
-/*! \fn template <class T> void QList<T>::setSharable(bool sharable)
-
- \internal
-*/
-
-/*! \fn template <class T> bool QList<T>::isSharedWith(const QList<T> &other) const
-
- \internal
-*/
-
-/*! \fn template <class T> bool QList<T>::isEmpty() const
-
- Returns \c true if the list contains no items; otherwise returns
- false.
-
- \sa size()
-*/
-
-/*! \fn template <class T> void QList<T>::clear()
-
- Removes all items from the list.
-
- \sa removeAll()
-*/
-
-/*! \fn template <class T> const T &QList<T>::at(int i) const
-
- 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{Algorithmic Complexity}{constant time}).
-
- \sa value(), operator[]()
-*/
-
-/*! \fn template <class T> T &QList<T>::operator[](int i)
-
- Returns the item at index position \a i as a modifiable reference.
- \a i must be a valid index position in the list (i.e., 0 <= \a i <
- size()).
-
- 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{Algorithmic Complexity}{constant time}. If you do not want to modify
- the list you should use QList::at().
-
- \sa at(), value()
-*/
-
-/*! \fn template <class T> const T &QList<T>::operator[](int i) const
-
- \overload
-
- Same as at(). This function runs in \l{Algorithmic Complexity}{constant time}.
-*/
-
-/*! \fn template <class T> void QList<T>::reserve(int alloc)
-
- Reserve space for \a alloc elements.
-
- If \a alloc is smaller than the current size of the list, nothing will happen.
-
- Use this function to avoid repetetive reallocation of QList's internal
- data if you can predict how many elements will be appended.
- Note that the reservation applies only to the internal pointer array.
-
- \since 4.7
-*/
-
-/*! \fn template <class T> void QList<T>::append(const T &value)
-
- Inserts \a value at the end of the list.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 6
-
- This is the same as list.insert(size(), \a value).
-
- If this list is not shared, this operation is typically
- 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()
-*/
-
-/*! \fn template <class T> void QList<T>::append(const QList<T> &value)
-
- \overload
-
- \since 4.5
-
- Appends the items of the \a value list to this list.
-
- \sa operator<<(), operator+=()
-*/
-
-/*! \fn template <class T> void QList<T>::prepend(const T &value)
-
- Inserts \a value at the beginning of the list.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 7
-
- This is the same as list.insert(0, \a value).
-
- If this list is not shared, this operation is typically
- 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()
-*/
-
-/*! \fn template <class T> void QList<T>::insert(int i, const T &value)
-
- Inserts \a value at index position \a i in the list.
-
- If \a i == 0, the value is prepended to the list. If \a i == size(),
- the value is appended to the list.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 8
-
- \sa append(), prepend(), replace(), removeAt()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::insert(iterator before, const T &value)
-
- \overload
-
- Inserts \a value in front of the item pointed to by the
- iterator \a before. Returns an iterator pointing at the inserted
- item. Note that the iterator passed to the function will be
- invalid after the call; the returned iterator should be used
- instead.
-*/
-
-/*! \fn template <class T> void QList<T>::replace(int i, const T &value)
-
- Replaces the item at index position \a i with \a value. \a i must
- be a valid index position in the list (i.e., 0 <= \a i < size()).
-
- \sa operator[](), removeAt()
-*/
-
-/*!
- \fn template <class T> int QList<T>::removeAll(const T &value)
-
- Removes all occurrences of \a value in the list and returns the
- number of entries removed.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 9
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa removeOne(), removeAt(), takeAt(), replace()
-*/
-
-/*!
- \fn template <class T> bool QList<T>::removeOne(const T &value)
- \since 4.4
-
- Removes the first occurrence of \a value in the list and returns
- true on success; otherwise returns \c false.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 10
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa removeAll(), removeAt(), takeAt(), replace()
-*/
-
-/*! \fn template <class T> void QList<T>::removeAt(int i)
-
- Removes the item at index position \a i. \a i must be a valid
- index position in the list (i.e., 0 <= \a i < size()).
-
- \sa takeAt(), removeFirst(), removeLast(), removeOne()
-*/
-
-/*! \fn template <class T> T QList<T>::takeAt(int i)
-
- Removes the item at index position \a i and returns it. \a i must
- be a valid index position in the list (i.e., 0 <= \a i < size()).
-
- If you don't use the return value, removeAt() is more efficient.
-
- \sa removeAt(), takeFirst(), takeLast()
-*/
-
-/*! \fn template <class T> T QList<T>::takeFirst()
-
- Removes the first item in the list and returns it. This is the
- 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 {Algorithmic Complexity}{constant time}.
-
- If you don't use the return value, removeFirst() is more
- efficient.
-
- \sa takeLast(), takeAt(), removeFirst()
-*/
-
-/*! \fn template <class T> T QList<T>::takeLast()
-
- Removes the last item in the list and returns it. This is the
- same as takeAt(size() - 1). 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 {Algorithmic Complexity}{constant time}.
-
- If you don't use the return value, removeLast() is more
- efficient.
-
- \sa takeFirst(), takeAt(), removeLast()
-*/
-
-/*! \fn template <class T> void QList<T>::move(int from, int to)
-
- Moves the item at index position \a from to index position \a to.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 11
-
- This is the same as insert(\a{to}, takeAt(\a{from})).This function
- assumes that both \a from and \a to are at least 0 but less than
- size(). To avoid failure, test that both \a from and \a to are at
- least 0 and less than size().
-
- \sa swap(), insert(), takeAt()
-*/
-
-/*! \fn template <class T> void QList<T>::swap(int i, int j)
-
- \obsolete Use swapItemsAt()
-
- \sa move(), swapItemsAt()
-*/
-
-/*! \fn template <class T> void QList<T>::swapItemsAt(int i, int j)
- \since 5.13
-
- Exchange the item at index position \a i with the item at index
- position \a j. This function assumes that both \a i and \a j are
- at least 0 but less than size(). To avoid failure, test that both
- \a i and \a j are at least 0 and less than size().
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 12
-
- \sa move()
-*/
-
-/*! \fn template <class T> int QList<T>::indexOf(const T &value, int from = 0) const
-
- Returns the index position of the first occurrence of \a value in
- the list, searching forward from index position \a from. Returns
- -1 if no item matched.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 13
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- Note that QList uses 0-based indexes, just like C++ arrays. Negative
- indexes are not supported with the exception of the value mentioned
- above.
-
- \sa lastIndexOf(), contains()
-*/
-
-/*! \fn template <class T> int QList<T>::lastIndexOf(const T &value, int from = -1) const
-
- Returns the index position of the last occurrence of \a value in
- the list, searching backward from index position \a from. If \a
- from is -1 (the default), the search starts at the last item.
- Returns -1 if no item matched.
-
- Example:
- \snippet code/src_corelib_tools_qlistdata.cpp 14
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- Note that QList uses 0-based indexes, just like C++ arrays. Negative
- indexes are not supported with the exception of the value mentioned
- above.
-
- \sa indexOf()
-*/
-
-/*! \fn template <class T> bool QList<T>::contains(const T &value) const
-
- Returns \c true if the list contains an occurrence of \a value;
- otherwise returns \c false.
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa indexOf(), count()
-*/
-
-/*! \fn template <class T> int QList<T>::count(const T &value) const
-
- Returns the number of occurrences of \a value in the list.
-
- This function requires the value type to have an implementation of
- \c operator==().
-
- \sa contains(), indexOf()
-*/
-
-/*! \fn template <class T> bool QList<T>::startsWith(const T &value) const
- \since 4.5
-
- Returns \c true if this list is not empty and its first
- item is equal to \a value; otherwise returns \c false.
-
- \sa isEmpty(), contains()
-*/
-
-/*! \fn template <class T> bool QList<T>::endsWith(const T &value) const
- \since 4.5
-
- Returns \c true if this list is not empty and its last
- item is equal to \a value; otherwise returns \c false.
-
- \sa isEmpty(), contains()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::begin()
-
- Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first item in
- the list.
-
- \sa constBegin(), end()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::begin() const
-
- \overload
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::cbegin() const
- \since 5.0
-
- Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first item
- in the list.
-
- \sa begin(), cend()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::constBegin() const
-
- Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first item
- in the list.
-
- \sa begin(), constEnd()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::end()
-
- Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary item
- after the last item in the list.
-
- \sa begin(), constEnd()
-*/
-
-/*! \fn template <class T> const_iterator QList<T>::end() const
-
- \overload
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::cend() const
- \since 5.0
-
- Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
- item after the last item in the list.
-
- \sa cbegin(), end()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::constEnd() const
-
- Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
- item after the last item in the list.
-
- \sa constBegin(), end()
-*/
-
-/*! \fn template <class T> QList<T>::reverse_iterator QList<T>::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 template <class T> QList<T>::const_reverse_iterator QList<T>::rbegin() const
- \since 5.6
- \overload
-*/
-
-/*! \fn template <class T> QList<T>::const_reverse_iterator QList<T>::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 template <class T> QList<T>::reverse_iterator QList<T>::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 template <class T> QList<T>::const_reverse_iterator QList<T>::rend() const
- \since 5.6
- \overload
-*/
-
-/*! \fn template <class T> QList<T>::const_reverse_iterator QList<T>::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 template <class T> QList<T>::iterator QList<T>::erase(iterator pos)
-
- Removes the item associated with the iterator \a pos from the
- list, and returns an iterator to the next item in the list (which
- may be end()).
-
- \sa insert(), removeAt()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::erase(iterator begin, iterator end)
-
- \overload
-
- Removes all the items from \a begin up to (but not including) \a
- end. Returns an iterator to the same item that \a end referred to
- before the call.
-*/
-
-/*! \typedef QList::Iterator
-
- Qt-style synonym for QList::iterator.
-*/
-
-/*! \typedef QList::ConstIterator
-
- Qt-style synonym for QList::const_iterator.
-*/
-
-/*!
- \typedef QList::size_type
-
- Typedef for int. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::value_type
-
- Typedef for T. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::difference_type
-
- Typedef for ptrdiff_t. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::pointer
-
- Typedef for T *. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::const_pointer
-
- Typedef for const T *. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::reference
-
- Typedef for T &. Provided for STL compatibility.
-*/
-
-/*!
- \typedef QList::const_reference
-
- 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 template <class T> int QList<T>::count() const
-
- Returns the number of items in the list. This is effectively the
- same as size().
-*/
-
-/*! \fn template <class T> int QList<T>::length() const
- \since 4.5
-
- This function is identical to count().
-
- \sa count()
-*/
-
-/*! \fn template <class T> T& QList<T>::first()
-
- Returns a 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 constFirst(), last(), isEmpty()
-*/
-
-/*! \fn template <class T> const T& QList<T>::first() const
-
- \overload
-*/
-
-/*! \fn template <class T> const T& QList<T>::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 template <class T> T& QList<T>::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 constLast(), first(), isEmpty()
-*/
-
-/*! \fn template <class T> const T& QList<T>::last() const
-
- \overload
-*/
-
-/*! \fn template <class T> const T& QList<T>::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 template <class T> void QList<T>::removeFirst()
-
- Removes the first item in the list. Calling this function is
- equivalent to calling removeAt(0). The list must not be empty. If
- the list can be empty, call isEmpty() before calling this
- function.
-
- \sa removeAt(), takeFirst()
-*/
-
-/*! \fn template <class T> void QList<T>::removeLast()
-
- Removes the last item in the list. Calling this function is
- equivalent to calling removeAt(size() - 1). The list must not be
- empty. If the list can be empty, call isEmpty() before calling
- this function.
-
- \sa removeAt(), takeLast()
-*/
-
-/*! \fn template <class T> T QList<T>::value(int i) const
-
- Returns the value at index position \a i in the list.
-
- If the index \a i is out of bounds, the function returns a
- \l{default-constructed value}. If you are certain that the index
- is going to be within bounds, you can use at() instead, which is
- slightly faster.
-
- \sa at(), operator[]()
-*/
-
-/*! \fn template <class T> T QList<T>::value(int i, const T &defaultValue) const
-
- \overload
-
- If the index \a i is out of bounds, the function returns
- \a defaultValue.
-*/
-
-/*! \fn template <class T> void QList<T>::push_back(const T &value)
-
- This function is provided for STL compatibility. It is equivalent
- to \l{QList::append()}{append(\a value)}.
-*/
-
-/*! \fn template <class T> void QList<T>::push_front(const T &value)
-
- This function is provided for STL compatibility. It is equivalent
- to \l{QList::prepend()}{prepend(\a value)}.
-*/
-
-/*! \fn template <class T> T& QList<T>::front()
-
- This function is provided for STL compatibility. It is equivalent
- to first(). The list must not be empty. If the list can be empty,
- call isEmpty() before calling this function.
-*/
-
-/*! \fn template <class T> const T& QList<T>::front() const
-
- \overload
-*/
-
-/*! \fn template <class T> T& QList<T>::back()
-
- This function is provided for STL compatibility. It is equivalent
- to last(). The list must not be empty. If the list can be empty,
- call isEmpty() before calling this function.
-*/
-
-/*! \fn template <class T> const T& QList<T>::back() const
-
- \overload
-*/
-
-/*! \fn template <class T> void QList<T>::pop_front()
-
- This function is provided for STL compatibility. It is equivalent
- to removeFirst(). The list must not be empty. If the list can be
- empty, call isEmpty() before calling this function.
-*/
-
-/*! \fn template <class T> void QList<T>::pop_back()
-
- This function is provided for STL compatibility. It is equivalent
- to removeLast(). The list must not be empty. If the list can be
- empty, call isEmpty() before calling this function.
-*/
-
-/*! \fn template <class T> bool QList<T>::empty() const
-
- This function is provided for STL compatibility. It is equivalent
- to isEmpty() and returns \c true if the list is empty.
-*/
-
-/*! \fn template <class T> QList<T> &QList<T>::operator+=(const QList<T> &other)
-
- Appends the items of the \a other list to this list and returns a
- reference to this list.
-
- \sa operator+(), append()
-*/
-
-/*! \fn template <class T> void QList<T>::operator+=(const T &value)
-
- \overload
-
- Appends \a value to the list.
-
- \sa append(), operator<<()
-*/
-
-/*! \fn template <class T> QList<T> QList<T>::operator+(const QList<T> &other) const
-
- Returns a list that contains all the items in this list followed
- by all the items in the \a other list.
-
- \sa operator+=()
-*/
-
-/*! \fn template <class T> QList<T> &QList<T>::operator<<(const QList<T> &other)
-
- Appends the items of the \a other list to this list and returns a
- reference to this list.
-
- \sa operator+=(), append()
-*/
-
-/*! \fn template <class T> void QList<T>::operator<<(const T &value)
-
- \overload
-
- Appends \a value to the list.
-*/
-
-/*! \class QList::iterator
- \inmodule QtCore
- \brief The QList::iterator class provides an STL-style non-const iterator for QList and QQueue.
-
- QList features both \l{STL-style iterators} and \l{Java-style
- iterators}. The STL-style iterators are more low-level and more
- cumbersome to use; on the other hand, they are slightly faster
- and, for developers who already know STL, have the advantage of
- familiarity.
-
- QList\<T\>::iterator allows you to iterate over a QList\<T\> (or
- QQueue\<T\>) and to modify the list item associated with the
- iterator. If you want to iterate over a const QList, use
- QList::const_iterator instead. It is generally good practice to
- use QList::const_iterator on a non-const QList as well, unless
- you need to change the QList through the iterator. Const
- iterators are slightly faster, and can improve code readability.
-
- The default QList::iterator constructor creates an uninitialized
- iterator. You must initialize it using a QList function like
- QList::begin(), QList::end(), or QList::insert() before you can
- start iterating. Here's a typical loop that prints all the items
- stored in a list:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 15
-
- Let's see a few examples of things we can do with a
- QList::iterator that we cannot do with a QList::const_iterator.
- Here's an example that increments every value stored in a
- QList\<int\> by 2:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 16
-
- Most QList functions accept an integer index rather than an
- iterator. For that reason, iterators are rarely useful in
- connection with QList. One place where STL-style iterators do
- make sense is as arguments to \l{generic algorithms}.
-
- For example, here's how to delete all the widgets stored in a
- QList\<QWidget *\>:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 17
-
- Multiple iterators can be used on the same list. However, be
- aware that any non-const function call performed on the QList
- will render all existing iterators undefined. If you need to keep
- iterators over a long period of time, we recommend that you use
- QLinkedList rather than QList.
-
- \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::const_iterator, QMutableListIterator
-*/
-
-/*! \typedef QList::iterator::iterator_category
-
- A synonym for \e {std::random_access_iterator_tag} indicating
- this iterator is a random access iterator.
-*/
-
-/*! \typedef QList::iterator::difference_type
-
- \internal
-*/
-
-/*! \typedef QList::iterator::value_type
-
- \internal
-*/
-
-/*! \typedef QList::iterator::pointer
-
- \internal
-*/
-
-/*! \typedef QList::iterator::reference
-
- \internal
-*/
-
-/*! \fn template <class T> QList<T>::iterator::iterator()
-
- Constructs an uninitialized iterator.
-
- Functions like operator*() and operator++() should not be called
- on an uninitialized iterator. Use operator=() to assign a value
- to it before using it.
-
- \sa QList::begin(), QList::end()
-*/
-
-/*! \fn template <class T> QList<T>::iterator::iterator(Node *node)
-
- \internal
-*/
-
-/*! \fn template <class T> QList<T>::iterator::iterator(const iterator &other)
-
- Constructs a copy of \a other.
-*/
-
-/*! \fn template <class T> T &QList<T>::iterator::operator*() const
-
- Returns a modifiable reference to the current item.
-
- You can change the value of an item by using operator*() on the
- left side of an assignment, for example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 18
-
- \sa operator->()
-*/
-
-/*! \fn template <class T> T *QList<T>::iterator::operator->() const
-
- Returns a pointer to the current item.
-
- \sa operator*()
-*/
-
-/*! \fn template <class T> T &QList<T>::iterator::operator[](difference_type j) const
-
- Returns a modifiable reference to the item at position *this +
- \a{j}.
-
- This function is provided to make QList iterators behave like C++
- pointers.
-
- \sa operator+()
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator==(const iterator &other) const
- \fn template <class T> bool QList<T>::iterator::operator==(const const_iterator &other) const
-
- Returns \c true if \a other points to the same item as this
- iterator; otherwise returns \c false.
-
- \sa operator!=()
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator!=(const iterator &other) const
- \fn template <class T> bool QList<T>::iterator::operator!=(const const_iterator &other) const
-
- Returns \c true if \a other points to a different item than this
- iterator; otherwise returns \c false.
-
- \sa operator==()
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator<(const iterator& other) const
- \fn template <class T> bool QList<T>::iterator::operator<(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is less than
- the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator<=(const iterator& other) const
- \fn template <class T> bool QList<T>::iterator::operator<=(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is less than
- or equal to the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator>(const iterator& other) const
- \fn template <class T> bool QList<T>::iterator::operator>(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is greater
- than the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::iterator::operator>=(const iterator& other) const
- \fn template <class T> bool QList<T>::iterator::operator>=(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is greater
- than or equal to the item pointed to by the \a other iterator.
-*/
-
-/*! \fn template <class T> QList<T>::iterator &QList<T>::iterator::operator++()
-
- The prefix ++ operator (\c{++it}) advances the iterator to the
- next item in the list and returns an iterator to the new current
- item.
-
- Calling this function on QList::end() leads to undefined results.
-
- \sa operator--()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::iterator::operator++(int)
-
- \overload
-
- The postfix ++ operator (\c{it++}) advances the iterator to the
- next item in the list and returns an iterator to the previously
- current item.
-*/
-
-/*! \fn template <class T> QList<T>::iterator &QList<T>::iterator::operator--()
-
- The prefix -- operator (\c{--it}) makes the preceding item
- current and returns an iterator to the new current item.
-
- Calling this function on QList::begin() leads to undefined results.
-
- \sa operator++()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::iterator::operator--(int)
-
- \overload
-
- The postfix -- operator (\c{it--}) makes the preceding item
- current and returns an iterator to the previously current item.
-*/
-
-/*! \fn template <class T> QList<T>::iterator &QList<T>::iterator::operator+=(difference_type j)
-
- Advances the iterator by \a j items. (If \a j is negative, the
- iterator goes backward.)
-
- \sa operator-=(), operator+()
-*/
-
-/*! \fn template <class T> QList<T>::iterator &QList<T>::iterator::operator-=(difference_type j)
-
- Makes the iterator go back by \a j items. (If \a j is negative,
- the iterator goes forward.)
-
- \sa operator+=(), operator-()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::iterator::operator+(difference_type j) const
-
- Returns an iterator to the item at \a j positions forward from
- this iterator. (If \a j is negative, the iterator goes backward.)
-
- \sa operator-(), operator+=()
-*/
-
-/*! \fn template <class T> QList<T>::iterator QList<T>::iterator::operator-(difference_type j) const
-
- Returns an iterator to the item at \a j positions backward from
- this iterator. (If \a j is negative, the iterator goes forward.)
-
- \sa operator+(), operator-=()
-*/
-
-/*! \fn template <class T> int QList<T>::iterator::operator-(iterator other) const
-
- Returns the number of items between the item pointed to by \a
- other and the item pointed to by this iterator.
-*/
-
-/*! \class QList::const_iterator
- \inmodule QtCore
- \brief The QList::const_iterator class provides an STL-style const iterator for QList and QQueue.
-
- QList provides both \l{STL-style iterators} and \l{Java-style
- iterators}. The STL-style iterators are more low-level and more
- cumbersome to use; on the other hand, they are slightly faster
- and, for developers who already know STL, have the advantage of
- familiarity.
-
- QList\<T\>::const_iterator allows you to iterate over a
- QList\<T\> (or a QQueue\<T\>). If you want to modify the QList as
- you iterate over it, use QList::iterator instead. It is generally
- good practice to use QList::const_iterator on a non-const QList
- as well, unless you need to change the QList through the
- iterator. Const iterators are slightly faster, and can improve
- code readability.
-
- The default QList::const_iterator constructor creates an
- uninitialized iterator. You must initialize it using a QList
- function like QList::constBegin(), QList::constEnd(), or
- QList::insert() before you can start iterating. Here's a typical
- loop that prints all the items stored in a list:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 19
-
- Most QList functions accept an integer index rather than an
- iterator. For that reason, iterators are rarely useful in
- connection with QList. One place where STL-style iterators do
- make sense is as arguments to \l{generic algorithms}.
-
- For example, here's how to delete all the widgets stored in a
- QList\<QWidget *\>:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 20
-
- Multiple iterators can be used on the same list. However, be
- aware that any non-const function call performed on the QList
- will render all existing iterators undefined. If you need to keep
- iterators over a long period of time, we recommend that you use
- QLinkedList rather than QList.
-
- \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::iterator, QListIterator
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator::const_iterator()
-
- Constructs an uninitialized iterator.
-
- Functions like operator*() and operator++() should not be called
- on an uninitialized iterator. Use operator=() to assign a value
- to it before using it.
-
- \sa QList::constBegin(), QList::constEnd()
-*/
-
-/*! \typedef QList::const_iterator::iterator_category
-
- A synonym for \e {std::random_access_iterator_tag} indicating
- this iterator is a random access iterator.
-*/
-
-/*! \typedef QList::const_iterator::difference_type
-
- \internal
-*/
-
-/*! \typedef QList::const_iterator::value_type
-
- \internal
-*/
-
-/*! \typedef QList::const_iterator::pointer
-
- \internal
-*/
-
-/*! \typedef QList::const_iterator::reference
-
- \internal
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator::const_iterator(Node *node)
-
- \internal
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator::const_iterator(const const_iterator &other)
-
- Constructs a copy of \a other.
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator::const_iterator(const iterator &other)
-
- Constructs a copy of \a other.
-*/
-
-/*! \fn template <class T> const T &QList<T>::const_iterator::operator*() const
-
- Returns the current item.
-
- \sa operator->()
-*/
-
-/*! \fn template <class T> const T *QList<T>::const_iterator::operator->() const
-
- Returns a pointer to the current item.
-
- \sa operator*()
-*/
-
-/*! \fn template <class T> const T &QList<T>::const_iterator::operator[](difference_type j) const
-
- Returns the item at position *this + \a{j}.
-
- This function is provided to make QList iterators behave like C++
- pointers.
-
- \sa operator+()
-*/
-
-/*! \fn template <class T> bool QList<T>::const_iterator::operator==(const const_iterator &other) const
-
- Returns \c true if \a other points to the same item as this
- iterator; otherwise returns \c false.
-
- \sa operator!=()
-*/
-
-/*! \fn template <class T> bool QList<T>::const_iterator::operator!=(const const_iterator &other) const
-
- Returns \c true if \a other points to a different item than this
- iterator; otherwise returns \c false.
-
- \sa operator==()
-*/
-
-/*!
- \fn template <class T> bool QList<T>::const_iterator::operator<(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is less than
- the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::const_iterator::operator<=(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is less than
- or equal to the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::const_iterator::operator>(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is greater
- than the item pointed to by the \a other iterator.
-*/
-
-/*!
- \fn template <class T> bool QList<T>::const_iterator::operator>=(const const_iterator& other) const
-
- Returns \c true if the item pointed to by this iterator is greater
- than or equal to the item pointed to by the \a other iterator.
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator &QList<T>::const_iterator::operator++()
-
- The prefix ++ operator (\c{++it}) advances the iterator to the
- next item in the list and returns an iterator to the new current
- item.
-
- Calling this function on QList::end() leads to undefined results.
-
- \sa operator--()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::const_iterator::operator++(int)
-
- \overload
-
- The postfix ++ operator (\c{it++}) advances the iterator to the
- next item in the list and returns an iterator to the previously
- current item.
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator &QList<T>::const_iterator::operator--()
-
- The prefix -- operator (\c{--it}) makes the preceding item
- current and returns an iterator to the new current item.
-
- Calling this function on QList::begin() leads to undefined results.
-
- \sa operator++()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::const_iterator::operator--(int)
-
- \overload
-
- The postfix -- operator (\c{it--}) makes the preceding item
- current and returns an iterator to the previously current item.
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator &QList<T>::const_iterator::operator+=(difference_type j)
-
- Advances the iterator by \a j items. (If \a j is negative, the
- iterator goes backward.)
-
- \sa operator-=(), operator+()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator &QList<T>::const_iterator::operator-=(difference_type j)
-
- Makes the iterator go back by \a j items. (If \a j is negative,
- the iterator goes forward.)
-
- \sa operator+=(), operator-()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::const_iterator::operator+(difference_type j) const
-
- Returns an iterator to the item at \a j positions forward from
- this iterator. (If \a j is negative, the iterator goes backward.)
-
- \sa operator-(), operator+=()
-*/
-
-/*! \fn template <class T> QList<T>::const_iterator QList<T>::const_iterator::operator-(difference_type j) const
-
- Returns an iterator to the item at \a j positions backward from
- this iterator. (If \a j is negative, the iterator goes forward.)
-
- \sa operator+(), operator-=()
-*/
-
-/*! \fn template <class T> int QList<T>::const_iterator::operator-(const_iterator other) const
-
- Returns the number of items between the item pointed to by \a
- other and the item pointed to by this iterator.
-*/
-
-/*! \fn template <class T> QDataStream &operator<<(QDataStream &out, const QList<T> &list)
- \relates QList
-
- Writes the list \a list to stream \a out.
-
- This function requires the value type to implement \c
- operator<<().
-
- \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
-*/
-
-/*! \fn template <class T> QDataStream &operator>>(QDataStream &in, QList<T> &list)
- \relates QList
-
- Reads a list from stream \a in into \a list.
-
- This function requires the value type to implement \c
- operator>>().
-
- \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
-*/
-
-/*! \fn template <class T> QList<T> QList<T>::fromVector(const QVector<T> &vector)
-
- Returns a QList object with the data contained in \a vector.
-
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 21
-
- \include containers-range-constructor.qdocinc
-
- \sa fromSet(), toVector(), QVector::toList()
-*/
-
-/*! \fn template <class T> QVector<T> QList<T>::toVector() const
-
- Returns a QVector object with the data contained in this QList.
-
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 22
-
- \include containers-range-constructor.qdocinc
-
- \sa toSet(), fromVector(), QVector::fromList()
-*/
-
-/*! \fn template <class T> QList<T> QList<T>::fromSet(const QSet<T> &set)
-
- Returns a QList object with the data contained in \a set. The
- order of the elements in the QList is undefined.
-
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 23
-
- \include containers-range-constructor.qdocinc
-
- \sa fromVector(), toSet(), QSet::toList()
-*/
-
-/*! \fn template <class T> QSet<T> QList<T>::toSet() const
-
- Returns a QSet object with the data contained in this QList.
- Since QSet doesn't allow duplicates, the resulting QSet might be
- smaller than the original list was.
-
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 24
-
- \include containers-range-constructor.qdocinc
-
- \sa toVector(), fromSet(), QSet::fromList()
-*/
-
-/*! \fn template <class T> QList<T> QList<T>::fromStdList(const std::list<T> &list)
-
- Returns a QList object with the data contained in \a list. The
- order of the elements in the QList is the same as in \a list.
-
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 25
-
- \include containers-range-constructor.qdocinc
-
- \sa toStdList(), QVector::fromStdVector()
-*/
-
-/*! \fn template <class T> std::list<T> QList<T>::toStdList() const
-
- Returns a std::list object with the data contained in this QList.
- Example:
-
- \snippet code/src_corelib_tools_qlistdata.cpp 26
-
- \include containers-range-constructor.qdocinc
-
- \sa fromStdList(), QVector::toStdVector()
-*/
-
QT_END_NAMESPACE
diff --git a/src/corelib/tools/qlist.h b/src/corelib/tools/qlist.h
index ffd470efcd..515fba6530 100644
--- a/src/corelib/tools/qlist.h
+++ b/src/corelib/tools/qlist.h
@@ -40,1160 +40,19 @@
#ifndef QLIST_H
#define QLIST_H
-#include <QtCore/qalgorithms.h>
-#include <QtCore/qiterator.h>
-#include <QtCore/qrefcount.h>
-#include <QtCore/qarraydata.h>
-#include <QtCore/qhashfunctions.h>
#include <QtCore/qvector.h>
-#include <QtCore/qcontainertools_impl.h>
-
-#include <algorithm>
-#include <initializer_list>
-#include <iterator>
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-#include <list>
-#endif
-
-#include <stdlib.h>
-#include <new>
-#include <limits.h>
-#include <string.h>
-
-#ifdef Q_CC_MSVC
-#pragma warning( push )
-#pragma warning( disable : 4127 ) // "conditional expression is constant"
-#endif
+#include <QtCore/qcontainerfwd.h>
+#if !defined(QT_NO_JAVA_STYLE_ITERATORS)
QT_BEGIN_NAMESPACE
-
-
-template <typename T> class QVector;
-template <typename T> class QSet;
-
-template <typename T> struct QListSpecialMethods
-{
-protected:
- ~QListSpecialMethods() = default;
-};
-template <> struct QListSpecialMethods<QByteArray>;
-template <> struct QListSpecialMethods<QString>;
-
-struct Q_CORE_EXPORT QListData {
- // tags for tag-dispatching of QList implementations,
- // based on QList's three different memory layouts:
- struct NotArrayCompatibleLayout {};
- struct NotIndirectLayout {};
- struct ArrayCompatibleLayout : NotIndirectLayout {}; // data laid out like a C array
- struct InlineWithPaddingLayout : NotArrayCompatibleLayout, NotIndirectLayout {}; // data laid out like a C array with padding
- struct IndirectLayout : NotArrayCompatibleLayout {}; // data allocated on the heap
-
- struct Data {
- QtPrivate::RefCount ref;
- int alloc, begin, end;
- void *array[1];
- };
- enum { DataHeaderSize = sizeof(Data) - sizeof(void *) };
-
- 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;
- Data *d;
- void **erase(void **xi);
- void **append(int n);
- void **append();
- void **append(const QListData &l);
- void **prepend();
- void **insert(int i);
- void remove(int i);
- void remove(int i, int n);
- void move(int from, int to);
- inline int size() const noexcept { return int(d->end - d->begin); } // q6sizetype
- inline bool isEmpty() const noexcept { return d->end == d->begin; }
- inline void **at(int i) const noexcept { return d->array + d->begin + i; }
- inline void **begin() const noexcept { return d->array + d->begin; }
- inline void **end() const noexcept { return d->array + d->end; }
-};
-
-namespace QtPrivate {
- template <typename V, typename U> int indexOf(const QList<V> &list, const U &u, int from);
- template <typename V, typename U> int lastIndexOf(const QList<V> &list, const U &u, int from);
-}
-
-template <typename T>
-class QList
-#ifndef Q_QDOC
- : public QListSpecialMethods<T>
-#endif
-{
-public:
- struct MemoryLayout
- : std::conditional<
- // must stay isStatic until ### Qt 6 for BC reasons (don't use !isRelocatable)!
- QTypeInfo<T>::isStatic || QTypeInfo<T>::isLarge,
- QListData::IndirectLayout,
- typename std::conditional<
- sizeof(T) == sizeof(void*),
- QListData::ArrayCompatibleLayout,
- QListData::InlineWithPaddingLayout
- >::type>::type {};
-private:
- template <typename V, typename U> friend int QtPrivate::indexOf(const QList<V> &list, const U &u, int from);
- template <typename V, typename U> friend int QtPrivate::lastIndexOf(const QList<V> &list, const U &u, int from);
- struct Node { void *v;
-#if defined(Q_CC_BOR)
- Q_INLINE_TEMPLATE T &t();
-#else
- Q_INLINE_TEMPLATE T &t()
- { return *reinterpret_cast<T*>(QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic
- ? v : this); }
-#endif
- };
-
- union { QListData p; QListData::Data *d; };
-
-public:
- inline QList() noexcept : d(const_cast<QListData::Data *>(&QListData::shared_null)) { }
- QList(const QList<T> &l);
- ~QList();
- QList<T> &operator=(const QList<T> &l);
- inline QList(QList<T> &&other) noexcept
- : d(other.d) { other.d = const_cast<QListData::Data *>(&QListData::shared_null); }
- inline QList &operator=(QList<T> &&other) noexcept
- { QList moved(std::move(other)); swap(moved); return *this; }
- inline void swap(QList<T> &other) noexcept { qSwap(d, other.d); }
- inline QList(std::initializer_list<T> args)
- : QList(args.begin(), args.end()) {}
- template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator> = true>
- QList(InputIterator first, InputIterator last);
- bool operator==(const QList<T> &l) const;
- inline bool operator!=(const QList<T> &l) const { return !(*this == l); }
-
- inline int size() const noexcept { return p.size(); }
-
- inline void detach() { if (d->ref.isShared()) detach_helper(); }
-
- inline void detachShared()
- {
- // The "this->" qualification is needed for GCCE.
- if (d->ref.isShared() && this->d != &QListData::shared_null)
- detach_helper();
- }
-
- inline bool isDetached() const { return !d->ref.isShared(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable)
- {
- if (sharable == d->ref.isSharable())
- return;
- if (!sharable)
- detach();
- if (d != &QListData::shared_null)
- d->ref.setSharable(sharable);
- }
-#endif
- inline bool isSharedWith(const QList<T> &other) const noexcept { return d == other.d; }
-
- inline bool isEmpty() const noexcept { return p.isEmpty(); }
-
- void clear();
-
- const T &at(int i) const;
- const T &operator[](int i) const;
- T &operator[](int i);
-
- void reserve(int size);
- void append(const T &t);
- void append(const QList<T> &t);
- void prepend(const T &t);
- void insert(int i, const T &t);
- void replace(int i, const T &t);
- void removeAt(int i);
- int removeAll(const T &t);
- bool removeOne(const T &t);
- T takeAt(int i);
- T takeFirst();
- T takeLast();
- void move(int from, int to);
- void swapItemsAt(int i, int j);
-#if QT_DEPRECATED_SINCE(5, 13) && QT_VERSION < QT_VERSION_CHECK(6,0,0)
- QT_DEPRECATED_X("Use QList<T>::swapItemsAt()")
- void swap(int i, int j) { swapItemsAt(i, j); }
-#endif
- int indexOf(const T &t, int from = 0) const;
- int lastIndexOf(const T &t, int from = -1) const;
- bool contains(const T &t) const;
- int count(const T &t) const;
-
- class const_iterator;
-
- class iterator {
- public:
- Node *i;
- typedef std::random_access_iterator_tag iterator_category;
- // ### Qt6: use int
- typedef qptrdiff difference_type;
- typedef T value_type;
- typedef T *pointer;
- typedef T &reference;
-
- inline iterator() noexcept : i(nullptr) {}
- inline iterator(Node *n) noexcept : 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) noexcept : i(o.i){}
- inline iterator &operator=(const iterator &o) noexcept
- { i = o.i; return *this; }
-#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 noexcept { return i == o.i; }
- inline bool operator!=(const iterator &o) const noexcept { return i != o.i; }
- inline bool operator<(const iterator& other) const noexcept { return i < other.i; }
- inline bool operator<=(const iterator& other) const noexcept { return i <= other.i; }
- inline bool operator>(const iterator& other) const noexcept { return i > other.i; }
- inline bool operator>=(const iterator& other) const noexcept { return i >= other.i; }
-#ifndef QT_STRICT_ITERATORS
- inline bool operator==(const const_iterator &o) const noexcept
- { return i == o.i; }
- inline bool operator!=(const const_iterator &o) const noexcept
- { return i != o.i; }
- inline bool operator<(const const_iterator& other) const noexcept
- { return i < other.i; }
- inline bool operator<=(const const_iterator& other) const noexcept
- { return i <= other.i; }
- inline bool operator>(const const_iterator& other) const noexcept
- { return i > other.i; }
- inline bool operator>=(const const_iterator& other) const noexcept
- { return i >= other.i; }
-#endif
- inline iterator &operator++() { ++i; return *this; }
- inline iterator operator++(int) { Node *n = i; ++i; return n; }
- inline iterator &operator--() { i--; return *this; }
- inline iterator operator--(int) { Node *n = i; i--; return n; }
- inline iterator &operator+=(difference_type j) { i+=j; return *this; }
- inline iterator &operator-=(difference_type j) { i-=j; return *this; }
- inline iterator operator+(difference_type j) const { return iterator(i+j); }
- inline iterator operator-(difference_type j) const { return iterator(i-j); }
- friend inline iterator operator+(difference_type j, iterator k) { return k + j; }
- inline int operator-(iterator j) const { return int(i - j.i); }
- };
- friend class iterator;
-
- class const_iterator {
- public:
- Node *i;
- typedef std::random_access_iterator_tag iterator_category;
- // ### Qt6: use int
- typedef qptrdiff difference_type;
- typedef T value_type;
- typedef const T *pointer;
- typedef const T &reference;
-
- inline const_iterator() noexcept : i(nullptr) {}
- inline const_iterator(Node *n) noexcept : 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) noexcept : i(o.i) {}
- inline const_iterator &operator=(const const_iterator &o) noexcept
- { i = o.i; return *this; }
-#endif
-#ifdef QT_STRICT_ITERATORS
- inline explicit const_iterator(const iterator &o) noexcept : i(o.i) {}
-#else
- inline const_iterator(const iterator &o) noexcept : 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 noexcept { return i == o.i; }
- inline bool operator!=(const const_iterator &o) const noexcept { return i != o.i; }
- inline bool operator<(const const_iterator& other) const noexcept { return i < other.i; }
- inline bool operator<=(const const_iterator& other) const noexcept { return i <= other.i; }
- inline bool operator>(const const_iterator& other) const noexcept { return i > other.i; }
- inline bool operator>=(const const_iterator& other) const noexcept { 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; }
- inline const_iterator operator--(int) { Node *n = i; i--; return n; }
- inline const_iterator &operator+=(difference_type j) { i+=j; return *this; }
- inline const_iterator &operator-=(difference_type j) { i-=j; return *this; }
- inline const_iterator operator+(difference_type j) const { return const_iterator(i+j); }
- inline const_iterator operator-(difference_type j) const { return const_iterator(i-j); }
- friend inline const_iterator operator+(difference_type j, const_iterator k) { return k + j; }
- inline int operator-(const_iterator j) const { return int(i - j.i); }
- };
- 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 noexcept { return reinterpret_cast<Node *>(p.begin()); }
- inline const_iterator cbegin() const noexcept { return reinterpret_cast<Node *>(p.begin()); }
- inline const_iterator constBegin() const noexcept { return reinterpret_cast<Node *>(p.begin()); }
- inline iterator end() { detach(); return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator end() const noexcept { return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator cend() const noexcept { return reinterpret_cast<Node *>(p.end()); }
- inline const_iterator constEnd() const noexcept { 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 noexcept { return const_reverse_iterator(end()); }
- const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
- const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); }
- const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); }
- iterator insert(iterator before, const T &t);
- iterator erase(iterator pos);
- iterator erase(iterator first, iterator last);
-
- // more Qt
- typedef iterator Iterator;
- typedef const_iterator ConstIterator;
- 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; }
- inline bool endsWith(const T &t) const { return !isEmpty() && last() == t; }
- QList<T> mid(int pos, int length = -1) const;
-
- T value(int i) const;
- T value(int i, const T &defaultValue) const;
-
- // stl compatibility
- inline void push_back(const T &t) { append(t); }
- inline void push_front(const T &t) { prepend(t); }
- inline T& front() { return first(); }
- inline const T& front() const { return first(); }
- inline T& back() { return last(); }
- inline const T& back() const { return last(); }
- inline void pop_front() { removeFirst(); }
- inline void pop_back() { removeLast(); }
- inline bool empty() const { return isEmpty(); }
- typedef int size_type;
- typedef T value_type;
- typedef value_type *pointer;
- typedef const value_type *const_pointer;
- typedef value_type &reference;
- typedef const value_type &const_reference;
- // ### Qt6: use int
- typedef qptrdiff difference_type;
-
- // comfort
- QList<T> &operator+=(const QList<T> &l);
- inline QList<T> operator+(const QList<T> &l) const
- { QList n = *this; n += l; return n; }
- inline QList<T> &operator+=(const T &t)
- { append(t); return *this; }
- inline QList<T> &operator<< (const T &t)
- { append(t); return *this; }
- inline QList<T> &operator<<(const QList<T> &l)
- { *this += l; return *this; }
-
- static QList<T> fromVector(const QVector<T> &vector);
- QVector<T> toVector() const;
-
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- Q_DECL_DEPRECATED_X("Use QList<T>(set.begin(), set.end()) instead.")
- static QList<T> fromSet(const QSet<T> &set);
- Q_DECL_DEPRECATED_X("Use QSet<T>(list.begin(), list.end()) instead.")
- QSet<T> toSet() const;
-
- Q_DECL_DEPRECATED_X("Use QList<T>(list.begin(), list.end()) instead.")
- static inline QList<T> fromStdList(const std::list<T> &list)
- { return QList<T>(list.begin(), list.end()); }
- Q_DECL_DEPRECATED_X("Use std::list<T>(list.begin(), list.end()) instead.")
- inline std::list<T> toStdList() const
- { return std::list<T>(begin(), end()); }
-#endif
-
-private:
- Node *detach_helper_grow(int i, int n);
- void detach_helper(int alloc);
- void detach_helper();
- void dealloc(QListData::Data *d);
-
- void node_construct(Node *n, const T &t);
- void node_destruct(Node *n);
- void node_copy(Node *from, Node *to, Node *src);
- void node_destruct(Node *from, Node *to);
-
- bool isValidIterator(const iterator &i) const noexcept
- {
- const std::less<const Node *> less = {};
- return !less(i.i, cbegin().i) && !less(cend().i, i.i);
- }
-
-private:
- inline bool op_eq_impl(const QList &other, QListData::NotArrayCompatibleLayout) const;
- inline bool op_eq_impl(const QList &other, QListData::ArrayCompatibleLayout) const;
- inline bool contains_impl(const T &, QListData::NotArrayCompatibleLayout) const;
- inline bool contains_impl(const T &, QListData::ArrayCompatibleLayout) const;
- inline int count_impl(const T &, QListData::NotArrayCompatibleLayout) const;
- inline int count_impl(const T &, QListData::ArrayCompatibleLayout) const;
-};
-
-#if defined(__cpp_deduction_guides) && __cpp_deduction_guides >= 201606
-template <typename InputIterator,
- typename ValueType = typename std::iterator_traits<InputIterator>::value_type,
- QtPrivate::IfIsInputIterator<InputIterator> = true>
-QList(InputIterator, InputIterator) -> QList<ValueType>;
-#endif
-
-#if defined(Q_CC_BOR)
-template <typename T>
-Q_INLINE_TEMPLATE T &QList<T>::Node::t()
-{ return QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic ? *(T*)v:*(T*)this; }
-#endif
-
-template <typename T>
-Q_INLINE_TEMPLATE void QList<T>::node_construct(Node *n, const T &t)
-{
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);
- else if (QTypeInfo<T>::isComplex) new (n) T(t);
-#if (defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__IBMCPP__)) && !defined(__OPTIMIZE__)
- // This violates pointer aliasing rules, but it is known to be safe (and silent)
- // in unoptimized GCC builds (-fno-strict-aliasing). The other compilers which
- // set the same define are assumed to be safe.
- else *reinterpret_cast<T*>(n) = t;
-#else
- // This is always safe, but penaltizes unoptimized builds a lot.
- else ::memcpy(n, static_cast<const void *>(&t), sizeof(T));
-#endif
-}
-
-template <typename T>
-Q_INLINE_TEMPLATE void QList<T>::node_destruct(Node *n)
-{
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) delete reinterpret_cast<T*>(n->v);
- else if (QTypeInfo<T>::isComplex) reinterpret_cast<T*>(n)->~T();
-}
-
-template <typename T>
-Q_INLINE_TEMPLATE void QList<T>::node_copy(Node *from, Node *to, Node *src)
-{
- Node *current = from;
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) {
- QT_TRY {
- while(current != to) {
- current->v = new T(*reinterpret_cast<T*>(src->v));
- ++current;
- ++src;
- }
- } QT_CATCH(...) {
- while (current-- != from)
- delete reinterpret_cast<T*>(current->v);
- QT_RETHROW;
- }
-
- } else if (QTypeInfo<T>::isComplex) {
- QT_TRY {
- while(current != to) {
- new (current) T(*reinterpret_cast<T*>(src));
- ++current;
- ++src;
- }
- } QT_CATCH(...) {
- while (current-- != from)
- (reinterpret_cast<T*>(current))->~T();
- QT_RETHROW;
- }
- } else {
- if (src != from && to - from > 0)
- memcpy(from, src, (to - from) * sizeof(Node));
- }
-}
-
-template <typename T>
-Q_INLINE_TEMPLATE void QList<T>::node_destruct(Node *from, Node *to)
-{
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic)
- while(from != to) --to, delete reinterpret_cast<T*>(to->v);
- else if (QTypeInfo<T>::isComplex)
- while (from != to) --to, reinterpret_cast<T*>(to)->~T();
-}
-
-template <typename T>
-Q_INLINE_TEMPLATE QList<T> &QList<T>::operator=(const QList<T> &l)
-{
- if (d != l.d) {
- QList<T> tmp(l);
- tmp.swap(*this);
- }
- return *this;
-}
-template <typename T>
-inline typename QList<T>::iterator QList<T>::insert(iterator before, const T &t)
-{
- Q_ASSERT_X(isValidIterator(before), "QList::insert", "The specified iterator argument 'before' is invalid");
-
- int iBefore = int(before.i - reinterpret_cast<Node *>(p.begin()));
- Node *n = nullptr;
- if (d->ref.isShared())
- n = detach_helper_grow(iBefore, 1);
- else
- n = reinterpret_cast<Node *>(p.insert(iBefore));
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- p.remove(iBefore);
- QT_RETHROW;
- }
- return n;
-}
-template <typename T>
-inline typename QList<T>::iterator QList<T>::erase(iterator it)
-{
- Q_ASSERT_X(isValidIterator(it), "QList::erase", "The specified iterator argument 'it' is invalid");
- if (d->ref.isShared()) {
- int offset = int(it.i - reinterpret_cast<Node *>(p.begin()));
- it = begin(); // implies detach()
- it += offset;
- }
- node_destruct(it.i);
- return reinterpret_cast<Node *>(p.erase(reinterpret_cast<void**>(it.i)));
-}
-template <typename T>
-inline const T &QList<T>::at(int i) const
-{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::at", "index out of range");
- return reinterpret_cast<Node *>(p.at(i))->t(); }
-template <typename T>
-inline const T &QList<T>::operator[](int i) const
-{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
- return reinterpret_cast<Node *>(p.at(i))->t(); }
-template <typename T>
-inline T &QList<T>::operator[](int i)
-{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
- detach(); return reinterpret_cast<Node *>(p.at(i))->t(); }
-template <typename T>
-inline void QList<T>::removeAt(int i)
-{
-#if !QT_DEPRECATED_SINCE(5, 15)
- Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::removeAt", "index out of range");
-#elif !defined(QT_NO_DEBUG)
- if (i < 0 || i >= p.size())
- qWarning("QList::removeAt(): Index out of range.");
-#endif
- detach();
- node_destruct(reinterpret_cast<Node *>(p.at(i))); p.remove(i);
-}
-template <typename T>
-inline T QList<T>::takeAt(int i)
-{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::take", "index out of range");
- detach(); Node *n = reinterpret_cast<Node *>(p.at(i)); T t = std::move(n->t()); node_destruct(n);
- p.remove(i); return t; }
-template <typename T>
-inline T QList<T>::takeFirst()
-{ T t = std::move(first()); removeFirst(); return t; }
-template <typename T>
-inline T QList<T>::takeLast()
-{ T t = std::move(last()); removeLast(); return t; }
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::reserve(int alloc)
-{
- if (d->alloc < alloc) {
- if (d->ref.isShared())
- detach_helper(alloc);
- else
- p.realloc(alloc);
- }
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::append(const T &t)
-{
- if (d->ref.isShared()) {
- Node *n = detach_helper_grow(INT_MAX, 1);
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- --d->end;
- QT_RETHROW;
- }
- } else {
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) {
- Node *n = reinterpret_cast<Node *>(p.append());
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- --d->end;
- QT_RETHROW;
- }
- } else {
- Node *n, copy;
- node_construct(&copy, t); // t might be a reference to an object in the array
- QT_TRY {
- n = reinterpret_cast<Node *>(p.append());;
- } QT_CATCH(...) {
- node_destruct(&copy);
- QT_RETHROW;
- }
- *n = copy;
- }
- }
-}
-
-template <typename T>
-inline void QList<T>::prepend(const T &t)
-{
- if (d->ref.isShared()) {
- Node *n = detach_helper_grow(0, 1);
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- ++d->begin;
- QT_RETHROW;
- }
- } else {
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) {
- Node *n = reinterpret_cast<Node *>(p.prepend());
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- ++d->begin;
- QT_RETHROW;
- }
- } else {
- Node *n, copy;
- node_construct(&copy, t); // t might be a reference to an object in the array
- QT_TRY {
- n = reinterpret_cast<Node *>(p.prepend());;
- } QT_CATCH(...) {
- node_destruct(&copy);
- QT_RETHROW;
- }
- *n = copy;
- }
- }
-}
-
-template <typename T>
-inline void QList<T>::insert(int i, const T &t)
-{
-#if !QT_DEPRECATED_SINCE(5, 15)
- Q_ASSERT_X(i >= 0 && i <= p.size(), "QList<T>::insert", "index out of range");
-#elif !defined(QT_NO_DEBUG)
- if (i < 0 || i > p.size())
- qWarning("QList::insert(): Index out of range.");
-#endif
- if (d->ref.isShared()) {
- Node *n = detach_helper_grow(i, 1);
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- p.remove(i);
- QT_RETHROW;
- }
- } else {
- if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) {
- Node *n = reinterpret_cast<Node *>(p.insert(i));
- QT_TRY {
- node_construct(n, t);
- } QT_CATCH(...) {
- p.remove(i);
- QT_RETHROW;
- }
- } else {
- Node *n, copy;
- node_construct(&copy, t); // t might be a reference to an object in the array
- QT_TRY {
- n = reinterpret_cast<Node *>(p.insert(i));;
- } QT_CATCH(...) {
- node_destruct(&copy);
- QT_RETHROW;
- }
- *n = copy;
- }
- }
-}
-
-template <typename T>
-inline void QList<T>::replace(int i, const T &t)
-{
- Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::replace", "index out of range");
- detach();
- reinterpret_cast<Node *>(p.at(i))->t() = t;
-}
-
-template <typename T>
-inline void QList<T>::swapItemsAt(int i, int j)
-{
- Q_ASSERT_X(i >= 0 && i < p.size() && j >= 0 && j < p.size(),
- "QList<T>::swap", "index out of range");
- detach();
- qSwap(d->array[d->begin + i], d->array[d->begin + j]);
-}
-
-template <typename T>
-inline void QList<T>::move(int from, int to)
-{
- Q_ASSERT_X(from >= 0 && from < p.size() && to >= 0 && to < p.size(),
- "QList<T>::move", "index out of range");
- detach();
- p.move(from, to);
-}
-
-template<typename T>
-Q_OUTOFLINE_TEMPLATE QList<T> QList<T>::mid(int pos, int alength) const
-{
- using namespace QtPrivate;
- switch (QContainerImplHelper::mid(size(), &pos, &alength)) {
- case QContainerImplHelper::Null:
- case QContainerImplHelper::Empty:
- return QList<T>();
- case QContainerImplHelper::Full:
- return *this;
- case QContainerImplHelper::Subset:
- break;
- }
-
- QList<T> cpy;
- if (alength <= 0)
- return cpy;
- cpy.reserve(alength);
- cpy.d->end = alength;
- QT_TRY {
- cpy.node_copy(reinterpret_cast<Node *>(cpy.p.begin()),
- reinterpret_cast<Node *>(cpy.p.end()),
- reinterpret_cast<Node *>(p.begin() + pos));
- } QT_CATCH(...) {
- // restore the old end
- cpy.d->end = 0;
- QT_RETHROW;
- }
- return cpy;
-}
-
template<typename T>
-Q_OUTOFLINE_TEMPLATE T QList<T>::value(int i) const
-{
- if (i < 0 || i >= p.size()) {
- return T();
- }
- return reinterpret_cast<Node *>(p.at(i))->t();
-}
-
+using QMutableListIterator = QMutableVectorIterator<T>;
template<typename T>
-Q_OUTOFLINE_TEMPLATE T QList<T>::value(int i, const T& defaultValue) const
-{
- return ((i < 0 || i >= p.size()) ? defaultValue : reinterpret_cast<Node *>(p.at(i))->t());
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE typename QList<T>::Node *QList<T>::detach_helper_grow(int i, int c)
-{
- Node *n = reinterpret_cast<Node *>(p.begin());
- QListData::Data *x = p.detach_grow(&i, c);
- QT_TRY {
- node_copy(reinterpret_cast<Node *>(p.begin()),
- reinterpret_cast<Node *>(p.begin() + i), n);
- } QT_CATCH(...) {
- p.dispose();
- d = x;
- QT_RETHROW;
- }
- QT_TRY {
- node_copy(reinterpret_cast<Node *>(p.begin() + i + c),
- reinterpret_cast<Node *>(p.end()), n + i);
- } QT_CATCH(...) {
- node_destruct(reinterpret_cast<Node *>(p.begin()),
- reinterpret_cast<Node *>(p.begin() + i));
- p.dispose();
- d = x;
- QT_RETHROW;
- }
-
- if (!x->ref.deref())
- dealloc(x);
-
- return reinterpret_cast<Node *>(p.begin() + i);
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::detach_helper(int alloc)
-{
- Node *n = reinterpret_cast<Node *>(p.begin());
- QListData::Data *x = p.detach(alloc);
- QT_TRY {
- node_copy(reinterpret_cast<Node *>(p.begin()), reinterpret_cast<Node *>(p.end()), n);
- } QT_CATCH(...) {
- p.dispose();
- d = x;
- QT_RETHROW;
- }
-
- if (!x->ref.deref())
- dealloc(x);
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::detach_helper()
-{
- detach_helper(d->alloc);
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QList<T>::QList(const QList<T> &l)
- : QListSpecialMethods<T>(l), d(l.d)
-{
- if (!d->ref.ref()) {
- p.detach(d->alloc);
-
- QT_TRY {
- node_copy(reinterpret_cast<Node *>(p.begin()),
- reinterpret_cast<Node *>(p.end()),
- reinterpret_cast<Node *>(l.p.begin()));
- } QT_CATCH(...) {
- QListData::dispose(d);
- QT_RETHROW;
- }
- }
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QList<T>::~QList()
-{
- if (!d->ref.deref())
- dealloc(d);
-}
-
-template <typename T>
-template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator>>
-QList<T>::QList(InputIterator first, InputIterator last)
- : QList()
-{
- QtPrivate::reserveIfForwardIterator(this, first, last);
- std::copy(first, last, std::back_inserter(*this));
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE bool QList<T>::operator==(const QList<T> &l) const
-{
- if (d == l.d)
- return true;
- if (p.size() != l.p.size())
- return false;
- return this->op_eq_impl(l, MemoryLayout());
-}
-
-template <typename T>
-inline bool QList<T>::op_eq_impl(const QList &l, QListData::NotArrayCompatibleLayout) const
-{
- Node *i = reinterpret_cast<Node *>(p.begin());
- Node *e = reinterpret_cast<Node *>(p.end());
- Node *li = reinterpret_cast<Node *>(l.p.begin());
- for (; i != e; ++i, ++li) {
- if (!(i->t() == li->t()))
- return false;
- }
- return true;
-}
-
-template <typename T>
-inline bool QList<T>::op_eq_impl(const QList &l, QListData::ArrayCompatibleLayout) const
-{
- const T *lb = reinterpret_cast<const T*>(l.p.begin());
- const T *b = reinterpret_cast<const T*>(p.begin());
- const T *e = reinterpret_cast<const T*>(p.end());
- return std::equal(b, e, QT_MAKE_CHECKED_ARRAY_ITERATOR(lb, l.p.size()));
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::dealloc(QListData::Data *data)
-{
- node_destruct(reinterpret_cast<Node *>(data->array + data->begin),
- reinterpret_cast<Node *>(data->array + data->end));
- QListData::dispose(data);
-}
-
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE void QList<T>::clear()
-{
- *this = QList<T>();
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE int QList<T>::removeAll(const T &_t)
-{
- int index = indexOf(_t);
- if (index == -1)
- return 0;
-
- const T t = _t;
- detach();
-
- Node *i = reinterpret_cast<Node *>(p.at(index));
- Node *e = reinterpret_cast<Node *>(p.end());
- Node *n = i;
- node_destruct(i);
- while (++i != e) {
- if (i->t() == t)
- node_destruct(i);
- else
- *n++ = *i;
- }
-
- int removedCount = int(e - n);
- d->end -= removedCount;
- return removedCount;
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE bool QList<T>::removeOne(const T &_t)
-{
- int index = indexOf(_t);
- if (index != -1) {
- removeAt(index);
- return true;
- }
- return false;
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE typename QList<T>::iterator QList<T>::erase(typename QList<T>::iterator afirst,
- typename QList<T>::iterator alast)
-{
- Q_ASSERT_X(isValidIterator(afirst), "QList::erase", "The specified iterator argument 'afirst' is invalid");
- Q_ASSERT_X(isValidIterator(alast), "QList::erase", "The specified iterator argument 'alast' is invalid");
-
- if (d->ref.isShared()) {
- // ### A block is erased and a detach is needed. We should shrink and only copy relevant items.
- int offsetfirst = int(afirst.i - reinterpret_cast<Node *>(p.begin()));
- int offsetlast = int(alast.i - reinterpret_cast<Node *>(p.begin()));
- afirst = begin(); // implies detach()
- alast = afirst;
- afirst += offsetfirst;
- alast += offsetlast;
- }
-
- for (Node *n = afirst.i; n < alast.i; ++n)
- node_destruct(n);
- int idx = afirst - begin();
- p.remove(idx, alast - afirst);
- return begin() + idx;
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QList<T> &QList<T>::operator+=(const QList<T> &l)
-{
- if (!l.isEmpty()) {
- if (d == &QListData::shared_null) {
- *this = l;
- } else {
- Node *n = (d->ref.isShared())
- ? detach_helper_grow(INT_MAX, l.size())
- : reinterpret_cast<Node *>(p.append(l.p));
- QT_TRY {
- node_copy(n, reinterpret_cast<Node *>(p.end()),
- reinterpret_cast<Node *>(l.p.begin()));
- } QT_CATCH(...) {
- // restore the old end
- d->end -= int(reinterpret_cast<Node *>(p.end()) - n);
- QT_RETHROW;
- }
- }
- }
- return *this;
-}
-
-template <typename T>
-inline void QList<T>::append(const QList<T> &t)
-{
- *this += t;
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE int QList<T>::indexOf(const T &t, int from) const
-{
- return QtPrivate::indexOf<T, T>(*this, t, from);
-}
-
-namespace QtPrivate
-{
-template <typename T, typename U>
-int indexOf(const QList<T> &list, const U &u, int from)
-{
- typedef typename QList<T>::Node Node;
-
- if (from < 0)
- from = qMax(from + list.p.size(), 0);
- if (from < list.p.size()) {
- Node *n = reinterpret_cast<Node *>(list.p.at(from -1));
- Node *e = reinterpret_cast<Node *>(list.p.end());
- while (++n != e)
- if (n->t() == u)
- return int(n - reinterpret_cast<Node *>(list.p.begin()));
- }
- return -1;
-}
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE int QList<T>::lastIndexOf(const T &t, int from) const
-{
- return QtPrivate::lastIndexOf<T, T>(*this, t, from);
-}
-
-namespace QtPrivate
-{
-template <typename T, typename U>
-int lastIndexOf(const QList<T> &list, const U &u, int from)
-{
- typedef typename QList<T>::Node Node;
-
- if (from < 0)
- from += list.p.size();
- else if (from >= list.p.size())
- from = list.p.size()-1;
- if (from >= 0) {
- Node *b = reinterpret_cast<Node *>(list.p.begin());
- Node *n = reinterpret_cast<Node *>(list.p.at(from + 1));
- while (n-- != b) {
- if (n->t() == u)
- return int(n - b);
- }
- }
- return -1;
-}
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE bool QList<T>::contains(const T &t) const
-{
- return contains_impl(t, MemoryLayout());
-}
-
-template <typename T>
-inline bool QList<T>::contains_impl(const T &t, QListData::NotArrayCompatibleLayout) const
-{
- Node *e = reinterpret_cast<Node *>(p.end());
- Node *i = reinterpret_cast<Node *>(p.begin());
- for (; i != e; ++i)
- if (i->t() == t)
- return true;
- return false;
-}
-
-template <typename T>
-inline bool QList<T>::contains_impl(const T &t, QListData::ArrayCompatibleLayout) const
-{
- const T *b = reinterpret_cast<const T*>(p.begin());
- const T *e = reinterpret_cast<const T*>(p.end());
- return std::find(b, e, t) != e;
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE int QList<T>::count(const T &t) const
-{
- return this->count_impl(t, MemoryLayout());
-}
-
-template <typename T>
-inline int QList<T>::count_impl(const T &t, QListData::NotArrayCompatibleLayout) const
-{
- int c = 0;
- Node *e = reinterpret_cast<Node *>(p.end());
- Node *i = reinterpret_cast<Node *>(p.begin());
- for (; i != e; ++i)
- if (i->t() == t)
- ++c;
- return c;
-}
-
-template <typename T>
-inline int QList<T>::count_impl(const T &t, QListData::ArrayCompatibleLayout) const
-{
- return int(std::count(reinterpret_cast<const T*>(p.begin()),
- reinterpret_cast<const T*>(p.end()),
- t));
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QVector<T> QList<T>::toVector() const
-{
- return QVector<T>(begin(), end());
-}
-
-template <typename T>
-QList<T> QList<T>::fromVector(const QVector<T> &vector)
-{
- return vector.toList();
-}
-
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QList<T> QVector<T>::toList() const
-{
- return QList<T>(begin(), end());
-}
-
-template <typename T>
-QVector<T> QVector<T>::fromList(const QList<T> &list)
-{
- return list.toVector();
-}
-
-Q_DECLARE_SEQUENTIAL_ITERATOR(List)
-Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(List)
-
-template <typename T>
-uint qHash(const QList<T> &key, uint seed = 0)
- noexcept(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)
- noexcept(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)
- noexcept(noexcept(lhs < rhs))
-{
- return rhs < lhs;
-}
-
-template <typename T>
-inline bool operator<=(const QList<T> &lhs, const QList<T> &rhs)
- noexcept(noexcept(lhs < rhs))
-{
- return !(lhs > rhs);
-}
-
-template <typename T>
-inline bool operator>=(const QList<T> &lhs, const QList<T> &rhs)
- noexcept(noexcept(lhs < rhs))
-{
- return !(lhs < rhs);
-}
-
+using QListIterator = QVectorIterator<T>;
QT_END_NAMESPACE
+#endif
#include <QtCore/qbytearraylist.h>
#include <QtCore/qstringlist.h>
-#ifdef Q_CC_MSVC
-#pragma warning( pop )
-#endif
-
#endif // QLIST_H
diff --git a/src/corelib/tools/qmap.h b/src/corelib/tools/qmap.h
index fa736e8413..5cc3116903 100644
--- a/src/corelib/tools/qmap.h
+++ b/src/corelib/tools/qmap.h
@@ -219,7 +219,7 @@ struct QMapData : public QMapDataBase
Node *createNode(const Key &k, const T &v, Node *parent = nullptr, bool left = false)
{
- Node *n = static_cast<Node *>(QMapDataBase::createNode(sizeof(Node), Q_ALIGNOF(Node),
+ Node *n = static_cast<Node *>(QMapDataBase::createNode(sizeof(Node), alignof(Node),
parent, left));
QT_TRY {
new (&n->key) Key(k);
@@ -243,7 +243,7 @@ struct QMapData : public QMapDataBase
void destroy() {
if (root()) {
root()->destroySubTree();
- freeTree(header.left, Q_ALIGNOF(Node));
+ freeTree(header.left, alignof(Node));
}
freeData(this);
}
@@ -356,17 +356,6 @@ public:
inline void detach() { if (d->ref.isShared()) detach_helper(); }
inline bool isDetached() const { return !d->ref.isShared(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable)
- {
- if (sharable == d->ref.isSharable())
- return;
- if (!sharable)
- detach();
- // Don't call on shared_null
- d->ref.setSharable(sharable);
- }
-#endif
inline bool isSharedWith(const QMap<Key, T> &other) const { return d == other.d; }
void clear();
@@ -444,13 +433,8 @@ public:
inline iterator &operator-=(int j) { return *this = *this - j; }
friend inline iterator operator+(int j, iterator k) { return k + j; }
-#ifndef QT_STRICT_ITERATORS
- public:
- inline bool operator==(const const_iterator &o) const
- { return i == o.i; }
- inline bool operator!=(const const_iterator &o) const
- { return i != o.i; }
-#endif
+ inline bool operator==(const const_iterator &o) const { return i == o.i; }
+ inline bool operator!=(const const_iterator &o) const { return i != o.i; }
friend class QMap<Key, T>;
};
friend class iterator;
@@ -469,12 +453,7 @@ public:
Q_DECL_CONSTEXPR inline const_iterator() : i(nullptr) { }
inline const_iterator(const Node *node) : i(node) { }
-#ifdef QT_STRICT_ITERATORS
- explicit inline const_iterator(const iterator &o)
-#else
- inline const_iterator(const iterator &o)
-#endif
- { i = o.i; }
+ inline const_iterator(const iterator &o) { i = o.i; }
inline const Key &key() const { return i->key; }
inline const T &value() const { return i->value; }
@@ -508,11 +487,6 @@ public:
inline const_iterator &operator-=(int j) { return *this = *this - j; }
friend inline const_iterator operator+(int j, const_iterator k) { return k + j; }
-#ifdef QT_STRICT_ITERATORS
- private:
- inline bool operator==(const iterator &o) const { return operator==(const_iterator(o)); }
- inline bool operator!=(const iterator &o) const { return operator!=(const_iterator(o)); }
-#endif
friend class QMap<Key, T>;
};
friend class const_iterator;
diff --git a/src/corelib/tools/qrefcount.h b/src/corelib/tools/qrefcount.h
index 2e5388ad9a..982a9c2bbf 100644
--- a/src/corelib/tools/qrefcount.h
+++ b/src/corelib/tools/qrefcount.h
@@ -53,10 +53,6 @@ class RefCount
public:
inline bool ref() noexcept {
int count = atomic.loadRelaxed();
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- if (count == 0) // !isSharable
- return false;
-#endif
if (count != -1) // !isStatic
atomic.ref();
return true;
@@ -64,32 +60,11 @@ public:
inline bool deref() noexcept {
int count = atomic.loadRelaxed();
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- if (count == 0) // !isSharable
- return false;
-#endif
if (count == -1) // isStatic
return true;
return atomic.deref();
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- bool setSharable(bool sharable) noexcept
- {
- Q_ASSERT(!isShared());
- if (sharable)
- return atomic.testAndSetRelaxed(0, 1);
- else
- return atomic.testAndSetRelaxed(1, 0);
- }
-
- bool isSharable() const noexcept
- {
- // Sharable === Shared ownership.
- return atomic.loadRelaxed() != 0;
- }
-#endif
-
bool isStatic() const noexcept
{
// Persistent object, never deleted
diff --git a/src/corelib/tools/qset.h b/src/corelib/tools/qset.h
index 879e2176f2..f98bb051ec 100644
--- a/src/corelib/tools/qset.h
+++ b/src/corelib/tools/qset.h
@@ -86,9 +86,6 @@ public:
inline void detach() { q_hash.detach(); }
inline bool isDetached() const { return q_hash.isDetached(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable) { q_hash.setSharable(sharable); }
-#endif
inline void clear() { q_hash.clear(); }
@@ -260,12 +257,6 @@ public:
{ QSet<T> result = *this; result -= other; return result; }
QList<T> values() const;
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- Q_DECL_DEPRECATED_X("Use values() instead.")
- QList<T> toList() const { return values(); }
- Q_DECL_DEPRECATED_X("Use QSet<T>(list.begin(), list.end()) instead.")
- static QSet<T> fromList(const QList<T> &list);
-#endif
private:
Hash q_hash;
@@ -397,30 +388,6 @@ Q_OUTOFLINE_TEMPLATE QList<T> QSet<T>::values() const
return result;
}
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-template <typename T>
-Q_OUTOFLINE_TEMPLATE QSet<T> QList<T>::toSet() const
-{
- QSet<T> result;
- result.reserve(size());
- for (int i = 0; i < size(); ++i)
- result.insert(at(i));
- return result;
-}
-
-template <typename T>
-QSet<T> QSet<T>::fromList(const QList<T> &list)
-{
- return list.toSet();
-}
-
-template <typename T>
-QList<T> QList<T>::fromSet(const QSet<T> &set)
-{
- return set.toList();
-}
-#endif
-
Q_DECLARE_SEQUENTIAL_ITERATOR(Set)
#if !defined(QT_NO_JAVA_STYLE_ITERATORS)
diff --git a/src/corelib/tools/qvector.h b/src/corelib/tools/qvector.h
index 62fbdb4a2a..3e98de41f4 100644
--- a/src/corelib/tools/qvector.h
+++ b/src/corelib/tools/qvector.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 Intel Corporation
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
@@ -40,127 +41,266 @@
#ifndef QVECTOR_H
#define QVECTOR_H
-#include <QtCore/qalgorithms.h>
-#include <QtCore/qiterator.h>
-#include <QtCore/qrefcount.h>
-#include <QtCore/qarraydata.h>
+#include <QtCore/qarraydatapointer.h>
+#include <QtCore/qnamespace.h>
#include <QtCore/qhashfunctions.h>
-#include <QtCore/qcontainertools_impl.h>
+#include <QtCore/qiterator.h>
-#include <iterator>
+#include <functional>
+#include <limits>
#include <initializer_list>
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-#include <vector>
-#endif
-#include <stdlib.h>
-#include <string.h>
-
-#include <algorithm>
+#include <type_traits>
QT_BEGIN_NAMESPACE
+namespace QtPrivate {
+ template <typename V, typename U> int indexOf(const QVector<V> &list, const U &u, int from);
+ template <typename V, typename U> int lastIndexOf(const QVector<V> &list, const U &u, int from);
+}
+
+template <typename T> struct QVectorSpecialMethods
+{
+protected:
+ ~QVectorSpecialMethods() = default;
+};
+template <> struct QVectorSpecialMethods<QByteArray>;
+template <> struct QVectorSpecialMethods<QString>;
+
template <typename T>
class QVector
+#ifndef Q_QDOC
+ : public QVectorSpecialMethods<T>
+#endif
{
typedef QTypedArrayData<T> Data;
- Data *d;
+ typedef QArrayDataOps<T> DataOps;
+ typedef QArrayDataPointer<T> DataPointer;
+ class DisableRValueRefs {};
+
+ DataPointer d;
+
+ template <typename V, typename U> friend int QtPrivate::indexOf(const QVector<V> &list, const U &u, int from);
+ template <typename V, typename U> friend int QtPrivate::lastIndexOf(const QVector<V> &list, const U &u, int from);
public:
- inline QVector() noexcept : d(Data::sharedNull()) { }
- explicit QVector(int size);
- QVector(int size, const T &t);
- inline QVector(const QVector<T> &v);
- inline ~QVector() { if (!d->ref.deref()) freeData(d); }
- QVector<T> &operator=(const QVector<T> &v);
- QVector(QVector<T> &&other) noexcept : d(other.d) { other.d = Data::sharedNull(); }
- QVector<T> &operator=(QVector<T> &&other) noexcept
- { QVector moved(std::move(other)); swap(moved); return *this; }
- void swap(QVector<T> &other) noexcept { qSwap(d, other.d); }
- inline QVector(std::initializer_list<T> args);
- QVector<T> &operator=(std::initializer_list<T> args);
- template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator> = true>
- inline QVector(InputIterator first, InputIterator last);
- explicit QVector(QArrayDataPointerRef<T> ref) noexcept : d(ref.ptr) {}
+ typedef T Type;
+ typedef T value_type;
+ typedef value_type *pointer;
+ typedef const value_type *const_pointer;
+ typedef value_type &reference;
+ typedef const value_type &const_reference;
+ typedef int size_type;
+ typedef qptrdiff difference_type;
+ typedef typename Data::iterator iterator;
+ typedef typename Data::const_iterator const_iterator;
+ typedef iterator Iterator;
+ typedef const_iterator ConstIterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef typename DataPointer::parameter_type parameter_type;
+ using rvalue_ref = typename std::conditional<DataPointer::pass_parameter_by_value, DisableRValueRefs, T &&>::type;
- bool operator==(const QVector<T> &v) const;
- inline bool operator!=(const QVector<T> &v) const { return !(*this == v); }
+private:
+ void resize_internal(int i, Qt::Initialization);
+ bool isValidIterator(const_iterator i) const
+ {
+ const std::less<const T*> less = {};
+ return !less(d->end(), i) && !less(i, d->begin());
+ }
+public:
+ QVector(DataPointer dd) noexcept
+ : d(dd)
+ {
+ }
- inline int size() const { return d->size; }
+public:
+ inline QVector() noexcept { }
+ explicit QVector(int size)
+ : d(Data::allocate(size))
+ {
+ if (size)
+ d->appendInitialize(size);
+ }
+ QVector(int size, const T &t)
+ : d(Data::allocate(size))
+ {
+ if (size)
+ d->copyAppend(size, t);
+ }
- inline bool isEmpty() const { return d->size == 0; }
+ inline QVector(const QVector<T> &other) noexcept : d(other.d) {}
+ QVector(QVector<T> &&other) noexcept : d(std::move(other.d)) {}
+ inline QVector(std::initializer_list<T> args)
+ : d(Data::allocate(args.size()))
+ {
+ if (args.size())
+ d->copyAppend(args.begin(), args.end());
+ }
- void resize(int size);
+ ~QVector() /*noexcept(std::is_nothrow_destructible<T>::value)*/ {}
+ QVector<T> &operator=(const QVector<T> &other) { d = other.d; return *this; }
+ QVector &operator=(QVector &&other) noexcept(std::is_nothrow_destructible<T>::value)
+ {
+ d = std::move(other.d);
+ return *this;
+ }
+ QVector<T> &operator=(std::initializer_list<T> args)
+ {
+ d = DataPointer(Data::allocate(args.size()));
+ if (args.size())
+ d->copyAppend(args.begin(), args.end());
+ return *this;
+ }
+ template <typename InputIterator, QtPrivate::IfIsForwardIterator<InputIterator> = true>
+ QVector(InputIterator i1, InputIterator i2)
+ : d(Data::allocate(std::distance(i1, i2)))
+ {
+ if (std::distance(i1, i2))
+ d->copyAppend(i1, i2);
+ }
- inline int capacity() const { return int(d->alloc); }
- void reserve(int size);
- inline void squeeze()
+ template <typename InputIterator, QtPrivate::IfIsNotForwardIterator<InputIterator> = true>
+ QVector(InputIterator i1, InputIterator i2)
+ : QVector()
{
- if (d->size < int(d->alloc)) {
- if (!d->size) {
- *this = QVector<T>();
- return;
- }
- realloc(d->size);
- }
- if (d->capacityReserved) {
- // capacity reserved in a read only memory would be useless
- // this checks avoid writing to such memory.
- d->capacityReserved = 0;
- }
+ QtPrivate::reserveIfForwardIterator(this, i1, i2);
+ std::copy(i1, i2, std::back_inserter(*this));
}
- inline void detach();
- inline bool isDetached() const { return !d->ref.isShared(); }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- inline void setSharable(bool sharable)
+ void swap(QVector<T> &other) noexcept { qSwap(d, other.d); }
+
+ friend bool operator==(const QVector &l, const QVector &r)
{
- if (sharable == d->ref.isSharable())
- return;
- if (!sharable)
- detach();
+ if (l.size() != r.size())
+ return false;
+ if (l.begin() == r.begin())
+ return true;
- if (d == Data::unsharableEmpty()) {
- if (sharable)
- d = Data::sharedNull();
+ // do element-by-element comparison
+ return l.d->compare(l.begin(), r.begin(), l.size());
+ }
+ friend bool operator!=(const QVector &l, const QVector &r)
+ {
+ return !(l == r);
+ }
+
+ int size() const noexcept { return int(d->size); }
+ int count() const noexcept { return size(); }
+ int length() const noexcept { return size(); }
+
+ inline bool isEmpty() const noexcept { return d->size == 0; }
+
+ void resize(int size)
+ {
+ resize_internal(size, Qt::Uninitialized);
+ if (size > this->size())
+ d->appendInitialize(size);
+ }
+ void resize(int size, parameter_type c)
+ {
+ resize_internal(size, Qt::Uninitialized);
+ if (size > this->size())
+ d->copyAppend(size - this->size(), c);
+ }
+
+ inline int capacity() const { return int(d->constAllocatedCapacity()); }
+ void reserve(int size);
+ inline void squeeze();
+
+ void detach() { d.detach(); }
+ bool isDetached() const noexcept { return !d->isShared(); }
+
+ inline bool isSharedWith(const QVector<T> &other) const { return d == other.d; }
+
+ pointer data() { detach(); return d->data(); }
+ const_pointer data() const noexcept { return d->data(); }
+ const_pointer constData() const noexcept { return d->data(); }
+ void clear() {
+ if (!size())
+ return;
+ if (d->needsDetach()) {
+ // must allocate memory
+ DataPointer detached(Data::allocate(d.allocatedCapacity(), d->detachFlags()));
+ d.swap(detached);
} else {
- d->ref.setSharable(sharable);
+ d->truncate(0);
}
- Q_ASSERT(d->ref.isSharable() == sharable);
}
+
+ const_reference at(int i) const noexcept
+ {
+ Q_ASSERT_X(size_t(i) < size_t(d->size), "QVector::at", "index out of range");
+ return data()[i];
+ }
+ reference operator[](int i)
+ {
+ Q_ASSERT_X(size_t(i) < size_t(d->size), "QVector::operator[]", "index out of range");
+ detach();
+ return data()[i];
+ }
+ const_reference operator[](int i) const noexcept { return at(i); }
+ void append(const_reference t)
+ { append(const_iterator(std::addressof(t)), const_iterator(std::addressof(t)) + 1); }
+ void append(const_iterator i1, const_iterator i2);
+ void append(value_type &&t);
+ void append(const QVector<T> &l) { append(l.constBegin(), l.constEnd()); }
+ void prepend(rvalue_ref t);
+ void prepend(const T &t);
+ iterator insert(int i, parameter_type t)
+ { return insert(i, 1, t); }
+ iterator insert(int i, int n, parameter_type t);
+ iterator insert(const_iterator before, parameter_type t)
+ {
+ Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
+ return insert(before, 1, t);
+ }
+ iterator insert(const_iterator before, int n, parameter_type t)
+ {
+ Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
+ return insert(std::distance(constBegin(), before), n, t);
+ }
+ iterator insert(const_iterator before, rvalue_ref t)
+ {
+ Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
+ return insert(std::distance(constBegin(), before), std::move(t));
+ }
+ iterator insert(int i, rvalue_ref t);
+#if 0
+ template< class InputIt >
+ iterator insert( const_iterator pos, InputIt first, InputIt last );
+ iterator insert( const_iterator pos, std::initializer_list<T> ilist );
#endif
+ void replace(int i, const T &t)
+ {
+ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::replace", "index out of range");
+ const T copy(t);
+ data()[i] = copy;
+ }
+ void replace(int i, rvalue_ref t)
+ {
+ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::replace", "index out of range");
+ const T copy(std::move(t));
+ data()[i] = std::move(copy);
+ }
- inline bool isSharedWith(const QVector<T> &other) const { return d == other.d; }
+ void remove(int i, int n = 1);
+ void removeFirst() { Q_ASSERT(!isEmpty()); remove(0); }
+ void removeLast() { Q_ASSERT(!isEmpty()); remove(size() - 1); }
+ value_type takeFirst() { Q_ASSERT(!isEmpty()); value_type v = std::move(first()); remove(0); return v; }
+ value_type takeLast() { Q_ASSERT(!isEmpty()); value_type v = std::move(last()); remove(size() - 1); return v; }
- inline T *data() { detach(); return d->begin(); }
- inline const T *data() const { return d->begin(); }
- inline const T *constData() const { return d->begin(); }
- void clear();
-
- const T &at(int i) const;
- T &operator[](int i);
- const T &operator[](int i) const;
- void append(const T &t);
- void append(T &&t);
- inline void append(const QVector<T> &l) { *this += l; }
- void prepend(T &&t);
- void prepend(const T &t);
- void insert(int i, T &&t);
- void insert(int i, const T &t);
- void insert(int i, int n, const T &t);
- void replace(int i, const T &t);
- void remove(int i);
- void remove(int i, int n);
- inline void removeFirst() { Q_ASSERT(!isEmpty()); erase(d->begin()); }
- inline void removeLast();
- T takeFirst() { Q_ASSERT(!isEmpty()); T r = std::move(first()); removeFirst(); return r; }
- T takeLast() { Q_ASSERT(!isEmpty()); T r = std::move(last()); removeLast(); return r; }
-
- QVector<T> &fill(const T &t, int size = -1);
-
- int indexOf(const T &t, int from = 0) const;
- int lastIndexOf(const T &t, int from = -1) const;
- bool contains(const T &t) const;
- int count(const T &t) const;
+ QVector<T> &fill(parameter_type t, int size = -1);
+
+ int indexOf(const T &t, int from = 0) const noexcept;
+ int lastIndexOf(const T &t, int from = -1) const noexcept;
+ bool contains(const T &t) const noexcept
+ {
+ return indexOf(t) != -1;
+ }
+ int count(const T &t) const noexcept
+ {
+ return int(std::count(&*cbegin(), &*cend(), t));
+ }
// QList compatibility
void removeAt(int i) { remove(i); }
@@ -169,10 +309,10 @@ public:
const const_iterator ce = this->cend(), cit = std::find(this->cbegin(), ce, t);
if (cit == ce)
return 0;
+ int index = cit - this->cbegin();
// next operation detaches, so ce, cit, t may become invalidated:
const T tCopy = t;
- const int firstFoundIdx = std::distance(this->cbegin(), cit);
- const iterator e = end(), it = std::remove(begin() + firstFoundIdx, e, tCopy);
+ const iterator e = end(), it = std::remove(begin() + index, e, tCopy);
const int result = std::distance(it, e);
erase(it, e);
return result;
@@ -185,7 +325,6 @@ public:
remove(i);
return true;
}
- int length() const { return size(); }
T takeAt(int i) { T t = std::move((*this)[i]); remove(i); return t; }
void move(int from, int to)
{
@@ -202,43 +341,26 @@ public:
}
// 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_CLANG_QDOC)
- inline iterator begin() { detach(); return d->begin(); }
- inline const_iterator begin() const noexcept { return d->constBegin(); }
- inline const_iterator cbegin() const noexcept { return d->constBegin(); }
- inline const_iterator constBegin() const noexcept { return d->constBegin(); }
- inline iterator end() { detach(); return d->end(); }
- inline const_iterator end() const noexcept { return d->constEnd(); }
- inline const_iterator cend() const noexcept { return d->constEnd(); }
- inline const_iterator constEnd() const noexcept { return d->constEnd(); }
-#else
- inline iterator begin(iterator = iterator()) { detach(); return d->begin(); }
- inline const_iterator begin(const_iterator = const_iterator()) const noexcept { return d->constBegin(); }
- inline const_iterator cbegin(const_iterator = const_iterator()) const noexcept { return d->constBegin(); }
- inline const_iterator constBegin(const_iterator = const_iterator()) const noexcept { return d->constBegin(); }
- inline iterator end(iterator = iterator()) { detach(); return d->end(); }
- inline const_iterator end(const_iterator = const_iterator()) const noexcept { return d->constEnd(); }
- inline const_iterator cend(const_iterator = const_iterator()) const noexcept { return d->constEnd(); }
- inline const_iterator constEnd(const_iterator = const_iterator()) const noexcept { return d->constEnd(); }
-#endif
+ iterator begin() { detach(); return d->begin(); }
+ iterator end() { detach(); return d->end(); }
+
+ const_iterator begin() const noexcept { return d->constBegin(); }
+ const_iterator end() const noexcept { return d->constEnd(); }
+ const_iterator cbegin() const noexcept { return d->constBegin(); }
+ const_iterator cend() const noexcept { return d->constEnd(); }
+ const_iterator constBegin() const noexcept { return d->constBegin(); }
+ const_iterator constEnd() const noexcept { return d->constEnd(); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }
const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); }
const_reverse_iterator crend() const noexcept { 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); }
- inline iterator insert(iterator before, T &&x);
+
iterator erase(iterator begin, iterator end);
inline iterator erase(iterator pos) { return erase(pos, pos+1); }
// more Qt
- 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(); }
@@ -249,7 +371,7 @@ public:
inline bool endsWith(const T &t) const { return !isEmpty() && last() == t; }
QVector<T> mid(int pos, int len = -1) const;
- T value(int i) const;
+ T value(int i) const { return value(i, T()); }
T value(int i, const T &defaultValue) const;
void swapItemsAt(int i, int j) {
@@ -260,31 +382,22 @@ public:
}
// STL compatibility
- typedef T value_type;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
- typedef value_type& reference;
- typedef const value_type& const_reference;
- typedef qptrdiff difference_type;
- typedef iterator Iterator;
- typedef const_iterator ConstIterator;
- typedef int size_type;
inline void push_back(const T &t) { append(t); }
- void push_back(T &&t) { append(std::move(t)); }
- void push_front(T &&t) { prepend(std::move(t)); }
+ void push_back(rvalue_ref t) { append(std::move(t)); }
+ void push_front(rvalue_ref t) { prepend(std::move(t)); }
inline void push_front(const T &t) { prepend(t); }
void pop_back() { removeLast(); }
void pop_front() { removeFirst(); }
inline bool empty() const
{ return d->size == 0; }
- inline T& front() { return first(); }
+ inline reference front() { return first(); }
inline const_reference front() const { return first(); }
inline reference back() { return last(); }
inline const_reference back() const { return last(); }
void shrink_to_fit() { squeeze(); }
// comfort
- QVector<T> &operator+=(const QVector<T> &l);
+ QVector<T> &operator+=(const QVector<T> &l) { append(l.cbegin(), l.cend()); return *this; }
inline QVector<T> operator+(const QVector<T> &l) const
{ QVector n = *this; n += l; return n; }
inline QVector<T> &operator+=(const T &t)
@@ -293,37 +406,17 @@ public:
{ append(t); return *this; }
inline QVector<T> &operator<<(const QVector<T> &l)
{ *this += l; return *this; }
- inline QVector<T> &operator+=(T &&t)
+ inline QVector<T> &operator+=(rvalue_ref t)
{ append(std::move(t)); return *this; }
- inline QVector<T> &operator<<(T &&t)
+ inline QVector<T> &operator<<(rvalue_ref t)
{ append(std::move(t)); return *this; }
- static QVector<T> fromList(const QList<T> &list);
- QList<T> toList() const;
+ // Consider deprecating in 6.4 or later
+ static QVector<T> fromList(const QVector<T> &list) { return list; }
+ QVector<T> toList() const { return *this; }
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- Q_DECL_DEPRECATED_X("Use QVector<T>(vector.begin(), vector.end()) instead.")
- static inline QVector<T> fromStdVector(const std::vector<T> &vector)
- { return QVector<T>(vector.begin(), vector.end()); }
- Q_DECL_DEPRECATED_X("Use std::vector<T>(vector.begin(), vector.end()) instead.")
- inline std::vector<T> toStdVector() const
- { return std::vector<T>(d->begin(), d->end()); }
-#endif
-private:
- // ### Qt6: remove methods, they are unused
- void reallocData(const int size, const int alloc, QArrayData::AllocationOptions options = QArrayData::Default);
- void reallocData(const int sz) { reallocData(sz, d->alloc); }
- void realloc(int alloc, QArrayData::AllocationOptions options = QArrayData::Default);
- void freeData(Data *d);
- void defaultConstruct(T *from, T *to);
- void copyConstruct(const T *srcFrom, const T *srcTo, T *dstFrom);
- void destruct(T *from, T *to);
- bool isValidIterator(const iterator &i) const
- {
- const std::less<const T*> less = {};
- return !less(d->end(), i) && !less(i, d->begin());
- }
- class AlignmentDummy { Data header; T array[1]; };
+ static inline QVector<T> fromVector(const QVector<T> &vector) { return vector; }
+ inline QVector<T> toVector() const { return *this; }
};
#if defined(__cpp_deduction_guides) && __cpp_deduction_guides >= 201606
@@ -333,747 +426,296 @@ template <typename InputIterator,
QVector(InputIterator, InputIterator) -> QVector<ValueType>;
#endif
-#ifdef Q_CC_MSVC
-// behavior change: an object of POD type constructed with an initializer of the form ()
-// will be default-initialized
-# pragma warning ( push )
-# pragma warning ( disable : 4345 )
-# pragma warning(disable : 4127) // conditional expression is constant
-#endif
-
template <typename T>
-void QVector<T>::defaultConstruct(T *from, T *to)
+inline void QVector<T>::resize_internal(int newSize, Qt::Initialization)
{
- if (QTypeInfo<T>::isComplex) {
- while (from != to) {
- new (from++) T();
+ Q_ASSERT(newSize >= 0);
+
+ if (d->needsDetach() || newSize > capacity()) {
+ // must allocate memory
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize),
+ d->detachFlags()));
+ if (size() && newSize) {
+ detached->copyAppend(constBegin(), constBegin() + qMin(newSize, size()));
}
- } else {
- ::memset(static_cast<void *>(from), 0, (to - from) * sizeof(T));
+ d.swap(detached);
}
-}
-template <typename T>
-void QVector<T>::copyConstruct(const T *srcFrom, const T *srcTo, T *dstFrom)
-{
- if (QTypeInfo<T>::isComplex) {
- while (srcFrom != srcTo)
- new (dstFrom++) T(*srcFrom++);
- } else {
- ::memcpy(static_cast<void *>(dstFrom), static_cast<const void *>(srcFrom), (srcTo - srcFrom) * sizeof(T));
- }
+ if (newSize < size())
+ d->truncate(newSize);
}
template <typename T>
-void QVector<T>::destruct(T *from, T *to)
+void QVector<T>::reserve(int asize)
{
- if (QTypeInfo<T>::isComplex) {
- while (from != to) {
- from++->~T();
+ // capacity() == 0 for immutable data, so this will force a detaching below
+ if (asize <= capacity()) {
+ if (d->flags() & Data::CapacityReserved)
+ return; // already reserved, don't shrink
+ if (!d->isShared()) {
+ // accept current allocation, don't shrink
+ d->flags() |= Data::CapacityReserved;
+ return;
}
}
+
+ DataPointer detached(Data::allocate(qMax(asize, size()),
+ d->detachFlags() | Data::CapacityReserved));
+ detached->copyAppend(constBegin(), constEnd());
+ d.swap(detached);
}
template <typename T>
-inline QVector<T>::QVector(const QVector<T> &v)
+inline void QVector<T>::squeeze()
{
- if (v.d->ref.ref()) {
- d = v.d;
- } else {
- if (v.d->capacityReserved) {
- d = Data::allocate(v.d->alloc);
- Q_CHECK_PTR(d);
- d->capacityReserved = true;
- } else {
- d = Data::allocate(v.d->size);
- Q_CHECK_PTR(d);
- }
- if (d->alloc) {
- copyConstruct(v.d->begin(), v.d->end(), d->begin());
- d->size = v.d->size;
+ if (d->needsDetach() || size() != capacity()) {
+ // must allocate memory
+ DataPointer detached(Data::allocate(size(), d->detachFlags() & ~Data::CapacityReserved));
+ if (size()) {
+ detached->copyAppend(constBegin(), constEnd());
}
+ d.swap(detached);
}
}
-#if defined(Q_CC_MSVC)
-#pragma warning( pop )
-#endif
-
template <typename T>
-void QVector<T>::detach()
+inline void QVector<T>::remove(int i, int n)
{
- if (!isDetached()) {
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- if (!d->alloc)
- d = Data::unsharableEmpty();
- else
-#endif
- realloc(int(d->alloc));
- }
- Q_ASSERT(isDetached());
-}
+ Q_ASSERT_X(size_t(i) + size_t(n) <= size_t(d->size), "QVector::remove", "index out of range");
+ Q_ASSERT_X(n >= 0, "QVector::remove", "invalid count");
-template <typename T>
-void QVector<T>::reserve(int asize)
-{
- if (asize > int(d->alloc))
- realloc(asize);
- if (isDetached()
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- && d != Data::unsharableEmpty()
-#endif
- )
- d->capacityReserved = 1;
- Q_ASSERT(capacity() >= asize);
-}
+ if (n == 0)
+ return;
-template <typename T>
-void QVector<T>::resize(int asize)
-{
- if (asize == d->size)
- return detach();
- if (asize > int(d->alloc) || !isDetached()) { // there is not enough space
- QArrayData::AllocationOptions opt = asize > int(d->alloc) ? QArrayData::Grow : QArrayData::Default;
- realloc(qMax(int(d->alloc), asize), opt);
+ const size_t newSize = size() - n;
+ if (d->needsDetach() ||
+ ((d->flags() & Data::CapacityReserved) == 0
+ && newSize < d->allocatedCapacity()/2)) {
+ // allocate memory
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize),
+ d->detachFlags() & ~(Data::GrowsBackwards | Data::GrowsForward)));
+ const_iterator where = constBegin() + i;
+ if (newSize) {
+ detached->copyAppend(constBegin(), where);
+ detached->copyAppend(where + n, constEnd());
+ }
+ d.swap(detached);
+ } else {
+ // we're detached and we can just move data around
+ d->erase(d->begin() + i, d->begin() + i + n);
}
- if (asize < d->size)
- destruct(begin() + asize, end());
- else
- defaultConstruct(end(), begin() + asize);
- d->size = asize;
-}
-template <typename T>
-inline void QVector<T>::clear()
-{
- if (!d->size)
- return;
- destruct(begin(), end());
- d->size = 0;
}
-template <typename T>
-inline const T &QVector<T>::at(int i) const
-{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::at", "index out of range");
- return d->begin()[i]; }
-template <typename T>
-inline const T &QVector<T>::operator[](int i) const
-{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
- return d->begin()[i]; }
-template <typename T>
-inline T &QVector<T>::operator[](int i)
-{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
- return data()[i]; }
-template <typename T>
-inline void QVector<T>::insert(int i, const T &t)
-{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
- insert(begin() + i, 1, t); }
-template <typename T>
-inline void QVector<T>::insert(int i, int n, const T &t)
-{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
- insert(begin() + i, n, t); }
-template <typename T>
-inline void QVector<T>::insert(int i, T &&t)
-{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
- insert(begin() + i, std::move(t)); }
-template <typename T>
-inline void QVector<T>::remove(int i, int n)
-{ Q_ASSERT_X(i >= 0 && n >= 0 && i + n <= d->size, "QVector<T>::remove", "index out of range");
- erase(d->begin() + i, d->begin() + i + n); }
-template <typename T>
-inline void QVector<T>::remove(int i)
-{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::remove", "index out of range");
- erase(d->begin() + i, d->begin() + i + 1); }
+
template <typename T>
inline void QVector<T>::prepend(const T &t)
-{ insert(begin(), 1, t); }
-template <typename T>
-inline void QVector<T>::prepend(T &&t)
-{ insert(begin(), std::move(t)); }
-
+{ insert(0, 1, t); }
template <typename T>
-inline void QVector<T>::replace(int i, const T &t)
-{
- Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::replace", "index out of range");
- const T copy(t);
- data()[i] = copy;
-}
+void QVector<T>::prepend(rvalue_ref t)
+{ insert(0, std::move(t)); }
-template <typename T>
-QVector<T> &QVector<T>::operator=(const QVector<T> &v)
+template<typename T>
+inline T QVector<T>::value(int i, const T &defaultValue) const
{
- if (v.d != d) {
- QVector<T> tmp(v);
- tmp.swap(*this);
- }
- return *this;
+ return size_t(i) < size_t(d->size) ? at(i) : defaultValue;
}
template <typename T>
-QVector<T>::QVector(int asize)
+inline void QVector<T>::append(const_iterator i1, const_iterator i2)
{
- Q_ASSERT_X(asize >= 0, "QVector::QVector", "Size must be greater than or equal to 0.");
- if (Q_LIKELY(asize > 0)) {
- d = Data::allocate(asize);
- Q_CHECK_PTR(d);
- d->size = asize;
- defaultConstruct(d->begin(), d->end());
+ if (i1 == i2)
+ return;
+ const size_t newSize = size() + std::distance(i1, i2);
+ if (d->needsDetach() || newSize > d->allocatedCapacity()) {
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize),
+ d->detachFlags() | Data::GrowsForward));
+ detached->copyAppend(constBegin(), constEnd());
+ detached->copyAppend(i1, i2);
+ d.swap(detached);
} else {
- d = Data::sharedNull();
+ // we're detached and we can just move data around
+ d->copyAppend(i1, i2);
}
}
template <typename T>
-QVector<T>::QVector(int asize, const T &t)
+inline void QVector<T>::append(value_type &&t)
{
- Q_ASSERT_X(asize >= 0, "QVector::QVector", "Size must be greater than or equal to 0.");
- if (asize > 0) {
- d = Data::allocate(asize);
- Q_CHECK_PTR(d);
- d->size = asize;
- T* i = d->end();
- while (i != d->begin())
- new (--i) T(t);
+ const size_t newSize = size() + 1;
+ const bool isTooSmall = newSize > d->allocatedCapacity();
+ const bool isOverlapping = std::addressof(*d->begin()) <= std::addressof(t)
+ && std::addressof(t) < std::addressof(*d->end());
+ if (isTooSmall || d->needsDetach() || Q_UNLIKELY(isOverlapping)) {
+ typename Data::ArrayOptions flags = d->detachFlags();
+ if (isTooSmall)
+ flags |= Data::GrowsForward;
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize), flags));
+ detached->copyAppend(constBegin(), constEnd());
+ detached->moveAppend(std::addressof(t), std::addressof(t) + 1);
+ d.swap(detached);
} else {
- d = Data::sharedNull();
+ // we're detached and we can just move data around
+ d->moveAppend(std::addressof(t), std::addressof(t) + 1);
}
}
-#if defined(Q_CC_MSVC)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_MSVC(4127) // conditional expression is constant
-#endif // Q_CC_MSVC
-
template <typename T>
-QVector<T>::QVector(std::initializer_list<T> args)
+inline typename QVector<T>::iterator
+QVector<T>::insert(int i, int n, parameter_type t)
{
- if (args.size() > 0) {
- d = Data::allocate(args.size());
- Q_CHECK_PTR(d);
- // std::initializer_list<T>::iterator is guaranteed to be
- // const T* ([support.initlist]/1), so can be memcpy'ed away from by copyConstruct
- copyConstruct(args.begin(), args.end(), d->begin());
- d->size = int(args.size());
- } else {
- d = Data::sharedNull();
- }
-}
+ Q_ASSERT_X(size_t(i) <= size_t(d->size), "QVector<T>::insert", "index out of range");
-template <typename T>
-QVector<T> &QVector<T>::operator=(std::initializer_list<T> args)
-{
- QVector<T> tmp(args);
- tmp.swap(*this);
- return *this;
-}
-
-#if defined(Q_CC_MSVC)
-QT_WARNING_POP
-#endif // Q_CC_MSVC
+ // we don't have a quick exit for n == 0
+ // it's not worth wasting CPU cycles for that
-template <typename T>
-template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator>>
-QVector<T>::QVector(InputIterator first, InputIterator last)
- : QVector()
-{
- QtPrivate::reserveIfForwardIterator(this, first, last);
- std::copy(first, last, std::back_inserter(*this));
-}
-
-template <typename T>
-void QVector<T>::freeData(Data *x)
-{
- destruct(x->begin(), x->end());
- Data::deallocate(x);
-}
+ const size_t newSize = size() + n;
+ if (d->needsDetach() || newSize > d->allocatedCapacity()) {
+ typename Data::ArrayOptions flags = d->detachFlags() | Data::GrowsForward;
+ if (size_t(i) <= newSize / 4)
+ flags |= Data::GrowsBackwards;
-#if defined(Q_CC_MSVC)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_MSVC(4127) // conditional expression is constant
-#endif
-
-template <typename T>
-void QVector<T>::reallocData(const int asize, const int aalloc, QArrayData::AllocationOptions options)
-{
- Q_ASSERT(asize >= 0 && asize <= aalloc);
- Data *x = d;
-
- const bool isShared = d->ref.isShared();
-
- if (aalloc != 0) {
- if (aalloc != int(d->alloc) || isShared) {
- QT_TRY {
- // allocate memory
- x = Data::allocate(aalloc, options);
- Q_CHECK_PTR(x);
- // aalloc is bigger then 0 so it is not [un]sharedEmpty
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Q_ASSERT(x->ref.isSharable() || options.testFlag(QArrayData::Unsharable));
-#endif
- Q_ASSERT(!x->ref.isStatic());
- x->size = asize;
-
- T *srcBegin = d->begin();
- T *srcEnd = asize > d->size ? d->end() : d->begin() + asize;
- T *dst = x->begin();
-
- if (!QTypeInfoQuery<T>::isRelocatable || (isShared && QTypeInfo<T>::isComplex)) {
- QT_TRY {
- if (isShared || !std::is_nothrow_move_constructible<T>::value) {
- // we can not move the data, we need to copy construct it
- while (srcBegin != srcEnd)
- new (dst++) T(*srcBegin++);
- } else {
- while (srcBegin != srcEnd)
- new (dst++) T(std::move(*srcBegin++));
- }
- } QT_CATCH (...) {
- // destruct already copied objects
- destruct(x->begin(), dst);
- QT_RETHROW;
- }
- } else {
- ::memcpy(static_cast<void *>(dst), static_cast<void *>(srcBegin), (srcEnd - srcBegin) * sizeof(T));
- dst += srcEnd - srcBegin;
-
- // destruct unused / not moved data
- if (asize < d->size)
- destruct(d->begin() + asize, d->end());
- }
-
- if (asize > d->size) {
- // construct all new objects when growing
- if (!QTypeInfo<T>::isComplex) {
- ::memset(static_cast<void *>(dst), 0, (static_cast<T *>(x->end()) - dst) * sizeof(T));
- } else {
- QT_TRY {
- while (dst != x->end())
- new (dst++) T();
- } QT_CATCH (...) {
- // destruct already copied objects
- destruct(x->begin(), dst);
- QT_RETHROW;
- }
- }
- }
- } QT_CATCH (...) {
- Data::deallocate(x);
- QT_RETHROW;
- }
- x->capacityReserved = d->capacityReserved;
- } else {
- Q_ASSERT(int(d->alloc) == aalloc); // resize, without changing allocation size
- Q_ASSERT(isDetached()); // can be done only on detached d
- Q_ASSERT(x == d); // in this case we do not need to allocate anything
- if (asize <= d->size) {
- destruct(x->begin() + asize, x->end()); // from future end to current end
- } else {
- defaultConstruct(x->end(), x->begin() + asize); // from current end to future end
- }
- x->size = asize;
- }
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize), flags));
+ const_iterator where = constBegin() + i;
+ detached->copyAppend(constBegin(), where);
+ detached->copyAppend(n, t);
+ detached->copyAppend(where, constEnd());
+ d.swap(detached);
} else {
- x = Data::sharedNull();
- }
- if (d != x) {
- if (!d->ref.deref()) {
- if (!QTypeInfoQuery<T>::isRelocatable || !aalloc || (isShared && QTypeInfo<T>::isComplex)) {
- // data was copy constructed, we need to call destructors
- // or if !alloc we did nothing to the old 'd'.
- freeData(d);
- } else {
- Data::deallocate(d);
- }
- }
- d = x;
- }
-
- Q_ASSERT(d->data());
- Q_ASSERT(uint(d->size) <= d->alloc);
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Q_ASSERT(d != Data::unsharableEmpty());
-#endif
- Q_ASSERT(aalloc ? d != Data::sharedNull() : d == Data::sharedNull());
- Q_ASSERT(d->alloc >= uint(aalloc));
- Q_ASSERT(d->size == asize);
-}
-
-template<typename T>
-void QVector<T>::realloc(int aalloc, QArrayData::AllocationOptions options)
-{
- Q_ASSERT(aalloc >= d->size);
- Data *x = d;
-
- const bool isShared = d->ref.isShared();
-
- QT_TRY {
- // allocate memory
- x = Data::allocate(aalloc, options);
- Q_CHECK_PTR(x);
- // aalloc is bigger then 0 so it is not [un]sharedEmpty
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Q_ASSERT(x->ref.isSharable() || options.testFlag(QArrayData::Unsharable));
-#endif
- Q_ASSERT(!x->ref.isStatic());
- x->size = d->size;
-
- T *srcBegin = d->begin();
- T *srcEnd = d->end();
- T *dst = x->begin();
-
- if (!QTypeInfoQuery<T>::isRelocatable || (isShared && QTypeInfo<T>::isComplex)) {
- QT_TRY {
- if (isShared || !std::is_nothrow_move_constructible<T>::value) {
- // we can not move the data, we need to copy construct it
- while (srcBegin != srcEnd)
- new (dst++) T(*srcBegin++);
- } else {
- while (srcBegin != srcEnd)
- new (dst++) T(std::move(*srcBegin++));
- }
- } QT_CATCH (...) {
- // destruct already copied objects
- destruct(x->begin(), dst);
- QT_RETHROW;
- }
- } else {
- ::memcpy(static_cast<void *>(dst), static_cast<void *>(srcBegin), (srcEnd - srcBegin) * sizeof(T));
- dst += srcEnd - srcBegin;
- }
-
- } QT_CATCH (...) {
- Data::deallocate(x);
- QT_RETHROW;
- }
- x->capacityReserved = d->capacityReserved;
-
- Q_ASSERT(d != x);
- if (!d->ref.deref()) {
- if (!QTypeInfoQuery<T>::isRelocatable || !aalloc || (isShared && QTypeInfo<T>::isComplex)) {
- // data was copy constructed, we need to call destructors
- // or if !alloc we did nothing to the old 'd'.
- freeData(d);
+ // we're detached and we can just move data around
+ if (i == size()) {
+ d->copyAppend(n, t);
} else {
- Data::deallocate(d);
+ T copy(t);
+ d->insert(d.begin() + i, n, copy);
}
}
- d = x;
-
- Q_ASSERT(d->data());
- Q_ASSERT(uint(d->size) <= d->alloc);
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Q_ASSERT(d != Data::unsharableEmpty());
-#endif
- Q_ASSERT(d != Data::sharedNull());
- Q_ASSERT(d->alloc >= uint(aalloc));
-}
-
-#if defined(Q_CC_MSVC)
-QT_WARNING_POP
-#endif
-
-template<typename T>
-Q_OUTOFLINE_TEMPLATE T QVector<T>::value(int i) const
-{
- if (uint(i) >= uint(d->size)) {
- return T();
- }
- return d->begin()[i];
-}
-template<typename T>
-Q_OUTOFLINE_TEMPLATE T QVector<T>::value(int i, const T &defaultValue) const
-{
- return uint(i) >= uint(d->size) ? defaultValue : d->begin()[i];
-}
-
-template <typename T>
-void QVector<T>::append(const T &t)
-{
- const bool isTooSmall = uint(d->size + 1) > d->alloc;
- if (!isDetached() || isTooSmall) {
- T copy(t);
- QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
- realloc(isTooSmall ? d->size + 1 : d->alloc, opt);
-
- if (QTypeInfo<T>::isComplex)
- new (d->end()) T(std::move(copy));
- else
- *d->end() = std::move(copy);
-
- } else {
- if (QTypeInfo<T>::isComplex)
- new (d->end()) T(t);
- else
- *d->end() = t;
- }
- ++d->size;
+ return d.begin() + i;
}
template <typename T>
-void QVector<T>::append(T &&t)
+typename QVector<T>::iterator
+QVector<T>::insert(int i, rvalue_ref t)
{
- const bool isTooSmall = uint(d->size + 1) > d->alloc;
- if (!isDetached() || isTooSmall) {
- QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
- realloc(isTooSmall ? d->size + 1 : d->alloc, opt);
- }
-
- new (d->end()) T(std::move(t));
+ Q_ASSERT_X(size_t(i) <= size_t(d->size), "QVector<T>::insert", "index out of range");
- ++d->size;
-}
-
-template <typename T>
-void QVector<T>::removeLast()
-{
- Q_ASSERT(!isEmpty());
- Q_ASSERT(d->alloc);
-
- if (d->ref.isShared())
- detach();
- --d->size;
- if (QTypeInfo<T>::isComplex)
- (d->data() + d->size)->~T();
-}
-
-template <typename T>
-typename QVector<T>::iterator QVector<T>::insert(iterator before, size_type n, const T &t)
-{
- Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
-
- const auto offset = std::distance(d->begin(), before);
- if (n != 0) {
- const T copy(t);
- if (!isDetached() || d->size + n > int(d->alloc))
- realloc(d->size + n, QArrayData::Grow);
- if (!QTypeInfoQuery<T>::isRelocatable) {
- T *b = d->end();
- T *i = d->end() + n;
- while (i != b)
- new (--i) T;
- i = d->end();
- T *j = i + n;
- b = d->begin() + offset;
- while (i != b)
- *--j = *--i;
- i = b+n;
- while (i != b)
- *--i = copy;
- } else {
- T *b = d->begin() + offset;
- T *i = b + n;
- memmove(static_cast<void *>(i), static_cast<const void *>(b), (d->size - offset) * sizeof(T));
- while (i != b)
- new (--i) T(copy);
- }
- d->size += n;
- }
- return d->begin() + offset;
-}
+ const size_t newSize = size() + 1;
+ if (d->needsDetach() || newSize > d->allocatedCapacity()) {
+ typename Data::ArrayOptions flags = d->detachFlags() | Data::GrowsForward;
+ if (size_t(i) <= newSize / 4)
+ flags |= Data::GrowsBackwards;
-template <typename T>
-typename QVector<T>::iterator QVector<T>::insert(iterator before, T &&t)
-{
- Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
-
- const auto offset = std::distance(d->begin(), before);
- if (!isDetached() || d->size + 1 > int(d->alloc))
- realloc(d->size + 1, QArrayData::Grow);
- if (!QTypeInfoQuery<T>::isRelocatable) {
- T *i = d->end();
- T *j = i + 1;
- T *b = d->begin() + offset;
- // The new end-element needs to be constructed, the rest must be move assigned
- if (i != b) {
- new (--j) T(std::move(*--i));
- while (i != b)
- *--j = std::move(*--i);
- *b = std::move(t);
- } else {
- new (b) T(std::move(t));
- }
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize), flags));
+ const_iterator where = constBegin() + i;
+ detached->copyAppend(constBegin(), where);
+ detached->moveAppend(std::addressof(t), std::addressof(t) + 1);
+ detached->copyAppend(where, constEnd());
+ d.swap(detached);
} else {
- T *b = d->begin() + offset;
- memmove(static_cast<void *>(b + 1), static_cast<const void *>(b), (d->size - offset) * sizeof(T));
- new (b) T(std::move(t));
+ d->insert(d.begin() + i, std::move(t));
}
- d->size += 1;
- return d->begin() + offset;
+ return d.begin() + i;
}
template <typename T>
typename QVector<T>::iterator QVector<T>::erase(iterator abegin, iterator aend)
{
- Q_ASSERT_X(isValidIterator(abegin), "QVector::erase", "The specified iterator argument 'abegin' is invalid");
- Q_ASSERT_X(isValidIterator(aend), "QVector::erase", "The specified iterator argument 'aend' is invalid");
-
- const auto itemsToErase = aend - abegin;
-
- if (!itemsToErase)
- return abegin;
-
- Q_ASSERT(abegin >= d->begin());
- Q_ASSERT(aend <= d->end());
- Q_ASSERT(abegin <= aend);
-
- const auto itemsUntouched = abegin - d->begin();
-
- // FIXME we could do a proper realloc, which copy constructs only needed data.
- // FIXME we are about to delete data - maybe it is good time to shrink?
- // FIXME the shrink is also an issue in removeLast, that is just a copy + reduce of this.
- if (d->alloc) {
- detach();
- abegin = d->begin() + itemsUntouched;
- aend = abegin + itemsToErase;
- if (!QTypeInfoQuery<T>::isRelocatable) {
- iterator moveBegin = abegin + itemsToErase;
- iterator moveEnd = d->end();
- while (moveBegin != moveEnd) {
- if (QTypeInfo<T>::isComplex)
- static_cast<T *>(abegin)->~T();
- new (abegin++) T(*moveBegin++);
- }
- if (abegin < d->end()) {
- // destroy rest of instances
- destruct(abegin, d->end());
- }
- } else {
- destruct(abegin, aend);
- // QTBUG-53605: static_cast<void *> masks clang errors of the form
- // error: destination for this 'memmove' call is a pointer to class containing a dynamic class
- // FIXME maybe use std::is_polymorphic (as soon as allowed) to avoid the memmove
- memmove(static_cast<void *>(abegin), static_cast<void *>(aend),
- (d->size - itemsToErase - itemsUntouched) * sizeof(T));
- }
- d->size -= int(itemsToErase);
- }
- return d->begin() + itemsUntouched;
-}
+ Q_ASSERT_X(isValidIterator(const_iterator(abegin)), "QVector::erase", "The specified iterator argument 'abegin' is invalid");
+ Q_ASSERT_X(isValidIterator(const_iterator(aend)), "QVector::erase", "The specified iterator argument 'aend' is invalid");
+ Q_ASSERT(aend >= abegin);
-template <typename T>
-bool QVector<T>::operator==(const QVector<T> &v) const
-{
- if (d == v.d)
- return true;
- if (d->size != v.d->size)
- return false;
- const T *vb = v.d->begin();
- const T *b = d->begin();
- const T *e = d->end();
- return std::equal(b, e, QT_MAKE_CHECKED_ARRAY_ITERATOR(vb, v.d->size));
-}
+ // d.begin() so we don't detach just yet
+ int i = std::distance(d.begin(), abegin);
+ int n = std::distance(abegin, aend);
+ remove(i, n);
-template <typename T>
-QVector<T> &QVector<T>::fill(const T &from, int asize)
-{
- const T copy(from);
- resize(asize < 0 ? d->size : asize);
- if (d->size) {
- T *i = d->end();
- T *b = d->begin();
- while (i != b)
- *--i = copy;
- }
- return *this;
+ return d.begin() + i;
}
template <typename T>
-QVector<T> &QVector<T>::operator+=(const QVector &l)
+inline QVector<T> &QVector<T>::fill(parameter_type t, int newSize)
{
- if (d->size == 0) {
- *this = l;
+ if (newSize == -1)
+ newSize = size();
+ if (d->needsDetach() || newSize > capacity()) {
+ // must allocate memory
+ DataPointer detached(Data::allocate(d->detachCapacity(newSize),
+ d->detachFlags()));
+ detached->copyAppend(newSize, t);
+ d.swap(detached);
} else {
- uint newSize = d->size + l.d->size;
- const bool isTooSmall = newSize > d->alloc;
- if (!isDetached() || isTooSmall) {
- QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
- realloc(isTooSmall ? newSize : d->alloc, opt);
- }
-
- if (d->alloc) {
- T *w = d->begin() + newSize;
- T *i = l.d->end();
- T *b = l.d->begin();
- while (i != b) {
- if (QTypeInfo<T>::isComplex)
- new (--w) T(*--i);
- else
- *--w = *--i;
- }
- d->size = newSize;
- }
+ // we're detached
+ const T copy(t);
+ d->assign(d.begin(), d.begin() + qMin(size(), newSize), t);
+ if (newSize > size())
+ d->copyAppend(newSize - size(), copy);
}
return *this;
}
-template <typename T>
-int QVector<T>::indexOf(const T &t, int from) const
+namespace QtPrivate {
+template <typename T, typename U>
+int indexOf(const QVector<T> &vector, const U &u, int from)
{
if (from < 0)
- from = qMax(from + d->size, 0);
- if (from < d->size) {
- T* n = d->begin() + from - 1;
- T* e = d->end();
+ from = qMax(from + vector.size(), 0);
+ if (from < vector.size()) {
+ auto n = vector.begin() + from - 1;
+ auto e = vector.end();
while (++n != e)
- if (*n == t)
- return n - d->begin();
+ if (*n == u)
+ return n - vector.begin();
}
return -1;
}
-template <typename T>
-int QVector<T>::lastIndexOf(const T &t, int from) const
+template <typename T, typename U>
+int lastIndexOf(const QVector<T> &vector, const U &u, int from)
{
if (from < 0)
- from += d->size;
- else if (from >= d->size)
- from = d->size-1;
+ from += vector.d->size;
+ else if (from >= vector.size())
+ from = vector.size() - 1;
if (from >= 0) {
- T* b = d->begin();
- T* n = d->begin() + from + 1;
+ auto b = vector.begin();
+ auto n = vector.begin() + from + 1;
while (n != b) {
- if (*--n == t)
+ if (*--n == u)
return n - b;
}
}
return -1;
}
+}
template <typename T>
-bool QVector<T>::contains(const T &t) const
+int QVector<T>::indexOf(const T &t, int from) const noexcept
{
- const T *b = d->begin();
- const T *e = d->end();
- return std::find(b, e, t) != e;
+ return QtPrivate::indexOf<T, T>(*this, t, from);
}
template <typename T>
-int QVector<T>::count(const T &t) const
+int QVector<T>::lastIndexOf(const T &t, int from) const noexcept
{
- const T *b = d->begin();
- const T *e = d->end();
- return int(std::count(b, e, t));
+ return QtPrivate::lastIndexOf(*this, t, from);
}
template <typename T>
-Q_OUTOFLINE_TEMPLATE QVector<T> QVector<T>::mid(int pos, int len) const
+inline QVector<T> QVector<T>::mid(int pos, int len) const
{
using namespace QtPrivate;
- switch (QContainerImplHelper::mid(d->size, &pos, &len)) {
+ switch (QContainerImplHelper::mid(d.size, &pos, &len)) {
case QContainerImplHelper::Null:
case QContainerImplHelper::Empty:
- return QVector<T>();
+ return QVector();
case QContainerImplHelper::Full:
return *this;
case QContainerImplHelper::Subset:
break;
}
- QVector<T> midResult;
- midResult.realloc(len);
- T *srcFrom = d->begin() + pos;
- T *srcTo = d->begin() + pos + len;
- midResult.copyConstruct(srcFrom, srcTo, midResult.data());
- midResult.d->size = len;
- return midResult;
+ // Allocate memory
+ DataPointer copied(Data::allocate(len));
+ copied->copyAppend(constBegin() + pos, constBegin() + pos + len);
+ return copied;
}
Q_DECLARE_SEQUENTIAL_ITERATOR(Vector)
@@ -1153,4 +795,7 @@ QVector<QStringRef> QStringRef::split(QChar sep, Qt::SplitBehavior behavior, Qt:
QT_END_NAMESPACE
+#include <QtCore/qbytearraylist.h>
+#include <QtCore/qstringlist.h>
+
#endif // QVECTOR_H
diff --git a/src/corelib/tools/qvector_msvc.cpp b/src/corelib/tools/qvector_msvc.cpp
index cee343e72b..7e87467d42 100644
--- a/src/corelib/tools/qvector_msvc.cpp
+++ b/src/corelib/tools/qvector_msvc.cpp
@@ -47,12 +47,5 @@
# error "This file must be compiled with no precompiled headers"
#endif
-// invert the setting of QT_STRICT_ITERATORS, whichever it was
-#ifdef QT_STRICT_ITERATORS
-# undef QT_STRICT_ITERATORS
-#else
-# define QT_STRICT_ITERATORS
-#endif
-
// the Q_TEMPLATE_EXTERN at the bottom of qvector.h will do the trick
#include <QtCore/qvector.h>
diff --git a/src/corelib/tools/tools.pri b/src/corelib/tools/tools.pri
index 40c84157cd..230456bef9 100644
--- a/src/corelib/tools/tools.pri
+++ b/src/corelib/tools/tools.pri
@@ -12,6 +12,7 @@ HEADERS += \
tools/qcontainerfwd.h \
tools/qcontainertools_impl.h \
tools/qcryptographichash.h \
+ tools/qflatmap_p.h \
tools/qfreelist_p.h \
tools/qhash.h \
tools/qhashfunctions.h \
@@ -47,7 +48,6 @@ HEADERS += \
tools/qvector.h \
tools/qversionnumber.h
-
SOURCES += \
tools/qarraydata.cpp \
tools/qbitarray.cpp \
diff --git a/src/dbus/doc/snippets/code/doc_src_qdbusadaptors.cpp b/src/dbus/doc/snippets/code/doc_src_qdbusadaptors.cpp
index 0fc7a2b26c..f5d9fe7889 100644
--- a/src/dbus/doc/snippets/code/doc_src_qdbusadaptors.cpp
+++ b/src/dbus/doc/snippets/code/doc_src_qdbusadaptors.cpp
@@ -62,7 +62,6 @@ QString processRequest(const QString &request, const QDBusMessage &message)
data->request = request;
message.setDelayedReply(true);
data->reply = message.createReply();
- QDBusConnection::sessionBus().send(data->reply);
appendRequest(data);
return QString();
diff --git a/src/dbus/doc/src/dbus-adaptors.qdoc b/src/dbus/doc/src/dbus-adaptors.qdoc
index 9ebf0cedf2..3398a45af7 100644
--- a/src/dbus/doc/src/dbus-adaptors.qdoc
+++ b/src/dbus/doc/src/dbus-adaptors.qdoc
@@ -174,9 +174,6 @@
\snippet code/doc_src_qdbusadaptors.cpp 10
- The use of
- \l{QDBusConnection::send()}{QDBusConnection::sessionBus().send(data->reply)}
- is needed to explicitly inform the caller that the response will be delayed.
In this case, the return value is unimportant; we return an arbitrary value
to satisfy the compiler.
diff --git a/src/dbus/qdbusabstractadaptor.cpp b/src/dbus/qdbusabstractadaptor.cpp
index bf0e33e26e..671f7f25d0 100644
--- a/src/dbus/qdbusabstractadaptor.cpp
+++ b/src/dbus/qdbusabstractadaptor.cpp
@@ -276,11 +276,11 @@ void QDBusAdaptorConnector::polish()
std::sort(adaptors.begin(), adaptors.end());
}
-void QDBusAdaptorConnector::relaySlot(void **argv)
+void QDBusAdaptorConnector::relaySlot(QMethodRawArguments argv)
{
QObject *sndr = sender();
if (Q_LIKELY(sndr)) {
- relay(sndr, senderSignalIndex(), argv);
+ relay(sndr, senderSignalIndex(), argv.arguments);
} else {
qWarning("QtDBus: cannot relay signals from parent %s(%p \"%s\") unless they are emitted in the object's thread %s(%p \"%s\"). "
"Current thread is %s(%p \"%s\").",
@@ -333,120 +333,6 @@ void QDBusAdaptorConnector::relay(QObject *senderObj, int lastSignalIdx, void **
emit relaySignal(realObject, senderMetaObject, lastSignalIdx, args);
}
-// our Meta Object
-// modify carefully: this has been hand-edited!
-// the relaySlot slot gets called with the void** array
-
-struct qt_meta_stringdata_QDBusAdaptorConnector_t {
- QByteArrayData data[10];
- char stringdata[96];
-};
-#define QT_MOC_LITERAL(idx, ofs, len) \
- Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
- offsetof(qt_meta_stringdata_QDBusAdaptorConnector_t, stringdata) + ofs \
- - idx * sizeof(QByteArrayData) \
- )
-static const qt_meta_stringdata_QDBusAdaptorConnector_t qt_meta_stringdata_QDBusAdaptorConnector = {
- {
-QT_MOC_LITERAL(0, 0, 21),
-QT_MOC_LITERAL(1, 22, 11),
-QT_MOC_LITERAL(2, 34, 0),
-QT_MOC_LITERAL(3, 35, 3),
-QT_MOC_LITERAL(4, 39, 18),
-QT_MOC_LITERAL(5, 58, 10),
-QT_MOC_LITERAL(6, 69, 3),
-QT_MOC_LITERAL(7, 73, 4),
-QT_MOC_LITERAL(8, 78, 9),
-QT_MOC_LITERAL(9, 88, 6)
- },
- "QDBusAdaptorConnector\0relaySignal\0\0"
- "obj\0const QMetaObject*\0metaObject\0sid\0"
- "args\0relaySlot\0polish\0"
-};
-#undef QT_MOC_LITERAL
-
-static const uint qt_meta_data_QDBusAdaptorConnector[] = {
-
- // content:
- 7, // revision
- 0, // classname
- 0, 0, // classinfo
- 3, 14, // methods
- 0, 0, // properties
- 0, 0, // enums/sets
- 0, 0, // constructors
- 0, // flags
- 1, // signalCount
-
- // signals: name, argc, parameters, tag, flags
- 1, 4, 29, 2, 0x05,
-
- // slots: name, argc, parameters, tag, flags
- 8, 0, 38, 2, 0x0a,
- 9, 0, 39, 2, 0x0a,
-
- // signals: parameters
- QMetaType::Void, QMetaType::QObjectStar, 0x80000000 | 4, QMetaType::Int, QMetaType::QVariantList, 3, 5, 6, 7,
-
- // slots: parameters
- QMetaType::Void,
- QMetaType::Void,
-
- 0 // eod
-};
-
-void QDBusAdaptorConnector::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
-{
- if (_c == QMetaObject::InvokeMetaMethod) {
- Q_ASSERT(staticMetaObject.cast(_o));
- QDBusAdaptorConnector *_t = static_cast<QDBusAdaptorConnector *>(_o);
- switch (_id) {
- case 0: _t->relaySignal((*reinterpret_cast< QObject*(*)>(_a[1])),(*reinterpret_cast< const QMetaObject*(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< const QVariantList(*)>(_a[4]))); break;
- case 1: _t->relaySlot(_a); break; // HAND EDIT: add the _a parameter
- case 2: _t->polish(); break;
- default: ;
- }
- }
-}
-
-const QMetaObject QDBusAdaptorConnector::staticMetaObject = {
- { &QObject::staticMetaObject, qt_meta_stringdata_QDBusAdaptorConnector.data,
- qt_meta_data_QDBusAdaptorConnector, qt_static_metacall, nullptr, nullptr }
-};
-
-const QMetaObject *QDBusAdaptorConnector::metaObject() const
-{
- return &staticMetaObject;
-}
-
-void *QDBusAdaptorConnector::qt_metacast(const char *_clname)
-{
- if (!_clname) return nullptr;
- if (!strcmp(_clname, qt_meta_stringdata_QDBusAdaptorConnector.stringdata))
- return static_cast<void*>(const_cast< QDBusAdaptorConnector*>(this));
- return QObject::qt_metacast(_clname);
-}
-
-int QDBusAdaptorConnector::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
-{
- _id = QObject::qt_metacall(_c, _id, _a);
- if (_id < 0)
- return _id;
- if (_c == QMetaObject::InvokeMetaMethod) {
- if (_id < 3)
- qt_static_metacall(this, _c, _id, _a);
- _id -= 3;
- }
- return _id;
-}
-
-// SIGNAL 0
-void QDBusAdaptorConnector::relaySignal(QObject * _t1, const QMetaObject * _t2, int _t3, const QVariantList & _t4)
-{
- void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) };
- QMetaObject::activate(this, &staticMetaObject, 0, _a);
-}
-
QT_END_NAMESPACE
#endif // QT_NO_DBUS
diff --git a/src/dbus/qdbusabstractadaptor_p.h b/src/dbus/qdbusabstractadaptor_p.h
index 023b3b1be2..404901381b 100644
--- a/src/dbus/qdbusabstractadaptor_p.h
+++ b/src/dbus/qdbusabstractadaptor_p.h
@@ -92,7 +92,7 @@ public:
class QDBusAdaptorConnector: public QObject
{
- Q_OBJECT_FAKE
+ Q_OBJECT
public: // typedefs
struct AdaptorData
@@ -118,12 +118,11 @@ public: // methods
void disconnectAllSignals(QObject *object);
void relay(QObject *sender, int id, void **);
-//public slots:
- void relaySlot(void **);
+public Q_SLOTS:
+ void relaySlot(QMethodRawArguments a);
void polish();
-protected:
-//signals:
+Q_SIGNALS:
void relaySignal(QObject *obj, const QMetaObject *metaObject, int sid, const QVariantList &args);
public: // member variables
diff --git a/src/dbus/qdbusmetaobject.cpp b/src/dbus/qdbusmetaobject.cpp
index 3c529ab755..b549e24066 100644
--- a/src/dbus/qdbusmetaobject.cpp
+++ b/src/dbus/qdbusmetaobject.cpp
@@ -547,7 +547,7 @@ void QDBusMetaObjectGenerator::write(QDBusMetaObject *obj)
obj->d.relatedMetaObjects = nullptr;
obj->d.static_metacall = nullptr;
obj->d.extradata = nullptr;
- obj->d.stringdata = reinterpret_cast<const QByteArrayData *>(string_data);
+ obj->d.stringdata = reinterpret_cast<const uint *>(string_data);
obj->d.superdata = &QDBusAbstractInterface::staticMetaObject;
}
diff --git a/src/dbus/qdbusmisc.cpp b/src/dbus/qdbusmisc.cpp
index c321b7524d..25edac8025 100644
--- a/src/dbus/qdbusmisc.cpp
+++ b/src/dbus/qdbusmisc.cpp
@@ -153,7 +153,7 @@ int qDBusParametersForMethod(const QList<QByteArray> &parameterTypes, QVector<in
QList<QByteArray>::ConstIterator it = parameterTypes.constBegin();
QList<QByteArray>::ConstIterator end = parameterTypes.constEnd();
for ( ; it != end; ++it) {
- const QByteArray &type = *it;
+ QByteArray type = *it;
if (type.endsWith('*')) {
errorMsg = QLatin1String("Pointers are not supported: ") + QLatin1String(type);
return -1;
@@ -180,6 +180,9 @@ int qDBusParametersForMethod(const QList<QByteArray> &parameterTypes, QVector<in
return -1; // not allowed
}
+ if (type.startsWith("QList<"))
+ type = "QVector<" + type.mid(sizeof("QList<") - 1);
+
int id = QMetaType::type(type);
#ifdef QT_BOOTSTRAPPED
// in bootstrap mode QDBusMessage isn't included, thus we need to resolve it manually here
diff --git a/src/gui/configure.json b/src/gui/configure.json
index 4de159d97a..9d9d312048 100644
--- a/src/gui/configure.json
+++ b/src/gui/configure.json
@@ -1638,15 +1638,9 @@
"condition": "features.imageformat_xpm",
"output": [ "publicFeature", "feature" ]
},
- "shortcut": {
- "label": "QShortcut",
- "purpose": "Provides keyboard accelerators and shortcuts.",
- "section": "Kernel",
- "output": [ "publicFeature", "feature" ]
- },
"action": {
- "label": "QAction",
- "purpose": "Provides widget actions.",
+ "label": "Q(Gui)Action(Group)",
+ "purpose": "Provides abstract user interface actions.",
"section": "Kernel",
"output": [ "publicFeature", "feature" ]
},
diff --git a/src/gui/doc/snippets/picture/picture.cpp b/src/gui/doc/snippets/picture/picture.cpp
index 863476fdbf..807c263b19 100644
--- a/src/gui/doc/snippets/picture/picture.cpp
+++ b/src/gui/doc/snippets/picture/picture.cpp
@@ -80,82 +80,3 @@ int main()
painter.end(); // painting done
//! [1]
}
-
- QPicture myPicture;
- {
- // FORMATS
-//! [2]
- const QStringList list = QPicture::inputFormatList();
- for (const QString &string : list)
- myProcessing(string);
-//! [2]
- }
-
- {
- // OUTPUT
-//! [3]
- const QStringList list = QPicture::outputFormatList();
- for (const QString &string : list)
- myProcessing(string);
-//! [3]
- }
-
- {
- // PIC READ
-//! [4]
- QPictureIO iio;
- QPixmap pixmap;
- iio.setFileName("vegeburger.pic");
- if (iio.read()) { // OK
- QPicture picture = iio.picture();
- QPainter painter(&pixmap);
- painter.drawPicture(0, 0, picture);
- }
-//! [4]
- }
-
- {
- QPixmap pixmap;
- // PIC WRITE
-//! [5]
- QPictureIO iio;
- QPicture picture;
- QPainter painter(&picture);
- painter.drawPixmap(0, 0, pixmap);
- iio.setPicture(picture);
- iio.setFileName("vegeburger.pic");
- iio.setFormat("PIC");
- if (iio.write())
- return true; // returned true if written successfully
-//! [5]
- }
-
-}
-
-// SVG READ
-//! [6]
-void readSVG(QPictureIO *picture)
-{
- // read the picture using the picture->ioDevice()
-}
-//! [6]
-
-// SVG WRITE
-//! [7]
-void writeSVG(QPictureIO *picture)
-{
- // write the picture using the picture->ioDevice()
-}
-//! [7]
-
-// USE SVG
-void foo() {
-
-//! [8]
- // add the SVG picture handler
- // ...
-//! [8]
- QPictureIO::defineIOHandler("SVG", 0, 0, readSVG, writeSVG);
- // ...
-
-}
diff --git a/src/gui/doc/src/dontdocument.qdoc b/src/gui/doc/src/dontdocument.qdoc
index b360acefc1..6b50daba88 100644
--- a/src/gui/doc/src/dontdocument.qdoc
+++ b/src/gui/doc/src/dontdocument.qdoc
@@ -27,7 +27,7 @@
/*!
\dontdocument (QTypeInfo QScreenOrientationChangeEvent QApplicationStateChangeEvent
- QImageTextKeyLang QMetaTypeId QAbstractUndoItem
+ QMetaTypeId QAbstractUndoItem
QOpenGLVersionStatus
QOpenGLVersionFunctionsBackend
QOpenGLVersionFunctionsStorage
diff --git a/src/gui/image/image.pri b/src/gui/image/image.pri
index 1f42f28d1e..760b737ec3 100644
--- a/src/gui/image/image.pri
+++ b/src/gui/image/image.pri
@@ -14,7 +14,6 @@ HEADERS += \
image/qpaintengine_pic_p.h \
image/qpicture.h \
image/qpicture_p.h \
- image/qpictureformatplugin.h \
image/qpixmap.h \
image/qpixmap_raster_p.h \
image/qpixmap_blitter_p.h \
@@ -38,7 +37,6 @@ SOURCES += \
image/qimagewriter.cpp \
image/qpaintengine_pic.cpp \
image/qpicture.cpp \
- image/qpictureformatplugin.cpp \
image/qpixmap.cpp \
image/qpixmapcache.cpp \
image/qplatformpixmap.cpp \
@@ -59,9 +57,6 @@ win32:!winrt: SOURCES += image/qpixmap_win.cpp
darwin: OBJECTIVE_SOURCES += image/qimage_darwin.mm
-NO_PCH_SOURCES += image/qimage_compat.cpp
-false: SOURCES += $$NO_PCH_SOURCES # Hack for QtCreator
-
# Built-in image format support
HEADERS += \
image/qbmphandler_p.h \
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index 3ddc52bed4..08b1373f96 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -1381,11 +1381,7 @@ int QImage::colorCount() const
\sa colorTable(), setColor(), {QImage#Image Transformations}{Image
Transformations}
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QImage::setColorTable(const QVector<QRgb> &colors)
-#else
-void QImage::setColorTable(const QVector<QRgb> colors)
-#endif
{
if (!d)
return;
@@ -1395,11 +1391,7 @@ void QImage::setColorTable(const QVector<QRgb> colors)
if (!d)
return;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
d->colortable = colors;
-#else
- d->colortable = std::move(const_cast<QVector<QRgb>&>(colors));
-#endif
d->has_alpha_clut = false;
for (int i = 0; i < d->colortable.size(); ++i) {
if (qAlpha(d->colortable.at(i)) != 255) {
@@ -1472,25 +1464,6 @@ void QImage::setDevicePixelRatio(qreal scaleFactor)
d->devicePixelRatio = scaleFactor;
}
-#if QT_DEPRECATED_SINCE(5, 10)
-/*!
- \since 4.6
- \obsolete
- Returns the number of bytes occupied by the image data.
-
- Note this method should never be called on an image larger than 2 gigabytes.
- Instead use sizeInBytes().
-
- \sa sizeInBytes(), bytesPerLine(), bits(), {QImage#Image Information}{Image
- Information}
-*/
-int QImage::byteCount() const
-{
- Q_ASSERT(!d || d->nbytes < std::numeric_limits<int>::max());
- return d ? int(d->nbytes) : 0;
-}
-#endif
-
/*!
\since 5.10
Returns the image data size in bytes.
@@ -1510,17 +1483,10 @@ qsizetype QImage::sizeInBytes() const
\sa scanLine()
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
qsizetype QImage::bytesPerLine() const
{
return d ? d->bytes_per_line : 0;
}
-#else
-int QImage::bytesPerLine() const
-{
- return d ? d->bytes_per_line : 0;
-}
-#endif
/*!
@@ -4054,71 +4020,10 @@ void QImage::setText(const QString &key, const QString &value)
}
/*!
- \fn QString QImage::text(const char* key, const char* language) const
- \obsolete
-
- Returns the text recorded for the given \a key in the given \a
- language, or in a default language if \a language is 0.
-
- Use text() instead.
-
- The language the text is recorded in is no longer relevant since
- the text is always set using QString and UTF-8 representation.
-*/
-
-/*!
- \fn QString QImage::text(const QImageTextKeyLang& keywordAndLanguage) const
- \overload
- \obsolete
-
- Returns the text recorded for the given \a keywordAndLanguage.
-
- Use text() instead.
-
- The language the text is recorded in is no longer relevant since
- the text is always set using QString and UTF-8 representation.
-*/
-
-/*!
- \fn void QImage::setText(const char* key, const char* language, const QString& text)
- \obsolete
-
- Sets the image text to the given \a text and associate it with the
- given \a key. The text is recorded in the specified \a language,
- or in a default language if \a language is 0.
-
- Use setText() instead.
-
- The language the text is recorded in is no longer relevant since
- the text is always set using QString and UTF-8 representation.
-
- \omit
- Records string \a for the keyword \a key. The \a key should be
- a portable keyword recognizable by other software - some suggested
- values can be found in
- \l{http://www.libpng.org/pub/png/spec/1.2/png-1.2-pdg.html#C.Anc-text}
- {the PNG specification}. \a s can be any text. \a lang should
- specify the language code (see
- \l{http://www.rfc-editor.org/rfc/rfc1766.txt}{RFC 1766}) or 0.
- \endomit
-*/
-
-/*
- Sets the image bits to the \a pixmap contents and returns a
- reference to the image.
-
- If the image shares data with other images, it will first
- dereference the shared data.
-
- Makes a call to QPixmap::convertToImage().
-*/
-
-/*!
\internal
Used by QPainter to retrieve a paint engine for the image.
*/
-
QPaintEngine *QImage::paintEngine() const
{
if (!d)
@@ -4364,22 +4269,6 @@ bool qt_xForm_helper(const QTransform &trueMat, int xoffset, int type, int depth
#undef IWX_LSB
#undef IWX_PIX
-/*! \fn int QImage::serialNumber() const
- \obsolete
- Returns a number that identifies the contents of this
- QImage object. Distinct QImage objects can only have the same
- serial number if they refer to the same contents (but they don't
- have to).
-
- Use cacheKey() instead.
-
- \warning The serial number doesn't necessarily change when the
- image is altered. This means that it may be dangerous to use
- it as a cache key.
-
- \sa operator==()
-*/
-
/*!
Returns a number that identifies the contents of this QImage
object. Distinct QImage objects can only have the same key if they
@@ -5085,50 +4974,6 @@ QDebug operator<<(QDebug dbg, const QImage &i)
}
#endif
-/*!
- \fn void QImage::setNumColors(int n)
- \obsolete
-
- Resizes the color table to contain \a n entries.
-
- \sa setColorCount()
- */
-
-/*!
- \fn int QImage::numBytes() const
- \obsolete
-
- Returns the number of bytes occupied by the image data.
-
- \sa sizeInBytes()
- */
-
-/*!
- \fn QStringList QImage::textLanguages() const
- \obsolete
-
- Returns the language identifiers for which some texts are recorded.
- Note that if you want to iterate over the list, you should iterate over a copy.
-
- The language the text is recorded in is no longer relevant since the text is
- always set using QString and UTF-8 representation.
-
- \sa textKeys()
- */
-
-/*!
- \fn QList<QImageTextKeyLang> QImage::textList() const
- \obsolete
-
- Returns a list of QImageTextKeyLang objects that enumerate all the texts
- key/language pairs set for this image.
-
- The language the text is recorded in is no longer relevant since the text
- is always set using QString and UTF-8 representation.
-
- \sa textKeys()
- */
-
static Q_CONSTEXPR QPixelFormat pixelformats[] = {
//QImage::Format_Invalid:
QPixelFormat(),
diff --git a/src/gui/image/qimage.h b/src/gui/image/qimage.h
index 115071c16e..b8df4b83d1 100644
--- a/src/gui/image/qimage.h
+++ b/src/gui/image/qimage.h
@@ -50,10 +50,6 @@
#include <QtCore/qrect.h>
#include <QtCore/qstring.h>
-#if QT_DEPRECATED_SINCE(5, 0)
-#include <QtCore/qstringlist.h>
-#endif
-
#if defined(Q_OS_DARWIN) || defined(Q_QDOC)
Q_FORWARD_DECLARE_MUTABLE_CG_TYPE(CGImage);
#endif
@@ -68,31 +64,9 @@ class QMatrix;
class QStringList;
class QTransform;
class QVariant;
-template <class T> class QList;
template <class T> class QVector;
struct QImageData;
-class QImageDataMisc; // internal
-#if QT_DEPRECATED_SINCE(5, 0)
-class QImageTextKeyLang {
-public:
- QT_DEPRECATED QImageTextKeyLang(const char* k, const char* l) : key(k), lang(l) { }
- QT_DEPRECATED QImageTextKeyLang() { }
-
- QByteArray key;
- QByteArray lang;
-
- bool operator< (const QImageTextKeyLang& other) const
- { return key < other.key || (key==other.key && lang < other.lang); }
- bool operator== (const QImageTextKeyLang& other) const
- { return key==other.key && lang==other.lang; }
- inline bool operator!= (const QImageTextKeyLang &other) const
- { return !operator==(other); }
-private:
- friend class QImage;
- QImageTextKeyLang(bool /*dummy*/) {}
-};
-#endif
typedef void (*QImageCleanupFunction)(void*);
@@ -179,7 +153,6 @@ public:
Format format() const;
-#if defined(Q_COMPILER_REF_QUALIFIERS) && !defined(QT_COMPILING_QIMAGE_COMPAT_CPP)
Q_REQUIRED_RESULT Q_ALWAYS_INLINE QImage convertToFormat(Format f, Qt::ImageConversionFlags flags = Qt::AutoColor) const &
{ return convertToFormat_helper(f, flags); }
Q_REQUIRED_RESULT Q_ALWAYS_INLINE QImage convertToFormat(Format f, Qt::ImageConversionFlags flags = Qt::AutoColor) &&
@@ -189,9 +162,6 @@ public:
else
return convertToFormat_helper(f, flags);
}
-#else
- Q_REQUIRED_RESULT QImage convertToFormat(Format f, Qt::ImageConversionFlags flags = Qt::AutoColor) const;
-#endif
Q_REQUIRED_RESULT QImage convertToFormat(Format f, const QVector<QRgb> &colorTable, Qt::ImageConversionFlags flags = Qt::AutoColor) const;
bool reinterpretAsFormat(Format f);
@@ -217,19 +187,12 @@ public:
const uchar *bits() const;
const uchar *constBits() const;
-#if QT_DEPRECATED_SINCE(5, 10)
- QT_DEPRECATED_X("Use sizeInBytes") int byteCount() const;
-#endif
qsizetype sizeInBytes() const;
uchar *scanLine(int);
const uchar *scanLine(int) const;
const uchar *constScanLine(int) const;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
qsizetype bytesPerLine() const;
-#else
- int bytesPerLine() const;
-#endif
bool valid(int x, int y) const;
bool valid(const QPoint &pt) const;
@@ -250,11 +213,7 @@ public:
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);
-#else
- void setColorTable(const QVector<QRgb> colors);
-#endif
qreal devicePixelRatio() const;
void setDevicePixelRatio(qreal scaleFactor);
@@ -286,7 +245,6 @@ public:
static QMatrix trueMatrix(const QMatrix &, int w, int h);
QImage transformed(const QTransform &matrix, Qt::TransformationMode mode = Qt::FastTransformation) const;
static QTransform trueMatrix(const QTransform &, int w, int h);
-#if defined(Q_COMPILER_REF_QUALIFIERS) && !defined(QT_COMPILING_QIMAGE_COMPAT_CPP)
QImage mirrored(bool horizontally = false, bool vertically = true) const &
{ return mirrored_helper(horizontally, vertically); }
QImage &&mirrored(bool horizontally = false, bool vertically = true) &&
@@ -295,10 +253,6 @@ public:
{ return rgbSwapped_helper(); }
QImage &&rgbSwapped() &&
{ rgbSwapped_inplace(); return std::move(*this); }
-#else
- QImage mirrored(bool horizontally = false, bool vertically = true) const;
- QImage rgbSwapped() const;
-#endif
void invertPixels(InvertMode = InvertRgb);
QColorSpace colorSpace() const;
@@ -321,9 +275,6 @@ public:
inline static QImage fromData(const QByteArray &data, const char *format = nullptr)
{ return fromData(reinterpret_cast<const uchar *>(data.constData()), data.size(), format); }
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline int serialNumber() const { return cacheKey() >> 32; }
-#endif
qint64 cacheKey() const;
QPaintEngine *paintEngine() const override;
@@ -349,20 +300,6 @@ public:
CGImageRef toCGImage() const Q_DECL_CF_RETURNS_RETAINED;
#endif
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline QString text(const char *key, const char *lang = nullptr) const;
- QT_DEPRECATED inline QList<QImageTextKeyLang> textList() const;
- QT_DEPRECATED inline QStringList textLanguages() const;
- QT_DEPRECATED inline QString text(const QImageTextKeyLang&) const;
- QT_DEPRECATED inline void setText(const char* key, const char* lang, const QString&);
-#endif
-
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline int numColors() const;
- QT_DEPRECATED inline void setNumColors(int);
- QT_DEPRECATED inline int numBytes() const;
-#endif
-
protected:
virtual int metric(PaintDeviceMetric metric) const override;
QImage mirrored_helper(bool horizontal, bool vertical) const;
@@ -397,99 +334,6 @@ inline void QImage::setPixel(const QPoint &pt, uint index_or_rgb) { setPixel(pt.
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)
-
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
-
-inline QString QImage::text(const char* key, const char* lang) const
-{
- if (!d)
- return QString();
- QString k = QString::fromLatin1(key);
- if (lang && *lang)
- k += QLatin1Char('/') + QString::fromLatin1(lang);
- return text(k);
-}
-
-inline QList<QImageTextKeyLang> QImage::textList() const
-{
- QList<QImageTextKeyLang> imageTextKeys;
- if (!d)
- return imageTextKeys;
- QStringList keys = textKeys();
- for (int i = 0; i < keys.size(); ++i) {
- int index = keys.at(i).indexOf(QLatin1Char('/'));
- if (index > 0) {
- QImageTextKeyLang tkl(true);
- tkl.key = keys.at(i).left(index).toLatin1();
- tkl.lang = keys.at(i).mid(index+1).toLatin1();
- imageTextKeys += tkl;
- }
- }
-
- return imageTextKeys;
-}
-
-inline QStringList QImage::textLanguages() const
-{
- if (!d)
- return QStringList();
- QStringList keys = textKeys();
- QStringList languages;
- for (int i = 0; i < keys.size(); ++i) {
- int index = keys.at(i).indexOf(QLatin1Char('/'));
- if (index > 0)
- languages += keys.at(i).mid(index+1);
- }
-
- return languages;
-}
-
-inline QString QImage::text(const QImageTextKeyLang&kl) const
-{
- if (!d)
- return QString();
- QString k = QString::fromLatin1(kl.key.constData());
- if (!kl.lang.isEmpty())
- k += QLatin1Char('/') + QString::fromLatin1(kl.lang.constData());
- return text(k);
-}
-
-inline void QImage::setText(const char* key, const char* lang, const QString &s)
-{
- if (!d)
- return;
- detach();
-
- // In case detach() ran out of memory
- if (!d)
- return;
-
- QString k = QString::fromLatin1(key);
- if (lang && *lang)
- k += QLatin1Char('/') + QString::fromLatin1(lang);
- setText(k, s);
-}
-
-QT_WARNING_POP
-
-inline int QImage::numColors() const
-{
- return colorCount();
-}
-
-inline void QImage::setNumColors(int n)
-{
- setColorCount(n);
-}
-
-inline int QImage::numBytes() const
-{
- return int(sizeInBytes());
-}
-#endif
-
// QImage stream functions
#if !defined(QT_NO_DATASTREAM)
diff --git a/src/gui/image/qimage_p.h b/src/gui/image/qimage_p.h
index 0930955f5a..9277472c3c 100644
--- a/src/gui/image/qimage_p.h
+++ b/src/gui/image/qimage_p.h
@@ -140,7 +140,7 @@ QImageData::calculateImageParameters(qsizetype width, qsizetype height, qsizetyp
qsizetype dummy;
if (mul_overflow(height, qsizetype(sizeof(uchar *)), &dummy))
return invalid; // why is this here?
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
+#if 1 || QT_VERSION < QT_VERSION_CHECK(6,0,0) // ### can only fix this if QImage dimensions are not int anymore
// Disallow images where width * depth calculations might overflow
if (width > (INT_MAX - 31) / depth)
return invalid;
diff --git a/src/gui/image/qpicture.cpp b/src/gui/image/qpicture.cpp
index 3a32cc7f15..d469ac8aae 100644
--- a/src/gui/image/qpicture.cpp
+++ b/src/gui/image/qpicture.cpp
@@ -264,14 +264,14 @@ void QPicture::setData(const char* data, uint size)
\sa save()
*/
-bool QPicture::load(const QString &fileName, const char *format)
+bool QPicture::load(const QString &fileName)
{
QFile f(fileName);
if (!f.open(QIODevice::ReadOnly)) {
operator=(QPicture());
return false;
}
- return load(&f, format);
+ return load(&f);
}
/*!
@@ -280,21 +280,8 @@ bool QPicture::load(const QString &fileName, const char *format)
\a dev is the device to use for loading.
*/
-bool QPicture::load(QIODevice *dev, const char *format)
+bool QPicture::load(QIODevice *dev)
{
- if(format) {
-#ifndef QT_NO_PICTUREIO
- QPictureIO io(dev, format);
- if (io.read()) {
- operator=(io.picture());
- return true;
- }
-#endif
- qWarning("QPicture::load: No such picture format: %s", format);
- operator=(QPicture());
- return false;
- }
-
detach();
QByteArray a = dev->readAll();
@@ -312,7 +299,7 @@ bool QPicture::load(QIODevice *dev, const char *format)
\sa load()
*/
-bool QPicture::save(const QString &fileName, const char *format)
+bool QPicture::save(const QString &fileName)
{
if (paintingActive()) {
qWarning("QPicture::save: still being painted on. "
@@ -320,27 +307,10 @@ bool QPicture::save(const QString &fileName, const char *format)
return false;
}
-
- if(format) {
-#ifndef QT_NO_PICTUREIO
- QPictureIO io(fileName, format);
- bool result = io.write();
- if (result) {
- operator=(io.picture());
- } else if (format)
-#else
- bool result = false;
-#endif
- {
- qWarning("QPicture::save: No such picture format: %s", format);
- }
- return result;
- }
-
QFile f(fileName);
if (!f.open(QIODevice::WriteOnly))
return false;
- return save(&f, format);
+ return save(&f);
}
/*!
@@ -349,7 +319,7 @@ bool QPicture::save(const QString &fileName, const char *format)
\a dev is the device to use for saving.
*/
-bool QPicture::save(QIODevice *dev, const char *format)
+bool QPicture::save(QIODevice *dev)
{
if (paintingActive()) {
qWarning("QPicture::save: still being painted on. "
@@ -357,22 +327,6 @@ bool QPicture::save(QIODevice *dev, const char *format)
return false;
}
- if(format) {
-#ifndef QT_NO_PICTUREIO
- QPictureIO io(dev, format);
- bool result = io.write();
- if (result) {
- operator=(io.picture());
- } else if (format)
-#else
- bool result = false;
-#endif
- {
- qWarning("QPicture::save: No such picture format: %s", format);
- }
- return result;
- }
-
dev->write(d_func()->pictb.buffer(), d_func()->pictb.buffer().size());
return true;
}
@@ -1189,780 +1143,6 @@ QDataStream &operator>>(QDataStream &s, QPicture &r)
}
#endif // QT_NO_DATASTREAM
-
-#ifndef QT_NO_PICTUREIO
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qregexp.h"
-#include "qpictureformatplugin.h"
-QT_END_INCLUDE_NAMESPACE
-
-#if QT_DEPRECATED_SINCE(5, 10)
-/*!
- \obsolete
-
- Returns a string that specifies the picture format of the file \a
- fileName, or \nullptr if the file cannot be read or if the format
- is not recognized.
-
- \sa load(), save()
-*/
-
-const char* QPicture::pictureFormat(const QString &fileName)
-{
- const QByteArray format = QPictureIO::pictureFormat(fileName);
- // This function returns a const char * from a QByteArray.
- // Double check that the QByteArray is not detached, otherwise
- // we would return a dangling pointer.
- Q_ASSERT(!format.isDetached());
- return format;
-}
-
-/*!
- \obsolete
-
- Returns a list of picture formats that are supported for picture
- input.
-
- \sa outputFormats(), inputFormatList(), QPictureIO
-*/
-QList<QByteArray> QPicture::inputFormats()
-{
- return QPictureIO::inputFormats();
-}
-
-static QStringList qToStringList(const QList<QByteArray> &arr)
-{
- QStringList list;
- const int count = arr.count();
- list.reserve(count);
- for (int i = 0; i < count; ++i)
- list.append(QString::fromLatin1(arr.at(i)));
- return list;
-}
-
-/*!
- \obsolete
-
- Returns a list of picture formats that are supported for picture
- input.
-
- Note that if you want to iterate over the list, you should iterate
- over a copy, e.g.
- \snippet picture/picture.cpp 2
-
- \sa outputFormatList(), inputFormats(), QPictureIO
-*/
-QStringList QPicture::inputFormatList()
-{
- return qToStringList(QPictureIO::inputFormats());
-}
-
-
-/*!
- \obsolete
-
- Returns a list of picture formats that are supported for picture
- output.
-
- Note that if you want to iterate over the list, you should iterate
- over a copy, e.g.
- \snippet picture/picture.cpp 3
-
- \sa inputFormatList(), outputFormats(), QPictureIO
-*/
-QStringList QPicture::outputFormatList()
-{
- return qToStringList(QPictureIO::outputFormats());
-}
-
-/*!
- \obsolete
-
- Returns a list of picture formats that are supported for picture
- output.
-
- \sa inputFormats(), outputFormatList(), QPictureIO
-*/
-QList<QByteArray> QPicture::outputFormats()
-{
- return QPictureIO::outputFormats();
-}
-#endif // QT_DEPRECATED_SINCE(5, 10)
-
-/*****************************************************************************
- QPictureIO member functions
- *****************************************************************************/
-
-/*!
- \obsolete
-
- \class QPictureIO
-
- \brief The QPictureIO class contains parameters for loading and
- saving pictures.
-
- \ingroup painting
- \ingroup io
- \inmodule QtGui
-
- QPictureIO contains a QIODevice object that is used for picture data
- I/O. The programmer can install new picture file formats in addition
- to those that Qt provides.
-
- You don't normally need to use this class; QPicture::load(),
- QPicture::save().
-
- \sa QPicture, QPixmap, QFile
-*/
-
-struct QPictureIOData
-{
- QPicture pi; // picture
- int iostat; // IO status
- QByteArray frmt; // picture format
- QIODevice *iodev; // IO device
- QString fname; // file name
- QString descr; // picture description
- const char *parameters;
- int quality;
- float gamma;
-};
-
-/*!
- Constructs a QPictureIO object with all parameters set to zero.
-*/
-
-QPictureIO::QPictureIO()
-{
- init();
-}
-
-/*!
- Constructs a QPictureIO object with the I/O device \a ioDevice and a
- \a format tag.
-*/
-
-QPictureIO::QPictureIO(QIODevice *ioDevice, const char *format)
-{
- init();
- d->iodev = ioDevice;
- d->frmt = format;
-}
-
-/*!
- Constructs a QPictureIO object with the file name \a fileName and a
- \a format tag.
-*/
-
-QPictureIO::QPictureIO(const QString &fileName, const char* format)
-{
- init();
- d->frmt = format;
- d->fname = fileName;
-}
-
-/*!
- Contains initialization common to all QPictureIO constructors.
-*/
-
-void QPictureIO::init()
-{
- d = new QPictureIOData();
- d->parameters = nullptr;
- d->quality = -1; // default quality of the current format
- d->gamma=0.0f;
- d->iostat = 0;
- d->iodev = nullptr;
-}
-
-/*!
- Destroys the object and all related data.
-*/
-
-QPictureIO::~QPictureIO()
-{
- if (d->parameters)
- delete [] d->parameters;
- delete d;
-}
-
-
-/*****************************************************************************
- QPictureIO picture handler functions
- *****************************************************************************/
-
-class QPictureHandler
-{
-public:
- QPictureHandler(const char *f, const char *h, const QByteArray& fl,
- picture_io_handler r, picture_io_handler w);
- QByteArray format; // picture format
- QRegExp header; // picture header pattern
- enum TMode { Untranslated=0, TranslateIn, TranslateInOut } text_mode;
- picture_io_handler read_picture; // picture read function
- picture_io_handler write_picture; // picture write function
- bool obsolete; // support not "published"
-};
-
-QPictureHandler::QPictureHandler(const char *f, const char *h, const QByteArray& fl,
- picture_io_handler r, picture_io_handler w)
- : format(f), header(QString::fromLatin1(h))
-{
- text_mode = Untranslated;
- if (fl.contains('t'))
- text_mode = TranslateIn;
- else if (fl.contains('T'))
- text_mode = TranslateInOut;
- obsolete = fl.contains('O');
- read_picture = r;
- write_picture = w;
-}
-
-typedef QList<QPictureHandler *> QPHList;
-Q_GLOBAL_STATIC(QPHList, pictureHandlers)
-
-void qt_init_picture_plugins()
-{
- typedef QMultiMap<int, QString> PluginKeyMap;
- typedef PluginKeyMap::const_iterator PluginKeyMapConstIterator;
-
- static QBasicMutex mutex;
- const auto locker = qt_scoped_lock(mutex);
- static QFactoryLoader loader(QPictureFormatInterface_iid,
- QStringLiteral("/pictureformats"));
-
- const PluginKeyMap keyMap = loader.keyMap();
- const PluginKeyMapConstIterator cend = keyMap.constEnd();
- for (PluginKeyMapConstIterator it = keyMap.constBegin(); it != cend; ++it) {
- if (QPictureFormatPlugin *format = qobject_cast<QPictureFormatPlugin*>(loader.instance(it.key())))
- format->installIOHandler(it.value());
- }
-}
-
-static void cleanup()
-{
- // make sure that picture handlers are delete before plugin manager
- if (QPHList *list = pictureHandlers()) {
- qDeleteAll(*list);
- list->clear();
- }
-}
-
-void qt_init_picture_handlers() // initialize picture handlers
-{
- static QBasicAtomicInt done = Q_BASIC_ATOMIC_INITIALIZER(0);
- if (done.testAndSetRelaxed(0, 1)) {
- qAddPostRoutine(cleanup);
- }
-}
-
-static QPictureHandler *get_picture_handler(const char *format)
-{ // get pointer to handler
- qt_init_picture_handlers();
- qt_init_picture_plugins();
- if (QPHList *list = pictureHandlers()) {
- for (int i = 0; i < list->size(); ++i) {
- if (list->at(i)->format == format)
- return list->at(i);
- }
- }
- return nullptr; // no such handler
-}
-
-
-/*!
- Defines a picture I/O handler for the picture format called \a
- format, which is recognized using the regular
- expression defined in \a header, read using \a readPicture and
- written using \a writePicture.
-
- \a flags is a string of single-character flags for this format.
- The only flag defined currently is T (upper case), so the only
- legal value for \a flags are "T" and the empty string. The "T"
- flag means that the picture file is a text file, and Qt should treat
- all newline conventions as equivalent. (XPM files and some PPM
- files are text files for example.)
-
- \a format is used to select a handler to write a QPicture; \a header
- is used to select a handler to read an picture file.
-
- If \a readPicture is \nullptr, the QPictureIO will not be able
- to read pictures in \a format. If \a writePicture is \nullptr,
- the QPictureIO will not be able to write pictures in \a format. If
- both are null, the QPictureIO object is valid but useless.
-
- Example:
- \snippet picture/picture.cpp 6
- \codeline
- \snippet picture/picture.cpp 7
- \codeline
- \snippet picture/picture.cpp 8
-
- Before the regular expression test, all the 0 bytes in the file header are
- converted to 1 bytes. This is done because when Qt was ASCII-based, QRegExp
- could not handle 0 bytes in strings.
-
- The regexp is only applied on the first 14 bytes of the file.
-
- (Note that if one handlerIO supports writing a format and another
- supports reading it, Qt supports both reading and writing. If two
- handlers support the same operation, Qt chooses one arbitrarily.)
-*/
-
-void QPictureIO::defineIOHandler(const char *format,
- const char *header,
- const char *flags,
- picture_io_handler readPicture,
- picture_io_handler writePicture)
-{
- qt_init_picture_handlers();
- if (QPHList *list = pictureHandlers()) {
- QPictureHandler *p;
- p = new QPictureHandler(format, header, QByteArray(flags), readPicture, writePicture);
- list->prepend(p);
- }
-}
-
-
-/*****************************************************************************
- QPictureIO normal member functions
- *****************************************************************************/
-
-/*!
- Returns the picture currently set.
-
- \sa setPicture()
-*/
-const QPicture &QPictureIO::picture() const { return d->pi; }
-
-/*!
- Returns the picture's IO status. A non-zero value indicates an
- error, whereas 0 means that the IO operation was successful.
-
- \sa setStatus()
-*/
-int QPictureIO::status() const { return d->iostat; }
-
-/*!
- Returns the picture format string or \nullptr if no format has been
- explicitly set.
-*/
-const char *QPictureIO::format() const { return d->frmt; }
-
-/*!
- Returns the IO device currently set.
-
- \sa setIODevice()
-*/
-QIODevice *QPictureIO::ioDevice() const { return d->iodev; }
-
-/*!
- Returns the file name currently set.
-
- \sa setFileName()
-*/
-QString QPictureIO::fileName() const { return d->fname; }
-
-
-/*!
- Returns the picture description string.
-
- \sa setDescription()
-*/
-QString QPictureIO::description() const { return d->descr; }
-
-/*!
- Sets the picture to \a picture.
-
- \sa picture()
-*/
-void QPictureIO::setPicture(const QPicture &picture)
-{
- d->pi = picture;
-}
-
-/*!
- Sets the picture IO status to \a status. A non-zero value indicates
- an error, whereas 0 means that the IO operation was successful.
-
- \sa status()
-*/
-void QPictureIO::setStatus(int status)
-{
- d->iostat = status;
-}
-
-/*!
- Sets the picture format to \a format for the picture to be read or
- written.
-
- It is necessary to specify a format before writing an picture, but
- it is not necessary to specify a format before reading an picture.
-
- If no format has been set, Qt guesses the picture format before
- reading it. If a format is set the picture will only be read if it
- has that format.
-
- \sa read(), write(), format()
-*/
-void QPictureIO::setFormat(const char *format)
-{
- d->frmt = format;
-}
-
-/*!
- Sets the IO device to be used for reading or writing an picture.
-
- Setting the IO device allows pictures to be read/written to any
- block-oriented QIODevice.
-
- If \a ioDevice is not null, this IO device will override file name
- settings.
-
- \sa setFileName()
-*/
-void QPictureIO::setIODevice(QIODevice *ioDevice)
-{
- d->iodev = ioDevice;
-}
-
-/*!
- Sets the name of the file to read or write an picture from to \a
- fileName.
-
- \sa setIODevice()
-*/
-void QPictureIO::setFileName(const QString &fileName)
-{
- d->fname = fileName;
-}
-
-/*!
- Returns the quality of the written picture, related to the
- compression ratio.
-
- \sa setQuality(), QPicture::save()
-*/
-int QPictureIO::quality() const
-{
- return d->quality;
-}
-
-/*!
- Sets the quality of the written picture to \a q, related to the
- compression ratio.
-
- \a q must be in the range -1..100. Specify 0 to obtain small
- compressed files, 100 for large uncompressed files. (-1 signifies
- the default compression.)
-
- \sa quality(), QPicture::save()
-*/
-
-void QPictureIO::setQuality(int q)
-{
- d->quality = q;
-}
-
-/*!
- Returns the picture's parameters string.
-
- \sa setParameters()
-*/
-
-const char *QPictureIO::parameters() const
-{
- return d->parameters;
-}
-
-/*!
- Sets the picture's parameter string to \a parameters. This is for
- picture handlers that require special parameters.
-
- Although the current picture formats supported by Qt ignore the
- parameters string, it may be used in future extensions or by
- contributions (for example, JPEG).
-
- \sa parameters()
-*/
-
-void QPictureIO::setParameters(const char *parameters)
-{
- if (d->parameters)
- delete [] d->parameters;
- d->parameters = qstrdup(parameters);
-}
-
-/*!
- Sets the gamma value at which the picture will be viewed to \a
- gamma. If the picture format stores a gamma value for which the
- picture is intended to be used, then this setting will be used to
- modify the picture. Setting to 0.0 will disable gamma correction
- (i.e. any specification in the file will be ignored).
-
- The default value is 0.0.
-
- \sa gamma()
-*/
-void QPictureIO::setGamma(float gamma)
-{
- d->gamma=gamma;
-}
-
-/*!
- Returns the gamma value at which the picture will be viewed.
-
- \sa setGamma()
-*/
-float QPictureIO::gamma() const
-{
- return d->gamma;
-}
-
-/*!
- Sets the picture description string for picture handlers that support
- picture descriptions to \a description.
-
- Currently, no picture format supported by Qt uses the description
- string.
-*/
-
-void QPictureIO::setDescription(const QString &description)
-{
- d->descr = description;
-}
-
-
-/*!
- Returns a string that specifies the picture format of the file \a
- fileName, or null if the file cannot be read or if the format is
- not recognized.
-*/
-
-QByteArray QPictureIO::pictureFormat(const QString &fileName)
-{
- QFile file(fileName);
- QByteArray format;
- if (!file.open(QIODevice::ReadOnly))
- return format;
- format = pictureFormat(&file);
- file.close();
- return format;
-}
-
-/*!
- \overload
-
- Returns a string that specifies the picture format of the picture read
- from IO device \a d, or 0 if the device cannot be read or if the
- format is not recognized.
-
- Make sure that \a d is at the right position in the device (for
- example, at the beginning of the file).
-
- \sa QIODevice::pos()
-*/
-
-QByteArray QPictureIO::pictureFormat(QIODevice *d)
-{
- // if you change this change the documentation for defineIOHandler()
- const int buflen = 14;
-
- char buf[buflen];
- char buf2[buflen];
- qt_init_picture_handlers();
- qt_init_picture_plugins();
- int pos = d->pos(); // save position
- int rdlen = d->read(buf, buflen); // read a few bytes
-
- QByteArray format;
- if (rdlen != buflen)
- return format;
-
- memcpy(buf2, buf, buflen);
-
- for (int n = 0; n < rdlen; n++)
- if (buf[n] == '\0')
- buf[n] = '\001';
- if (rdlen > 0) {
- buf[rdlen - 1] = '\0';
- QString bufStr = QString::fromLatin1(buf);
- if (QPHList *list = pictureHandlers()) {
- for (int i = 0; i < list->size(); ++i) {
- if (list->at(i)->header.indexIn(bufStr) != -1) { // try match with headers
- format = list->at(i)->format;
- break;
- }
- }
- }
- }
- d->seek(pos); // restore position
- return format;
-}
-
-/*!
- Returns a sorted list of picture formats that are supported for
- picture input.
-*/
-QList<QByteArray> QPictureIO::inputFormats()
-{
- QList<QByteArray> result;
-
- qt_init_picture_handlers();
- qt_init_picture_plugins();
-
- if (QPHList *list = pictureHandlers()) {
- for (int i = 0; i < list->size(); ++i) {
- QPictureHandler *p = list->at(i);
- if (p->read_picture && !p->obsolete && !result.contains(p->format))
- result.append(p->format);
- }
- }
- std::sort(result.begin(), result.end());
-
- return result;
-}
-
-/*!
- Returns a sorted list of picture formats that are supported for
- picture output.
-*/
-QList<QByteArray> QPictureIO::outputFormats()
-{
- qt_init_picture_handlers();
- qt_init_picture_plugins();
-
- QList<QByteArray> result;
- if (QPHList *list = pictureHandlers()) {
- for (int i = 0; i < list->size(); ++i) {
- QPictureHandler *p = list->at(i);
- if (p->write_picture && !p->obsolete && !result.contains(p->format))
- result.append(p->format);
- }
- }
- return result;
-}
-
-
-
-/*!
- Reads an picture into memory and returns \c true if the picture was
- successfully read; otherwise returns \c false.
-
- Before reading an picture you must set an IO device or a file name.
- If both an IO device and a file name have been set, the IO device
- will be used.
-
- Setting the picture file format string is optional.
-
- Note that this function does \e not set the \l{format()}{format} used to read the picture. If you need that
- information, use the pictureFormat() static functions.
-
- Example:
-
- \snippet picture/picture.cpp 4
-
- \sa setIODevice(), setFileName(), setFormat(), write(), QPixmap::load()
-*/
-bool QPictureIO::read()
-{
- QFile file;
- QByteArray picture_format;
- QPictureHandler *h;
-
- if (d->iodev) { // read from io device
- // ok, already open
- } else if (!d->fname.isEmpty()) { // read from file
- file.setFileName(d->fname);
- if (!file.open(QIODevice::ReadOnly))
- return false; // cannot open file
- d->iodev = &file;
- } else { // no file name or io device
- return false;
- }
- if (d->frmt.isEmpty()) {
- // Try to guess format
- picture_format = pictureFormat(d->iodev); // get picture format
- if (picture_format.isEmpty()) {
- if (file.isOpen()) { // unknown format
- file.close();
- d->iodev = nullptr;
- }
- return false;
- }
- } else {
- picture_format = d->frmt;
- }
-
- h = get_picture_handler(picture_format);
- if (file.isOpen()) {
-#if !defined(Q_OS_UNIX)
- if (h && h->text_mode) { // reopen in translated mode
- file.close();
- file.open(QIODevice::ReadOnly | QIODevice::Text);
- }
- else
-#endif
- file.seek(0); // position to start
- }
- d->iostat = 1; // assume error
-
- if (h && h->read_picture)
- (*h->read_picture)(this);
-
- if (file.isOpen()) { // picture was read using file
- file.close();
- d->iodev = nullptr;
- }
- return d->iostat == 0; // picture successfully read?
-}
-
-
-/*!
- Writes an picture to an IO device and returns \c true if the picture was
- successfully written; otherwise returns \c false.
-
- Before writing an picture you must set an IO device or a file name.
- If both an IO device and a file name have been set, the IO device
- will be used.
-
- The picture will be written using the specified picture format.
-
- Example:
- \snippet picture/picture.cpp 5
-
- \sa setIODevice(), setFileName(), setFormat(), read(), QPixmap::save()
-*/
-bool QPictureIO::write()
-{
- if (d->frmt.isEmpty())
- return false;
- QPictureHandler *h = get_picture_handler(d->frmt);
- if (!h || !h->write_picture) {
- qWarning("QPictureIO::write: No such picture format handler: %s",
- format());
- return false;
- }
- QFile file;
- if (!d->iodev && !d->fname.isEmpty()) {
- file.setFileName(d->fname);
- bool translate = h->text_mode==QPictureHandler::TranslateInOut;
- QIODevice::OpenMode fmode = translate ? QIODevice::WriteOnly | QIODevice::Text : QIODevice::OpenMode(QIODevice::WriteOnly);
- if (!file.open(fmode)) // couldn't create file
- return false;
- d->iodev = &file;
- }
- d->iostat = 1;
- (*h->write_picture)(this);
- if (file.isOpen()) { // picture was written using file
- file.close();
- d->iodev = nullptr;
- }
- return d->iostat == 0; // picture successfully written?
-}
-#endif //QT_NO_PICTUREIO
-
QT_END_NAMESPACE
#endif // QT_NO_PICTURE
diff --git a/src/gui/image/qpicture.h b/src/gui/image/qpicture.h
index 189e57b9a3..34860985ed 100644
--- a/src/gui/image/qpicture.h
+++ b/src/gui/image/qpicture.h
@@ -48,7 +48,6 @@
QT_BEGIN_NAMESPACE
-
#ifndef QT_NO_PICTURE
class QPicturePrivate;
@@ -69,10 +68,10 @@ public:
bool play(QPainter *p);
- bool load(QIODevice *dev, const char *format = nullptr);
- bool load(const QString &fileName, const char *format = nullptr);
- bool save(QIODevice *dev, const char *format = nullptr);
- bool save(const QString &fileName, const char *format = nullptr);
+ bool load(QIODevice *dev);
+ bool load(const QString &fileName);
+ bool save(QIODevice *dev);
+ bool save(const QString &fileName);
QRect boundingRect() const;
void setBoundingRect(const QRect &r);
@@ -88,14 +87,6 @@ public:
friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &in, const QPicture &p);
friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QPicture &p);
-#if QT_DEPRECATED_SINCE(5, 10)
- static QT_DEPRECATED const char* pictureFormat(const QString &fileName);
- static QT_DEPRECATED QList<QByteArray> inputFormats();
- static QT_DEPRECATED QList<QByteArray> outputFormats();
- static QT_DEPRECATED QStringList inputFormatList();
- static QT_DEPRECATED QStringList outputFormatList();
-#endif // QT_DEPRECATED_SINCE(5, 10)
-
QPaintEngine *paintEngine() const override;
protected:
@@ -118,67 +109,6 @@ public:
Q_DECLARE_SHARED(QPicture)
-
-#ifndef QT_NO_PICTUREIO
-class QIODevice;
-class QPictureIO;
-typedef void (*picture_io_handler)(QPictureIO *); // picture IO handler
-
-struct QPictureIOData;
-
-class Q_GUI_EXPORT QPictureIO
-{
-public:
- QPictureIO();
- QPictureIO(QIODevice *ioDevice, const char *format);
- QPictureIO(const QString &fileName, const char *format);
- ~QPictureIO();
-
- const QPicture &picture() const;
- int status() const;
- const char *format() const;
- QIODevice *ioDevice() const;
- QString fileName() const;
- int quality() const;
- QString description() const;
- const char *parameters() const;
- float gamma() const;
-
- void setPicture(const QPicture &);
- void setStatus(int);
- void setFormat(const char *);
- void setIODevice(QIODevice *);
- void setFileName(const QString &);
- void setQuality(int);
- void setDescription(const QString &);
- void setParameters(const char *);
- void setGamma(float);
-
- bool read();
- bool write();
-
- static QByteArray pictureFormat(const QString &fileName);
- static QByteArray pictureFormat(QIODevice *);
- static QList<QByteArray> inputFormats();
- static QList<QByteArray> outputFormats();
-
- static void defineIOHandler(const char *format,
- const char *header,
- const char *flags,
- picture_io_handler read_picture,
- picture_io_handler write_picture);
-
-private:
- Q_DISABLE_COPY(QPictureIO)
-
- void init();
-
- QPictureIOData *d;
-};
-
-#endif //QT_NO_PICTUREIO
-
-
/*****************************************************************************
QPicture stream functions
*****************************************************************************/
diff --git a/src/gui/image/qpictureformatplugin.cpp b/src/gui/image/qpictureformatplugin.cpp
deleted file mode 100644
index ef57ad720f..0000000000
--- a/src/gui/image/qpictureformatplugin.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtGui module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpictureformatplugin.h"
-#if !defined(QT_NO_PICTURE)
-#include "qpicture.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \obsolete
-
- \class QPictureFormatPlugin
- \brief The QPictureFormatPlugin class provides an abstract base
- for custom picture format plugins.
-
- \ingroup plugins
- \inmodule QtGui
-
- The picture format plugin is a simple plugin interface that makes
- it easy to create custom picture formats that can be used
- transparently by applications.
-
- Writing an picture format plugin is achieved by subclassing this
- base class, reimplementing the pure virtual functions
- loadPicture(), savePicture(), and installIOHandler(), and
- exporting the class with the Q_PLUGIN_METADATA() macro.
-
- The json file containing the metadata should contain one entry
- with the list of picture formats supported by the plugin:
-
- \code
- { "Keys": [ "mypictureformat" ] }
- \endcode
-
- \sa {How to Create Qt Plugins}
-*/
-
-/*!
- \fn bool QPictureFormatPlugin::installIOHandler(const QString &format)
-
- Installs a QPictureIO picture I/O handler for the picture format \a
- format. Returns \c true on success.
-*/
-
-
-/*!
- Constructs an picture format plugin with the given \a parent.
- This is invoked automatically by the moc generated code that exports the plugin.
-*/
-QPictureFormatPlugin::QPictureFormatPlugin(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- Destroys the picture format plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it is no longer used.
-*/
-QPictureFormatPlugin::~QPictureFormatPlugin()
-{
-}
-
-
-/*!
- Loads the picture stored in the file called \a fileName, with the
- given \a format, into *\a picture. Returns \c true on success;
- otherwise returns \c false.
-
- \sa savePicture()
-*/
-bool QPictureFormatPlugin::loadPicture(const QString &format, const QString &fileName, QPicture *picture)
-{
- Q_UNUSED(format)
- Q_UNUSED(fileName)
- Q_UNUSED(picture)
- return false;
-}
-
-/*!
- Saves the given \a picture into the file called \a fileName,
- using the specified \a format. Returns \c true on success; otherwise
- returns \c false.
-
- \sa loadPicture()
-*/
-bool QPictureFormatPlugin::savePicture(const QString &format, const QString &fileName, const QPicture &picture)
-{
- Q_UNUSED(format)
- Q_UNUSED(fileName)
- Q_UNUSED(picture)
- return false;
-}
-
-#endif // QT_NO_PICTURE
-
-QT_END_NAMESPACE
diff --git a/src/gui/itemmodels/qstandarditemmodel.h b/src/gui/itemmodels/qstandarditemmodel.h
index a9ee25da75..f1c6e6df5c 100644
--- a/src/gui/itemmodels/qstandarditemmodel.h
+++ b/src/gui/itemmodels/qstandarditemmodel.h
@@ -53,8 +53,6 @@ QT_REQUIRE_CONFIG(standarditemmodel);
QT_BEGIN_NAMESPACE
-template <class T> class QList;
-
class QStandardItemModel;
class QStandardItemPrivate;
@@ -344,8 +342,11 @@ public:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
- // Qt 6: add override keyword
- bool clearItemData(const QModelIndex &index);
+ bool clearItemData(const QModelIndex &index)
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ override
+#endif
+ ;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
index 9c80f1e2cc..3784abdacc 100644
--- a/src/gui/kernel/kernel.pri
+++ b/src/gui/kernel/kernel.pri
@@ -48,11 +48,8 @@ HEADERS += \
kernel/qinputmethod.h \
kernel/qinputmethod_p.h \
kernel/qinternalmimedata_p.h \
- kernel/qkeysequence.h \
- kernel/qkeysequence_p.h \
kernel/qkeymapper_p.h \
kernel/qpalette.h \
- kernel/qshortcutmap_p.h \
kernel/qsessionmanager.h \
kernel/qsessionmanager_p.h \
kernel/qwindowdefs.h \
@@ -108,12 +105,10 @@ SOURCES += \
kernel/qevent.cpp \
kernel/qinputmethod.cpp \
kernel/qinternalmimedata.cpp \
- kernel/qkeysequence.cpp \
kernel/qkeymapper.cpp \
kernel/qpalette.cpp \
kernel/qguivariant.cpp \
kernel/qscreen.cpp \
- kernel/qshortcutmap.cpp \
kernel/qstylehints.cpp \
kernel/qtouchdevice.cpp \
kernel/qplatformsharedgraphicscache.cpp \
@@ -131,6 +126,18 @@ SOURCES += \
kernel/qhighdpiscaling.cpp \
kernel/qtestsupport_gui.cpp
+qtConfig(action) {
+ HEADERS += \
+ kernel/qguiaction.h \
+ kernel/qguiaction_p.h \
+ kernel/qguiactiongroup.h \
+ kernel/qguiactiongroup_p.h
+
+ SOURCES += \
+ kernel/qguiactiongroup.cpp \
+ kernel/qguiaction.cpp
+}
+
qtConfig(draganddrop) {
HEADERS += \
kernel/qdnd_p.h \
@@ -160,4 +167,17 @@ qtConfig(opengl) {
kernel/qopenglwindow.cpp
}
+qtConfig(shortcut) {
+ HEADERS += \
+ kernel/qguishortcut.h \
+ kernel/qguishortcut_p.h \
+ kernel/qshortcutmap_p.h \
+ kernel/qkeysequence.h \
+ kernel/qkeysequence_p.h
+ SOURCES += \
+ kernel/qguishortcut.cpp \
+ kernel/qshortcutmap.cpp \
+ kernel/qkeysequence.cpp
+}
+
win32:HEADERS+=kernel/qwindowdefs_win.h
diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp
index c69cc8ce6f..ede68f0719 100644
--- a/src/gui/kernel/qevent.cpp
+++ b/src/gui/kernel/qevent.cpp
@@ -1225,7 +1225,7 @@ Qt::KeyboardModifiers QKeyEvent::modifiers() const
return QInputEvent::modifiers();
}
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
/*!
\fn bool QKeyEvent::matches(QKeySequence::StandardKey key) const
\since 4.2
@@ -1241,7 +1241,7 @@ bool QKeyEvent::matches(QKeySequence::StandardKey matchKey) const
const QList<QKeySequence> bindings = QKeySequence::keyBindings(matchKey);
return bindings.contains(QKeySequence(searchkey));
}
-#endif // QT_NO_SHORTCUT
+#endif // QT_CONFIG(shortcut)
/*!
@@ -2696,10 +2696,6 @@ QNativeGestureEvent::QNativeGestureEvent(Qt::NativeGestureType type, const QPoin
{ }
#endif
-typedef QHash<const QNativeGestureEvent*, const QTouchDevice*> NativeGestureEventDataHash;
-// ### Qt6: move this to a member in QNativeGestureEvent
-Q_GLOBAL_STATIC(NativeGestureEventDataHash, g_nativeGestureEventDataHash)
-
/*!
Constructs a native gesture event of type \a type originating from \a device.
@@ -2714,27 +2710,20 @@ QNativeGestureEvent::QNativeGestureEvent(Qt::NativeGestureType type, const QTouc
const QPointF &screenPos, qreal realValue, ulong sequenceId, quint64 intValue)
: QInputEvent(QEvent::NativeGesture), mGestureType(type),
mLocalPos(localPos), mWindowPos(windowPos), mScreenPos(screenPos), mRealValue(realValue),
- mSequenceId(sequenceId), mIntValue(intValue)
+ mSequenceId(sequenceId), mIntValue(intValue), mDevice(device)
{
- g_nativeGestureEventDataHash->insert(this, device);
}
QNativeGestureEvent::~QNativeGestureEvent()
-{
- g_nativeGestureEventDataHash->remove(this);
-}
+ = default;
/*!
+ \fn const QTouchDevice *QNativeGestureEvent::device() const
\since 5.10
Returns the device.
*/
-const QTouchDevice *QNativeGestureEvent::device() const
-{
- return g_nativeGestureEventDataHash->value(this);
-}
-
/*!
\fn QNativeGestureEvent::gestureType() const
\since 5.2
@@ -3336,18 +3325,18 @@ QWhatsThisClickedEvent::~QWhatsThisClickedEvent()
/*!
\class QActionEvent
\brief The QActionEvent class provides an event that is generated
- when a QAction is added, removed, or changed.
+ when a QGuiAction is added, removed, or changed.
\ingroup events
\inmodule QtGui
- Actions can be added to widgets using QWidget::addAction(). This
- generates an \l ActionAdded event, which you can handle to provide
+ Actions can be added to controls, for example by using QWidget::addAction().
+ This generates an \l ActionAdded event, which you can handle to provide
custom behavior. For example, QToolBar reimplements
QWidget::actionEvent() to create \l{QToolButton}s for the
actions.
- \sa QAction, QWidget::addAction(), QWidget::removeAction(), QWidget::actions()
+ \sa QGuiAction, QWidget::addAction(), QWidget::removeAction(), QWidget::actions()
*/
/*!
@@ -3358,7 +3347,7 @@ QWhatsThisClickedEvent::~QWhatsThisClickedEvent()
type is ActionAdded, the action is to be inserted before the
action \a before. If \a before is 0, the action is appended.
*/
-QActionEvent::QActionEvent(int type, QAction *action, QAction *before)
+QActionEvent::QActionEvent(int type, QGuiAction *action, QGuiAction *before)
: QEvent(static_cast<QEvent::Type>(type)), act(action), bef(before)
{}
@@ -3593,7 +3582,7 @@ QToolBarChangeEvent::~QToolBarChangeEvent()
#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
/*!
Constructs a shortcut event for the given \a key press,
@@ -3614,7 +3603,7 @@ QShortcutEvent::~QShortcutEvent()
{
}
-#endif // QT_NO_SHORTCUT
+#endif // QT_CONFIG(shortcut)
#ifndef QT_NO_DEBUG_STREAM
@@ -3968,7 +3957,7 @@ QT_WARNING_POP
dbg << ')';
}
break;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
case QEvent::Shortcut: {
const QShortcutEvent *se = static_cast<const QShortcutEvent *>(e);
dbg << "QShortcutEvent(" << se->key().toString() << ", id=" << se->shortcutId();
diff --git a/src/gui/kernel/qevent.h b/src/gui/kernel/qevent.h
index f363ece48b..6f3215652b 100644
--- a/src/gui/kernel/qevent.h
+++ b/src/gui/kernel/qevent.h
@@ -45,7 +45,9 @@
#include <QtGui/qregion.h>
#include <QtCore/qnamespace.h>
#include <QtCore/qstring.h>
-#include <QtGui/qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/qkeysequence.h>
+#endif
#include <QtCore/qcoreevent.h>
#include <QtCore/qvariant.h>
#include <QtCore/qmap.h> // ### Qt 6: Remove
@@ -59,7 +61,7 @@
QT_BEGIN_NAMESPACE
-class QAction;
+class QGuiAction;
#ifndef QT_NO_GESTURES
class QGesture;
#endif
@@ -350,7 +352,7 @@ public:
const QPointF &windowPos() const { return mWindowPos; }
const QPointF &screenPos() const { return mScreenPos; }
- const QTouchDevice *device() const;
+ const QTouchDevice *device() const { return mDevice; }
protected:
Qt::NativeGestureType mGestureType;
@@ -360,6 +362,7 @@ protected:
qreal mRealValue;
ulong mSequenceId;
quint64 mIntValue;
+ const QTouchDevice *mDevice;
};
#endif // QT_NO_GESTURES
@@ -374,7 +377,7 @@ public:
~QKeyEvent();
int key() const { return k; }
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
bool matches(QKeySequence::StandardKey key) const;
#endif
Qt::KeyboardModifiers modifiers() const;
@@ -750,18 +753,18 @@ private:
};
#endif
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
class Q_GUI_EXPORT QActionEvent : public QEvent
{
- QAction *act, *bef;
+ QGuiAction *act, *bef;
public:
- QActionEvent(int type, QAction *action, QAction *before = nullptr);
+ QActionEvent(int type, QGuiAction *action, QGuiAction *before = nullptr);
~QActionEvent();
- inline QAction *action() const { return act; }
- inline QAction *before() const { return bef; }
+ inline QGuiAction *action() const { return act; }
+ inline QGuiAction *before() const { return bef; }
};
-#endif
+#endif // QT_CONFIG(action)
class Q_GUI_EXPORT QFileOpenEvent : public QEvent
{
@@ -791,7 +794,7 @@ private:
};
#endif
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
class Q_GUI_EXPORT QShortcutEvent : public QEvent
{
public:
@@ -826,10 +829,10 @@ private:
Q_GUI_EXPORT QDebug operator<<(QDebug, const QEvent *);
#endif
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
inline bool operator==(QKeyEvent *e, QKeySequence::StandardKey key){return (e ? e->matches(key) : false);}
inline bool operator==(QKeySequence::StandardKey key, QKeyEvent *e){return (e ? e->matches(key) : false);}
-#endif // QT_NO_SHORTCUT
+#endif // QT_CONFIG(shortcut)
class Q_GUI_EXPORT QPointingDeviceUniqueId
{
@@ -854,14 +857,6 @@ private:
};
Q_DECLARE_TYPEINFO(QPointingDeviceUniqueId, Q_MOVABLE_TYPE);
-#if 0
-#pragma qt_sync_suspend_processing
-#endif
-template <> class QList<QPointingDeviceUniqueId> {}; // to prevent instantiation: use QVector instead
-#if 0
-#pragma qt_sync_resume_processing
-#endif
-
Q_GUI_EXPORT bool operator==(QPointingDeviceUniqueId lhs, QPointingDeviceUniqueId rhs) noexcept;
inline bool operator!=(QPointingDeviceUniqueId lhs, QPointingDeviceUniqueId rhs) noexcept
{ return !operator==(lhs, rhs); }
diff --git a/src/gui/kernel/qguiaction.cpp b/src/gui/kernel/qguiaction.cpp
new file mode 100644
index 0000000000..7c7d86f5ab
--- /dev/null
+++ b/src/gui/kernel/qguiaction.cpp
@@ -0,0 +1,1214 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qguiaction.h"
+#include "qguiactiongroup.h"
+
+#include "qguiaction_p.h"
+#include "qguiapplication.h"
+#include "qevent.h"
+#include "qlist.h"
+#include "qstylehints.h"
+#if QT_CONFIG(shortcut)
+# include <private/qshortcutmap_p.h>
+#endif
+#include <private/qguiapplication_p.h>
+#include <private/qdebug_p.h>
+
+#define QAPP_CHECK(functionName) \
+ if (Q_UNLIKELY(!QCoreApplication::instance())) { \
+ qWarning("QAction: Initialize Q(Gui)Application before calling '" functionName "'."); \
+ return; \
+ }
+
+QT_BEGIN_NAMESPACE
+
+/*
+ internal: guesses a descriptive text from a text suited for a menu entry
+ */
+static QString qt_strippedText(QString s)
+{
+ s.remove(QLatin1String("..."));
+ for (int i = 0; i < s.size(); ++i) {
+ if (s.at(i) == QLatin1Char('&'))
+ s.remove(i, 1);
+ }
+ return s.trimmed();
+}
+
+QGuiActionPrivate::QGuiActionPrivate() :
+#if QT_CONFIG(shortcut)
+ autorepeat(1),
+#endif
+ enabled(1), forceDisabled(0), visible(1), forceInvisible(0), checkable(0),
+ checked(0), separator(0), fontSet(false),
+ iconVisibleInMenu(-1), shortcutVisibleInContextMenu(-1)
+{
+}
+
+#if QT_CONFIG(shortcut)
+static bool dummy(QObject *, Qt::ShortcutContext) { return false; } // only for GUI testing.
+
+QShortcutMap::ContextMatcher QGuiActionPrivate::contextMatcher() const
+{
+ return dummy;
+}
+#endif // QT_CONFIG(shortcut)
+
+QGuiActionPrivate::~QGuiActionPrivate() = default;
+
+void QGuiActionPrivate::sendDataChanged()
+{
+ Q_Q(QGuiAction);
+ QActionEvent e(QEvent::ActionChanged, q);
+ QCoreApplication::sendEvent(q, &e);
+
+ emit q->changed();
+}
+
+#if QT_CONFIG(shortcut)
+void QGuiActionPrivate::redoGrab(QShortcutMap &map)
+{
+ Q_Q(QGuiAction);
+ if (shortcutId)
+ map.removeShortcut(shortcutId, q);
+ if (shortcut.isEmpty())
+ return;
+ shortcutId = map.addShortcut(q, shortcut, shortcutContext, contextMatcher());
+ if (!enabled)
+ map.setShortcutEnabled(false, shortcutId, q);
+ if (!autorepeat)
+ map.setShortcutAutoRepeat(false, shortcutId, q);
+}
+
+void QGuiActionPrivate::redoGrabAlternate(QShortcutMap &map)
+{
+ Q_Q(QGuiAction);
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ if (const int id = alternateShortcutIds.at(i))
+ map.removeShortcut(id, q);
+ }
+ alternateShortcutIds.clear();
+ if (alternateShortcuts.isEmpty())
+ return;
+ for(int i = 0; i < alternateShortcuts.count(); ++i) {
+ const QKeySequence& alternate = alternateShortcuts.at(i);
+ if (!alternate.isEmpty())
+ alternateShortcutIds.append(map.addShortcut(q, alternate, shortcutContext, contextMatcher()));
+ else
+ alternateShortcutIds.append(0);
+ }
+ if (!enabled) {
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ const int id = alternateShortcutIds.at(i);
+ map.setShortcutEnabled(false, id, q);
+ }
+ }
+ if (!autorepeat) {
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ const int id = alternateShortcutIds.at(i);
+ map.setShortcutAutoRepeat(false, id, q);
+ }
+ }
+}
+
+void QGuiActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map)
+{
+ Q_Q(QGuiAction);
+ if (shortcutId)
+ map.setShortcutEnabled(enable, shortcutId, q);
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ if (const int id = alternateShortcutIds.at(i))
+ map.setShortcutEnabled(enable, id, q);
+ }
+}
+#endif // QT_NO_SHORTCUT
+
+
+/*!
+ \class QGuiAction
+ \brief QGuiAction is the base class for actions, an abstract user interface
+ action that can be inserted into widgets.
+ \since 6.0
+
+ \inmodule QtGui
+
+ In applications many common commands can be invoked via menus,
+ toolbar buttons, and keyboard shortcuts. Since the user expects
+ each command to be performed in the same way, regardless of the
+ user interface used, it is useful to represent each command as
+ an \e action.
+
+ Actions can be added to menus and toolbars, and will
+ automatically keep them in sync. For example, in a word processor,
+ if the user presses a Bold toolbar button, the Bold menu item
+ will automatically be checked.
+
+ Actions can be created as independent objects, but they may
+ also be created during the construction of menus; the QMenu class
+ contains convenience functions for creating actions suitable for
+ use as menu items.
+
+ A QGuiAction may contain an icon, menu text, a shortcut, status text,
+ "What's This?" text, and a tooltip. Most of these can be set in
+ the constructor. They can also be set independently with
+ setIcon(), setText(), setIconText(), setShortcut(),
+ setStatusTip(), setWhatsThis(), and setToolTip(). For menu items,
+ it is possible to set an individual font with setFont().
+
+ We recommend that actions are created as children of the window
+ they are used in. In most cases actions will be children of
+ the application's main window.
+
+ \sa QMenu, QToolBar, {Application Example}
+*/
+
+/*!
+ \fn void QGuiAction::trigger()
+
+ This is a convenience slot that calls activate(Trigger).
+*/
+
+/*!
+ \fn void QGuiAction::hover()
+
+ This is a convenience slot that calls activate(Hover).
+*/
+
+/*!
+ \enum QGuiAction::MenuRole
+
+ This enum describes how an action should be moved into the application menu on \macos.
+
+ \value NoRole This action should not be put into the application menu
+ \value TextHeuristicRole This action should be put in the application menu based on the action's text
+ as described in the QMenuBar documentation.
+ \value ApplicationSpecificRole This action should be put in the application menu with an application specific role
+ \value AboutQtRole This action handles the "About Qt" menu item.
+ \value AboutRole This action should be placed where the "About" menu item is in the application menu. The text of
+ the menu item will be set to "About <application name>". The application name is fetched from the
+ \c{Info.plist} file in the application's bundle (See \l{Qt for macOS - Deployment}).
+ \value PreferencesRole This action should be placed where the "Preferences..." menu item is in the application menu.
+ \value QuitRole This action should be placed where the Quit menu item is in the application menu.
+
+ Setting this value only has effect on items that are in the immediate menus
+ of the menubar, not the submenus of those menus. For example, if you have
+ File menu in your menubar and the File menu has a submenu, setting the
+ MenuRole for the actions in that submenu have no effect. They will never be moved.
+*/
+
+/*!
+ Constructs an action with \a parent. If \a parent is an action
+ group the action will be automatically inserted into the group.
+
+ \note The \a parent argument is optional since Qt 5.7.
+*/
+QGuiAction::QGuiAction(QObject *parent)
+ : QGuiAction(*new QGuiActionPrivate, parent)
+{
+}
+
+/*!
+ Constructs an action with some \a text and \a parent. If \a
+ parent is an action group the action will be automatically
+ inserted into the group.
+
+ The action uses a stripped version of \a text (e.g. "\&Menu
+ Option..." becomes "Menu Option") as descriptive text for
+ tool buttons. You can override this by setting a specific
+ description with setText(). The same text will be used for
+ tooltips unless you specify a different text using
+ setToolTip().
+
+*/
+QGuiAction::QGuiAction(const QString &text, QObject *parent)
+ : QGuiAction(parent)
+{
+ Q_D(QGuiAction);
+ d->text = text;
+}
+
+/*!
+ Constructs an action with an \a icon and some \a text and \a
+ parent. If \a parent is an action group the action will be
+ automatically inserted into the group.
+
+ The action uses a stripped version of \a text (e.g. "\&Menu
+ Option..." becomes "Menu Option") as descriptive text for
+ tool buttons. You can override this by setting a specific
+ description with setText(). The same text will be used for
+ tooltips unless you specify a different text using
+ setToolTip().
+*/
+QGuiAction::QGuiAction(const QIcon &icon, const QString &text, QObject *parent)
+ : QGuiAction(text, parent)
+{
+ Q_D(QGuiAction);
+ d->icon = icon;
+}
+
+/*!
+ \internal
+*/
+QGuiAction::QGuiAction(QGuiActionPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+ Q_D(QGuiAction);
+ d->group = qobject_cast<QGuiActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+#if QT_CONFIG(shortcut)
+/*!
+ \property QGuiAction::shortcut
+ \brief the action's primary shortcut key
+
+ Valid keycodes for this property can be found in \l Qt::Key and
+ \l Qt::Modifier. There is no default shortcut key.
+*/
+void QGuiAction::setShortcut(const QKeySequence &shortcut)
+{
+ QAPP_CHECK("setShortcut");
+
+ Q_D(QGuiAction);
+ if (d->shortcut == shortcut)
+ return;
+
+ d->shortcut = shortcut;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->sendDataChanged();
+}
+
+/*!
+ Sets \a shortcuts as the list of shortcuts that trigger the
+ action. The first element of the list is the primary shortcut.
+
+ \sa shortcut
+*/
+void QGuiAction::setShortcuts(const QList<QKeySequence> &shortcuts)
+{
+ Q_D(QGuiAction);
+
+ QList <QKeySequence> listCopy = shortcuts;
+
+ QKeySequence primary;
+ if (!listCopy.isEmpty())
+ primary = listCopy.takeFirst();
+
+ if (d->shortcut == primary && d->alternateShortcuts == listCopy)
+ return;
+
+ QAPP_CHECK("setShortcuts");
+
+ d->shortcut = primary;
+ d->alternateShortcuts = listCopy;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->sendDataChanged();
+}
+
+/*!
+ Sets a platform dependent list of shortcuts based on the \a key.
+ The result of calling this function will depend on the currently running platform.
+ Note that more than one shortcut can assigned by this action.
+ If only the primary shortcut is required, use setShortcut instead.
+
+ \sa QKeySequence::keyBindings()
+*/
+void QGuiAction::setShortcuts(QKeySequence::StandardKey key)
+{
+ QList <QKeySequence> list = QKeySequence::keyBindings(key);
+ setShortcuts(list);
+}
+
+/*!
+ Returns the primary shortcut.
+
+ \sa setShortcuts()
+*/
+QKeySequence QGuiAction::shortcut() const
+{
+ Q_D(const QGuiAction);
+ return d->shortcut;
+}
+
+/*!
+ Returns the list of shortcuts, with the primary shortcut as
+ the first element of the list.
+
+ \sa setShortcuts()
+*/
+QList<QKeySequence> QGuiAction::shortcuts() const
+{
+ Q_D(const QGuiAction);
+ QList <QKeySequence> shortcuts;
+ if (!d->shortcut.isEmpty())
+ shortcuts << d->shortcut;
+ if (!d->alternateShortcuts.isEmpty())
+ shortcuts << d->alternateShortcuts;
+ return shortcuts;
+}
+
+/*!
+ \property QGuiAction::shortcutContext
+ \brief the context for the action's shortcut
+
+ Valid values for this property can be found in \l Qt::ShortcutContext.
+ The default value is Qt::WindowShortcut.
+*/
+void QGuiAction::setShortcutContext(Qt::ShortcutContext context)
+{
+ Q_D(QGuiAction);
+ if (d->shortcutContext == context)
+ return;
+ QAPP_CHECK("setShortcutContext");
+ d->shortcutContext = context;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->sendDataChanged();
+}
+
+Qt::ShortcutContext QGuiAction::shortcutContext() const
+{
+ Q_D(const QGuiAction);
+ return d->shortcutContext;
+}
+
+/*!
+ \property QGuiAction::autoRepeat
+ \brief whether the action can auto repeat
+
+ If true, the action will auto repeat when the keyboard shortcut
+ combination is held down, provided that keyboard auto repeat is
+ enabled on the system.
+ The default value is true.
+*/
+void QGuiAction::setAutoRepeat(bool on)
+{
+ Q_D(QGuiAction);
+ if (d->autorepeat == on)
+ return;
+ QAPP_CHECK("setAutoRepeat");
+ d->autorepeat = on;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->sendDataChanged();
+}
+
+bool QGuiAction::autoRepeat() const
+{
+ Q_D(const QGuiAction);
+ return d->autorepeat;
+}
+#endif // QT_CONFIG(shortcut)
+
+/*!
+ \property QGuiAction::font
+ \brief the action's font
+
+ The font property is used to render the text set on the
+ QAction. The font will can be considered a hint as it will not be
+ consulted in all cases based upon application and style.
+
+ By default, this property contains the application's default font.
+
+ \sa setText()
+*/
+void QGuiAction::setFont(const QFont &font)
+{
+ Q_D(QGuiAction);
+ if (d->font == font)
+ return;
+
+ d->fontSet = true;
+ d->font = font;
+ d->sendDataChanged();
+}
+
+QFont QGuiAction::font() const
+{
+ Q_D(const QGuiAction);
+ return d->font;
+}
+
+
+/*!
+ Destroys the object and frees allocated resources.
+*/
+QGuiAction::~QGuiAction()
+{
+ Q_D(QGuiAction);
+ if (d->group)
+ d->group->removeAction(this);
+#if QT_CONFIG(shortcut)
+ if (d->shortcutId && qApp) {
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->shortcutId, this);
+ for (int id : qAsConst(d->alternateShortcutIds))
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(id, this);
+ }
+#endif
+}
+
+/*!
+ Sets this action group to \a group. The action will be automatically
+ added to the group's list of actions.
+
+ Actions within the group will be mutually exclusive.
+
+ \sa QGuiActionGroup, guiActionGroup()
+*/
+void QGuiAction::setActionGroup(QGuiActionGroup *group)
+{
+ Q_D(QGuiAction);
+ if(group == d->group)
+ return;
+
+ if(d->group)
+ d->group->removeAction(this);
+ d->group = group;
+ if(group)
+ group->addAction(this);
+ d->sendDataChanged();
+}
+
+/*!
+ Returns the action group for this action. If no action group manages
+ this action, then \nullptr will be returned.
+
+ \sa QGuiActionGroup, setActionGroup()
+*/
+QGuiActionGroup *QGuiAction::guiActionGroup() const
+{
+ Q_D(const QGuiAction);
+ return d->group;
+}
+
+
+/*!
+ \property QGuiAction::icon
+ \brief the action's icon
+
+ In toolbars, the icon is used as the tool button icon; in menus,
+ it is displayed to the left of the menu text. There is no default
+ icon.
+
+ If a null icon (QIcon::isNull()) is passed into this function,
+ the icon of the action is cleared.
+*/
+void QGuiAction::setIcon(const QIcon &icon)
+{
+ Q_D(QGuiAction);
+ d->icon = icon;
+ d->sendDataChanged();
+}
+
+QIcon QGuiAction::icon() const
+{
+ Q_D(const QGuiAction);
+ return d->icon;
+}
+
+/*!
+ If \a b is true then this action will be considered a separator.
+
+ How a separator is represented depends on the widget it is inserted
+ into. Under most circumstances the text, submenu, and icon will be
+ ignored for separator actions.
+
+ \sa isSeparator()
+*/
+void QGuiAction::setSeparator(bool b)
+{
+ Q_D(QGuiAction);
+ if (d->separator == b)
+ return;
+
+ d->separator = b;
+ d->sendDataChanged();
+}
+
+/*!
+ Returns \c true if this action is a separator action; otherwise it
+ returns \c false.
+
+ \sa setSeparator()
+*/
+bool QGuiAction::isSeparator() const
+{
+ Q_D(const QGuiAction);
+ return d->separator;
+}
+
+/*!
+ \property QGuiAction::text
+ \brief the action's descriptive text
+
+ If the action is added to a menu, the menu option will consist of
+ the icon (if there is one), the text, and the shortcut (if there
+ is one). If the text is not explicitly set in the constructor, or
+ by using setText(), the action's description icon text will be
+ used as text. There is no default text.
+
+ \sa iconText
+*/
+void QGuiAction::setText(const QString &text)
+{
+ Q_D(QGuiAction);
+ if (d->text == text)
+ return;
+
+ d->text = text;
+ d->sendDataChanged();
+}
+
+QString QGuiAction::text() const
+{
+ Q_D(const QGuiAction);
+ QString s = d->text;
+ if(s.isEmpty()) {
+ s = d->iconText;
+ s.replace(QLatin1Char('&'), QLatin1String("&&"));
+ }
+ return s;
+}
+
+/*!
+ \property QGuiAction::iconText
+ \brief the action's descriptive icon text
+
+ If QToolBar::toolButtonStyle is set to a value that permits text to
+ be displayed, the text defined held in this property appears as a
+ label in the relevant tool button.
+
+ It also serves as the default text in menus and tooltips if the action
+ has not been defined with setText() or setToolTip(), and will
+ also be used in toolbar buttons if no icon has been defined using setIcon().
+
+ If the icon text is not explicitly set, the action's normal text will be
+ used for the icon text.
+
+ By default, this property contains an empty string.
+
+ \sa setToolTip(), setStatusTip()
+*/
+void QGuiAction::setIconText(const QString &text)
+{
+ Q_D(QGuiAction);
+ if (d->iconText == text)
+ return;
+
+ d->iconText = text;
+ d->sendDataChanged();
+}
+
+QString QGuiAction::iconText() const
+{
+ Q_D(const QGuiAction);
+ if (d->iconText.isEmpty())
+ return qt_strippedText(d->text);
+ return d->iconText;
+}
+
+/*!
+ \property QGuiAction::toolTip
+ \brief the action's tooltip
+
+ This text is used for the tooltip. If no tooltip is specified,
+ the action's text is used.
+
+ By default, this property contains the action's text.
+
+ \sa setStatusTip(), setShortcut()
+*/
+void QGuiAction::setToolTip(const QString &tooltip)
+{
+ Q_D(QGuiAction);
+ if (d->tooltip == tooltip)
+ return;
+
+ d->tooltip = tooltip;
+ d->sendDataChanged();
+}
+
+QString QGuiAction::toolTip() const
+{
+ Q_D(const QGuiAction);
+ if (d->tooltip.isEmpty()) {
+ if (!d->text.isEmpty())
+ return qt_strippedText(d->text);
+ return qt_strippedText(d->iconText);
+ }
+ return d->tooltip;
+}
+
+/*!
+ \property QGuiAction::statusTip
+ \brief the action's status tip
+
+ The status tip is displayed on all status bars provided by the
+ action's top-level parent widget.
+
+ By default, this property contains an empty string.
+
+ \sa setToolTip(), showStatusText()
+*/
+void QGuiAction::setStatusTip(const QString &statustip)
+{
+ Q_D(QGuiAction);
+ if (d->statustip == statustip)
+ return;
+
+ d->statustip = statustip;
+ d->sendDataChanged();
+}
+
+QString QGuiAction::statusTip() const
+{
+ Q_D(const QGuiAction);
+ return d->statustip;
+}
+
+/*!
+ \property QGuiAction::whatsThis
+ \brief the action's "What's This?" help text
+
+ The "What's This?" text is used to provide a brief description of
+ the action. The text may contain rich text. There is no default
+ "What's This?" text.
+
+ \sa QWhatsThis
+*/
+void QGuiAction::setWhatsThis(const QString &whatsthis)
+{
+ Q_D(QGuiAction);
+ if (d->whatsthis == whatsthis)
+ return;
+
+ d->whatsthis = whatsthis;
+ d->sendDataChanged();
+}
+
+QString QGuiAction::whatsThis() const
+{
+ Q_D(const QGuiAction);
+ return d->whatsthis;
+}
+
+/*!
+ \enum QGuiAction::Priority
+
+ This enum defines priorities for actions in user interface.
+
+ \value LowPriority The action should not be prioritized in
+ the user interface.
+
+ \value NormalPriority
+
+ \value HighPriority The action should be prioritized in
+ the user interface.
+
+ \sa priority
+*/
+
+
+/*!
+ \property QGuiAction::priority
+
+ \brief the actions's priority in the user interface.
+
+ This property can be set to indicate how the action should be prioritized
+ in the user interface.
+
+ For instance, when toolbars have the Qt::ToolButtonTextBesideIcon
+ mode set, then actions with LowPriority will not show the text
+ labels.
+*/
+void QGuiAction::setPriority(Priority priority)
+{
+ Q_D(QGuiAction);
+ if (d->priority == priority)
+ return;
+
+ d->priority = priority;
+ d->sendDataChanged();
+}
+
+QGuiAction::Priority QGuiAction::priority() const
+{
+ Q_D(const QGuiAction);
+ return d->priority;
+}
+
+/*!
+ \property QGuiAction::checkable
+ \brief whether the action is a checkable action
+
+ A checkable action is one which has an on/off state. For example,
+ in a word processor, a Bold toolbar button may be either on or
+ off. An action which is not a toggle action is a command action;
+ a command action is simply executed, e.g. file save.
+ By default, this property is \c false.
+
+ In some situations, the state of one toggle action should depend
+ on the state of others. For example, "Left Align", "Center" and
+ "Right Align" toggle actions are mutually exclusive. To achieve
+ exclusive toggling, add the relevant toggle actions to a
+ QGuiActionGroup with the QGuiActionGroup::exclusive property set to
+ true.
+
+ \sa setChecked()
+*/
+void QGuiAction::setCheckable(bool b)
+{
+ Q_D(QGuiAction);
+ if (d->checkable == b)
+ return;
+
+ d->checkable = b;
+ d->checked = false;
+ d->sendDataChanged();
+}
+
+bool QGuiAction::isCheckable() const
+{
+ Q_D(const QGuiAction);
+ return d->checkable;
+}
+
+/*!
+ \fn void QGuiAction::toggle()
+
+ This is a convenience function for the \l checked property.
+ Connect to it to change the checked state to its opposite state.
+*/
+void QGuiAction::toggle()
+{
+ Q_D(QGuiAction);
+ setChecked(!d->checked);
+}
+
+/*!
+ \property QGuiAction::checked
+ \brief whether the action is checked.
+
+ Only checkable actions can be checked. By default, this is false
+ (the action is unchecked).
+
+ \note The notifier signal for this property is toggled(). As toggling
+ a QAction changes its state, it will also emit a changed() signal.
+
+ \sa checkable, toggled()
+*/
+void QGuiAction::setChecked(bool b)
+{
+ Q_D(QGuiAction);
+ if (!d->checkable || d->checked == b)
+ return;
+
+ QPointer<QGuiAction> guard(this);
+ d->checked = b;
+ d->sendDataChanged();
+ if (guard)
+ emit toggled(b);
+}
+
+bool QGuiAction::isChecked() const
+{
+ Q_D(const QGuiAction);
+ return d->checked;
+}
+
+/*!
+ \fn void QGuiAction::setDisabled(bool b)
+
+ This is a convenience function for the \l enabled property, that
+ is useful for signals--slots connections. If \a b is true the
+ action is disabled; otherwise it is enabled.
+*/
+
+/*!
+ \property QGuiAction::enabled
+ \brief whether the action is enabled
+
+ Disabled actions cannot be chosen by the user. They do not
+ disappear from menus or toolbars, but they are displayed in a way
+ which indicates that they are unavailable. For example, they might
+ be displayed using only shades of gray.
+
+ \uicontrol{What's This?} help on disabled actions is still available, provided
+ that the QAction::whatsThis property is set.
+
+ An action will be disabled when all widgets to which it is added
+ (with QWidget::addAction()) are disabled or not visible. When an
+ action is disabled, it is not possible to trigger it through its
+ shortcut.
+
+ By default, this property is \c true (actions are enabled).
+
+ \sa text
+*/
+void QGuiAction::setEnabled(bool b)
+{
+ Q_D(QGuiAction);
+ if (b == d->enabled && b != d->forceDisabled)
+ return;
+ d->forceDisabled = !b;
+ if (b && (!d->visible || (d->group && !d->group->isEnabled())))
+ return;
+ QAPP_CHECK("setEnabled");
+ d->enabled = b;
+#if QT_CONFIG(shortcut)
+ d->setShortcutEnabled(b, QGuiApplicationPrivate::instance()->shortcutMap);
+#endif
+ d->sendDataChanged();
+}
+
+bool QGuiAction::isEnabled() const
+{
+ Q_D(const QGuiAction);
+ return d->enabled;
+}
+
+/*!
+ \property QGuiAction::visible
+ \brief whether the action can be seen (e.g. in menus and toolbars)
+
+ If \e visible is true the action can be seen (e.g. in menus and
+ toolbars) and chosen by the user; if \e visible is false the
+ action cannot be seen or chosen by the user.
+
+ Actions which are not visible are \e not grayed out; they do not
+ appear at all.
+
+ By default, this property is \c true (actions are visible).
+*/
+void QGuiAction::setVisible(bool b)
+{
+ Q_D(QGuiAction);
+ if (b == d->visible && b != d->forceInvisible)
+ return;
+ QAPP_CHECK("setVisible");
+ d->forceInvisible = !b;
+ d->visible = b;
+ d->enabled = b && !d->forceDisabled && (!d->group || d->group->isEnabled()) ;
+#if QT_CONFIG(shortcut)
+ d->setShortcutEnabled(d->enabled, QGuiApplicationPrivate::instance()->shortcutMap);
+#endif
+ d->sendDataChanged();
+}
+
+
+bool QGuiAction::isVisible() const
+{
+ Q_D(const QGuiAction);
+ return d->visible;
+}
+
+/*!
+ \reimp
+*/
+bool QGuiAction::event(QEvent *e)
+{
+#if QT_CONFIG(shortcut)
+ if (e->type() == QEvent::Shortcut) {
+ QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
+ Q_ASSERT_X(se->key() == d_func()->shortcut || d_func()->alternateShortcuts.contains(se->key()),
+ "QAction::event",
+ "Received shortcut event from incorrect shortcut");
+ if (se->isAmbiguous())
+ qWarning("QAction::event: Ambiguous shortcut overload: %s", se->key().toString(QKeySequence::NativeText).toLatin1().constData());
+ else
+ activate(Trigger);
+ return true;
+ }
+#endif // QT_CONFIG(shortcut)
+ return QObject::event(e);
+}
+
+/*!
+ Returns the user data as set in QAction::setData.
+
+ \sa setData()
+*/
+QVariant QGuiAction::data() const
+{
+ Q_D(const QGuiAction);
+ return d->userData;
+}
+
+/*!
+ Sets the action's internal data to the given \a userData.
+
+ \sa data()
+*/
+void QGuiAction::setData(const QVariant &data)
+{
+ Q_D(QGuiAction);
+ if (d->userData == data)
+ return;
+ d->userData = data;
+ d->sendDataChanged();
+}
+
+/*!
+ Sends the relevant signals for ActionEvent \a event.
+
+ Action based widgets use this API to cause the QAction
+ to emit signals as well as emitting their own.
+*/
+void QGuiAction::activate(ActionEvent event)
+{
+ Q_D(QGuiAction);
+ if(event == Trigger) {
+ QPointer<QObject> guard = this;
+ if(d->checkable) {
+ // the checked action of an exclusive group may not be unchecked
+ if (d->checked && (d->group
+ && d->group->exclusionPolicy() == QGuiActionGroup::ExclusionPolicy::Exclusive
+ && d->group->checkedGuiAction() == this)) {
+ if (!guard.isNull())
+ emit triggered(true);
+ return;
+ }
+ setChecked(!d->checked);
+ }
+ if (!guard.isNull())
+ emit triggered(d->checked);
+ } else if(event == Hover) {
+ emit hovered();
+ }
+}
+
+/*!
+ \fn void QGuiAction::triggered(bool checked)
+
+ This signal is emitted when an action is activated by the user;
+ for example, when the user clicks a menu option, toolbar button,
+ or presses an action's shortcut key combination, or when trigger()
+ was called. Notably, it is \e not emitted when setChecked() or
+ toggle() is called.
+
+ If the action is checkable, \a checked is true if the action is
+ checked, or false if the action is unchecked.
+
+ \sa activate(), toggled(), checked
+*/
+
+/*!
+ \fn void QGuiAction::toggled(bool checked)
+
+ This signal is emitted whenever a checkable action changes its
+ isChecked() status. This can be the result of a user interaction,
+ or because setChecked() was called. As setChecked() changes the
+ QAction, it emits changed() in addition to toggled().
+
+ \a checked is true if the action is checked, or false if the
+ action is unchecked.
+
+ \sa activate(), triggered(), checked
+*/
+
+/*!
+ \fn void QGuiAction::hovered()
+
+ This signal is emitted when an action is highlighted by the user;
+ for example, when the user pauses with the cursor over a menu option,
+ toolbar button, or presses an action's shortcut key combination.
+
+ \sa activate()
+*/
+
+/*!
+ \fn void QGuiAction::changed()
+
+ This signal is emitted when an action has changed. If you
+ are only interested in actions in a given widget, you can
+ watch for QWidget::actionEvent() sent with an
+ QEvent::ActionChanged.
+
+ \sa QWidget::actionEvent()
+*/
+
+/*!
+ \enum QGuiAction::ActionEvent
+
+ This enum type is used when calling QAction::activate()
+
+ \value Trigger this will cause the QAction::triggered() signal to be emitted.
+
+ \value Hover this will cause the QAction::hovered() signal to be emitted.
+*/
+
+/*!
+ \property QGuiAction::menuRole
+ \brief the action's menu role
+
+ This indicates what role the action serves in the application menu on
+ \macos. By default all actions have the TextHeuristicRole, which means that
+ the action is added based on its text (see QMenuBar for more information).
+
+ The menu role can only be changed before the actions are put into the menu
+ bar in \macos (usually just before the first application window is
+ shown).
+*/
+void QGuiAction::setMenuRole(MenuRole menuRole)
+{
+ Q_D(QGuiAction);
+ if (d->menuRole == menuRole)
+ return;
+
+ d->menuRole = menuRole;
+ d->sendDataChanged();
+}
+
+QGuiAction::MenuRole QGuiAction::menuRole() const
+{
+ Q_D(const QGuiAction);
+ return d->menuRole;
+}
+
+/*!
+ \property QGuiAction::iconVisibleInMenu
+ \brief Whether or not an action should show an icon in a menu
+
+ In some applications, it may make sense to have actions with icons in the
+ toolbar, but not in menus. If true, the icon (if valid) is shown in the menu, when it
+ is false, it is not shown.
+
+ The default is to follow whether the Qt::AA_DontShowIconsInMenus attribute
+ is set for the application. Explicitly settings this property overrides
+ the presence (or abscence) of the attribute.
+
+ For example:
+ \snippet code/src_gui_kernel_qaction.cpp 0
+
+ \sa icon, QCoreApplication::setAttribute()
+*/
+void QGuiAction::setIconVisibleInMenu(bool visible)
+{
+ Q_D(QGuiAction);
+ if (d->iconVisibleInMenu == -1 || visible != bool(d->iconVisibleInMenu)) {
+ int oldValue = d->iconVisibleInMenu;
+ d->iconVisibleInMenu = visible;
+ // Only send data changed if we really need to.
+ if (oldValue != -1
+ || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus)) {
+ d->sendDataChanged();
+ }
+ }
+}
+
+bool QGuiAction::isIconVisibleInMenu() const
+{
+ Q_D(const QGuiAction);
+ if (d->iconVisibleInMenu == -1) {
+ return !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus);
+ }
+ return d->iconVisibleInMenu;
+}
+
+/*!
+ \property QGuiAction::shortcutVisibleInContextMenu
+ \brief Whether or not an action should show a shortcut in a context menu
+
+ In some applications, it may make sense to have actions with shortcuts in
+ context menus. If true, the shortcut (if valid) is shown when the action is
+ shown via a context menu, when it is false, it is not shown.
+
+ The default is to follow whether the Qt::AA_DontShowShortcutsInContextMenus attribute
+ is set for the application, falling back to the widget style hint.
+ Explicitly setting this property overrides the presence (or abscence) of the attribute.
+
+ \sa shortcut, QCoreApplication::setAttribute()
+*/
+void QGuiAction::setShortcutVisibleInContextMenu(bool visible)
+{
+ Q_D(QGuiAction);
+ if (d->shortcutVisibleInContextMenu == -1 || visible != bool(d->shortcutVisibleInContextMenu)) {
+ int oldValue = d->shortcutVisibleInContextMenu;
+ d->shortcutVisibleInContextMenu = visible;
+ // Only send data changed if we really need to.
+ if (oldValue != -1
+ || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)) {
+ d->sendDataChanged();
+ }
+ }
+}
+
+bool QGuiAction::isShortcutVisibleInContextMenu() const
+{
+ Q_D(const QGuiAction);
+ if (d->shortcutVisibleInContextMenu == -1) {
+ return !QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)
+ && QGuiApplication::styleHints()->showShortcutsInContextMenus();
+ }
+ return d->shortcutVisibleInContextMenu;
+}
+
+#ifndef QT_NO_DEBUG_STREAM
+Q_GUI_EXPORT QDebug operator<<(QDebug d, const QGuiAction *action)
+{
+ QDebugStateSaver saver(d);
+ d.nospace();
+ d << "QAction(" << static_cast<const void *>(action);
+ if (action) {
+ d << " text=" << action->text();
+ if (!action->toolTip().isEmpty())
+ d << " toolTip=" << action->toolTip();
+ if (action->isCheckable())
+ d << " checked=" << action->isChecked();
+#if QT_CONFIG(shortcut)
+ if (!action->shortcut().isEmpty())
+ d << " shortcut=" << action->shortcut();
+#endif
+ d << " menuRole=";
+ QtDebugUtils::formatQEnum(d, action->menuRole());
+ d << " visible=" << action->isVisible();
+ } else {
+ d << '0';
+ }
+ d << ')';
+ return d;
+}
+#endif // QT_NO_DEBUG_STREAM
+
+QT_END_NAMESPACE
+
+#include "moc_qguiaction.cpp"
diff --git a/src/gui/kernel/qguiaction.h b/src/gui/kernel/qguiaction.h
new file mode 100644
index 0000000000..454f66893f
--- /dev/null
+++ b/src/gui/kernel/qguiaction.h
@@ -0,0 +1,198 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QGUIACTION_H
+#define QGUIACTION_H
+
+#include <QtGui/qtguiglobal.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/qkeysequence.h>
+#endif
+#include <QtGui/qicon.h>
+#include <QtCore/qstring.h>
+#include <QtCore/qvariant.h>
+
+QT_REQUIRE_CONFIG(action);
+
+QT_BEGIN_NAMESPACE
+
+class QActionEvent;
+class QGuiActionGroup;
+class QGuiActionPrivate;
+
+class Q_GUI_EXPORT QGuiAction : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QGuiAction)
+
+ Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable NOTIFY changed)
+ Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled)
+ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY changed)
+ Q_PROPERTY(QIcon icon READ icon WRITE setIcon NOTIFY changed)
+ Q_PROPERTY(QString text READ text WRITE setText NOTIFY changed)
+ Q_PROPERTY(QString iconText READ iconText WRITE setIconText NOTIFY changed)
+ Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip NOTIFY changed)
+ Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip NOTIFY changed)
+ Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis NOTIFY changed)
+ Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY changed)
+#if QT_CONFIG(shortcut)
+ Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut NOTIFY changed)
+ Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext NOTIFY changed)
+ Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat NOTIFY changed)
+#endif // QT_CONFIG(shortcut)
+ Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY changed)
+ Q_PROPERTY(MenuRole menuRole READ menuRole WRITE setMenuRole NOTIFY changed)
+ Q_PROPERTY(bool iconVisibleInMenu READ isIconVisibleInMenu WRITE setIconVisibleInMenu NOTIFY changed)
+ Q_PROPERTY(bool shortcutVisibleInContextMenu READ isShortcutVisibleInContextMenu WRITE setShortcutVisibleInContextMenu NOTIFY changed)
+ Q_PROPERTY(Priority priority READ priority WRITE setPriority)
+
+public:
+ // note this is copied into qplatformmenu.h, which must stay in sync
+ enum MenuRole { NoRole = 0, TextHeuristicRole, ApplicationSpecificRole, AboutQtRole,
+ AboutRole, PreferencesRole, QuitRole };
+ Q_ENUM(MenuRole)
+ enum Priority { LowPriority = 0,
+ NormalPriority = 128,
+ HighPriority = 256};
+ Q_ENUM(Priority)
+ explicit QGuiAction(QObject *parent = nullptr);
+ explicit QGuiAction(const QString &text, QObject *parent = nullptr);
+ explicit QGuiAction(const QIcon &icon, const QString &text, QObject *parent = nullptr);
+
+ ~QGuiAction();
+
+ void setActionGroup(QGuiActionGroup *group);
+ QGuiActionGroup *guiActionGroup() const;
+ void setIcon(const QIcon &icon);
+ QIcon icon() const;
+
+ void setText(const QString &text);
+ QString text() const;
+
+ void setIconText(const QString &text);
+ QString iconText() const;
+
+ void setToolTip(const QString &tip);
+ QString toolTip() const;
+
+ void setStatusTip(const QString &statusTip);
+ QString statusTip() const;
+
+ void setWhatsThis(const QString &what);
+ QString whatsThis() const;
+
+ void setPriority(Priority priority);
+ Priority priority() const;
+
+ void setSeparator(bool b);
+ bool isSeparator() const;
+
+#if QT_CONFIG(shortcut)
+ void setShortcut(const QKeySequence &shortcut);
+ QKeySequence shortcut() const;
+
+ void setShortcuts(const QList<QKeySequence> &shortcuts);
+ void setShortcuts(QKeySequence::StandardKey);
+ QList<QKeySequence> shortcuts() const;
+
+ void setShortcutContext(Qt::ShortcutContext context);
+ Qt::ShortcutContext shortcutContext() const;
+
+ void setAutoRepeat(bool);
+ bool autoRepeat() const;
+#endif // QT_CONFIG(shortcut)
+
+ void setFont(const QFont &font);
+ QFont font() const;
+
+ void setCheckable(bool);
+ bool isCheckable() const;
+
+ QVariant data() const;
+ void setData(const QVariant &var);
+
+ bool isChecked() const;
+
+ bool isEnabled() const;
+
+ bool isVisible() const;
+
+ enum ActionEvent { Trigger, Hover };
+ void activate(ActionEvent event);
+
+ void setMenuRole(MenuRole menuRole);
+ MenuRole menuRole() const;
+
+ void setIconVisibleInMenu(bool visible);
+ bool isIconVisibleInMenu() const;
+
+ void setShortcutVisibleInContextMenu(bool show);
+ bool isShortcutVisibleInContextMenu() const;
+
+protected:
+ bool event(QEvent *) override;
+ QGuiAction(QGuiActionPrivate &dd, QObject *parent);
+
+public Q_SLOTS:
+ void trigger() { activate(Trigger); }
+ void hover() { activate(Hover); }
+ void setChecked(bool);
+ void toggle();
+ void setEnabled(bool);
+ inline void setDisabled(bool b) { setEnabled(!b); }
+ void setVisible(bool);
+
+Q_SIGNALS:
+ void changed();
+ void triggered(bool checked = false);
+ void hovered();
+ void toggled(bool);
+
+private:
+ Q_DISABLE_COPY(QGuiAction)
+ friend class QGuiActionGroup;
+};
+
+#ifndef QT_NO_DEBUG_STREAM
+Q_GUI_EXPORT QDebug operator<<(QDebug, const QGuiAction *);
+#endif
+
+QT_END_NAMESPACE
+
+#endif // QGUIACTION_H
diff --git a/src/opengl/qglpaintdevice_p.h b/src/gui/kernel/qguiaction_p.h
index bfecdabd53..3358ed1070 100644
--- a/src/opengl/qglpaintdevice_p.h
+++ b/src/gui/kernel/qguiaction_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,77 +37,92 @@
**
****************************************************************************/
-#ifndef QGLPAINTDEVICE_P_H
-#define QGLPAINTDEVICE_P_H
+#ifndef QGUIACTION_P_H
+#define QGUIACTION_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
-// of the Qt OpenGL module. This header file may change from
-// version to version without notice, or even be removed.
+// of other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
//
// We mean it.
//
+#include <QtGui/private/qtguiglobal_p.h>
+#include <QtGui/qguiaction.h>
+#include <QtGui/qfont.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/private/qshortcutmap_p.h>
+#endif
+#include "private/qobject_p.h"
-#include <qpaintdevice.h>
-#include <QtOpenGL/qgl.h>
-
+QT_REQUIRE_CONFIG(action);
QT_BEGIN_NAMESPACE
-class Q_OPENGL_EXPORT QGLPaintDevice : public QPaintDevice
-{
-public:
- QGLPaintDevice();
- virtual ~QGLPaintDevice();
-
- int devType() const override {return QInternal::OpenGL;}
-
- virtual void beginPaint();
- virtual void ensureActiveTarget();
- virtual void endPaint();
-
- virtual QGLContext* context() const = 0;
- virtual QGLFormat format() const;
- virtual QSize size() const = 0;
- virtual bool alphaRequested() const;
- virtual bool isFlipped() const;
-
- // returns the QGLPaintDevice for the given QPaintDevice
- static QGLPaintDevice* getDevice(QPaintDevice*);
+class QShortcutMap;
-protected:
- int metric(QPaintDevice::PaintDeviceMetric metric) const override;
- GLuint m_previousFBO;
- GLuint m_thisFBO;
-};
-
-
-// Wraps a QGLWidget
-class QGLWidget;
-class Q_OPENGL_EXPORT QGLWidgetGLPaintDevice : public QGLPaintDevice
+class Q_GUI_EXPORT QGuiActionPrivate : public QObjectPrivate
{
+ Q_DECLARE_PUBLIC(QGuiAction)
public:
- QGLWidgetGLPaintDevice();
-
- virtual QPaintEngine* paintEngine() const override;
-
- // QGLWidgets need to do swapBufers in endPaint:
- virtual void beginPaint() override;
- virtual void endPaint() override;
- virtual QSize size() const override;
- virtual QGLContext* context() const override;
-
- void setWidget(QGLWidget*);
-
-private:
- friend class QGLWidget;
- QGLWidget *glWidget;
+ QGuiActionPrivate();
+ ~QGuiActionPrivate();
+
+#if QT_CONFIG(shortcut)
+ virtual QShortcutMap::ContextMatcher contextMatcher() const;
+#endif
+
+ static QGuiActionPrivate *get(QGuiAction *q)
+ {
+ return q->d_func();
+ }
+
+
+ QPointer<QGuiActionGroup> group;
+ QString text;
+ QString iconText;
+ QIcon icon;
+ QString tooltip;
+ QString statustip;
+ QString whatsthis;
+#if QT_CONFIG(shortcut)
+ QKeySequence shortcut;
+ QList<QKeySequence> alternateShortcuts;
+#endif
+ QVariant userData;
+#if QT_CONFIG(shortcut)
+ int shortcutId = 0;
+ QVector<int> alternateShortcutIds;
+ Qt::ShortcutContext shortcutContext = Qt::WindowShortcut;
+ uint autorepeat : 1;
+#endif
+ QFont font;
+ uint enabled : 1, forceDisabled : 1;
+ uint visible : 1, forceInvisible : 1;
+ uint checkable : 1;
+ uint checked : 1;
+ uint separator : 1;
+ uint fontSet : 1;
+
+ int iconVisibleInMenu : 2; // Only has values -1, 0, and 1
+ int shortcutVisibleInContextMenu : 2; // Only has values -1, 0, and 1
+
+ QGuiAction::MenuRole menuRole = QGuiAction::TextHeuristicRole;
+ QGuiAction::Priority priority = QGuiAction::NormalPriority;
+
+#if QT_CONFIG(shortcut)
+ void redoGrab(QShortcutMap &map);
+ void redoGrabAlternate(QShortcutMap &map);
+ void setShortcutEnabled(bool enable, QShortcutMap &map);
+#endif // QT_NO_SHORTCUT
+
+ void sendDataChanged();
};
QT_END_NAMESPACE
-#endif // QGLPAINTDEVICE_P_H
+#endif // QACTION_P_H
diff --git a/src/gui/kernel/qguiactiongroup.cpp b/src/gui/kernel/qguiactiongroup.cpp
new file mode 100644
index 0000000000..7360214aad
--- /dev/null
+++ b/src/gui/kernel/qguiactiongroup.cpp
@@ -0,0 +1,346 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qguiactiongroup.h"
+
+#include "qguiaction.h"
+#include "qguiaction_p.h"
+#include "qguiactiongroup_p.h"
+#include "qevent.h"
+#include "qlist.h"
+
+QT_BEGIN_NAMESPACE
+
+QGuiActionGroupPrivate::QGuiActionGroupPrivate() :
+ enabled(1), visible(1)
+{
+}
+
+QGuiActionGroupPrivate::~QGuiActionGroupPrivate() = default;
+
+void QGuiActionGroup::_q_actionChanged()
+{
+ Q_D(QGuiActionGroup);
+ auto action = qobject_cast<QGuiAction*>(sender());
+ Q_ASSERT_X(action != nullptr, "QGuiActionGroup::_q_actionChanged", "internal error");
+ if (d->exclusionPolicy != QGuiActionGroup::ExclusionPolicy::None) {
+ if (action->isChecked()) {
+ if (action != d->current) {
+ if (!d->current.isNull())
+ d->current->setChecked(false);
+ d->current = action;
+ }
+ } else if (action == d->current) {
+ d->current = nullptr;
+ }
+ }
+}
+
+void QGuiActionGroup::_q_actionTriggered()
+{
+ Q_D(QGuiActionGroup);
+ auto action = qobject_cast<QGuiAction*>(sender());
+ Q_ASSERT_X(action != nullptr, "QGuiActionGroup::_q_actionTriggered", "internal error");
+ d->emitSignal(QGuiActionGroupPrivate::Triggered, action);
+}
+
+void QGuiActionGroup::_q_actionHovered()
+{
+ Q_D(QGuiActionGroup);
+ auto action = qobject_cast<QGuiAction*>(sender());
+ Q_ASSERT_X(action != nullptr, "QGuiActionGroup::_q_actionHovered", "internal error");
+ d->emitSignal(QGuiActionGroupPrivate::Hovered, action);
+}
+
+/*!
+ \class QGuiActionGroup
+ \brief The QGuiActionGroup class groups actions together.
+ \since 6.0
+
+ \inmodule QtGui
+
+ QGuiActionGroup is a base class for classes grouping
+ classes inhheriting QGuiAction objects together.
+
+ In some situations it is useful to group QGuiAction objects together.
+ For example, if you have a \uicontrol{Left Align} action, a \uicontrol{Right
+ Align} action, a \uicontrol{Justify} action, and a \uicontrol{Center} action,
+ only one of these actions should be active at any one time. One
+ simple way of achieving this is to group the actions together in
+ an action group, inheriting QGuiActionGroup.
+
+ \sa QGuiAction
+*/
+
+/*!
+ \enum QGuiActionGroup::ExclusionPolicy
+
+ This enum specifies the different policies that can be used to
+ control how the group performs exclusive checking on checkable actions.
+
+ \value None
+ The actions in the group can be checked independently of each other.
+
+ \value Exclusive
+ Exactly one action can be checked at any one time.
+ This is the default policy.
+
+ \value ExclusiveOptional
+ At most one action can be checked at any one time. The actions
+ can also be all unchecked.
+
+ \sa exclusionPolicy
+*/
+
+/*!
+ Constructs an action group for the \a parent object.
+
+ The action group is exclusive by default. Call setExclusive(false)
+ to make the action group non-exclusive. To make the group exclusive
+ but allow unchecking the active action call instead
+ setExclusionPolicy(QGuiActionGroup::ExclusionPolicy::ExclusiveOptional)
+*/
+QGuiActionGroup::QGuiActionGroup(QObject* parent) :
+ QGuiActionGroup(*new QGuiActionGroupPrivate, parent)
+{
+}
+
+QGuiActionGroup::QGuiActionGroup(QGuiActionGroupPrivate &dd, QObject *parent) :
+ QObject(dd, parent)
+{
+}
+
+/*!
+ Destroys the action group.
+*/
+QGuiActionGroup::~QGuiActionGroup() = default;
+
+/*!
+ \fn QGuiAction *QGuiActionGroup::addAction(QGuiAction *action)
+
+ Adds the \a action to this group, and returns it.
+
+ Normally an action is added to a group by creating it with the
+ group as its parent, so this function is not usually used.
+
+ \sa QGuiAction::setActionGroup()
+*/
+QGuiAction *QGuiActionGroup::addAction(QGuiAction* a)
+{
+ Q_D(QGuiActionGroup);
+ if (!d->actions.contains(a)) {
+ d->actions.append(a);
+ QObject::connect(a, &QGuiAction::triggered, this, &QGuiActionGroup::_q_actionTriggered);
+ QObject::connect(a, &QGuiAction::changed, this, &QGuiActionGroup::_q_actionChanged);
+ QObject::connect(a, &QGuiAction::hovered, this, &QGuiActionGroup::_q_actionHovered);
+ }
+ if (!a->d_func()->forceDisabled) {
+ a->setEnabled(d->enabled);
+ a->d_func()->forceDisabled = false;
+ }
+ if (!a->d_func()->forceInvisible) {
+ a->setVisible(d->visible);
+ a->d_func()->forceInvisible = false;
+ }
+ if (a->isChecked())
+ d->current = a;
+ QGuiActionGroup *oldGroup = a->d_func()->group;
+ if (oldGroup != this) {
+ if (oldGroup)
+ oldGroup->removeAction(a);
+ a->d_func()->group = this;
+ a->d_func()->sendDataChanged();
+ }
+ return a;
+}
+
+/*!
+ Removes the \a action from this group. The action will have no
+ parent as a result.
+
+ \sa QGuiAction::setActionGroup()
+*/
+void QGuiActionGroup::removeAction(QGuiAction *action)
+{
+ Q_D(QGuiActionGroup);
+ if (d->actions.removeAll(action)) {
+ if (action == d->current)
+ d->current = nullptr;
+ QObject::disconnect(action, &QGuiAction::triggered, this, &QGuiActionGroup::_q_actionTriggered);
+ QObject::disconnect(action, &QGuiAction::changed, this, &QGuiActionGroup::_q_actionChanged);
+ QObject::disconnect(action, &QGuiAction::hovered, this, &QGuiActionGroup::_q_actionHovered);
+ action->d_func()->group = nullptr;
+ }
+}
+
+/*!
+ Returns the list of this groups's actions. This may be empty.
+*/
+QList<QGuiAction*> QGuiActionGroup::guiActions() const
+{
+ Q_D(const QGuiActionGroup);
+ return d->actions;
+}
+
+/*!
+ \brief Enable or disable the group exclusion checking
+
+ This is a convenience method that calls
+ setExclusionPolicy(ExclusionPolicy::Exclusive) when \a b is true,
+ else setExclusionPolicy(QActionGroup::ExclusionPolicy::None).
+
+ \sa QGuiActionGroup::exclusionPolicy
+*/
+void QGuiActionGroup::setExclusive(bool b)
+{
+ setExclusionPolicy(b ? QGuiActionGroup::ExclusionPolicy::Exclusive
+ : QGuiActionGroup::ExclusionPolicy::None);
+}
+
+/*!
+ \brief Returns true if the group is exclusive
+
+ The group is exclusive if the ExclusionPolicy is either Exclusive
+ or ExclusionOptional.
+
+*/
+bool QGuiActionGroup::isExclusive() const
+{
+ return exclusionPolicy() != QGuiActionGroup::ExclusionPolicy::None;
+}
+
+/*!
+ \property QGuiActionGroup::exclusionPolicy
+ \brief This property holds the group exclusive checking policy
+
+ If exclusionPolicy is set to Exclusive, only one checkable
+ action in the action group can ever be active at any time. If the user
+ chooses another checkable action in the group, the one they chose becomes
+ active and the one that was active becomes inactive. If exclusionPolicy is
+ set to ExclusionOptional the group is exclusive but the active checkable
+ action in the group can be unchecked leaving the group with no actions
+ checked.
+
+ \sa QGuiAction::checkable
+*/
+void QGuiActionGroup::setExclusionPolicy(QGuiActionGroup::ExclusionPolicy policy)
+{
+ Q_D(QGuiActionGroup);
+ d->exclusionPolicy = policy;
+}
+
+QGuiActionGroup::ExclusionPolicy QGuiActionGroup::exclusionPolicy() const
+{
+ Q_D(const QGuiActionGroup);
+ return d->exclusionPolicy;
+}
+
+/*!
+ \fn void QGuiActionGroup::setDisabled(bool b)
+
+ This is a convenience function for the \l enabled property, that
+ is useful for signals--slots connections. If \a b is true the
+ action group is disabled; otherwise it is enabled.
+*/
+
+/*!
+ \property QGuiActionGroup::enabled
+ \brief whether the action group is enabled
+
+ Each action in the group will be enabled or disabled unless it
+ has been explicitly disabled.
+
+ \sa QGuiAction::setEnabled()
+*/
+void QGuiActionGroup::setEnabled(bool b)
+{
+ Q_D(QGuiActionGroup);
+ d->enabled = b;
+ for (auto action : qAsConst(d->actions)) {
+ if (!action->d_func()->forceDisabled) {
+ action->setEnabled(b);
+ action->d_func()->forceDisabled = false;
+ }
+ }
+}
+
+bool QGuiActionGroup::isEnabled() const
+{
+ Q_D(const QGuiActionGroup);
+ return d->enabled;
+}
+
+/*!
+ Returns the currently checked action in the group, or \nullptr if
+ none are checked.
+*/
+QGuiAction *QGuiActionGroup::checkedGuiAction() const
+{
+ Q_D(const QGuiActionGroup);
+ return d->current.data();
+}
+
+/*!
+ \property QGuiActionGroup::visible
+ \brief whether the action group is visible
+
+ Each action in the action group will match the visible state of
+ this group unless it has been explicitly hidden.
+
+ \sa QGuiAction::setEnabled()
+*/
+void QGuiActionGroup::setVisible(bool b)
+{
+ Q_D(QGuiActionGroup);
+ d->visible = b;
+ for (auto action : qAsConst(d->actions)) {
+ if (!action->d_func()->forceInvisible) {
+ action->setVisible(b);
+ action->d_func()->forceInvisible = false;
+ }
+ }
+}
+
+bool QGuiActionGroup::isVisible() const
+{
+ Q_D(const QGuiActionGroup);
+ return d->visible;
+}
+
+QT_END_NAMESPACE
diff --git a/src/gui/image/qpictureformatplugin.h b/src/gui/kernel/qguiactiongroup.h
index 3f59c04d79..ef08fb2e04 100644
--- a/src/gui/image/qpictureformatplugin.h
+++ b/src/gui/kernel/qguiactiongroup.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
@@ -37,40 +37,68 @@
**
****************************************************************************/
-#ifndef QPICTUREFORMATPLUGIN_H
-#define QPICTUREFORMATPLUGIN_H
+#ifndef QGUIACTIONGROUP_H
+#define QGUIACTIONGROUP_H
#include <QtGui/qtguiglobal.h>
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_NAMESPACE
+#include <QtGui/qguiaction.h>
+QT_REQUIRE_CONFIG(action);
-#if !defined(QT_NO_PICTURE)
-
-class QPicture;
-class QImage;
-class QString;
-class QStringList;
+QT_BEGIN_NAMESPACE
-#define QPictureFormatInterface_iid "org.qt-project.Qt.QPictureFormatInterface"
+class QGuiActionGroupPrivate;
-class Q_GUI_EXPORT QPictureFormatPlugin : public QObject
+class Q_GUI_EXPORT QGuiActionGroup : public QObject
{
Q_OBJECT
+ Q_DECLARE_PRIVATE(QGuiActionGroup)
+
+ Q_PROPERTY(QGuiActionGroup::ExclusionPolicy exclusionPolicy READ exclusionPolicy WRITE setExclusionPolicy)
+ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
+ Q_PROPERTY(bool visible READ isVisible WRITE setVisible)
+
public:
- explicit QPictureFormatPlugin(QObject *parent = nullptr);
- ~QPictureFormatPlugin();
+ enum class ExclusionPolicy {
+ None,
+ Exclusive,
+ ExclusiveOptional
+ };
+ Q_ENUM(ExclusionPolicy)
- virtual bool loadPicture(const QString &format, const QString &filename, QPicture *pic);
- virtual bool savePicture(const QString &format, const QString &filename, const QPicture &pic);
- virtual bool installIOHandler(const QString &format) = 0;
+ explicit QGuiActionGroup(QObject *parent);
+ ~QGuiActionGroup();
-};
+ QGuiAction *addAction(QGuiAction *a);
+ void removeAction(QGuiAction *a);
+ QList<QGuiAction*> guiActions() const;
+ QGuiAction *checkedGuiAction() const;
-#endif // QT_NO_PICTURE
+ bool isExclusive() const;
+ bool isEnabled() const;
+ bool isVisible() const;
+ ExclusionPolicy exclusionPolicy() const;
+
+
+public Q_SLOTS:
+ void setEnabled(bool);
+ inline void setDisabled(bool b) { setEnabled(!b); }
+ void setVisible(bool);
+ void setExclusive(bool);
+ void setExclusionPolicy(ExclusionPolicy policy);
+
+private Q_SLOTS:
+ void _q_actionTriggered();
+ void _q_actionHovered();
+ void _q_actionChanged();
+
+protected:
+ QGuiActionGroup(QGuiActionGroupPrivate &dd, QObject *parent);
+
+private:
+ Q_DISABLE_COPY(QGuiActionGroup)
+};
QT_END_NAMESPACE
-#endif // QPICTUREFORMATPLUGIN_H
+#endif // QGUIACTIONGROUP_H
diff --git a/src/opengl/qgraphicsshadereffect_p.h b/src/gui/kernel/qguiactiongroup_p.h
index 218caa2936..99a58262c9 100644
--- a/src/opengl/qgraphicsshadereffect_p.h
+++ b/src/gui/kernel/qguiactiongroup_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,54 +37,55 @@
**
****************************************************************************/
-#ifndef QGRAPHICSSHADEREFFECT_P_H
-#define QGRAPHICSSHADEREFFECT_P_H
+#ifndef QGUIACTIONGROUP_P_H
+#define QGUIACTIONGROUP_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
+// This file is not part of the Qt API. It exists for the convenience
+// of other Qt classes. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
-#include <QtWidgets/qgraphicseffect.h>
+#include <QtGui/private/qtguiglobal_p.h>
+#include <QtGui/qguiactiongroup.h>
+#include <QtGui/qfont.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/private/qshortcutmap_p.h>
+#endif
+#include "private/qobject_p.h"
-#include <QtOpenGL/qtopenglglobal.h>
-
-QT_REQUIRE_CONFIG(graphicseffect);
+QT_REQUIRE_CONFIG(action);
QT_BEGIN_NAMESPACE
-class QGLShaderProgram;
-class QGLCustomShaderEffectStage;
-class QGraphicsShaderEffectPrivate;
-
-class Q_OPENGL_EXPORT QGraphicsShaderEffect : public QGraphicsEffect
+class Q_GUI_EXPORT QGuiActionGroupPrivate : public QObjectPrivate
{
- Q_OBJECT
+ Q_DECLARE_PUBLIC(QGuiActionGroup)
public:
- QGraphicsShaderEffect(QObject *parent = nullptr);
- virtual ~QGraphicsShaderEffect();
+ enum Signal { Triggered, Hovered };
- QByteArray pixelShaderFragment() const;
- void setPixelShaderFragment(const QByteArray& code);
+ QGuiActionGroupPrivate();
+ ~QGuiActionGroupPrivate();
-protected:
- void draw(QPainter *painter) override;
- void setUniformsDirty();
- virtual void setUniforms(QGLShaderProgram *program);
+ virtual void emitSignal(Signal, QGuiAction *) {}
-private:
- Q_DECLARE_PRIVATE(QGraphicsShaderEffect)
- Q_DISABLE_COPY_MOVE(QGraphicsShaderEffect)
+ QList<QGuiAction *> actions;
+ QPointer<QGuiAction> current;
+ uint enabled : 1;
+ uint visible : 1;
+ QGuiActionGroup::ExclusionPolicy exclusionPolicy = QGuiActionGroup::ExclusionPolicy::Exclusive;
- friend class QGLCustomShaderEffectStage;
+private:
+ void _q_actionTriggered(); //private slot
+ void _q_actionChanged(); //private slot
+ void _q_actionHovered(); //private slot
};
QT_END_NAMESPACE
-#endif // QGRAPHICSSHADEREFFECT_P_H
+#endif // QACTIONGROUP_P_H
diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp
index 680c69a978..6503acaef0 100644
--- a/src/gui/kernel/qguiapplication.cpp
+++ b/src/gui/kernel/qguiapplication.cpp
@@ -1187,14 +1187,18 @@ Q_LOGGING_CATEGORY(lcQpaPluginLoading, "qt.qpa.plugin");
static void init_platform(const QString &pluginNamesWithArguments, const QString &platformPluginPath, const QString &platformThemeName, int &argc, char **argv)
{
- QStringList plugins = pluginNamesWithArguments.split(QLatin1Char(';'));
+ QStringList plugins = pluginNamesWithArguments.split(QLatin1Char(';'), QString::SkipEmptyParts);
QStringList platformArguments;
QStringList availablePlugins = QPlatformIntegrationFactory::keys(platformPluginPath);
for (const auto &pluginArgument : plugins) {
// Split into platform name and arguments
- QStringList arguments = pluginArgument.split(QLatin1Char(':'));
+ QStringList arguments = pluginArgument.split(QLatin1Char(':'), QString::SkipEmptyParts);
+ if (arguments.isEmpty())
+ continue;
const QString name = arguments.takeFirst().toLower();
QString argumentsKey = name;
+ if (name.isEmpty())
+ continue;
argumentsKey[0] = argumentsKey.at(0).toUpper();
arguments.append(QLibraryInfo::platformPluginArguments(argumentsKey));
diff --git a/src/gui/kernel/qguiapplication_p.h b/src/gui/kernel/qguiapplication_p.h
index 2fe4ae02cf..a8017216d4 100644
--- a/src/gui/kernel/qguiapplication_p.h
+++ b/src/gui/kernel/qguiapplication_p.h
@@ -62,7 +62,10 @@
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qwindowsysteminterface_p.h>
-#include "private/qshortcutmap_p.h"
+#if QT_CONFIG(shortcut)
+# include "private/qshortcutmap_p.h"
+#endif
+
#include <qicon.h>
QT_BEGIN_NAMESPACE
@@ -263,7 +266,7 @@ public:
QIcon forcedWindowIcon;
static QList<QObject *> generic_plugin_list;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
QShortcutMap shortcutMap;
#endif
diff --git a/src/gui/kernel/qguishortcut.cpp b/src/gui/kernel/qguishortcut.cpp
new file mode 100644
index 0000000000..add1dce12e
--- /dev/null
+++ b/src/gui/kernel/qguishortcut.cpp
@@ -0,0 +1,354 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qguishortcut.h"
+#include "qguishortcut_p.h"
+
+#include <qevent.h>
+#include <qguiapplication.h>
+#include <qwindow.h>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformmenu.h>
+
+QT_BEGIN_NAMESPACE
+
+#define QAPP_CHECK(functionName) \
+ if (Q_UNLIKELY(!qApp)) { \
+ qWarning("QGuiShortcut: Initialize QGuiApplication before calling '" functionName "'."); \
+ return; \
+ }
+
+/*!
+ \class QGuiShortcut
+ \brief The QGuiShortcut class is a base class for handling keyboard shortcuts.
+
+ \ingroup events
+ \inmodule QtGui
+ \since 6.0
+
+ The QGuiShortcut class is a base class for classes providing a way of
+ connecting keyboard shortcuts to Qt's \l{signals and slots} mechanism,
+ so that objects can be informed when a shortcut is executed. The shortcut
+ can be set up to contain all the key presses necessary to
+ describe a keyboard shortcut, including the states of modifier
+ keys such as \uicontrol Shift, \uicontrol Ctrl, and \uicontrol Alt.
+
+ \target mnemonic
+
+ \sa QShortcutEvent, QKeySequence, QAction
+*/
+
+/*!
+ \fn void QGuiShortcut::activated()
+
+ This signal is emitted when the user types the shortcut's key
+ sequence.
+
+ \sa activatedAmbiguously()
+*/
+
+/*!
+ \fn void QGuiShortcut::activatedAmbiguously()
+
+ When a key sequence is being typed at the keyboard, it is said to
+ be ambiguous as long as it matches the start of more than one
+ shortcut.
+
+ When a shortcut's key sequence is completed,
+ activatedAmbiguously() is emitted if the key sequence is still
+ ambiguous (i.e., it is the start of one or more other shortcuts).
+ The activated() signal is not emitted in this case.
+
+ \sa activated()
+*/
+
+static bool simpleContextMatcher(QObject *object, Qt::ShortcutContext context)
+{
+ auto guiShortcut = qobject_cast<QGuiShortcut *>(object);
+ if (QGuiApplication::applicationState() != Qt::ApplicationActive || guiShortcut == nullptr)
+ return false;
+ if (context == Qt::ApplicationShortcut)
+ return true;
+ auto focusWindow = QGuiApplication::focusWindow();
+ if (!focusWindow)
+ return false;
+ auto window = qobject_cast<const QWindow *>(guiShortcut->parent());
+ if (!window)
+ return false;
+ if (focusWindow == window && focusWindow->isTopLevel())
+ return context == Qt::WindowShortcut || context == Qt::WidgetWithChildrenShortcut;
+ return focusWindow->isAncestorOf(window, QWindow::ExcludeTransients);
+}
+
+QShortcutMap::ContextMatcher QGuiShortcutPrivate::contextMatcher() const
+{
+ return simpleContextMatcher;
+}
+
+void QGuiShortcutPrivate::redoGrab(QShortcutMap &map)
+{
+ Q_Q(QGuiShortcut);
+ if (Q_UNLIKELY(!parent)) {
+ qWarning("QGuiShortcut: No window parent defined");
+ return;
+ }
+
+ if (sc_id)
+ map.removeShortcut(sc_id, q);
+ if (sc_sequence.isEmpty())
+ return;
+ sc_id = map.addShortcut(q, sc_sequence, sc_context, contextMatcher());
+ if (!sc_enabled)
+ map.setShortcutEnabled(false, sc_id, q);
+ if (!sc_autorepeat)
+ map.setShortcutAutoRepeat(false, sc_id, q);
+}
+
+/*!
+ Constructs a QGuiShortcut object for the \a parent window. Since no
+ shortcut key sequence is specified, the shortcut will not emit any
+ signals.
+
+ \sa setKey()
+*/
+QGuiShortcut::QGuiShortcut(QWindow *parent)
+ : QGuiShortcut(*new QGuiShortcutPrivate, parent)
+{
+}
+
+/*!
+ Constructs a QGuiShortcut object for the \a parent window. The shortcut
+ operates on its parent, listening for \l{QShortcutEvent}s that
+ match the \a key sequence. Depending on the ambiguity of the
+ event, the shortcut will call the \a member function, or the \a
+ ambiguousMember function, if the key press was in the shortcut's
+ \a context.
+*/
+QGuiShortcut::QGuiShortcut(const QKeySequence &key, QWindow *parent,
+ const char *member, const char *ambiguousMember,
+ Qt::ShortcutContext context)
+ : QGuiShortcut(*new QGuiShortcutPrivate, key, parent, member, ambiguousMember, context)
+{
+}
+
+/*!
+ \internal
+*/
+QGuiShortcut::QGuiShortcut(QGuiShortcutPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+ Q_ASSERT(parent != nullptr);
+}
+
+/*!
+ \internal
+*/
+QGuiShortcut::QGuiShortcut(QGuiShortcutPrivate &dd,
+ const QKeySequence &key, QObject *parent,
+ const char *member, const char *ambiguousMember,
+ Qt::ShortcutContext context)
+ : QGuiShortcut(dd, parent)
+{
+ QAPP_CHECK("QGuiShortcut");
+
+ Q_D(QGuiShortcut);
+ d->sc_context = context;
+ d->sc_sequence = key;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ if (member)
+ connect(this, SIGNAL(activated()), parent, member);
+ if (ambiguousMember)
+ connect(this, SIGNAL(activatedAmbiguously()), parent, ambiguousMember);
+}
+
+/*!
+ Destroys the shortcut.
+*/
+QGuiShortcut::~QGuiShortcut()
+{
+ Q_D(QGuiShortcut);
+ if (qApp)
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->sc_id, this);
+}
+
+/*!
+ \property QGuiShortcut::key
+ \brief the shortcut's key sequence
+
+ This is a key sequence with an optional combination of Shift, Ctrl,
+ and Alt. The key sequence may be supplied in a number of ways:
+
+ \snippet code/src_gui_kernel_qshortcut.cpp 1
+
+ By default, this property contains an empty key sequence.
+*/
+void QGuiShortcut::setKey(const QKeySequence &key)
+{
+ Q_D(QGuiShortcut);
+ if (d->sc_sequence == key)
+ return;
+ QAPP_CHECK("setKey");
+ d->sc_sequence = key;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+}
+
+QKeySequence QGuiShortcut::key() const
+{
+ Q_D(const QGuiShortcut);
+ return d->sc_sequence;
+}
+
+/*!
+ \property QGuiShortcut::enabled
+ \brief whether the shortcut is enabled
+
+ An enabled shortcut emits the activated() or activatedAmbiguously()
+ signal when a QShortcutEvent occurs that matches the shortcut's
+ key() sequence.
+
+ If the application is in \c WhatsThis mode the shortcut will not emit
+ the signals, but will show the "What's This?" text instead.
+
+ By default, this property is \c true.
+
+ \sa whatsThis
+*/
+void QGuiShortcut::setEnabled(bool enable)
+{
+ Q_D(QGuiShortcut);
+ if (d->sc_enabled == enable)
+ return;
+ QAPP_CHECK("setEnabled");
+ d->sc_enabled = enable;
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutEnabled(enable, d->sc_id, this);
+}
+
+bool QGuiShortcut::isEnabled() const
+{
+ Q_D(const QGuiShortcut);
+ return d->sc_enabled;
+}
+
+/*!
+ \property QGuiShortcut::context
+ \brief the context in which the shortcut is valid
+
+ A shortcut's context decides in which circumstances a shortcut is
+ allowed to be triggered. The normal context is Qt::WindowShortcut,
+ which allows the shortcut to trigger if the parent (the widget
+ containing the shortcut) is a subwidget of the active top-level
+ window.
+
+ By default, this property is set to Qt::WindowShortcut.
+*/
+void QGuiShortcut::setContext(Qt::ShortcutContext context)
+{
+ Q_D(QGuiShortcut);
+ if (d->sc_context == context)
+ return;
+ QAPP_CHECK("setContext");
+ d->sc_context = context;
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+}
+
+Qt::ShortcutContext QGuiShortcut::context() const
+{
+ Q_D(const QGuiShortcut);
+ return d->sc_context;
+}
+
+/*!
+ \property QGuiShortcut::autoRepeat
+ \brief whether the shortcut can auto repeat
+
+ If true, the shortcut will auto repeat when the keyboard shortcut
+ combination is held down, provided that keyboard auto repeat is
+ enabled on the system.
+ The default value is true.
+*/
+void QGuiShortcut::setAutoRepeat(bool on)
+{
+ Q_D(QGuiShortcut);
+ if (d->sc_autorepeat == on)
+ return;
+ QAPP_CHECK("setAutoRepeat");
+ d->sc_autorepeat = on;
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutAutoRepeat(on, d->sc_id, this);
+}
+
+bool QGuiShortcut::autoRepeat() const
+{
+ Q_D(const QGuiShortcut);
+ return d->sc_autorepeat;
+}
+
+/*!
+ Returns the shortcut's ID.
+
+ \sa QShortcutEvent::shortcutId()
+*/
+int QGuiShortcut::id() const
+{
+ Q_D(const QGuiShortcut);
+ return d->sc_id;
+}
+
+/*!
+ \internal
+*/
+bool QGuiShortcut::event(QEvent *e)
+{
+ Q_D(QGuiShortcut);
+ if (d->sc_enabled && e->type() == QEvent::Shortcut) {
+ auto se = static_cast<QShortcutEvent *>(e);
+ if (se->shortcutId() == d->sc_id && se->key() == d->sc_sequence
+ && !d->handleWhatsThis()) {
+ if (se->isAmbiguous())
+ emit activatedAmbiguously();
+ else
+ emit activated();
+ return true;
+ }
+ }
+ return QObject::event(e);
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qguishortcut.cpp"
diff --git a/src/gui/image/qimage_compat.cpp b/src/gui/kernel/qguishortcut.h
index ba31a9ac9b..fb64f10c84 100644
--- a/src/gui/image/qimage_compat.cpp
+++ b/src/gui/kernel/qguishortcut.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
@@ -37,30 +37,62 @@
**
****************************************************************************/
-#ifdef QIMAGE_H
-# error "This file cannot be used with precompiled headers"
-#endif
-#define QT_COMPILING_QIMAGE_COMPAT_CPP
+#ifndef QGUISHORTCUT_H
+#define QGUISHORTCUT_H
-#include "qimage.h"
+#include <QtGui/qtguiglobal.h>
+#include <QtGui/qkeysequence.h>
+#include <QtCore/qobject.h>
+
+QT_REQUIRE_CONFIG(shortcut);
QT_BEGIN_NAMESPACE
-// These implementations must be the same as the inline versions in qimage.h
+class QGuiShortcutPrivate;
+class QWindow;
-QImage QImage::convertToFormat(Format f, Qt::ImageConversionFlags flags) const
+class Q_GUI_EXPORT QGuiShortcut : public QObject
{
- return convertToFormat_helper(f, flags);
-}
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QGuiShortcut)
+ Q_PROPERTY(QKeySequence key READ key WRITE setKey)
+ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
+ Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat)
+ Q_PROPERTY(Qt::ShortcutContext context READ context WRITE setContext)
+public:
+ explicit QGuiShortcut(QWindow *parent);
+ explicit QGuiShortcut(const QKeySequence& key, QWindow *parent,
+ const char *member = nullptr, const char *ambiguousMember = nullptr,
+ Qt::ShortcutContext context = Qt::WindowShortcut);
+ ~QGuiShortcut();
-QImage QImage::mirrored(bool horizontally, bool vertically) const
-{
- return mirrored_helper(horizontally, vertically);
-}
+ void setKey(const QKeySequence& key);
+ QKeySequence key() const;
-QImage QImage::rgbSwapped() const
-{
- return rgbSwapped_helper();
-}
+ void setEnabled(bool enable);
+ bool isEnabled() const;
+
+ void setContext(Qt::ShortcutContext context);
+ Qt::ShortcutContext context() const;
+
+ void setAutoRepeat(bool on);
+ bool autoRepeat() const;
+
+ int id() const;
+
+Q_SIGNALS:
+ void activated();
+ void activatedAmbiguously();
+
+protected:
+ QGuiShortcut(QGuiShortcutPrivate &dd, QObject *parent);
+ QGuiShortcut(QGuiShortcutPrivate &dd, const QKeySequence& key, QObject *parent,
+ const char *member, const char *ambiguousMember,
+ Qt::ShortcutContext context);
+
+ bool event(QEvent *e) override;
+};
QT_END_NAMESPACE
+
+#endif // QGUISHORTCUT_H
diff --git a/src/opengl/gl2paintengineex/qglcustomshaderstage_p.h b/src/gui/kernel/qguishortcut_p.h
index 77421ebdd3..420b02ef1a 100644
--- a/src/opengl/gl2paintengineex/qglcustomshaderstage_p.h
+++ b/src/gui/kernel/qguishortcut_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,50 +37,56 @@
**
****************************************************************************/
-#ifndef QGL_CUSTOM_SHADER_STAGE_H
-#define QGL_CUSTOM_SHADER_STAGE_H
+#ifndef QGUISHORTCUT_P_H
+#define QGUISHORTCUT_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
+// 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 <QGLShaderProgram>
+#include <QtGui/private/qtguiglobal_p.h>
+#include "qguishortcut.h"
+#include <QtGui/qkeysequence.h>
+
+#include <QtCore/qstring.h>
+#include <QtCore/private/qobject_p.h>
+
+#include <private/qshortcutmap_p.h>
+
+
QT_BEGIN_NAMESPACE
+class QShortcutMap;
-class QGLCustomShaderStagePrivate;
-class Q_OPENGL_EXPORT QGLCustomShaderStage
+/*
+ \internal
+ Private data accessed through d-pointer.
+*/
+class Q_GUI_EXPORT QGuiShortcutPrivate : public QObjectPrivate
{
- Q_DECLARE_PRIVATE(QGLCustomShaderStage)
+ Q_DECLARE_PUBLIC(QGuiShortcut)
public:
- QGLCustomShaderStage();
- virtual ~QGLCustomShaderStage();
- virtual void setUniforms(QGLShaderProgram*) {}
+ QGuiShortcutPrivate() = default;
- void setUniformsDirty();
+ virtual QShortcutMap::ContextMatcher contextMatcher() const;
+ virtual bool handleWhatsThis() { return false; }
- bool setOnPainter(QPainter*);
- void removeFromPainter(QPainter*);
- QByteArray source() const;
-
- void setInactive();
-protected:
- void setSource(const QByteArray&);
-
-private:
- QGLCustomShaderStagePrivate* d_ptr;
+ QKeySequence sc_sequence;
+ Qt::ShortcutContext sc_context = Qt::WindowShortcut;
+ bool sc_enabled = true;
+ bool sc_autorepeat = true;
+ int sc_id = 0;
+ void redoGrab(QShortcutMap &map);
};
-
QT_END_NAMESPACE
-
-#endif
+#endif // QGUISHORTCUT_P_H
diff --git a/src/gui/kernel/qguivariant.cpp b/src/gui/kernel/qguivariant.cpp
index 4ed9d032f6..0f29633222 100644
--- a/src/gui/kernel/qguivariant.cpp
+++ b/src/gui/kernel/qguivariant.cpp
@@ -44,7 +44,9 @@
#include "qcursor.h"
#include "qfont.h"
#include "qimage.h"
-#include "qkeysequence.h"
+#if QT_CONFIG(shortcut)
+# include "qkeysequence.h"
+#endif
#include "qtransform.h"
#include "qmatrix.h"
#include "qpalette.h"
@@ -188,7 +190,7 @@ static bool convert(const QVariant::Private *d, int t,
case QVariant::String: {
QString *str = static_cast<QString *>(result);
switch (d->type) {
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
case QVariant::KeySequence:
*str = (*v_cast<QKeySequence>(d)).toString(QKeySequence::NativeText);
return true;
@@ -238,7 +240,7 @@ static bool convert(const QVariant::Private *d, int t,
return true;
}
break;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
case QVariant::Int:
if (d->type == QVariant::KeySequence) {
const QKeySequence &seq = *v_cast<QKeySequence>(d);
@@ -277,7 +279,7 @@ static bool convert(const QVariant::Private *d, int t,
return true;
}
break;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
case QVariant::KeySequence: {
QKeySequence *seq = static_cast<QKeySequence *>(result);
switch (d->type) {
diff --git a/src/gui/kernel/qkeymapper_p.h b/src/gui/kernel/qkeymapper_p.h
index 8364557020..fd53747fdd 100644
--- a/src/gui/kernel/qkeymapper_p.h
+++ b/src/gui/kernel/qkeymapper_p.h
@@ -53,7 +53,6 @@
#include <QtGui/private/qtguiglobal_p.h>
#include <qobject.h>
#include <private/qobject_p.h>
-#include <qkeysequence.h>
#include <qlist.h>
#include <qlocale.h>
#include <qevent.h>
diff --git a/src/gui/kernel/qkeysequence.cpp b/src/gui/kernel/qkeysequence.cpp
index e1244e1006..d5bdf1f15b 100644
--- a/src/gui/kernel/qkeysequence.cpp
+++ b/src/gui/kernel/qkeysequence.cpp
@@ -42,8 +42,6 @@
#include <qpa/qplatformtheme.h>
#include "private/qguiapplication_p.h"
-#if !defined(QT_NO_SHORTCUT) || defined(Q_CLANG_QDOC)
-
#include "qdebug.h"
#include <QtCore/qhashfunctions.h>
#ifndef QT_NO_DATASTREAM
@@ -1679,9 +1677,6 @@ QDebug operator<<(QDebug dbg, const QKeySequence &p)
}
#endif
-#endif // QT_NO_SHORTCUT
-
-
/*!
\typedef QKeySequence::DataPtr
\internal
diff --git a/src/gui/kernel/qkeysequence.h b/src/gui/kernel/qkeysequence.h
index 3dcbbe5941..68f256c37a 100644
--- a/src/gui/kernel/qkeysequence.h
+++ b/src/gui/kernel/qkeysequence.h
@@ -44,10 +44,9 @@
#include <QtCore/qstring.h>
#include <QtCore/qobjectdefs.h>
-QT_BEGIN_NAMESPACE
-
+QT_REQUIRE_CONFIG(shortcut);
-#if !defined(QT_NO_SHORTCUT) || defined(Q_CLANG_QDOC)
+QT_BEGIN_NAMESPACE
class QKeySequence;
@@ -227,17 +226,6 @@ Q_DECLARE_SHARED(QKeySequence)
Q_GUI_EXPORT QDebug operator<<(QDebug, const QKeySequence &);
#endif
-#else
-
-class Q_GUI_EXPORT QKeySequence
-{
-public:
- QKeySequence() {}
- QKeySequence(int) {}
-};
-
-#endif // QT_NO_SHORTCUT
-
QT_END_NAMESPACE
#endif // QKEYSEQUENCE_H
diff --git a/src/gui/kernel/qkeysequence_p.h b/src/gui/kernel/qkeysequence_p.h
index fbcab5d34e..8c59505561 100644
--- a/src/gui/kernel/qkeysequence_p.h
+++ b/src/gui/kernel/qkeysequence_p.h
@@ -56,9 +56,10 @@
#include <algorithm>
+QT_REQUIRE_CONFIG(shortcut);
+
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_SHORTCUT
struct QKeyBinding
{
QKeySequence::StandardKey standardKey;
@@ -87,7 +88,6 @@ public:
Q_GUI_EXPORT static QString keyName(int key, QKeySequence::SequenceFormat format);
static int decodeString(QString accel, QKeySequence::SequenceFormat format);
};
-#endif // QT_NO_SHORTCUT
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qpalette.cpp b/src/gui/kernel/qpalette.cpp
index fc063bc72c..e31ce00e14 100644
--- a/src/gui/kernel/qpalette.cpp
+++ b/src/gui/kernel/qpalette.cpp
@@ -44,10 +44,28 @@
#include "qvariant.h"
#include "qdebug.h"
+#include <QtCore/qmetaobject.h>
+
QT_BEGIN_NAMESPACE
static int qt_palette_count = 1;
+static constexpr QPalette::ResolveMask colorRoleOffset(QPalette::ColorGroup colorGroup)
+{
+ return QPalette::NColorRoles * colorGroup;
+}
+
+static constexpr QPalette::ResolveMask bitPosition(QPalette::ColorGroup colorGroup,
+ QPalette::ColorRole colorRole)
+{
+ return colorRole + colorRoleOffset(colorGroup);
+}
+
+Q_STATIC_ASSERT_X(bitPosition(QPalette::ColorGroup(QPalette::NColorGroups - 1),
+ QPalette::ColorRole(QPalette::NColorRoles - 1))
+ < sizeof(QPalette::ResolveMask) * CHAR_BIT,
+ "The resolve mask type is not wide enough to fit the entire bit mask.");
+
class QPalettePrivate {
public:
QPalettePrivate() : ref(1), ser_no(qt_palette_count++), detach_no(0) { }
@@ -321,11 +339,8 @@ static void qt_palette_from_color(QPalette &pal, const QColor &button)
Returns the placeholder text brush of the current color group.
- \note Before Qt 5.12, the placeholder text color was hard-coded in the code as
- QPalette::text().color() where an alpha of 128 was applied.
- We continue to support this behavior by default, unless you set your own brush.
- One can get back the original placeholder color setting the special QBrush default
- constructor as placeholder brush.
+ \note Before Qt 5.12, the placeholder text color was hard-coded as QPalette::text().color()
+ with an alpha of 128 applied. In Qt 6, it is an independent color.
\sa ColorRole, brush()
*/
@@ -538,8 +553,6 @@ static void qt_palette_from_color(QPalette &pal, const QColor &button)
QPalette::QPalette()
: d(nullptr)
{
- data.current_group = Active;
- data.resolve_mask = 0;
// Initialize to application palette if present, else default to black.
// This makes it possible to instantiate QPalette outside QGuiApplication,
// for example in the platform plugins.
@@ -549,7 +562,7 @@ QPalette::QPalette()
} else {
init();
qt_palette_from_color(*this, Qt::black);
- data.resolve_mask = 0;
+ data.resolveMask = 0;
}
}
@@ -681,8 +694,6 @@ QPalette::~QPalette()
/*!\internal*/
void QPalette::init() {
d = new QPalettePrivate;
- data.resolve_mask = 0;
- data.current_group = Active; //as a default..
}
/*!
@@ -739,7 +750,7 @@ const QBrush &QPalette::brush(ColorGroup gr, ColorRole cr) const
Q_ASSERT(cr < NColorRoles);
if(gr >= (int)NColorGroups) {
if(gr == Current) {
- gr = (ColorGroup)data.current_group;
+ gr = data.currentGroup;
} else {
qWarning("QPalette::brush: Unknown ColorGroup: %d", (int)gr);
gr = Active;
@@ -777,38 +788,18 @@ void QPalette::setBrush(ColorGroup cg, ColorRole cr, const QBrush &b)
}
if (cg == Current) {
- cg = ColorGroup(data.current_group);
+ cg = data.currentGroup;
} else if (cg >= NColorGroups) {
qWarning("QPalette::setBrush: Unknown ColorGroup: %d", cg);
cg = Active;
}
- // For placeholder we want to continue to respect the original behavior, which is
- // derivating the text color, but only if user has not yet set his own brush.
- // We then use Qt::NoBrush as an inernal way to know if the brush is customized or not.
-
- // ### Qt 6 - remove this special case
- // Part 1 - Restore initial color to the given color group
- if (cr == PlaceholderText && b == QBrush()) {
- QColor col = brush(Text).color();
- col.setAlpha(128);
- setBrush(cg, PlaceholderText, QBrush(col, Qt::NoBrush));
- return;
- }
-
if (d->br[cg][cr] != b) {
detach();
d->br[cg][cr] = b;
}
- data.resolve_mask |= (1<<cr);
-
- // ### Qt 6 - remove this special case
- // Part 2 - Update initial color to the given color group
- if (cr == Text && d->br[cg][PlaceholderText].style() == Qt::NoBrush) {
- QColor col = brush(Text).color();
- col.setAlpha(128);
- setBrush(cg, PlaceholderText, QBrush(col, Qt::NoBrush));
- }
+
+ data.resolveMask |= ResolveMask(1) << bitPosition(cg, cr);
}
/*!
@@ -817,12 +808,30 @@ void QPalette::setBrush(ColorGroup cg, ColorRole cr, const QBrush &b)
Returns \c true if the ColorGroup \a cg and ColorRole \a cr has been
set previously on this palette; otherwise returns \c false.
- \sa setBrush()
+ The ColorGroup \a cg should be less than QPalette::NColorGroups,
+ but you can use QPalette::Current. In this case, the previously
+ set current color group will be used.
+
+ The ColorRole \a cr should be less than QPalette::NColorRoles.
+
+ \sa setBrush(), currentColorGroup()
*/
bool QPalette::isBrushSet(ColorGroup cg, ColorRole cr) const
{
- Q_UNUSED(cg);
- return (data.resolve_mask & (1<<cr));
+ if (cg == Current)
+ cg = data.currentGroup;
+
+ if (cg >= NColorGroups) {
+ qWarning() << "Wrong color group:" << cg;
+ return false;
+ }
+
+ if (cr >= NColorRoles) {
+ qWarning() << "Wrong color role:" << cr;
+ return false;
+ }
+
+ return data.resolveMask & (ResolveMask(1) << bitPosition(cg, cr));
}
/*!
@@ -887,7 +896,7 @@ bool QPalette::isEqual(QPalette::ColorGroup group1, QPalette::ColorGroup group2)
{
if(group1 >= (int)NColorGroups) {
if(group1 == Current) {
- group1 = (ColorGroup)data.current_group;
+ group1 = data.currentGroup;
} else {
qWarning("QPalette::brush: Unknown ColorGroup(1): %d", (int)group1);
group1 = Active;
@@ -895,7 +904,7 @@ bool QPalette::isEqual(QPalette::ColorGroup group1, QPalette::ColorGroup group2)
}
if(group2 >= (int)NColorGroups) {
if(group2 == Current) {
- group2 = (ColorGroup)data.current_group;
+ group2 = data.currentGroup;
} else {
qWarning("QPalette::brush: Unknown ColorGroup(2): %d", (int)group2);
group2 = Active;
@@ -946,21 +955,25 @@ qint64 QPalette::cacheKey() const
*/
QPalette QPalette::resolve(const QPalette &other) const
{
- if ((*this == other && data.resolve_mask == other.data.resolve_mask)
- || data.resolve_mask == 0) {
+ if ((*this == other && data.resolveMask == other.data.resolveMask)
+ || data.resolveMask == 0) {
QPalette o = other;
- o.data.resolve_mask = data.resolve_mask;
+ o.data.resolveMask = data.resolveMask;
return o;
}
QPalette palette(*this);
palette.detach();
- for(int role = 0; role < (int)NColorRoles; role++)
- if (!(data.resolve_mask & (1<<role)))
- for(int grp = 0; grp < (int)NColorGroups; grp++)
+ for (int role = 0; role < int(NColorRoles); ++role) {
+ for (int grp = 0; grp < int(NColorGroups); ++grp) {
+ if (!(data.resolveMask & (ResolveMask(1) << bitPosition(ColorGroup(grp), ColorRole(role))))) {
palette.d->br[grp][role] = other.d->br[grp][role];
- palette.data.resolve_mask |= other.data.resolve_mask;
+ }
+ }
+ }
+
+ palette.data.resolveMask |= other.data.resolveMask;
return palette;
}
@@ -971,7 +984,12 @@ QPalette QPalette::resolve(const QPalette &other) const
*/
/*!
- \fn void QPalette::resolve(uint mask)
+ \typedef ResolveMaskType
+ \internal
+ */
+
+/*!
+ \fn void QPalette::resolve(ResolveMaskType mask)
\internal
*/
@@ -1105,10 +1123,15 @@ void QPalette::setColorGroup(ColorGroup cg, const QBrush &windowText, const QBru
QBrush(Qt::blue), QBrush(Qt::magenta), QBrush(toolTipBase),
QBrush(toolTipText));
- data.resolve_mask &= ~(1 << Highlight);
- data.resolve_mask &= ~(1 << HighlightedText);
- data.resolve_mask &= ~(1 << LinkVisited);
- data.resolve_mask &= ~(1 << Link);
+ for (int cr = Highlight; cr <= LinkVisited; ++cr) {
+ if (cg == All) {
+ for (int group = Active; group < NColorGroups; ++group) {
+ data.resolveMask &= ~(ResolveMask(1) << bitPosition(ColorGroup(group), ColorRole(cr)));
+ }
+ } else {
+ data.resolveMask &= ~(ResolveMask(1) << bitPosition(ColorGroup(cg), ColorRole(cr)));
+ }
+ }
}
@@ -1177,6 +1200,8 @@ Q_GUI_EXPORT QPalette qt_fusionPalette()
QColor button = backGround;
QColor shadow = dark.darker(135);
QColor disabledShadow = shadow.lighter(150);
+ QColor placeholder = text;
+ placeholder.setAlpha(128);
QPalette fusionPalette(Qt::black,backGround,light,dark,mid,text,base);
fusionPalette.setBrush(QPalette::Midlight, midLight);
@@ -1194,40 +1219,65 @@ Q_GUI_EXPORT QPalette qt_fusionPalette()
fusionPalette.setBrush(QPalette::Active, QPalette::Highlight, QColor(48, 140, 198));
fusionPalette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(48, 140, 198));
fusionPalette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(145, 145, 145));
+
+ fusionPalette.setBrush(QPalette::PlaceholderText, placeholder);
+
return fusionPalette;
}
#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug dbg, const QPalette &p)
+static QString groupsToString(const QPalette &p, QPalette::ColorRole cr)
{
- const char *colorGroupNames[] = {"Active", "Disabled", "Inactive"};
- const char *colorRoleNames[] =
- {"WindowText", "Button", "Light", "Midlight", "Dark", "Mid", "Text",
- "BrightText", "ButtonText", "Base", "Window", "Shadow", "Highlight",
- "HighlightedText", "Link", "LinkVisited", "AlternateBase", "NoRole",
- "ToolTipBase","ToolTipText", "PlaceholderText" };
- QDebugStateSaver saver(dbg);
- QDebug nospace = dbg.nospace();
- const uint mask = p.resolve();
- nospace << "QPalette(resolve=" << Qt::hex << Qt::showbase << mask << ',';
- for (int role = 0; role < (int)QPalette::NColorRoles; ++role) {
- if (mask & (1<<role)) {
- if (role)
- nospace << ',';
- nospace << colorRoleNames[role] << ":[";
- for (int group = 0; group < (int)QPalette::NColorGroups; ++group) {
- if (group)
- nospace << ',';
- const QRgb color = p.color(static_cast<QPalette::ColorGroup>(group),
- static_cast<QPalette::ColorRole>(role)).rgba();
- nospace << colorGroupNames[group] << ':' << color;
- }
- nospace << ']';
+ const auto groupEnum = QMetaEnum::fromType<QPalette::ColorGroup>();
+
+ QString groupString;
+ for (int group = 0; group < QPalette::NColorGroups; ++group) {
+ const auto cg = QPalette::ColorGroup(group);
+
+ if (p.isBrushSet(cg, cr)) {
+ const auto &color = p.color(cg, cr);
+ groupString += QString::fromUtf8(groupEnum.valueToKey(cg)) + QLatin1Char(':') +
+ color.name(QColor::HexArgb) + QLatin1Char(',');
}
}
- nospace << ')' << Qt::noshowbase << Qt::dec;
- return dbg;
+ groupString.chop(1);
+
+ return groupString;
}
+
+static QString rolesToString(const QPalette &p)
+{
+ const auto roleEnum = QMetaEnum::fromType<QPalette::ColorRole>();
+
+ QString roleString;
+ for (int role = 0; role < QPalette::NColorRoles; ++role) {
+ const auto cr = QPalette::ColorRole(role);
+
+ auto groupString = groupsToString(p, cr);
+ if (!groupString.isEmpty())
+ roleString += QString::fromUtf8(roleEnum.valueToKey(cr)) + QStringLiteral(":[") +
+ groupString + QStringLiteral("],");
+ }
+ roleString.chop(1);
+
+ return roleString;
+}
+
+QDebug operator<<(QDebug dbg, const QPalette &p)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace();
+
+ dbg << "QPalette(resolve=" << Qt::hex << Qt::showbase << p.resolve();
+
+ auto roleString = rolesToString(p);
+ if (!roleString.isEmpty())
+ dbg << ',' << roleString;
+
+ dbg << ')';
+
+ return dbg;
+ }
#endif
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qpalette.h b/src/gui/kernel/qpalette.h
index d3a840d9ad..c95640d383 100644
--- a/src/gui/kernel/qpalette.h
+++ b/src/gui/kernel/qpalette.h
@@ -72,14 +72,12 @@ public:
{ other.d = nullptr; }
inline QPalette &operator=(QPalette &&other) noexcept
{
- for_faster_swapping_dont_use = other.for_faster_swapping_dont_use;
qSwap(d, other.d); return *this;
}
void swap(QPalette &other) noexcept
{
qSwap(d, other.d);
- qSwap(for_faster_swapping_dont_use, other.for_faster_swapping_dont_use);
}
operator QVariant() const;
@@ -103,8 +101,8 @@ public:
};
Q_ENUM(ColorRole)
- inline ColorGroup currentColorGroup() const { return static_cast<ColorGroup>(data.current_group); }
- inline void setCurrentColorGroup(ColorGroup cg) { data.current_group = cg; }
+ inline ColorGroup currentColorGroup() const { return data.currentGroup; }
+ inline void setCurrentColorGroup(ColorGroup cg) { data.currentGroup = cg; }
inline const QColor &color(ColorGroup cg, ColorRole cr) const
{ return brush(cg, cr).color(); }
@@ -158,9 +156,11 @@ public:
#endif
qint64 cacheKey() const;
- QPalette resolve(const QPalette &) const;
- inline uint resolve() const { return data.resolve_mask; }
- inline void resolve(uint mask) { data.resolve_mask = mask; }
+ QPalette resolve(const QPalette &other) const;
+
+ using ResolveMask = quint64;
+ inline ResolveMask resolve() const { return data.resolveMask; }
+ inline void resolve(ResolveMask mask) { data.resolveMask = mask; }
private:
void setColorGroup(ColorGroup cr, const QBrush &windowText, const QBrush &button,
@@ -185,13 +185,11 @@ private:
QPalettePrivate *d;
struct Data {
- uint current_group : 4;
- uint resolve_mask : 28;
- };
- union {
- Data data;
- quint32 for_faster_swapping_dont_use;
+ ResolveMask resolveMask{0};
+ ColorGroup currentGroup{Active};
};
+ Data data;
+
friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &s, const QPalette &p);
};
diff --git a/src/gui/kernel/qplatformmenu.h b/src/gui/kernel/qplatformmenu.h
index 28c29a704c..8e470aefd3 100644
--- a/src/gui/kernel/qplatformmenu.h
+++ b/src/gui/kernel/qplatformmenu.h
@@ -52,7 +52,9 @@
#include <QtGui/qtguiglobal.h>
#include <QtCore/qpointer.h>
#include <QtGui/QFont>
-#include <QtGui/QKeySequence>
+#if QT_CONFIG(shortcut)
+# include <QtGui/QKeySequence>
+#endif
#include <QtGui/QIcon>
QT_BEGIN_NAMESPACE
@@ -85,7 +87,7 @@ public:
virtual void setRole(MenuRole role) = 0;
virtual void setCheckable(bool checkable) = 0;
virtual void setChecked(bool isChecked) = 0;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
virtual void setShortcut(const QKeySequence& shortcut) = 0;
#endif
virtual void setEnabled(bool enabled) = 0;
diff --git a/src/gui/kernel/qplatformtheme.cpp b/src/gui/kernel/qplatformtheme.cpp
index 71521c0339..93fd59e53f 100644
--- a/src/gui/kernel/qplatformtheme.cpp
+++ b/src/gui/kernel/qplatformtheme.cpp
@@ -167,7 +167,7 @@ QT_BEGIN_NAMESPACE
*/
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
// Table of key bindings. It must be sorted on key sequence:
// The integer value of VK_KEY | Modifier Keys (e.g., VK_META, and etc.)
// A priority of 1 indicates that this is the primary key binding when multiple are defined.
@@ -623,7 +623,7 @@ static inline int maybeSwapShortcut(int shortcut)
}
#endif
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
// mixed-mode predicate: all of these overloads are actually needed (but not all for every compiler)
struct ByStandardKey {
typedef bool result_type;
@@ -688,6 +688,7 @@ QString QPlatformTheme::standardButtonText(int button) const
return QPlatformTheme::defaultStandardButtonText(button);
}
+#if QT_CONFIG(shortcut)
/*!
Returns the mnemonic that should be used for a standard \a button.
@@ -700,6 +701,7 @@ QKeySequence QPlatformTheme::standardButtonShortcut(int button) const
Q_UNUSED(button)
return QKeySequence();
}
+#endif // QT_CONFIG(shortcut)
QString QPlatformTheme::defaultStandardButtonText(int button)
{
@@ -784,7 +786,7 @@ unsigned QPlatformThemePrivate::currentKeyPlatforms()
{
const uint keyboardScheme = QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::KeyboardScheme).toInt();
unsigned result = 1u << keyboardScheme;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
if (keyboardScheme == QPlatformTheme::KdeKeyboardScheme
|| keyboardScheme == QPlatformTheme::GnomeKeyboardScheme
|| keyboardScheme == QPlatformTheme::CdeKeyboardScheme)
diff --git a/src/gui/kernel/qplatformtheme.h b/src/gui/kernel/qplatformtheme.h
index 3185fc4541..6ed612b785 100644
--- a/src/gui/kernel/qplatformtheme.h
+++ b/src/gui/kernel/qplatformtheme.h
@@ -51,7 +51,9 @@
#include <QtGui/qtguiglobal.h>
#include <QtCore/QScopedPointer>
-#include <QtGui/QKeySequence>
+#if QT_CONFIG(shortcut)
+# include <QtGui/QKeySequence>
+#endif
QT_BEGIN_NAMESPACE
@@ -312,12 +314,14 @@ public:
QPlatformTheme::IconOptions iconOptions = { }) const;
virtual QIconEngine *createIconEngine(const QString &iconName) const;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
virtual QList<QKeySequence> keyBindings(QKeySequence::StandardKey key) const;
#endif
virtual QString standardButtonText(int button) const;
+#if QT_CONFIG(shortcut)
virtual QKeySequence standardButtonShortcut(int button) const;
+#endif
static QVariant defaultThemeHint(ThemeHint hint);
static QString defaultStandardButtonText(int button);
diff --git a/src/gui/kernel/qplatformtheme_p.h b/src/gui/kernel/qplatformtheme_p.h
index 73deb890bb..2c16fec141 100644
--- a/src/gui/kernel/qplatformtheme_p.h
+++ b/src/gui/kernel/qplatformtheme_p.h
@@ -52,7 +52,9 @@
//
#include <QtGui/private/qtguiglobal_p.h>
-#include "private/qkeysequence_p.h"
+#if QT_CONFIG(shortcut)
+# include "private/qkeysequence_p.h"
+#endif
QT_BEGIN_NAMESPACE
@@ -67,7 +69,7 @@ public:
void initializeSystemPalette();
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
static const QKeyBinding keyBindings[];
static const uint numberOfKeyBindings;
#endif
diff --git a/src/gui/kernel/qshortcutmap.cpp b/src/gui/kernel/qshortcutmap.cpp
index a7ea20266b..6039101cf4 100644
--- a/src/gui/kernel/qshortcutmap.cpp
+++ b/src/gui/kernel/qshortcutmap.cpp
@@ -49,8 +49,6 @@
#include <algorithm>
-#ifndef QT_NO_SHORTCUT
-
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcShortcutMap, "qt.gui.shortcutmap")
@@ -689,5 +687,3 @@ void QShortcutMap::dumpMap() const
#endif
QT_END_NAMESPACE
-
-#endif // QT_NO_SHORTCUT
diff --git a/src/gui/kernel/qshortcutmap_p.h b/src/gui/kernel/qshortcutmap_p.h
index 8fc68229fb..aa3dd969f0 100644
--- a/src/gui/kernel/qshortcutmap_p.h
+++ b/src/gui/kernel/qshortcutmap_p.h
@@ -56,9 +56,9 @@
#include "QtCore/qvector.h"
#include "QtCore/qscopedpointer.h"
-QT_BEGIN_NAMESPACE
+QT_REQUIRE_CONFIG(shortcut);
-#ifndef QT_NO_SHORTCUT
+QT_BEGIN_NAMESPACE
// To enable dump output uncomment below
//#define Dump_QShortcutMap
@@ -106,8 +106,6 @@ private:
QScopedPointer<QShortcutMapPrivate> d_ptr;
};
-#endif // QT_NO_SHORTCUT
-
QT_END_NAMESPACE
#endif // QSHORTCUTMAP_P_H
diff --git a/src/gui/kernel/qwindowdefs.h b/src/gui/kernel/qwindowdefs.h
index b4f3ed4712..cb0842da8c 100644
--- a/src/gui/kernel/qwindowdefs.h
+++ b/src/gui/kernel/qwindowdefs.h
@@ -43,6 +43,7 @@
#include <QtGui/qtguiglobal.h>
#include <QtCore/qobjectdefs.h>
#include <QtCore/qnamespace.h>
+#include <QtCore/qcontainerfwd.h>
QT_BEGIN_NAMESPACE
@@ -80,7 +81,6 @@ class QString;
class QByteArray;
class QApplication;
-template<typename T> class QList;
typedef QList<QWidget *> QWidgetList;
typedef QList<QWindow *> QWindowList;
diff --git a/src/gui/kernel/qwindowsysteminterface.cpp b/src/gui/kernel/qwindowsysteminterface.cpp
index 3e7d592016..2de0131640 100644
--- a/src/gui/kernel/qwindowsysteminterface.cpp
+++ b/src/gui/kernel/qwindowsysteminterface.cpp
@@ -442,7 +442,7 @@ void QWindowSystemInterface::handleFrameStrutMouseEvent(QWindow *window, ulong t
bool QWindowSystemInterface::handleShortcutEvent(QWindow *window, ulong timestamp, int keyCode, Qt::KeyboardModifiers modifiers, quint32 nativeScanCode,
quint32 nativeVirtualKey, quint32 nativeModifiers, const QString &text, bool autorepeat, ushort count)
{
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
if (!window)
window = QGuiApplication::focusWindow();
@@ -1247,7 +1247,7 @@ Q_GUI_EXPORT void qt_handleKeyEvent(QWindow *window, QEvent::Type t, int k, Qt::
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)
{
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
// FIXME: This method should not allow targeting a specific object, but should
// instead forward the event to a window, which then takes care of normal event
diff --git a/src/gui/opengl/opengl.pri b/src/gui/opengl/opengl.pri
index 24758afdeb..26060ea5df 100644
--- a/src/gui/opengl/opengl.pri
+++ b/src/gui/opengl/opengl.pri
@@ -27,7 +27,6 @@ qtConfig(opengl) {
opengl/qopenglversionfunctions.h \
opengl/qopenglversionfunctionsfactory_p.h \
opengl/qopenglvertexarrayobject.h \
- opengl/qopengldebug.h \
opengl/qopengltextureblitter.h \
opengl/qopengltexture.h \
opengl/qopengltexture_p.h \
@@ -53,7 +52,6 @@ qtConfig(opengl) {
opengl/qopenglversionfunctions.cpp \
opengl/qopenglversionfunctionsfactory.cpp \
opengl/qopenglvertexarrayobject.cpp \
- opengl/qopengldebug.cpp \
opengl/qopengltextureblitter.cpp \
opengl/qopengltexture.cpp \
opengl/qopengltexturehelper.cpp \
@@ -87,9 +85,7 @@ qtConfig(opengl) {
opengl/qopenglfunctions_4_2_compatibility.h \
opengl/qopenglfunctions_4_3_compatibility.h \
opengl/qopenglfunctions_4_4_compatibility.h \
- opengl/qopenglfunctions_4_5_compatibility.h \
- opengl/qopenglqueryhelper_p.h \
- opengl/qopengltimerquery.h
+ opengl/qopenglfunctions_4_5_compatibility.h
SOURCES += opengl/qopenglfunctions_1_0.cpp \
opengl/qopenglfunctions_1_1.cpp \
@@ -116,8 +112,7 @@ qtConfig(opengl) {
opengl/qopenglfunctions_4_2_compatibility.cpp \
opengl/qopenglfunctions_4_3_compatibility.cpp \
opengl/qopenglfunctions_4_4_compatibility.cpp \
- opengl/qopenglfunctions_4_5_compatibility.cpp \
- opengl/qopengltimerquery.cpp
+ opengl/qopenglfunctions_4_5_compatibility.cpp
}
qtConfig(opengles2) {
diff --git a/src/gui/opengl/qopengltexture.cpp b/src/gui/opengl/qopengltexture.cpp
index cf4a8dee8d..fd282e3ba0 100644
--- a/src/gui/opengl/qopengltexture.cpp
+++ b/src/gui/opengl/qopengltexture.cpp
@@ -4612,7 +4612,7 @@ QOpenGLTexture::WrapMode QOpenGLTexture::wrapMode(QOpenGLTexture::CoordinateDire
\note This function has no effect on Mac and Qt built for OpenGL ES 2.
\sa borderColor()
*/
-void QOpenGLTexture::setBorderColor(QColor color)
+void QOpenGLTexture::setBorderColor(const QColor &color)
{
setBorderColor(static_cast<float>(color.redF()), static_cast<float>(color.greenF()),
static_cast<float>(color.blueF()), static_cast<float>(color.alphaF()));
diff --git a/src/gui/opengl/qopengltexture.h b/src/gui/opengl/qopengltexture.h
index 7d984babc8..539b6aa7b2 100644
--- a/src/gui/opengl/qopengltexture.h
+++ b/src/gui/opengl/qopengltexture.h
@@ -621,7 +621,7 @@ public:
void setWrapMode(CoordinateDirection direction, WrapMode mode);
WrapMode wrapMode(CoordinateDirection direction) const;
- void setBorderColor(QColor color);
+ void setBorderColor(const QColor &color);
void setBorderColor(float r, float g, float b, float a);
void setBorderColor(int r, int g, int b, int a);
void setBorderColor(uint r, uint g, uint b, uint a);
diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp
index 8780cce223..c567b25468 100644
--- a/src/gui/painting/qcolor.cpp
+++ b/src/gui/painting/qcolor.cpp
@@ -855,18 +855,6 @@ QColor::QColor(Spec spec) noexcept
*/
/*!
- Returns the name of the color in the format "#RRGGBB"; i.e. a "#"
- character followed by three two-digit hexadecimal numbers.
-
- \sa setNamedColor()
-*/
-
-QString QColor::name() const
-{
- return name(HexRgb);
-}
-
-/*!
\since 5.2
Returns the name of the color in the specified \a format.
@@ -1086,6 +1074,7 @@ void QColor::setHsvF(qreal h, qreal s, qreal v, qreal a)
|| (v < qreal(0.0) || v > qreal(1.0))
|| (a < qreal(0.0) || a > qreal(1.0))) {
qWarning("QColor::setHsvF: HSV parameters out of range");
+ invalidate();
return;
}
@@ -1198,7 +1187,8 @@ void QColor::setHslF(qreal h, qreal s, qreal l, qreal a)
|| (s < qreal(0.0) || s > qreal(1.0))
|| (l < qreal(0.0) || l > qreal(1.0))
|| (a < qreal(0.0) || a > qreal(1.0))) {
- qWarning("QColor::setHsvF: HSV parameters out of range");
+ qWarning("QColor::setHslF: HSL parameters out of range");
+ invalidate();
return;
}
@@ -1224,7 +1214,7 @@ void QColor::setHslF(qreal h, qreal s, qreal l, qreal a)
void QColor::setHsl(int h, int s, int l, int a)
{
if (h < -1 || (uint)s > 255 || (uint)l > 255 || (uint)a > 255) {
- qWarning("QColor::setHsv: HSV parameters out of range");
+ qWarning("QColor::setHsl: HSL parameters out of range");
invalidate();
return;
}
@@ -2626,16 +2616,6 @@ QColor QColor::fromHslF(qreal h, qreal s, qreal l, qreal a)
}
/*!
- \obsolete
-
- Use the \c const overload instead.
-*/
-void QColor::getCmyk(int *c, int *m, int *y, int *k, int *a)
-{
- const_cast<const QColor *>(this)->getCmyk(c, m, y, k, a);
-}
-
-/*!
Sets the contents pointed to by \a c, \a m, \a y, \a k, and \a a, to the
cyan, magenta, yellow, black, and alpha-channel (transparency) components
of the color's CMYK value.
@@ -2665,16 +2645,6 @@ void QColor::getCmyk(int *c, int *m, int *y, int *k, int *a) const
}
/*!
- \obsolete
-
- Use the \c const overload instead.
-*/
-void QColor::getCmykF(qreal *c, qreal *m, qreal *y, qreal *k, qreal *a)
-{
- const_cast<const QColor *>(this)->getCmykF(c, m, y, k, a);
-}
-
-/*!
Sets the contents pointed to by \a c, \a m, \a y, \a k, and \a a, to the
cyan, magenta, yellow, black, and alpha-channel (transparency) components
of the color's CMYK value.
@@ -2719,6 +2689,7 @@ void QColor::setCmyk(int c, int m, int y, int k, int a)
|| k < 0 || k > 255
|| a < 0 || a > 255) {
qWarning("QColor::setCmyk: CMYK parameters out of range");
+ invalidate();
return;
}
@@ -2748,6 +2719,7 @@ void QColor::setCmykF(qreal c, qreal m, qreal y, qreal k, qreal a)
|| k < qreal(0.0) || k > qreal(1.0)
|| a < qreal(0.0) || a > qreal(1.0)) {
qWarning("QColor::setCmykF: CMYK parameters out of range");
+ invalidate();
return;
}
@@ -2920,18 +2892,6 @@ QColor QColor::dark(int factor) const noexcept
}
#endif
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-/*!
- Assigns a copy of \a color to this color, and returns a reference to it.
-*/
-QColor &QColor::operator=(const QColor &color) noexcept
-{
- cspec = color.cspec;
- 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 f0d7dd23ad..423a0ac50f 100644
--- a/src/gui/painting/qcolor.h
+++ b/src/gui/painting/qcolor.h
@@ -46,6 +46,8 @@
#include <QtCore/qstringlist.h>
#include <QtGui/qrgba64.h>
+#include <limits.h>
+
QT_BEGIN_NAMESPACE
@@ -87,24 +89,11 @@ public:
inline QColor(QLatin1String name);
QColor(Spec spec) noexcept;
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- // ### Qt 6: remove all of these, the trivial ones are fine.
- Q_DECL_CONSTEXPR QColor(const QColor &color) noexcept
- : cspec(color.cspec), ct(color.ct)
- {}
- Q_DECL_CONSTEXPR QColor(QColor &&other) noexcept : cspec(other.cspec), ct(other.ct) {}
- QColor &operator=(QColor &&other) noexcept
- { cspec = other.cspec; ct = other.ct; return *this; }
- QColor &operator=(const QColor &) noexcept;
-#endif // Qt < 6
-
QColor &operator=(Qt::GlobalColor color) noexcept;
bool isValid() const noexcept;
- // ### Qt 6: merge overloads
- QString name() const;
- QString name(NameFormat format) const;
+ QString name(NameFormat format = HexRgb) const;
#if QT_STRINGVIEW_LEVEL < 2
void setNamedColor(const QString& name);
@@ -180,11 +169,9 @@ public:
qreal yellowF() const noexcept;
qreal blackF() const noexcept;
- void getCmyk(int *c, int *m, int *y, int *k, int *a = nullptr); // ### Qt 6: remove
void getCmyk(int *c, int *m, int *y, int *k, int *a = nullptr) const;
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 = nullptr); // ### Qt 6: remove
void getCmykF(qreal *c, qreal *m, qreal *y, qreal *k, qreal *a = nullptr) const;
void setCmykF(qreal c, qreal m, qreal y, qreal k, qreal a = 1.0);
diff --git a/src/gui/painting/qdrawhelper_ssse3.cpp b/src/gui/painting/qdrawhelper_ssse3.cpp
index 14d7047bb6..a175b591dd 100644
--- a/src/gui/painting/qdrawhelper_ssse3.cpp
+++ b/src/gui/painting/qdrawhelper_ssse3.cpp
@@ -197,7 +197,7 @@ void qt_memfill24_ssse3(quint24 *dest, quint24 color, qsizetype count)
quint24 *end = dest + count;
constexpr uchar x = 2, y = 1, z = 0;
- Q_DECL_ALIGN(__m128i) static const uchar
+ alignas(__m128i) static const uchar
shuffleMask[16 + 1] = { x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y };
__m128i mval1 = _mm_shuffle_epi8(m, _mm_load_si128(reinterpret_cast<const __m128i *>(shuffleMask)));
diff --git a/src/gui/text/qfontdatabase.h b/src/gui/text/qfontdatabase.h
index 80b092f177..63e6b48e4f 100644
--- a/src/gui/text/qfontdatabase.h
+++ b/src/gui/text/qfontdatabase.h
@@ -49,7 +49,6 @@ QT_BEGIN_NAMESPACE
class QStringList;
-template <class T> class QList;
struct QFontDef;
class QFontEngine;
diff --git a/src/gui/text/qfontengine_qpf2.cpp b/src/gui/text/qfontengine_qpf2.cpp
index e00f9d058c..d636bca510 100644
--- a/src/gui/text/qfontengine_qpf2.cpp
+++ b/src/gui/text/qfontengine_qpf2.cpp
@@ -168,7 +168,7 @@ const QFontEngineQPF2::Glyph *QFontEngineQPF2::findGlyph(glyph_t g) const
bool QFontEngineQPF2::verifyHeader(const uchar *data, int size)
{
- VERIFY(quintptr(data) % Q_ALIGNOF(Header) == 0);
+ VERIFY(quintptr(data) % alignof(Header) == 0);
VERIFY(size >= int(sizeof(Header)));
const Header *header = reinterpret_cast<const Header *>(data);
if (header->magic[0] != 'Q'
diff --git a/src/gui/text/qtextoption.h b/src/gui/text/qtextoption.h
index 8b57278633..a90d73dc43 100644
--- a/src/gui/text/qtextoption.h
+++ b/src/gui/text/qtextoption.h
@@ -48,8 +48,6 @@
QT_BEGIN_NAMESPACE
-
-template <typename T> class QList;
struct QTextOptionPrivate;
class Q_GUI_EXPORT QTextOption
diff --git a/src/gui/util/qgridlayoutengine.cpp b/src/gui/util/qgridlayoutengine.cpp
index 4af5e47f8f..2b81d34848 100644
--- a/src/gui/util/qgridlayoutengine.cpp
+++ b/src/gui/util/qgridlayoutengine.cpp
@@ -960,7 +960,7 @@ void QGridLayoutEngine::insertItem(QGridLayoutItem *item, int index)
{
maybeExpandGrid(item->lastRow(), item->lastColumn());
- if (index == -1)
+ if (index < 0 || index >= q_items.size())
q_items.append(item);
else
q_items.insert(index, item);
diff --git a/src/gui/util/qtexturefiledata.cpp b/src/gui/util/qtexturefiledata.cpp
index 41cbd1b15a..3c8130c229 100644
--- a/src/gui/util/qtexturefiledata.cpp
+++ b/src/gui/util/qtexturefiledata.cpp
@@ -38,11 +38,7 @@
****************************************************************************/
#include "qtexturefiledata_p.h"
-#include <QMetaEnum>
#include <QSize>
-#if QT_CONFIG(opengl)
-#include <QOpenGLTexture>
-#endif
QT_BEGIN_NAMESPACE
@@ -247,13 +243,7 @@ void QTextureFileData::setLogName(const QByteArray &name)
static QByteArray glFormatName(quint32 fmt)
{
- const char *id = nullptr;
-#if QT_CONFIG(opengl)
- id = QMetaEnum::fromType<QOpenGLTexture::TextureFormat>().valueToKey(fmt);
-#endif
- QByteArray res(id ? id : "(?)");
- res += " [0x" + QByteArray::number(fmt, 16).rightJustified(4, '0') + ']';
- return res;
+ return QByteArray("0x" + QByteArray::number(fmt, 16).rightJustified(4, '0'));
}
QDebug operator<<(QDebug dbg, const QTextureFileData &d)
diff --git a/src/network/access/access.pri b/src/network/access/access.pri
index cfb20dcd71..083fbbf5fd 100644
--- a/src/network/access/access.pri
+++ b/src/network/access/access.pri
@@ -114,11 +114,4 @@ qtConfig(http) {
access/qhttpthreaddelegate_p.h \
access/qnetworkreplyhttpimpl_p.h \
access/qhttp2configuration.h
-
- qtConfig(ssl) {
- SOURCES += \
- access/qspdyprotocolhandler.cpp
- HEADERS += \
- access/qspdyprotocolhandler_p.h
- }
}
diff --git a/src/network/access/qabstractnetworkcache.h b/src/network/access/qabstractnetworkcache.h
index e357dfe58f..a4048c5b8f 100644
--- a/src/network/access/qabstractnetworkcache.h
+++ b/src/network/access/qabstractnetworkcache.h
@@ -52,7 +52,6 @@ QT_BEGIN_NAMESPACE
class QIODevice;
class QDateTime;
class QUrl;
-template<class T> class QList;
class QNetworkCacheMetaDataPrivate;
class Q_NETWORK_EXPORT QNetworkCacheMetaData
diff --git a/src/network/access/qhsts_p.h b/src/network/access/qhsts_p.h
index c219d9eab5..b5be4ff455 100644
--- a/src/network/access/qhsts_p.h
+++ b/src/network/access/qhsts_p.h
@@ -66,7 +66,6 @@
QT_BEGIN_NAMESPACE
-template<typename T> class QList;
template <typename T> class QVector;
class Q_AUTOTEST_EXPORT QHstsCache
diff --git a/src/network/access/qhttp2protocolhandler.cpp b/src/network/access/qhttp2protocolhandler.cpp
index dce51d4fd5..efbeb17d39 100644
--- a/src/network/access/qhttp2protocolhandler.cpp
+++ b/src/network/access/qhttp2protocolhandler.cpp
@@ -332,13 +332,13 @@ bool QHttp2ProtocolHandler::sendRequest()
// so we cannot create new streams.
m_channel->emitFinishedWithError(QNetworkReply::ProtocolUnknownError,
"GOAWAY received, cannot start a request");
- m_channel->spdyRequestsToSend.clear();
+ m_channel->h2RequestsToSend.clear();
return false;
}
// Process 'fake' (created by QNetworkAccessManager::connectToHostEncrypted())
// requests first:
- auto &requests = m_channel->spdyRequestsToSend;
+ auto &requests = m_channel->h2RequestsToSend;
for (auto it = requests.begin(), endIt = requests.end(); it != endIt;) {
const auto &pair = *it;
const QString scheme(pair.first.url().scheme());
@@ -862,7 +862,7 @@ void QHttp2ProtocolHandler::handleGOAWAY()
m_channel->emitFinishedWithError(QNetworkReply::ProtocolUnknownError,
"GOAWAY received, cannot start a request");
// Also, prevent further calls to sendRequest:
- m_channel->spdyRequestsToSend.clear();
+ m_channel->h2RequestsToSend.clear();
QNetworkReply::NetworkError error = QNetworkReply::NoError;
QString message;
@@ -1281,7 +1281,7 @@ quint32 QHttp2ProtocolHandler::createNewStream(const HttpMessagePair &message, b
const auto replyPrivate = reply->d_func();
replyPrivate->connection = m_connection;
replyPrivate->connectionChannel = m_channel;
- reply->setSpdyWasUsed(true);
+ reply->setHttp2WasUsed(true);
streamIDs.insert(reply, newStreamID);
connect(reply, SIGNAL(destroyed(QObject*)),
this, SLOT(_q_replyDestroyed(QObject*)));
@@ -1387,7 +1387,7 @@ void QHttp2ProtocolHandler::deleteActiveStream(quint32 streamID)
}
removeFromSuspended(streamID);
- if (m_channel->spdyRequestsToSend.size())
+ if (m_channel->h2RequestsToSend.size())
QMetaObject::invokeMethod(this, "sendRequest", Qt::QueuedConnection);
}
@@ -1506,7 +1506,7 @@ void QHttp2ProtocolHandler::initReplyFromPushPromise(const HttpMessagePair &mess
Q_ASSERT(promisedData.contains(cacheKey));
auto promise = promisedData.take(cacheKey);
Q_ASSERT(message.second);
- message.second->setSpdyWasUsed(true);
+ message.second->setHttp2WasUsed(true);
qCDebug(QT_HTTP2) << "found cached/promised response on stream" << promise.reservedID;
diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp
index b9a4c874c0..04f63e8735 100644
--- a/src/network/access/qhttpnetworkconnection.cpp
+++ b/src/network/access/qhttpnetworkconnection.cpp
@@ -82,9 +82,6 @@ QHttpNetworkConnectionPrivate::QHttpNetworkConnectionPrivate(const QString &host
hostName(hostName), port(port), encrypt(encrypt), delayIpv4(true)
, activeChannelCount(type == QHttpNetworkConnection::ConnectionTypeHTTP2
|| type == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
-#ifndef QT_NO_SSL
- || type == QHttpNetworkConnection::ConnectionTypeSPDY
-#endif
? 1 : defaultHttpChannelCount)
, channelCount(defaultHttpChannelCount)
#ifndef QT_NO_NETWORKPROXY
@@ -93,9 +90,9 @@ QHttpNetworkConnectionPrivate::QHttpNetworkConnectionPrivate(const QString &host
, preConnectRequests(0)
, connectionType(type)
{
- // We allocate all 6 channels even if it's SPDY or HTTP/2 enabled
- // connection: in case the protocol negotiation via NPN/ALPN fails,
- // we will have normally working HTTP/1.1.
+ // We allocate all 6 channels even if it's HTTP/2 enabled connection:
+ // in case the protocol negotiation via NPN/ALPN fails, we will have
+ // normally working HTTP/1.1.
Q_ASSERT(channelCount >= activeChannelCount);
channels = new QHttpNetworkConnectionChannel[channelCount];
}
@@ -641,10 +638,10 @@ QHttpNetworkReply* QHttpNetworkConnectionPrivate::queueRequest(const QHttpNetwor
break;
}
}
- else { // SPDY, HTTP/2 ('h2' mode)
+ else { // HTTP/2 ('h2' mode)
if (!pair.second->d_func()->requestIsPrepared)
prepareRequest(pair);
- channels[0].spdyRequestsToSend.insert(request.priority(), pair);
+ channels[0].h2RequestsToSend.insert(request.priority(), pair);
}
#ifndef Q_OS_WINRT
@@ -680,7 +677,7 @@ void QHttpNetworkConnectionPrivate::fillHttp2Queue()
for (auto &pair : highPriorityQueue) {
if (!pair.second->d_func()->requestIsPrepared)
prepareRequest(pair);
- channels[0].spdyRequestsToSend.insert(QHttpNetworkRequest::HighPriority, pair);
+ channels[0].h2RequestsToSend.insert(QHttpNetworkRequest::HighPriority, pair);
}
highPriorityQueue.clear();
@@ -688,7 +685,7 @@ void QHttpNetworkConnectionPrivate::fillHttp2Queue()
for (auto &pair : lowPriorityQueue) {
if (!pair.second->d_func()->requestIsPrepared)
prepareRequest(pair);
- channels[0].spdyRequestsToSend.insert(pair.first.priority(), pair);
+ channels[0].h2RequestsToSend.insert(pair.first.priority(), pair);
}
lowPriorityQueue.clear();
@@ -984,12 +981,12 @@ void QHttpNetworkConnectionPrivate::removeReply(QHttpNetworkReply *reply)
}
}
#ifndef QT_NO_SSL
- // is the reply inside the SPDY pipeline of this channel already?
- QMultiMap<int, HttpMessagePair>::iterator it = channels[i].spdyRequestsToSend.begin();
- QMultiMap<int, HttpMessagePair>::iterator end = channels[i].spdyRequestsToSend.end();
+ // is the reply inside the H2 pipeline of this channel already?
+ QMultiMap<int, HttpMessagePair>::iterator it = channels[i].h2RequestsToSend.begin();
+ QMultiMap<int, HttpMessagePair>::iterator end = channels[i].h2RequestsToSend.end();
for (; it != end; ++it) {
if (it.value().second == reply) {
- channels[i].spdyRequestsToSend.remove(it.key());
+ channels[i].h2RequestsToSend.remove(it.key());
QMetaObject::invokeMethod(q, "_q_startNextRequest", Qt::QueuedConnection);
return;
@@ -1068,9 +1065,8 @@ void QHttpNetworkConnectionPrivate::_q_startNextRequest()
break;
}
case QHttpNetworkConnection::ConnectionTypeHTTP2Direct:
- case QHttpNetworkConnection::ConnectionTypeHTTP2:
- case QHttpNetworkConnection::ConnectionTypeSPDY: {
- if (channels[0].spdyRequestsToSend.isEmpty() && channels[0].switchedToHttp2)
+ case QHttpNetworkConnection::ConnectionTypeHTTP2: {
+ if (channels[0].h2RequestsToSend.isEmpty() && channels[0].switchedToHttp2)
return;
if (networkLayerState == IPv4)
@@ -1079,7 +1075,7 @@ void QHttpNetworkConnectionPrivate::_q_startNextRequest()
channels[0].networkLayerPreference = QAbstractSocket::IPv6Protocol;
channels[0].ensureConnection();
if (channels[0].socket && channels[0].socket->state() == QAbstractSocket::ConnectedState
- && !channels[0].pendingEncrypt && channels[0].spdyRequestsToSend.size())
+ && !channels[0].pendingEncrypt && channels[0].h2RequestsToSend.size())
channels[0].sendRequest();
break;
}
@@ -1234,19 +1230,18 @@ void QHttpNetworkConnectionPrivate::_q_hostLookupFinished(const QHostInfo &info)
if (dequeueRequest(channels[0].socket)) {
emitReplyError(channels[0].socket, channels[0].reply, QNetworkReply::HostNotFoundError);
networkLayerState = QHttpNetworkConnectionPrivate::Unknown;
- } else if (connectionType == QHttpNetworkConnection::ConnectionTypeSPDY
- || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2
+ } else if (connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2
|| connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
- for (const HttpMessagePair &spdyPair : qAsConst(channels[0].spdyRequestsToSend)) {
+ for (const HttpMessagePair &h2Pair : qAsConst(channels[0].h2RequestsToSend)) {
// emit error for all replies
- QHttpNetworkReply *currentReply = spdyPair.second;
+ QHttpNetworkReply *currentReply = h2Pair.second;
Q_ASSERT(currentReply);
emitReplyError(channels[0].socket, currentReply, QNetworkReply::HostNotFoundError);
}
} else {
// Should not happen: we start a host lookup before sending a request,
- // so it's natural to have requests either in SPDY/HTTP/2 queue,
- // or in low/high priority queues.
+ // so it's natural to have requests either in HTTP/2 queue, or in low/high
+ // priority queues.
qWarning("QHttpNetworkConnectionPrivate::_q_hostLookupFinished"
" could not de-queue request, failed to report HostNotFoundError");
networkLayerState = QHttpNetworkConnectionPrivate::Unknown;
@@ -1576,17 +1571,12 @@ void QHttpNetworkConnectionPrivate::emitProxyAuthenticationRequired(const QHttpN
pauseConnection();
QHttpNetworkReply *reply;
if (connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2
- || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
-#if QT_CONFIG(ssl)
- || connectionType == QHttpNetworkConnection::ConnectionTypeSPDY
-#endif
- ) {
-
+ || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
// we choose the reply to emit the proxyAuth signal from somewhat arbitrarily,
// but that does not matter because the signal will ultimately be emitted
// by the QNetworkAccessManager.
- Q_ASSERT(chan->spdyRequestsToSend.count() > 0);
- reply = chan->spdyRequestsToSend.cbegin().value().second;
+ Q_ASSERT(chan->h2RequestsToSend.count() > 0);
+ reply = chan->h2RequestsToSend.cbegin().value().second;
} else { // HTTP
reply = chan->reply;
}
diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h
index 6808a0c0ac..fee84bb6c0 100644
--- a/src/network/access/qhttpnetworkconnection_p.h
+++ b/src/network/access/qhttpnetworkconnection_p.h
@@ -96,7 +96,6 @@ public:
enum ConnectionType {
ConnectionTypeHTTP,
- ConnectionTypeSPDY,
ConnectionTypeHTTP2,
ConnectionTypeHTTP2Direct
};
@@ -172,7 +171,6 @@ private:
friend class QHttpNetworkConnectionChannel;
friend class QHttp2ProtocolHandler;
friend class QHttpProtocolHandler;
- friend class QSpdyProtocolHandler;
Q_PRIVATE_SLOT(d_func(), void _q_startNextRequest())
Q_PRIVATE_SLOT(d_func(), void _q_hostLookupFinished(QHostInfo))
diff --git a/src/network/access/qhttpnetworkconnectionchannel.cpp b/src/network/access/qhttpnetworkconnectionchannel.cpp
index 47081b29d2..98809e460b 100644
--- a/src/network/access/qhttpnetworkconnectionchannel.cpp
+++ b/src/network/access/qhttpnetworkconnectionchannel.cpp
@@ -48,7 +48,6 @@
#include <private/qhttp2protocolhandler_p.h>
#include <private/qhttpprotocolhandler_p.h>
-#include <private/qspdyprotocolhandler_p.h>
#include <private/http2protocol_p.h>
#ifndef QT_NO_SSL
@@ -931,7 +930,7 @@ void QHttpNetworkConnectionChannel::_q_connected()
} else if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
state = QHttpNetworkConnectionChannel::IdleState;
protocolHandler.reset(new QHttp2ProtocolHandler(this));
- if (spdyRequestsToSend.count() > 0) {
+ if (h2RequestsToSend.count() > 0) {
// In case our peer has sent us its settings (window size, max concurrent streams etc.)
// let's give _q_receiveReply a chance to read them first ('invokeMethod', QueuedConnection).
QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
@@ -1108,15 +1107,11 @@ void QHttpNetworkConnectionChannel::_q_error(QAbstractSocket::SocketError socket
|| !connection->d_func()->lowPriorityQueue.isEmpty());
if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
- || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
-#ifndef QT_NO_SSL
- || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeSPDY
-#endif
- ) {
- QList<HttpMessagePair> spdyPairs = spdyRequestsToSend.values();
- for (int a = 0; a < spdyPairs.count(); ++a) {
+ || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
+ QList<HttpMessagePair> h2Pairs = h2RequestsToSend.values();
+ for (int a = 0; a < h2Pairs.count(); ++a) {
// emit error for all replies
- QHttpNetworkReply *currentReply = spdyPairs.at(a).second;
+ QHttpNetworkReply *currentReply = h2Pairs.at(a).second;
Q_ASSERT(currentReply);
emit currentReply->finishedWithError(errorCode, errorString);
}
@@ -1143,12 +1138,8 @@ void QHttpNetworkConnectionChannel::_q_error(QAbstractSocket::SocketError socket
void QHttpNetworkConnectionChannel::_q_proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator* auth)
{
if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
- || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
-#ifndef QT_NO_SSL
- || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeSPDY
-#endif
- ) {
- if (spdyRequestsToSend.count() > 0)
+ || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
+ if (h2RequestsToSend.count() > 0)
connection->d_func()->emitProxyAuthenticationRequired(this, proxy, auth);
} else { // HTTP
// Need to dequeue the request before we can emit the error.
@@ -1171,9 +1162,9 @@ void QHttpNetworkConnectionChannel::emitFinishedWithError(QNetworkReply::Network
{
if (reply)
emit reply->finishedWithError(error, QHttpNetworkConnectionChannel::tr(message));
- QList<HttpMessagePair> spdyPairs = spdyRequestsToSend.values();
- for (int a = 0; a < spdyPairs.count(); ++a) {
- QHttpNetworkReply *currentReply = spdyPairs.at(a).second;
+ QList<HttpMessagePair> h2Pairs = h2RequestsToSend.values();
+ for (int a = 0; a < h2Pairs.count(); ++a) {
+ QHttpNetworkReply *currentReply = h2Pairs.at(a).second;
Q_ASSERT(currentReply);
emit currentReply->finishedWithError(error, QHttpNetworkConnectionChannel::tr(message));
}
@@ -1195,12 +1186,6 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
QByteArray nextProtocol = sslSocket->sslConfiguration().nextNegotiatedProtocol();
if (nextProtocol == QSslConfiguration::NextProtocolHttp1_1) {
// fall through to create a QHttpProtocolHandler
- } else if (nextProtocol == QSslConfiguration::NextProtocolSpdy3_0) {
- protocolHandler.reset(new QSpdyProtocolHandler(this));
- connection->setConnectionType(QHttpNetworkConnection::ConnectionTypeSPDY);
- // no need to re-queue requests, if SPDY was enabled on the request it
- // has gone to the SPDY queue already
- break;
} else if (nextProtocol == QSslConfiguration::ALPNProtocolHTTP2) {
switchedToHttp2 = true;
protocolHandler.reset(new QHttp2ProtocolHandler(this));
@@ -1229,8 +1214,6 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
// it again on other channels that our connection can create/open.
if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2)
protocols.removeAll(QSslConfiguration::ALPNProtocolHTTP2);
- else if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeSPDY)
- protocols.removeAll(QSslConfiguration::NextProtocolSpdy3_0);
if (nProtocols > protocols.size()) {
sslConfiguration->setAllowedNextProtocols(protocols);
@@ -1240,13 +1223,13 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
}
connection->setConnectionType(QHttpNetworkConnection::ConnectionTypeHTTP);
- // We use only one channel for SPDY or HTTP/2, but normally six for
+ // We use only one channel for HTTP/2, but normally six for
// HTTP/1.1 - let's restore this number to the reserved number of
// channels:
if (connection->d_func()->activeChannelCount < connection->d_func()->channelCount) {
connection->d_func()->activeChannelCount = connection->d_func()->channelCount;
- // re-queue requests from SPDY queue to HTTP queue, if any
- requeueSpdyRequests();
+ // re-queue requests from HTTP/2 queue to HTTP queue, if any
+ requeueHttp2Requests();
}
break;
}
@@ -1266,11 +1249,9 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
state = QHttpNetworkConnectionChannel::IdleState;
pendingEncrypt = false;
- if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeSPDY ||
- connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2 ||
+ if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2 ||
connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
- // we call setSpdyWasUsed(true) on the replies in the SPDY handler when the request is sent
- if (spdyRequestsToSend.count() > 0) {
+ if (h2RequestsToSend.count() > 0) {
// In case our peer has sent us its settings (window size, max concurrent streams etc.)
// let's give _q_receiveReply a chance to read them first ('invokeMethod', QueuedConnection).
QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
@@ -1279,7 +1260,7 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
if (!reply)
connection->d_func()->dequeueRequest(socket);
if (reply) {
- reply->setSpdyWasUsed(false);
+ reply->setHttp2WasUsed(false);
Q_ASSERT(reply->d_func()->connectionChannel == this);
emit reply->encrypted();
}
@@ -1288,13 +1269,12 @@ void QHttpNetworkConnectionChannel::_q_encrypted()
}
}
-void QHttpNetworkConnectionChannel::requeueSpdyRequests()
+void QHttpNetworkConnectionChannel::requeueHttp2Requests()
{
- QList<HttpMessagePair> spdyPairs = spdyRequestsToSend.values();
- for (int a = 0; a < spdyPairs.count(); ++a) {
- connection->d_func()->requeueRequest(spdyPairs.at(a));
- }
- spdyRequestsToSend.clear();
+ QList<HttpMessagePair> h2Pairs = h2RequestsToSend.values();
+ for (int a = 0; a < h2Pairs.count(); ++a)
+ connection->d_func()->requeueRequest(h2Pairs.at(a));
+ h2RequestsToSend.clear();
}
void QHttpNetworkConnectionChannel::_q_sslErrors(const QList<QSslError> &errors)
@@ -1312,11 +1292,11 @@ void QHttpNetworkConnectionChannel::_q_sslErrors(const QList<QSslError> &errors)
emit reply->sslErrors(errors);
}
#ifndef QT_NO_SSL
- else { // SPDY
- QList<HttpMessagePair> spdyPairs = spdyRequestsToSend.values();
- for (int a = 0; a < spdyPairs.count(); ++a) {
+ else { // HTTP/2
+ QList<HttpMessagePair> h2Pairs = h2RequestsToSend.values();
+ for (int a = 0; a < h2Pairs.count(); ++a) {
// emit SSL errors for all replies
- QHttpNetworkReply *currentReply = spdyPairs.at(a).second;
+ QHttpNetworkReply *currentReply = h2Pairs.at(a).second;
Q_ASSERT(currentReply);
emit currentReply->sslErrors(errors);
}
@@ -1336,10 +1316,10 @@ void QHttpNetworkConnectionChannel::_q_preSharedKeyAuthenticationRequired(QSslPr
if (reply)
emit reply->preSharedKeyAuthenticationRequired(authenticator);
} else {
- QList<HttpMessagePair> spdyPairs = spdyRequestsToSend.values();
- for (int a = 0; a < spdyPairs.count(); ++a) {
+ QList<HttpMessagePair> h2Pairs = h2RequestsToSend.values();
+ for (int a = 0; a < h2Pairs.count(); ++a) {
// emit SSL errors for all replies
- QHttpNetworkReply *currentReply = spdyPairs.at(a).second;
+ QHttpNetworkReply *currentReply = h2Pairs.at(a).second;
Q_ASSERT(currentReply);
emit currentReply->preSharedKeyAuthenticationRequired(authenticator);
}
diff --git a/src/network/access/qhttpnetworkconnectionchannel_p.h b/src/network/access/qhttpnetworkconnectionchannel_p.h
index 270b3eb9ba..44ad2d7959 100644
--- a/src/network/access/qhttpnetworkconnectionchannel_p.h
+++ b/src/network/access/qhttpnetworkconnectionchannel_p.h
@@ -123,10 +123,7 @@ public:
bool authenticationCredentialsSent;
bool proxyCredentialsSent;
QScopedPointer<QAbstractProtocolHandler> protocolHandler;
- // SPDY or HTTP/2 requests; SPDY is TLS-only, but
- // HTTP/2 can be cleartext also, that's why it's
- // outside of QT_NO_SSL section. Sorted by priority:
- QMultiMap<int, HttpMessagePair> spdyRequestsToSend;
+ QMultiMap<int, HttpMessagePair> h2RequestsToSend;
bool switchedToHttp2 = false;
#ifndef QT_NO_SSL
bool ignoreAllSslErrors;
@@ -135,7 +132,7 @@ public:
void ignoreSslErrors();
void ignoreSslErrors(const QList<QSslError> &errors);
void setSslConfiguration(const QSslConfiguration &config);
- void requeueSpdyRequests(); // when we wanted SPDY but got HTTP
+ void requeueHttp2Requests(); // when we wanted HTTP/2 but got HTTP/1.1
#endif
// to emit the signal for all in-flight replies:
void emitFinishedWithError(QNetworkReply::NetworkError error, const char *message);
diff --git a/src/network/access/qhttpnetworkreply.cpp b/src/network/access/qhttpnetworkreply.cpp
index af456c3607..1ba52ac6d6 100644
--- a/src/network/access/qhttpnetworkreply.cpp
+++ b/src/network/access/qhttpnetworkreply.cpp
@@ -287,14 +287,14 @@ bool QHttpNetworkReply::isPipeliningUsed() const
return d_func()->pipeliningUsed;
}
-bool QHttpNetworkReply::isSpdyUsed() const
+bool QHttpNetworkReply::isHttp2Used() const
{
- return d_func()->spdyUsed;
+ return d_func()->h2Used;
}
-void QHttpNetworkReply::setSpdyWasUsed(bool spdy)
+void QHttpNetworkReply::setHttp2WasUsed(bool h2)
{
- d_func()->spdyUsed = spdy;
+ d_func()->h2Used = h2;
}
qint64 QHttpNetworkReply::removedContentLength() const
@@ -324,15 +324,11 @@ QHttpNetworkReplyPrivate::QHttpNetworkReplyPrivate(const QUrl &newUrl)
forceConnectionCloseEnabled(false),
lastChunkRead(false),
currentChunkSize(0), currentChunkRead(0), readBufferMaxSize(0),
- windowSizeDownload(65536), // 64K initial window size according to SPDY standard
- windowSizeUpload(65536), // 64K initial window size according to SPDY standard
- currentlyReceivedDataInWindow(0),
- currentlyUploadedDataInWindow(0),
totallyUploadedData(0),
removedContentLength(-1),
connection(nullptr),
autoDecompress(false), responseData(), requestIsPrepared(false)
- ,pipeliningUsed(false), spdyUsed(false), downstreamLimited(false)
+ ,pipeliningUsed(false), h2Used(false), downstreamLimited(false)
,userProvidedDownloadBuffer(nullptr)
#ifndef QT_NO_COMPRESS
,inflateStrm(nullptr)
diff --git a/src/network/access/qhttpnetworkreply_p.h b/src/network/access/qhttpnetworkreply_p.h
index 12cfe359aa..82128f656e 100644
--- a/src/network/access/qhttpnetworkreply_p.h
+++ b/src/network/access/qhttpnetworkreply_p.h
@@ -137,8 +137,8 @@ public:
bool isFinished() const;
bool isPipeliningUsed() const;
- bool isSpdyUsed() const;
- void setSpdyWasUsed(bool spdy);
+ bool isHttp2Used() const;
+ void setHttp2WasUsed(bool h2Used);
qint64 removedContentLength() const;
bool isRedirecting() const;
@@ -251,11 +251,7 @@ public:
qint64 currentChunkSize;
qint64 currentChunkRead;
qint64 readBufferMaxSize;
- qint32 windowSizeDownload; // only for SPDY
- qint32 windowSizeUpload; // only for SPDY
- qint32 currentlyReceivedDataInWindow; // only for SPDY
- qint32 currentlyUploadedDataInWindow; // only for SPDY
- qint64 totallyUploadedData; // only for SPDY
+ qint64 totallyUploadedData; // HTTP/2
qint64 removedContentLength;
QPointer<QHttpNetworkConnection> connection;
QPointer<QHttpNetworkConnectionChannel> connectionChannel;
@@ -267,7 +263,7 @@ public:
bool requestIsPrepared;
bool pipeliningUsed;
- bool spdyUsed;
+ bool h2Used;
bool downstreamLimited;
char* userProvidedDownloadBuffer;
diff --git a/src/network/access/qhttpnetworkrequest.cpp b/src/network/access/qhttpnetworkrequest.cpp
index 5fb8885bdf..0b03e6e69e 100644
--- a/src/network/access/qhttpnetworkrequest.cpp
+++ b/src/network/access/qhttpnetworkrequest.cpp
@@ -45,7 +45,7 @@ QT_BEGIN_NAMESPACE
QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(QHttpNetworkRequest::Operation op,
QHttpNetworkRequest::Priority pri, const QUrl &newUrl)
: QHttpNetworkHeaderPrivate(newUrl), operation(op), priority(pri), uploadByteDevice(nullptr),
- autoDecompress(false), pipeliningAllowed(false), spdyAllowed(false), http2Allowed(false),
+ autoDecompress(false), pipeliningAllowed(false), http2Allowed(false),
http2Direct(false), withCredentials(true), preConnect(false), redirectCount(0),
redirectPolicy(QNetworkRequest::ManualRedirectPolicy)
{
@@ -59,7 +59,6 @@ QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(const QHttpNetworkRequest
uploadByteDevice(other.uploadByteDevice),
autoDecompress(other.autoDecompress),
pipeliningAllowed(other.pipeliningAllowed),
- spdyAllowed(other.spdyAllowed),
http2Allowed(other.http2Allowed),
http2Direct(other.http2Direct),
withCredentials(other.withCredentials),
@@ -83,7 +82,6 @@ bool QHttpNetworkRequestPrivate::operator==(const QHttpNetworkRequestPrivate &ot
&& (uploadByteDevice == other.uploadByteDevice)
&& (autoDecompress == other.autoDecompress)
&& (pipeliningAllowed == other.pipeliningAllowed)
- && (spdyAllowed == other.spdyAllowed)
&& (http2Allowed == other.http2Allowed)
&& (http2Direct == other.http2Direct)
// we do not clear the customVerb in setOperation
@@ -339,16 +337,6 @@ void QHttpNetworkRequest::setPipeliningAllowed(bool b)
d->pipeliningAllowed = b;
}
-bool QHttpNetworkRequest::isSPDYAllowed() const
-{
- return d->spdyAllowed;
-}
-
-void QHttpNetworkRequest::setSPDYAllowed(bool b)
-{
- d->spdyAllowed = b;
-}
-
bool QHttpNetworkRequest::isHTTP2Allowed() const
{
return d->http2Allowed;
diff --git a/src/network/access/qhttpnetworkrequest_p.h b/src/network/access/qhttpnetworkrequest_p.h
index fb4896195b..f263e348ef 100644
--- a/src/network/access/qhttpnetworkrequest_p.h
+++ b/src/network/access/qhttpnetworkrequest_p.h
@@ -116,9 +116,6 @@ public:
bool isPipeliningAllowed() const;
void setPipeliningAllowed(bool b);
- bool isSPDYAllowed() const;
- void setSPDYAllowed(bool b);
-
bool isHTTP2Allowed() const;
void setHTTP2Allowed(bool b);
@@ -176,7 +173,6 @@ public:
mutable QNonContiguousByteDevice* uploadByteDevice;
bool autoDecompress;
bool pipeliningAllowed;
- bool spdyAllowed;
bool http2Allowed;
bool http2Direct;
bool withCredentials;
diff --git a/src/network/access/qhttpthreaddelegate.cpp b/src/network/access/qhttpthreaddelegate.cpp
index f3125a3a95..6322c773ac 100644
--- a/src/network/access/qhttpthreaddelegate.cpp
+++ b/src/network/access/qhttpthreaddelegate.cpp
@@ -236,7 +236,7 @@ QHttpThreadDelegate::QHttpThreadDelegate(QObject *parent) :
, synchronous(false)
, incomingStatusCode(0)
, isPipeliningUsed(false)
- , isSpdyUsed(false)
+ , isHttp2Used(false)
, incomingContentLength(-1)
, removedContentLength(-1)
, incomingErrorCode(QNetworkReply::NoError)
@@ -320,17 +320,6 @@ void QHttpThreadDelegate::startRequest()
}
}
-#ifndef QT_NO_SSL
- if (!isH2 && httpRequest.isSPDYAllowed() && ssl) {
- connectionType = QHttpNetworkConnection::ConnectionTypeSPDY;
- urlCopy.setScheme(QStringLiteral("spdy")); // to differentiate SPDY requests from HTTPS requests
- QList<QByteArray> nextProtocols;
- nextProtocols << QSslConfiguration::NextProtocolSpdy3_0
- << QSslConfiguration::NextProtocolHttp1_1;
- incomingSslConfiguration->setAllowedNextProtocols(nextProtocols);
- }
-#endif // QT_NO_SSL
-
#ifndef QT_NO_NETWORKPROXY
if (transparentProxy.type() != QNetworkProxy::NoProxy)
cacheKey = makeCacheKey(urlCopy, &transparentProxy, httpRequest.peerVerifyName());
@@ -652,7 +641,7 @@ void QHttpThreadDelegate::headerChangedSlot()
isPipeliningUsed = httpReply->isPipeliningUsed();
incomingContentLength = httpReply->contentLength();
removedContentLength = httpReply->removedContentLength();
- isSpdyUsed = httpReply->isSpdyUsed();
+ isHttp2Used = httpReply->isHttp2Used();
emit downloadMetaData(incomingHeaders,
incomingStatusCode,
@@ -661,7 +650,7 @@ void QHttpThreadDelegate::headerChangedSlot()
downloadBuffer,
incomingContentLength,
removedContentLength,
- isSpdyUsed);
+ isHttp2Used);
}
void QHttpThreadDelegate::synchronousHeaderChangedSlot()
@@ -677,7 +666,7 @@ void QHttpThreadDelegate::synchronousHeaderChangedSlot()
incomingStatusCode = httpReply->statusCode();
incomingReasonPhrase = httpReply->reasonPhrase();
isPipeliningUsed = httpReply->isPipeliningUsed();
- isSpdyUsed = httpReply->isSpdyUsed();
+ isHttp2Used = httpReply->isHttp2Used();
incomingContentLength = httpReply->contentLength();
}
diff --git a/src/network/access/qhttpthreaddelegate_p.h b/src/network/access/qhttpthreaddelegate_p.h
index 355d1afc30..208b2cb149 100644
--- a/src/network/access/qhttpthreaddelegate_p.h
+++ b/src/network/access/qhttpthreaddelegate_p.h
@@ -112,7 +112,7 @@ public:
int incomingStatusCode;
QString incomingReasonPhrase;
bool isPipeliningUsed;
- bool isSpdyUsed;
+ bool isHttp2Used;
qint64 incomingContentLength;
qint64 removedContentLength;
QNetworkReply::NetworkError incomingErrorCode;
diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp
index ff916ff283..68bd107a83 100644
--- a/src/network/access/qnetworkaccessmanager.cpp
+++ b/src/network/access/qnetworkaccessmanager.cpp
@@ -1237,12 +1237,10 @@ void QNetworkAccessManager::connectToHostEncrypted(const QString &hostName, quin
if (sslConfiguration != QSslConfiguration::defaultConfiguration())
request.setSslConfiguration(sslConfiguration);
- // There is no way to enable SPDY/HTTP2 via a request, so we need to check
- // the ssl configuration whether SPDY/HTTP2 is allowed here.
+ // There is no way to enable HTTP2 via a request, so we need to check
+ // the ssl configuration whether HTTP2 is allowed here.
if (sslConfiguration.allowedNextProtocols().contains(QSslConfiguration::ALPNProtocolHTTP2))
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, true);
- else if (sslConfiguration.allowedNextProtocols().contains(QSslConfiguration::NextProtocolSpdy3_0))
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
request.setPeerVerifyName(peerName);
get(request);
diff --git a/src/network/access/qnetworkaccessmanager.h b/src/network/access/qnetworkaccessmanager.h
index aa4765a043..a883bf93fb 100644
--- a/src/network/access/qnetworkaccessmanager.h
+++ b/src/network/access/qnetworkaccessmanager.h
@@ -56,7 +56,6 @@ class QIODevice;
class QAbstractNetworkCache;
class QAuthenticator;
class QByteArray;
-template<typename T> class QList;
class QNetworkCookie;
class QNetworkCookieJar;
class QNetworkReply;
diff --git a/src/network/access/qnetworkreplyhttpimpl.cpp b/src/network/access/qnetworkreplyhttpimpl.cpp
index 5a775142b0..002d9ec5d1 100644
--- a/src/network/access/qnetworkreplyhttpimpl.cpp
+++ b/src/network/access/qnetworkreplyhttpimpl.cpp
@@ -775,9 +775,6 @@ void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpReq
if (newHttpRequest.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool())
httpRequest.setPipeliningAllowed(true);
- if (request.attribute(QNetworkRequest::SpdyAllowedAttribute).toBool())
- httpRequest.setSPDYAllowed(true);
-
if (request.attribute(QNetworkRequest::Http2AllowedAttribute).toBool())
httpRequest.setHTTP2Allowed(true);
@@ -969,7 +966,7 @@ void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpReq
QSharedPointer<char>(),
delegate->incomingContentLength,
delegate->removedContentLength,
- delegate->isSpdyUsed);
+ delegate->isHttp2Used);
replyDownloadData(delegate->synchronousDownloadData);
httpError(delegate->incomingErrorCode, delegate->incomingErrorDetail);
} else {
@@ -981,7 +978,7 @@ void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpReq
QSharedPointer<char>(),
delegate->incomingContentLength,
delegate->removedContentLength,
- delegate->isSpdyUsed);
+ delegate->isHttp2Used);
replyDownloadData(delegate->synchronousDownloadData);
}
@@ -1256,7 +1253,7 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData(const QList<QPair<QByte
QSharedPointer<char> db,
qint64 contentLength,
qint64 removedContentLength,
- bool spdyWasUsed)
+ bool h2Used)
{
Q_Q(QNetworkReplyHttpImpl);
Q_UNUSED(contentLength);
@@ -1282,16 +1279,7 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData(const QList<QPair<QByte
}
q->setAttribute(QNetworkRequest::HttpPipeliningWasUsedAttribute, pu);
- const QVariant http2Allowed = request.attribute(QNetworkRequest::Http2AllowedAttribute);
- const QVariant http2Direct = request.attribute(QNetworkRequest::Http2DirectAttribute);
- if ((http2Allowed.isValid() && http2Allowed.toBool())
- || (http2Direct.isValid() && http2Direct.toBool())) {
- q->setAttribute(QNetworkRequest::Http2WasUsedAttribute, spdyWasUsed);
- q->setAttribute(QNetworkRequest::SpdyWasUsedAttribute, false);
- } else {
- q->setAttribute(QNetworkRequest::SpdyWasUsedAttribute, spdyWasUsed);
- q->setAttribute(QNetworkRequest::Http2WasUsedAttribute, false);
- }
+ q->setAttribute(QNetworkRequest::Http2WasUsedAttribute, h2Used);
// reconstruct the HTTP header
QList<QPair<QByteArray, QByteArray> > headerMap = hm;
diff --git a/src/network/access/qnetworkrequest.cpp b/src/network/access/qnetworkrequest.cpp
index 70b09dba22..473aa42e1e 100644
--- a/src/network/access/qnetworkrequest.cpp
+++ b/src/network/access/qnetworkrequest.cpp
@@ -272,18 +272,6 @@ QT_BEGIN_NAMESPACE
The QNetworkSession ConnectInBackground property will be set according to
this attribute.
- \value SpdyAllowedAttribute
- Requests only, type: QMetaType::Bool (default: false)
- Indicates whether the QNetworkAccessManager code is
- allowed to use SPDY with this request. This applies only
- to SSL requests, and depends on the server supporting SPDY.
- Obsolete, use Http2 instead of Spdy.
-
- \value SpdyWasUsedAttribute
- Replies only, type: QMetaType::Bool
- Indicates whether SPDY was used for receiving
- this reply. Obsolete, use Http2 instead of Spdy.
-
\value Http2AllowedAttribute
Requests only, type: QMetaType::Bool (default: false)
Indicates whether the QNetworkAccessManager code is
@@ -295,12 +283,6 @@ QT_BEGIN_NAMESPACE
Indicates whether HTTP/2 was used for receiving this reply.
(This value was introduced in 5.9.)
- \value HTTP2AllowedAttribute
- Obsolete alias for Http2AllowedAttribute.
-
- \value HTTP2WasUsedAttribute
- Obsolete alias for Http2WasUsedAttribute.
-
\value EmitAllUploadProgressSignalsAttribute
Requests only, type: QMetaType::Bool (default: false)
Indicates whether all upload signals should be emitted.
diff --git a/src/network/access/qnetworkrequest.h b/src/network/access/qnetworkrequest.h
index dcd2c6b61f..cb15ca5aa5 100644
--- a/src/network/access/qnetworkrequest.h
+++ b/src/network/access/qnetworkrequest.h
@@ -89,18 +89,10 @@ public:
DownloadBufferAttribute, // internal
SynchronousRequestAttribute, // internal
BackgroundRequestAttribute,
-#if QT_DEPRECATED_SINCE(5, 15)
- SpdyAllowedAttribute,
- SpdyWasUsedAttribute,
-#endif // QT_DEPRECATED_SINCE(5, 15)
EmitAllUploadProgressSignalsAttribute = BackgroundRequestAttribute + 3,
FollowRedirectsAttribute,
Http2AllowedAttribute,
Http2WasUsedAttribute,
-#if QT_DEPRECATED_SINCE(5, 15)
- HTTP2AllowedAttribute Q_DECL_ENUMERATOR_DEPRECATED_X("Use Http2AllowedAttribute") = Http2AllowedAttribute,
- HTTP2WasUsedAttribute Q_DECL_ENUMERATOR_DEPRECATED_X("Use Http2WasUsedAttribute"),
-#endif // QT_DEPRECATED_SINCE(5, 15)
OriginalContentLengthAttribute,
RedirectPolicyAttribute,
Http2DirectAttribute,
diff --git a/src/network/access/qspdyprotocolhandler_p.h b/src/network/access/qspdyprotocolhandler_p.h
deleted file mode 100644
index 14e2ff388a..0000000000
--- a/src/network/access/qspdyprotocolhandler_p.h
+++ /dev/null
@@ -1,232 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSPDYPROTOCOLHANDLER_H
-#define QSPDYPROTOCOLHANDLER_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the Network Access API. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtNetwork/private/qtnetworkglobal_p.h>
-#include <private/qabstractprotocolhandler_p.h>
-#include <QtNetwork/qnetworkreply.h>
-#include <private/qbytedata_p.h>
-
-#include <zlib.h>
-
-QT_REQUIRE_CONFIG(http);
-
-#if !defined(QT_NO_SSL)
-
-QT_BEGIN_NAMESPACE
-
-class QHttpNetworkRequest;
-
-#ifndef HttpMessagePair
-typedef QPair<QHttpNetworkRequest, QHttpNetworkReply*> HttpMessagePair;
-#endif
-
-class QSpdyProtocolHandler : public QObject, public QAbstractProtocolHandler {
- Q_OBJECT
-public:
- QSpdyProtocolHandler(QHttpNetworkConnectionChannel *channel);
- ~QSpdyProtocolHandler();
-
- enum DataFrameFlag {
- DataFrame_FLAG_FIN = 0x01,
- DataFrame_FLAG_COMPRESS = 0x02
- };
-
- Q_DECLARE_FLAGS(DataFrameFlags, DataFrameFlag)
-
- enum ControlFrameFlag {
- ControlFrame_FLAG_FIN = 0x01,
- ControlFrame_FLAG_UNIDIRECTIONAL = 0x02
- };
-
- Q_DECLARE_FLAGS(ControlFrameFlags, ControlFrameFlag)
-
- enum SETTINGS_Flag {
- FLAG_SETTINGS_CLEAR_SETTINGS = 0x01
- };
-
- Q_DECLARE_FLAGS(SETTINGS_Flags, SETTINGS_Flag)
-
- enum SETTINGS_ID_Flag {
- FLAG_SETTINGS_PERSIST_VALUE = 0x01,
- FLAG_SETTINGS_PERSISTED = 0x02
- };
-
- Q_DECLARE_FLAGS(SETTINGS_ID_Flags, SETTINGS_ID_Flag)
-
- virtual void _q_receiveReply() override;
- virtual void _q_readyRead() override;
- virtual bool sendRequest() override;
-
-private slots:
- void _q_uploadDataReadyRead();
- void _q_replyDestroyed(QObject*);
- void _q_uploadDataDestroyed(QObject *);
-
-private:
-
- enum FrameType {
- FrameType_SYN_STREAM = 1,
- FrameType_SYN_REPLY = 2,
- FrameType_RST_STREAM = 3,
- FrameType_SETTINGS = 4,
- FrameType_PING = 6,
- FrameType_GOAWAY = 7,
- FrameType_HEADERS = 8,
- FrameType_WINDOW_UPDATE = 9,
- FrameType_CREDENTIAL // has a special type
- };
-
- enum StatusCode {
- StatusCode_PROTOCOL_ERROR = 1,
- StatusCode_INVALID_STREAM = 2,
- StatusCode_REFUSED_STREAM = 3,
- StatusCode_UNSUPPORTED_VERSION = 4,
- StatusCode_CANCEL = 5,
- StatusCode_INTERNAL_ERROR = 6,
- StatusCode_FLOW_CONTROL_ERROR = 7,
- StatusCode_STREAM_IN_USE = 8,
- StatusCode_STREAM_ALREADY_CLOSED = 9,
- StatusCode_INVALID_CREDENTIALS = 10,
- StatusCode_FRAME_TOO_LARGE = 11
- };
-
- enum SETTINGS_ID {
- SETTINGS_UPLOAD_BANDWIDTH = 1,
- SETTINGS_DOWNLOAD_BANDWIDTH = 2,
- SETTINGS_ROUND_TRIP_TIME = 3,
- SETTINGS_MAX_CONCURRENT_STREAMS = 4,
- SETTINGS_CURRENT_CWND = 5,
- SETTINGS_DOWNLOAD_RETRANS_RATE = 6,
- SETTINGS_INITIAL_WINDOW_SIZE = 7,
- SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE = 8
- };
-
- enum GOAWAY_STATUS {
- GOAWAY_OK = 0,
- GOAWAY_PROTOCOL_ERROR = 1,
- GOAWAY_INTERNAL_ERROR = 11
- };
-
- enum RST_STREAM_STATUS_CODE {
- RST_STREAM_PROTOCOL_ERROR = 1,
- RST_STREAM_INVALID_STREAM = 2,
- RST_STREAM_REFUSED_STREAM = 3,
- RST_STREAM_UNSUPPORTED_VERSION = 4,
- RST_STREAM_CANCEL = 5,
- RST_STREAM_INTERNAL_ERROR = 6,
- RST_STREAM_FLOW_CONTROL_ERROR = 7,
- RST_STREAM_STREAM_IN_USE = 8,
- RST_STREAM_STREAM_ALREADY_CLOSED = 9,
- RST_STREAM_INVALID_CREDENTIALS = 10,
- RST_STREAM_FRAME_TOO_LARGE = 11
- };
-
- quint64 bytesAvailable() const;
- bool readNextChunk(qint64 length, char *sink);
-
- void sendControlFrame(FrameType type, ControlFrameFlags flags, const char *data, quint32 length);
-
- void sendSYN_STREAM(const HttpMessagePair &pair, qint32 streamID,
- qint32 associatedToStreamID);
- void sendRST_STREAM(qint32 streamID, RST_STREAM_STATUS_CODE statusCode);
- void sendPING(quint32 pingID);
-
- bool uploadData(qint32 streamID);
- Q_INVOKABLE void sendWINDOW_UPDATE(qint32 streamID, quint32 deltaWindowSize);
-
- qint64 sendDataFrame(qint32 streamID, DataFrameFlags flags, quint32 length,
- const char *data);
-
- QByteArray composeHeader(const QHttpNetworkRequest &request);
- bool uncompressHeader(const QByteArray &input, QByteArray *output);
-
- void handleControlFrame(const QByteArray &frameHeaders);
- void handleDataFrame(const QByteArray &frameHeaders);
-
- void handleSYN_STREAM(char, quint32, const QByteArray &frameData);
- void handleSYN_REPLY(char flags, quint32, const QByteArray &frameData);
- void handleRST_STREAM(char flags, quint32 length, const QByteArray &frameData);
- void handleSETTINGS(char flags, quint32 length, const QByteArray &frameData);
- void handlePING(char, quint32 length, const QByteArray &frameData);
- void handleGOAWAY(char flags, quint32, const QByteArray &frameData);
- void handleHEADERS(char flags, quint32, const QByteArray &frameData);
- void handleWINDOW_UPDATE(char, quint32, const QByteArray &frameData);
-
- qint32 generateNextStreamID();
- void parseHttpHeaders(char flags, const QByteArray &frameData);
-
- void replyFinished(QHttpNetworkReply *httpReply, qint32 streamID);
- void replyFinishedWithError(QHttpNetworkReply *httpReply, qint32 streamID,
- QNetworkReply::NetworkError errorCode, const char *errorMessage);
-
- qint32 m_nextStreamID;
- QHash<quint32, HttpMessagePair> m_inFlightStreams;
- qint32 m_maxConcurrentStreams;
- quint32 m_initialWindowSize;
- QByteDataBuffer m_spdyBuffer;
- bool m_waitingForCompleteStream;
- z_stream m_deflateStream;
- z_stream m_inflateStream;
- QHash<QObject *, qint32> m_streamIDs;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSpdyProtocolHandler::DataFrameFlags)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSpdyProtocolHandler::ControlFrameFlags)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSpdyProtocolHandler::SETTINGS_Flags)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSpdyProtocolHandler::SETTINGS_ID_Flags)
-
-QT_END_NAMESPACE
-
-#endif // !defined(QT_NO_SSL)
-
-#endif // QSPDYPROTOCOLHANDLER_H
diff --git a/src/network/bearer/bearer.pri b/src/network/bearer/bearer.pri
index d58d5ec168..bcb7a5971e 100644
--- a/src/network/bearer/bearer.pri
+++ b/src/network/bearer/bearer.pri
@@ -6,11 +6,14 @@ HEADERS += bearer/qnetworkconfiguration.h \
bearer/qnetworkconfigmanager_p.h \
bearer/qnetworkconfiguration_p.h \
bearer/qnetworksession_p.h \
+ bearer/qnetworksession_impl_p.h \
bearer/qbearerengine_p.h \
+ bearer/qbearerengine_impl_p.h \
bearer/qbearerplugin_p.h \
bearer/qsharednetworksession_p.h
SOURCES += bearer/qnetworksession.cpp \
+ bearer/qnetworksession_impl.cpp \
bearer/qnetworkconfigmanager.cpp \
bearer/qnetworkconfiguration.cpp \
bearer/qnetworkconfigmanager_p.cpp \
diff --git a/src/plugins/bearer/qbearerengine_impl.h b/src/network/bearer/qbearerengine_impl_p.h
index 5c003aaaf6..4221b73276 100644
--- a/src/plugins/bearer/qbearerengine_impl.h
+++ b/src/network/bearer/qbearerengine_impl_p.h
@@ -42,9 +42,11 @@
#include <QtNetwork/private/qbearerengine_p.h>
+#ifndef QT_NO_BEARERMANAGEMENT
+
QT_BEGIN_NAMESPACE
-class QBearerEngineImpl : public QBearerEngine
+class Q_NETWORK_EXPORT QBearerEngineImpl : public QBearerEngine
{
Q_OBJECT
@@ -78,4 +80,6 @@ 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/network/bearer/qnetworksession_impl.cpp
index 8eba9ccc42..45a00b45fd 100644
--- a/src/plugins/bearer/qnetworksession_impl.cpp
+++ b/src/network/bearer/qnetworksession_impl.cpp
@@ -40,8 +40,8 @@
// see comment in ../platformdefs_win.h.
#define WIN32_LEAN_AND_MEAN 1
-#include "qnetworksession_impl.h"
-#include "qbearerengine_impl.h"
+#include "qnetworksession_impl_p.h"
+#include "qbearerengine_impl_p.h"
#include <QtNetwork/qnetworksession.h>
#include <QtNetwork/private/qnetworkconfigmanager_p.h>
@@ -51,6 +51,8 @@
#include <QtCore/qmutex.h>
#include <QtCore/qstringlist.h>
+#ifndef QT_NO_BEARERMANAGEMENT
+
QT_BEGIN_NAMESPACE
static QBearerEngineImpl *getEngineFromId(const QString &id)
@@ -433,3 +435,5 @@ void QNetworkSessionPrivateImpl::decrementTimeout()
QT_END_NAMESPACE
#include "qnetworksession_impl.moc"
+
+#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/qnetworksession_impl.h b/src/network/bearer/qnetworksession_impl_p.h
index 0f8e014900..b174760152 100644
--- a/src/plugins/bearer/qnetworksession_impl.h
+++ b/src/network/bearer/qnetworksession_impl_p.h
@@ -51,16 +51,18 @@
// We mean it.
//
-#include "qbearerengine_impl.h"
+#include "qbearerengine_impl_p.h"
#include <QtNetwork/private/qnetworkconfigmanager_p.h>
#include <QtNetwork/private/qnetworksession_p.h>
+#ifndef QT_NO_BEARERMANAGEMENT
+
QT_BEGIN_NAMESPACE
class QBearerEngineImpl;
-class QNetworkSessionPrivateImpl : public QNetworkSessionPrivate
+class Q_NETWORK_EXPORT QNetworkSessionPrivateImpl : public QNetworkSessionPrivate
{
Q_OBJECT
@@ -127,4 +129,6 @@ private:
QT_END_NAMESPACE
+#endif // QT_NO_BEARERMANAGEMENT
+
#endif // QNETWORKSESSION_IMPL_H
diff --git a/src/network/kernel/qnetworkinterface.h b/src/network/kernel/qnetworkinterface.h
index 4caedaa38f..c65ea58860 100644
--- a/src/network/kernel/qnetworkinterface.h
+++ b/src/network/kernel/qnetworkinterface.h
@@ -50,7 +50,6 @@
QT_BEGIN_NAMESPACE
class QDeadlineTimer;
-template<typename T> class QList;
class QNetworkAddressEntryPrivate;
class Q_NETWORK_EXPORT QNetworkAddressEntry
diff --git a/src/network/socket/qlocalserver_p.h b/src/network/socket/qlocalserver_p.h
index 92616e59ce..f331a3f10d 100644
--- a/src/network/socket/qlocalserver_p.h
+++ b/src/network/socket/qlocalserver_p.h
@@ -99,15 +99,18 @@ public:
QMap<quintptr, QTcpSocket*> socketMap;
#elif defined(Q_OS_WIN)
struct Listener {
- HANDLE handle;
+ Listener() = default;
+ HANDLE handle = nullptr;
OVERLAPPED overlapped;
- bool connected;
+ bool connected = false;
+ private:
+ Q_DISABLE_COPY(Listener)
};
void setError(const QString &function);
bool addListener();
- QList<Listener> listeners;
+ std::vector<std::unique_ptr<Listener>> listeners;
HANDLE eventHandle;
QWinEventNotifier *connectionEventNotifier;
#else
diff --git a/src/network/socket/qlocalserver_win.cpp b/src/network/socket/qlocalserver_win.cpp
index 2d71a7e730..6d92ebe93a 100644
--- a/src/network/socket/qlocalserver_win.cpp
+++ b/src/network/socket/qlocalserver_win.cpp
@@ -62,8 +62,8 @@ bool QLocalServerPrivate::addListener()
{
// The object must not change its address once the
// contained OVERLAPPED struct is passed to Windows.
- listeners << Listener();
- Listener &listener = listeners.last();
+ listeners.push_back(std::make_unique<Listener>());
+ auto &listener = listeners.back();
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
@@ -175,7 +175,7 @@ bool QLocalServerPrivate::addListener()
sa.lpSecurityDescriptor = pSD.data();
}
- listener.handle = CreateNamedPipe(
+ listener->handle = CreateNamedPipe(
reinterpret_cast<const wchar_t *>(fullServerName.utf16()), // pipe name
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, // read/write access
PIPE_TYPE_BYTE | // byte type pipe
@@ -187,32 +187,32 @@ bool QLocalServerPrivate::addListener()
3000, // client time-out
&sa);
- if (listener.handle == INVALID_HANDLE_VALUE) {
+ if (listener->handle == INVALID_HANDLE_VALUE) {
setError(QLatin1String("QLocalServerPrivate::addListener"));
- listeners.removeLast();
+ listeners.pop_back();
return false;
}
if (worldSID)
FreeSid(worldSID);
- memset(&listener.overlapped, 0, sizeof(listener.overlapped));
- listener.overlapped.hEvent = eventHandle;
+ memset(&listener->overlapped, 0, sizeof(OVERLAPPED));
+ listener->overlapped.hEvent = eventHandle;
// Beware! ConnectNamedPipe will reset the eventHandle to non-signaled.
// Callers of addListener must check all listeners for connections.
- if (!ConnectNamedPipe(listener.handle, &listener.overlapped)) {
+ if (!ConnectNamedPipe(listener->handle, &listener->overlapped)) {
switch (GetLastError()) {
case ERROR_IO_PENDING:
- listener.connected = false;
+ listener->connected = false;
break;
case ERROR_PIPE_CONNECTED:
- listener.connected = true;
+ listener->connected = true;
break;
default:
- CloseHandle(listener.handle);
+ CloseHandle(listener->handle);
setError(QLatin1String("QLocalServerPrivate::addListener"));
- listeners.removeLast();
+ listeners.pop_back();
return false;
}
} else {
@@ -284,12 +284,12 @@ void QLocalServerPrivate::_q_onNewConnection()
// Testing shows that there is indeed absolutely no guarantee which listener gets
// a client connection first, so there is no way around polling all of them.
- for (int i = 0; i < listeners.size(); ) {
- HANDLE handle = listeners[i].handle;
- if (listeners[i].connected
- || GetOverlappedResult(handle, &listeners[i].overlapped, &dummy, FALSE))
+ for (size_t i = 0; i < listeners.size(); ) {
+ HANDLE handle = listeners[i]->handle;
+ if (listeners[i]->connected
+ || GetOverlappedResult(handle, &listeners[i]->overlapped, &dummy, FALSE))
{
- listeners.removeAt(i);
+ listeners.erase(listeners.begin() + i);
addListener();
@@ -319,8 +319,8 @@ void QLocalServerPrivate::closeServer()
connectionEventNotifier->deleteLater();
connectionEventNotifier = 0;
CloseHandle(eventHandle);
- for (int i = 0; i < listeners.size(); ++i)
- CloseHandle(listeners[i].handle);
+ for (size_t i = 0; i < listeners.size(); ++i)
+ CloseHandle(listeners[i]->handle);
listeners.clear();
}
diff --git a/src/network/ssl/qssl.cpp b/src/network/ssl/qssl.cpp
index c9fa7f85d9..bfbe8eb90f 100644
--- a/src/network/ssl/qssl.cpp
+++ b/src/network/ssl/qssl.cpp
@@ -120,8 +120,6 @@ Q_LOGGING_CATEGORY(lcSsl, "qt.network.ssl");
Describes the protocol of the cipher.
- \value SslV3 SSLv3; not supported by QSslSocket.
- \value SslV2 SSLv2; not supported by QSslSocket.
\value TlsV1_0 TLSv1.0
\value TlsV1_0OrLater TLSv1.0 and later versions. This option is not available when using the WinRT backend due to platform limitations.
\value TlsV1 Obsolete, means the same as TlsV1_0
@@ -137,7 +135,6 @@ Q_LOGGING_CATEGORY(lcSsl, "qt.network.ssl");
\value TlsV1_3OrLater TLSv1.3 and later versions. (Since Qt 5.12)
\value UnknownProtocol The cipher's protocol cannot be determined.
\value AnyProtocol Any supported protocol. This value is used by QSslSocket only.
- \value TlsV1SslV3 Same as TlsV1_0.
\value SecureProtocols The default option, using protocols known to be secure.
*/
diff --git a/src/network/ssl/qssl.h b/src/network/ssl/qssl.h
index b28c2a87b9..1fd2cf9c6d 100644
--- a/src/network/ssl/qssl.h
+++ b/src/network/ssl/qssl.h
@@ -77,20 +77,10 @@ namespace QSsl {
#endif
enum SslProtocol {
-#if QT_DEPRECATED_SINCE(5, 15)
- SslV3,
- SslV2,
-#endif
TlsV1_0 = 2,
-#if QT_DEPRECATED_SINCE(5,0)
- TlsV1 = TlsV1_0,
-#endif
TlsV1_1,
TlsV1_2,
AnyProtocol,
-#if QT_DEPRECATED_SINCE(5, 15)
- TlsV1SslV3,
-#endif
SecureProtocols = AnyProtocol + 2,
TlsV1_0OrLater,
diff --git a/src/network/ssl/qsslconfiguration.cpp b/src/network/ssl/qsslconfiguration.cpp
index a2e694ec92..b6199a2b16 100644
--- a/src/network/ssl/qsslconfiguration.cpp
+++ b/src/network/ssl/qsslconfiguration.cpp
@@ -54,7 +54,6 @@ const QSsl::SslOptions QSslConfigurationPrivate::defaultSslOptions = QSsl::SslOp
|QSsl::SslOptionDisableSessionPersistence;
const char QSslConfiguration::ALPNProtocolHTTP2[] = "h2";
-const char QSslConfiguration::NextProtocolSpdy3_0[] = "spdy/3";
const char QSslConfiguration::NextProtocolHttp1_1[] = "http/1.1";
/*!
@@ -134,12 +133,6 @@ const char QSslConfiguration::NextProtocolHttp1_1[] = "http/1.1";
*/
/*!
- \variable QSslConfiguration::NextProtocolSpdy3_0
- \brief The value used for negotiating SPDY 3.0 during the Next
- Protocol Negotiation.
-*/
-
-/*!
\variable QSslConfiguration::NextProtocolHttp1_1
\brief The value used for negotiating HTTP 1.1 during the Next
Protocol Negotiation.
@@ -229,7 +222,9 @@ bool QSslConfiguration::operator==(const QSslConfiguration &other) const
d->nextNegotiatedProtocol == other.d->nextNegotiatedProtocol &&
d->nextProtocolNegotiationStatus == other.d->nextProtocolNegotiationStatus &&
d->dtlsCookieEnabled == other.d->dtlsCookieEnabled &&
- d->ocspStaplingEnabled == other.d->ocspStaplingEnabled;
+ d->ocspStaplingEnabled == other.d->ocspStaplingEnabled &&
+ d->reportFromCallback == other.d->reportFromCallback &&
+ d->missingCertIsFatal == other.d->missingCertIsFatal;
}
/*!
@@ -274,7 +269,9 @@ bool QSslConfiguration::isNull() const
d->nextAllowedProtocols.isEmpty() &&
d->nextNegotiatedProtocol.isNull() &&
d->nextProtocolNegotiationStatus == QSslConfiguration::NextProtocolNegotiationNone &&
- d->ocspStaplingEnabled == false);
+ d->ocspStaplingEnabled == false &&
+ d->reportFromCallback == false &&
+ d->missingCertIsFatal == false);
}
/*!
@@ -1033,7 +1030,7 @@ QByteArray QSslConfiguration::nextNegotiatedProtocol() const
Whether or not the negotiation succeeded can be queried through
nextProtocolNegotiationStatus().
- \sa nextNegotiatedProtocol(), nextProtocolNegotiationStatus(), allowedNextProtocols(), QSslConfiguration::NextProtocolSpdy3_0, QSslConfiguration::NextProtocolHttp1_1
+ \sa nextNegotiatedProtocol(), nextProtocolNegotiationStatus(), allowedNextProtocols(), QSslConfiguration::NextProtocolHttp1_1
*/
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QSslConfiguration::setAllowedNextProtocols(const QList<QByteArray> &protocols)
@@ -1051,7 +1048,7 @@ void QSslConfiguration::setAllowedNextProtocols(QList<QByteArray> protocols)
server through the Next Protocol Negotiation (NPN) or Application-Layer
Protocol Negotiation (ALPN) TLS extension, as set by setAllowedNextProtocols().
- \sa nextNegotiatedProtocol(), nextProtocolNegotiationStatus(), setAllowedNextProtocols(), QSslConfiguration::NextProtocolSpdy3_0, QSslConfiguration::NextProtocolHttp1_1
+ \sa nextNegotiatedProtocol(), nextProtocolNegotiationStatus(), setAllowedNextProtocols(), QSslConfiguration::NextProtocolHttp1_1
*/
QList<QByteArray> QSslConfiguration::allowedNextProtocols() const
{
@@ -1197,6 +1194,89 @@ bool QSslConfiguration::ocspStaplingEnabled() const
return d->ocspStaplingEnabled;
}
+/*!
+ \since 6.0
+
+ Returns true if a verification callback will emit QSslSocket::handshakeInterruptedOnError()
+ early, before concluding the handshake.
+
+ \note This function always returns false for all backends but OpenSSL.
+
+ \sa setHandshakeMustInterruptOnError(), QSslSocket::handshakeInterruptedOnError(), QSslSocket::continueInterruptedHandshake()
+*/
+bool QSslConfiguration::handshakeMustInterruptOnError() const
+{
+ return d->reportFromCallback;
+}
+
+/*!
+ \since 6.0
+
+ If \a interrupt is true and the underlying backend supports this option,
+ errors found during certificate verification are reported immediately
+ by emitting QSslSocket::handshakeInterruptedOnError(). This allows
+ to stop the unfinished handshake and send a proper alert message to
+ a peer. No special action is required from the application in this case.
+ QSslSocket will close the connection after sending the alert message.
+ If the application after inspecting the error wants to continue the
+ handshake, it must call QSslSocket::continueInterruptedHandshake()
+ from its slot function. The signal-slot connection must be direct.
+
+ \note When interrupting handshake is enabled, errors that would otherwise
+ be reported by QSslSocket::peerVerifyError() are instead only reported by
+ QSslSocket::handshakeInterruptedOnError().
+ \note Even if the handshake was continued, these errors will be
+ reported when emitting QSslSocket::sslErrors() signal (and thus must
+ be ignored in the corresponding function slot).
+
+ \sa handshakeMustInterruptOnError(), QSslSocket::handshakeInterruptedOnError(), QSslSocket::continueInterruptedHandshake()
+*/
+void QSslConfiguration::setHandshakeMustInterruptOnError(bool interrupt)
+{
+#if QT_CONFIG(openssl)
+ d->reportFromCallback = interrupt;
+#else
+ qCWarning(lcSsl, "This operation requires OpenSSL as TLS backend");
+#endif
+}
+
+/*!
+ \since 6.0
+
+ Returns true if errors with code QSslError::NoPeerCertificate
+ cannot be ignored.
+
+ \note Always returns false for all TLS backends but OpenSSL.
+
+ \sa QSslSocket::ignoreSslErrors(), setMissingCertificateIsFatal()
+*/
+bool QSslConfiguration::missingCertificateIsFatal() const
+{
+ return d->missingCertIsFatal;
+}
+
+/*!
+ \since 6.0
+
+ If \a cannotRecover is true, and verification mode in use is
+ QSslSocket::VerifyPeer or QSslSocket::AutoVerifyPeer (for a
+ client-side socket), the missing peer's certificate would be
+ treated as an unrecoverable error that cannot be ignored. A proper
+ alert message will be sent to the peer before closing the connection.
+
+ \note Only available if Qt was configured and built with OpenSSL backend.
+
+ \sa QSslSocket::ignoreSslErrors(), QSslSocket::PeerVerifyMode, missingCertificateIsFatal()
+*/
+void QSslConfiguration::setMissingCertificateIsFatal(bool cannotRecover)
+{
+#if QT_CONFIG(openssl)
+ d->missingCertIsFatal = cannotRecover;
+#else
+ qCWarning(lcSsl, "Handling a missing certificate as a fatal error requires an OpenSSL backend");
+#endif // openssl
+}
+
/*! \internal
*/
bool QSslConfigurationPrivate::peerSessionWasShared(const QSslConfiguration &configuration) {
diff --git a/src/network/ssl/qsslconfiguration.h b/src/network/ssl/qsslconfiguration.h
index 247f3aecc9..dc4587a835 100644
--- a/src/network/ssl/qsslconfiguration.h
+++ b/src/network/ssl/qsslconfiguration.h
@@ -66,7 +66,6 @@
QT_BEGIN_NAMESPACE
-template<typename T> class QList;
class QSslCertificate;
class QSslCipher;
class QSslKey;
@@ -173,6 +172,12 @@ public:
static void setDefaultDtlsConfiguration(const QSslConfiguration &configuration);
#endif // dtls
+ bool handshakeMustInterruptOnError() const;
+ void setHandshakeMustInterruptOnError(bool interrupt);
+
+ bool missingCertificateIsFatal() const;
+ void setMissingCertificateIsFatal(bool cannotRecover);
+
void setOcspStaplingEnabled(bool enable);
bool ocspStaplingEnabled() const;
@@ -193,7 +198,6 @@ public:
NextProtocolNegotiationStatus nextProtocolNegotiationStatus() const;
static const char ALPNProtocolHTTP2[];
- static const char NextProtocolSpdy3_0[];
static const char NextProtocolHttp1_1[];
private:
diff --git a/src/network/ssl/qsslconfiguration_p.h b/src/network/ssl/qsslconfiguration_p.h
index 83126bb9a0..6ee3490df6 100644
--- a/src/network/ssl/qsslconfiguration_p.h
+++ b/src/network/ssl/qsslconfiguration_p.h
@@ -149,6 +149,14 @@ public:
const bool ocspStaplingEnabled = false;
#endif
+#if QT_CONFIG(openssl)
+ bool reportFromCallback = false;
+ bool missingCertIsFatal = false;
+#else
+ const bool reportFromCallback = false;
+ const bool missingCertIsFatal = false;
+#endif // openssl
+
// in qsslsocket.cpp:
static QSslConfiguration defaultConfiguration();
static void setDefaultConfiguration(const QSslConfiguration &configuration);
diff --git a/src/network/ssl/qsslcontext_openssl.cpp b/src/network/ssl/qsslcontext_openssl.cpp
index 562aa4f518..574f48a2b5 100644
--- a/src/network/ssl/qsslcontext_openssl.cpp
+++ b/src/network/ssl/qsslcontext_openssl.cpp
@@ -56,6 +56,7 @@ QT_BEGIN_NAMESPACE
// defined in qsslsocket_openssl.cpp:
extern int q_X509Callback(int ok, X509_STORE_CTX *ctx);
+extern "C" int q_X509CallbackDirect(int ok, X509_STORE_CTX *ctx);
extern QString getErrorsFromOpenSsl();
#if QT_CONFIG(dtls)
@@ -286,42 +287,31 @@ void QSslContext::initSslContext(QSslContext *sslContext, QSslSocket::SslMode mo
bool unsupportedProtocol = false;
bool isDtls = false;
init_context:
- if (sslContext->sslConfiguration.protocol() == QSsl::SslV2) {
- // SSL 2 is no longer supported, but chosen deliberately -> error
- sslContext->ctx = nullptr;
- unsupportedProtocol = true;
- } else if (sslContext->sslConfiguration.protocol() == QSsl::SslV3) {
- // SSL 3 is no longer supported, but chosen deliberately -> error
- sslContext->ctx = nullptr;
- unsupportedProtocol = true;
- } else {
- switch (sslContext->sslConfiguration.protocol()) {
- case QSsl::DtlsV1_0:
- case QSsl::DtlsV1_0OrLater:
- case QSsl::DtlsV1_2:
- case QSsl::DtlsV1_2OrLater:
+ switch (sslContext->sslConfiguration.protocol()) {
+ case QSsl::DtlsV1_0:
+ case QSsl::DtlsV1_0OrLater:
+ case QSsl::DtlsV1_2:
+ case QSsl::DtlsV1_2OrLater:
#if QT_CONFIG(dtls)
- isDtls = true;
- sslContext->ctx = q_SSL_CTX_new(client ? q_DTLS_client_method() : q_DTLS_server_method());
+ isDtls = true;
+ sslContext->ctx = q_SSL_CTX_new(client ? q_DTLS_client_method() : q_DTLS_server_method());
#else // dtls
- sslContext->ctx = nullptr;
- unsupportedProtocol = true;
- qCWarning(lcSsl, "DTLS protocol requested, but feature 'dtls' is disabled");
-
+ sslContext->ctx = nullptr;
+ unsupportedProtocol = true;
+ qCWarning(lcSsl, "DTLS protocol requested, but feature 'dtls' is disabled");
#endif // dtls
- break;
- case QSsl::TlsV1_3:
- case QSsl::TlsV1_3OrLater:
+ break;
+ case QSsl::TlsV1_3:
+ case QSsl::TlsV1_3OrLater:
#if !defined(TLS1_3_VERSION)
- qCWarning(lcSsl, "TLS 1.3 is not supported");
- sslContext->ctx = nullptr;
- unsupportedProtocol = true;
- break;
+ qCWarning(lcSsl, "TLS 1.3 is not supported");
+ sslContext->ctx = nullptr;
+ unsupportedProtocol = true;
+ break;
#endif // TLS1_3_VERSION
- default:
- // The ssl options will actually control the supported methods
- sslContext->ctx = q_SSL_CTX_new(client ? q_TLS_client_method() : q_TLS_server_method());
- }
+ default:
+ // The ssl options will actually control the supported methods
+ sslContext->ctx = q_SSL_CTX_new(client ? q_TLS_client_method() : q_TLS_server_method());
}
if (!sslContext->ctx) {
@@ -373,7 +363,6 @@ init_context:
#endif // TLS1_3_VERSION
break;
// Ranges:
- case QSsl::TlsV1SslV3:
case QSsl::AnyProtocol:
case QSsl::SecureProtocols:
case QSsl::TlsV1_0OrLater:
@@ -415,12 +404,6 @@ init_context:
Q_UNREACHABLE();
break;
#endif // TLS1_3_VERSION
- case QSsl::SslV2:
- case QSsl::SslV3:
- // These protocols are not supported, and we handle
- // them as an error (see the code above).
- Q_UNREACHABLE();
- break;
case QSsl::UnknownProtocol:
break;
}
@@ -589,11 +572,20 @@ init_context:
if (sslContext->sslConfiguration.peerVerifyMode() == QSslSocket::VerifyNone) {
q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_NONE, nullptr);
} else {
- q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_PEER,
-#if QT_CONFIG(dtls)
- isDtls ? dtlscallbacks::q_X509DtlsCallback :
-#endif // dtls
- q_X509Callback);
+ auto verificationCallback =
+ #if QT_CONFIG(dtls)
+ isDtls ? dtlscallbacks::q_X509DtlsCallback :
+ #endif // dtls
+ q_X509Callback;
+
+ if (!isDtls && configuration.handshakeMustInterruptOnError())
+ verificationCallback = q_X509CallbackDirect;
+
+ auto verificationMode = SSL_VERIFY_PEER;
+ if (!isDtls && sslContext->sslConfiguration.missingCertificateIsFatal())
+ verificationMode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
+
+ q_SSL_CTX_set_verify(sslContext->ctx, verificationMode, verificationCallback);
}
#if QT_CONFIG(dtls)
diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp
index cf971a30bf..504e27a463 100644
--- a/src/network/ssl/qsslsocket.cpp
+++ b/src/network/ssl/qsslsocket.cpp
@@ -228,6 +228,74 @@
*/
/*!
+ \enum QAlertLevel
+ \brief Describes the level of an alert message
+ \relates QSslSocket
+ \since 6.0
+
+ \ingroup network
+ \ingroup ssl
+ \inmodule QtNetwork
+
+ This enum describes the level of an alert message that was sent
+ or received.
+
+ \value Warning Non-fatal alert message
+ \value Fatal Fatal alert message, the underlying backend will
+ handle such an alert properly and close the connection.
+ \value Unknown An alert of unknown level of severity.
+*/
+
+/*!
+ \enum QAlertType
+ \brief Enumerates possible codes that an alert message can have
+ \relates QSslSocket
+ \since 6.0
+
+ \ingroup network
+ \ingroup ssl
+ \inmodule QtNetwork
+
+ See \l{https://tools.ietf.org/html/rfc8446#page-85}{RFC 8446, section 6}
+ for the possible values and their meaning.
+
+ \value CloseNotify,
+ \value UnexpectedMessage
+ \value BadRecordMac
+ \value RecordOverflow
+ \value DecompressionFailure
+ \value HandshakeFailure
+ \value NoCertificate
+ \value BadCertificate
+ \value UnsupportedCertificate
+ \value CertificateRevoked
+ \value CertificateExpired
+ \value CertificateUnknown
+ \value IllegalParameter
+ \value UnknownCa
+ \value AccessDenied
+ \value DecodeError
+ \value DecryptError
+ \value ExportRestriction
+ \value ProtocolVersion
+ \value InsufficientSecurity
+ \value InternalError
+ \value InappropriateFallback
+ \value UserCancelled
+ \value NoRenegotiation
+ \value MissingExtension
+ \value UnsupportedExtension
+ \value CertificateUnobtainable
+ \value UnrecognizedName
+ \value BadCertificateStatusResponse
+ \value BadCertificateHashValue
+ \value UnknownPskIdentity
+ \value CertificateRequired
+ \value NoApplicationProtocol
+ \value UnknownAlertMessage
+*/
+
+/*!
\fn void QSslSocket::encrypted()
This signal is emitted when QSslSocket enters encrypted mode. After this
@@ -322,6 +390,48 @@
\sa QSslPreSharedKeyAuthenticator
*/
+/*!
+ \fn void QSslSocket::alertSent(QAlertLevel level, QAlertType type, const QString &description)
+
+ QSslSocket emits this signal if an alert message was sent to a peer. \a level
+ describes if it was a warning or a fatal error. \a type gives the code
+ of the alert message. When a textual description of the alert message is
+ available, it is supplied in \a description.
+
+ \note This signal is mostly informational and can be used for debugging
+ purposes, normally it does not require any actions from the application.
+ \note Not all backends support this functionality.
+
+ \sa alertReceived(), QAlertLevel, QAlertType
+*/
+
+/*!
+ \fn void QSslSocket::alertReceived(QAlertLevel level, QAlertType type, const QString &description)
+
+ QSslSocket emits this signal if an alert message was received from a peer.
+ \a level tells if the alert was fatal or it was a warning. \a type is the
+ code explaining why the alert was sent. When a textual description of
+ the alert message is available, it is supplied in \a description.
+
+ \note The signal is mostly for informational and debugging purposes and does not
+ require any handling in the application. If the alert was fatal, underlying
+ backend will handle it and close the connection.
+ \note Not all backends support this functionality.
+
+ \sa alertSent(), QAlertLevel, QAlertType
+*/
+
+/*!
+ \fn void QSslSocket::handshakeInterruptedOnError(const QSslError &error)
+
+ QSslSocket emits this signal if a certificate verification error was
+ found and if early error reporting was enabled in QSslConfiguration.
+ An application is expected to inspect the \a error and decide if
+ it wants to continue the handshake, or abort it and send an alert message
+ to the peer. The signal-slot connection must be direct.
+
+ \sa continueInterruptedHandshake(), sslErrors(), QSslConfiguration::setHandshakeMustInterruptOnError()
+*/
#include "qssl_p.h"
#include "qsslsocket.h"
#include "qsslcipher.h"
@@ -977,7 +1087,10 @@ void QSslSocket::setSslConfiguration(const QSslConfiguration &configuration)
#if QT_CONFIG(ocsp)
d->configuration.ocspStaplingEnabled = configuration.ocspStaplingEnabled();
#endif
-
+#if QT_CONFIG(openssl)
+ d->configuration.reportFromCallback = configuration.handshakeMustInterruptOnError();
+ d->configuration.missingCertIsFatal = configuration.missingCertificateIsFatal();
+#endif // openssl
// if the CA certificates were set explicitly (either via
// QSslConfiguration::setCaCertificates() or QSslSocket::setCaCertificates(),
// we cannot load the certificates on demand
@@ -2064,6 +2177,23 @@ void QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
d->ignoreErrorsList = errors;
}
+
+/*!
+ \since 6.0
+
+ If an application wants to conclude a handshake even after receiving
+ handshakeInterruptedOnError() signal, it must call this function.
+ This call must be done from a slot function attached to the signal.
+ The signal-slot connection must be direct.
+
+ \sa handshakeInterruptedOnError(), QSslConfiguration::setHandshakeMustInterruptOnError()
+*/
+void QSslSocket::continueInterruptedHandshake()
+{
+ Q_D(QSslSocket);
+ d->handshakeInterrupted = false;
+}
+
/*!
\internal
*/
@@ -2238,13 +2368,24 @@ void QSslSocketPrivate::init()
*/
bool QSslSocketPrivate::verifyProtocolSupported(const char *where)
{
- if (configuration.protocol == QSsl::SslV2 || configuration.protocol == QSsl::SslV3) {
- qCWarning(lcSsl) << where << "Attempted to use an unsupported protocol.";
+ QLatin1String protocolName("DTLS");
+ switch (configuration.protocol) {
+ case QSsl::UnknownProtocol:
+ // UnknownProtocol, according to our docs, is for cipher whose protocol is unknown.
+ // Should not be used when configuring QSslSocket.
+ protocolName = QLatin1String("UnknownProtocol");
+ Q_FALLTHROUGH();
+ case QSsl::DtlsV1_0:
+ case QSsl::DtlsV1_2:
+ case QSsl::DtlsV1_0OrLater:
+ case QSsl::DtlsV1_2OrLater:
+ qCWarning(lcSsl) << where << "QSslConfiguration with unexpected protocol" << protocolName;
setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
QSslSocket::tr("Attempted to use an unsupported protocol."));
return false;
+ default:
+ return true;
}
- return true;
}
/*!
@@ -2455,6 +2596,10 @@ void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPri
#if QT_CONFIG(ocsp)
ptr->ocspStaplingEnabled = global->ocspStaplingEnabled;
#endif
+#if QT_CONFIG(openssl)
+ ptr->reportFromCallback = global->reportFromCallback;
+ ptr->missingCertIsFatal = global->missingCertIsFatal;
+#endif
}
/*!
diff --git a/src/network/ssl/qsslsocket.h b/src/network/ssl/qsslsocket.h
index 2c3b876c49..c12bb53334 100644
--- a/src/network/ssl/qsslsocket.h
+++ b/src/network/ssl/qsslsocket.h
@@ -63,6 +63,49 @@ class QSslEllipticCurve;
class QSslPreSharedKeyAuthenticator;
class QOcspResponse;
+enum class QAlertLevel {
+ Warning,
+ Fatal,
+ Unknown
+};
+
+enum class QAlertType {
+ CloseNotify,
+ UnexpectedMessage = 10,
+ BadRecordMac = 20,
+ RecordOverflow = 22,
+ DecompressionFailure = 30, // reserved
+ HandshakeFailure = 40,
+ NoCertificate = 41, // reserved
+ BadCertificate = 42,
+ UnsupportedCertificate = 43,
+ CertificateRevoked = 44,
+ CertificateExpired = 45,
+ CertificateUnknown = 46,
+ IllegalParameter = 47,
+ UnknownCa = 48,
+ AccessDenied = 49,
+ DecodeError = 50,
+ DecryptError = 51,
+ ExportRestriction = 60, // reserved
+ ProtocolVersion = 70,
+ InsufficientSecurity = 71,
+ InternalError = 80,
+ InappropriateFallback = 86,
+ UserCancelled = 90,
+ NoRenegotiation = 100,
+ MissingExtension = 109,
+ UnsupportedExtension = 110,
+ CertificateUnobtainable = 111, // reserved
+ UnrecognizedName = 112,
+ BadCertificateStatusResponse = 113,
+ BadCertificateHashValue = 114, // reserved
+ UnknownPskIdentity = 115,
+ CertificateRequired = 116,
+ NoApplicationProtocol = 120,
+ UnknownAlertMessage = 255
+};
+
class QSslSocketPrivate;
class Q_NETWORK_EXPORT QSslSocket : public QTcpSocket
{
@@ -204,6 +247,7 @@ public:
static QString sslLibraryBuildVersionString();
void ignoreSslErrors(const QList<QSslError> &errors);
+ void continueInterruptedHandshake();
public Q_SLOTS:
void startClientEncryption();
@@ -217,6 +261,9 @@ Q_SIGNALS:
void modeChanged(QSslSocket::SslMode newMode);
void encryptedBytesWritten(qint64 totalBytes);
void preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator);
+ void alertSent(QAlertLevel level, QAlertType type, const QString &description);
+ void alertReceived(QAlertLevel level, QAlertType type, const QString &description);
+ void handshakeInterruptedOnError(const QSslError &error);
protected:
qint64 readData(char *data, qint64 maxlen) override;
diff --git a/src/network/ssl/qsslsocket_mac.cpp b/src/network/ssl/qsslsocket_mac.cpp
index e0e065679d..fe1c43d992 100644
--- a/src/network/ssl/qsslsocket_mac.cpp
+++ b/src/network/ssl/qsslsocket_mac.cpp
@@ -496,10 +496,6 @@ QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
}
switch (protocol) {
- case kSSLProtocol2:
- return QSsl::SslV2;
- case kSSLProtocol3:
- return QSsl::SslV3;
case kTLSProtocol1:
return QSsl::TlsV1_0;
case kTLSProtocol11:
@@ -657,23 +653,6 @@ QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSLCipherSuite(SSLCipherSui
QSslCipher ciph;
switch (cipher) {
// Sorted as in CipherSuite.h (and groupped by their RFC)
- case SSL_RSA_WITH_NULL_MD5:
- ciph.d->name = QLatin1String("NULL-MD5");
- ciph.d->protocol = QSsl::SslV3;
- break;
- case SSL_RSA_WITH_NULL_SHA:
- ciph.d->name = QLatin1String("NULL-SHA");
- ciph.d->protocol = QSsl::SslV3;
- break;
- case SSL_RSA_WITH_RC4_128_MD5:
- ciph.d->name = QLatin1String("RC4-MD5");
- ciph.d->protocol = QSsl::SslV3;
- break;
- case SSL_RSA_WITH_RC4_128_SHA:
- ciph.d->name = QLatin1String("RC4-SHA");
- ciph.d->protocol = QSsl::SslV3;
- break;
-
// TLS addenda using AES, per RFC 3268
case TLS_RSA_WITH_AES_128_CBC_SHA:
ciph.d->name = QLatin1String("AES128-SHA");
@@ -822,12 +801,8 @@ QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSLCipherSuite(SSLCipherSui
ciph.d->isNull = false;
// protocol
- if (ciph.d->protocol == QSsl::SslV3) {
- ciph.d->protocolString = QLatin1String("SSLv3");
- } else {
- ciph.d->protocol = QSsl::TlsV1_2;
- ciph.d->protocolString = QLatin1String("TLSv1.2");
- }
+ ciph.d->protocol = QSsl::TlsV1_2;
+ ciph.d->protocolString = QLatin1String("TLSv1.2");
const auto bits = ciph.d->name.splitRef(QLatin1Char('-'));
if (bits.size() >= 2) {
@@ -1106,22 +1081,6 @@ bool QSslSocketBackendPrivate::setSessionProtocol()
{
Q_ASSERT_X(context, Q_FUNC_INFO, "invalid SSL context (null)");
- // QSsl::SslV2 == kSSLProtocol2 is disabled in Secure Transport and
- // always fails with errSSLIllegalParam:
- // if (version < MINIMUM_STREAM_VERSION || version > MAXIMUM_STREAM_VERSION)
- // return errSSLIllegalParam;
- // where MINIMUM_STREAM_VERSION is SSL_Version_3_0, MAXIMUM_STREAM_VERSION is TLS_Version_1_2.
- if (configuration.protocol == QSsl::SslV2) {
- qCDebug(lcSsl) << "protocol QSsl::SslV2 is disabled";
- return false;
- }
-
- // SslV3 is unsupported.
- if (configuration.protocol == QSsl::SslV3) {
- qCDebug(lcSsl) << "protocol QSsl::SslV3 is disabled";
- return false;
- }
-
// SecureTransport has kTLSProtocol13 constant and also, kTLSProtocolMaxSupported.
// Calling SSLSetProtocolVersionMax/Min with any of these two constants results
// in errInvalidParam and a failure to set the protocol version. This means
@@ -1162,13 +1121,6 @@ bool QSslSocketBackendPrivate::setSessionProtocol()
qCDebug(lcSsl) << plainSocket << "requesting : any";
#endif
err = SSLSetProtocolVersionMin(context, kTLSProtocol1);
- } else if (configuration.protocol == QSsl::TlsV1SslV3) {
- #ifdef QSSLSOCKET_DEBUG
- qCDebug(lcSsl) << plainSocket << "requesting : SSLv3 - TLSv1.2";
- #endif
- err = SSLSetProtocolVersionMin(context, kTLSProtocol1);
- if (err == errSecSuccess)
- err = SSLSetProtocolVersionMax(context, kTLSProtocol1);
} else if (configuration.protocol == QSsl::SecureProtocols) {
#ifdef QSSLSOCKET_DEBUG
qCDebug(lcSsl) << plainSocket << "requesting : TLSv1 - TLSv1.2";
@@ -1213,8 +1165,6 @@ bool QSslSocketBackendPrivate::verifySessionProtocol() const
bool protocolOk = false;
if (configuration.protocol == QSsl::AnyProtocol)
protocolOk = true;
- else if (configuration.protocol == QSsl::TlsV1SslV3)
- protocolOk = (sessionProtocol() == QSsl::TlsV1_0);
else if (configuration.protocol == QSsl::SecureProtocols)
protocolOk = (sessionProtocol() >= QSsl::TlsV1_0);
else if (configuration.protocol == QSsl::TlsV1_0OrLater)
diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp
index 41f933b299..11989cd2ef 100644
--- a/src/network/ssl/qsslsocket_openssl.cpp
+++ b/src/network/ssl/qsslsocket_openssl.cpp
@@ -98,6 +98,123 @@
QT_BEGIN_NAMESPACE
+namespace {
+
+QAlertLevel tlsAlertLevel(int value)
+{
+ if (const char *typeString = q_SSL_alert_type_string(value)) {
+ // Documented to return 'W' for warning, 'F' for fatal,
+ // 'U' for unknown.
+ switch (typeString[0]) {
+ case 'W':
+ return QAlertLevel::Warning;
+ case 'F':
+ return QAlertLevel::Fatal;
+ default:;
+ }
+ }
+
+ return QAlertLevel::Unknown;
+}
+
+QString tlsAlertDescription(int value)
+{
+ QString description = QLatin1String(q_SSL_alert_desc_string_long(value));
+ if (!description.size())
+ description = QLatin1String("no description provided");
+ return description;
+}
+
+QAlertType tlsAlertType(int value)
+{
+ // In case for some reason openssl gives us a value,
+ // which is not in our enum actually, we leave it to
+ // an application to handle (supposedly they have
+ // if or switch-statements).
+ return QAlertType(value & 0xff);
+}
+
+} // Unnamed namespace
+
+extern "C"
+{
+
+void qt_AlertInfoCallback(const SSL *connection, int from, int value)
+{
+ // Passed to SSL_set_info_callback()
+ // https://www.openssl.org/docs/man1.1.1/man3/SSL_set_info_callback.html
+
+ if (!connection) {
+#ifdef QSSLSOCKET_DEBUG
+ qCWarning(lcSsl, "Invalid 'connection' parameter (nullptr)");
+#endif // QSSLSOCKET_DEBUG
+ return;
+ }
+
+ const auto offset = QSslSocketBackendPrivate::s_indexForSSLExtraData
+ + QSslSocketBackendPrivate::socketOffsetInExData;
+ auto privateSocket =
+ static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(connection, offset));
+ if (!privateSocket) {
+ // SSL_set_ex_data can fail:
+#ifdef QSSLSOCKET_DEBUG
+ qCWarning(lcSsl, "No external data (socket backend) found for parameter 'connection'");
+#endif // QSSLSOCKET_DEBUG
+ return;
+ }
+
+ if (!(from & SSL_CB_ALERT)) {
+ // We only want to know about alerts (at least for now).
+ return;
+ }
+
+ if (from & SSL_CB_WRITE)
+ privateSocket->alertMessageSent(value);
+ else
+ privateSocket->alertMessageReceived(value);
+}
+
+int q_X509CallbackDirect(int ok, X509_STORE_CTX *ctx)
+{
+ // Passed to SSL_CTX_set_verify()
+ // https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_verify.html
+ // Returns 0 to abort verification, 1 to continue.
+
+ // This is a new, experimental verification callback, reporting
+ // errors immediately and returning 0 or 1 depending on an application
+ // either ignoring or not ignoring verification errors as they come.
+ if (!ctx) {
+ qCWarning(lcSsl, "Invalid store context (nullptr)");
+ return 0;
+ }
+
+ if (!ok) {
+ // "Whenever a X509_STORE_CTX object is created for the verification of the
+ // peer's certificate during a handshake, a pointer to the SSL object is
+ // stored into the X509_STORE_CTX object to identify the connection affected.
+ // To retrieve this pointer the X509_STORE_CTX_get_ex_data() function can be
+ // used with the correct index."
+ SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(ctx, q_SSL_get_ex_data_X509_STORE_CTX_idx()));
+ if (!ssl) {
+ qCWarning(lcSsl, "No external data (SSL) found in X509 store object");
+ return 0;
+ }
+
+ const auto offset = QSslSocketBackendPrivate::s_indexForSSLExtraData
+ + QSslSocketBackendPrivate::socketOffsetInExData;
+ auto privateSocket = static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, offset));
+ if (!privateSocket) {
+ qCWarning(lcSsl, "No external data (QSslSocketBackendPrivate) found in SSL object");
+ return 0;
+ }
+
+ return privateSocket->emitErrorFromCallback(ctx);
+ }
+ return 1;
+}
+
+} // extern "C"
+
Q_GLOBAL_STATIC(QRecursiveMutex, qt_opensslInitMutex)
bool QSslSocketPrivate::s_libraryLoaded = false;
@@ -250,11 +367,7 @@ QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(const SSL_CIPHER
QString protoString = descriptionList.at(1).toString();
ciph.d->protocolString = protoString;
ciph.d->protocol = QSsl::UnknownProtocol;
- if (protoString == QLatin1String("SSLv3"))
- ciph.d->protocol = QSsl::SslV3;
- else if (protoString == QLatin1String("SSLv2"))
- ciph.d->protocol = QSsl::SslV2;
- else if (protoString == QLatin1String("TLSv1"))
+ if (protoString == QLatin1String("TLSv1"))
ciph.d->protocol = QSsl::TlsV1_0;
else if (protoString == QLatin1String("TLSv1.1"))
ciph.d->protocol = QSsl::TlsV1_1;
@@ -409,12 +522,15 @@ int q_X509Callback(int ok, X509_STORE_CTX *ctx)
// Not found on store? Try SSL and its external data then. According to the OpenSSL's
// documentation:
//
- // "Whenever a X509_STORE_CTX object is created for the verification of the peers certificate
- // during a handshake, a pointer to the SSL object is stored into the X509_STORE_CTX object
- // to identify the connection affected. To retrieve this pointer the X509_STORE_CTX_get_ex_data()
- // function can be used with the correct index."
+ // "Whenever a X509_STORE_CTX object is created for the verification of the
+ // peer's certificate during a handshake, a pointer to the SSL object is
+ // stored into the X509_STORE_CTX object to identify the connection affected.
+ // To retrieve this pointer the X509_STORE_CTX_get_ex_data() function can be
+ // used with the correct index."
+ const auto offset = QSslSocketBackendPrivate::s_indexForSSLExtraData
+ + QSslSocketBackendPrivate::errorOffsetInExData;
if (SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(ctx, q_SSL_get_ex_data_X509_STORE_CTX_idx())))
- errors = ErrorListPtr(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData + 1));
+ errors = ErrorListPtr(q_SSL_get_ex_data(ssl, offset));
}
if (!errors) {
@@ -460,20 +576,23 @@ void q_setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers);
long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions)
{
long options;
- if (protocol == QSsl::TlsV1SslV3)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
- else if (protocol == QSsl::SecureProtocols)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
- else if (protocol == QSsl::TlsV1_0OrLater)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
- else if (protocol == QSsl::TlsV1_1OrLater)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1;
- else if (protocol == QSsl::TlsV1_2OrLater)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1;
- else if (protocol == QSsl::TlsV1_3OrLater)
- options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2;
- else
+ switch (protocol) {
+ case QSsl::SecureProtocols:
+ case QSsl::TlsV1_0OrLater:
+ options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
+ break;
+ case QSsl::TlsV1_1OrLater:
+ options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1;
+ break;
+ case QSsl::TlsV1_2OrLater:
+ options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1;
+ break;
+ case QSsl::TlsV1_3OrLater:
+ options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2;
+ break;
+ default:
options = SSL_OP_ALL;
+ }
// This option is disabled by default, so we need to be able to clear it
if (sslOptions & QSsl::SslOptionDisableEmptyFragments)
@@ -531,10 +650,7 @@ bool QSslSocketBackendPrivate::initSslContext()
return false;
}
- if (configuration.protocol != QSsl::SslV2 &&
- configuration.protocol != QSsl::SslV3 &&
- configuration.protocol != QSsl::UnknownProtocol &&
- mode == QSslSocket::SslClientMode) {
+ if (configuration.protocol != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
// Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
if (tlsHostName.isEmpty())
@@ -1200,18 +1316,32 @@ bool QSslSocketBackendPrivate::startHandshake()
if (inSetAndEmitError)
return false;
+ pendingFatalAlert = false;
+ errorsReportedFromCallback = false;
QVector<QSslErrorEntry> lastErrors;
- q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + 1, &lastErrors);
+ q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + errorOffsetInExData, &lastErrors);
+
+ // SSL_set_ex_data can fail, but see the callback's code - we handle this there.
+ q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + socketOffsetInExData, this);
+ q_SSL_set_info_callback(ssl, qt_AlertInfoCallback);
+
int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
- q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + 1, nullptr);
+ q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + errorOffsetInExData, nullptr);
+ // Note, unlike errors as external data on SSL object, we do not unset
+ // a callback/ex-data if alert notifications are enabled: an alert can
+ // arrive after the handshake, for example, this happens when the server
+ // does not find a ClientCert or does not like it.
- if (!lastErrors.isEmpty())
+ if (!lastErrors.isEmpty() || errorsReportedFromCallback)
storePeerCertificates();
- for (const auto &currentError : qAsConst(lastErrors)) {
- emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.code,
- configuration.peerCertificateChain.value(currentError.depth)));
- if (q->state() != QAbstractSocket::ConnectedState)
- break;
+
+ if (!errorsReportedFromCallback) {
+ for (const auto &currentError : qAsConst(lastErrors)) {
+ emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.code,
+ configuration.peerCertificateChain.value(currentError.depth)));
+ if (q->state() != QAbstractSocket::ConnectedState)
+ break;
+ }
}
errorList << lastErrors;
@@ -1235,6 +1365,10 @@ bool QSslSocketBackendPrivate::startHandshake()
{
const ScopedBool bg(inSetAndEmitError, true);
setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, errorString);
+ if (pendingFatalAlert) {
+ trySendFatalAlert();
+ pendingFatalAlert = false;
+ }
}
q->abort();
}
@@ -1704,6 +1838,88 @@ bool QSslSocketBackendPrivate::checkOcspStatus()
#endif // ocsp
+void QSslSocketBackendPrivate::alertMessageSent(int value)
+{
+ Q_Q(QSslSocket);
+
+ const auto level = tlsAlertLevel(value);
+ if (level == QAlertLevel::Fatal && !connectionEncrypted) {
+ // Note, this logic is handshake-time only:
+ pendingFatalAlert = true;
+ }
+
+ emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
+}
+
+void QSslSocketBackendPrivate::alertMessageReceived(int value)
+{
+ Q_Q(QSslSocket);
+
+ emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
+}
+
+int QSslSocketBackendPrivate::emitErrorFromCallback(X509_STORE_CTX *ctx)
+{
+ // Returns 0 to abort verification, 1 to continue despite error (as
+ // OpenSSL expects from the verification callback).
+ Q_Q(QSslSocket);
+
+ Q_ASSERT(ctx);
+
+ using ScopedBool = QScopedValueRollback<bool>;
+ // While we are not setting, we are emitting and in general -
+ // we want to prevent accidental recursive startHandshake()
+ // calls:
+ const ScopedBool bg(inSetAndEmitError, true);
+
+ X509 *x509 = q_X509_STORE_CTX_get_current_cert(ctx);
+ if (!x509) {
+ qCWarning(lcSsl, "Could not obtain the certificate (that failed to verify)");
+ return 0;
+ }
+ const QSslCertificate certificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
+
+ const auto errorAndDepth = QSslErrorEntry::fromStoreContext(ctx);
+ const QSslError tlsError = _q_OpenSSL_to_QSslError(errorAndDepth.code, certificate);
+
+ errorsReportedFromCallback = true;
+ handshakeInterrupted = true;
+ emit q->handshakeInterruptedOnError(tlsError);
+
+ // Conveniently so, we also can access 'lastErrors' external data set
+ // in startHandshake, we store it for the case an application later
+ // wants to check errors (ignored or not):
+ const auto offset = QSslSocketBackendPrivate::s_indexForSSLExtraData
+ + QSslSocketBackendPrivate::errorOffsetInExData;
+ if (auto errorList = static_cast<QVector<QSslErrorEntry>*>(q_SSL_get_ex_data(ssl, offset)))
+ errorList->append(errorAndDepth);
+
+ // An application is expected to ignore this error (by calling ignoreSslErrors)
+ // in its directly connected slot:
+ return !handshakeInterrupted;
+}
+
+void QSslSocketBackendPrivate::trySendFatalAlert()
+{
+ Q_ASSERT(pendingFatalAlert);
+
+ pendingFatalAlert = false;
+ QVarLengthArray<char, 4096> data;
+ int pendingBytes = 0;
+ while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
+ && plainSocket->openMode() != QIODevice::NotOpen) {
+ // Read encrypted data from the write BIO into a buffer.
+ data.resize(pendingBytes);
+ const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
+
+ // Write encrypted data from the buffer to the socket.
+ qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
+ if (actualWritten < 0)
+ return;
+ plainSocket->flush();
+ }
+}
+
void QSslSocketBackendPrivate::disconnectFromHost()
{
if (ssl) {
@@ -1747,10 +1963,6 @@ QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
int ver = q_SSL_version(ssl);
switch (ver) {
- case 0x2:
- return QSsl::SslV2;
- case 0x300:
- return QSsl::SslV3;
case 0x301:
return QSsl::TlsV1_0;
case 0x302:
diff --git a/src/network/ssl/qsslsocket_openssl_p.h b/src/network/ssl/qsslsocket_openssl_p.h
index 0370a7d2ac..06af9f5974 100644
--- a/src/network/ssl/qsslsocket_openssl_p.h
+++ b/src/network/ssl/qsslsocket_openssl_p.h
@@ -131,6 +131,10 @@ public:
SSL_SESSION *session;
QVector<QSslErrorEntry> errorList;
static int s_indexForSSLExtraData; // index used in SSL_get_ex_data to get the matching QSslSocketBackendPrivate
+ enum ExDataOffset {
+ errorOffsetInExData = 1,
+ socketOffsetInExData = 2
+ };
bool inSetAndEmitError = false;
@@ -157,6 +161,15 @@ public:
bool checkOcspStatus();
#endif
+ void alertMessageSent(int encoded);
+ void alertMessageReceived(int encoded);
+
+ int emitErrorFromCallback(X509_STORE_CTX *ctx);
+ void trySendFatalAlert();
+
+ bool pendingFatalAlert = false;
+ bool errorsReportedFromCallback = false;
+
// This decription will go to setErrorAndEmit(SslHandshakeError, ocspErrorDescription)
QString ocspErrorDescription;
// These will go to sslErrors()
diff --git a/src/network/ssl/qsslsocket_openssl_symbols.cpp b/src/network/ssl/qsslsocket_openssl_symbols.cpp
index 3504924888..5b0a70d495 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols.cpp
+++ b/src/network/ssl/qsslsocket_openssl_symbols.cpp
@@ -156,6 +156,10 @@ DEFINEFUNC(void, OPENSSL_sk_free, OPENSSL_STACK *a, a, return, DUMMYARG)
DEFINEFUNC2(void *, OPENSSL_sk_value, OPENSSL_STACK *a, a, int b, b, return nullptr, return)
DEFINEFUNC(int, SSL_session_reused, SSL *a, a, return 0, return)
DEFINEFUNC2(unsigned long, SSL_CTX_set_options, SSL_CTX *ctx, ctx, unsigned long op, op, return 0, return)
+using info_callback = void (*) (const SSL *ssl, int type, int val);
+DEFINEFUNC2(void, SSL_set_info_callback, SSL *ssl, ssl, info_callback cb, cb, return, return)
+DEFINEFUNC(const char *, SSL_alert_type_string, int value, value, return nullptr, return)
+DEFINEFUNC(const char *, SSL_alert_desc_string_long, int value, value, return nullptr, return)
#ifdef TLS1_3_VERSION
DEFINEFUNC2(int, SSL_CTX_set_ciphersuites, SSL_CTX *ctx, ctx, const char *str, str, return 0, return)
DEFINEFUNC2(void, SSL_set_psk_use_session_callback, SSL *ssl, ssl, q_SSL_psk_use_session_cb_func_t callback, callback, return, DUMMYARG)
@@ -839,7 +843,9 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(OPENSSL_sk_value)
RESOLVEFUNC(DH_get0_pqg)
RESOLVEFUNC(SSL_CTX_set_options)
-
+ RESOLVEFUNC(SSL_set_info_callback)
+ RESOLVEFUNC(SSL_alert_type_string)
+ RESOLVEFUNC(SSL_alert_desc_string_long)
#ifdef TLS1_3_VERSION
RESOLVEFUNC(SSL_CTX_set_ciphersuites)
RESOLVEFUNC(SSL_set_psk_use_session_callback)
diff --git a/src/network/ssl/qsslsocket_openssl_symbols_p.h b/src/network/ssl/qsslsocket_openssl_symbols_p.h
index baf1a43113..ac6aa1760f 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols_p.h
+++ b/src/network/ssl/qsslsocket_openssl_symbols_p.h
@@ -719,6 +719,10 @@ int q_OCSP_id_cmp(OCSP_CERTID *a, OCSP_CERTID *b);
void *q_CRYPTO_malloc(size_t num, const char *file, int line);
#define q_OPENSSL_malloc(num) q_CRYPTO_malloc(num, "", 0)
+void q_SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val));
+const char *q_SSL_alert_type_string(int value);
+const char *q_SSL_alert_desc_string_long(int value);
+
QT_END_NAMESPACE
#endif
diff --git a/src/network/ssl/qsslsocket_p.h b/src/network/ssl/qsslsocket_p.h
index 1abd18bb32..4b020b6a73 100644
--- a/src/network/ssl/qsslsocket_p.h
+++ b/src/network/ssl/qsslsocket_p.h
@@ -208,6 +208,7 @@ protected:
bool paused;
bool flushTriggered;
QVector<QOcspResponse> ocspResponses;
+ bool handshakeInterrupted = false;
};
#if QT_CONFIG(securetransport) || QT_CONFIG(schannel)
diff --git a/src/network/ssl/qsslsocket_schannel.cpp b/src/network/ssl/qsslsocket_schannel.cpp
index f9586b7862..ba15a0a65e 100644
--- a/src/network/ssl/qsslsocket_schannel.cpp
+++ b/src/network/ssl/qsslsocket_schannel.cpp
@@ -226,12 +226,6 @@ DWORD toSchannelProtocol(QSsl::SslProtocol protocol)
protocols = SP_PROT_TLS1_0 | SP_PROT_TLS1_1 | SP_PROT_TLS1_2;
// @future Add TLS 1.3 when supported by Windows!
break;
- case QSsl::SslV2:
- case QSsl::SslV3:
- return DWORD(-1); // Not supported
- case QSsl::TlsV1SslV3:
- protocols = SP_PROT_TLS1_0;
- break;
case QSsl::TlsV1_0:
protocols = SP_PROT_TLS1_0;
break;
diff --git a/src/network/ssl/qsslsocket_winrt.cpp b/src/network/ssl/qsslsocket_winrt.cpp
index f3ca3dc257..5f5201fc82 100644
--- a/src/network/ssl/qsslsocket_winrt.cpp
+++ b/src/network/ssl/qsslsocket_winrt.cpp
@@ -230,13 +230,7 @@ void QSslSocketBackendPrivate::startClientEncryption()
QSsl::SslProtocol protocol = q->protocol();
switch (q->protocol()) {
- case QSsl::SslV2:
- case QSsl::SslV3:
- setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
- QStringLiteral("unsupported protocol"));
- return;
case QSsl::AnyProtocol:
- case QSsl::TlsV1SslV3:
protectionLevel = SocketProtectionLevel_Tls10;
break;
case QSsl::TlsV1_0:
@@ -270,7 +264,7 @@ void QSslSocketBackendPrivate::startClientEncryption()
}
// Sync custom certificates
- const QSet<QSslCertificate> caCertificates = configuration.caCertificates.toSet();
+ const QSet<QSslCertificate> caCertificates(configuration.caCertificates.constBegin(), configuration.caCertificates.constEnd());
const QSet<QSslCertificate> newCertificates = caCertificates - previousCaCertificates;
const QSet<QSslCertificate> oldCertificates = previousCaCertificates - caCertificates;
g->syncCaCertificates(newCertificates, oldCertificates);
@@ -393,7 +387,7 @@ void QSslSocketBackendPrivate::continueHandshake()
hr = control2->get_IgnorableServerCertificateErrors(&ignoreList);
Q_ASSERT_SUCCEEDED(hr);
- QSet<QSslError> ignoreErrors = ignoreErrorsList.toSet();
+ QSet<QSslError> ignoreErrors(ignoreErrorsList.constBegin(), ignoreErrorsList.constEnd());
for (int i = ChainValidationResult_Untrusted; i < ChainValidationResult_OtherErrors + 1; ++i) {
// Populate the native ignore list - break to add, continue to skip
switch (i) {
@@ -596,7 +590,7 @@ HRESULT QSslSocketBackendPrivate::onSslUpgrade(IAsyncAction *action, AsyncStatus
}
}
- sslErrors = errors.toList();
+ sslErrors = QList<QSslError>(errors.constBegin(), errors.constEnd());
// Peer validation
if (!configuration.peerCertificate.isNull()) {
diff --git a/src/opengl/doc/snippets/code/src_opengl_qgl.cpp b/src/opengl/doc/snippets/code/src_opengl_qgl.cpp
deleted file mode 100644
index a73ee2cdc5..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qgl.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
-QGLFormat fmt;
-fmt.setAlpha(true);
-fmt.setStereo(true);
-QGLFormat::setDefaultFormat(fmt);
-//! [0]
-
-
-//! [1]
-QGLFormat fmt;
-fmt.setDoubleBuffer(false); // single buffer
-fmt.setDirectRendering(false); // software rendering
-MyGLWidget* myWidget = new MyGLWidget(fmt, ...);
-//! [1]
-
-
-//! [2]
-QGLFormat fmt;
-fmt.setOverlay(true);
-fmt.setStereo(true);
-MyGLWidget* myWidget = new MyGLWidget(fmt, ...);
-if (!myWidget->format().stereo()) {
- // ok, goggles off
- if (!myWidget->format().hasOverlay()) {
- qFatal("Cool hardware required");
- }
-}
-//! [2]
-
-
-//! [3]
-// The rendering in MyGLWidget depends on using
-// stencil buffer and alpha channel
-MyGLWidget::MyGLWidget(QWidget* parent)
- : QGLWidget(QGLFormat(QGL::StencilBuffer | QGL::AlphaChannel), parent)
-{
- if (!format().stencil())
- qWarning("Could not get stencil buffer; results will be suboptimal");
- if (!format().alpha())
- qWarning("Could not get alpha channel; results will be suboptimal");
- ...
-}
-//! [3]
-
-
-//! [4]
-QApplication a(argc, argv);
-QGLFormat f;
-f.setDoubleBuffer(false);
-QGLFormat::setDefaultFormat(f);
-//! [4]
-
-
-//! [5]
-QGLFormat f = QGLFormat::defaultOverlayFormat();
-f.setDoubleBuffer(true);
-QGLFormat::setDefaultOverlayFormat(f);
-//! [5]
-
-
-//! [6]
-// ...continued from above
-MyGLWidget* myWidget = new MyGLWidget(QGLFormat(QGL::HasOverlay), ...);
-if (myWidget->format().hasOverlay()) {
- // Yes, we got an overlay, let's check _its_ format:
- QGLContext* olContext = myWidget->overlayContext();
- if (olContext->format().doubleBuffer())
- ; // yes, we got a double buffered overlay
- else
- ; // no, only single buffered overlays are available
-}
-//! [6]
-
-
-//! [7]
-QGLContext *cx;
-// ...
-QGLFormat f;
-f.setStereo(true);
-cx->setFormat(f);
-if (!cx->create())
- exit(); // no OpenGL support, or cannot render on the specified paintdevice
-if (!cx->format().stereo())
- exit(); // could not create stereo context
-//! [7]
-
-
-//! [8]
-class MyGLDrawer : public QGLWidget
-{
- Q_OBJECT // must include this if you use Qt signals/slots
-
-public:
- MyGLDrawer(QWidget *parent)
- : QGLWidget(parent) {}
-
-protected:
-
- void initializeGL() override
- {
- // Set up the rendering context, define display lists etc.:
- ...
- glClearColor(0.0, 0.0, 0.0, 0.0);
- glEnable(GL_DEPTH_TEST);
- ...
- }
-
- void resizeGL(int w, int h) override
- {
- // setup viewport, projection etc.:
- glViewport(0, 0, (GLint)w, (GLint)h);
- ...
- glFrustum(...);
- ...
- }
-
- void paintGL() override
- {
- // draw the scene:
- ...
- glRotatef(...);
- glMaterialfv(...);
- glBegin(GL_QUADS);
- glVertex3f(...);
- glVertex3f(...);
- ...
- glEnd();
- ...
- }
-
-};
-//! [8]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qglbuffer.cpp b/src/opengl/doc/snippets/code/src_opengl_qglbuffer.cpp
deleted file mode 100644
index 11ef88ab37..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qglbuffer.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
- QGLBuffer buffer1(QGLBuffer::IndexBuffer);
- buffer1.create();
-
- QGLBuffer buffer2 = buffer1;
-//! [0]
-
-//! [1]
- QGLBuffer::release(QGLBuffer::VertexBuffer);
-//! [1]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qglcolormap.cpp b/src/opengl/doc/snippets/code/src_opengl_qglcolormap.cpp
deleted file mode 100644
index 12a089944f..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qglcolormap.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
-#include <QApplication>
-#include <QGLColormap>
-
-int main()
-{
- QApplication app(argc, argv);
-
- MySuperGLWidget widget; // a QGLWidget in color-index mode
- QGLColormap colormap;
-
- // This will fill the colormap with colors ranging from
- // black to white.
- for (int i = 0; i < colormap.size(); i++)
- colormap.setEntry(i, qRgb(i, i, i));
-
- widget.setColormap(colormap);
- widget.show();
- return app.exec();
-}
-//! [0]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qglfunctions.cpp b/src/opengl/doc/snippets/code/src_opengl_qglfunctions.cpp
deleted file mode 100644
index c848ae7ede..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qglfunctions.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
- class MyGLWidget : public QGLWidget, protected QGLFunctions
- {
- Q_OBJECT
- public:
- MyGLWidget(QWidget *parent = 0) : QGLWidget(parent) {}
-
- protected:
- void initializeGL();
- void paintGL();
- };
-
- void MyGLWidget::initializeGL()
- {
- initializeGLFunctions();
- }
-//! [0]
-
-//! [1]
- void MyGLWidget::paintGL()
- {
- glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, textureId);
- ...
- }
-//! [1]
-
-//! [2]
- QGLFunctions glFuncs(QGLContext::currentContext());
- glFuncs.glActiveTexture(GL_TEXTURE1);
-//! [2]
-
-//! [3]
- QGLFunctions funcs(QGLContext::currentContext());
- bool npot = funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures);
-//! [3]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qglpixelbuffer.cpp b/src/opengl/doc/snippets/code/src_opengl_qglpixelbuffer.cpp
deleted file mode 100644
index f6fbe6ddb4..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qglpixelbuffer.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
-QGLPixelBuffer pbuffer(...);
-...
-pbuffer.makeCurrent();
-GLuint dynamicTexture = pbuffer.generateDynamicTexture();
-pbuffer.bindToDynamicTexture(dynamicTexture);
-...
-pbuffer.releaseFromDynamicTexture();
-//! [0]
-
-
-//! [1]
-QGLPixelBuffer pbuffer(...);
-...
-pbuffer.makeCurrent();
-GLuint dynamicTexture = pbuffer.generateDynamicTexture();
-...
-pbuffer.updateDynamicTexture(dynamicTexture);
-//! [1]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qglshaderprogram.cpp b/src/opengl/doc/snippets/code/src_opengl_qglshaderprogram.cpp
deleted file mode 100644
index 04492499e8..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qglshaderprogram.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
-QGLShader shader(QGLShader::Vertex);
-shader.compileSourceCode(code);
-
-QGLShaderProgram program(context);
-program.addShader(shader);
-program.link();
-
-program.bind();
-//! [0]
-
-//! [1]
-program.addShaderFromSourceCode(QGLShader::Vertex,
- "attribute highp vec4 vertex;\n"
- "uniform highp mat4 matrix;\n"
- "void main(void)\n"
- "{\n"
- " gl_Position = matrix * vertex;\n"
- "}");
-program.addShaderFromSourceCode(QGLShader::Fragment,
- "uniform mediump vec4 color;\n"
- "void main(void)\n"
- "{\n"
- " gl_FragColor = color;\n"
- "}");
-program.link();
-program.bind();
-
-int vertexLocation = program.attributeLocation("vertex");
-int matrixLocation = program.uniformLocation("matrix");
-int colorLocation = program.uniformLocation("color");
-//! [1]
-
-//! [2]
-static GLfloat const triangleVertices[] = {
- 60.0f, 10.0f, 0.0f,
- 110.0f, 110.0f, 0.0f,
- 10.0f, 110.0f, 0.0f
-};
-
-QColor color(0, 255, 0, 255);
-
-QMatrix4x4 pmvMatrix;
-pmvMatrix.ortho(rect());
-
-program.enableAttributeArray(vertexLocation);
-program.setAttributeArray(vertexLocation, triangleVertices, 3);
-program.setUniformValue(matrixLocation, pmvMatrix);
-program.setUniformValue(colorLocation, color);
-
-glDrawArrays(GL_TRIANGLES, 0, 3);
-
-program.disableAttributeArray(vertexLocation);
-//! [2]
diff --git a/src/opengl/doc/snippets/code/src_opengl_qgraphicsshadereffect.cpp b/src/opengl/doc/snippets/code/src_opengl_qgraphicsshadereffect.cpp
deleted file mode 100644
index 461e96e094..0000000000
--- a/src/opengl/doc/snippets/code/src_opengl_qgraphicsshadereffect.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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$
-**
-****************************************************************************/
-
-//! [0]
- static char const colorizeShaderCode[] =
- "uniform lowp vec4 effectColor;\n"
- "lowp vec4 customShader(lowp sampler2D imageTexture, highp vec2 textureCoords) {\n"
- " vec4 src = texture2D(imageTexture, textureCoords);\n"
- " float gray = dot(src.rgb, vec3(0.212671, 0.715160, 0.072169));\n"
- " vec4 colorize = 1.0-((1.0-gray)*(1.0-effectColor));\n"
- " return vec4(colorize.rgb, src.a);\n"
- "}";
-//! [0]
-
-//! [1]
- class ColorizeEffect : public QGraphicsShaderEffect
- {
- Q_OBJECT
- public:
- ColorizeEffect(QObject *parent = 0)
- : QGraphicsShaderEffect(parent), color(Qt::black)
- {
- setPixelShaderFragment(colorizeShaderCode);
- }
-
- QColor effectColor() const { return color; }
- void setEffectColor(const QColor& c)
- {
- color = c;
- setUniformsDirty();
- }
-
- protected:
- void setUniforms(QGLShaderProgram *program)
- {
- program->setUniformValue("effectColor", color);
- }
-
- private:
- QColor color;
- };
-//! [1]
-
-//! [2]
- lowp vec4 customShader(lowp sampler2D imageTexture, highp vec2 textureCoords) {
- return texture2D(imageTexture, textureCoords);
- }
-//! [2]
diff --git a/src/opengl/doc/src/qtopengl-examples.qdoc b/src/opengl/doc/src/qtopengl-examples.qdoc
index de80c92883..8770d6247e 100644
--- a/src/opengl/doc/src/qtopengl-examples.qdoc
+++ b/src/opengl/doc/src/qtopengl-examples.qdoc
@@ -33,12 +33,11 @@
\image opengl-examples.png
- These examples describe how to use the \l {Qt OpenGL} module. For new code,
- please use the OpenGL classes in the \l {Qt GUI} module.
+ These examples describe how to use the \l {Qt OpenGL} module.
- Qt provides support for integration with OpenGL implementations on all
- platforms, giving developers the opportunity to display hardware accelerated
- 3D graphics alongside a more conventional user interface.
+ Qt provides support for integration with OpenGL implementations, giving
+ developers the opportunity to display hardware accelerated 3D graphics
+ alongside a more conventional user interface.
These examples demonstrate the basic techniques used to take advantage of
OpenGL in Qt applications.
diff --git a/src/opengl/doc/src/qtopengl-module.qdoc b/src/opengl/doc/src/qtopengl-module.qdoc
index 336d37c73f..24df4aec76 100644
--- a/src/opengl/doc/src/qtopengl-module.qdoc
+++ b/src/opengl/doc/src/qtopengl-module.qdoc
@@ -34,8 +34,7 @@
\brief The Qt OpenGL module offers classes that make it easy to
use OpenGL in Qt applications.
- \warning This module should not be used anymore for new code. Please
- use the corresponding OpenGL classes in \l{Qt GUI}.
+ \warning This module should not be used anymore for new code.
OpenGL is a standard API for rendering 3D graphics. OpenGL only
deals with 3D rendering and provides little or no support for GUI
@@ -48,9 +47,6 @@
the United States and other countries.
The Qt OpenGL module makes it easy to use OpenGL in Qt applications.
- It provides an OpenGL widget class that can be used just like any
- other Qt widget, except that it opens an OpenGL display buffer where
- you can use the OpenGL API to render the contents.
To include the definitions of the module's classes, use the
following directive:
@@ -63,11 +59,4 @@
\snippet code/doc_src_qtopengl.pro 1
\endif
-
- The Qt OpenGL module is implemented as a platform-independent Qt/C++
- wrapper around the platform-dependent GLX (version 1.3 or later),
- WGL, or AGL C APIs. Although the basic functionality provided is very
- similar to Mark Kilgard's GLUT library, applications using the Qt
- OpenGL module can take advantage of the whole Qt API for
- non-OpenGL-specific GUI functionality.
*/
diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp
deleted file mode 100644
index 979ea19fee..0000000000
--- a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qgl2pexvertexarray_p.h"
-
-#include <private/qbezier_p.h>
-
-QT_BEGIN_NAMESPACE
-
-void QGL2PEXVertexArray::clear()
-{
- vertexArray.reset();
- vertexArrayStops.reset();
- boundingRectDirty = true;
-}
-
-
-QGLRect QGL2PEXVertexArray::boundingRect() const
-{
- if (boundingRectDirty)
- return QGLRect(0.0, 0.0, 0.0, 0.0);
- else
- return QGLRect(minX, minY, maxX, maxY);
-}
-
-void QGL2PEXVertexArray::addClosingLine(int index)
-{
- QPointF point(vertexArray.at(index));
- if (point != QPointF(vertexArray.last()))
- vertexArray.add(point);
-}
-
-void QGL2PEXVertexArray::addCentroid(const QVectorPath &path, int subPathIndex)
-{
- const QPointF *const points = reinterpret_cast<const QPointF *>(path.points());
- const QPainterPath::ElementType *const elements = path.elements();
-
- QPointF sum = points[subPathIndex];
- int count = 1;
-
- for (int i = subPathIndex + 1; i < path.elementCount() && (!elements || elements[i] != QPainterPath::MoveToElement); ++i) {
- sum += points[i];
- ++count;
- }
-
- const QPointF centroid = sum / qreal(count);
- vertexArray.add(centroid);
-}
-
-void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale, bool outline)
-{
- const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
- const QPainterPath::ElementType* const elements = path.elements();
-
- if (boundingRectDirty) {
- minX = maxX = points[0].x();
- minY = maxY = points[0].y();
- boundingRectDirty = false;
- }
-
- if (!outline && !path.isConvex())
- addCentroid(path, 0);
-
- int lastMoveTo = vertexArray.size();
- vertexArray.add(points[0]); // The first element is always a moveTo
-
- do {
- if (!elements) {
-// qDebug("QVectorPath has no elements");
- // If the path has a null elements pointer, the elements implicitly
- // start with a moveTo (already added) and continue with lineTos:
- for (int i=1; i<path.elementCount(); ++i)
- lineToArray(points[i].x(), points[i].y());
-
- break;
- }
-// qDebug("QVectorPath has element types");
-
- for (int i=1; i<path.elementCount(); ++i) {
- switch (elements[i]) {
- case QPainterPath::MoveToElement:
- if (!outline)
- addClosingLine(lastMoveTo);
-// qDebug("element[%d] is a MoveToElement", i);
- vertexArrayStops.add(vertexArray.size());
- if (!outline) {
- if (!path.isConvex()) addCentroid(path, i);
- lastMoveTo = vertexArray.size();
- }
- lineToArray(points[i].x(), points[i].y()); // Add the moveTo as a new vertex
- break;
- case QPainterPath::LineToElement:
-// qDebug("element[%d] is a LineToElement", i);
- lineToArray(points[i].x(), points[i].y());
- break;
- case QPainterPath::CurveToElement: {
- QBezier b = QBezier::fromPoints(*(((const QPointF *) points) + i - 1),
- points[i],
- points[i+1],
- points[i+2]);
- QRectF bounds = b.bounds();
- // threshold based on same algorithm as in qtriangulatingstroker.cpp
- int threshold = qMin<float>(64, qMax(bounds.width(), bounds.height()) * 3.14f / (curveInverseScale * 6));
- if (threshold < 3) threshold = 3;
- qreal one_over_threshold_minus_1 = qreal(1) / (threshold - 1);
- for (int t=0; t<threshold; ++t) {
- QPointF pt = b.pointAt(t * one_over_threshold_minus_1);
- lineToArray(pt.x(), pt.y());
- }
- i += 2;
- break; }
- default:
- break;
- }
- }
- } while (0);
-
- if (!outline)
- addClosingLine(lastMoveTo);
- vertexArrayStops.add(vertexArray.size());
-}
-
-void QGL2PEXVertexArray::lineToArray(const GLfloat x, const GLfloat y)
-{
- vertexArray.add(QGLPoint(x, y));
-
- if (x > maxX)
- maxX = x;
- else if (x < minX)
- minX = x;
- if (y > maxY)
- maxY = y;
- else if (y < minY)
- minY = y;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h
deleted file mode 100644
index 5c95268790..0000000000
--- a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QGL2PEXVERTEXARRAY_P_H
-#define QGL2PEXVERTEXARRAY_P_H
-
-#include <QRectF>
-
-#include <private/qdatabuffer_p.h>
-#include <private/qvectorpath_p.h>
-#include <private/qgl_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGLPoint
-{
-public:
- QGLPoint(GLfloat new_x, GLfloat new_y) :
- x(new_x), y(new_y) {};
-
- QGLPoint(const QPointF &p) :
- x(p.x()), y(p.y()) {};
-
- QGLPoint(const QPointF* p) :
- x(p->x()), y(p->y()) {};
-
- GLfloat x;
- GLfloat y;
-
- operator QPointF() {return QPointF(x,y);}
- operator QPointF() const {return QPointF(x,y);}
-};
-
-struct QGLRect
-{
- QGLRect(const QRectF &r)
- : left(r.left()), top(r.top()), right(r.right()), bottom(r.bottom()) {}
-
- QGLRect(GLfloat l, GLfloat t, GLfloat r, GLfloat b)
- : left(l), top(t), right(r), bottom(b) {}
-
- GLfloat left;
- GLfloat top;
- GLfloat right;
- GLfloat bottom;
-
- operator QRectF() const {return QRectF(left, top, right-left, bottom-top);}
-};
-
-class QGL2PEXVertexArray
-{
-public:
- QGL2PEXVertexArray() :
- vertexArray(0), vertexArrayStops(0),
- maxX(-2e10), maxY(-2e10), minX(2e10), minY(2e10),
- boundingRectDirty(true)
- { }
-
- inline void addRect(const QRectF &rect)
- {
- qreal top = rect.top();
- qreal left = rect.left();
- qreal bottom = rect.bottom();
- qreal right = rect.right();
-
- vertexArray << QGLPoint(left, top)
- << QGLPoint(right, top)
- << QGLPoint(right, bottom)
- << QGLPoint(right, bottom)
- << QGLPoint(left, bottom)
- << QGLPoint(left, top);
- }
-
- inline void addQuad(const QRectF &rect)
- {
- qreal top = rect.top();
- qreal left = rect.left();
- qreal bottom = rect.bottom();
- qreal right = rect.right();
-
- vertexArray << QGLPoint(left, top)
- << QGLPoint(right, top)
- << QGLPoint(left, bottom)
- << QGLPoint(right, bottom);
-
- }
-
- inline void addVertex(const GLfloat x, const GLfloat y)
- {
- vertexArray.add(QGLPoint(x, y));
- }
-
- void addPath(const QVectorPath &path, GLfloat curveInverseScale, bool outline = true);
- void clear();
-
- QGLPoint* data() {return vertexArray.data();}
- int *stops() const { return vertexArrayStops.data(); }
- int stopCount() const { return vertexArrayStops.size(); }
- QGLRect boundingRect() const;
-
- int vertexCount() const { return vertexArray.size(); }
-
- void lineToArray(const GLfloat x, const GLfloat y);
-
-private:
- QDataBuffer<QGLPoint> vertexArray;
- QDataBuffer<int> vertexArrayStops;
-
- GLfloat maxX;
- GLfloat maxY;
- GLfloat minX;
- GLfloat minY;
- bool boundingRectDirty;
- void addClosingLine(int index);
- void addCentroid(const QVectorPath &path, int subPathIndex);
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp b/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp
deleted file mode 100644
index 7d6d4595ba..0000000000
--- a/src/opengl/gl2paintengineex/qglcustomshaderstage.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglcustomshaderstage_p.h"
-#include "qglengineshadermanager_p.h"
-#include "qpaintengineex_opengl2_p.h"
-#include <private/qpainter_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGLCustomShaderStagePrivate
-{
-public:
- QGLCustomShaderStagePrivate() :
- m_manager(0) {}
-
- QPointer<QGLEngineShaderManager> m_manager;
- QByteArray m_source;
-};
-
-
-
-
-QGLCustomShaderStage::QGLCustomShaderStage()
- : d_ptr(new QGLCustomShaderStagePrivate)
-{
-}
-
-QGLCustomShaderStage::~QGLCustomShaderStage()
-{
- Q_D(QGLCustomShaderStage);
- if (d->m_manager) {
- d->m_manager->removeCustomStage();
- d->m_manager->sharedShaders->cleanupCustomStage(this);
- }
- delete d_ptr;
-}
-
-void QGLCustomShaderStage::setUniformsDirty()
-{
- Q_D(QGLCustomShaderStage);
- if (d->m_manager)
- d->m_manager->setDirty(); // ### Probably a bit overkill!
-}
-
-bool QGLCustomShaderStage::setOnPainter(QPainter* p)
-{
- Q_D(QGLCustomShaderStage);
- if (p->paintEngine()->type() != QPaintEngine::OpenGL2) {
- qWarning("QGLCustomShaderStage::setOnPainter() - paint engine not OpenGL2");
- return false;
- }
- if (d->m_manager)
- qWarning("Custom shader is already set on a painter");
-
- QGL2PaintEngineEx *engine = static_cast<QGL2PaintEngineEx*>(p->paintEngine());
- d->m_manager = QGL2PaintEngineExPrivate::shaderManagerForEngine(engine);
- Q_ASSERT(d->m_manager);
-
- d->m_manager->setCustomStage(this);
- return true;
-}
-
-void QGLCustomShaderStage::removeFromPainter(QPainter* p)
-{
- Q_D(QGLCustomShaderStage);
- if (p->paintEngine()->type() != QPaintEngine::OpenGL2)
- return;
-
- QGL2PaintEngineEx *engine = static_cast<QGL2PaintEngineEx*>(p->paintEngine());
- d->m_manager = QGL2PaintEngineExPrivate::shaderManagerForEngine(engine);
- Q_ASSERT(d->m_manager);
-
- // Just set the stage to null, don't call removeCustomStage().
- // This should leave the program in a compiled/linked state
- // if the next custom shader stage is this one again.
- d->m_manager->setCustomStage(0);
- d->m_manager = 0;
-}
-
-QByteArray QGLCustomShaderStage::source() const
-{
- Q_D(const QGLCustomShaderStage);
- return d->m_source;
-}
-
-// Called by the shader manager if another custom shader is attached or
-// the manager is deleted
-void QGLCustomShaderStage::setInactive()
-{
- Q_D(QGLCustomShaderStage);
- d->m_manager = 0;
-}
-
-void QGLCustomShaderStage::setSource(const QByteArray& s)
-{
- Q_D(QGLCustomShaderStage);
- d->m_source = s;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp
deleted file mode 100644
index 47e8531959..0000000000
--- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp
+++ /dev/null
@@ -1,875 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglengineshadermanager_p.h"
-#include "qglengineshadersource_p.h"
-#include "qpaintengineex_opengl2_p.h"
-#include "qglshadercache_p.h"
-
-#include <QtGui/private/qopenglcontext_p.h>
-
-#if defined(QT_DEBUG)
-#include <QMetaEnum>
-#endif
-
-#include <algorithm>
-
-// #define QT_GL_SHARED_SHADER_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-class QGLEngineSharedShadersResource : public QOpenGLSharedResource
-{
-public:
- QGLEngineSharedShadersResource(QOpenGLContext *ctx)
- : QOpenGLSharedResource(ctx->shareGroup())
- , m_shaders(new QGLEngineSharedShaders(QGLContext::fromOpenGLContext(ctx)))
- {
- }
-
- ~QGLEngineSharedShadersResource()
- {
- delete m_shaders;
- }
-
- void invalidateResource() override
- {
- delete m_shaders;
- m_shaders = 0;
- }
-
- void freeResource(QOpenGLContext *) override
- {
- }
-
- QGLEngineSharedShaders *shaders() const { return m_shaders; }
-
-private:
- QGLEngineSharedShaders *m_shaders;
-};
-
-class QGLShaderStorage
-{
-public:
- QGLEngineSharedShaders *shadersForThread(const QGLContext *context) {
- QOpenGLMultiGroupSharedResource *&shaders = m_storage.localData();
- if (!shaders)
- shaders = new QOpenGLMultiGroupSharedResource;
- QGLEngineSharedShadersResource *resource =
- shaders->value<QGLEngineSharedShadersResource>(context->contextHandle());
- return resource ? resource->shaders() : 0;
- }
-
-private:
- QThreadStorage<QOpenGLMultiGroupSharedResource *> m_storage;
-};
-
-Q_GLOBAL_STATIC(QGLShaderStorage, qt_shader_storage);
-
-QGLEngineSharedShaders *QGLEngineSharedShaders::shadersForContext(const QGLContext *context)
-{
- return qt_shader_storage()->shadersForThread(context);
-}
-
-const char* QGLEngineSharedShaders::qShaderSnippets[] = {
- 0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0
-};
-
-QGLEngineSharedShaders::QGLEngineSharedShaders(const QGLContext* context)
- : blitShaderProg(0)
- , simpleShaderProg(0)
-{
-
-/*
- Rather than having the shader source array statically initialised, it is initialised
- here instead. This is to allow new shader names to be inserted or existing names moved
- around without having to change the order of the glsl strings. It is hoped this will
- make future hard-to-find runtime bugs more obvious and generally give more solid code.
-*/
- static bool snippetsPopulated = false;
- if (!snippetsPopulated) {
-
- const char** code = qShaderSnippets; // shortcut
-
- code[MainVertexShader] = qglslMainVertexShader;
- code[MainWithTexCoordsVertexShader] = qglslMainWithTexCoordsVertexShader;
- code[MainWithTexCoordsAndOpacityVertexShader] = qglslMainWithTexCoordsAndOpacityVertexShader;
-
- code[UntransformedPositionVertexShader] = qglslUntransformedPositionVertexShader;
- code[PositionOnlyVertexShader] = qglslPositionOnlyVertexShader;
- code[ComplexGeometryPositionOnlyVertexShader] = qglslComplexGeometryPositionOnlyVertexShader;
- code[PositionWithPatternBrushVertexShader] = qglslPositionWithPatternBrushVertexShader;
- code[PositionWithLinearGradientBrushVertexShader] = qglslPositionWithLinearGradientBrushVertexShader;
- code[PositionWithConicalGradientBrushVertexShader] = qglslPositionWithConicalGradientBrushVertexShader;
- code[PositionWithRadialGradientBrushVertexShader] = qglslPositionWithRadialGradientBrushVertexShader;
- code[PositionWithTextureBrushVertexShader] = qglslPositionWithTextureBrushVertexShader;
- code[AffinePositionWithPatternBrushVertexShader] = qglslAffinePositionWithPatternBrushVertexShader;
- code[AffinePositionWithLinearGradientBrushVertexShader] = qglslAffinePositionWithLinearGradientBrushVertexShader;
- code[AffinePositionWithConicalGradientBrushVertexShader] = qglslAffinePositionWithConicalGradientBrushVertexShader;
- code[AffinePositionWithRadialGradientBrushVertexShader] = qglslAffinePositionWithRadialGradientBrushVertexShader;
- code[AffinePositionWithTextureBrushVertexShader] = qglslAffinePositionWithTextureBrushVertexShader;
-
- code[MainFragmentShader_CMO] = qglslMainFragmentShader_CMO;
- code[MainFragmentShader_CM] = qglslMainFragmentShader_CM;
- code[MainFragmentShader_MO] = qglslMainFragmentShader_MO;
- code[MainFragmentShader_M] = qglslMainFragmentShader_M;
- code[MainFragmentShader_CO] = qglslMainFragmentShader_CO;
- code[MainFragmentShader_C] = qglslMainFragmentShader_C;
- code[MainFragmentShader_O] = qglslMainFragmentShader_O;
- code[MainFragmentShader] = qglslMainFragmentShader;
- code[MainFragmentShader_ImageArrays] = qglslMainFragmentShader_ImageArrays;
-
- code[ImageSrcFragmentShader] = qglslImageSrcFragmentShader;
- code[ImageSrcWithPatternFragmentShader] = qglslImageSrcWithPatternFragmentShader;
- code[NonPremultipliedImageSrcFragmentShader] = qglslNonPremultipliedImageSrcFragmentShader;
- code[CustomImageSrcFragmentShader] = qglslCustomSrcFragmentShader; // Calls "customShader", which must be appended
- code[SolidBrushSrcFragmentShader] = qglslSolidBrushSrcFragmentShader;
- if (!context->contextHandle()->isOpenGLES())
- code[TextureBrushSrcFragmentShader] = qglslTextureBrushSrcFragmentShader_desktop;
- else
- code[TextureBrushSrcFragmentShader] = qglslTextureBrushSrcFragmentShader_ES;
- code[TextureBrushSrcWithPatternFragmentShader] = qglslTextureBrushSrcWithPatternFragmentShader;
- code[PatternBrushSrcFragmentShader] = qglslPatternBrushSrcFragmentShader;
- code[LinearGradientBrushSrcFragmentShader] = qglslLinearGradientBrushSrcFragmentShader;
- code[RadialGradientBrushSrcFragmentShader] = qglslRadialGradientBrushSrcFragmentShader;
- code[ConicalGradientBrushSrcFragmentShader] = qglslConicalGradientBrushSrcFragmentShader;
- code[ShockingPinkSrcFragmentShader] = qglslShockingPinkSrcFragmentShader;
-
- code[NoMaskFragmentShader] = "";
- code[MaskFragmentShader] = qglslMaskFragmentShader;
- code[RgbMaskFragmentShaderPass1] = qglslRgbMaskFragmentShaderPass1;
- code[RgbMaskFragmentShaderPass2] = qglslRgbMaskFragmentShaderPass2;
- code[RgbMaskWithGammaFragmentShader] = ""; //###
-
- code[NoCompositionModeFragmentShader] = "";
- code[MultiplyCompositionModeFragmentShader] = ""; //###
- code[ScreenCompositionModeFragmentShader] = ""; //###
- code[OverlayCompositionModeFragmentShader] = ""; //###
- code[DarkenCompositionModeFragmentShader] = ""; //###
- code[LightenCompositionModeFragmentShader] = ""; //###
- code[ColorDodgeCompositionModeFragmentShader] = ""; //###
- code[ColorBurnCompositionModeFragmentShader] = ""; //###
- code[HardLightCompositionModeFragmentShader] = ""; //###
- code[SoftLightCompositionModeFragmentShader] = ""; //###
- code[DifferenceCompositionModeFragmentShader] = ""; //###
- code[ExclusionCompositionModeFragmentShader] = ""; //###
-
-#if defined(QT_DEBUG)
- // Check that all the elements have been filled:
- for (int i = 0; i < TotalSnippetCount; ++i) {
- if (Q_UNLIKELY(!qShaderSnippets[i])) {
- qFatal("Shader snippet for %s (#%d) is missing!",
- snippetNameStr(SnippetName(i)).constData(), i);
- }
- }
-#endif
- snippetsPopulated = true;
- }
-
- QGLShader* fragShader;
- QGLShader* vertexShader;
- QByteArray vertexSource;
- QByteArray fragSource;
-
- // Compile up the simple shader:
- vertexSource.append(qShaderSnippets[MainVertexShader]);
- vertexSource.append(qShaderSnippets[PositionOnlyVertexShader]);
-
- fragSource.append(qShaderSnippets[MainFragmentShader]);
- fragSource.append(qShaderSnippets[ShockingPinkSrcFragmentShader]);
-
- simpleShaderProg = new QGLShaderProgram(context, 0);
-
- CachedShader simpleShaderCache(fragSource, vertexSource);
-
- bool inCache = simpleShaderCache.load(simpleShaderProg, context);
-
- if (!inCache) {
- vertexShader = new QGLShader(QGLShader::Vertex, context, 0);
- shaders.append(vertexShader);
- if (!vertexShader->compileSourceCode(vertexSource))
- qWarning("Vertex shader for simpleShaderProg (MainVertexShader & PositionOnlyVertexShader) failed to compile");
-
- fragShader = new QGLShader(QGLShader::Fragment, context, 0);
- shaders.append(fragShader);
- if (!fragShader->compileSourceCode(fragSource))
- qWarning("Fragment shader for simpleShaderProg (MainFragmentShader & ShockingPinkSrcFragmentShader) failed to compile");
-
- simpleShaderProg->addShader(vertexShader);
- simpleShaderProg->addShader(fragShader);
-
- simpleShaderProg->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
- simpleShaderProg->bindAttributeLocation("pmvMatrix1", QT_PMV_MATRIX_1_ATTR);
- simpleShaderProg->bindAttributeLocation("pmvMatrix2", QT_PMV_MATRIX_2_ATTR);
- simpleShaderProg->bindAttributeLocation("pmvMatrix3", QT_PMV_MATRIX_3_ATTR);
- }
-
- simpleShaderProg->link();
-
- if (Q_UNLIKELY(!simpleShaderProg->isLinked())) {
- qCritical("Errors linking simple shader: %s", qPrintable(simpleShaderProg->log()));
- } else {
- if (!inCache)
- simpleShaderCache.store(simpleShaderProg, context);
- }
-
- // Compile the blit shader:
- vertexSource.clear();
- vertexSource.append(qShaderSnippets[MainWithTexCoordsVertexShader]);
- vertexSource.append(qShaderSnippets[UntransformedPositionVertexShader]);
-
- fragSource.clear();
- fragSource.append(qShaderSnippets[MainFragmentShader]);
- fragSource.append(qShaderSnippets[ImageSrcFragmentShader]);
-
- blitShaderProg = new QGLShaderProgram(context, 0);
-
- CachedShader blitShaderCache(fragSource, vertexSource);
-
- inCache = blitShaderCache.load(blitShaderProg, context);
-
- if (!inCache) {
- vertexShader = new QGLShader(QGLShader::Vertex, context, 0);
- shaders.append(vertexShader);
- if (!vertexShader->compileSourceCode(vertexSource))
- qWarning("Vertex shader for blitShaderProg (MainWithTexCoordsVertexShader & UntransformedPositionVertexShader) failed to compile");
-
- fragShader = new QGLShader(QGLShader::Fragment, context, 0);
- shaders.append(fragShader);
- if (!fragShader->compileSourceCode(fragSource))
- qWarning("Fragment shader for blitShaderProg (MainFragmentShader & ImageSrcFragmentShader) failed to compile");
-
- blitShaderProg->addShader(vertexShader);
- blitShaderProg->addShader(fragShader);
-
- blitShaderProg->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);
- blitShaderProg->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
- }
-
- blitShaderProg->link();
- if (Q_UNLIKELY(!blitShaderProg->isLinked())) {
- qCritical("Errors linking blit shader: %s", qPrintable(blitShaderProg->log()));
- } else {
- if (!inCache)
- blitShaderCache.store(blitShaderProg, context);
- }
-
-#ifdef QT_GL_SHARED_SHADER_DEBUG
- qDebug(" -> QGLEngineSharedShaders() %p for thread %p.", this, QThread::currentThread());
-#endif
-}
-
-QGLEngineSharedShaders::~QGLEngineSharedShaders()
-{
-#ifdef QT_GL_SHARED_SHADER_DEBUG
- qDebug(" -> ~QGLEngineSharedShaders() %p for thread %p.", this, QThread::currentThread());
-#endif
- qDeleteAll(shaders);
- shaders.clear();
-
- qDeleteAll(cachedPrograms);
- cachedPrograms.clear();
-
- if (blitShaderProg) {
- delete blitShaderProg;
- blitShaderProg = 0;
- }
-
- if (simpleShaderProg) {
- delete simpleShaderProg;
- simpleShaderProg = 0;
- }
-}
-
-#if defined (QT_DEBUG)
-QByteArray QGLEngineSharedShaders::snippetNameStr(SnippetName name)
-{
- QMetaEnum m = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("SnippetName"));
- return QByteArray(m.valueToKey(name));
-}
-#endif
-
-// The address returned here will only be valid until next time this function is called.
-// The program is return bound.
-QGLEngineShaderProg *QGLEngineSharedShaders::findProgramInCache(const QGLEngineShaderProg &prog)
-{
- for (int i = 0; i < cachedPrograms.size(); ++i) {
- QGLEngineShaderProg *cachedProg = cachedPrograms.at(i);
- if (*cachedProg == prog) {
- // Move the program to the top of the list as a poor-man's cache algo
- cachedPrograms.move(i, 0);
- cachedProg->program->bind();
- return cachedProg;
- }
- }
-
- QScopedPointer<QGLEngineShaderProg> newProg;
-
- do {
- QByteArray fragSource;
- // Insert the custom stage before the srcPixel shader to work around an ATI driver bug
- // where you cannot forward declare a function that takes a sampler as argument.
- if (prog.srcPixelFragShader == CustomImageSrcFragmentShader)
- fragSource.append(prog.customStageSource);
- fragSource.append(qShaderSnippets[prog.mainFragShader]);
- fragSource.append(qShaderSnippets[prog.srcPixelFragShader]);
- if (prog.compositionFragShader)
- fragSource.append(qShaderSnippets[prog.compositionFragShader]);
- if (prog.maskFragShader)
- fragSource.append(qShaderSnippets[prog.maskFragShader]);
-
- QByteArray vertexSource;
- vertexSource.append(qShaderSnippets[prog.mainVertexShader]);
- vertexSource.append(qShaderSnippets[prog.positionVertexShader]);
-
- QScopedPointer<QGLShaderProgram> shaderProgram(new QGLShaderProgram);
-
- CachedShader shaderCache(fragSource, vertexSource);
- bool inCache = shaderCache.load(shaderProgram.data(), QGLContext::currentContext());
-
- if (!inCache) {
-
- QScopedPointer<QGLShader> fragShader(new QGLShader(QGLShader::Fragment));
- QByteArray description;
-#if defined(QT_DEBUG)
- // Name the shader for easier debugging
- description.append("Fragment shader: main=");
- description.append(snippetNameStr(prog.mainFragShader));
- description.append(", srcPixel=");
- description.append(snippetNameStr(prog.srcPixelFragShader));
- if (prog.compositionFragShader) {
- description.append(", composition=");
- description.append(snippetNameStr(prog.compositionFragShader));
- }
- if (prog.maskFragShader) {
- description.append(", mask=");
- description.append(snippetNameStr(prog.maskFragShader));
- }
- fragShader->setObjectName(QString::fromLatin1(description));
-#endif
- if (!fragShader->compileSourceCode(fragSource)) {
- qWarning() << "Warning:" << description << "failed to compile!";
- break;
- }
-
- QScopedPointer<QGLShader> vertexShader(new QGLShader(QGLShader::Vertex));
-#if defined(QT_DEBUG)
- // Name the shader for easier debugging
- description.clear();
- description.append("Vertex shader: main=");
- description.append(snippetNameStr(prog.mainVertexShader));
- description.append(", position=");
- description.append(snippetNameStr(prog.positionVertexShader));
- vertexShader->setObjectName(QString::fromLatin1(description));
-#endif
- if (!vertexShader->compileSourceCode(vertexSource)) {
- qWarning() << "Warning:" << description << "failed to compile!";
- break;
- }
-
- shaders.append(vertexShader.data());
- shaders.append(fragShader.data());
- shaderProgram->addShader(vertexShader.take());
- shaderProgram->addShader(fragShader.take());
-
- // We have to bind the vertex attribute names before the program is linked:
- shaderProgram->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
- if (prog.useTextureCoords)
- shaderProgram->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);
- if (prog.useOpacityAttribute)
- shaderProgram->bindAttributeLocation("opacityArray", QT_OPACITY_ATTR);
- if (prog.usePmvMatrixAttribute) {
- shaderProgram->bindAttributeLocation("pmvMatrix1", QT_PMV_MATRIX_1_ATTR);
- shaderProgram->bindAttributeLocation("pmvMatrix2", QT_PMV_MATRIX_2_ATTR);
- shaderProgram->bindAttributeLocation("pmvMatrix3", QT_PMV_MATRIX_3_ATTR);
- }
- }
-
- newProg.reset(new QGLEngineShaderProg(prog));
- newProg->program = shaderProgram.take();
-
- newProg->program->link();
- if (newProg->program->isLinked()) {
- if (!inCache)
- shaderCache.store(newProg->program, QGLContext::currentContext());
- } else {
- 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) {
- QGLShader *shader = newProg->program->shaders().at(i);
- error += QLatin1String(" ") + shader->objectName() + QLatin1String(": \n")
- + QLatin1String(shader->sourceCode()) + br;
- }
-#endif
- error += QLatin1String(" Error Log:\n")
- + QLatin1String(" ") + newProg->program->log();
- qWarning() << error;
- break;
- }
-
- newProg->program->bind();
-
- if (newProg->maskFragShader != QGLEngineSharedShaders::NoMaskFragmentShader) {
- GLuint location = newProg->program->uniformLocation("maskTexture");
- newProg->program->setUniformValue(location, QT_MASK_TEXTURE_UNIT);
- }
-
- if (cachedPrograms.count() > 30) {
- // The cache is full, so delete the last 5 programs in the list.
- // These programs will be least used, as a program us bumped to
- // the top of the list when it's used.
- for (int i = 0; i < 5; ++i) {
- delete cachedPrograms.last();
- cachedPrograms.removeLast();
- }
- }
-
- cachedPrograms.insert(0, newProg.data());
- } while (false);
-
- return newProg.take();
-}
-
-void QGLEngineSharedShaders::cleanupCustomStage(QGLCustomShaderStage* stage)
-{
- auto hasStageAsCustomShaderSouce = [stage](QGLEngineShaderProg *cachedProg) -> bool {
- if (cachedProg->customStageSource == stage->source()) {
- delete cachedProg;
- return true;
- }
- return false;
- };
- cachedPrograms.erase(std::remove_if(cachedPrograms.begin(), cachedPrograms.end(),
- hasStageAsCustomShaderSouce),
- cachedPrograms.end());
-}
-
-
-QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context)
- : ctx(context),
- shaderProgNeedsChanging(true),
- complexGeometry(false),
- srcPixelType(Qt::NoBrush),
- opacityMode(NoOpacity),
- maskType(NoMask),
- compositionMode(QPainter::CompositionMode_SourceOver),
- customSrcStage(0),
- currentShaderProg(0)
-{
- sharedShaders = QGLEngineSharedShaders::shadersForContext(context);
-}
-
-QGLEngineShaderManager::~QGLEngineShaderManager()
-{
- //###
- removeCustomStage();
-}
-
-GLuint QGLEngineShaderManager::getUniformLocation(Uniform id)
-{
- if (!currentShaderProg)
- return 0;
-
- QVector<uint> &uniformLocations = currentShaderProg->uniformLocations;
- if (uniformLocations.isEmpty())
- uniformLocations.fill(GLuint(-1), NumUniforms);
-
- static const char *const uniformNames[] = {
- "imageTexture",
- "patternColor",
- "globalOpacity",
- "depth",
- "maskTexture",
- "fragmentColor",
- "linearData",
- "angle",
- "halfViewportSize",
- "fmp",
- "fmp2_m_radius2",
- "inverse_2_fmp2_m_radius2",
- "sqrfr",
- "bradius",
- "invertedTextureSize",
- "brushTransform",
- "brushTexture",
- "matrix",
- "translateZ"
- };
-
- if (uniformLocations.at(id) == GLuint(-1))
- uniformLocations[id] = currentShaderProg->program->uniformLocation(uniformNames[id]);
-
- return uniformLocations.at(id);
-}
-
-
-void QGLEngineShaderManager::optimiseForBrushTransform(QTransform::TransformationType transformType)
-{
- Q_UNUSED(transformType); // Currently ignored
-}
-
-void QGLEngineShaderManager::setDirty()
-{
- shaderProgNeedsChanging = true;
-}
-
-void QGLEngineShaderManager::setSrcPixelType(Qt::BrushStyle style)
-{
- Q_ASSERT(style != Qt::NoBrush);
- if (srcPixelType == PixelSrcType(style))
- return;
-
- srcPixelType = style;
- shaderProgNeedsChanging = true; //###
-}
-
-void QGLEngineShaderManager::setSrcPixelType(PixelSrcType type)
-{
- if (srcPixelType == type)
- return;
-
- srcPixelType = type;
- shaderProgNeedsChanging = true; //###
-}
-
-void QGLEngineShaderManager::setOpacityMode(OpacityMode mode)
-{
- if (opacityMode == mode)
- return;
-
- opacityMode = mode;
- shaderProgNeedsChanging = true; //###
-}
-
-void QGLEngineShaderManager::setMaskType(MaskType type)
-{
- if (maskType == type)
- return;
-
- maskType = type;
- shaderProgNeedsChanging = true; //###
-}
-
-void QGLEngineShaderManager::setCompositionMode(QPainter::CompositionMode mode)
-{
- if (compositionMode == mode)
- return;
-
- compositionMode = mode;
- shaderProgNeedsChanging = true; //###
-}
-
-void QGLEngineShaderManager::setCustomStage(QGLCustomShaderStage* stage)
-{
- if (customSrcStage)
- removeCustomStage();
- customSrcStage = stage;
- shaderProgNeedsChanging = true;
-}
-
-void QGLEngineShaderManager::removeCustomStage()
-{
- if (customSrcStage)
- customSrcStage->setInactive();
- customSrcStage = 0;
- shaderProgNeedsChanging = true;
-}
-
-QGLShaderProgram* QGLEngineShaderManager::currentProgram()
-{
- if (currentShaderProg)
- return currentShaderProg->program;
- else
- return sharedShaders->simpleProgram();
-}
-
-void QGLEngineShaderManager::useSimpleProgram()
-{
- sharedShaders->simpleProgram()->bind();
- QGLContextPrivate* ctx_d = ctx->d_func();
- ctx_d->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, true);
- ctx_d->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
- ctx_d->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
- shaderProgNeedsChanging = true;
-}
-
-void QGLEngineShaderManager::useBlitProgram()
-{
- sharedShaders->blitProgram()->bind();
- QGLContextPrivate* ctx_d = ctx->d_func();
- ctx_d->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, true);
- ctx_d->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, true);
- ctx_d->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
- shaderProgNeedsChanging = true;
-}
-
-QGLShaderProgram* QGLEngineShaderManager::simpleProgram()
-{
- return sharedShaders->simpleProgram();
-}
-
-QGLShaderProgram* QGLEngineShaderManager::blitProgram()
-{
- return sharedShaders->blitProgram();
-}
-
-
-
-// Select & use the correct shader program using the current state.
-// Returns \c true if program needed changing.
-bool QGLEngineShaderManager::useCorrectShaderProg()
-{
- if (!shaderProgNeedsChanging)
- return false;
-
- bool useCustomSrc = customSrcStage != 0;
- if (useCustomSrc && srcPixelType != QGLEngineShaderManager::ImageSrc && srcPixelType != Qt::TexturePattern) {
- useCustomSrc = false;
- qWarning("QGLEngineShaderManager - Ignoring custom shader stage for non image src");
- }
-
- QGLEngineShaderProg requiredProgram;
-
- bool texCoords = false;
-
- // Choose vertex shader shader position function (which typically also sets
- // varyings) and the source pixel (srcPixel) fragment shader function:
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::InvalidSnippetName;
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::InvalidSnippetName;
- bool isAffine = brushTransform.isAffine();
- if ( (srcPixelType >= Qt::Dense1Pattern) && (srcPixelType <= Qt::DiagCrossPattern) ) {
- if (isAffine)
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::AffinePositionWithPatternBrushVertexShader;
- else
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::PositionWithPatternBrushVertexShader;
-
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::PatternBrushSrcFragmentShader;
- }
- else switch (srcPixelType) {
- default:
- case Qt::NoBrush:
- qFatal("QGLEngineShaderManager::useCorrectShaderProg() - Qt::NoBrush style is set");
- break;
- case QGLEngineShaderManager::ImageSrc:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::ImageSrcFragmentShader;
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::PositionOnlyVertexShader;
- texCoords = true;
- break;
- case QGLEngineShaderManager::NonPremultipliedImageSrc:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::NonPremultipliedImageSrcFragmentShader;
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::PositionOnlyVertexShader;
- texCoords = true;
- break;
- case QGLEngineShaderManager::PatternSrc:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::ImageSrcWithPatternFragmentShader;
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::PositionOnlyVertexShader;
- texCoords = true;
- break;
- case QGLEngineShaderManager::TextureSrcWithPattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::TextureBrushSrcWithPatternFragmentShader;
- requiredProgram.positionVertexShader = isAffine ? QGLEngineSharedShaders::AffinePositionWithTextureBrushVertexShader
- : QGLEngineSharedShaders::PositionWithTextureBrushVertexShader;
- break;
- case Qt::SolidPattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::SolidBrushSrcFragmentShader;
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::PositionOnlyVertexShader;
- break;
- case Qt::LinearGradientPattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::LinearGradientBrushSrcFragmentShader;
- requiredProgram.positionVertexShader = isAffine ? QGLEngineSharedShaders::AffinePositionWithLinearGradientBrushVertexShader
- : QGLEngineSharedShaders::PositionWithLinearGradientBrushVertexShader;
- break;
- case Qt::ConicalGradientPattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::ConicalGradientBrushSrcFragmentShader;
- requiredProgram.positionVertexShader = isAffine ? QGLEngineSharedShaders::AffinePositionWithConicalGradientBrushVertexShader
- : QGLEngineSharedShaders::PositionWithConicalGradientBrushVertexShader;
- break;
- case Qt::RadialGradientPattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::RadialGradientBrushSrcFragmentShader;
- requiredProgram.positionVertexShader = isAffine ? QGLEngineSharedShaders::AffinePositionWithRadialGradientBrushVertexShader
- : QGLEngineSharedShaders::PositionWithRadialGradientBrushVertexShader;
- break;
- case Qt::TexturePattern:
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::TextureBrushSrcFragmentShader;
- requiredProgram.positionVertexShader = isAffine ? QGLEngineSharedShaders::AffinePositionWithTextureBrushVertexShader
- : QGLEngineSharedShaders::PositionWithTextureBrushVertexShader;
- break;
- };
-
- if (useCustomSrc) {
- requiredProgram.srcPixelFragShader = QGLEngineSharedShaders::CustomImageSrcFragmentShader;
- requiredProgram.customStageSource = customSrcStage->source();
- }
-
- const bool hasCompose = compositionMode > QPainter::CompositionMode_Plus;
- const bool hasMask = maskType != QGLEngineShaderManager::NoMask;
-
- // Choose fragment shader main function:
- if (opacityMode == AttributeOpacity) {
- Q_ASSERT(!hasCompose && !hasMask);
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_ImageArrays;
- } else {
- bool useGlobalOpacity = (opacityMode == UniformOpacity);
- if (hasCompose && hasMask && useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_CMO;
- if (hasCompose && hasMask && !useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_CM;
- if (!hasCompose && hasMask && useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_MO;
- if (!hasCompose && hasMask && !useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_M;
- if (hasCompose && !hasMask && useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_CO;
- if (hasCompose && !hasMask && !useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_C;
- if (!hasCompose && !hasMask && useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader_O;
- if (!hasCompose && !hasMask && !useGlobalOpacity)
- requiredProgram.mainFragShader = QGLEngineSharedShaders::MainFragmentShader;
- }
-
- if (hasMask) {
- if (maskType == PixelMask) {
- requiredProgram.maskFragShader = QGLEngineSharedShaders::MaskFragmentShader;
- texCoords = true;
- } else if (maskType == SubPixelMaskPass1) {
- requiredProgram.maskFragShader = QGLEngineSharedShaders::RgbMaskFragmentShaderPass1;
- texCoords = true;
- } else if (maskType == SubPixelMaskPass2) {
- requiredProgram.maskFragShader = QGLEngineSharedShaders::RgbMaskFragmentShaderPass2;
- texCoords = true;
- } else if (maskType == SubPixelWithGammaMask) {
- requiredProgram.maskFragShader = QGLEngineSharedShaders::RgbMaskWithGammaFragmentShader;
- texCoords = true;
- } else {
- qCritical("QGLEngineShaderManager::useCorrectShaderProg() - Unknown mask type");
- }
- } else {
- requiredProgram.maskFragShader = QGLEngineSharedShaders::NoMaskFragmentShader;
- }
-
- if (hasCompose) {
- switch (compositionMode) {
- case QPainter::CompositionMode_Multiply:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::MultiplyCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Screen:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::ScreenCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Overlay:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::OverlayCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Darken:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::DarkenCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Lighten:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::LightenCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_ColorDodge:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::ColorDodgeCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_ColorBurn:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::ColorBurnCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_HardLight:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::HardLightCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_SoftLight:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::SoftLightCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Difference:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::DifferenceCompositionModeFragmentShader;
- break;
- case QPainter::CompositionMode_Exclusion:
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::ExclusionCompositionModeFragmentShader;
- break;
- default:
- qWarning("QGLEngineShaderManager::useCorrectShaderProg() - Unsupported composition mode");
- }
- } else {
- requiredProgram.compositionFragShader = QGLEngineSharedShaders::NoCompositionModeFragmentShader;
- }
-
- // Choose vertex shader main function
- if (opacityMode == AttributeOpacity) {
- Q_ASSERT(texCoords);
- requiredProgram.mainVertexShader = QGLEngineSharedShaders::MainWithTexCoordsAndOpacityVertexShader;
- } else if (texCoords) {
- requiredProgram.mainVertexShader = QGLEngineSharedShaders::MainWithTexCoordsVertexShader;
- } else {
- requiredProgram.mainVertexShader = QGLEngineSharedShaders::MainVertexShader;
- }
- requiredProgram.useTextureCoords = texCoords;
- requiredProgram.useOpacityAttribute = (opacityMode == AttributeOpacity);
- if (complexGeometry && srcPixelType == Qt::SolidPattern) {
- requiredProgram.positionVertexShader = QGLEngineSharedShaders::ComplexGeometryPositionOnlyVertexShader;
- requiredProgram.usePmvMatrixAttribute = false;
- } else {
- requiredProgram.usePmvMatrixAttribute = true;
-
- // Force complexGeometry off, since we currently don't support that mode for
- // non-solid brushes
- complexGeometry = false;
- }
-
- // At this point, requiredProgram is fully populated so try to find the program in the cache
- currentShaderProg = sharedShaders->findProgramInCache(requiredProgram);
-
- if (currentShaderProg && useCustomSrc) {
- customSrcStage->setUniforms(currentShaderProg->program);
- }
-
- // Make sure all the vertex attribute arrays the program uses are enabled (and the ones it
- // doesn't use are disabled)
- QGLContextPrivate* ctx_d = ctx->d_func();
- ctx_d->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, true);
- ctx_d->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, currentShaderProg && currentShaderProg->useTextureCoords);
- ctx_d->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, currentShaderProg && currentShaderProg->useOpacityAttribute);
-
- shaderProgNeedsChanging = false;
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h
deleted file mode 100644
index d23b3ad550..0000000000
--- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h
+++ /dev/null
@@ -1,508 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-/*
- VERTEX SHADERS
- ==============
-
- Vertex shaders are specified as multiple (partial) shaders. On desktop,
- this works fine. On ES, QGLShader & QGLShaderProgram will make partial
- shaders work by concatenating the source in each QGLShader and compiling
- it as a single shader. This is abstracted nicely by QGLShaderProgram and
- the GL2 engine doesn't need to worry about it.
-
- Generally, there's two vertex shader objects. The position shaders are
- the ones which set gl_Position. There's also two "main" vertex shaders,
- one which just calls the position shader and another which also passes
- through some texture coordinates from a vertex attribute array to a
- varying. These texture coordinates are used for mask position in text
- rendering and for the source coordinates in drawImage/drawPixmap. There's
- also a "Simple" vertex shader for rendering a solid colour (used to render
- into the stencil buffer where the actual colour value is discarded).
-
- The position shaders for brushes look scary. This is because many of the
- calculations which logically belong in the fragment shader have been moved
- into the vertex shader to improve performance. This is why the position
- calculation is in a separate shader. Not only does it calculate the
- position, but it also calculates some data to be passed to the fragment
- shader as a varying. It is optimal to move as much of the calculation as
- possible into the vertex shader as this is executed less often.
-
- The varyings passed to the fragment shaders are interpolated (which is
- cheap). Unfortunately, GL will apply perspective correction to the
- interpolation calusing errors. To get around this, the vertex shader must
- apply perspective correction itself and set the w-value of gl_Position to
- zero. That way, GL will be tricked into thinking it doesn't need to apply a
- perspective correction and use linear interpolation instead (which is what
- we want). Of course, if the brush transform is affeine, no perspective
- correction is needed and a simpler vertex shader can be used instead.
-
- So there are the following "main" vertex shaders:
- qglslMainVertexShader
- qglslMainWithTexCoordsVertexShader
-
- And the following position vertex shaders:
- qglslPositionOnlyVertexShader
- qglslPositionWithTextureBrushVertexShader
- qglslPositionWithPatternBrushVertexShader
- qglslPositionWithLinearGradientBrushVertexShader
- qglslPositionWithRadialGradientBrushVertexShader
- qglslPositionWithConicalGradientBrushVertexShader
- qglslAffinePositionWithTextureBrushVertexShader
- qglslAffinePositionWithPatternBrushVertexShader
- qglslAffinePositionWithLinearGradientBrushVertexShader
- qglslAffinePositionWithRadialGradientBrushVertexShader
- qglslAffinePositionWithConicalGradientBrushVertexShader
-
- Leading to 23 possible vertex shaders
-
-
- FRAGMENT SHADERS
- ================
-
- Fragment shaders are also specified as multiple (partial) shaders. The
- different fragment shaders represent the different stages in Qt's fragment
- pipeline. There are 1-3 stages in this pipeline: First stage is to get the
- fragment's colour value. The next stage is to get the fragment's mask value
- (coverage value for anti-aliasing) and the final stage is to blend the
- incoming fragment with the background (for composition modes not supported
- by GL).
-
- Of these, the first stage will always be present. If Qt doesn't need to
- apply anti-aliasing (because it's off or handled by multisampling) then
- the coverage value doesn't need to be applied. (Note: There are two types
- of mask, one for regular anti-aliasing and one for sub-pixel anti-
- aliasing.) If the composition mode is one which GL supports natively then
- the blending stage doesn't need to be applied.
-
- As eash stage can have multiple implementations, they are abstracted as
- GLSL function calls with the following signatures:
-
- Brushes & image drawing are implementations of "qcolorp vec4 srcPixel()":
- qglslImageSrcFragShader
- qglslImageSrcWithPatternFragShader
- qglslNonPremultipliedImageSrcFragShader
- qglslSolidBrushSrcFragShader
- qglslTextureBrushSrcFragShader
- qglslTextureBrushWithPatternFragShader
- qglslPatternBrushSrcFragShader
- qglslLinearGradientBrushSrcFragShader
- qglslRadialGradientBrushSrcFragShader
- qglslConicalGradientBrushSrcFragShader
- NOTE: It is assumed the colour returned by srcPixel() is pre-multiplied
-
- Masks are implementations of "qcolorp vec4 applyMask(qcolorp vec4 src)":
- qglslMaskFragmentShader
- qglslRgbMaskFragmentShaderPass1
- qglslRgbMaskFragmentShaderPass2
- qglslRgbMaskWithGammaFragmentShader
-
- Composition modes are "qcolorp vec4 compose(qcolorp vec4 src)":
- qglslColorBurnCompositionModeFragmentShader
- qglslColorDodgeCompositionModeFragmentShader
- qglslDarkenCompositionModeFragmentShader
- qglslDifferenceCompositionModeFragmentShader
- qglslExclusionCompositionModeFragmentShader
- qglslHardLightCompositionModeFragmentShader
- qglslLightenCompositionModeFragmentShader
- qglslMultiplyCompositionModeFragmentShader
- qglslOverlayCompositionModeFragmentShader
- qglslScreenCompositionModeFragmentShader
- qglslSoftLightCompositionModeFragmentShader
-
-
- Note: In the future, some GLSL compilers will support an extension allowing
- a new 'color' precision specifier. To support this, qcolorp is used for
- all color components so it can be defined to colorp or lowp depending upon
- the implementation.
-
- So there are differnt frament shader main functions, depending on the
- number & type of pipelines the fragment needs to go through.
-
- The choice of which main() fragment shader string to use depends on:
- - Use of global opacity
- - Brush style (some brushes apply opacity themselves)
- - Use & type of mask (TODO: Need to support high quality anti-aliasing & text)
- - Use of non-GL Composition mode
-
- Leading to the following fragment shader main functions:
- gl_FragColor = compose(applyMask(srcPixel()*globalOpacity));
- gl_FragColor = compose(applyMask(srcPixel()));
- gl_FragColor = applyMask(srcPixel()*globalOpacity);
- gl_FragColor = applyMask(srcPixel());
- gl_FragColor = compose(srcPixel()*globalOpacity);
- gl_FragColor = compose(srcPixel());
- gl_FragColor = srcPixel()*globalOpacity;
- gl_FragColor = srcPixel();
-
- Called:
- qglslMainFragmentShader_CMO
- qglslMainFragmentShader_CM
- qglslMainFragmentShader_MO
- qglslMainFragmentShader_M
- qglslMainFragmentShader_CO
- qglslMainFragmentShader_C
- qglslMainFragmentShader_O
- qglslMainFragmentShader
-
- Where:
- M = Mask
- C = Composition
- O = Global Opacity
-
-
- CUSTOM SHADER CODE
- ==================
-
- The use of custom shader code is supported by the engine for drawImage and
- drawPixmap calls. This is implemented via hooks in the fragment pipeline.
-
- The custom shader is passed to the engine as a partial fragment shader
- (QGLCustomShaderStage). The shader will implement a pre-defined method name
- which Qt's fragment pipeline will call:
-
- lowp vec4 customShader(lowp sampler2d imageTexture, highp vec2 textureCoords)
-
- The provided src and srcCoords parameters can be used to sample from the
- source image.
-
- Transformations, clipping, opacity, and composition modes set using QPainter
- will be respected when using the custom shader hook.
-*/
-
-#ifndef QGLENGINE_SHADER_MANAGER_H
-#define QGLENGINE_SHADER_MANAGER_H
-
-#include <QGLShader>
-#include <QGLShaderProgram>
-#include <QPainter>
-#include <private/qgl_p.h>
-#include <private/qglcustomshaderstage_p.h>
-
-QT_BEGIN_NAMESPACE
-
-
-
-/*
-struct QGLEngineCachedShaderProg
-{
- QGLEngineCachedShaderProg(QGLEngineShaderManager::ShaderName vertexMain,
- QGLEngineShaderManager::ShaderName vertexPosition,
- QGLEngineShaderManager::ShaderName fragMain,
- QGLEngineShaderManager::ShaderName pixelSrc,
- QGLEngineShaderManager::ShaderName mask,
- QGLEngineShaderManager::ShaderName composition);
-
- int cacheKey;
- QGLShaderProgram* program;
-}
-*/
-
-static const GLuint QT_VERTEX_COORDS_ATTR = 0;
-static const GLuint QT_TEXTURE_COORDS_ATTR = 1;
-static const GLuint QT_OPACITY_ATTR = 2;
-static const GLuint QT_PMV_MATRIX_1_ATTR = 3;
-static const GLuint QT_PMV_MATRIX_2_ATTR = 4;
-static const GLuint QT_PMV_MATRIX_3_ATTR = 5;
-
-class QGLEngineShaderProg;
-
-class Q_OPENGL_EXPORT QGLEngineSharedShaders
-{
- Q_GADGET
-public:
-
- enum SnippetName {
- MainVertexShader,
- MainWithTexCoordsVertexShader,
- MainWithTexCoordsAndOpacityVertexShader,
-
- // UntransformedPositionVertexShader must be first in the list:
- UntransformedPositionVertexShader,
- PositionOnlyVertexShader,
- ComplexGeometryPositionOnlyVertexShader,
- PositionWithPatternBrushVertexShader,
- PositionWithLinearGradientBrushVertexShader,
- PositionWithConicalGradientBrushVertexShader,
- PositionWithRadialGradientBrushVertexShader,
- PositionWithTextureBrushVertexShader,
- AffinePositionWithPatternBrushVertexShader,
- AffinePositionWithLinearGradientBrushVertexShader,
- AffinePositionWithConicalGradientBrushVertexShader,
- AffinePositionWithRadialGradientBrushVertexShader,
- AffinePositionWithTextureBrushVertexShader,
-
- // MainFragmentShader_CMO must be first in the list:
- MainFragmentShader_CMO,
- MainFragmentShader_CM,
- MainFragmentShader_MO,
- MainFragmentShader_M,
- MainFragmentShader_CO,
- MainFragmentShader_C,
- MainFragmentShader_O,
- MainFragmentShader,
- MainFragmentShader_ImageArrays,
-
- // ImageSrcFragmentShader must be first in the list::
- ImageSrcFragmentShader,
- ImageSrcWithPatternFragmentShader,
- NonPremultipliedImageSrcFragmentShader,
- CustomImageSrcFragmentShader,
- SolidBrushSrcFragmentShader,
- TextureBrushSrcFragmentShader,
- TextureBrushSrcWithPatternFragmentShader,
- PatternBrushSrcFragmentShader,
- LinearGradientBrushSrcFragmentShader,
- RadialGradientBrushSrcFragmentShader,
- ConicalGradientBrushSrcFragmentShader,
- ShockingPinkSrcFragmentShader,
-
- // NoMaskFragmentShader must be first in the list:
- NoMaskFragmentShader,
- MaskFragmentShader,
- RgbMaskFragmentShaderPass1,
- RgbMaskFragmentShaderPass2,
- RgbMaskWithGammaFragmentShader,
-
- // NoCompositionModeFragmentShader must be first in the list:
- NoCompositionModeFragmentShader,
- MultiplyCompositionModeFragmentShader,
- ScreenCompositionModeFragmentShader,
- OverlayCompositionModeFragmentShader,
- DarkenCompositionModeFragmentShader,
- LightenCompositionModeFragmentShader,
- ColorDodgeCompositionModeFragmentShader,
- ColorBurnCompositionModeFragmentShader,
- HardLightCompositionModeFragmentShader,
- SoftLightCompositionModeFragmentShader,
- DifferenceCompositionModeFragmentShader,
- ExclusionCompositionModeFragmentShader,
-
- TotalSnippetCount, InvalidSnippetName
- };
-#if defined (QT_DEBUG)
- Q_ENUMS(SnippetName)
- static QByteArray snippetNameStr(SnippetName snippetName);
-#endif
-
-/*
- // These allow the ShaderName enum to be used as a cache key
- const int mainVertexOffset = 0;
- const int positionVertexOffset = (1<<2) - PositionOnlyVertexShader;
- const int mainFragOffset = (1<<6) - MainFragmentShader_CMO;
- const int srcPixelOffset = (1<<10) - ImageSrcFragmentShader;
- const int maskOffset = (1<<14) - NoMaskShader;
- const int compositionOffset = (1 << 16) - MultiplyCompositionModeFragmentShader;
-*/
-
- QGLEngineSharedShaders(const QGLContext *context);
- ~QGLEngineSharedShaders();
-
- QGLShaderProgram *simpleProgram() { return simpleShaderProg; }
- QGLShaderProgram *blitProgram() { return blitShaderProg; }
- // Compile the program if it's not already in the cache, return the item in the cache.
- QGLEngineShaderProg *findProgramInCache(const QGLEngineShaderProg &prog);
- // Compile the custom shader if it's not already in the cache, return the item in the cache.
-
- static QGLEngineSharedShaders *shadersForContext(const QGLContext *context);
-
- // Ideally, this would be static and cleanup all programs in all contexts which
- // contain the custom code. Currently it is just a hint and we rely on deleted
- // custom shaders being cleaned up by being kicked out of the cache when it's
- // full.
- void cleanupCustomStage(QGLCustomShaderStage* stage);
-
-private:
- QGLShaderProgram *blitShaderProg;
- QGLShaderProgram *simpleShaderProg;
- QList<QGLEngineShaderProg*> cachedPrograms;
- QList<QGLShader *> shaders;
-
- static const char* qShaderSnippets[TotalSnippetCount];
-};
-
-
-class QGLEngineShaderProg
-{
-public:
- QGLEngineShaderProg() : program(nullptr) {}
-
- ~QGLEngineShaderProg() {
- if (program)
- delete program;
- }
-
- QGLEngineSharedShaders::SnippetName mainVertexShader;
- QGLEngineSharedShaders::SnippetName positionVertexShader;
- QGLEngineSharedShaders::SnippetName mainFragShader;
- QGLEngineSharedShaders::SnippetName srcPixelFragShader;
- QGLEngineSharedShaders::SnippetName maskFragShader;
- QGLEngineSharedShaders::SnippetName compositionFragShader;
-
- QByteArray customStageSource; //TODO: Decent cache key for custom stages
- QGLShaderProgram* program;
-
- QVector<uint> uniformLocations;
-
- bool useTextureCoords;
- bool useOpacityAttribute;
- bool usePmvMatrixAttribute;
-
- bool operator==(const QGLEngineShaderProg& other) const {
- // We don't care about the program
- return ( mainVertexShader == other.mainVertexShader &&
- positionVertexShader == other.positionVertexShader &&
- mainFragShader == other.mainFragShader &&
- srcPixelFragShader == other.srcPixelFragShader &&
- maskFragShader == other.maskFragShader &&
- compositionFragShader == other.compositionFragShader &&
- customStageSource == other.customStageSource
- );
- }
-};
-
-class Q_OPENGL_EXPORT QGLEngineShaderManager : public QObject
-{
- Q_OBJECT
-public:
- QGLEngineShaderManager(QGLContext* context);
- ~QGLEngineShaderManager();
-
- enum MaskType {NoMask, PixelMask, SubPixelMaskPass1, SubPixelMaskPass2, SubPixelWithGammaMask};
- enum PixelSrcType {
- ImageSrc = Qt::TexturePattern+1,
- NonPremultipliedImageSrc = Qt::TexturePattern+2,
- PatternSrc = Qt::TexturePattern+3,
- TextureSrcWithPattern = Qt::TexturePattern+4
- };
-
- enum Uniform {
- ImageTexture,
- PatternColor,
- GlobalOpacity,
- Depth,
- MaskTexture,
- FragmentColor,
- LinearData,
- Angle,
- HalfViewportSize,
- Fmp,
- Fmp2MRadius2,
- Inverse2Fmp2MRadius2,
- SqrFr,
- BRadius,
- InvertedTextureSize,
- BrushTransform,
- BrushTexture,
- Matrix,
- TranslateZ,
- NumUniforms
- };
-
- enum OpacityMode {
- NoOpacity,
- UniformOpacity,
- AttributeOpacity
- };
-
- // There are optimizations we can do, depending on the brush transform:
- // 1) May not have to apply perspective-correction
- // 2) Can use lower precision for matrix
- void optimiseForBrushTransform(QTransform::TransformationType transformType);
- void setSrcPixelType(Qt::BrushStyle);
- void setSrcPixelType(PixelSrcType); // For non-brush sources, like pixmaps & images
- void setOpacityMode(OpacityMode);
- void setMaskType(MaskType);
- void setCompositionMode(QPainter::CompositionMode);
- void setCustomStage(QGLCustomShaderStage* stage);
- void removeCustomStage();
-
- GLuint getUniformLocation(Uniform id);
-
- void setDirty(); // someone has manually changed the current shader program
- bool useCorrectShaderProg(); // returns true if the shader program needed to be changed
-
- void useSimpleProgram();
- void useBlitProgram();
- void setHasComplexGeometry(bool hasComplexGeometry)
- {
- complexGeometry = hasComplexGeometry;
- shaderProgNeedsChanging = true;
- }
- bool hasComplexGeometry() const
- {
- return complexGeometry;
- }
-
- QGLShaderProgram* currentProgram(); // Returns pointer to the shader the manager has chosen
- QGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers
- QGLShaderProgram* blitProgram(); // Used to blit a texture into the framebuffer
-
- QGLEngineSharedShaders* sharedShaders;
-
-private:
- QGLContext* ctx;
- bool shaderProgNeedsChanging;
- bool complexGeometry;
-
- // Current state variables which influence the choice of shader:
- QTransform brushTransform;
- int srcPixelType;
- OpacityMode opacityMode;
- MaskType maskType;
- QPainter::CompositionMode compositionMode;
- QGLCustomShaderStage* customSrcStage;
-
- QGLEngineShaderProg* currentShaderProg;
-};
-
-QT_END_NAMESPACE
-
-#endif //QGLENGINE_SHADER_MANAGER_H
diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h
deleted file mode 100644
index a667af9b96..0000000000
--- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h
+++ /dev/null
@@ -1,523 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-
-#ifndef QGL_ENGINE_SHADER_SOURCE_H
-#define QGL_ENGINE_SHADER_SOURCE_H
-
-#include "qglengineshadermanager_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-
-static const char* const qglslMainVertexShader = "\n\
- void setPosition(); \n\
- void main(void) \n\
- { \n\
- setPosition(); \n\
- }\n";
-
-static const char* const qglslMainWithTexCoordsVertexShader = "\n\
- attribute highp vec2 textureCoordArray; \n\
- varying highp vec2 textureCoords; \n\
- void setPosition(); \n\
- void main(void) \n\
- { \n\
- setPosition(); \n\
- textureCoords = textureCoordArray; \n\
- }\n";
-
-static const char* const qglslMainWithTexCoordsAndOpacityVertexShader = "\n\
- attribute highp vec2 textureCoordArray; \n\
- attribute lowp float opacityArray; \n\
- varying highp vec2 textureCoords; \n\
- varying lowp float opacity; \n\
- void setPosition(); \n\
- void main(void) \n\
- { \n\
- setPosition(); \n\
- textureCoords = textureCoordArray; \n\
- opacity = opacityArray; \n\
- }\n";
-
-// NOTE: We let GL do the perspective correction so texture lookups in the fragment
-// shader are also perspective corrected.
-static const char* const qglslPositionOnlyVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray; \n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- void setPosition(void) \n\
- { \n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position = vec4(transformedPos.xy, 0.0, transformedPos.z); \n\
- }\n";
-
-static const char* const qglslComplexGeometryPositionOnlyVertexShader = "\n\
- uniform highp mat3 matrix; \n\
- uniform highp float translateZ; \n\
- attribute highp vec2 vertexCoordsArray; \n\
- void setPosition(void) \n\
- { \n\
- vec3 v = matrix * vec3(vertexCoordsArray, 1.0); \n\
- vec4 vz = mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, translateZ, 1) * vec4(v, 1.0); \n\
- gl_Position = vec4(vz.xyz, 1.0);\n\
- } \n";
-
-static const char* const qglslUntransformedPositionVertexShader = "\n\
- attribute highp vec4 vertexCoordsArray; \n\
- void setPosition(void) \n\
- { \n\
- gl_Position = vertexCoordsArray; \n\
- }\n";
-
-// Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125
-static const char* const qglslPositionWithPatternBrushVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray; \n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- uniform mediump vec2 halfViewportSize; \n\
- uniform highp vec2 invertedTextureSize; \n\
- uniform highp mat3 brushTransform; \n\
- varying highp vec2 patternTexCoords; \n\
- void setPosition(void) \n\
- { \n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position.xy = transformedPos.xy / transformedPos.z; \n\
- mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \n\
- mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1.0); \n\
- mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \n\
- gl_Position = vec4(gl_Position.xy * invertedHTexCoordsZ, 0.0, invertedHTexCoordsZ); \n\
- patternTexCoords.xy = (hTexCoords.xy * 0.125) * invertedHTexCoordsZ; \n\
- }\n";
-
-static const char* const qglslAffinePositionWithPatternBrushVertexShader
- = qglslPositionWithPatternBrushVertexShader;
-
-static const char* const qglslPatternBrushSrcFragmentShader = "\n\
- uniform sampler2D brushTexture; \n\
- uniform lowp vec4 patternColor; \n\
- varying highp vec2 patternTexCoords;\n\
- lowp vec4 srcPixel() \n\
- { \n\
- return patternColor * (1.0 - texture2D(brushTexture, patternTexCoords).r); \n\
- }\n";
-
-
-// Linear Gradient Brush
-static const char* const qglslPositionWithLinearGradientBrushVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray; \n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- uniform mediump vec2 halfViewportSize; \n\
- uniform highp vec3 linearData; \n\
- uniform highp mat3 brushTransform; \n\
- varying mediump float index; \n\
- void setPosition() \n\
- { \n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position.xy = transformedPos.xy / transformedPos.z; \n\
- mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \n\
- mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \n\
- mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \n\
- gl_Position = vec4(gl_Position.xy * invertedHTexCoordsZ, 0.0, invertedHTexCoordsZ); \n\
- index = (dot(linearData.xy, hTexCoords.xy) * linearData.z) * invertedHTexCoordsZ; \n\
- }\n";
-
-static const char* const qglslAffinePositionWithLinearGradientBrushVertexShader
- = qglslPositionWithLinearGradientBrushVertexShader;
-
-static const char* const qglslLinearGradientBrushSrcFragmentShader = "\n\
- uniform sampler2D brushTexture; \n\
- varying mediump float index; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- mediump vec2 val = vec2(index, 0.5); \n\
- return texture2D(brushTexture, val); \n\
- }\n";
-
-
-// Conical Gradient Brush
-static const char* const qglslPositionWithConicalGradientBrushVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray; \n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- uniform mediump vec2 halfViewportSize; \n\
- uniform highp mat3 brushTransform; \n\
- varying highp vec2 A; \n\
- void setPosition(void) \n\
- { \n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position.xy = transformedPos.xy / transformedPos.z; \n\
- mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \n\
- mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \n\
- mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \n\
- gl_Position = vec4(gl_Position.xy * invertedHTexCoordsZ, 0.0, invertedHTexCoordsZ); \n\
- A = hTexCoords.xy * invertedHTexCoordsZ; \n\
- }\n";
-
-static const char* const qglslAffinePositionWithConicalGradientBrushVertexShader
- = qglslPositionWithConicalGradientBrushVertexShader;
-
-static const char* const qglslConicalGradientBrushSrcFragmentShader = "\n\
- #define INVERSE_2PI 0.1591549430918953358 \n\
- uniform sampler2D brushTexture; \n\
- uniform mediump float angle; \n\
- varying highp vec2 A; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- highp float t; \n\
- if (abs(A.y) == abs(A.x)) \n\
- t = (atan(-A.y + 0.002, A.x) + angle) * INVERSE_2PI; \n\
- else \n\
- t = (atan(-A.y, A.x) + angle) * INVERSE_2PI; \n\
- return texture2D(brushTexture, vec2(t - floor(t), 0.5)); \n\
- }\n";
-
-
-// Radial Gradient Brush
-static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray;\n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- uniform mediump vec2 halfViewportSize; \n\
- uniform highp mat3 brushTransform; \n\
- uniform highp vec2 fmp; \n\
- uniform mediump vec3 bradius; \n\
- varying highp float b; \n\
- varying highp vec2 A; \n\
- void setPosition(void) \n\
- {\n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position.xy = transformedPos.xy / transformedPos.z; \n\
- mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \n\
- mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \n\
- mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \n\
- gl_Position = vec4(gl_Position.xy * invertedHTexCoordsZ, 0.0, invertedHTexCoordsZ); \n\
- A = hTexCoords.xy * invertedHTexCoordsZ; \n\
- b = bradius.x + 2.0 * dot(A, fmp); \n\
- }\n";
-
-static const char* const qglslAffinePositionWithRadialGradientBrushVertexShader
- = qglslPositionWithRadialGradientBrushVertexShader;
-
-static const char* const qglslRadialGradientBrushSrcFragmentShader = "\n\
- uniform sampler2D brushTexture; \n\
- uniform highp float fmp2_m_radius2; \n\
- uniform highp float inverse_2_fmp2_m_radius2; \n\
- uniform highp float sqrfr; \n\
- varying highp float b; \n\
- varying highp vec2 A; \n\
- uniform mediump vec3 bradius; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- highp float c = sqrfr-dot(A, A); \n\
- highp float det = b*b - 4.0*fmp2_m_radius2*c; \n\
- lowp vec4 result = vec4(0.0); \n\
- if (det >= 0.0) { \n\
- highp float detSqrt = sqrt(det); \n\
- highp float w = max((-b - detSqrt) * inverse_2_fmp2_m_radius2, (-b + detSqrt) * inverse_2_fmp2_m_radius2); \n\
- if (bradius.y + w * bradius.z >= 0.0) \n\
- result = texture2D(brushTexture, vec2(w, 0.5)); \n\
- } \n\
- return result; \n\
- }\n";
-
-
-// Texture Brush
-static const char* const qglslPositionWithTextureBrushVertexShader = "\n\
- attribute highp vec2 vertexCoordsArray; \n\
- attribute highp vec3 pmvMatrix1; \n\
- attribute highp vec3 pmvMatrix2; \n\
- attribute highp vec3 pmvMatrix3; \n\
- uniform mediump vec2 halfViewportSize; \n\
- uniform highp vec2 invertedTextureSize; \n\
- uniform highp mat3 brushTransform; \n\
- varying highp vec2 brushTextureCoords; \n\
- void setPosition(void) \n\
- { \n\
- highp mat3 pmvMatrix = mat3(pmvMatrix1, pmvMatrix2, pmvMatrix3); \n\
- vec3 transformedPos = pmvMatrix * vec3(vertexCoordsArray.xy, 1.0); \n\
- gl_Position.xy = transformedPos.xy / transformedPos.z; \n\
- mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \n\
- mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \n\
- mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \n\
- gl_Position = vec4(gl_Position.xy * invertedHTexCoordsZ, 0.0, invertedHTexCoordsZ); \n\
- brushTextureCoords.xy = (hTexCoords.xy * invertedTextureSize) * gl_Position.w; \n\
- }\n";
-
-static const char* const qglslAffinePositionWithTextureBrushVertexShader
- = qglslPositionWithTextureBrushVertexShader;
-
-// OpenGL ES does not support GL_REPEAT wrap modes for NPOT textures. So instead,
-// we emulate GL_REPEAT by only taking the fractional part of the texture coords.
-// TODO: Special case POT textures which don't need this emulation
-static const char* const qglslTextureBrushSrcFragmentShader_ES = "\n\
- varying highp vec2 brushTextureCoords; \n\
- uniform sampler2D brushTexture; \n\
- lowp vec4 srcPixel() { \n\
- return texture2D(brushTexture, fract(brushTextureCoords)); \n\
- }\n";
-
-static const char* const qglslTextureBrushSrcFragmentShader_desktop = "\n\
- varying highp vec2 brushTextureCoords; \n\
- uniform sampler2D brushTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- return texture2D(brushTexture, brushTextureCoords); \n\
- }\n";
-
-static const char* const qglslTextureBrushSrcWithPatternFragmentShader = "\n\
- varying highp vec2 brushTextureCoords; \n\
- uniform lowp vec4 patternColor; \n\
- uniform sampler2D brushTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- return patternColor * (1.0 - texture2D(brushTexture, brushTextureCoords).r); \n\
- }\n";
-
-// Solid Fill Brush
-static const char* const qglslSolidBrushSrcFragmentShader = "\n\
- uniform lowp vec4 fragmentColor; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- return fragmentColor; \n\
- }\n";
-
-static const char* const qglslImageSrcFragmentShader = "\n\
- varying highp vec2 textureCoords; \n\
- uniform sampler2D imageTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n"
- "return texture2D(imageTexture, textureCoords); \n"
- "}\n";
-
-static const char* const qglslCustomSrcFragmentShader = "\n\
- varying highp vec2 textureCoords; \n\
- uniform sampler2D imageTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- return customShader(imageTexture, textureCoords); \n\
- }\n";
-
-static const char* const qglslImageSrcWithPatternFragmentShader = "\n\
- varying highp vec2 textureCoords; \n\
- uniform lowp vec4 patternColor; \n\
- uniform sampler2D imageTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- return patternColor * (1.0 - texture2D(imageTexture, textureCoords).r); \n\
- }\n";
-
-static const char* const qglslNonPremultipliedImageSrcFragmentShader = "\n\
- varying highp vec2 textureCoords; \n\
- uniform sampler2D imageTexture; \n\
- lowp vec4 srcPixel() \n\
- { \n\
- lowp vec4 sample = texture2D(imageTexture, textureCoords); \n\
- sample.rgb = sample.rgb * sample.a; \n\
- return sample; \n\
- }\n";
-
-static const char* const qglslShockingPinkSrcFragmentShader = "\n\
- lowp vec4 srcPixel() \n\
- { \n\
- return vec4(0.98, 0.06, 0.75, 1.0); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_ImageArrays = "\n\
- varying lowp float opacity; \n\
- lowp vec4 srcPixel(); \n\
- void main() \n\
- { \n\
- gl_FragColor = srcPixel() * opacity; \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_CMO = "\n\
- uniform lowp float globalOpacity; \n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 applyMask(lowp vec4); \n\
- lowp vec4 compose(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = applyMask(compose(srcPixel()*globalOpacity))); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_CM = "\n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 applyMask(lowp vec4); \n\
- lowp vec4 compose(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = applyMask(compose(srcPixel())); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_MO = "\n\
- uniform lowp float globalOpacity; \n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 applyMask(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = applyMask(srcPixel()*globalOpacity); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_M = "\n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 applyMask(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = applyMask(srcPixel()); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_CO = "\n\
- uniform lowp float globalOpacity; \n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 compose(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = compose(srcPixel()*globalOpacity); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_C = "\n\
- lowp vec4 srcPixel(); \n\
- lowp vec4 compose(lowp vec4); \n\
- void main() \n\
- { \n\
- gl_FragColor = compose(srcPixel()); \n\
- }\n";
-
-static const char* const qglslMainFragmentShader_O = "\n\
- uniform lowp float globalOpacity; \n\
- lowp vec4 srcPixel(); \n\
- void main() \n\
- { \n\
- gl_FragColor = srcPixel()*globalOpacity; \n\
- }\n";
-
-static const char* const qglslMainFragmentShader = "\n\
- lowp vec4 srcPixel(); \n\
- void main() \n\
- { \n\
- gl_FragColor = srcPixel(); \n\
- }\n";
-
-static const char* const qglslMaskFragmentShader = "\n\
- varying highp vec2 textureCoords;\n\
- uniform sampler2D maskTexture;\n\
- lowp vec4 applyMask(lowp vec4 src) \n\
- {\n\
- lowp vec4 mask = texture2D(maskTexture, textureCoords); \n\
- return src * mask.a; \n\
- }\n";
-
-// For source over with subpixel antialiasing, the final color is calculated per component as follows
-// (.a is alpha component, .c is red, green or blue component):
-// alpha = src.a * mask.c * opacity
-// dest.c = dest.c * (1 - alpha) + src.c * alpha
-//
-// In the first pass, calculate: dest.c = dest.c * (1 - alpha) with blend funcs: zero, 1 - source color
-// In the second pass, calculate: dest.c = dest.c + src.c * alpha with blend funcs: one, one
-//
-// If source is a solid color (src is constant), only the first pass is needed, with blend funcs: constant, 1 - source color
-
-// For source composition with subpixel antialiasing, the final color is calculated per component as follows:
-// alpha = src.a * mask.c * opacity
-// dest.c = dest.c * (1 - mask.c) + src.c * alpha
-//
-
-static const char* const qglslRgbMaskFragmentShaderPass1 = "\n\
- varying highp vec2 textureCoords;\n\
- uniform sampler2D maskTexture;\n\
- lowp vec4 applyMask(lowp vec4 src) \n\
- { \n\
- lowp vec4 mask = texture2D(maskTexture, textureCoords); \n\
- return src.a * mask; \n\
- }\n";
-
-static const char* const qglslRgbMaskFragmentShaderPass2 = "\n\
- varying highp vec2 textureCoords;\n\
- uniform sampler2D maskTexture;\n\
- lowp vec4 applyMask(lowp vec4 src) \n\
- { \n\
- lowp vec4 mask = texture2D(maskTexture, textureCoords); \n\
- return src * mask; \n\
- }\n";
-
-/*
- Left to implement:
- RgbMaskFragmentShader,
- RgbMaskWithGammaFragmentShader,
-
- MultiplyCompositionModeFragmentShader,
- ScreenCompositionModeFragmentShader,
- OverlayCompositionModeFragmentShader,
- DarkenCompositionModeFragmentShader,
- LightenCompositionModeFragmentShader,
- ColorDodgeCompositionModeFragmentShader,
- ColorBurnCompositionModeFragmentShader,
- HardLightCompositionModeFragmentShader,
- SoftLightCompositionModeFragmentShader,
- DifferenceCompositionModeFragmentShader,
- ExclusionCompositionModeFragmentShader,
-*/
-
-QT_END_NAMESPACE
-
-#endif // GLGC_SHADER_SOURCE_H
diff --git a/src/opengl/gl2paintengineex/qglgradientcache.cpp b/src/opengl/gl2paintengineex/qglgradientcache.cpp
deleted file mode 100644
index fc5e236ca6..0000000000
--- a/src/opengl/gl2paintengineex/qglgradientcache.cpp
+++ /dev/null
@@ -1,225 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglgradientcache_p.h"
-#include <private/qdrawhelper_p.h>
-#include <private/qgl_p.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qrandom.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGL2GradientCacheWrapper
-{
-public:
- QGL2GradientCache *cacheForContext(const QGLContext *context) {
- QMutexLocker lock(&m_mutex);
- return m_resource.value<QGL2GradientCache>(context->contextHandle());
- }
-
-private:
- QOpenGLMultiGroupSharedResource m_resource;
- QMutex m_mutex;
-};
-
-Q_GLOBAL_STATIC(QGL2GradientCacheWrapper, qt_gradient_caches)
-
-QGL2GradientCache::QGL2GradientCache(QOpenGLContext *ctx)
- : QOpenGLSharedResource(ctx->shareGroup())
-{
-}
-
-QGL2GradientCache::~QGL2GradientCache()
-{
- cache.clear();
-}
-
-QGL2GradientCache *QGL2GradientCache::cacheForContext(const QGLContext *context)
-{
- return qt_gradient_caches()->cacheForContext(context);
-}
-
-void QGL2GradientCache::invalidateResource()
-{
- QMutexLocker lock(&m_mutex);
- cache.clear();
-}
-
-void QGL2GradientCache::freeResource(QOpenGLContext *)
-{
- cleanCache();
-}
-
-void QGL2GradientCache::cleanCache()
-{
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- QMutexLocker lock(&m_mutex);
- QGLGradientColorTableHash::const_iterator it = cache.constBegin();
- for (; it != cache.constEnd(); ++it) {
- const CacheInfo &cache_info = it.value();
- funcs->glDeleteTextures(1, &cache_info.texId);
- }
- cache.clear();
-}
-
-GLuint QGL2GradientCache::getBuffer(const QGradient &gradient, qreal opacity)
-{
- QMutexLocker lock(&m_mutex);
- quint64 hash_val = 0;
-
- const QGradientStops stops = gradient.stops();
- for (int i = 0; i < stops.size() && i <= 2; i++)
- hash_val += stops[i].second.rgba();
-
- QGLGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
-
- if (it == cache.constEnd())
- return addCacheElement(hash_val, gradient, opacity);
- else {
- do {
- const CacheInfo &cache_info = it.value();
- if (cache_info.stops == stops && cache_info.opacity == opacity
- && cache_info.interpolationMode == gradient.interpolationMode())
- {
- return cache_info.texId;
- }
- ++it;
- } while (it != cache.constEnd() && it.key() == hash_val);
- // an exact match for these stops and opacity was not found, create new cache
- return addCacheElement(hash_val, gradient, opacity);
- }
-}
-
-
-GLuint QGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity)
-{
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- if (cache.size() == maxCacheSize()) {
- int elem_to_remove = QRandomGenerator::global()->bounded(maxCacheSize());
- quint64 key = cache.keys()[elem_to_remove];
-
- // need to call glDeleteTextures on each removed cache entry:
- QGLGradientColorTableHash::const_iterator it = cache.constFind(key);
- do {
- funcs->glDeleteTextures(1, &it.value().texId);
- } while (++it != cache.constEnd() && it.key() == key);
- cache.remove(key); // may remove more than 1, but OK
- }
-
- 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);
- return cache.insert(hash_val, cache_entry).value().texId;
-}
-
-
-// GL's expects pixels in RGBA (when using GL_RGBA), bin-endian (ABGR on x86).
-// Qt always stores in ARGB reguardless of the byte-order the mancine uses.
-static inline uint qtToGlColor(uint c)
-{
- uint o;
-#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
- o = (c & 0xff00ff00) // alpha & green already in the right place
- | ((c >> 16) & 0x000000ff) // red
- | ((c << 16) & 0x00ff0000); // blue
-#else //Q_BIG_ENDIAN
- o = (c << 8)
- | ((c >> 24) & 0x000000ff);
-#endif // Q_BYTE_ORDER
- return o;
-}
-
-//TODO: Let GL generate the texture using an FBO
-void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
-{
- int pos = 0;
- const QGradientStops s = gradient.stops();
- bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
-
- uint alpha = qRound(opacity * 256);
- // Qt LIES! It returns ARGB (on little-endian AND on big-endian)
- uint current_color = ARGB_COMBINE_ALPHA(s[0].second.rgba(), alpha);
- qreal incr = 1.0 / qreal(size);
- qreal fpos = 1.5 * incr;
- colorTable[pos++] = qtToGlColor(qPremultiply(current_color));
-
- while (fpos <= s.first().first) {
- colorTable[pos] = colorTable[pos - 1];
- pos++;
- fpos += incr;
- }
-
- if (colorInterpolation)
- current_color = qPremultiply(current_color);
-
- const int sLast = s.size() - 1;
- for (int i = 0; i < sLast; ++i) {
- qreal delta = 1/(s[i+1].first - s[i].first);
- uint next_color = ARGB_COMBINE_ALPHA(s[i + 1].second.rgba(), 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] = qtToGlColor(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
- else
- colorTable[pos] = qtToGlColor(qPremultiply(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist)));
- ++pos;
- fpos += incr;
- }
- current_color = next_color;
- }
-
- Q_ASSERT(s.size() > 0);
-
- uint last_color = qtToGlColor(qPremultiply(ARGB_COMBINE_ALPHA(s[sLast].second.rgba(), 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;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qglgradientcache_p.h b/src/opengl/gl2paintengineex/qglgradientcache_p.h
deleted file mode 100644
index 3c9da982e9..0000000000
--- a/src/opengl/gl2paintengineex/qglgradientcache_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLGRADIENTCACHE_P_H
-#define QGLGRADIENTCACHE_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 <QMultiHash>
-#include <QObject>
-#include <QtOpenGL/QtOpenGL>
-#include <private/qgl_p.h>
-#include <QtCore/qmutex.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGL2GradientCache : public QOpenGLSharedResource
-{
- struct CacheInfo
- {
- inline CacheInfo(QGradientStops s, qreal op, QGradient::InterpolationMode mode) :
- stops(s), opacity(op), interpolationMode(mode) {}
-
- GLuint texId;
- QGradientStops stops;
- qreal opacity;
- QGradient::InterpolationMode interpolationMode;
- };
-
- typedef QMultiHash<quint64, CacheInfo> QGLGradientColorTableHash;
-
-public:
- static QGL2GradientCache *cacheForContext(const QGLContext *context);
-
- QGL2GradientCache(QOpenGLContext *);
- ~QGL2GradientCache();
-
- GLuint getBuffer(const QGradient &gradient, qreal opacity);
- inline int paletteSize() const { return 1024; }
-
- void invalidateResource() override;
- void freeResource(QOpenGLContext *ctx) override;
-
-private:
- inline int maxCacheSize() const { return 60; }
- inline void generateGradientColorTable(const QGradient& gradient,
- uint *colorTable,
- int size, qreal opacity) const;
- GLuint addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity);
- void cleanCache();
-
- QGLGradientColorTableHash cache;
- QMutex m_mutex;
-};
-
-QT_END_NAMESPACE
-
-#endif // QGLGRADIENTCACHE_P_H
diff --git a/src/opengl/gl2paintengineex/qglshadercache_p.h b/src/opengl/gl2paintengineex/qglshadercache_p.h
deleted file mode 100644
index 4204e3e256..0000000000
--- a/src/opengl/gl2paintengineex/qglshadercache_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QGLSHADERCACHE_P_H
-#define QGLSHADERCACHE_P_H
-
-#include <QtCore/qglobal.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QGLShaderProgram;
-class QGLContext;
-
-class CachedShader
-{
-public:
- inline CachedShader(const QByteArray &, const QByteArray &)
- {}
-
- inline bool isCached()
- {
- return false;
- }
-
- inline bool load(QGLShaderProgram *, const QGLContext *)
- {
- return false;
- }
-
- inline bool store(QGLShaderProgram *, const QGLContext *)
- {
- return false;
- }
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp
deleted file mode 100644
index 2546f6dc13..0000000000
--- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp
+++ /dev/null
@@ -1,2515 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*
- When the active program changes, we need to update it's uniforms.
- We could track state for each program and only update stale uniforms
- - Could lead to lots of overhead if there's a lot of programs
- We could update all the uniforms when the program changes
- - Could end up updating lots of uniforms which don't need updating
-
- Updating uniforms should be cheap, so the overhead of updating up-to-date
- uniforms should be minimal. It's also less complex.
-
- Things which _may_ cause a different program to be used:
- - Change in brush/pen style
- - Change in painter opacity
- - Change in composition mode
-
- Whenever we set a mode on the shader manager - it needs to tell us if it had
- to switch to a different program.
-
- The shader manager should only switch when we tell it to. E.g. if we set a new
- brush style and then switch to transparent painter, we only want it to compile
- and use the correct program when we really need it.
-*/
-
-// #define QT_OPENGL_CACHE_AS_VBOS
-
-#include "qglgradientcache_p.h"
-#include "qpaintengineex_opengl2_p.h"
-
-#include <string.h> //for memcpy
-#include <qmath.h>
-
-#include <private/qgl_p.h>
-#include <private/qpaintengineex_p.h>
-#include <QPaintEngine>
-#include <private/qpainter_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qdatabuffer_p.h>
-#include <private/qstatictext_p.h>
-#include <QtGui/private/qtriangulator_p.h>
-
-#include "qglengineshadermanager_p.h"
-#include "qgl2pexvertexarray_p.h"
-#include "qtextureglyphcache_gl_p.h"
-
-#include <QDebug>
-
-#ifndef QT_OPENGL_ES_2
-# include <qopenglfunctions_1_1.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-
-
-Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
-
-////////////////////////////////// Private Methods //////////////////////////////////////////
-
-QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
-{
- delete shaderManager;
-
- while (pathCaches.size()) {
- QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
- e->cleanup(e->engine, e->data);
- e->data = 0;
- e->engine = 0;
- }
-
- if (elementIndicesVBOId != 0) {
- glDeleteBuffers(1, &elementIndicesVBOId);
- elementIndicesVBOId = 0;
- }
-}
-
-void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
-{
-// glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
- if (id != GLuint(-1) && id == lastTextureUsed)
- return;
-
- lastTextureUsed = id;
-
- if (smoothPixmapTransform) {
- glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- } else {
- glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- }
- glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
- glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
-}
-
-
-inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
-{
- qreal alpha = c.alphaF() * opacity;
- c.setAlphaF(alpha);
- c.setRedF(c.redF() * alpha);
- c.setGreenF(c.greenF() * alpha);
- c.setBlueF(c.blueF() * alpha);
- return c;
-}
-
-
-void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
-{
- if (qbrush_fast_equals(currentBrush, brush))
- return;
-
- const Qt::BrushStyle newStyle = qbrush_style(brush);
- Q_ASSERT(newStyle != Qt::NoBrush);
-
- currentBrush = brush;
- if (!currentBrushPixmap.isNull())
- currentBrushPixmap = QPixmap();
- brushUniformsDirty = true; // All brushes have at least one uniform
-
- if (newStyle > Qt::SolidPattern)
- brushTextureDirty = true;
-
- if (currentBrush.style() == Qt::TexturePattern
- && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
- {
- shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
- } else {
- shaderManager->setSrcPixelType(newStyle);
- }
- shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
-}
-
-
-void QGL2PaintEngineExPrivate::useSimpleShader()
-{
- shaderManager->useSimpleProgram();
-
- if (matrixDirty)
- updateMatrix();
-}
-
-// ####TODO Properly #ifdef this class to use #define symbols actually defined
-// by OpenGL/ES includes
-#ifndef GL_MIRRORED_REPEAT_IBM
-#define GL_MIRRORED_REPEAT_IBM 0x8370
-#endif
-
-void QGL2PaintEngineExPrivate::updateBrushTexture()
-{
- Q_Q(QGL2PaintEngineEx);
-// qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
- Qt::BrushStyle style = currentBrush.style();
-
- if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
- // Get the image data for the pattern
- QImage texImage = qt_imageForBrush(style, false);
-
- glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
- ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
- updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
- }
- else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
- // Gradiant brush: All the gradiants use the same texture
-
- const QGradient* g = currentBrush.gradient();
-
- // We apply global opacity in the fragment shaders, so we always pass 1.0
- // for opacity to the cache.
- GLuint texId = QGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
-
- glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
- glBindTexture(GL_TEXTURE_2D, texId);
-
- if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
- updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
- else if (g->spread() == QGradient::ReflectSpread)
- updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, q->state()->renderHints & QPainter::SmoothPixmapTransform);
- else
- updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
- }
- else if (style == Qt::TexturePattern) {
- currentBrushPixmap = currentBrush.texture();
-
- int max_texture_size = ctx->d_func()->maxTextureSize();
- if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
- currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
-
- GLuint wrapMode = GL_REPEAT;
- if (ctx->contextHandle()->isOpenGLES()) {
- // OpenGL ES does not support GL_REPEAT wrap modes for NPOT textures. So instead,
- // we emulate GL_REPEAT by only taking the fractional part of the texture coords
- // in the qopenglslTextureBrushSrcFragmentShader program.
- wrapMode = GL_CLAMP_TO_EDGE;
- }
-
- glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
- QGLTexture *tex = ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
- QGLContext::InternalBindOption |
- QGLContext::CanFlipNativePixmapBindOption);
- updateTextureFilter(GL_TEXTURE_2D, wrapMode, q->state()->renderHints & QPainter::SmoothPixmapTransform);
- textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
- }
- brushTextureDirty = false;
-}
-
-
-void QGL2PaintEngineExPrivate::updateBrushUniforms()
-{
-// qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
- Qt::BrushStyle style = currentBrush.style();
-
- if (style == Qt::NoBrush)
- return;
-
- QTransform brushQTransform = currentBrush.transform();
-
- if (style == Qt::SolidPattern) {
- QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::FragmentColor), col);
- }
- else {
- // All other brushes have a transform and thus need the translation point:
- QPointF translationPoint;
-
- if (style <= Qt::DiagCrossPattern) {
- QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
-
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
-
- QVector2D halfViewportSize(width*0.5, height*0.5);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
- }
- else if (style == Qt::LinearGradientPattern) {
- const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
-
- QPointF realStart = g->start();
- QPointF realFinal = g->finalStop();
- translationPoint = realStart;
-
- QPointF l = realFinal - realStart;
-
- QVector3D linearData(
- l.x(),
- l.y(),
- 1.0f / (l.x() * l.x() + l.y() * l.y())
- );
-
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::LinearData), linearData);
-
- QVector2D halfViewportSize(width*0.5, height*0.5);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
- }
- else if (style == Qt::ConicalGradientPattern) {
- const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
- translationPoint = g->center();
-
- GLfloat angle = -qDegreesToRadians(g->angle());
-
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Angle), angle);
-
- QVector2D halfViewportSize(width*0.5, height*0.5);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
- }
- else if (style == Qt::RadialGradientPattern) {
- const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
- QPointF realCenter = g->center();
- QPointF realFocal = g->focalPoint();
- qreal realRadius = g->centerRadius() - g->focalRadius();
- translationPoint = realFocal;
-
- QPointF fmp = realCenter - realFocal;
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp), fmp);
-
- GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Inverse2Fmp2MRadius2),
- GLfloat(1.0 / (2.0*fmp2_m_radius2)));
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::SqrFr),
- GLfloat(g->focalRadius() * g->focalRadius()));
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BRadius),
- GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
- g->focalRadius(),
- g->centerRadius() - g->focalRadius());
-
- QVector2D halfViewportSize(width*0.5, height*0.5);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
- }
- else if (style == Qt::TexturePattern) {
- const QPixmap& texPixmap = currentBrush.texture();
-
- if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
- QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
- }
-
- QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
-
- QVector2D halfViewportSize(width*0.5, height*0.5);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
- }
- else
- qWarning("QGL2PaintEngineEx: Unimplemented fill style");
-
- const QPointF &brushOrigin = q->state()->brushOrigin;
- QTransform matrix = q->state()->matrix;
- matrix.translate(brushOrigin.x(), brushOrigin.y());
-
- QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
- qreal m22 = -1;
- qreal dy = height;
- if (device->isFlipped()) {
- m22 = 1;
- dy = 0;
- }
- QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
- QTransform inv_matrix;
- if (style == Qt::TexturePattern && textureInvertedY == -1)
- inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
- else
- inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
-
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTransform), inv_matrix);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
- }
- brushUniformsDirty = false;
-}
-
-
-// This assumes the shader manager has already setup the correct shader program
-void QGL2PaintEngineExPrivate::updateMatrix()
-{
-// qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
-
- const QTransform& transform = q->state()->matrix;
-
- // The projection matrix converts from Qt's coordinate system to GL's coordinate system
- // * GL's viewport is 2x2, Qt's is width x height
- // * GL has +y -> -y going from bottom -> top, Qt is the other way round
- // * GL has [0,0] in the center, Qt has it in the top-left
- //
- // This results in the Projection matrix below, which is multiplied by the painter's
- // transformation matrix, as shown below:
- //
- // Projection Matrix Painter Transform
- // ------------------------------------------------ ------------------------
- // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
- // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
- // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
- // ------------------------------------------------ ------------------------
- //
- // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
-
- const GLfloat wfactor = 2.0f / width;
- GLfloat hfactor = -2.0f / height;
-
- GLfloat dx = transform.dx();
- GLfloat dy = transform.dy();
-
- if (device->isFlipped()) {
- hfactor *= -1;
- dy -= height;
- }
-
- // Non-integer translates can have strange effects for some rendering operations such as
- // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
- if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
- // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
- dx = std::ceil(dx - 0.5f);
- dy = std::ceil(dy - 0.5f);
- }
- pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
- pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
- pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
- pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
- pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
- pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
- pmvMatrix[0][2] = transform.m13();
- pmvMatrix[1][2] = transform.m23();
- pmvMatrix[2][2] = transform.m33();
-
- // 1/10000 == 0.0001, so we have good enough res to cover curves
- // that span the entire widget...
- inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
- qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
- qreal(0.0001));
-
- matrixDirty = false;
- matrixUniformDirty = true;
-
- // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
- // need to do this once for every matrix change and persists across all shader programs.
- glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
- glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
- glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
-
- dasher.setInvScale(inverseScale);
- stroker.setInvScale(inverseScale);
-}
-
-
-void QGL2PaintEngineExPrivate::updateCompositionMode()
-{
- // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
- // composition modes look odd.
-// qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
- switch(q->state()->composition_mode) {
- case QPainter::CompositionMode_SourceOver:
- glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_DestinationOver:
- glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
- break;
- case QPainter::CompositionMode_Clear:
- glBlendFunc(GL_ZERO, GL_ZERO);
- break;
- case QPainter::CompositionMode_Source:
- glBlendFunc(GL_ONE, GL_ZERO);
- break;
- case QPainter::CompositionMode_Destination:
- glBlendFunc(GL_ZERO, GL_ONE);
- break;
- case QPainter::CompositionMode_SourceIn:
- glBlendFunc(GL_DST_ALPHA, GL_ZERO);
- break;
- case QPainter::CompositionMode_DestinationIn:
- glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_SourceOut:
- glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
- break;
- case QPainter::CompositionMode_DestinationOut:
- glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_SourceAtop:
- glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_DestinationAtop:
- glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_Xor:
- glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case QPainter::CompositionMode_Plus:
- glBlendFunc(GL_ONE, GL_ONE);
- break;
- default:
- qWarning("Unsupported composition mode");
- break;
- }
-
- compositionModeDirty = false;
-}
-
-static inline void setCoords(GLfloat *coords, const QGLRect &rect)
-{
- coords[0] = rect.left;
- coords[1] = rect.top;
- coords[2] = rect.right;
- coords[3] = rect.top;
- coords[4] = rect.right;
- coords[5] = rect.bottom;
- coords[6] = rect.left;
- coords[7] = rect.bottom;
-}
-
-void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
-{
- // Setup for texture drawing
- currentBrush = noBrush;
- shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
-
- if (snapToPixelGrid) {
- snapToPixelGrid = false;
- matrixDirty = true;
- }
-
- if (prepareForDraw(opaque))
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
-
- if (pattern) {
- QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
- }
-
- GLfloat dx = 1.0 / textureSize.width();
- GLfloat dy = 1.0 / textureSize.height();
-
- QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
-
- setCoords(staticVertexCoordinateArray, dest);
- setCoords(staticTextureCoordinateArray, srcTextureRect);
-
- glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-}
-
-void QGL2PaintEngineEx::beginNativePainting()
-{
- Q_D(QGL2PaintEngineEx);
- ensureActive();
- d->transferMode(BrushDrawingMode);
-
- d->nativePaintingActive = true;
-
- d->glUseProgram(0);
-
- // Disable all the vertex attribute arrays:
- for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
- d->glDisableVertexAttribArray(i);
-
-#ifndef QT_OPENGL_ES_2
- if (!d->ctx->contextHandle()->isOpenGLES()) {
- const QGLContext *ctx = d->ctx;
- const QGLFormat &fmt = d->device->format();
- if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
- || (fmt.majorVersion() == 3 && fmt.minorVersion() == 1 && ctx->contextHandle()->hasExtension(QByteArrayLiteral("GL_ARB_compatibility")))
- || fmt.profile() == QGLFormat::CompatibilityProfile)
- {
- // be nice to people who mix OpenGL 1.x code with QPainter commands
- // by setting modelview and projection matrices to mirror the GL 1
- // paint engine
- const QTransform& mtx = state()->matrix;
-
- float mv_matrix[4][4] =
- {
- { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
- { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
- { 0, 0, 1, 0 },
- { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
- };
-
- const QSize sz = d->device->size();
-
- QOpenGLFunctions_1_1 *gl1funcs = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_1_1>();
- gl1funcs->initializeOpenGLFunctions();
-
- gl1funcs->glMatrixMode(GL_PROJECTION);
- gl1funcs->glLoadIdentity();
- gl1funcs->glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
-
- gl1funcs->glMatrixMode(GL_MODELVIEW);
- gl1funcs->glLoadMatrixf(&mv_matrix[0][0]);
- }
- }
-#endif
-
- d->lastTextureUsed = GLuint(-1);
- d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
- d->resetGLState();
-
- d->shaderManager->setDirty();
-
- d->needsSync = true;
-}
-
-void QGL2PaintEngineExPrivate::resetGLState()
-{
- glDisable(GL_BLEND);
- glActiveTexture(GL_TEXTURE0);
- glDisable(GL_STENCIL_TEST);
- glDisable(GL_DEPTH_TEST);
- glDisable(GL_SCISSOR_TEST);
- glDepthMask(true);
- glDepthFunc(GL_LESS);
- glClearDepthf(1);
- glStencilMask(0xff);
- glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
- glStencilFunc(GL_ALWAYS, 0, 0xff);
- ctx->d_func()->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
- ctx->d_func()->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
- ctx->d_func()->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
-#ifndef QT_OPENGL_ES_2
- if (!ctx->contextHandle()->isOpenGLES()) {
- // gl_Color, corresponding to vertex attribute 3, may have been changed
- float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
- glVertexAttrib4fv(3, color);
- }
-#endif
-}
-
-bool QGL2PaintEngineExPrivate::resetOpenGLContextActiveEngine()
-{
- QOpenGLContext *guiGlContext = ctx->contextHandle();
- QOpenGLContextPrivate *guiGlContextPrivate =
- guiGlContext ? QOpenGLContextPrivate::get(guiGlContext) : 0;
-
- if (guiGlContextPrivate && guiGlContextPrivate->active_engine) {
- ctx->d_func()->refreshCurrentFbo();
- guiGlContextPrivate->active_engine = 0;
- return true;
- }
-
- return false;
-}
-
-void QGL2PaintEngineEx::endNativePainting()
-{
- Q_D(QGL2PaintEngineEx);
- d->needsSync = true;
- d->nativePaintingActive = false;
-}
-
-void QGL2PaintEngineEx::invalidateState()
-{
- Q_D(QGL2PaintEngineEx);
- d->needsSync = true;
-}
-
-bool QGL2PaintEngineEx::isNativePaintingActive() const {
- Q_D(const QGL2PaintEngineEx);
- return d->nativePaintingActive;
-}
-
-bool QGL2PaintEngineEx::shouldDrawCachedGlyphs(QFontEngine *fontEngine, const QTransform &t) const
-{
- // The paint engine does not support projected cached glyph drawing
- if (t.type() == QTransform::TxProject)
- return false;
-
- // The font engine might not support filling the glyph cache
- // with the given transform applied, in which case we need to
- // fall back to the QPainterPath code-path.
- if (!fontEngine->supportsTransformation(t)) {
- // Except that drawing paths is slow, so for scales between
- // 0.5 and 2.0 we leave the glyph cache untransformed and deal
- // with the transform ourselves when painting, resulting in
- // drawing 1x cached glyphs with a smooth-scale.
- float det = t.determinant();
- if (det >= 0.25f && det <= 4.f) {
- // Assuming the baseclass still agrees
- return QPaintEngineEx::shouldDrawCachedGlyphs(fontEngine, t);
- }
-
- return false; // Fall back to path-drawing
- }
-
- return QPaintEngineEx::shouldDrawCachedGlyphs(fontEngine, t);
-}
-
-void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
-{
- if (newMode == mode)
- return;
-
- if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
- lastTextureUsed = GLuint(-1);
- }
-
- if (newMode == TextDrawingMode) {
- shaderManager->setHasComplexGeometry(true);
- } else {
- shaderManager->setHasComplexGeometry(false);
- }
-
- if (newMode == ImageDrawingMode) {
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
- setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
- }
-
- if (newMode == ImageArrayDrawingMode) {
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
- setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
- setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
- }
-
- // This needs to change when we implement high-quality anti-aliasing...
- if (newMode != TextDrawingMode)
- shaderManager->setMaskType(QGLEngineShaderManager::NoMask);
-
- mode = newMode;
-}
-
-struct QGL2PEVectorPathCache
-{
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- GLuint vbo;
- GLuint ibo;
-#else
- float *vertices;
- void *indices;
-#endif
- int vertexCount;
- int indexCount;
- GLenum primitiveType;
- qreal iscale;
- QVertexIndexVector::Type indexType;
-};
-
-void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
-{
- QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
- static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
- if (c->ibo)
- d->unusedIBOSToClean << c->ibo;
-#else
- Q_UNUSED(engine);
- free(c->vertices);
- free(c->indices);
-#endif
- delete c;
-}
-
-// Assumes everything is configured for the brush you want to use
-void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
-{
- transferMode(BrushDrawingMode);
-
- if (snapToPixelGrid) {
- snapToPixelGrid = false;
- matrixDirty = true;
- }
-
- // Might need to call updateMatrix to re-calculate inverseScale
- if (matrixDirty)
- updateMatrix();
-
- const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
-
- // Check to see if there's any hints
- if (path.shape() == QVectorPath::RectangleHint) {
- QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
- prepareForDraw(currentBrush.isOpaque());
- composite(rect);
- } else if (path.isConvex()) {
-
- if (path.isCacheable()) {
- QVectorPath::CacheEntry *data = path.lookupCacheData(q);
- QGL2PEVectorPathCache *cache;
-
- bool updateCache = false;
-
- if (data) {
- cache = (QGL2PEVectorPathCache *) data->data;
- // Check if scale factor is exceeded for curved paths and generate curves if so...
- if (path.isCurved()) {
- qreal scaleFactor = cache->iscale / inverseScale;
- if (scaleFactor < 0.5 || scaleFactor > 2.0) {
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glDeleteBuffers(1, &cache->vbo);
- cache->vbo = 0;
- Q_ASSERT(cache->ibo == 0);
-#else
- free(cache->vertices);
- Q_ASSERT(cache->indices == 0);
-#endif
- updateCache = true;
- }
- }
- } else {
- cache = new QGL2PEVectorPathCache;
- data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
- updateCache = true;
- }
-
- // Flatten the path at the current scale factor and fill it into the cache struct.
- if (updateCache) {
- vertexCoordinateArray.clear();
- vertexCoordinateArray.addPath(path, inverseScale, false);
- int vertexCount = vertexCoordinateArray.vertexCount();
- int floatSizeInBytes = vertexCount * 2 * sizeof(float);
- cache->vertexCount = vertexCount;
- cache->indexCount = 0;
- cache->primitiveType = GL_TRIANGLE_FAN;
- cache->iscale = inverseScale;
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glGenBuffers(1, &cache->vbo);
- glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
- glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
- cache->ibo = 0;
-#else
- cache->vertices = (float *) malloc(floatSizeInBytes);
- memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
- cache->indices = 0;
-#endif
- }
-
- prepareForDraw(currentBrush.isOpaque());
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
-#else
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
-#endif
- glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
-
- } else {
- // printf(" - Marking path as cachable...\n");
- // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
- path.makeCacheable();
- vertexCoordinateArray.clear();
- vertexCoordinateArray.addPath(path, inverseScale, false);
- prepareForDraw(currentBrush.isOpaque());
- drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
- }
-
- } else {
- bool useCache = path.isCacheable();
- if (useCache) {
- QRectF bbox = path.controlPointRect();
- // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
- useCache &= (bbox.left() > -0x8000 * inverseScale)
- && (bbox.right() < 0x8000 * inverseScale)
- && (bbox.top() > -0x8000 * inverseScale)
- && (bbox.bottom() < 0x8000 * inverseScale);
- }
-
- if (useCache) {
- QVectorPath::CacheEntry *data = path.lookupCacheData(q);
- QGL2PEVectorPathCache *cache;
-
- bool updateCache = false;
-
- if (data) {
- cache = (QGL2PEVectorPathCache *) data->data;
- // Check if scale factor is exceeded for curved paths and generate curves if so...
- if (path.isCurved()) {
- qreal scaleFactor = cache->iscale / inverseScale;
- if (scaleFactor < 0.5 || scaleFactor > 2.0) {
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glDeleteBuffers(1, &cache->vbo);
- glDeleteBuffers(1, &cache->ibo);
-#else
- free(cache->vertices);
- free(cache->indices);
-#endif
- updateCache = true;
- }
- }
- } else {
- cache = new QGL2PEVectorPathCache;
- data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
- updateCache = true;
- }
-
- // Flatten the path at the current scale factor and fill it into the cache struct.
- if (updateCache) {
- QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
- cache->vertexCount = polys.vertices.size() / 2;
- cache->indexCount = polys.indices.size();
- cache->primitiveType = GL_TRIANGLES;
- cache->iscale = inverseScale;
- cache->indexType = polys.indices.type();
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glGenBuffers(1, &cache->vbo);
- glGenBuffers(1, &cache->ibo);
- glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
-
- if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
- else
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
-
- QVarLengthArray<float> vertices(polys.vertices.size());
- for (int i = 0; i < polys.vertices.size(); ++i)
- vertices[i] = float(inverseScale * polys.vertices.at(i));
- glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
-#else
- cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
- if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
- cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
- memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
- } else {
- cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
- memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
- }
- for (int i = 0; i < polys.vertices.size(); ++i)
- cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
-#endif
- }
-
- prepareForDraw(currentBrush.isOpaque());
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
- if (cache->indexType == QVertexIndexVector::UnsignedInt)
- glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
- else
- glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
-#else
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
- if (cache->indexType == QVertexIndexVector::UnsignedInt)
- glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
- else
- glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
-#endif
-
- } else {
- // printf(" - Marking path as cachable...\n");
- // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
- path.makeCacheable();
-
- if (!device->format().stencil()) {
- // If there is no stencil buffer, triangulate the path instead.
-
- QRectF bbox = path.controlPointRect();
- // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
- bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
- && (bbox.right() < 0x8000 * inverseScale)
- && (bbox.top() > -0x8000 * inverseScale)
- && (bbox.bottom() < 0x8000 * inverseScale);
- if (withinLimits) {
- QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
-
- QVarLengthArray<float> vertices(polys.vertices.size());
- for (int i = 0; i < polys.vertices.size(); ++i)
- vertices[i] = float(inverseScale * polys.vertices.at(i));
-
- prepareForDraw(currentBrush.isOpaque());
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
- if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
- glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
- else
- glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
- } else {
- // We can't handle big, concave painter paths with OpenGL without stencil buffer.
- qWarning("Painter path exceeds +/-32767 pixels.");
- }
- return;
- }
-
- // The path is too complicated & needs the stencil technique
- vertexCoordinateArray.clear();
- vertexCoordinateArray.addPath(path, inverseScale, false);
-
- fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
-
- glStencilMask(0xff);
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
-
- if (q->state()->clipTestEnabled) {
- // Pass when high bit is set, replace stencil value with current clip
- glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
- } else if (path.hasWindingFill()) {
- // Pass when any bit is set, replace stencil value with 0
- glStencilFunc(GL_NOTEQUAL, 0, 0xff);
- } else {
- // Pass when high bit is set, replace stencil value with 0
- glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
- }
- prepareForDraw(currentBrush.isOpaque());
-
- // Stencil the brush onto the dest buffer
- composite(vertexCoordinateArray.boundingRect());
- glStencilMask(0);
- updateClipScissorTest();
- }
- }
-}
-
-
-void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
- int count,
- int *stops,
- int stopCount,
- const QGLRect &bounds,
- StencilFillMode mode)
-{
- Q_ASSERT(count || stops);
-
-// qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
- glStencilMask(0xff); // Enable stencil writes
-
- if (dirtyStencilRegion.intersects(currentScissorBounds)) {
- const QRegion clearRegion = dirtyStencilRegion.intersected(currentScissorBounds);
- glClearStencil(0); // Clear to zero
- for (const QRect &rect : clearRegion) {
-#ifndef QT_GL_NO_SCISSOR_TEST
- setScissor(rect);
-#endif
- glClear(GL_STENCIL_BUFFER_BIT);
- }
-
- dirtyStencilRegion -= currentScissorBounds;
-
-#ifndef QT_GL_NO_SCISSOR_TEST
- updateClipScissorTest();
-#endif
- }
-
- glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
- useSimpleShader();
- glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
-
- if (mode == WindingFillMode) {
- Q_ASSERT(stops && !count);
- if (q->state()->clipTestEnabled) {
- // Flatten clip values higher than current clip, and set high bit to match current clip
- glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
- composite(bounds);
-
- glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
- } else if (!stencilClean) {
- // Clear stencil buffer within bounding rect
- glStencilFunc(GL_ALWAYS, 0, 0xff);
- glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
- composite(bounds);
- }
-
- // Inc. for front-facing triangle
- glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
- // Dec. for back-facing "holes"
- glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
- glStencilMask(~GL_STENCIL_HIGH_BIT);
- drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
-
- if (q->state()->clipTestEnabled) {
- // Clear high bit of stencil outside of path
- glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
- glStencilMask(GL_STENCIL_HIGH_BIT);
- composite(bounds);
- }
- } else if (mode == OddEvenFillMode) {
- glStencilMask(GL_STENCIL_HIGH_BIT);
- glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
- drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
-
- } else { // TriStripStrokeFillMode
- Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
- glStencilMask(GL_STENCIL_HIGH_BIT);
-#if 0
- glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
- glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
-#else
-
- glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
- if (q->state()->clipTestEnabled) {
- glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
- ~GL_STENCIL_HIGH_BIT);
- } else {
- glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
- }
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
- glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
-#endif
- }
-
- // Enable color writes & disable stencil writes
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-}
-
-/*
- If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
- restore the stencil buffer to a pristine state. The current clip region
- is set to 1, and the rest to 0.
-*/
-void QGL2PaintEngineExPrivate::resetClipIfNeeded()
-{
- if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
- return;
-
- Q_Q(QGL2PaintEngineEx);
-
- useSimpleShader();
- glEnable(GL_STENCIL_TEST);
- glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-
- QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
- QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
-
- // Set high bit on clip region
- glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
- glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
- glStencilMask(GL_STENCIL_HIGH_BIT);
- composite(rect);
-
- // Reset clipping to 1 and everything else to zero
- glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
- glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
- glStencilMask(0xff);
- composite(rect);
-
- q->state()->currentClip = 1;
- q->state()->canRestoreClip = false;
-
- maxClip = 1;
-
- glStencilMask(0x0);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-}
-
-bool QGL2PaintEngineExPrivate::prepareForCachedGlyphDraw(const QFontEngineGlyphCache &cache)
-{
- Q_Q(QGL2PaintEngineEx);
-
- Q_ASSERT(cache.transform().type() <= QTransform::TxScale);
-
- QTransform &transform = q->state()->matrix;
- transform.scale(1.0 / cache.transform().m11(), 1.0 / cache.transform().m22());
- bool ret = prepareForDraw(false);
- transform.scale(cache.transform().m11(), cache.transform().m22());
-
- return ret;
-}
-
-bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
-{
- if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
- updateBrushTexture();
-
- if (compositionModeDirty)
- updateCompositionMode();
-
- if (matrixDirty)
- updateMatrix();
-
- const bool stateHasOpacity = q->state()->opacity < 0.99f;
- if (q->state()->composition_mode == QPainter::CompositionMode_Source
- || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
- && srcPixelsAreOpaque && !stateHasOpacity))
- {
- glDisable(GL_BLEND);
- } else {
- glEnable(GL_BLEND);
- }
-
- QGLEngineShaderManager::OpacityMode opacityMode;
- if (mode == ImageArrayDrawingMode) {
- opacityMode = QGLEngineShaderManager::AttributeOpacity;
- } else {
- opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
- : QGLEngineShaderManager::NoOpacity;
- if (stateHasOpacity && (mode != ImageDrawingMode)) {
- // Using a brush
- bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
- (currentBrush.style() <= Qt::DiagCrossPattern);
-
- if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
- opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
- }
- }
- shaderManager->setOpacityMode(opacityMode);
-
- bool changed = shaderManager->useCorrectShaderProg();
- // If the shader program needs changing, we change it and mark all uniforms as dirty
- if (changed) {
- // The shader program has changed so mark all uniforms as dirty:
- brushUniformsDirty = true;
- opacityUniformDirty = true;
- matrixUniformDirty = true;
- translateZUniformDirty = true;
- }
-
- if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
- updateBrushUniforms();
-
- if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
- opacityUniformDirty = false;
- }
-
- if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
- pmvMatrix);
- matrixUniformDirty = false;
- }
-
- if (translateZUniformDirty && shaderManager->hasComplexGeometry()) {
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::TranslateZ),
- translateZ);
- translateZUniformDirty = false;
- }
-
- return changed;
-}
-
-void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
-{
- setCoords(staticVertexCoordinateArray, boundingRect);
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
- glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-}
-
-// Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
-void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
- GLenum primitive)
-{
- // Now setup the pointer to the vertex array:
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
-
- int previousStop = 0;
- for (int i=0; i<stopCount; ++i) {
- int stop = stops[i];
-/*
- qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
- for (int i=previousStop; i<stop; ++i)
- qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
-*/
- glDrawArrays(primitive, previousStop, stop - previousStop);
- previousStop = stop;
- }
-}
-
-/////////////////////////////////// Public Methods //////////////////////////////////////////
-
-QGL2PaintEngineEx::QGL2PaintEngineEx()
- : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
-{
-}
-
-QGL2PaintEngineEx::~QGL2PaintEngineEx()
-{
-}
-
-void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
-{
- Q_D(QGL2PaintEngineEx);
-
- if (qbrush_style(brush) == Qt::NoBrush)
- return;
- ensureActive();
- d->setBrush(brush);
- d->fill(path);
-}
-
-Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
-
-
-void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
-{
- Q_D(QGL2PaintEngineEx);
-
- const QBrush &penBrush = qpen_brush(pen);
- if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
- return;
-
- QGL2PaintEngineState *s = state();
- if (qt_pen_is_cosmetic(pen, s->renderHints) && !qt_scaleForTransform(s->transform(), 0)) {
- // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
- QPaintEngineEx::stroke(path, pen);
- return;
- }
-
- ensureActive();
- d->setBrush(penBrush);
- d->stroke(path, pen);
-}
-
-void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
-{
- const QGL2PaintEngineState *s = q->state();
- if (snapToPixelGrid) {
- snapToPixelGrid = false;
- matrixDirty = true;
- }
-
- const Qt::PenStyle penStyle = qpen_style(pen);
- const QBrush &penBrush = qpen_brush(pen);
- const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
-
- transferMode(BrushDrawingMode);
-
- // updateMatrix() is responsible for setting the inverse scale on
- // the strokers, so we need to call it here and not wait for
- // prepareForDraw() down below.
- updateMatrix();
-
- QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
- ? q->state()->rectangleClip
- : QRectF(0, 0, width, height));
-
- if (penStyle == Qt::SolidLine) {
- stroker.process(path, pen, clip, s->renderHints);
-
- } else { // Some sort of dash
- dasher.process(path, pen, clip, s->renderHints);
-
- QVectorPath dashStroke(dasher.points(),
- dasher.elementCount(),
- dasher.elementTypes());
- stroker.process(dashStroke, pen, clip, s->renderHints);
- }
-
- if (!stroker.vertexCount())
- return;
-
- if (opaque) {
- prepareForDraw(opaque);
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
- glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
-
-// QBrush b(Qt::green);
-// d->setBrush(&b);
-// d->prepareForDraw(true);
-// glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
-
- } else {
- qreal width = qpen_widthf(pen) / 2;
- if (width == 0)
- width = 0.5;
- qreal extra = pen.joinStyle() == Qt::MiterJoin
- ? qMax(pen.miterLimit() * width, width)
- : width;
-
- if (qt_pen_is_cosmetic(pen, s->renderHints))
- extra = extra * inverseScale;
-
- QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
-
- fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
- 0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
-
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
-
- // Pass when any bit is set, replace stencil value with 0
- glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
- prepareForDraw(false);
-
- // Stencil the brush onto the dest buffer
- composite(bounds);
-
- glStencilMask(0);
-
- updateClipScissorTest();
- }
-}
-
-void QGL2PaintEngineEx::penChanged() { }
-void QGL2PaintEngineEx::brushChanged() { }
-void QGL2PaintEngineEx::brushOriginChanged() { }
-
-void QGL2PaintEngineEx::opacityChanged()
-{
-// qDebug("QGL2PaintEngineEx::opacityChanged()");
- Q_D(QGL2PaintEngineEx);
- state()->opacityChanged = true;
-
- Q_ASSERT(d->shaderManager);
- d->brushUniformsDirty = true;
- d->opacityUniformDirty = true;
-}
-
-void QGL2PaintEngineEx::compositionModeChanged()
-{
-// qDebug("QGL2PaintEngineEx::compositionModeChanged()");
- Q_D(QGL2PaintEngineEx);
- state()->compositionModeChanged = true;
- d->compositionModeDirty = true;
-}
-
-void QGL2PaintEngineEx::renderHintsChanged()
-{
- Q_D(QGL2PaintEngineEx);
- state()->renderHintsChanged = true;
-
-#if !defined(QT_OPENGL_ES_2)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- if (!d->ctx->contextHandle()->isOpenGLES()) {
- if ((state()->renderHints & QPainter::Antialiasing)
-#if QT_DEPRECATED_SINCE(5, 14)
- || (state()->renderHints & QPainter::HighQualityAntialiasing)
-#endif
- )
- d->glEnable(GL_MULTISAMPLE);
- else
- d->glDisable(GL_MULTISAMPLE);
- }
-QT_WARNING_POP
-#endif
-
- d->lastTextureUsed = GLuint(-1);
- d->brushTextureDirty = true;
-// qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
-}
-
-void QGL2PaintEngineEx::transformChanged()
-{
- Q_D(QGL2PaintEngineEx);
- d->matrixDirty = true;
- state()->matrixChanged = true;
-}
-
-
-static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
-{
- return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
-}
-
-void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
-{
- Q_D(QGL2PaintEngineEx);
- QGLContext *ctx = d->ctx;
-
- int max_texture_size = ctx->d_func()->maxTextureSize();
- if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
- QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
-
- const qreal sx = scaled.width() / qreal(pixmap.width());
- const qreal sy = scaled.height() / qreal(pixmap.height());
-
- drawPixmap(dest, scaled, scaleRect(src, sx, sy));
- return;
- }
-
- ensureActive();
- d->transferMode(ImageDrawingMode);
-
- QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
-#ifdef QGL_USE_TEXTURE_POOL
- bindOptions |= QGLContext::TemporarilyCachedBindOption;
-#endif
-
- d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
- QGLTexture *texture =
- ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
-
- GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
- GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
- QGLRect srcRect(src.left(), top, src.right(), bottom);
-
- bool isBitmap = pixmap.isQBitmap();
- bool isOpaque = !isBitmap && !pixmap.hasAlpha();
-
- d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
- state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
- d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
-
- if (texture->options&QGLContext::TemporarilyCachedBindOption) {
- // pixmap was temporarily cached as a QImage texture by pooling system
- // and should be destroyed immediately
- QGLTextureCache::instance()->remove(ctx, texture->id);
- }
-}
-
-void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
- Qt::ImageConversionFlags)
-{
- Q_D(QGL2PaintEngineEx);
- QGLContext *ctx = d->ctx;
-
- int max_texture_size = ctx->d_func()->maxTextureSize();
- if (image.width() > max_texture_size || image.height() > max_texture_size) {
- QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
-
- const qreal sx = scaled.width() / qreal(image.width());
- const qreal sy = scaled.height() / qreal(image.height());
-
- drawImage(dest, scaled, scaleRect(src, sx, sy));
- return;
- }
-
- ensureActive();
- d->transferMode(ImageDrawingMode);
-
- d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
-
- QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
-#ifdef QGL_USE_TEXTURE_POOL
- bindOptions |= QGLContext::TemporarilyCachedBindOption;
-#endif
-
- QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
- GLuint id = texture->id;
-
- d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
- state()->renderHints & QPainter::SmoothPixmapTransform, id);
- d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
-
- if (texture->options&QGLContext::TemporarilyCachedBindOption) {
- // image was temporarily cached by texture pooling system
- // and should be destroyed immediately
- QGLTextureCache::instance()->remove(ctx, texture->id);
- }
-}
-
-void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
-{
- Q_D(QGL2PaintEngineEx);
-
- ensureActive();
-
- QPainterState *s = state();
-
- // don't try to cache huge fonts or vastly transformed fonts
- QFontEngine *fontEngine = textItem->fontEngine();
- if (shouldDrawCachedGlyphs(fontEngine, s->matrix)) {
-
- QFontEngine::GlyphFormat glyphFormat = fontEngine->glyphFormat != QFontEngine::Format_None
- ? fontEngine->glyphFormat : d->glyphCacheFormat;
-
- if (glyphFormat == QFontEngine::Format_A32) {
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
- || d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
- || (s->composition_mode != QPainter::CompositionMode_Source
- && s->composition_mode != QPainter::CompositionMode_SourceOver))
- {
- glyphFormat = QFontEngine::Format_A8;
- }
- }
-
- d->drawCachedGlyphs(glyphFormat, textItem);
- } else {
- QPaintEngineEx::drawStaticTextItem(textItem);
- }
-}
-
-bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
-{
- Q_D(QGL2PaintEngineEx);
- if (!d->shaderManager)
- return false;
-
- ensureActive();
- d->transferMode(ImageDrawingMode);
-
- d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
- d->glBindTexture(GL_TEXTURE_2D, textureId);
-
- QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
-
- d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
- state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
- d->drawTexture(dest, srcRect, size, false);
- return true;
-}
-
-void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
-{
- Q_D(QGL2PaintEngineEx);
-
- ensureActive();
- QGL2PaintEngineState *s = state();
-
- const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
-
- QTransform::TransformationType txtype = s->matrix.type();
-
- QFontEngine::GlyphFormat glyphFormat = ti.fontEngine->glyphFormat != QFontEngine::Format_None
- ? ti.fontEngine->glyphFormat : d->glyphCacheFormat;
-
- if (glyphFormat == QFontEngine::Format_A32) {
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
- || d->device->alphaRequested() || txtype > QTransform::TxTranslate
- || (state()->composition_mode != QPainter::CompositionMode_Source
- && state()->composition_mode != QPainter::CompositionMode_SourceOver))
- {
- glyphFormat = QFontEngine::Format_A8;
- }
- }
-
- if (shouldDrawCachedGlyphs(ti.fontEngine, s->matrix)) {
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
- ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
-
- {
- QStaticTextItem staticTextItem;
- staticTextItem.setFontEngine(ti.fontEngine);
- staticTextItem.glyphs = glyphs.data();
- staticTextItem.numGlyphs = glyphs.size();
- staticTextItem.glyphPositions = positions.data();
-
- d->drawCachedGlyphs(glyphFormat, &staticTextItem);
- }
- return;
- }
-
- QPaintEngineEx::drawTextItem(p, ti);
-}
-
-namespace {
-
- class QOpenGLStaticTextUserData: public QStaticTextUserData
- {
- public:
- QOpenGLStaticTextUserData()
- : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
- {
- }
-
- ~QOpenGLStaticTextUserData()
- {
- }
-
- QSize cacheSize;
- QGL2PEXVertexArray vertexCoordinateArray;
- QGL2PEXVertexArray textureCoordinateArray;
- QFontEngine::GlyphFormat glyphFormat;
- int cacheSerialNumber;
- };
-
-}
-
-
-// #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
-
-void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngine::GlyphFormat glyphFormat,
- QStaticTextItem *staticTextItem)
-{
- Q_Q(QGL2PaintEngineEx);
-
- QGL2PaintEngineState *s = q->state();
-
- void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
- bool recreateVertexArrays = false;
-
- QTransform glyphCacheTransform;
- QFontEngine *fe = staticTextItem->fontEngine();
- if (fe->supportsTransformation(s->matrix)) {
- // The font-engine supports rendering glyphs with the current transform, so we
- // build a glyph-cache with the scale pre-applied, so that the cache contains
- // glyphs with the appropriate resolution in the case of retina displays.
- glyphCacheTransform = s->matrix.type() < QTransform::TxRotate ?
- QTransform::fromScale(qAbs(s->matrix.m11()), qAbs(s->matrix.m22())) :
- QTransform::fromScale(
- QVector2D(s->matrix.m11(), s->matrix.m12()).length(),
- QVector2D(s->matrix.m21(), s->matrix.m22()).length());
- }
-
- QGLTextureGlyphCache *cache =
- (QGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphFormat, glyphCacheTransform);
- if (!cache || cache->glyphFormat() != glyphFormat || cache->contextGroup() == 0) {
- cache = new QGLTextureGlyphCache(glyphFormat, glyphCacheTransform);
- fe->setGlyphCache(cacheKey, cache);
- recreateVertexArrays = true;
- }
-
- if (staticTextItem->userDataNeedsUpdate) {
- recreateVertexArrays = true;
- } else if (staticTextItem->userData() == 0) {
- recreateVertexArrays = true;
- } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
- recreateVertexArrays = true;
- } else {
- QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
- if (userData->glyphFormat != glyphFormat) {
- recreateVertexArrays = true;
- } else if (userData->cacheSerialNumber != cache->serialNumber()) {
- recreateVertexArrays = true;
- }
- }
-
- // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
- // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
- // cache so this text is performed before we test if the cache size has changed.
- if (recreateVertexArrays) {
- cache->setPaintEnginePrivate(this);
- if (!cache->populate(fe, staticTextItem->numGlyphs,
- staticTextItem->glyphs, staticTextItem->glyphPositions)) {
- // No space for glyphs in cache. We need to reset it and try again.
- cache->clear();
- cache->populate(fe, staticTextItem->numGlyphs,
- staticTextItem->glyphs, staticTextItem->glyphPositions);
- }
- cache->fillInPendingGlyphs();
- }
-
- if (cache->width() == 0 || cache->height() == 0)
- return;
-
- transferMode(TextDrawingMode);
-
- int margin = fe->glyphMargin(glyphFormat);
-
- GLfloat dx = 1.0 / cache->width();
- GLfloat dy = 1.0 / cache->height();
-
- // Use global arrays by default
- QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
- QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
-
- if (staticTextItem->useBackendOptimizations) {
- QOpenGLStaticTextUserData *userData = 0;
-
- if (staticTextItem->userData() == 0
- || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
-
- userData = new QOpenGLStaticTextUserData();
- staticTextItem->setUserData(userData);
-
- } else {
- userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
- }
-
- userData->glyphFormat = glyphFormat;
- userData->cacheSerialNumber = cache->serialNumber();
-
- // Use cache if backend optimizations is turned on
- vertexCoordinates = &userData->vertexCoordinateArray;
- textureCoordinates = &userData->textureCoordinateArray;
-
- QSize size(cache->width(), cache->height());
- if (userData->cacheSize != size) {
- recreateVertexArrays = true;
- userData->cacheSize = size;
- }
- }
-
- if (recreateVertexArrays) {
- vertexCoordinates->clear();
- textureCoordinates->clear();
-
- bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
- for (int i=0; i<staticTextItem->numGlyphs; ++i) {
- QFixed subPixelPosition;
- if (supportsSubPixelPositions)
- subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
-
- QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
-
- const QTextureGlyphCache::Coord &c = cache->coords[glyph];
- if (c.isNull())
- continue;
-
- int x = qFloor(staticTextItem->glyphPositions[i].x.toReal() * cache->transform().m11()) + c.baseLineX - margin;
- int y = qRound(staticTextItem->glyphPositions[i].y.toReal() * cache->transform().m22()) - c.baseLineY - margin;
-
- vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
- textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
- }
-
- staticTextItem->userDataNeedsUpdate = false;
- }
-
- int numGlyphs = vertexCoordinates->vertexCount() / 4;
- if (numGlyphs == 0)
- return;
-
- if (elementIndices.size() < numGlyphs*6) {
- Q_ASSERT(elementIndices.size() % 6 == 0);
- int j = elementIndices.size() / 6 * 4;
- while (j < numGlyphs*4) {
- elementIndices.append(j + 0);
- elementIndices.append(j + 0);
- elementIndices.append(j + 1);
- elementIndices.append(j + 2);
- elementIndices.append(j + 3);
- elementIndices.append(j + 3);
-
- j += 4;
- }
-
-#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
- if (elementIndicesVBOId == 0)
- glGenBuffers(1, &elementIndicesVBOId);
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
- elementIndices.constData(), GL_STATIC_DRAW);
-#endif
- } else {
-#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
-#endif
- }
-
- setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
- setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
-
- if (!snapToPixelGrid) {
- snapToPixelGrid = true;
- matrixDirty = true;
- }
-
- QBrush pensBrush = q->state()->pen.brush();
- setBrush(pensBrush);
-
- if (glyphFormat == QFontEngine::Format_A32) {
-
- // Subpixel antialiasing without gamma correction
-
- QPainter::CompositionMode compMode = q->state()->composition_mode;
- Q_ASSERT(compMode == QPainter::CompositionMode_Source
- || compMode == QPainter::CompositionMode_SourceOver);
-
- shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
-
- if (pensBrush.style() == Qt::SolidPattern) {
- // Solid patterns can get away with only one pass.
- QColor c = pensBrush.color();
- qreal oldOpacity = q->state()->opacity;
- if (compMode == QPainter::CompositionMode_Source) {
- c = qt_premultiplyColor(c, q->state()->opacity);
- q->state()->opacity = 1;
- opacityUniformDirty = true;
- }
-
- compositionModeDirty = false; // I can handle this myself, thank you very much
- prepareForCachedGlyphDraw(*cache);
-
- // prepareForCachedGlyphDraw() have set the opacity on the current shader, so the opacity state can now be reset.
- if (compMode == QPainter::CompositionMode_Source) {
- q->state()->opacity = oldOpacity;
- opacityUniformDirty = true;
- }
-
- glEnable(GL_BLEND);
- glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
- glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
- } else {
- // Other brush styles need two passes.
-
- qreal oldOpacity = q->state()->opacity;
- if (compMode == QPainter::CompositionMode_Source) {
- q->state()->opacity = 1;
- opacityUniformDirty = true;
- pensBrush = Qt::white;
- setBrush(pensBrush);
- }
-
- compositionModeDirty = false; // I can handle this myself, thank you very much
- prepareForCachedGlyphDraw(*cache);
- glEnable(GL_BLEND);
- glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
-
- glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
- glBindTexture(GL_TEXTURE_2D, cache->texture());
- updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
-
-#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
- glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
-#else
- glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
-#endif
-
- shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
-
- if (compMode == QPainter::CompositionMode_Source) {
- q->state()->opacity = oldOpacity;
- opacityUniformDirty = true;
- pensBrush = q->state()->pen.brush();
- setBrush(pensBrush);
- }
-
- compositionModeDirty = false;
- prepareForCachedGlyphDraw(*cache);
- glEnable(GL_BLEND);
- glBlendFunc(GL_ONE, GL_ONE);
- }
- compositionModeDirty = true;
- } else {
- // Grayscale/mono glyphs
-
- shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
- prepareForCachedGlyphDraw(*cache);
- }
-
- QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
- if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
-
- glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
- if (lastMaskTextureUsed != cache->texture()) {
- glBindTexture(GL_TEXTURE_2D, cache->texture());
- lastMaskTextureUsed = cache->texture();
- }
-
- if (cache->filterMode() != filterMode) {
- if (filterMode == QGLTextureGlyphCache::Linear) {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- } else {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- }
- cache->setFilterMode(filterMode);
- }
- }
-
-#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
- glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
-#else
- glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
-#endif
-}
-
-void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
- QPainter::PixmapFragmentHints hints)
-{
- Q_D(QGL2PaintEngineEx);
- // Use fallback for extended composition modes.
- if (state()->composition_mode > QPainter::CompositionMode_Plus) {
- QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
- return;
- }
-
- ensureActive();
- int max_texture_size = d->ctx->d_func()->maxTextureSize();
- if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
- QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
- d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
- } else {
- d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
- }
-}
-
-
-void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
- int fragmentCount, const QPixmap &pixmap,
- QPainter::PixmapFragmentHints hints)
-{
- GLfloat dx = 1.0f / pixmap.size().width();
- GLfloat dy = 1.0f / pixmap.size().height();
-
- vertexCoordinateArray.clear();
- textureCoordinateArray.clear();
- opacityArray.reset();
-
- if (snapToPixelGrid) {
- snapToPixelGrid = false;
- matrixDirty = true;
- }
-
- bool allOpaque = true;
-
- for (int i = 0; i < fragmentCount; ++i) {
- qreal s = 0;
- qreal c = 1;
- if (fragments[i].rotation != 0) {
- s = qFastSin(qDegreesToRadians(fragments[i].rotation));
- c = qFastCos(qDegreesToRadians(fragments[i].rotation));
- }
-
- qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
- qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
- QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
- QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
-
- vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
- vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
- vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
- vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
- vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
- vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
-
- QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
- (fragments[i].sourceLeft + fragments[i].width) * dx,
- (fragments[i].sourceTop + fragments[i].height) * dy);
-
- textureCoordinateArray.addVertex(src.right, src.bottom);
- textureCoordinateArray.addVertex(src.right, src.top);
- textureCoordinateArray.addVertex(src.left, src.top);
- textureCoordinateArray.addVertex(src.left, src.top);
- textureCoordinateArray.addVertex(src.left, src.bottom);
- textureCoordinateArray.addVertex(src.right, src.bottom);
-
- qreal opacity = fragments[i].opacity * q->state()->opacity;
- opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
- allOpaque &= (opacity >= 0.99f);
- }
-
- glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
- QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
- QGLContext::InternalBindOption
- | QGLContext::CanFlipNativePixmapBindOption);
-
- if (texture->options & QGLContext::InvertedYBindOption) {
- // Flip texture y-coordinate.
- QGLPoint *data = textureCoordinateArray.data();
- for (int i = 0; i < 6 * fragmentCount; ++i)
- data[i].y = 1 - data[i].y;
- }
-
- transferMode(ImageArrayDrawingMode);
-
- bool isBitmap = pixmap.isQBitmap();
- bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
-
- updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
- q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
-
- // Setup for texture drawing
- currentBrush = noBrush;
- shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
- : QGLEngineShaderManager::ImageSrc);
- if (prepareForDraw(isOpaque))
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
-
- if (isBitmap) {
- QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
- shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
- }
-
- glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
-}
-
-bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
-{
- Q_D(QGL2PaintEngineEx);
-
-// qDebug("QGL2PaintEngineEx::begin()");
- if (pdev->devType() == QInternal::OpenGL)
- d->device = static_cast<QGLPaintDevice*>(pdev);
- else
- d->device = QGLPaintDevice::getDevice(pdev);
-
- if (!d->device)
- return false;
-
- d->ctx = d->device->context();
- d->ctx->d_ptr->active_engine = this;
-
- d->resetOpenGLContextActiveEngine();
-
- const QSize sz = d->device->size();
- d->width = sz.width();
- d->height = sz.height();
- d->mode = BrushDrawingMode;
- d->brushTextureDirty = true;
- d->brushUniformsDirty = true;
- d->matrixUniformDirty = true;
- d->matrixDirty = true;
- d->compositionModeDirty = true;
- d->opacityUniformDirty = true;
- d->translateZUniformDirty = true;
- d->needsSync = true;
- d->useSystemClip = !systemClip().isEmpty();
- d->currentBrush = QBrush();
-
- d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
- d->stencilClean = true;
-
- // Calling begin paint should make the correct context current. So, any
- // code which calls into GL or otherwise needs a current context *must*
- // go after beginPaint:
- d->device->beginPaint();
-
- d->initializeOpenGLFunctions();
-
- d->shaderManager = new QGLEngineShaderManager(d->ctx);
-
- d->glDisable(GL_STENCIL_TEST);
- d->glDisable(GL_DEPTH_TEST);
- d->glDisable(GL_SCISSOR_TEST);
-
-#if !defined(QT_OPENGL_ES_2)
- if (!d->ctx->contextHandle()->isOpenGLES())
- d->glDisable(GL_MULTISAMPLE);
-#endif
-
- d->glyphCacheFormat = QFontEngine::Format_A8;
-
-#if !defined(QT_OPENGL_ES_2)
- if (!d->ctx->contextHandle()->isOpenGLES()) {
- d->glyphCacheFormat = QFontEngine::Format_A32;
- d->multisamplingAlwaysEnabled = false;
- } else {
- d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
- }
-#else
- // OpenGL ES can't switch MSAA off, so if the gl paint device is
- // multisampled, it's always multisampled.
- d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
-#endif
-
- return true;
-}
-
-bool QGL2PaintEngineEx::end()
-{
- Q_D(QGL2PaintEngineEx);
-
- QGLContext *ctx = d->ctx;
- d->glUseProgram(0);
- d->transferMode(BrushDrawingMode);
- d->device->endPaint();
-
- ctx->d_ptr->active_engine = 0;
- ctx->makeCurrent();
- d->resetOpenGLContextActiveEngine();
- d->resetGLState();
-
- delete d->shaderManager;
- d->shaderManager = 0;
- d->currentBrush = QBrush();
-
-#ifdef QT_OPENGL_CACHE_AS_VBOS
- if (!d->unusedVBOSToClean.isEmpty()) {
- d->glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
- d->unusedVBOSToClean.clear();
- }
- if (!d->unusedIBOSToClean.isEmpty()) {
- d->glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
- d->unusedIBOSToClean.clear();
- }
-#endif
-
- return false;
-}
-
-void QGL2PaintEngineEx::ensureActive()
-{
- Q_D(QGL2PaintEngineEx);
- QGLContext *ctx = d->ctx;
-
- if (isActive() && (ctx->d_ptr->active_engine != this || d->resetOpenGLContextActiveEngine())) {
- ctx->d_ptr->active_engine = this;
- d->needsSync = true;
- }
-
- d->device->ensureActiveTarget();
-
- if (d->needsSync) {
- d->transferMode(BrushDrawingMode);
- d->glViewport(0, 0, d->width, d->height);
- d->needsSync = false;
- d->lastMaskTextureUsed = 0;
- d->shaderManager->setDirty();
- d->ctx->d_func()->syncGlState();
- for (int i = 0; i < 3; ++i)
- d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
- setState(state());
- }
-}
-
-void QGL2PaintEngineExPrivate::updateClipScissorTest()
-{
- Q_Q(QGL2PaintEngineEx);
- if (q->state()->clipTestEnabled) {
- glEnable(GL_STENCIL_TEST);
- glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
- } else {
- glDisable(GL_STENCIL_TEST);
- glStencilFunc(GL_ALWAYS, 0, 0xff);
- }
-
-#ifdef QT_GL_NO_SCISSOR_TEST
- currentScissorBounds = QRect(0, 0, width, height);
-#else
- QRect bounds = q->state()->rectangleClip;
- if (!q->state()->clipEnabled) {
- if (useSystemClip)
- bounds = systemClip.boundingRect();
- else
- bounds = QRect(0, 0, width, height);
- } else {
- if (useSystemClip)
- bounds = bounds.intersected(systemClip.boundingRect());
- else
- bounds = bounds.intersected(QRect(0, 0, width, height));
- }
-
- currentScissorBounds = bounds;
-
- if (bounds == QRect(0, 0, width, height)) {
- glDisable(GL_SCISSOR_TEST);
- } else {
- glEnable(GL_SCISSOR_TEST);
- setScissor(bounds);
- }
-#endif
-}
-
-void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
-{
- const int left = rect.left();
- const int width = rect.width();
- int bottom = height - (rect.top() + rect.height());
- if (device->isFlipped()) {
- bottom = rect.top();
- }
- const int height = rect.height();
-
- glScissor(left, bottom, width, height);
-}
-
-void QGL2PaintEngineEx::clipEnabledChanged()
-{
- Q_D(QGL2PaintEngineEx);
-
- state()->clipChanged = true;
-
- if (painter()->hasClipping())
- d->regenerateClip();
- else
- d->systemStateChanged();
-}
-
-void QGL2PaintEngineExPrivate::clearClip(uint value)
-{
- dirtyStencilRegion -= currentScissorBounds;
-
- glStencilMask(0xff);
- glClearStencil(value);
- glClear(GL_STENCIL_BUFFER_BIT);
- glStencilMask(0x0);
-
- q->state()->needsClipBufferClear = false;
-}
-
-void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
-{
- transferMode(BrushDrawingMode);
-
- if (snapToPixelGrid) {
- snapToPixelGrid = false;
- matrixDirty = true;
- }
-
- if (matrixDirty)
- updateMatrix();
-
- stencilClean = false;
-
- const bool singlePass = !path.hasWindingFill()
- && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
- || q->state()->needsClipBufferClear);
- const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
-
- if (q->state()->needsClipBufferClear)
- clearClip(1);
-
- if (path.isEmpty()) {
- glEnable(GL_STENCIL_TEST);
- glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
- return;
- }
-
- if (q->state()->clipTestEnabled)
- glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
- else
- glStencilFunc(GL_ALWAYS, 0, 0xff);
-
- vertexCoordinateArray.clear();
- vertexCoordinateArray.addPath(path, inverseScale, false);
-
- if (!singlePass)
- fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
-
- glColorMask(false, false, false, false);
- glEnable(GL_STENCIL_TEST);
- useSimpleShader();
-
- if (singlePass) {
- // Under these conditions we can set the new stencil value in a single
- // pass, by using the current value and the "new value" as the toggles
-
- glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
- glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
- glStencilMask(value ^ referenceClipValue);
-
- drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
- } else {
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
- glStencilMask(0xff);
-
- if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
- // Pass when any clip bit is set, set high bit
- glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
- composite(vertexCoordinateArray.boundingRect());
- }
-
- // Pass when high bit is set, replace stencil value with new clip value
- glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
-
- composite(vertexCoordinateArray.boundingRect());
- }
-
- glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
- glStencilMask(0);
-
- glColorMask(true, true, true, true);
-}
-
-void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
-{
-// qDebug("QGL2PaintEngineEx::clip()");
- Q_D(QGL2PaintEngineEx);
-
- state()->clipChanged = true;
-
- ensureActive();
-
- if (op == Qt::ReplaceClip) {
- op = Qt::IntersectClip;
- if (d->hasClipOperations()) {
- d->systemStateChanged();
- state()->canRestoreClip = false;
- }
- }
-
-#ifndef QT_GL_NO_SCISSOR_TEST
- if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
- const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
- QRectF rect(points[0], points[2]);
-
- if (state()->matrix.type() <= QTransform::TxScale
- || (state()->matrix.type() == QTransform::TxRotate
- && qFuzzyIsNull(state()->matrix.m11())
- && qFuzzyIsNull(state()->matrix.m22())))
- {
- state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
- d->updateClipScissorTest();
- return;
- }
- }
-#endif
-
- const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
-
- switch (op) {
- case Qt::NoClip:
- if (d->useSystemClip) {
- state()->clipTestEnabled = true;
- state()->currentClip = 1;
- } else {
- state()->clipTestEnabled = false;
- }
- state()->rectangleClip = QRect(0, 0, d->width, d->height);
- state()->canRestoreClip = false;
- d->updateClipScissorTest();
- break;
- case Qt::IntersectClip:
- state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
- d->updateClipScissorTest();
- d->resetClipIfNeeded();
- ++d->maxClip;
- d->writeClip(path, d->maxClip);
- state()->currentClip = d->maxClip;
- state()->clipTestEnabled = true;
- break;
- default:
- break;
- }
-}
-
-void QGL2PaintEngineExPrivate::regenerateClip()
-{
- systemStateChanged();
- replayClipOperations();
-}
-
-void QGL2PaintEngineExPrivate::systemStateChanged()
-{
- Q_Q(QGL2PaintEngineEx);
-
- q->state()->clipChanged = true;
-
- if (systemClip.isEmpty()) {
- useSystemClip = false;
- } else {
- if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
- QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
- useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
- } else {
- useSystemClip = true;
- }
- }
-
- q->state()->clipTestEnabled = false;
- q->state()->needsClipBufferClear = true;
-
- q->state()->currentClip = 1;
- maxClip = 1;
-
- q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
- updateClipScissorTest();
-
- if (systemClip.rectCount() == 1) {
- if (systemClip.boundingRect() == QRect(0, 0, width, height))
- useSystemClip = false;
-#ifndef QT_GL_NO_SCISSOR_TEST
- // scissoring takes care of the system clip
- return;
-#endif
- }
-
- if (useSystemClip) {
- clearClip(0);
-
- QPainterPath path;
- path.addRegion(systemClip);
-
- q->state()->currentClip = 0;
- writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
- q->state()->currentClip = 1;
- q->state()->clipTestEnabled = true;
- }
-}
-
-void QGL2PaintEngineEx::setTranslateZ(GLfloat z)
-{
- Q_D(QGL2PaintEngineEx);
- if (d->translateZ != z) {
- d->translateZ = z;
- d->translateZUniformDirty = true;
- }
-}
-
-void QGL2PaintEngineEx::setState(QPainterState *new_state)
-{
- // qDebug("QGL2PaintEngineEx::setState()");
-
- Q_D(QGL2PaintEngineEx);
-
- QGL2PaintEngineState *s = static_cast<QGL2PaintEngineState *>(new_state);
- QGL2PaintEngineState *old_state = state();
-
- QPaintEngineEx::setState(s);
-
- if (s->isNew) {
- // Newly created state object. The call to setState()
- // will either be followed by a call to begin(), or we are
- // setting the state as part of a save().
- s->isNew = false;
- return;
- }
-
- // Setting the state as part of a restore().
-
- if (old_state == s || old_state->renderHintsChanged)
- renderHintsChanged();
-
- if (old_state == s || old_state->matrixChanged)
- d->matrixDirty = true;
-
- if (old_state == s || old_state->compositionModeChanged)
- d->compositionModeDirty = true;
-
- if (old_state == s || old_state->opacityChanged)
- d->opacityUniformDirty = true;
-
- if (old_state == s || old_state->clipChanged) {
- if (old_state && old_state != s && old_state->canRestoreClip) {
- d->updateClipScissorTest();
- d->glDepthFunc(GL_LEQUAL);
- } else {
- d->regenerateClip();
- }
- }
-}
-
-QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
-{
- if (orig)
- const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
-
- QGL2PaintEngineState *s;
- if (!orig)
- s = new QGL2PaintEngineState();
- else
- s = new QGL2PaintEngineState(*static_cast<QGL2PaintEngineState *>(orig));
-
- s->matrixChanged = false;
- s->compositionModeChanged = false;
- s->opacityChanged = false;
- s->renderHintsChanged = false;
- s->clipChanged = false;
-
- return s;
-}
-
-QGL2PaintEngineState::QGL2PaintEngineState(QGL2PaintEngineState &other)
- : QPainterState(other)
-{
- isNew = true;
- needsClipBufferClear = other.needsClipBufferClear;
- clipTestEnabled = other.clipTestEnabled;
- currentClip = other.currentClip;
- canRestoreClip = other.canRestoreClip;
- rectangleClip = other.rectangleClip;
-}
-
-QGL2PaintEngineState::QGL2PaintEngineState()
-{
- isNew = true;
- needsClipBufferClear = true;
- clipTestEnabled = false;
- canRestoreClip = true;
-}
-
-QGL2PaintEngineState::~QGL2PaintEngineState()
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h
deleted file mode 100644
index 762aac2f65..0000000000
--- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h
+++ /dev/null
@@ -1,334 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPAINTENGINEEX_OPENGL2_P_H
-#define QPAINTENGINEEX_OPENGL2_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QDebug>
-
-#include <private/qpaintengineex_p.h>
-#include <private/qglengineshadermanager_p.h>
-#include <private/qgl2pexvertexarray_p.h>
-#include <private/qglpaintdevice_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qdatabuffer_p.h>
-#include <private/qtriangulatingstroker_p.h>
-#include <private/qopenglextensions_p.h>
-
-enum EngineMode {
- ImageDrawingMode,
- TextDrawingMode,
- BrushDrawingMode,
- ImageArrayDrawingMode
-};
-
-QT_BEGIN_NAMESPACE
-
-#define GL_STENCIL_HIGH_BIT GLuint(0x80)
-#define QT_BRUSH_TEXTURE_UNIT GLuint(0)
-#define QT_IMAGE_TEXTURE_UNIT GLuint(0) //Can be the same as brush texture unit
-#define QT_MASK_TEXTURE_UNIT GLuint(1)
-#define QT_BACKGROUND_TEXTURE_UNIT GLuint(2)
-
-class QGL2PaintEngineExPrivate;
-
-
-class QGL2PaintEngineState : public QPainterState
-{
-public:
- QGL2PaintEngineState(QGL2PaintEngineState &other);
- QGL2PaintEngineState();
- ~QGL2PaintEngineState();
-
- uint isNew : 1;
- uint needsClipBufferClear : 1;
- uint clipTestEnabled : 1;
- uint canRestoreClip : 1;
- uint matrixChanged : 1;
- uint compositionModeChanged : 1;
- uint opacityChanged : 1;
- uint renderHintsChanged : 1;
- uint clipChanged : 1;
- uint currentClip : 8;
-
- QRect rectangleClip;
-};
-
-class Q_OPENGL_EXPORT QGL2PaintEngineEx : public QPaintEngineEx
-{
- Q_DECLARE_PRIVATE(QGL2PaintEngineEx)
-public:
- QGL2PaintEngineEx();
- ~QGL2PaintEngineEx();
-
- bool begin(QPaintDevice *device) override;
- void ensureActive();
- bool end() override;
-
- virtual void clipEnabledChanged() override;
- virtual void penChanged() override;
- virtual void brushChanged() override;
- virtual void brushOriginChanged() override;
- virtual void opacityChanged() override;
- virtual void compositionModeChanged() override;
- virtual void renderHintsChanged() override;
- virtual void transformChanged() override;
-
- virtual void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr) override;
- virtual void drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
- QPainter::PixmapFragmentHints hints) override;
- virtual void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr,
- Qt::ImageConversionFlags flags = Qt::AutoColor) override;
- virtual void drawTextItem(const QPointF &p, const QTextItem &textItem) override;
- virtual void fill(const QVectorPath &path, const QBrush &brush) override;
- virtual void stroke(const QVectorPath &path, const QPen &pen) override;
- virtual void clip(const QVectorPath &path, Qt::ClipOperation op) override;
-
- virtual void drawStaticTextItem(QStaticTextItem *textItem) override;
-
- bool drawTexture(const QRectF &r, GLuint textureId, const QSize &size, const QRectF &sr);
-
- Type type() const override { return OpenGL2; }
-
- virtual void setState(QPainterState *s) override;
- virtual QPainterState *createState(QPainterState *orig) const override;
- inline QGL2PaintEngineState *state() {
- return static_cast<QGL2PaintEngineState *>(QPaintEngineEx::state());
- }
- inline const QGL2PaintEngineState *state() const {
- return static_cast<const QGL2PaintEngineState *>(QPaintEngineEx::state());
- }
-
- void beginNativePainting() override;
- void endNativePainting() override;
-
- void invalidateState();
-
- void setRenderTextActive(bool);
-
- bool isNativePaintingActive() const;
- bool requiresPretransformedGlyphPositions(QFontEngine *, const QTransform &) const override { return false; }
- bool shouldDrawCachedGlyphs(QFontEngine *, const QTransform &) const override;
-
- void setTranslateZ(GLfloat z);
-
-private:
- Q_DISABLE_COPY_MOVE(QGL2PaintEngineEx)
-};
-
-class QGL2PaintEngineExPrivate : public QPaintEngineExPrivate, protected QOpenGLExtensions
-{
- Q_DECLARE_PUBLIC(QGL2PaintEngineEx)
-public:
- enum StencilFillMode {
- OddEvenFillMode,
- WindingFillMode,
- TriStripStrokeFillMode
- };
-
- QGL2PaintEngineExPrivate(QGL2PaintEngineEx *q_ptr) :
- q(q_ptr),
- shaderManager(nullptr),
- width(0), height(0),
- ctx(nullptr),
- useSystemClip(true),
- elementIndicesVBOId(0),
- opacityArray(0),
- snapToPixelGrid(false),
- nativePaintingActive(false),
- inverseScale(1),
- lastMaskTextureUsed(0),
- translateZ(0)
- { }
-
- ~QGL2PaintEngineExPrivate();
-
- void updateBrushTexture();
- void updateBrushUniforms();
- void updateMatrix();
- void updateCompositionMode();
- void updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id = GLuint(-1));
-
- void resetGLState();
- bool resetOpenGLContextActiveEngine();
-
- // fill, stroke, drawTexture, drawPixmaps & drawCachedGlyphs are the main rendering entry-points,
- // however writeClip can also be thought of as en entry point as it does similar things.
- void fill(const QVectorPath &path);
- void stroke(const QVectorPath &path, const QPen &pen);
- void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern = false);
- void drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
- QPainter::PixmapFragmentHints hints);
- void drawCachedGlyphs(QFontEngine::GlyphFormat glyphFormat, QStaticTextItem *staticTextItem);
-
- // Calls glVertexAttributePointer if the pointer has changed
- inline void setVertexAttributePointer(unsigned int arrayIndex, const GLfloat *pointer);
-
- // draws whatever is in the vertex array:
- void drawVertexArrays(const float *data, int *stops, int stopCount, GLenum primitive);
- void drawVertexArrays(QGL2PEXVertexArray &vertexArray, GLenum primitive) {
- drawVertexArrays((const float *) vertexArray.data(), vertexArray.stops(), vertexArray.stopCount(), primitive);
- }
-
- // Composites the bounding rect onto dest buffer:
- void composite(const QGLRect& boundingRect);
-
- // Calls drawVertexArrays to render into stencil buffer:
- void fillStencilWithVertexArray(const float *data, int count, int *stops, int stopCount, const QGLRect &bounds, StencilFillMode mode);
- void fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill) {
- fillStencilWithVertexArray((const float *) vertexArray.data(), 0, vertexArray.stops(), vertexArray.stopCount(),
- vertexArray.boundingRect(),
- useWindingFill ? WindingFillMode : OddEvenFillMode);
- }
-
- void setBrush(const QBrush& brush);
- void transferMode(EngineMode newMode);
- bool prepareForDraw(bool srcPixelsAreOpaque); // returns true if the program has changed
- bool prepareForCachedGlyphDraw(const QFontEngineGlyphCache &cache);
- inline void useSimpleShader();
- inline GLuint location(const QGLEngineShaderManager::Uniform uniform) {
- return shaderManager->getUniformLocation(uniform);
- }
-
- void clearClip(uint value);
- void writeClip(const QVectorPath &path, uint value);
- void resetClipIfNeeded();
-
- void updateClipScissorTest();
- void setScissor(const QRect &rect);
- void regenerateClip();
- void systemStateChanged() override;
-
-
- static QGLEngineShaderManager* shaderManagerForEngine(QGL2PaintEngineEx *engine) { return engine->d_func()->shaderManager; }
- static QGL2PaintEngineExPrivate *getData(QGL2PaintEngineEx *engine) { return engine->d_func(); }
- static void cleanupVectorPath(QPaintEngineEx *engine, void *data);
-
-
- QGL2PaintEngineEx* q;
- QGLEngineShaderManager* shaderManager;
- QGLPaintDevice* device;
- int width, height;
- QGLContext *ctx;
- EngineMode mode;
- QFontEngine::GlyphFormat glyphCacheFormat;
-
- // Dirty flags
- bool matrixDirty; // Implies matrix uniforms are also dirty
- bool compositionModeDirty;
- bool brushTextureDirty;
- bool brushUniformsDirty;
- bool opacityUniformDirty;
- bool matrixUniformDirty;
- bool translateZUniformDirty;
-
- bool stencilClean; // Has the stencil not been used for clipping so far?
- bool useSystemClip;
- QRegion dirtyStencilRegion;
- QRect currentScissorBounds;
- uint maxClip;
-
- QBrush currentBrush; // May not be the state's brush!
- const QBrush noBrush;
-
- QPixmap currentBrushPixmap;
-
- QGL2PEXVertexArray vertexCoordinateArray;
- QGL2PEXVertexArray textureCoordinateArray;
- QVector<GLushort> elementIndices;
- GLuint elementIndicesVBOId;
- QDataBuffer<GLfloat> opacityArray;
- GLfloat staticVertexCoordinateArray[8];
- GLfloat staticTextureCoordinateArray[8];
-
- bool snapToPixelGrid;
- bool nativePaintingActive;
- GLfloat pmvMatrix[3][3];
- GLfloat inverseScale;
-
- GLuint lastTextureUsed;
- GLuint lastMaskTextureUsed;
-
- bool needsSync;
- bool multisamplingAlwaysEnabled;
-
- GLfloat depthRange[2];
-
- float textureInvertedY;
-
- QTriangulatingStroker stroker;
- QDashedStrokeProcessor dasher;
-
- QSet<QVectorPath::CacheEntry *> pathCaches;
- QVector<GLuint> unusedVBOSToClean;
- QVector<GLuint> unusedIBOSToClean;
-
- const GLfloat *vertexAttribPointers[3];
-
- GLfloat translateZ;
-};
-
-
-void QGL2PaintEngineExPrivate::setVertexAttributePointer(unsigned int arrayIndex, const GLfloat *pointer)
-{
- Q_ASSERT(arrayIndex < 3);
- if (pointer == vertexAttribPointers[arrayIndex])
- return;
-
- vertexAttribPointers[arrayIndex] = pointer;
- if (arrayIndex == QT_OPACITY_ATTR)
- glVertexAttribPointer(arrayIndex, 1, GL_FLOAT, GL_FALSE, 0, pointer);
- else
- glVertexAttribPointer(arrayIndex, 2, GL_FLOAT, GL_FALSE, 0, pointer);
-}
-
-QT_END_NAMESPACE
-
-#endif // QPAINTENGINEEX_OPENGL2_P_H
diff --git a/src/opengl/gl2paintengineex/qtextureglyphcache_gl.cpp b/src/opengl/gl2paintengineex/qtextureglyphcache_gl.cpp
deleted file mode 100644
index d5ce4efd1a..0000000000
--- a/src/opengl/gl2paintengineex/qtextureglyphcache_gl.cpp
+++ /dev/null
@@ -1,414 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtextureglyphcache_gl_p.h"
-#include "qpaintengineex_opengl2_p.h"
-#include "qglfunctions.h"
-#include "private/qglengineshadersource_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-static int next_qgltextureglyphcache_serial_number()
-{
- static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(0);
- return 1 + serial.fetchAndAddRelaxed(1);
-}
-
-QGLTextureGlyphCache::QGLTextureGlyphCache(QFontEngine::GlyphFormat format, const QTransform &matrix)
- : QImageTextureGlyphCache(format, matrix)
- , m_textureResource(0)
- , pex(0)
- , m_blitProgram(0)
- , m_filterMode(Nearest)
- , m_serialNumber(next_qgltextureglyphcache_serial_number())
-{
-#ifdef QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
- qDebug(" -> QGLTextureGlyphCache() %p for context %p.", this, QOpenGLContext::currentContext());
-#endif
- m_vertexCoordinateArray[0] = -1.0f;
- m_vertexCoordinateArray[1] = -1.0f;
- m_vertexCoordinateArray[2] = 1.0f;
- m_vertexCoordinateArray[3] = -1.0f;
- m_vertexCoordinateArray[4] = 1.0f;
- m_vertexCoordinateArray[5] = 1.0f;
- m_vertexCoordinateArray[6] = -1.0f;
- m_vertexCoordinateArray[7] = 1.0f;
-
- m_textureCoordinateArray[0] = 0.0f;
- m_textureCoordinateArray[1] = 0.0f;
- m_textureCoordinateArray[2] = 1.0f;
- m_textureCoordinateArray[3] = 0.0f;
- m_textureCoordinateArray[4] = 1.0f;
- m_textureCoordinateArray[5] = 1.0f;
- m_textureCoordinateArray[6] = 0.0f;
- m_textureCoordinateArray[7] = 1.0f;
-}
-
-QGLTextureGlyphCache::~QGLTextureGlyphCache()
-{
-#ifdef QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
- qDebug(" -> ~QGLTextureGlyphCache() %p.", this);
-#endif
- delete m_blitProgram;
- if (m_textureResource)
- m_textureResource->free();
-}
-
-void QGLTextureGlyphCache::createTextureData(int width, int height)
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx == 0) {
- qWarning("QGLTextureGlyphCache::createTextureData: Called with no context");
- return;
- }
- QOpenGLFunctions *funcs = ctx->contextHandle()->functions();
-
- // create in QImageTextureGlyphCache baseclass is meant to be called
- // only to create the initial image and does not preserve the content,
- // so we don't call when this function is called from resize.
- if ((!QGLFramebufferObject::hasOpenGLFramebufferObjects() || ctx->d_ptr->workaround_brokenFBOReadBack) && image().isNull())
- QImageTextureGlyphCache::createTextureData(width, height);
-
- // Make the lower glyph texture size 16 x 16.
- if (width < 16)
- width = 16;
- if (height < 16)
- height = 16;
-
- if (m_textureResource && !m_textureResource->m_texture) {
- delete m_textureResource;
- m_textureResource = 0;
- }
-
- if (!m_textureResource)
- m_textureResource = new QGLGlyphTexture(ctx);
-
- funcs->glGenTextures(1, &m_textureResource->m_texture);
- funcs->glBindTexture(GL_TEXTURE_2D, m_textureResource->m_texture);
-
- m_textureResource->m_width = width;
- m_textureResource->m_height = height;
-
- if (m_format == QFontEngine::Format_A32) {
- QVarLengthArray<uchar> data(width * height * 4);
- for (int i = 0; i < data.size(); ++i)
- data[i] = 0;
- funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
- } else {
- QVarLengthArray<uchar> data(width * height);
- for (int i = 0; i < data.size(); ++i)
- data[i] = 0;
- funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]);
- }
-
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- m_filterMode = Nearest;
-}
-
-void QGLTextureGlyphCache::resizeTextureData(int width, int height)
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx == 0) {
- qWarning("QGLTextureGlyphCache::resizeTextureData: Called with no context");
- return;
- }
- QOpenGLFunctions *funcs = ctx->contextHandle()->functions();
-
- int oldWidth = m_textureResource->m_width;
- int oldHeight = m_textureResource->m_height;
-
- // Make the lower glyph texture size 16 x 16.
- if (width < 16)
- width = 16;
- if (height < 16)
- height = 16;
-
- GLuint oldTexture = m_textureResource->m_texture;
- createTextureData(width, height);
-
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects() || ctx->d_ptr->workaround_brokenFBOReadBack) {
- QImageTextureGlyphCache::resizeTextureData(width, height);
- Q_ASSERT(image().depth() == 8);
- funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, oldHeight, GL_ALPHA, GL_UNSIGNED_BYTE, image().constBits());
- funcs->glDeleteTextures(1, &oldTexture);
- return;
- }
-
- // ### the QTextureGlyphCache API needs to be reworked to allow
- // ### resizeTextureData to fail
-
- ctx->d_ptr->refreshCurrentFbo();
-
- funcs->glBindFramebuffer(GL_FRAMEBUFFER, m_textureResource->m_fbo);
-
- GLuint tmp_texture;
- funcs->glGenTextures(1, &tmp_texture);
- funcs->glBindTexture(GL_TEXTURE_2D, tmp_texture);
- funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,
- GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- m_filterMode = Nearest;
- funcs->glBindTexture(GL_TEXTURE_2D, 0);
- funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, tmp_texture, 0);
-
- funcs->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
- funcs->glBindTexture(GL_TEXTURE_2D, oldTexture);
-
- if (pex != 0)
- pex->transferMode(BrushDrawingMode);
-
- funcs->glDisable(GL_STENCIL_TEST);
- funcs->glDisable(GL_DEPTH_TEST);
- funcs->glDisable(GL_SCISSOR_TEST);
- funcs->glDisable(GL_BLEND);
-
- funcs->glViewport(0, 0, oldWidth, oldHeight);
-
- QGLShaderProgram *blitProgram = 0;
- if (pex == 0) {
- if (m_blitProgram == 0) {
- m_blitProgram = new QGLShaderProgram(ctx);
-
- {
- QString source;
- source.append(QLatin1String(qglslMainWithTexCoordsVertexShader));
- source.append(QLatin1String(qglslUntransformedPositionVertexShader));
-
- QGLShader *vertexShader = new QGLShader(QGLShader::Vertex, m_blitProgram);
- vertexShader->compileSourceCode(source);
-
- m_blitProgram->addShader(vertexShader);
- }
-
- {
- QString source;
- source.append(QLatin1String(qglslMainFragmentShader));
- source.append(QLatin1String(qglslImageSrcFragmentShader));
-
- QGLShader *fragmentShader = new QGLShader(QGLShader::Fragment, m_blitProgram);
- fragmentShader->compileSourceCode(source);
-
- m_blitProgram->addShader(fragmentShader);
- }
-
- m_blitProgram->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
- m_blitProgram->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);
-
- m_blitProgram->link();
- }
-
- funcs->glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_vertexCoordinateArray);
- funcs->glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_textureCoordinateArray);
-
- m_blitProgram->bind();
- m_blitProgram->enableAttributeArray(int(QT_VERTEX_COORDS_ATTR));
- m_blitProgram->enableAttributeArray(int(QT_TEXTURE_COORDS_ATTR));
- m_blitProgram->disableAttributeArray(int(QT_OPACITY_ATTR));
-
- blitProgram = m_blitProgram;
-
- } else {
- pex->setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, m_vertexCoordinateArray);
- pex->setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, m_textureCoordinateArray);
-
- pex->shaderManager->useBlitProgram();
- blitProgram = pex->shaderManager->blitProgram();
- }
-
- blitProgram->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT);
-
- funcs->glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-
- funcs->glBindTexture(GL_TEXTURE_2D, m_textureResource->m_texture);
-
- funcs->glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);
-
- funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_RENDERBUFFER, 0);
- funcs->glDeleteTextures(1, &tmp_texture);
- funcs->glDeleteTextures(1, &oldTexture);
-
- funcs->glBindFramebuffer(GL_FRAMEBUFFER, ctx->d_ptr->current_fbo);
-
- if (pex != 0) {
- funcs->glViewport(0, 0, pex->width, pex->height);
- pex->updateClipScissorTest();
- }
-}
-
-void QGLTextureGlyphCache::fillTexture(const Coord &c, glyph_t glyph, QFixed subPixelPosition)
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx == 0) {
- qWarning("QGLTextureGlyphCache::fillTexture: Called with no context");
- return;
- }
- QOpenGLFunctions *funcs = ctx->contextHandle()->functions();
-
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects() || ctx->d_ptr->workaround_brokenFBOReadBack) {
- QImageTextureGlyphCache::fillTexture(c, glyph, subPixelPosition);
-
- funcs->glBindTexture(GL_TEXTURE_2D, m_textureResource->m_texture);
- const QImage &texture = image();
- const uchar *bits = texture.constBits();
- bits += c.y * texture.bytesPerLine() + c.x;
- for (int i=0; i<c.h; ++i) {
- funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y + i, c.w, 1, GL_ALPHA, GL_UNSIGNED_BYTE, bits);
- bits += texture.bytesPerLine();
- }
- return;
- }
-
- QImage mask = textureMapForGlyph(glyph, subPixelPosition);
- const int maskWidth = mask.width();
- const int maskHeight = mask.height();
-
- if (mask.format() == QImage::Format_Mono) {
- mask = mask.convertToFormat(QImage::Format_Indexed8);
- for (int y = 0; y < maskHeight; ++y) {
- uchar *src = (uchar *) mask.scanLine(y);
- for (int x = 0; x < maskWidth; ++x)
- src[x] = -src[x]; // convert 0 and 1 into 0 and 255
- }
- } else if (mask.depth() == 32) {
- // Make the alpha component equal to the average of the RGB values.
- // This is needed when drawing sub-pixel antialiased text on translucent targets.
- for (int y = 0; y < maskHeight; ++y) {
- quint32 *src = (quint32 *) mask.scanLine(y);
- for (int x = 0; x < maskWidth; ++x) {
- int r = qRed(src[x]);
- int g = qGreen(src[x]);
- int b = qBlue(src[x]);
- int avg;
- if (mask.format() == QImage::Format_RGB32)
- avg = (r + g + b + 1) / 3; // "+1" for rounding.
- else // Format_ARGB_Premultiplied
- avg = qAlpha(src[x]);
- if (ctx->contextHandle()->isOpenGLES()) {
- // swizzle the bits to accommodate for the GL_RGBA upload.
- src[x] = (avg << 24) | (r << 0) | (g << 8) | (b << 16);
- } else {
- src[x] = (src[x] & 0x00ffffff) | (avg << 24);
- }
- }
- }
- }
-
- funcs->glBindTexture(GL_TEXTURE_2D, m_textureResource->m_texture);
- if (mask.depth() == 32) {
- GLenum format = GL_RGBA;
-#if !defined(QT_OPENGL_ES_2)
- if (!ctx->contextHandle()->isOpenGLES())
- format = GL_BGRA;
-#endif
- funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, format, GL_UNSIGNED_BYTE, mask.bits());
- } else {
- // glTexSubImage2D() might cause some garbage to appear in the texture if the mask width is
- // not a multiple of four bytes. The bug appeared on a computer with 32-bit Windows Vista
- // and nVidia GeForce 8500GT. GL_UNPACK_ALIGNMENT is set to four bytes, 'mask' has a
- // multiple of four bytes per line, and most of the glyph shows up correctly in the
- // texture, which makes me think that this is a driver bug.
- // One workaround is to make sure the mask width is a multiple of four bytes, for instance
- // by converting it to a format with four bytes per pixel. Another is to copy one line at a
- // time.
-
- if (!ctx->d_ptr->workaround_brokenAlphaTexSubImage_init) {
- // don't know which driver versions exhibit this bug, so be conservative for now
- const QByteArray vendorString(reinterpret_cast<const char*>(funcs->glGetString(GL_VENDOR)));
- ctx->d_ptr->workaround_brokenAlphaTexSubImage = vendorString.indexOf("NVIDIA") >= 0;
- ctx->d_ptr->workaround_brokenAlphaTexSubImage_init = true;
- }
-
- if (ctx->d_ptr->workaround_brokenAlphaTexSubImage) {
- for (int i = 0; i < maskHeight; ++i)
- funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y + i, maskWidth, 1, GL_ALPHA, GL_UNSIGNED_BYTE, mask.scanLine(i));
- } else {
- funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_ALPHA, GL_UNSIGNED_BYTE, mask.bits());
- }
- }
-}
-
-int QGLTextureGlyphCache::glyphPadding() const
-{
- return 1;
-}
-
-int QGLTextureGlyphCache::maxTextureWidth() const
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx == 0)
- return QImageTextureGlyphCache::maxTextureWidth();
- else
- return ctx->d_ptr->maxTextureSize();
-}
-
-int QGLTextureGlyphCache::maxTextureHeight() const
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx == 0)
- return QImageTextureGlyphCache::maxTextureHeight();
-
- if (ctx->d_ptr->workaround_brokenTexSubImage)
- return qMin(1024, ctx->d_ptr->maxTextureSize());
- else
- return ctx->d_ptr->maxTextureSize();
-}
-
-void QGLTextureGlyphCache::clear()
-{
- m_textureResource->free();
- m_textureResource = 0;
-
- m_w = 0;
- m_h = 0;
- m_cx = 0;
- m_cy = 0;
- m_currentRowHeight = 0;
- coords.clear();
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qtextureglyphcache_gl_p.h b/src/opengl/gl2paintengineex/qtextureglyphcache_gl_p.h
deleted file mode 100644
index 7c12ce8998..0000000000
--- a/src/opengl/gl2paintengineex/qtextureglyphcache_gl_p.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTEXTUREGLYPHCACHE_GL_P_H
-#define QTEXTUREGLYPHCACHE_GL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <private/qtextureglyphcache_p.h>
-#include <private/qgl_p.h>
-#include <qglshaderprogram.h>
-#include <qglframebufferobject.h>
-#include <qopenglfunctions.h>
-
-// #define QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-class QGL2PaintEngineExPrivate;
-
-struct QGLGlyphTexture : public QOpenGLSharedResource
-{
- QGLGlyphTexture(const QGLContext *ctx)
- : QOpenGLSharedResource(ctx->contextHandle()->shareGroup())
- , m_fbo(0)
- , m_width(0)
- , m_height(0)
- {
- if (ctx && QGLFramebufferObject::hasOpenGLFramebufferObjects() && !ctx->d_ptr->workaround_brokenFBOReadBack)
- ctx->contextHandle()->functions()->glGenFramebuffers(1, &m_fbo);
-
-#ifdef QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
- qDebug(" -> QGLGlyphTexture() %p for context %p.", this, ctx);
-#endif
- }
-
- void freeResource(QOpenGLContext *context) override
- {
- const QGLContext *ctx = QGLContext::fromOpenGLContext(context);
-#ifdef QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
- qDebug("~QGLGlyphTexture() %p for context %p.", this, ctx);
-#else
- Q_UNUSED(ctx);
-#endif
- if (ctx && m_fbo)
- ctx->contextHandle()->functions()->glDeleteFramebuffers(1, &m_fbo);
- if (m_width || m_height)
- ctx->contextHandle()->functions()->glDeleteTextures(1, &m_texture);
- }
-
- void invalidateResource() override
- {
- m_texture = 0;
- m_fbo = 0;
- m_width = 0;
- m_height = 0;
- }
-
- GLuint m_texture;
- GLuint m_fbo;
- int m_width;
- int m_height;
-};
-
-class Q_OPENGL_EXPORT QGLTextureGlyphCache : public QImageTextureGlyphCache
-{
-public:
- QGLTextureGlyphCache(QFontEngine::GlyphFormat format, const QTransform &matrix);
- ~QGLTextureGlyphCache();
-
- virtual void createTextureData(int width, int height) override;
- virtual void resizeTextureData(int width, int height) override;
- virtual void fillTexture(const Coord &c, glyph_t glyph, QFixed subPixelPosition) override;
- virtual int glyphPadding() const override;
- virtual int maxTextureWidth() const override;
- virtual int maxTextureHeight() const override;
-
- inline GLuint texture() const {
- QGLTextureGlyphCache *that = const_cast<QGLTextureGlyphCache *>(this);
- QGLGlyphTexture *glyphTexture = that->m_textureResource;
- return glyphTexture ? glyphTexture->m_texture : 0;
- }
-
- inline int width() const {
- QGLTextureGlyphCache *that = const_cast<QGLTextureGlyphCache *>(this);
- QGLGlyphTexture *glyphTexture = that->m_textureResource;
- return glyphTexture ? glyphTexture->m_width : 0;
- }
- inline int height() const {
- QGLTextureGlyphCache *that = const_cast<QGLTextureGlyphCache *>(this);
- QGLGlyphTexture *glyphTexture = that->m_textureResource;
- return glyphTexture ? glyphTexture->m_height : 0;
- }
-
- inline void setPaintEnginePrivate(QGL2PaintEngineExPrivate *p) { pex = p; }
-
- inline const QOpenGLContextGroup *contextGroup() const { return m_textureResource ? m_textureResource->group() : nullptr; }
-
- inline int serialNumber() const { return m_serialNumber; }
-
- enum FilterMode {
- Nearest,
- Linear
- };
- FilterMode filterMode() const { return m_filterMode; }
- void setFilterMode(FilterMode m) { m_filterMode = m; }
-
- void clear();
-
-private:
- QGLGlyphTexture *m_textureResource;
-
- QGL2PaintEngineExPrivate *pex;
- QGLShaderProgram *m_blitProgram;
- FilterMode m_filterMode;
-
- GLfloat m_vertexCoordinateArray[8];
- GLfloat m_textureCoordinateArray[8];
-
- int m_serialNumber;
-};
-
-QT_END_NAMESPACE
-
-#endif
-
diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro
index 8b2349ff2f..eaa10de22a 100644
--- a/src/opengl/opengl.pro
+++ b/src/opengl/opengl.pro
@@ -1,57 +1,32 @@
TARGET = QtOpenGL
-QT = core-private gui-private widgets-private
+QT = core-private gui-private
+qtConfig(widgets): QT += widgets widgets-private
DEFINES += QT_NO_USING_NAMESPACE QT_NO_FOREACH
-msvc:equals(QT_ARCH, i386): QMAKE_LFLAGS += /BASE:0x63000000
-solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2
-
QMAKE_DOCS = $$PWD/doc/qtopengl.qdocconf
qtConfig(opengl): CONFIG += opengl
qtConfig(opengles2): CONFIG += opengles2
-HEADERS += qgl.h \
- qgl_p.h \
- qglcolormap.h \
- qglfunctions.h \
- qglpixelbuffer.h \
- qglpixelbuffer_p.h \
- qglframebufferobject.h \
- qglframebufferobject_p.h \
- qglpaintdevice_p.h \
- qglbuffer.h \
- qtopenglglobal.h
-
-SOURCES += qgl.cpp \
- qglcolormap.cpp \
- qglfunctions.cpp \
- qglpixelbuffer.cpp \
- qglframebufferobject.cpp \
- qglpaintdevice.cpp \
- qglbuffer.cpp \
-
-HEADERS += qglshaderprogram.h \
- gl2paintengineex/qglgradientcache_p.h \
- gl2paintengineex/qglengineshadermanager_p.h \
- gl2paintengineex/qgl2pexvertexarray_p.h \
- gl2paintengineex/qpaintengineex_opengl2_p.h \
- gl2paintengineex/qglengineshadersource_p.h \
- gl2paintengineex/qglcustomshaderstage_p.h \
- gl2paintengineex/qtextureglyphcache_gl_p.h \
- gl2paintengineex/qglshadercache_p.h
-
-SOURCES += qglshaderprogram.cpp \
- gl2paintengineex/qglgradientcache.cpp \
- gl2paintengineex/qglengineshadermanager.cpp \
- gl2paintengineex/qgl2pexvertexarray.cpp \
- gl2paintengineex/qpaintengineex_opengl2.cpp \
- gl2paintengineex/qglcustomshaderstage.cpp \
- gl2paintengineex/qtextureglyphcache_gl.cpp
-
-qtConfig(graphicseffect) {
- HEADERS += qgraphicsshadereffect_p.h
- SOURCES += qgraphicsshadereffect.cpp
+HEADERS += \
+ qopengldebug.h \
+ qtopenglglobal.h
+
+SOURCES += \
+ qopengldebug.cpp
+
+!qtConfig(opengles2) {
+ HEADERS += \
+ qopenglqueryhelper_p.h \
+ qopengltimerquery.h
+
+ SOURCES += qopengltimerquery.cpp
+}
+
+qtConfig(widgets) {
+ HEADERS += qopenglwidget.h
+ SOURCES += qopenglwidget.cpp
}
load(qt_module)
diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp
deleted file mode 100644
index 4108b70094..0000000000
--- a/src/opengl/qgl.cpp
+++ /dev/null
@@ -1,5558 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qapplication.h"
-#include "qplatformdefs.h"
-#include "qgl.h"
-#include <qdebug.h>
-#include <qglfunctions.h>
-
-#include <qdatetime.h>
-
-#include <stdlib.h> // malloc
-
-#include "qpixmap.h"
-#include "qimage.h"
-#include "qgl_p.h"
-
-#include "gl2paintengineex/qpaintengineex_opengl2_p.h"
-
-#include <qpa/qplatformopenglcontext.h>
-
-#include <qglpixelbuffer.h>
-#include <qglframebufferobject.h>
-#include <private/qopenglextensions_p.h>
-
-#include <private/qimage_p.h>
-#include <qpa/qplatformpixmap.h>
-#include <private/qglpixelbuffer_p.h>
-#include <private/qimagepixmapcleanuphooks_p.h>
-#include "qcolormap.h"
-#include "qfile.h"
-#include <qmutex.h>
-
-#include "qsurfaceformat.h"
-#include <private/qapplication_p.h>
-#include <qpa/qplatformopenglcontext.h>
-#include <qpa/qplatformwindow.h>
-
-#ifndef QT_OPENGL_ES_2
-#include <qopenglfunctions_1_1.h>
-#endif
-
-// #define QT_GL_CONTEXT_RESOURCE_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-class QGLDefaultExtensions
-{
-public:
- QGLDefaultExtensions()
- {
- QGLTemporaryContext tempContext;
- Q_ASSERT(QOpenGLContext::currentContext());
- QOpenGLExtensions *ext = qgl_extensions();
- Q_ASSERT(ext);
- extensions = ext->openGLExtensions();
- features = ext->openGLFeatures();
- }
-
- QOpenGLFunctions::OpenGLFeatures features;
- QOpenGLExtensions::OpenGLExtensions extensions;
-};
-
-Q_GLOBAL_STATIC(QGLDefaultExtensions, qtDefaultExtensions)
-
-bool qgl_hasFeature(QOpenGLFunctions::OpenGLFeature feature)
-{
- if (QOpenGLContext::currentContext())
- return QOpenGLContext::currentContext()->functions()->hasOpenGLFeature(feature);
- return qtDefaultExtensions()->features & feature;
-}
-
-bool qgl_hasExtension(QOpenGLExtensions::OpenGLExtension extension)
-{
- if (QOpenGLContext::currentContext())
- return qgl_extensions()->hasOpenGLExtension(extension);
- return qtDefaultExtensions()->extensions & extension;
-}
-
-QOpenGLExtensions::OpenGLExtensions extensions;
-
-/*
- Returns the GL extensions for the current QOpenGLContext. If there is no
- current QOpenGLContext, a default context will be created and the extensions
- for that context will be returned instead.
-*/
-QOpenGLExtensions* qgl_extensions()
-{
- if (QOpenGLContext *context = QOpenGLContext::currentContext())
- return static_cast<QOpenGLExtensions *>(context->functions());
-
- Q_ASSERT(false);
- return 0;
-}
-
-QOpenGLFunctions *qgl_functions()
-{
- return qgl_extensions(); // QOpenGLExtensions is just a subclass of QOpenGLFunctions
-}
-
-#ifndef QT_OPENGL_ES_2
-QOpenGLFunctions_1_1 *qgl1_functions()
-{
- QOpenGLFunctions_1_1 *f = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_1_1>();
- f->initializeOpenGLFunctions();
- return f;
-}
-#endif
-
-struct QGLThreadContext {
- ~QGLThreadContext() {
- if (context)
- context->doneCurrent();
- }
- QGLContext *context;
-};
-
-Q_GLOBAL_STATIC(QGLFormat, qgl_default_format)
-
-class QGLDefaultOverlayFormat: public QGLFormat
-{
-public:
- inline QGLDefaultOverlayFormat()
- {
- setOption(QGL::FormatOption(0xffffU << 16)); // turn off all options
- setOption(QGL::DirectRendering);
- setPlane(1);
- }
-};
-Q_GLOBAL_STATIC(QGLDefaultOverlayFormat, defaultOverlayFormatInstance)
-
-Q_GLOBAL_STATIC(QGLSignalProxy, theSignalProxy)
-QGLSignalProxy *QGLSignalProxy::instance()
-{
- QGLSignalProxy *proxy = theSignalProxy();
- if (proxy && qApp && proxy->thread() != qApp->thread()) {
- if (proxy->thread() == QThread::currentThread())
- proxy->moveToThread(qApp->thread());
- }
- return proxy;
-}
-
-
-/*!
- \namespace QGL
- \inmodule QtOpenGL
-
- \brief The QGL namespace specifies miscellaneous identifiers used
- in the Qt OpenGL module.
-*/
-
-/*!
- \enum QGL::FormatOption
-
- This enum specifies the format options that can be used to configure an OpenGL
- context. These are set using QGLFormat::setOption().
-
- \value DoubleBuffer Specifies the use of double buffering.
- \value DepthBuffer Enables the use of a depth buffer.
- \value Rgba Specifies that the context should use RGBA as its pixel format.
- \value AlphaChannel Enables the use of an alpha channel.
- \value AccumBuffer Enables the use of an accumulation buffer.
- \value StencilBuffer Enables the use of a stencil buffer.
- \value StereoBuffers Enables the use of a stereo buffers for use with visualization hardware.
- \value DirectRendering Specifies that the context is used for direct rendering to a display.
- \value HasOverlay Enables the use of an overlay.
- \value SampleBuffers Enables the use of sample buffers.
- \value DeprecatedFunctions Enables the use of deprecated functionality for OpenGL 3.x
- contexts. A context with deprecated functionality enabled is
- called a full context in the OpenGL specification.
- \value SingleBuffer Specifies the use of a single buffer, as opposed to double buffers.
- \value NoDepthBuffer Disables the use of a depth buffer.
- \value ColorIndex Specifies that the context should use a color index as its pixel format.
- \value NoAlphaChannel Disables the use of an alpha channel.
- \value NoAccumBuffer Disables the use of an accumulation buffer.
- \value NoStencilBuffer Disables the use of a stencil buffer.
- \value NoStereoBuffers Disables the use of stereo buffers.
- \value IndirectRendering Specifies that the context is used for indirect rendering to a buffer.
- \value NoOverlay Disables the use of an overlay.
- \value NoSampleBuffers Disables the use of sample buffers.
- \value NoDeprecatedFunctions Disables the use of deprecated functionality for OpenGL 3.x
- contexts. A context with deprecated functionality disabled is
- called a forward compatible context in the OpenGL specification.
-*/
-
-/*****************************************************************************
- QGLFormat implementation
- *****************************************************************************/
-
-
-/*!
- \class QGLFormat
- \inmodule QtOpenGL
- \obsolete
-
- \brief The QGLFormat class specifies the display format of an OpenGL
- rendering context.
-
- A display format has several characteristics:
- \list
- \li \l{setDoubleBuffer()}{Double or single buffering.}
- \li \l{setDepth()}{Depth buffer.}
- \li \l{setRgba()}{RGBA or color index mode.}
- \li \l{setAlpha()}{Alpha channel.}
- \li \l{setAccum()}{Accumulation buffer.}
- \li \l{setStencil()}{Stencil buffer.}
- \li \l{setStereo()}{Stereo buffers.}
- \li \l{setDirectRendering()}{Direct rendering.}
- \li \l{setOverlay()}{Presence of an overlay.}
- \li \l{setPlane()}{Plane of an overlay.}
- \li \l{setSampleBuffers()}{Multisample buffers.}
- \endlist
-
- You can also specify preferred bit depths for the color buffer,
- depth buffer, alpha buffer, accumulation buffer and the stencil
- buffer with the functions: setRedBufferSize(), setGreenBufferSize(),
- setBlueBufferSize(), setDepthBufferSize(), setAlphaBufferSize(),
- setAccumBufferSize() and setStencilBufferSize().
-
- Note that even if you specify that you prefer a 32 bit depth
- buffer (e.g. with setDepthBufferSize(32)), the format that is
- chosen may not have a 32 bit depth buffer, even if there is a
- format available with a 32 bit depth buffer. The main reason for
- this is how the system dependant picking algorithms work on the
- different platforms, and some format options may have higher
- precedence than others.
-
- You create and tell a QGLFormat object what rendering options you
- want from an OpenGL rendering context.
-
- OpenGL drivers or accelerated hardware may or may not support
- advanced features such as alpha channel or stereographic viewing.
- If you request some features that the driver/hardware does not
- provide when you create a QGLWidget, you will get a rendering
- context with the nearest subset of features.
-
- There are different ways to define the display characteristics of
- a rendering context. One is to create a QGLFormat and make it the
- default for the entire application:
- \snippet code/src_opengl_qgl.cpp 0
-
- Or you can specify the desired format when creating an object of
- your QGLWidget subclass:
- \snippet code/src_opengl_qgl.cpp 1
-
- After the widget has been created, you can find out which of the
- requested features the system was able to provide:
- \snippet code/src_opengl_qgl.cpp 2
-
- \legalese
- OpenGL is a trademark of Silicon Graphics, Inc. in the
- United States and other countries.
- \endlegalese
-
- \sa QGLContext, QGLWidget
-*/
-
-#ifndef QT_OPENGL_ES
-
-static inline void transform_point(GLdouble out[4], const GLdouble m[16], const GLdouble in[4])
-{
-#define M(row,col) m[col*4+row]
- out[0] =
- M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
- out[1] =
- M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
- out[2] =
- M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
- out[3] =
- M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
-#undef M
-}
-
-static inline GLint qgluProject(GLdouble objx, GLdouble objy, GLdouble objz,
- const GLdouble model[16], const GLdouble proj[16],
- const GLint viewport[4],
- GLdouble * winx, GLdouble * winy, GLdouble * winz)
-{
- GLdouble in[4], out[4];
-
- in[0] = objx;
- in[1] = objy;
- in[2] = objz;
- in[3] = 1.0;
- transform_point(out, model, in);
- transform_point(in, proj, out);
-
- if (in[3] == 0.0)
- return GL_FALSE;
-
- in[0] /= in[3];
- in[1] /= in[3];
- in[2] /= in[3];
-
- *winx = viewport[0] + (1 + in[0]) * viewport[2] / 2;
- *winy = viewport[1] + (1 + in[1]) * viewport[3] / 2;
-
- *winz = (1 + in[2]) / 2;
- return GL_TRUE;
-}
-
-#endif // !QT_OPENGL_ES
-
-/*!
- Constructs a QGLFormat object with the following default settings:
- \list
- \li \l{setDoubleBuffer()}{Double buffer:} Enabled.
- \li \l{setDepth()}{Depth buffer:} Enabled.
- \li \l{setRgba()}{RGBA:} Enabled (i.e., color index disabled).
- \li \l{setAlpha()}{Alpha channel:} Disabled.
- \li \l{setAccum()}{Accumulator buffer:} Disabled.
- \li \l{setStencil()}{Stencil buffer:} Enabled.
- \li \l{setStereo()}{Stereo:} Disabled.
- \li \l{setDirectRendering()}{Direct rendering:} Enabled.
- \li \l{setOverlay()}{Overlay:} Disabled.
- \li \l{setPlane()}{Plane:} 0 (i.e., normal plane).
- \li \l{setSampleBuffers()}{Multisample buffers:} Disabled.
- \endlist
-*/
-
-QGLFormat::QGLFormat()
-{
- d = new QGLFormatPrivate;
-}
-
-
-/*!
- Creates a QGLFormat object that is a copy of the current
- defaultFormat().
-
- If \a options is not 0, the default format is modified by the
- specified format options. The \a options parameter should be
- QGL::FormatOption values OR'ed together.
-
- This constructor makes it easy to specify a certain desired format
- in classes derived from QGLWidget, for example:
- \snippet code/src_opengl_qgl.cpp 3
-
- Note that there are QGL::FormatOption values to turn format settings
- both on and off, e.g. QGL::DepthBuffer and QGL::NoDepthBuffer,
- QGL::DirectRendering and QGL::IndirectRendering, etc.
-
- The \a plane parameter defaults to 0 and is the plane which this
- format should be associated with. Not all OpenGL implementations
- supports overlay/underlay rendering planes.
-
- \sa defaultFormat(), setOption(), setPlane()
-*/
-
-QGLFormat::QGLFormat(QGL::FormatOptions options, int plane)
-{
- d = new QGLFormatPrivate;
- QGL::FormatOptions newOpts = options;
- d->opts = defaultFormat().d->opts;
- d->opts |= (newOpts & 0xffff);
- d->opts &= ~(newOpts >> 16);
- d->pln = plane;
-}
-
-/*!
- \internal
-*/
-void QGLFormat::detach()
-{
- if (d->ref.loadRelaxed() != 1) {
- QGLFormatPrivate *newd = new QGLFormatPrivate(d);
- if (!d->ref.deref())
- delete d;
- d = newd;
- }
-}
-
-/*!
- Constructs a copy of \a other.
-*/
-
-QGLFormat::QGLFormat(const QGLFormat &other)
-{
- d = other.d;
- d->ref.ref();
-}
-
-/*!
- Assigns \a other to this object.
-*/
-
-QGLFormat &QGLFormat::operator=(const QGLFormat &other)
-{
- if (d != other.d) {
- other.d->ref.ref();
- if (!d->ref.deref())
- delete d;
- d = other.d;
- }
- return *this;
-}
-
-/*!
- Destroys the QGLFormat.
-*/
-QGLFormat::~QGLFormat()
-{
- if (!d->ref.deref())
- delete d;
-}
-
-/*!
- Returns an OpenGL format for the window format specified by \a format.
-*/
-QGLFormat QGLFormat::fromSurfaceFormat(const QSurfaceFormat &format)
-{
- QGLFormat retFormat;
- if (format.alphaBufferSize() >= 0)
- retFormat.setAlphaBufferSize(format.alphaBufferSize());
- if (format.blueBufferSize() >= 0)
- retFormat.setBlueBufferSize(format.blueBufferSize());
- if (format.greenBufferSize() >= 0)
- retFormat.setGreenBufferSize(format.greenBufferSize());
- if (format.redBufferSize() >= 0)
- retFormat.setRedBufferSize(format.redBufferSize());
- if (format.depthBufferSize() >= 0)
- retFormat.setDepthBufferSize(format.depthBufferSize());
- if (format.samples() > 1) {
- retFormat.setSampleBuffers(true);
- retFormat.setSamples(format.samples());
- }
- if (format.stencilBufferSize() > 0) {
- retFormat.setStencil(true);
- retFormat.setStencilBufferSize(format.stencilBufferSize());
- }
- retFormat.setSwapInterval(format.swapInterval());
- retFormat.setDoubleBuffer(format.swapBehavior() != QSurfaceFormat::SingleBuffer);
- retFormat.setStereo(format.stereo());
- retFormat.setVersion(format.majorVersion(), format.minorVersion());
- retFormat.setProfile(static_cast<QGLFormat::OpenGLContextProfile>(format.profile()));
- return retFormat;
-}
-
-/*!
- Returns a window format for the OpenGL format specified by \a format.
-*/
-QSurfaceFormat QGLFormat::toSurfaceFormat(const QGLFormat &format)
-{
- QSurfaceFormat retFormat;
- if (format.alpha())
- retFormat.setAlphaBufferSize(format.alphaBufferSize() == -1 ? 1 : format.alphaBufferSize());
- if (format.blueBufferSize() >= 0)
- retFormat.setBlueBufferSize(format.blueBufferSize());
- if (format.greenBufferSize() >= 0)
- retFormat.setGreenBufferSize(format.greenBufferSize());
- if (format.redBufferSize() >= 0)
- retFormat.setRedBufferSize(format.redBufferSize());
- if (format.depth())
- retFormat.setDepthBufferSize(format.depthBufferSize() == -1 ? 1 : format.depthBufferSize());
- retFormat.setSwapBehavior(format.doubleBuffer() ? QSurfaceFormat::DoubleBuffer : QSurfaceFormat::SingleBuffer);
- if (format.sampleBuffers())
- retFormat.setSamples(format.samples() == -1 ? 4 : format.samples());
- if (format.stencil())
- retFormat.setStencilBufferSize(format.stencilBufferSize() == -1 ? 1 : format.stencilBufferSize());
- retFormat.setSwapInterval(format.swapInterval());
- retFormat.setStereo(format.stereo());
- retFormat.setMajorVersion(format.majorVersion());
- retFormat.setMinorVersion(format.minorVersion());
- retFormat.setProfile(static_cast<QSurfaceFormat::OpenGLContextProfile>(format.profile()));
- // QGLFormat has no way to set DeprecatedFunctions, that is, to tell that forward
- // compatibility should not be requested. Some drivers fail to ignore the fwdcompat
- // bit with compatibility profiles so make sure it is not set.
- if (format.profile() == QGLFormat::CompatibilityProfile)
- retFormat.setOption(QSurfaceFormat::DeprecatedFunctions);
- return retFormat;
-}
-
-void QGLContextPrivate::setupSharing() {
- Q_Q(QGLContext);
- QOpenGLContext *sharedContext = guiGlContext->shareContext();
- if (sharedContext) {
- QGLContext *actualSharedContext = QGLContext::fromOpenGLContext(sharedContext);
- sharing = true;
- QGLContextGroup::addShare(q, actualSharedContext);
- }
-}
-
-void QGLContextPrivate::refreshCurrentFbo()
-{
- QOpenGLContextPrivate *guiGlContextPrivate =
- guiGlContext ? QOpenGLContextPrivate::get(guiGlContext) : 0;
-
- // if QOpenGLFramebufferObjects have been used in the mean-time, we've lost our cached value
- if (guiGlContextPrivate && guiGlContextPrivate->qgl_current_fbo_invalid) {
- GLint current;
- QOpenGLFunctions *funcs = qgl_functions();
- funcs->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &current);
-
- current_fbo = current;
-
- guiGlContextPrivate->qgl_current_fbo_invalid = false;
- }
-}
-
-void QGLContextPrivate::setCurrentFbo(GLuint fbo)
-{
- current_fbo = fbo;
-
- QOpenGLContextPrivate *guiGlContextPrivate =
- guiGlContext ? QOpenGLContextPrivate::get(guiGlContext) : 0;
-
- if (guiGlContextPrivate)
- guiGlContextPrivate->qgl_current_fbo_invalid = false;
-}
-
-
-/*!
- \fn bool QGLFormat::doubleBuffer() const
-
- Returns \c true if double buffering is enabled; otherwise returns
- false. Double buffering is enabled by default.
-
- \sa setDoubleBuffer()
-*/
-
-/*!
- If \a enable is true sets double buffering; otherwise sets single
- buffering.
-
- Double buffering is enabled by default.
-
- Double buffering is a technique where graphics are rendered on an
- off-screen buffer and not directly to the screen. When the drawing
- has been completed, the program calls a swapBuffers() function to
- exchange the screen contents with the buffer. The result is
- flicker-free drawing and often better performance.
-
- Note that single buffered contexts are currently not supported
- with EGL.
-
- \sa doubleBuffer(), QGLContext::swapBuffers(),
- QGLWidget::swapBuffers()
-*/
-
-void QGLFormat::setDoubleBuffer(bool enable)
-{
- setOption(enable ? QGL::DoubleBuffer : QGL::SingleBuffer);
-}
-
-
-/*!
- \fn bool QGLFormat::depth() const
-
- Returns \c true if the depth buffer is enabled; otherwise returns
- false. The depth buffer is enabled by default.
-
- \sa setDepth(), setDepthBufferSize()
-*/
-
-/*!
- If \a enable is true enables the depth buffer; otherwise disables
- the depth buffer.
-
- The depth buffer is enabled by default.
-
- The purpose of a depth buffer (or Z-buffering) is to remove hidden
- surfaces. Pixels are assigned Z values based on the distance to
- the viewer. A pixel with a high Z value is closer to the viewer
- than a pixel with a low Z value. This information is used to
- decide whether to draw a pixel or not.
-
- \sa depth(), setDepthBufferSize()
-*/
-
-void QGLFormat::setDepth(bool enable)
-{
- setOption(enable ? QGL::DepthBuffer : QGL::NoDepthBuffer);
-}
-
-
-/*!
- \fn bool QGLFormat::rgba() const
-
- Returns \c true if RGBA color mode is set. Returns \c false if color
- index mode is set. The default color mode is RGBA.
-
- \sa setRgba()
-*/
-
-/*!
- If \a enable is true sets RGBA mode. If \a enable is false sets
- color index mode.
-
- The default color mode is RGBA.
-
- RGBA is the preferred mode for most OpenGL applications. In RGBA
- color mode you specify colors as red + green + blue + alpha
- quadruplets.
-
- In color index mode you specify an index into a color lookup
- table.
-
- \sa rgba()
-*/
-
-void QGLFormat::setRgba(bool enable)
-{
- setOption(enable ? QGL::Rgba : QGL::ColorIndex);
-}
-
-
-/*!
- \fn bool QGLFormat::alpha() const
-
- Returns \c true if the alpha buffer in the framebuffer is enabled;
- otherwise returns \c false. The alpha buffer is disabled by default.
-
- \sa setAlpha(), setAlphaBufferSize()
-*/
-
-/*!
- If \a enable is true enables the alpha buffer; otherwise disables
- the alpha buffer.
-
- The alpha buffer is disabled by default.
-
- The alpha buffer is typically used for implementing transparency
- or translucency. The A in RGBA specifies the transparency of a
- pixel.
-
- \sa alpha(), setAlphaBufferSize()
-*/
-
-void QGLFormat::setAlpha(bool enable)
-{
- setOption(enable ? QGL::AlphaChannel : QGL::NoAlphaChannel);
-}
-
-
-/*!
- \fn bool QGLFormat::accum() const
-
- Returns \c true if the accumulation buffer is enabled; otherwise
- returns \c false. The accumulation buffer is disabled by default.
-
- \sa setAccum(), setAccumBufferSize()
-*/
-
-/*!
- If \a enable is true enables the accumulation buffer; otherwise
- disables the accumulation buffer.
-
- The accumulation buffer is disabled by default.
-
- The accumulation buffer is used to create blur effects and
- multiple exposures.
-
- \sa accum(), setAccumBufferSize()
-*/
-
-void QGLFormat::setAccum(bool enable)
-{
- setOption(enable ? QGL::AccumBuffer : QGL::NoAccumBuffer);
-}
-
-
-/*!
- \fn bool QGLFormat::stencil() const
-
- Returns \c true if the stencil buffer is enabled; otherwise returns
- false. The stencil buffer is enabled by default.
-
- \sa setStencil(), setStencilBufferSize()
-*/
-
-/*!
- If \a enable is true enables the stencil buffer; otherwise
- disables the stencil buffer.
-
- The stencil buffer is enabled by default.
-
- The stencil buffer masks certain parts of the drawing area so that
- masked parts are not drawn on.
-
- \sa stencil(), setStencilBufferSize()
-*/
-
-void QGLFormat::setStencil(bool enable)
-{
- setOption(enable ? QGL::StencilBuffer: QGL::NoStencilBuffer);
-}
-
-
-/*!
- \fn bool QGLFormat::stereo() const
-
- Returns \c true if stereo buffering is enabled; otherwise returns
- false. Stereo buffering is disabled by default.
-
- \sa setStereo()
-*/
-
-/*!
- If \a enable is true enables stereo buffering; otherwise disables
- stereo buffering.
-
- Stereo buffering is disabled by default.
-
- Stereo buffering provides extra color buffers to generate left-eye
- and right-eye images.
-
- \sa stereo()
-*/
-
-void QGLFormat::setStereo(bool enable)
-{
- setOption(enable ? QGL::StereoBuffers : QGL::NoStereoBuffers);
-}
-
-
-/*!
- \fn bool QGLFormat::directRendering() const
-
- Returns \c true if direct rendering is enabled; otherwise returns
- false.
-
- Direct rendering is enabled by default.
-
- \sa setDirectRendering()
-*/
-
-/*!
- If \a enable is true enables direct rendering; otherwise disables
- direct rendering.
-
- Direct rendering is enabled by default.
-
- Enabling this option will make OpenGL bypass the underlying window
- system and render directly from hardware to the screen, if this is
- supported by the system.
-
- \sa directRendering()
-*/
-
-void QGLFormat::setDirectRendering(bool enable)
-{
- setOption(enable ? QGL::DirectRendering : QGL::IndirectRendering);
-}
-
-/*!
- \fn bool QGLFormat::sampleBuffers() const
-
- Returns \c true if multisample buffer support is enabled; otherwise
- returns \c false.
-
- The multisample buffer is disabled by default.
-
- \sa setSampleBuffers()
-*/
-
-/*!
- If \a enable is true, a GL context with multisample buffer support
- is picked; otherwise ignored.
-
- \sa sampleBuffers(), setSamples(), samples()
-*/
-void QGLFormat::setSampleBuffers(bool enable)
-{
- setOption(enable ? QGL::SampleBuffers : QGL::NoSampleBuffers);
-}
-
-/*!
- Returns the number of samples per pixel when multisampling is
- enabled. By default, the highest number of samples that is
- available is used.
-
- \sa setSampleBuffers(), sampleBuffers(), setSamples()
-*/
-int QGLFormat::samples() const
-{
- return d->numSamples;
-}
-
-/*!
- Set the preferred number of samples per pixel when multisampling
- is enabled to \a numSamples. By default, the highest number of
- samples available is used.
-
- \sa setSampleBuffers(), sampleBuffers(), samples()
-*/
-void QGLFormat::setSamples(int numSamples)
-{
- detach();
- if (numSamples < 0) {
- qWarning("QGLFormat::setSamples: Cannot have negative number of samples per pixel %d", numSamples);
- return;
- }
- d->numSamples = numSamples;
- setSampleBuffers(numSamples > 0);
-}
-
-/*!
- \since 4.2
-
- Set the preferred swap interval. This can be used to sync the GL
- drawing into a system window to the vertical refresh of the screen.
- Setting an \a interval value of 0 will turn the vertical refresh syncing
- off, any value higher than 0 will turn the vertical syncing on.
-
- Under Windows and under X11, where the \c{WGL_EXT_swap_control}
- and \c{GLX_SGI_video_sync} extensions are used, the \a interval
- parameter can be used to set the minimum number of video frames
- that are displayed before a buffer swap will occur. In effect,
- setting the \a interval to 10, means there will be 10 vertical
- retraces between every buffer swap.
-
- Under Windows the \c{WGL_EXT_swap_control} extension has to be present,
- and under X11 the \c{GLX_SGI_video_sync} extension has to be present.
-*/
-void QGLFormat::setSwapInterval(int interval)
-{
- detach();
- d->swapInterval = interval;
-}
-
-/*!
- \since 4.2
-
- Returns the currently set swap interval. -1 is returned if setting
- the swap interval isn't supported in the system GL implementation.
-*/
-int QGLFormat::swapInterval() const
-{
- return d->swapInterval;
-}
-
-/*!
- \fn bool QGLFormat::hasOverlay() const
-
- Returns \c true if overlay plane is enabled; otherwise returns \c false.
-
- Overlay is disabled by default.
-
- \sa setOverlay()
-*/
-
-/*!
- If \a enable is true enables an overlay plane; otherwise disables
- the overlay plane.
-
- Enabling the overlay plane will cause QGLWidget to create an
- additional context in an overlay plane. See the QGLWidget
- documentation for further information.
-
- \sa hasOverlay()
-*/
-
-void QGLFormat::setOverlay(bool enable)
-{
- setOption(enable ? QGL::HasOverlay : QGL::NoOverlay);
-}
-
-/*!
- Returns the plane of this format. The default for normal formats
- is 0, which means the normal plane. The default for overlay
- formats is 1, which is the first overlay plane.
-
- \sa setPlane(), defaultOverlayFormat()
-*/
-int QGLFormat::plane() const
-{
- return d->pln;
-}
-
-/*!
- Sets the requested plane to \a plane. 0 is the normal plane, 1 is
- the first overlay plane, 2 is the second overlay plane, etc.; -1,
- -2, etc. are underlay planes.
-
- Note that in contrast to other format specifications, the plane
- specifications will be matched exactly. This means that if you
- specify a plane that the underlying OpenGL system cannot provide,
- an \l{QGLWidget::isValid()}{invalid} QGLWidget will be
- created.
-
- \sa plane()
-*/
-void QGLFormat::setPlane(int plane)
-{
- detach();
- d->pln = plane;
-}
-
-/*!
- Sets the format option to \a opt.
-
- \sa testOption()
-*/
-
-void QGLFormat::setOption(QGL::FormatOptions opt)
-{
- detach();
- if (opt & 0xffff)
- d->opts |= opt;
- else
- d->opts &= ~(opt >> 16);
-}
-
-
-
-/*!
- Returns \c true if format option \a opt is set; otherwise returns \c false.
-
- \sa setOption()
-*/
-
-bool QGLFormat::testOption(QGL::FormatOptions opt) const
-{
- if (opt & 0xffff)
- return (d->opts & opt) != 0;
- else
- return (d->opts & (opt >> 16)) == 0;
-}
-
-/*!
- Set the minimum depth buffer size to \a size.
-
- \sa depthBufferSize(), setDepth(), depth()
-*/
-void QGLFormat::setDepthBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setDepthBufferSize: Cannot set negative depth buffer size %d", size);
- return;
- }
- d->depthSize = size;
- setDepth(size > 0);
-}
-
-/*!
- Returns the depth buffer size.
-
- \sa depth(), setDepth(), setDepthBufferSize()
-*/
-int QGLFormat::depthBufferSize() const
-{
- return d->depthSize;
-}
-
-/*!
- \since 4.2
-
- Set the preferred red buffer size to \a size.
-
- \sa setGreenBufferSize(), setBlueBufferSize(), setAlphaBufferSize()
-*/
-void QGLFormat::setRedBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setRedBufferSize: Cannot set negative red buffer size %d", size);
- return;
- }
- d->redSize = size;
-}
-
-/*!
- \since 4.2
-
- Returns the red buffer size.
-
- \sa setRedBufferSize()
-*/
-int QGLFormat::redBufferSize() const
-{
- return d->redSize;
-}
-
-/*!
- \since 4.2
-
- Set the preferred green buffer size to \a size.
-
- \sa setRedBufferSize(), setBlueBufferSize(), setAlphaBufferSize()
-*/
-void QGLFormat::setGreenBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setGreenBufferSize: Cannot set negative green buffer size %d", size);
- return;
- }
- d->greenSize = size;
-}
-
-/*!
- \since 4.2
-
- Returns the green buffer size.
-
- \sa setGreenBufferSize()
-*/
-int QGLFormat::greenBufferSize() const
-{
- return d->greenSize;
-}
-
-/*!
- \since 4.2
-
- Set the preferred blue buffer size to \a size.
-
- \sa setRedBufferSize(), setGreenBufferSize(), setAlphaBufferSize()
-*/
-void QGLFormat::setBlueBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setBlueBufferSize: Cannot set negative blue buffer size %d", size);
- return;
- }
- d->blueSize = size;
-}
-
-/*!
- \since 4.2
-
- Returns the blue buffer size.
-
- \sa setBlueBufferSize()
-*/
-int QGLFormat::blueBufferSize() const
-{
- return d->blueSize;
-}
-
-/*!
- Set the preferred alpha buffer size to \a size.
- This function implicitly enables the alpha channel.
-
- \sa setRedBufferSize(), setGreenBufferSize(), alphaBufferSize()
-*/
-void QGLFormat::setAlphaBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setAlphaBufferSize: Cannot set negative alpha buffer size %d", size);
- return;
- }
- d->alphaSize = size;
- setAlpha(size > 0);
-}
-
-/*!
- Returns the alpha buffer size.
-
- \sa alpha(), setAlpha(), setAlphaBufferSize()
-*/
-int QGLFormat::alphaBufferSize() const
-{
- return d->alphaSize;
-}
-
-/*!
- Set the preferred accumulation buffer size, where \a size is the
- bit depth for each RGBA component.
-
- \sa accum(), setAccum(), accumBufferSize()
-*/
-void QGLFormat::setAccumBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setAccumBufferSize: Cannot set negative accumulate buffer size %d", size);
- return;
- }
- d->accumSize = size;
- setAccum(size > 0);
-}
-
-/*!
- Returns the accumulation buffer size.
-
- \sa setAccumBufferSize(), accum(), setAccum()
-*/
-int QGLFormat::accumBufferSize() const
-{
- return d->accumSize;
-}
-
-/*!
- Set the preferred stencil buffer size to \a size.
-
- \sa stencilBufferSize(), setStencil(), stencil()
-*/
-void QGLFormat::setStencilBufferSize(int size)
-{
- detach();
- if (size < 0) {
- qWarning("QGLFormat::setStencilBufferSize: Cannot set negative stencil buffer size %d", size);
- return;
- }
- d->stencilSize = size;
- setStencil(size > 0);
-}
-
-/*!
- Returns the stencil buffer size.
-
- \sa stencil(), setStencil(), setStencilBufferSize()
-*/
-int QGLFormat::stencilBufferSize() const
-{
- return d->stencilSize;
-}
-
-/*!
- \since 4.7
-
- Set the OpenGL version to the \a major and \a minor numbers. If a
- context compatible with the requested OpenGL version cannot be
- created, a context compatible with version 1.x is created instead.
-
- \sa majorVersion(), minorVersion()
-*/
-void QGLFormat::setVersion(int major, int minor)
-{
- if (major < 1 || minor < 0) {
- qWarning("QGLFormat::setVersion: Cannot set zero or negative version number %d.%d", major, minor);
- return;
- }
- detach();
- d->majorVersion = major;
- d->minorVersion = minor;
-}
-
-/*!
- \since 4.7
-
- Returns the OpenGL major version.
-
- \sa setVersion(), minorVersion()
-*/
-int QGLFormat::majorVersion() const
-{
- return d->majorVersion;
-}
-
-/*!
- \since 4.7
-
- Returns the OpenGL minor version.
-
- \sa setVersion(), majorVersion()
-*/
-int QGLFormat::minorVersion() const
-{
- return d->minorVersion;
-}
-
-/*!
- \enum QGLFormat::OpenGLContextProfile
- \since 4.7
-
- This enum describes the OpenGL context profiles that can be
- specified for contexts implementing OpenGL version 3.2 or
- higher. These profiles are different from OpenGL ES profiles.
-
- \value NoProfile OpenGL version is lower than 3.2.
- \value CoreProfile Functionality deprecated in OpenGL version 3.0 is not available.
- \value CompatibilityProfile Functionality from earlier OpenGL versions is available.
-*/
-
-/*!
- \since 4.7
-
- Set the OpenGL context profile to \a profile. The \a profile is
- ignored if the requested OpenGL version is less than 3.2.
-
- \sa profile()
-*/
-void QGLFormat::setProfile(OpenGLContextProfile profile)
-{
- detach();
- d->profile = profile;
-}
-
-/*!
- \since 4.7
-
- Returns the OpenGL context profile.
-
- \sa setProfile()
-*/
-QGLFormat::OpenGLContextProfile QGLFormat::profile() const
-{
- return d->profile;
-}
-
-
-/*!
- \fn bool QGLFormat::hasOpenGL()
-
- Returns \c true if the window system has any OpenGL support;
- otherwise returns \c false.
-
- \warning This function must not be called until the QApplication
- object has been created.
-*/
-bool QGLFormat::hasOpenGL()
-{
- return QApplicationPrivate::platformIntegration()
- ->hasCapability(QPlatformIntegration::OpenGL);
-}
-
-/*!
- \fn bool QGLFormat::hasOpenGLOverlays()
-
- Returns \c true if the window system supports OpenGL overlays;
- otherwise returns \c false.
-
- \warning This function must not be called until the QApplication
- object has been created.
-*/
-bool QGLFormat::hasOpenGLOverlays()
-{
- return false;
-}
-
-QGLFormat::OpenGLVersionFlags Q_AUTOTEST_EXPORT qOpenGLVersionFlagsFromString(const QString &versionString)
-{
- QGLFormat::OpenGLVersionFlags versionFlags = QGLFormat::OpenGL_Version_None;
-
- if (versionString.startsWith(QLatin1String("OpenGL ES"))) {
- const auto parts = versionString.splitRef(QLatin1Char(' '));
- if (parts.size() >= 3) {
- if (parts[2].startsWith(QLatin1String("1."))) {
- if (parts[1].endsWith(QLatin1String("-CM"))) {
- versionFlags |= QGLFormat::OpenGL_ES_Common_Version_1_0 |
- QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- if (parts[2].startsWith(QLatin1String("1.1")))
- versionFlags |= QGLFormat::OpenGL_ES_Common_Version_1_1 |
- QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
- } else {
- // Not -CM, must be CL, CommonLite
- versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- if (parts[2].startsWith(QLatin1String("1.1")))
- versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
- }
- } else {
- // OpenGL ES version 2.0 or higher
- versionFlags |= QGLFormat::OpenGL_ES_Version_2_0;
- }
- } else {
- // if < 3 parts to the name, it is an unrecognised OpenGL ES
- qWarning("Unrecognised OpenGL ES version");
- }
- } else {
- // not ES, regular OpenGL, the version numbers are first in the string
- if (versionString.startsWith(QLatin1String("1."))) {
- switch (versionString[2].toLatin1()) {
- case '5':
- versionFlags |= QGLFormat::OpenGL_Version_1_5;
- Q_FALLTHROUGH();
- case '4':
- versionFlags |= QGLFormat::OpenGL_Version_1_4;
- Q_FALLTHROUGH();
- case '3':
- versionFlags |= QGLFormat::OpenGL_Version_1_3;
- Q_FALLTHROUGH();
- case '2':
- versionFlags |= QGLFormat::OpenGL_Version_1_2;
- Q_FALLTHROUGH();
- case '1':
- versionFlags |= QGLFormat::OpenGL_Version_1_1;
- Q_FALLTHROUGH();
- default:
- break;
- }
- } else if (versionString.startsWith(QLatin1String("2."))) {
- versionFlags |= QGLFormat::OpenGL_Version_1_1 |
- QGLFormat::OpenGL_Version_1_2 |
- QGLFormat::OpenGL_Version_1_3 |
- QGLFormat::OpenGL_Version_1_4 |
- QGLFormat::OpenGL_Version_1_5 |
- QGLFormat::OpenGL_Version_2_0;
- if (versionString[2].toLatin1() == '1')
- versionFlags |= QGLFormat::OpenGL_Version_2_1;
- } else if (versionString.startsWith(QLatin1String("3."))) {
- versionFlags |= QGLFormat::OpenGL_Version_1_1 |
- QGLFormat::OpenGL_Version_1_2 |
- QGLFormat::OpenGL_Version_1_3 |
- QGLFormat::OpenGL_Version_1_4 |
- QGLFormat::OpenGL_Version_1_5 |
- QGLFormat::OpenGL_Version_2_0 |
- QGLFormat::OpenGL_Version_2_1 |
- QGLFormat::OpenGL_Version_3_0;
- switch (versionString[2].toLatin1()) {
- case '3':
- versionFlags |= QGLFormat::OpenGL_Version_3_3;
- Q_FALLTHROUGH();
- case '2':
- versionFlags |= QGLFormat::OpenGL_Version_3_2;
- Q_FALLTHROUGH();
- case '1':
- versionFlags |= QGLFormat::OpenGL_Version_3_1;
- Q_FALLTHROUGH();
- case '0':
- break;
- default:
- versionFlags |= QGLFormat::OpenGL_Version_3_1 |
- QGLFormat::OpenGL_Version_3_2 |
- QGLFormat::OpenGL_Version_3_3;
- break;
- }
- } else if (versionString.startsWith(QLatin1String("4."))) {
- versionFlags |= QGLFormat::OpenGL_Version_1_1 |
- QGLFormat::OpenGL_Version_1_2 |
- QGLFormat::OpenGL_Version_1_3 |
- QGLFormat::OpenGL_Version_1_4 |
- QGLFormat::OpenGL_Version_1_5 |
- QGLFormat::OpenGL_Version_2_0 |
- QGLFormat::OpenGL_Version_2_1 |
- QGLFormat::OpenGL_Version_3_0 |
- QGLFormat::OpenGL_Version_3_1 |
- QGLFormat::OpenGL_Version_3_2 |
- QGLFormat::OpenGL_Version_3_3 |
- QGLFormat::OpenGL_Version_4_0;
- switch (versionString[2].toLatin1()) {
- case '3':
- versionFlags |= QGLFormat::OpenGL_Version_4_3;
- Q_FALLTHROUGH();
- case '2':
- versionFlags |= QGLFormat::OpenGL_Version_4_2;
- Q_FALLTHROUGH();
- case '1':
- versionFlags |= QGLFormat::OpenGL_Version_4_1;
- Q_FALLTHROUGH();
- case '0':
- break;
- default:
- versionFlags |= QGLFormat::OpenGL_Version_4_1 |
- QGLFormat::OpenGL_Version_4_2 |
- QGLFormat::OpenGL_Version_4_3;
- break;
- }
- } else {
- versionFlags |= QGLFormat::OpenGL_Version_1_1 |
- QGLFormat::OpenGL_Version_1_2 |
- QGLFormat::OpenGL_Version_1_3 |
- QGLFormat::OpenGL_Version_1_4 |
- QGLFormat::OpenGL_Version_1_5 |
- QGLFormat::OpenGL_Version_2_0 |
- QGLFormat::OpenGL_Version_2_1 |
- QGLFormat::OpenGL_Version_3_0 |
- QGLFormat::OpenGL_Version_3_1 |
- QGLFormat::OpenGL_Version_3_2 |
- QGLFormat::OpenGL_Version_3_3 |
- QGLFormat::OpenGL_Version_4_0 |
- QGLFormat::OpenGL_Version_4_1 |
- QGLFormat::OpenGL_Version_4_2 |
- QGLFormat::OpenGL_Version_4_3;
- }
- }
- return versionFlags;
-}
-
-/*!
- \enum QGLFormat::OpenGLVersionFlag
- \since 4.2
-
- This enum describes the various OpenGL versions that are
- recognized by Qt. Use the QGLFormat::openGLVersionFlags() function
- to identify which versions that are supported at runtime.
-
- \value OpenGL_Version_None If no OpenGL is present or if no OpenGL context is current.
-
- \value OpenGL_Version_1_1 OpenGL version 1.1 or higher is present.
-
- \value OpenGL_Version_1_2 OpenGL version 1.2 or higher is present.
-
- \value OpenGL_Version_1_3 OpenGL version 1.3 or higher is present.
-
- \value OpenGL_Version_1_4 OpenGL version 1.4 or higher is present.
-
- \value OpenGL_Version_1_5 OpenGL version 1.5 or higher is present.
-
- \value OpenGL_Version_2_0 OpenGL version 2.0 or higher is present.
- Note that version 2.0 supports all the functionality of version 1.5.
-
- \value OpenGL_Version_2_1 OpenGL version 2.1 or higher is present.
-
- \value OpenGL_Version_3_0 OpenGL version 3.0 or higher is present.
-
- \value OpenGL_Version_3_1 OpenGL version 3.1 or higher is present.
- Note that OpenGL version 3.1 or higher does not necessarily support all the features of
- version 3.0 and lower.
-
- \value OpenGL_Version_3_2 OpenGL version 3.2 or higher is present.
-
- \value OpenGL_Version_3_3 OpenGL version 3.3 or higher is present.
-
- \value OpenGL_Version_4_0 OpenGL version 4.0 or higher is present.
-
- \value OpenGL_Version_4_1 OpenGL version 4.1 or higher is present.
-
- \value OpenGL_Version_4_2 OpenGL version 4.2 or higher is present.
-
- \value OpenGL_Version_4_3 OpenGL version 4.3 or higher is present.
-
- \value OpenGL_ES_CommonLite_Version_1_0 OpenGL ES version 1.0 Common Lite or higher is present.
-
- \value OpenGL_ES_Common_Version_1_0 OpenGL ES version 1.0 Common or higher is present.
- The Common profile supports all the features of Common Lite.
-
- \value OpenGL_ES_CommonLite_Version_1_1 OpenGL ES version 1.1 Common Lite or higher is present.
-
- \value OpenGL_ES_Common_Version_1_1 OpenGL ES version 1.1 Common or higher is present.
- The Common profile supports all the features of Common Lite.
-
- \value OpenGL_ES_Version_2_0 OpenGL ES version 2.0 or higher is present.
- Note that OpenGL ES version 2.0 does not support all the features of OpenGL ES 1.x.
- So if OpenGL_ES_Version_2_0 is returned, none of the ES 1.x flags are returned.
-
- See also \l{http://www.opengl.org} for more information about the different
- revisions of OpenGL.
-
- \sa openGLVersionFlags()
-*/
-
-/*!
- \since 4.2
-
- Identifies, at runtime, which OpenGL versions that are supported
- by the current platform.
-
- Note that if OpenGL version 1.5 is supported, its predecessors
- (i.e., version 1.4 and lower) are also supported. To identify the
- support of a particular feature, like multi texturing, test for
- the version in which the feature was first introduced (i.e.,
- version 1.3 in the case of multi texturing) to adapt to the largest
- possible group of runtime platforms.
-
- This function needs a valid current OpenGL context to work;
- otherwise it will return OpenGL_Version_None.
-
- \sa hasOpenGL(), hasOpenGLOverlays()
-*/
-QGLFormat::OpenGLVersionFlags QGLFormat::openGLVersionFlags()
-{
- static bool cachedDefault = false;
- static OpenGLVersionFlags defaultVersionFlags = OpenGL_Version_None;
- QGLContext *currentCtx = const_cast<QGLContext *>(QGLContext::currentContext());
- QGLTemporaryContext *tmpContext = 0;
-
- if (currentCtx && currentCtx->d_func()->version_flags_cached)
- return currentCtx->d_func()->version_flags;
-
- if (!currentCtx) {
- if (cachedDefault) {
- return defaultVersionFlags;
- } else {
- if (!hasOpenGL())
- return defaultVersionFlags;
- tmpContext = new QGLTemporaryContext;
- cachedDefault = true;
- }
- }
-
- QString versionString(QLatin1String(reinterpret_cast<const char*>(qgl_functions()->glGetString(GL_VERSION))));
- OpenGLVersionFlags versionFlags = qOpenGLVersionFlagsFromString(versionString);
- if (currentCtx) {
- currentCtx->d_func()->version_flags_cached = true;
- currentCtx->d_func()->version_flags = versionFlags;
- }
- if (tmpContext) {
- defaultVersionFlags = versionFlags;
- delete tmpContext;
- }
-
- return versionFlags;
-}
-
-
-/*!
- Returns the default QGLFormat for the application. All QGLWidget
- objects that are created use this format unless another format is
- specified, e.g. when they are constructed.
-
- If no special default format has been set using
- setDefaultFormat(), the default format is the same as that created
- with QGLFormat().
-
- \sa setDefaultFormat()
-*/
-
-QGLFormat QGLFormat::defaultFormat()
-{
- return *qgl_default_format();
-}
-
-/*!
- Sets a new default QGLFormat for the application to \a f. For
- example, to set single buffering as the default instead of double
- buffering, your main() might contain code like this:
- \snippet code/src_opengl_qgl.cpp 4
-
- \sa defaultFormat()
-*/
-
-void QGLFormat::setDefaultFormat(const QGLFormat &f)
-{
- *qgl_default_format() = f;
-}
-
-
-/*!
- Returns the default QGLFormat for overlay contexts.
-
- The default overlay format is:
- \list
- \li \l{setDoubleBuffer()}{Double buffer:} Disabled.
- \li \l{setDepth()}{Depth buffer:} Disabled.
- \li \l{setRgba()}{RGBA:} Disabled (i.e., color index enabled).
- \li \l{setAlpha()}{Alpha channel:} Disabled.
- \li \l{setAccum()}{Accumulator buffer:} Disabled.
- \li \l{setStencil()}{Stencil buffer:} Disabled.
- \li \l{setStereo()}{Stereo:} Disabled.
- \li \l{setDirectRendering()}{Direct rendering:} Enabled.
- \li \l{setOverlay()}{Overlay:} Disabled.
- \li \l{setSampleBuffers()}{Multisample buffers:} Disabled.
- \li \l{setPlane()}{Plane:} 1 (i.e., first overlay plane).
- \endlist
-
- \sa setDefaultFormat()
-*/
-
-QGLFormat QGLFormat::defaultOverlayFormat()
-{
- return *defaultOverlayFormatInstance();
-}
-
-/*!
- Sets a new default QGLFormat for overlay contexts to \a f. This
- format is used whenever a QGLWidget is created with a format that
- hasOverlay() enabled.
-
- For example, to get a double buffered overlay context (if
- available), use code like this:
-
- \snippet code/src_opengl_qgl.cpp 5
-
- As usual, you can find out after widget creation whether the
- underlying OpenGL system was able to provide the requested
- specification:
-
- \snippet code/src_opengl_qgl.cpp 6
-
- \sa defaultOverlayFormat()
-*/
-
-void QGLFormat::setDefaultOverlayFormat(const QGLFormat &f)
-{
- QGLFormat *defaultFormat = defaultOverlayFormatInstance();
- *defaultFormat = f;
- // Make sure the user doesn't request that the overlays themselves
- // have overlays, since it is unlikely that the system supports
- // infinitely many planes...
- defaultFormat->setOverlay(false);
-}
-
-
-/*!
- Returns \c true if all the options of the two QGLFormat objects
- \a a and \a b are equal; otherwise returns \c false.
-
- \relates QGLFormat
-*/
-
-bool operator==(const QGLFormat& a, const QGLFormat& b)
-{
- return (a.d == b.d) || ((int) a.d->opts == (int) b.d->opts
- && a.d->pln == b.d->pln
- && a.d->alphaSize == b.d->alphaSize
- && a.d->accumSize == b.d->accumSize
- && a.d->stencilSize == b.d->stencilSize
- && a.d->depthSize == b.d->depthSize
- && a.d->redSize == b.d->redSize
- && a.d->greenSize == b.d->greenSize
- && a.d->blueSize == b.d->blueSize
- && a.d->numSamples == b.d->numSamples
- && a.d->swapInterval == b.d->swapInterval
- && a.d->majorVersion == b.d->majorVersion
- && a.d->minorVersion == b.d->minorVersion
- && a.d->profile == b.d->profile);
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug dbg, const QGLFormat &f)
-{
- const QGLFormatPrivate * const d = f.d;
-
- QDebugStateSaver saver(dbg);
- dbg.nospace() << "QGLFormat("
- << "options " << d->opts
- << ", plane " << d->pln
- << ", depthBufferSize " << d->depthSize
- << ", accumBufferSize " << d->accumSize
- << ", stencilBufferSize " << d->stencilSize
- << ", redBufferSize " << d->redSize
- << ", greenBufferSize " << d->greenSize
- << ", blueBufferSize " << d->blueSize
- << ", alphaBufferSize " << d->alphaSize
- << ", samples " << d->numSamples
- << ", swapInterval " << d->swapInterval
- << ", majorVersion " << d->majorVersion
- << ", minorVersion " << d->minorVersion
- << ", profile " << d->profile
- << ')';
-
- return dbg;
-}
-#endif
-
-
-/*!
- Returns \c false if all the options of the two QGLFormat objects
- \a a and \a b are equal; otherwise returns \c true.
-
- \relates QGLFormat
-*/
-
-bool operator!=(const QGLFormat& a, const QGLFormat& b)
-{
- return !(a == b);
-}
-
-struct QGLContextGroupList {
- void append(QGLContextGroup *group) {
- QMutexLocker locker(&m_mutex);
- m_list.append(group);
- }
-
- void remove(QGLContextGroup *group) {
- QMutexLocker locker(&m_mutex);
- m_list.removeOne(group);
- }
-
- QList<QGLContextGroup *> m_list;
- QRecursiveMutex m_mutex;
-};
-
-Q_GLOBAL_STATIC(QGLContextGroupList, qt_context_groups)
-
-/*****************************************************************************
- QGLContext implementation
- *****************************************************************************/
-
-QGLContextGroup::QGLContextGroup(const QGLContext *context)
- : m_context(context), m_refs(1)
-{
- qt_context_groups()->append(this);
-}
-
-QGLContextGroup::~QGLContextGroup()
-{
- qt_context_groups()->remove(this);
-}
-
-const QGLContext *qt_gl_transfer_context(const QGLContext *ctx)
-{
- if (!ctx)
- return 0;
- QList<const QGLContext *> shares
- (QGLContextPrivate::contextGroup(ctx)->shares());
- if (shares.size() >= 2)
- return (ctx == shares.at(0)) ? shares.at(1) : shares.at(0);
- else
- return 0;
-}
-
-QGLContextPrivate::QGLContextPrivate(QGLContext *context)
- : internal_context(false)
- , q_ptr(context)
- , texture_destroyer(0)
- , functions(0)
-{
- group = new QGLContextGroup(context);
-
- texture_destroyer = new QGLTextureDestroyer;
-}
-
-QGLContextPrivate::~QGLContextPrivate()
-{
- delete functions;
-
- if (!group->m_refs.deref()) {
- Q_ASSERT(group->context() == q_ptr);
- delete group;
- }
-
- delete texture_destroyer;
-}
-
-void QGLContextPrivate::init(QPaintDevice *dev, const QGLFormat &format)
-{
- Q_Q(QGLContext);
- glFormat = reqFormat = format;
- valid = false;
- q->setDevice(dev);
-
- guiGlContext = 0;
- ownContext = false;
- fbo = 0;
- crWin = false;
- initDone = false;
- sharing = false;
- max_texture_size = -1;
- version_flags_cached = false;
- version_flags = QGLFormat::OpenGL_Version_None;
- current_fbo = 0;
- default_fbo = 0;
- active_engine = 0;
- workaround_needsFullClearOnEveryFrame = false;
- workaround_brokenFBOReadBack = false;
- workaround_brokenTexSubImage = false;
- workaroundsCached = false;
-
- workaround_brokenTextureFromPixmap = false;
- workaround_brokenTextureFromPixmap_init = false;
-
- workaround_brokenAlphaTexSubImage = false;
- workaround_brokenAlphaTexSubImage_init = false;
-
- for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
- vertexAttributeArraysEnabledState[i] = false;
-}
-
-QGLContext* QGLContext::currentCtx = 0;
-
-/*
- QGLTemporaryContext implementation
-*/
-class QGLTemporaryContextPrivate
-{
-public:
- QWindow *window;
- QOpenGLContext *context;
-
- QGLContext *oldContext;
-};
-
-QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *)
- : d(new QGLTemporaryContextPrivate)
-{
- d->oldContext = const_cast<QGLContext *>(QGLContext::currentContext());
-
- d->window = new QWindow;
- d->window->setSurfaceType(QWindow::OpenGLSurface);
- d->window->setGeometry(QRect(0, 0, 3, 3));
- d->window->create();
-
- d->context = new QOpenGLContext;
-#if !defined(QT_OPENGL_ES)
- if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) {
- // On desktop, request latest released version
- QSurfaceFormat format;
-#if defined(Q_OS_MAC)
- // OS X is limited to OpenGL 3.2 Core Profile at present
- // so set that here. If we use compatibility profile it
- // only reports 2.x contexts.
- format.setMajorVersion(3);
- format.setMinorVersion(2);
- format.setProfile(QSurfaceFormat::CoreProfile);
-#else
- format.setMajorVersion(4);
- format.setMinorVersion(3);
-#endif
- d->context->setFormat(format);
- }
-#endif // QT_OPENGL_ES
- d->context->create();
- d->context->makeCurrent(d->window);
-}
-
-QGLTemporaryContext::~QGLTemporaryContext()
-{
- if (d->oldContext)
- d->oldContext->makeCurrent();
-
- delete d->context;
- delete d->window;
-}
-
-/*
- Read back the contents of the currently bound framebuffer, used in
- QGLWidget::grabFrameBuffer(), QGLPixelbuffer::toImage() and
- QGLFramebufferObject::toImage()
-*/
-
-static void convertFromGLImage(QImage &img, int w, int h, bool alpha_format, bool include_alpha)
-{
- Q_ASSERT(!img.isNull());
- if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
- // OpenGL gives RGBA; Qt wants ARGB
- uint *p = (uint*)img.bits();
- uint *end = p + w*h;
- if (alpha_format && include_alpha) {
- while (p < end) {
- uint a = *p << 24;
- *p = (*p >> 8) | a;
- p++;
- }
- } else {
- // This is an old legacy fix for PowerPC based Macs, which
- // we shouldn't remove
- while (p < end) {
- *p = 0xff000000 | (*p>>8);
- ++p;
- }
- }
- } else {
- // OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB
- for (int y = 0; y < h; y++) {
- uint *q = (uint*)img.scanLine(y);
- for (int x=0; x < w; ++x) {
- const uint pixel = *q;
- if (alpha_format && include_alpha) {
- *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff)
- | (pixel & 0xff00ff00);
- } else {
- *q = 0xff000000 | ((pixel << 16) & 0xff0000)
- | ((pixel >> 16) & 0xff) | (pixel & 0x00ff00);
- }
-
- q++;
- }
- }
-
- }
- img = img.mirrored();
-}
-
-QImage qt_gl_read_frame_buffer(const QSize &size, bool alpha_format, bool include_alpha)
-{
- QImage img(size, (alpha_format && include_alpha) ? QImage::Format_ARGB32_Premultiplied
- : QImage::Format_RGB32);
- if (img.isNull())
- return QImage();
- int w = size.width();
- int h = size.height();
- qgl_functions()->glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
- convertFromGLImage(img, w, h, alpha_format, include_alpha);
- return img;
-}
-
-QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha)
-{
- QImage img(size, alpha_format ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
- if (img.isNull())
- return QImage();
- int w = size.width();
- int h = size.height();
-#ifndef QT_OPENGL_ES
- if (!QOpenGLContext::currentContext()->isOpenGLES()) {
-
- qgl1_functions()->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
- }
-#endif // QT_OPENGL_ES
- convertFromGLImage(img, w, h, alpha_format, include_alpha);
- return img;
-}
-
-Q_GLOBAL_STATIC(QGLTextureCache, qt_gl_texture_cache)
-
-QGLTextureCache::QGLTextureCache()
- : m_cache(64*1024) // cache ~64 MB worth of textures - this is not accurate though
-{
- QImagePixmapCleanupHooks::instance()->addPlatformPixmapModificationHook(cleanupTexturesForPixampData);
- QImagePixmapCleanupHooks::instance()->addPlatformPixmapDestructionHook(cleanupBeforePixmapDestruction);
- QImagePixmapCleanupHooks::instance()->addImageHook(cleanupTexturesForCacheKey);
-}
-
-QGLTextureCache::~QGLTextureCache()
-{
- QImagePixmapCleanupHooks::instance()->removePlatformPixmapModificationHook(cleanupTexturesForPixampData);
- QImagePixmapCleanupHooks::instance()->removePlatformPixmapDestructionHook(cleanupBeforePixmapDestruction);
- QImagePixmapCleanupHooks::instance()->removeImageHook(cleanupTexturesForCacheKey);
-}
-
-void QGLTextureCache::insert(QGLContext* ctx, qint64 key, QGLTexture* texture, int cost)
-{
- QWriteLocker locker(&m_lock);
- const QGLTextureCacheKey cacheKey = {key, QGLContextPrivate::contextGroup(ctx)};
- const bool inserted = m_cache.insert(cacheKey, texture, cost);
- Q_UNUSED(inserted) Q_ASSERT(inserted);
-}
-
-void QGLTextureCache::remove(qint64 key)
-{
- QWriteLocker locker(&m_lock);
- QMutexLocker groupLocker(&qt_context_groups()->m_mutex);
- QList<QGLContextGroup *>::const_iterator it = qt_context_groups()->m_list.constBegin();
- while (it != qt_context_groups()->m_list.constEnd()) {
- const QGLTextureCacheKey cacheKey = {key, *it};
- m_cache.remove(cacheKey);
- ++it;
- }
-}
-
-bool QGLTextureCache::remove(QGLContext* ctx, GLuint textureId)
-{
- QWriteLocker locker(&m_lock);
- QList<QGLTextureCacheKey> keys = m_cache.keys();
- for (int i = 0; i < keys.size(); ++i) {
- QGLTexture *tex = m_cache.object(keys.at(i));
- if (tex->id == textureId && tex->context == ctx) {
- tex->options |= QGLContext::MemoryManagedBindOption; // forces a glDeleteTextures() call
- m_cache.remove(keys.at(i));
- return true;
- }
- }
- return false;
-}
-
-void QGLTextureCache::removeContextTextures(QGLContext* ctx)
-{
- QWriteLocker locker(&m_lock);
- QList<QGLTextureCacheKey> keys = m_cache.keys();
- for (int i = 0; i < keys.size(); ++i) {
- const QGLTextureCacheKey &key = keys.at(i);
- if (m_cache.object(key)->context == ctx)
- m_cache.remove(key);
- }
-}
-
-/*
- a hook that removes textures from the cache when a pixmap/image
- is deref'ed
-*/
-void QGLTextureCache::cleanupTexturesForCacheKey(qint64 cacheKey)
-{
- qt_gl_texture_cache()->remove(cacheKey);
-}
-
-
-void QGLTextureCache::cleanupTexturesForPixampData(QPlatformPixmap* pmd)
-{
- cleanupTexturesForCacheKey(pmd->cacheKey());
-}
-
-void QGLTextureCache::cleanupBeforePixmapDestruction(QPlatformPixmap* pmd)
-{
- // Remove any bound textures first:
- cleanupTexturesForPixampData(pmd);
-}
-
-QGLTextureCache *QGLTextureCache::instance()
-{
- return qt_gl_texture_cache();
-}
-
-// DDS format structure
-struct DDSFormat {
- quint32 dwSize;
- quint32 dwFlags;
- quint32 dwHeight;
- quint32 dwWidth;
- quint32 dwLinearSize;
- quint32 dummy1;
- quint32 dwMipMapCount;
- quint32 dummy2[11];
- struct {
- quint32 dummy3[2];
- quint32 dwFourCC;
- quint32 dummy4[5];
- } ddsPixelFormat;
-};
-
-// compressed texture pixel formats
-#define FOURCC_DXT1 0x31545844
-#define FOURCC_DXT2 0x32545844
-#define FOURCC_DXT3 0x33545844
-#define FOURCC_DXT4 0x34545844
-#define FOURCC_DXT5 0x35545844
-
-// ####TODO Properly #ifdef this class to use #define symbols actually defined
-// by system GL includes
-#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
-#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
-#endif
-
-#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
-#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
-#endif
-
-#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
-#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
-#endif
-
-#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
-#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
-#endif
-
-#ifndef GL_GENERATE_MIPMAP_SGIS
-#define GL_GENERATE_MIPMAP_SGIS 0x8191
-#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
-#endif
-
-/*!
- \class QGLContext
- \inmodule QtOpenGL
- \obsolete
-
- \brief The QGLContext class encapsulates an OpenGL rendering context.
-
- An OpenGL rendering context is a complete set of OpenGL state
- variables. The rendering context's \l {QGL::FormatOption} {format}
- is set in the constructor, but it can also be set later with
- setFormat(). The format options that are actually set are returned
- by format(); the options you asked for are returned by
- requestedFormat(). Note that after a QGLContext object has been
- constructed, the actual OpenGL context must be created by
- explicitly calling the \l{create()}
- function. The makeCurrent() function makes this context the
- current rendering context. You can make \e no context current
- using doneCurrent(). The reset() function will reset the context
- and make it invalid.
-
- You can examine properties of the context with, e.g. isValid(),
- isSharing(), initialized(), windowCreated() and
- overlayTransparentColor().
-
- If you're using double buffering you can swap the screen contents
- with the off-screen buffer using swapBuffers().
-
- Please note that QGLContext is not thread safe.
-*/
-
-/*!
- \enum QGLContext::BindOption
- \since 4.6
-
- A set of options to decide how to bind a texture using bindTexture().
-
- \value NoBindOption Don't do anything, pass the texture straight
- through.
-
- \value InvertedYBindOption Specifies that the texture should be flipped
- over the X axis so that the texture coordinate 0,0 corresponds to
- the top left corner. Inverting the texture implies a deep copy
- prior to upload.
-
- \value MipmapBindOption Specifies that bindTexture() should try
- to generate mipmaps. If the GL implementation supports the \c
- GL_SGIS_generate_mipmap extension, mipmaps will be automatically
- generated for the texture. Mipmap generation is only supported for
- the \c GL_TEXTURE_2D target.
-
- \value PremultipliedAlphaBindOption Specifies that the image should be
- uploaded with premultiplied alpha and does a conversion accordingly.
-
- \value LinearFilteringBindOption Specifies that the texture filtering
- should be set to GL_LINEAR. Default is GL_NEAREST. If mipmap is
- also enabled, filtering will be set to GL_LINEAR_MIPMAP_LINEAR.
-
- \value DefaultBindOption In Qt 4.5 and earlier, bindTexture()
- would mirror the image and automatically generate mipmaps. This
- option helps preserve this default behavior.
-
- \omitvalue CanFlipNativePixmapBindOption \omit Used by x11 from pixmap to choose
- whether or not it can bind the pixmap upside down or not. \endomit
-
- \omitvalue MemoryManagedBindOption \omit Used by paint engines to
- indicate that the pixmap should be memory managed along side with
- the pixmap/image that it stems from, e.g. installing destruction
- hooks in them. \endomit
-
- \omitvalue TemporarilyCachedBindOption \omit Used by paint engines on some
- platforms to indicate that the pixmap or image texture is possibly
- cached only temporarily and must be destroyed immediately after the use. \endomit
-
- \omitvalue InternalBindOption
-*/
-
-/*!
- \obsolete
-
- Constructs an OpenGL context for the given paint \a device, which
- can be a widget or a pixmap. The \a format specifies several
- display options for the context.
-
- If the underlying OpenGL/Window system cannot satisfy all the
- features requested in \a format, the nearest subset of features
- will be used. After creation, the format() method will return the
- actual format obtained.
-
- Note that after a QGLContext object has been constructed, \l
- create() must be called explicitly to create the actual OpenGL
- context. The context will be \l {isValid()}{invalid} if it was not
- possible to obtain a GL context at all.
-*/
-
-QGLContext::QGLContext(const QGLFormat &format, QPaintDevice *device)
- : d_ptr(new QGLContextPrivate(this))
-{
- Q_D(QGLContext);
- d->init(device, format);
-}
-
-/*!
- Constructs an OpenGL context with the given \a format which
- specifies several display options for the context.
-
- If the underlying OpenGL/Window system cannot satisfy all the
- features requested in \a format, the nearest subset of features
- will be used. After creation, the format() method will return the
- actual format obtained.
-
- Note that after a QGLContext object has been constructed, \l
- create() must be called explicitly to create the actual OpenGL
- context. The context will be \l {isValid()}{invalid} if it was not
- possible to obtain a GL context at all.
-
- \sa format(), isValid()
-*/
-QGLContext::QGLContext(const QGLFormat &format)
- : d_ptr(new QGLContextPrivate(this))
-{
- Q_D(QGLContext);
- d->init(0, format);
-}
-
-static void qDeleteQGLContext(void *handle)
-{
- QGLContext *context = static_cast<QGLContext *>(handle);
- delete context;
-}
-
-QGLContext::QGLContext(QOpenGLContext *context)
- : d_ptr(new QGLContextPrivate(this))
-{
- Q_D(QGLContext);
- d->init(0, QGLFormat::fromSurfaceFormat(context->format()));
- d->guiGlContext = context;
- d->guiGlContext->setQGLContextHandle(this, qDeleteQGLContext);
- d->ownContext = false;
- d->valid = context->isValid();
- d->setupSharing();
-}
-
-/*!
- Returns the OpenGL context handle.
-*/
-QOpenGLContext *QGLContext::contextHandle() const
-{
- Q_D(const QGLContext);
- return d->guiGlContext;
-}
-
-/*!
- Returns an OpenGL context for the window context specified by the \a context
- parameter.
-*/
-QGLContext *QGLContext::fromOpenGLContext(QOpenGLContext *context)
-{
- if (!context)
- return 0;
- if (context->qGLContextHandle()) {
- return reinterpret_cast<QGLContext *>(context->qGLContextHandle());
- }
- QGLContext *glContext = new QGLContext(context);
- //Don't call create on context. This can cause the platformFormat to be set on the widget, which
- //will cause the platformWindow to be recreated.
- return glContext;
-}
-
-/*!
- Destroys the OpenGL context and frees its resources.
-*/
-
-QGLContext::~QGLContext()
-{
- // remove any textures cached in this context
- QGLTextureCache::instance()->removeContextTextures(this);
-
- // clean up resources specific to this context
- d_ptr->cleanup();
-
- QGLSignalProxy::instance()->emitAboutToDestroyContext(this);
- reset();
-}
-
-void QGLContextPrivate::cleanup()
-{
-}
-
-#define ctx q_ptr
-void QGLContextPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
-{
- Q_Q(QGLContext);
- Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
-#ifdef glEnableVertexAttribArray
- Q_ASSERT(glEnableVertexAttribArray);
-#endif
-
- if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
- q->functions()->glDisableVertexAttribArray(arrayIndex);
-
- if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
- q->functions()->glEnableVertexAttribArray(arrayIndex);
-
- vertexAttributeArraysEnabledState[arrayIndex] = enabled;
-}
-
-void QGLContextPrivate::syncGlState()
-{
- Q_Q(QGLContext);
-#ifdef glEnableVertexAttribArray
- Q_ASSERT(glEnableVertexAttribArray);
-#endif
- for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
- if (vertexAttributeArraysEnabledState[i])
- q->functions()->glEnableVertexAttribArray(i);
- else
- q->functions()->glDisableVertexAttribArray(i);
- }
-
-}
-#undef ctx
-
-void QGLContextPrivate::swapRegion(const QRegion &)
-{
- Q_Q(QGLContext);
- q->swapBuffers();
-}
-
-/*!
- \overload
-
- Reads the compressed texture file \a fileName and generates a 2D GL
- texture from it.
-
- This function can load DirectDrawSurface (DDS) textures in the
- DXT1, DXT3 and DXT5 DDS formats if the \c GL_ARB_texture_compression
- and \c GL_EXT_texture_compression_s3tc extensions are supported.
-
- Since 4.6.1, textures in the ETC1 format can be loaded if the
- \c GL_OES_compressed_ETC1_RGB8_texture extension is supported
- and the ETC1 texture has been encapsulated in the PVR container format.
- Also, textures in the PVRTC2 and PVRTC4 formats can be loaded
- if the \c GL_IMG_texture_compression_pvrtc extension is supported.
-
- \sa deleteTexture()
-*/
-
-GLuint QGLContext::bindTexture(const QString &fileName)
-{
- QGLTexture texture(this);
- QSize size = texture.bindCompressedTexture(fileName);
- if (!size.isValid())
- return 0;
- return texture.id;
-}
-
-static inline QRgb qt_gl_convertToGLFormatHelper(QRgb src_pixel, GLenum texture_format)
-{
- if (texture_format == GL_BGRA) {
- if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
- return ((src_pixel << 24) & 0xff000000)
- | ((src_pixel >> 24) & 0x000000ff)
- | ((src_pixel << 8) & 0x00ff0000)
- | ((src_pixel >> 8) & 0x0000ff00);
- } else {
- return src_pixel;
- }
- } else { // GL_RGBA
- if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
- return (src_pixel << 8) | ((src_pixel >> 24) & 0xff);
- } else {
- return ((src_pixel << 16) & 0xff0000)
- | ((src_pixel >> 16) & 0xff)
- | (src_pixel & 0xff00ff00);
- }
- }
-}
-
-static void convertToGLFormatHelper(QImage &dst, const QImage &img, GLenum texture_format)
-{
- Q_ASSERT(dst.depth() == 32);
- Q_ASSERT(img.depth() == 32);
-
- if (dst.size() != img.size()) {
- int target_width = dst.width();
- int target_height = dst.height();
- qreal sx = target_width / qreal(img.width());
- qreal sy = target_height / qreal(img.height());
-
- quint32 *dest = (quint32 *) dst.scanLine(0); // NB! avoid detach here
- const uchar *srcPixels = img.constScanLine(img.height() - 1);
- int sbpl = img.bytesPerLine();
- int dbpl = dst.bytesPerLine();
-
- int ix = int(0x00010000 / sx);
- int iy = int(0x00010000 / sy);
-
- quint32 basex = int(0.5 * ix);
- quint32 srcy = int(0.5 * iy);
-
- // scale, swizzle and mirror in one loop
- while (target_height--) {
- const uint *src = (const quint32 *) (srcPixels - (srcy >> 16) * sbpl);
- int srcx = basex;
- for (int x=0; x<target_width; ++x) {
- dest[x] = qt_gl_convertToGLFormatHelper(src[srcx >> 16], texture_format);
- srcx += ix;
- }
- dest = (quint32 *)(((uchar *) dest) + dbpl);
- srcy += iy;
- }
- } else {
- const int width = img.width();
- const int height = img.height();
- const uint *p = (const uint*) img.scanLine(img.height() - 1);
- uint *q = (uint*) dst.scanLine(0);
-
- if (texture_format == GL_BGRA) {
- if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
- // mirror + swizzle
- for (int i=0; i < height; ++i) {
- const uint *end = p + width;
- while (p < end) {
- *q = ((*p << 24) & 0xff000000)
- | ((*p >> 24) & 0x000000ff)
- | ((*p << 8) & 0x00ff0000)
- | ((*p >> 8) & 0x0000ff00);
- p++;
- q++;
- }
- p -= 2 * width;
- }
- } else {
- const uint bytesPerLine = img.bytesPerLine();
- for (int i=0; i < height; ++i) {
- memcpy(q, p, bytesPerLine);
- q += width;
- p -= width;
- }
- }
- } else {
- if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
- for (int i=0; i < height; ++i) {
- const uint *end = p + width;
- while (p < end) {
- *q = (*p << 8) | ((*p >> 24) & 0xff);
- p++;
- q++;
- }
- p -= 2 * width;
- }
- } else {
- for (int i=0; i < height; ++i) {
- const uint *end = p + width;
- while (p < end) {
- *q = ((*p << 16) & 0xff0000) | ((*p >> 16) & 0xff) | (*p & 0xff00ff00);
- p++;
- q++;
- }
- p -= 2 * width;
- }
- }
- }
- }
-}
-
-/*! \internal */
-QGLTexture *QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint format,
- QGLContext::BindOptions options)
-{
- Q_Q(QGLContext);
-
- const qint64 key = image.cacheKey();
- QGLTexture *texture = textureCacheLookup(key, target);
- if (texture) {
- if (image.paintingActive()) {
- // A QPainter is active on the image - take the safe route and replace the texture.
- q->deleteTexture(texture->id);
- texture = 0;
- } else {
- qgl_functions()->glBindTexture(target, texture->id);
- return texture;
- }
- }
-
- if (!texture)
- texture = bindTexture(image, target, format, key, options);
- // NOTE: bindTexture(const QImage&, GLenum, GLint, const qint64, bool) should never return null
- Q_ASSERT(texture);
-
- // Enable the cleanup hooks for this image so that the texture cache entry is removed when the
- // image gets deleted:
- QImagePixmapCleanupHooks::enableCleanupHooks(image);
-
- return texture;
-}
-
-// #define QGL_BIND_TEXTURE_DEBUG
-
-// ####TODO Properly #ifdef this file to use #define symbols actually defined
-// by OpenGL/ES includes
-#ifndef GL_UNSIGNED_INT_8_8_8_8_REV
-#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
-#endif
-
-// map from Qt's ARGB endianness-dependent format to GL's big-endian RGBA layout
-static inline void qgl_byteSwapImage(QImage &img, GLenum pixel_type)
-{
- const int width = img.width();
- const int height = img.height();
-
- if (pixel_type == GL_UNSIGNED_INT_8_8_8_8_REV
- || (pixel_type == GL_UNSIGNED_BYTE && QSysInfo::ByteOrder == QSysInfo::LittleEndian))
- {
- for (int i = 0; i < height; ++i) {
- uint *p = (uint *) img.scanLine(i);
- for (int x = 0; x < width; ++x)
- p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);
- }
- } else {
- for (int i = 0; i < height; ++i) {
- uint *p = (uint *) img.scanLine(i);
- for (int x = 0; x < width; ++x)
- p[x] = (p[x] << 8) | ((p[x] >> 24) & 0xff);
- }
- }
-}
-
-QGLTexture* QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint internalFormat,
- const qint64 key, QGLContext::BindOptions options)
-{
- Q_Q(QGLContext);
- QOpenGLFunctions *funcs = qgl_functions();
-
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf("QGLContextPrivate::bindTexture(), imageSize=(%d,%d), internalFormat =0x%x, options=%x, key=%llx\n",
- image.width(), image.height(), internalFormat, int(options), key);
- QTime time;
- time.start();
-#endif
-
-#ifndef QT_NO_DEBUG
- // Reset the gl error stack...git
- while (funcs->glGetError() != GL_NO_ERROR) ;
-#endif
-
- // Scale the pixmap if needed. GL textures needs to have the
- // dimensions 2^n+2(border) x 2^m+2(border), unless we're using GL
- // 2.0 or use the GL_TEXTURE_RECTANGLE texture target
- int tx_w = qNextPowerOfTwo(image.width() - 1);
- int tx_h = qNextPowerOfTwo(image.height() - 1);
-
- QImage img = image;
-
- if (!qgl_extensions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures)
- && !(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0)
- && (target == GL_TEXTURE_2D && (tx_w != image.width() || tx_h != image.height())))
- {
- img = img.scaled(tx_w, tx_h);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - upscaled to %dx%d (%d ms)\n", tx_w, tx_h, time.elapsed());
-
-#endif
- }
-
- GLuint filtering = options & QGLContext::LinearFilteringBindOption ? GL_LINEAR : GL_NEAREST;
-
- GLuint tx_id;
- funcs->glGenTextures(1, &tx_id);
- funcs->glBindTexture(target, tx_id);
- funcs->glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filtering);
-
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- bool genMipmap = !ctx->isOpenGLES();
- if (glFormat.directRendering()
- && (qgl_extensions()->hasOpenGLExtension(QOpenGLExtensions::GenerateMipmap))
- && target == GL_TEXTURE_2D
- && (options & QGLContext::MipmapBindOption))
- {
-#if !defined(QT_OPENGL_ES_2)
- if (genMipmap) {
- funcs->glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_NICEST);
- funcs->glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
- } else {
- funcs->glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
- genMipmap = true;
- }
-#else
- funcs->glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
- genMipmap = true;
-#endif
- funcs->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, options & QGLContext::LinearFilteringBindOption
- ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_NEAREST);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - generating mipmaps (%d ms)\n", time.elapsed());
-#endif
- } else {
- funcs->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filtering);
- }
-
- QImage::Format target_format = img.format();
- bool premul = options & QGLContext::PremultipliedAlphaBindOption;
- bool needsbyteswap = true;
- GLenum externalFormat;
- GLuint pixel_type;
- if (target_format == QImage::Format_RGBA8888
- || target_format == QImage::Format_RGBA8888_Premultiplied
- || target_format == QImage::Format_RGBX8888) {
- externalFormat = GL_RGBA;
- pixel_type = GL_UNSIGNED_BYTE;
- needsbyteswap = false;
- } else if (qgl_extensions()->hasOpenGLExtension(QOpenGLExtensions::BGRATextureFormat)) {
- externalFormat = GL_BGRA;
- needsbyteswap = false;
- if (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2)
- pixel_type = GL_UNSIGNED_INT_8_8_8_8_REV;
- else
- pixel_type = GL_UNSIGNED_BYTE;
- } else {
- externalFormat = GL_RGBA;
- pixel_type = GL_UNSIGNED_BYTE;
- }
-
- switch (target_format) {
- case QImage::Format_ARGB32:
- if (premul) {
- img = img.convertToFormat(target_format = QImage::Format_ARGB32_Premultiplied);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted ARGB32 -> ARGB32_Premultiplied (%d ms) \n", time.elapsed());
-#endif
- }
- break;
- case QImage::Format_ARGB32_Premultiplied:
- if (!premul) {
- img = img.convertToFormat(target_format = QImage::Format_ARGB32);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted ARGB32_Premultiplied -> ARGB32 (%d ms)\n", time.elapsed());
-#endif
- }
- break;
- case QImage::Format_RGBA8888:
- if (premul) {
- img = img.convertToFormat(target_format = QImage::Format_RGBA8888_Premultiplied);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted RGBA8888 -> RGBA8888_Premultiplied (%d ms) \n", time.elapsed());
-#endif
- }
- break;
- case QImage::Format_RGBA8888_Premultiplied:
- if (!premul) {
- img = img.convertToFormat(target_format = QImage::Format_RGBA8888);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted RGBA8888_Premultiplied -> RGBA8888 (%d ms) \n", time.elapsed());
-#endif
- }
- break;
- case QImage::Format_RGB16:
- pixel_type = GL_UNSIGNED_SHORT_5_6_5;
- externalFormat = GL_RGB;
- internalFormat = GL_RGB;
- needsbyteswap = false;
- break;
- case QImage::Format_RGB32:
- case QImage::Format_RGBX8888:
- break;
- default:
- // Ideally more formats would be converted directly to an RGBA8888 format,
- // but we are only guaranteed to have a fast conversion to an ARGB format.
- if (img.hasAlphaChannel()) {
- img = img.convertToFormat(premul
- ? QImage::Format_ARGB32_Premultiplied
- : QImage::Format_ARGB32);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted to 32-bit alpha format (%d ms)\n", time.elapsed());
-#endif
- } else {
- img = img.convertToFormat(QImage::Format_RGB32);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - converted to 32-bit (%d ms)\n", time.elapsed());
-#endif
- }
- }
-
- if (options & QGLContext::InvertedYBindOption) {
- if (img.isDetached()) {
- int ipl = img.bytesPerLine() / 4;
- int h = img.height();
- for (int y=0; y<h/2; ++y) {
- int *a = (int *) img.scanLine(y);
- int *b = (int *) img.scanLine(h - y - 1);
- for (int x=0; x<ipl; ++x)
- qSwap(a[x], b[x]);
- }
- } else {
- // Create a new image and copy across. If we use the
- // above in-place code then a full copy of the image is
- // made before the lines are swapped, which processes the
- // data twice. This version should only do it once.
- img = img.mirrored();
- }
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - flipped bits over y (%d ms)\n", time.elapsed());
-#endif
- }
-
- if (needsbyteswap) {
- // The only case where we end up with a depth different from
- // 32 in the switch above is for the RGB16 case, where we do
- // not need a byteswap.
- Q_ASSERT(img.depth() == 32);
- qgl_byteSwapImage(img, pixel_type);
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - did byte swapping (%d ms)\n", time.elapsed());
-#endif
- }
- if (ctx->isOpenGLES()) {
- // OpenGL/ES requires that the internal and external formats be
- // identical.
- internalFormat = externalFormat;
- }
-#ifdef QGL_BIND_TEXTURE_DEBUG
- printf(" - uploading, image.format=%d, externalFormat=0x%x, internalFormat=0x%x, pixel_type=0x%x\n",
- img.format(), externalFormat, internalFormat, pixel_type);
-#endif
-
- const QImage &constRef = img; // to avoid detach in bits()...
- funcs->glTexImage2D(target, 0, internalFormat, img.width(), img.height(), 0, externalFormat,
- pixel_type, constRef.bits());
- if (genMipmap && ctx->isOpenGLES())
- q->functions()->glGenerateMipmap(target);
-#ifndef QT_NO_DEBUG
- GLenum error = funcs->glGetError();
- if (error != GL_NO_ERROR) {
- qWarning(" - texture upload failed, error code 0x%x, enum: %d (%x)\n", error, target, target);
- }
-#endif
-
-#ifdef QGL_BIND_TEXTURE_DEBUG
- static int totalUploadTime = 0;
- totalUploadTime += time.elapsed();
- printf(" - upload done in %d ms, (accumulated: %d ms)\n", time.elapsed(), totalUploadTime);
-#endif
-
-
- // this assumes the size of a texture is always smaller than the max cache size
- int cost = img.width()*img.height()*4/1024;
- QGLTexture *texture = new QGLTexture(q, tx_id, target, options);
- QGLTextureCache::instance()->insert(q, key, texture, cost);
-
- return texture;
-}
-
-QGLTexture *QGLContextPrivate::textureCacheLookup(const qint64 key, GLenum target)
-{
- Q_Q(QGLContext);
- QGLTexture *texture = QGLTextureCache::instance()->getTexture(q, key);
- if (texture && texture->target == target
- && (texture->context == q || QGLContext::areSharing(q, texture->context)))
- {
- return texture;
- }
- return 0;
-}
-
-/*! \internal */
-QGLTexture *QGLContextPrivate::bindTexture(const QPixmap &pixmap, GLenum target, GLint format, QGLContext::BindOptions options)
-{
- Q_Q(QGLContext);
- QPlatformPixmap *pd = pixmap.handle();
- Q_UNUSED(pd);
-
- const qint64 key = pixmap.cacheKey();
- QGLTexture *texture = textureCacheLookup(key, target);
- if (texture) {
- if (pixmap.paintingActive()) {
- // A QPainter is active on the pixmap - take the safe route and replace the texture.
- q->deleteTexture(texture->id);
- texture = 0;
- } else {
- qgl_functions()->glBindTexture(target, texture->id);
- return texture;
- }
- }
-
- if (!texture) {
- QImage image;
- QPaintEngine* paintEngine = pixmap.paintEngine();
- if (!paintEngine || paintEngine->type() != QPaintEngine::Raster)
- image = pixmap.toImage();
- else {
- // QRasterPixmapData::toImage() will deep-copy the backing QImage if there's an active QPainter on it.
- // For performance reasons, we don't want that here, so we temporarily redirect the paint engine.
- QPaintDevice* currentPaintDevice = paintEngine->paintDevice();
- paintEngine->setPaintDevice(0);
- image = pixmap.toImage();
- paintEngine->setPaintDevice(currentPaintDevice);
- }
-
- // If the system depth is 16 and the pixmap doesn't have an alpha channel
- // then we convert it to RGB16 in the hope that it gets uploaded as a 16
- // bit texture which is much faster to access than a 32-bit one.
- if (pixmap.depth() == 16 && !image.hasAlphaChannel() )
- image = image.convertToFormat(QImage::Format_RGB16);
- texture = bindTexture(image, target, format, key, options);
- }
- // NOTE: bindTexture(const QImage&, GLenum, GLint, const qint64, bool) should never return null
- Q_ASSERT(texture);
-
- if (texture->id > 0)
- QImagePixmapCleanupHooks::enableCleanupHooks(pixmap);
-
- return texture;
-}
-
-/*! \internal */
-int QGLContextPrivate::maxTextureSize()
-{
- if (max_texture_size != -1)
- return max_texture_size;
-
- QOpenGLFunctions *funcs = qgl_functions();
- funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
-
-#ifndef QT_OPENGL_ES
- Q_Q(QGLContext);
- if (!q->contextHandle()->isOpenGLES()) {
- GLenum proxy = GL_PROXY_TEXTURE_2D;
-
- GLint size;
- GLint next = 64;
- funcs->glTexImage2D(proxy, 0, GL_RGBA, next, next, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
- gl1funcs->glGetTexLevelParameteriv(proxy, 0, GL_TEXTURE_WIDTH, &size);
- if (size == 0) {
- return max_texture_size;
- }
- do {
- size = next;
- next = size * 2;
-
- if (next > max_texture_size)
- break;
- funcs->glTexImage2D(proxy, 0, GL_RGBA, next, next, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
- gl1funcs->glGetTexLevelParameteriv(proxy, 0, GL_TEXTURE_WIDTH, &next);
- } while (next > size);
-
- max_texture_size = size;
- }
-#endif
-
- return max_texture_size;
-}
-
-/*!
- Returns a QGLFunctions object that is initialized for this context.
- */
-QGLFunctions *QGLContext::functions() const
-{
- QGLContextPrivate *d = const_cast<QGLContextPrivate *>(d_func());
- if (!d->functions) {
- d->functions = new QGLFunctions(this);
- d->functions->initializeGLFunctions(this);
- }
- return d->functions;
-}
-
-/*!
- Generates and binds a 2D GL texture to the current context, based
- on \a image. The generated texture id is returned and can be used in
- later \c glBindTexture() calls.
-
- \overload
-*/
-GLuint QGLContext::bindTexture(const QImage &image, GLenum target, GLint format)
-{
- if (image.isNull())
- return 0;
-
- Q_D(QGLContext);
- QGLTexture *texture = d->bindTexture(image, target, format, DefaultBindOption);
- return texture->id;
-}
-
-/*!
- \since 4.6
-
- Generates and binds a 2D GL texture to the current context, based
- on \a image. The generated texture id is returned and can be used
- in later \c glBindTexture() calls.
-
- The \a target parameter specifies the texture target. The default
- target is \c GL_TEXTURE_2D.
-
- The \a format parameter sets the internal format for the
- texture. The default format is \c GL_RGBA.
-
- The binding \a options are a set of options used to decide how to
- bind the texture to the context.
-
- The texture that is generated is cached, so multiple calls to
- bindTexture() with the same QImage will return the same texture
- id.
-
- Note that we assume default values for the glPixelStore() and
- glPixelTransfer() parameters.
-
- \sa deleteTexture()
-*/
-GLuint QGLContext::bindTexture(const QImage &image, GLenum target, GLint format, BindOptions options)
-{
- if (image.isNull())
- return 0;
-
- Q_D(QGLContext);
- QGLTexture *texture = d->bindTexture(image, target, format, options);
- return texture->id;
-}
-
-/*! \overload
-
- Generates and binds a 2D GL texture based on \a pixmap.
-*/
-GLuint QGLContext::bindTexture(const QPixmap &pixmap, GLenum target, GLint format)
-{
- if (pixmap.isNull())
- return 0;
-
- Q_D(QGLContext);
- QGLTexture *texture = d->bindTexture(pixmap, target, format, DefaultBindOption);
- return texture->id;
-}
-
-/*!
- \overload
- \since 4.6
-
- Generates and binds a 2D GL texture to the current context, based
- on \a pixmap.
-*/
-GLuint QGLContext::bindTexture(const QPixmap &pixmap, GLenum target, GLint format, BindOptions options)
-{
- if (pixmap.isNull())
- return 0;
-
- Q_D(QGLContext);
- QGLTexture *texture = d->bindTexture(pixmap, target, format, options);
- return texture->id;
-}
-
-/*!
- Removes the texture identified by \a id from the texture cache,
- and calls glDeleteTextures() to delete the texture from the
- context.
-
- \sa bindTexture()
-*/
-void QGLContext::deleteTexture(GLuint id)
-{
- if (QGLTextureCache::instance()->remove(this, id))
- return;
- qgl_functions()->glDeleteTextures(1, &id);
-}
-
-void qt_add_rect_to_array(const QRectF &r, GLfloat *array)
-{
- qreal left = r.left();
- qreal right = r.right();
- qreal top = r.top();
- qreal bottom = r.bottom();
-
- array[0] = left;
- array[1] = top;
- array[2] = right;
- array[3] = top;
- array[4] = right;
- array[5] = bottom;
- array[6] = left;
- array[7] = bottom;
-}
-
-void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, GLfloat *array)
-{
- array[0] = x1;
- array[1] = y1;
- array[2] = x2;
- array[3] = y1;
- array[4] = x2;
- array[5] = y2;
- array[6] = x1;
- array[7] = y2;
-}
-
-#if !defined(QT_OPENGL_ES_2)
-
-static void qDrawTextureRect(const QRectF &target, GLint textureWidth, GLint textureHeight, GLenum textureTarget)
-{
- QOpenGLFunctions *funcs = qgl_functions();
- GLfloat tx = 1.0f;
- GLfloat ty = 1.0f;
-
-#ifdef QT_OPENGL_ES
- Q_UNUSED(textureWidth);
- Q_UNUSED(textureHeight);
- Q_UNUSED(textureTarget);
-#else
- if (textureTarget != GL_TEXTURE_2D && !QOpenGLContext::currentContext()->isOpenGLES()) {
- if (textureWidth == -1 || textureHeight == -1) {
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
- gl1funcs->glGetTexLevelParameteriv(textureTarget, 0, GL_TEXTURE_WIDTH, &textureWidth);
- gl1funcs->glGetTexLevelParameteriv(textureTarget, 0, GL_TEXTURE_HEIGHT, &textureHeight);
- }
-
- tx = GLfloat(textureWidth);
- ty = GLfloat(textureHeight);
- }
-#endif
-
- GLfloat texCoordArray[4*2] = {
- 0, ty, tx, ty, tx, 0, 0, 0
- };
-
- GLfloat vertexArray[4*2];
- qt_add_rect_to_array(target, vertexArray);
-
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
- gl1funcs->glVertexPointer(2, GL_FLOAT, 0, vertexArray);
- gl1funcs->glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
-
- gl1funcs->glEnableClientState(GL_VERTEX_ARRAY);
- gl1funcs->glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- funcs->glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-
- gl1funcs->glDisableClientState(GL_VERTEX_ARRAY);
- gl1funcs->glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-}
-
-#endif // !QT_OPENGL_ES_2
-
-/*!
- \since 4.4
-
- This function supports the following use cases:
-
- \list
- \li On OpenGL and OpenGL ES 1.x it draws the given texture, \a textureId,
- to the given target rectangle, \a target, in OpenGL model space. The
- \a textureTarget should be a 2D texture target.
- \li On OpenGL and OpenGL ES 2.x, if a painter is active, not inside a
- beginNativePainting / endNativePainting block, and uses the
- engine with type QPaintEngine::OpenGL2, the function will draw the given
- texture, \a textureId, to the given target rectangle, \a target,
- respecting the current painter state. This will let you draw a texture
- with the clip, transform, render hints, and composition mode set by the
- painter. Note that the texture target needs to be GL_TEXTURE_2D for this
- use case, and that this is the only supported use case under OpenGL ES 2.x.
- \endlist
-
-*/
-void QGLContext::drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget)
-{
-#if !defined(QT_OPENGL_ES) || defined(QT_OPENGL_ES_2)
- if (d_ptr->active_engine &&
- d_ptr->active_engine->type() == QPaintEngine::OpenGL2) {
- QGL2PaintEngineEx *eng = static_cast<QGL2PaintEngineEx*>(d_ptr->active_engine);
- if (!eng->isNativePaintingActive()) {
- QRectF src(0, 0, target.width(), target.height());
- QSize size(target.width(), target.height());
- if (eng->drawTexture(target, textureId, size, src))
- return;
- }
- }
-#endif
-
-#ifndef QT_OPENGL_ES_2
- QOpenGLFunctions *funcs = qgl_functions();
- if (!contextHandle()->isOpenGLES()) {
-#ifdef QT_OPENGL_ES
- if (textureTarget != GL_TEXTURE_2D) {
- qWarning("QGLContext::drawTexture(): texture target must be GL_TEXTURE_2D on OpenGL ES");
- return;
- }
-#else
- const bool wasEnabled = funcs->glIsEnabled(GL_TEXTURE_2D);
- GLint oldTexture;
- funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTexture);
-#endif
-
- funcs->glEnable(textureTarget);
- funcs->glBindTexture(textureTarget, textureId);
-
- qDrawTextureRect(target, -1, -1, textureTarget);
-
-#ifdef QT_OPENGL_ES
- funcs->glDisable(textureTarget);
-#else
- if (!wasEnabled)
- funcs->glDisable(textureTarget);
- funcs->glBindTexture(textureTarget, oldTexture);
-#endif
- return;
- }
-#else
- Q_UNUSED(target);
- Q_UNUSED(textureId);
- Q_UNUSED(textureTarget);
-#endif
- qWarning("drawTexture() with OpenGL ES 2.0 requires an active OpenGL2 paint engine");
-}
-
-/*!
- \since 4.4
-
- This function supports the following use cases:
-
- \list
- \li By default it draws the given texture, \a textureId,
- at the given \a point in OpenGL model space. The
- \a textureTarget should be a 2D texture target.
- \li If a painter is active, not inside a
- beginNativePainting / endNativePainting block, and uses the
- engine with type QPaintEngine::OpenGL2, the function will draw the given
- texture, \a textureId, at the given \a point,
- respecting the current painter state. This will let you draw a texture
- with the clip, transform, render hints, and composition mode set by the
- painter. Note that the texture target needs to be GL_TEXTURE_2D for this
- use case.
- \endlist
-
- \note This function is not supported under any version of OpenGL ES.
-*/
-void QGLContext::drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget)
-{
-#ifdef QT_OPENGL_ES
- Q_UNUSED(point);
- Q_UNUSED(textureId);
- Q_UNUSED(textureTarget);
-#else
- if (!contextHandle()->isOpenGLES()) {
- QOpenGLFunctions *funcs = qgl_functions();
- const bool wasEnabled = funcs->glIsEnabled(GL_TEXTURE_2D);
- GLint oldTexture;
- funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTexture);
-
- funcs->glEnable(textureTarget);
- funcs->glBindTexture(textureTarget, textureId);
-
- GLint textureWidth;
- GLint textureHeight;
-
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
- gl1funcs->glGetTexLevelParameteriv(textureTarget, 0, GL_TEXTURE_WIDTH, &textureWidth);
- gl1funcs->glGetTexLevelParameteriv(textureTarget, 0, GL_TEXTURE_HEIGHT, &textureHeight);
-
- if (d_ptr->active_engine &&
- d_ptr->active_engine->type() == QPaintEngine::OpenGL2) {
- QGL2PaintEngineEx *eng = static_cast<QGL2PaintEngineEx*>(d_ptr->active_engine);
- if (!eng->isNativePaintingActive()) {
- QRectF dest(point, QSizeF(textureWidth, textureHeight));
- QRectF src(0, 0, textureWidth, textureHeight);
- QSize size(textureWidth, textureHeight);
- if (eng->drawTexture(dest, textureId, size, src))
- return;
- }
- }
-
- qDrawTextureRect(QRectF(point, QSizeF(textureWidth, textureHeight)), textureWidth, textureHeight, textureTarget);
-
- if (!wasEnabled)
- funcs->glDisable(textureTarget);
- funcs->glBindTexture(textureTarget, oldTexture);
- return;
- }
-#endif
- qWarning("drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget) not supported with OpenGL ES, use rect version instead");
-}
-
-/*!
- This function sets the limit for the texture cache to \a size,
- expressed in kilobytes.
-
- By default, the cache limit is approximately 64 MB.
-
- \sa textureCacheLimit()
-*/
-void QGLContext::setTextureCacheLimit(int size)
-{
- QGLTextureCache::instance()->setMaxCost(size);
-}
-
-/*!
- Returns the current texture cache limit in kilobytes.
-
- \sa setTextureCacheLimit()
-*/
-int QGLContext::textureCacheLimit()
-{
- return QGLTextureCache::instance()->maxCost();
-}
-
-
-/*!
- \fn QGLFormat QGLContext::format() const
-
- Returns the frame buffer format that was obtained (this may be a
- subset of what was requested).
-
- \sa requestedFormat()
-*/
-
-/*!
- \fn QGLFormat QGLContext::requestedFormat() const
-
- Returns the frame buffer format that was originally requested in
- the constructor or setFormat().
-
- \sa format()
-*/
-
-/*!
- Sets a \a format for this context. The context is \l{reset()}{reset}.
-
- Call create() to create a new GL context that tries to match the
- new format.
-
- \snippet code/src_opengl_qgl.cpp 7
-
- \sa format(), reset(), create()
-*/
-
-void QGLContext::setFormat(const QGLFormat &format)
-{
- Q_D(QGLContext);
- reset();
- d->glFormat = d->reqFormat = format;
-}
-
-/*!
- \internal
-*/
-void QGLContext::setDevice(QPaintDevice *pDev)
-{
- Q_D(QGLContext);
- // Do not touch the valid flag here. The context is either a new one and
- // valid is not yet set or it is adapted from a valid QOpenGLContext in which
- // case it must remain valid.
- d->paintDevice = pDev;
- if (d->paintDevice && (d->paintDevice->devType() != QInternal::Widget
- && d->paintDevice->devType() != QInternal::Pixmap
- && d->paintDevice->devType() != QInternal::Pbuffer)) {
- qWarning("QGLContext: Unsupported paint device type");
- }
-}
-
-/*!
- \fn bool QGLContext::isValid() const
-
- Returns \c true if a GL rendering context has been successfully
- created; otherwise returns \c false.
-*/
-
-/*!
- \fn void QGLContext::setValid(bool valid)
- \internal
-
- Forces the GL rendering context to be valid.
-*/
-
-/*!
- \fn bool QGLContext::isSharing() const
-
- Returns \c true if this context is sharing its GL context with
- another QGLContext, otherwise false is returned. Note that context
- sharing might not be supported between contexts with different
- formats.
-*/
-
-/*!
- Returns \c true if \a context1 and \a context2 are sharing their
- GL resources such as textures, shader programs, etc;
- otherwise returns \c false.
-
- \since 4.6
-*/
-bool QGLContext::areSharing(const QGLContext *context1, const QGLContext *context2)
-{
- if (!context1 || !context2)
- return false;
- return context1->d_ptr->group == context2->d_ptr->group;
-}
-
-/*!
- \fn bool QGLContext::deviceIsPixmap() const
-
- Returns \c true if the paint device of this context is a pixmap;
- otherwise returns \c false.
-
- Since Qt 5 the paint device is never actually a pixmap. renderPixmap() is
- however still simulated using framebuffer objects and readbacks, and this
- function will return \c true in this case.
-*/
-
-/*!
- \fn bool QGLContext::windowCreated() const
-
- Returns \c true if a window has been created for this context;
- otherwise returns \c false.
-
- \sa setWindowCreated()
-*/
-
-/*!
- \fn void QGLContext::setWindowCreated(bool on)
-
- If \a on is true the context has had a window created for it. If
- \a on is false no window has been created for the context.
-
- \sa windowCreated()
-*/
-
-/*!
- \fn uint QGLContext::colorIndex(const QColor& c) const
-
- \internal
-
- Returns a colormap index for the color c, in ColorIndex mode. Used
- by qglColor() and qglClearColor().
-*/
-uint QGLContext::colorIndex(const QColor&) const
-{
- return 0;
-}
-
-/*!
- \fn bool QGLContext::initialized() const
-
- Returns \c true if this context has been initialized, i.e. if
- QGLWidget::initializeGL() has been performed on it; otherwise
- returns \c false.
-
- \sa setInitialized()
-*/
-
-/*!
- \fn void QGLContext::setInitialized(bool on)
-
- If \a on is true the context has been initialized, i.e.
- QGLContext::setInitialized() has been called on it. If \a on is
- false the context has not been initialized.
-
- \sa initialized()
-*/
-
-/*!
- \fn const QGLContext* QGLContext::currentContext()
-
- Returns the current context, i.e. the context to which any OpenGL
- commands will currently be directed. Returns 0 if no context is
- current.
-
- \sa makeCurrent()
-*/
-
-/*!
- \fn QColor QGLContext::overlayTransparentColor() const
-
- If this context is a valid context in an overlay plane, returns
- the plane's transparent color. Otherwise returns an \l{QColor::isValid()}{invalid} color.
-
- The returned color's \l{QColormap::pixel()}{pixel} value is
- the index of the transparent color in the colormap of the overlay
- plane. (Naturally, the color's RGB values are meaningless.)
-
- The returned QColor object will generally work as expected only
- when passed as the argument to QGLWidget::qglColor() or
- QGLWidget::qglClearColor(). Under certain circumstances it can
- also be used to draw transparent graphics with a QPainter.
-*/
-QColor QGLContext::overlayTransparentColor() const
-{
- return QColor(); // Invalid color
-}
-
-/*!
- Creates the GL context. Returns \c true if it was successful in
- creating a valid GL rendering context on the paint device
- specified in the constructor; otherwise returns \c false (i.e. the
- context is invalid).
-
- If the OpenGL implementation on your system does not support the requested
- version of OpenGL context, then QGLContext will try to create the closest
- matching version. The actual created context properties can be queried
- using the QGLFormat returned by the format() function. For example, if
- you request a context that supports OpenGL 4.3 Core profile but the driver
- and/or hardware only supports version 3.2 Core profile contexts then you will
- get a 3.2 Core profile context.
-
- After successful creation, format() returns the set of features of
- the created GL rendering context.
-
- If \a shareContext points to a valid QGLContext, this method will
- try to establish OpenGL display list and texture object sharing
- between this context and the \a shareContext. Note that this may
- fail if the two contexts have different \l {format()} {formats}.
- Use isSharing() to see if sharing is in effect.
-
- \warning Implementation note: initialization of C++ class
- members usually takes place in the class constructor. QGLContext
- is an exception because it must be simple to customize. The
- virtual functions chooseContext() (and chooseVisual() for X11) can
- be reimplemented in a subclass to select a particular context. The
- problem is that virtual functions are not properly called during
- construction (even though this is correct C++) because C++
- constructs class hierarchies from the bottom up. For this reason
- we need a create() function.
-
- \sa chooseContext(), format(), isValid()
-*/
-
-bool QGLContext::create(const QGLContext* shareContext)
-{
- Q_D(QGLContext);
- if (!d->paintDevice && !d->guiGlContext)
- return false;
-
- reset();
- d->valid = chooseContext(shareContext);
- if (d->valid && d->paintDevice && d->paintDevice->devType() == QInternal::Widget) {
- QWidgetPrivate *wd = qt_widget_private(static_cast<QWidget *>(d->paintDevice));
- wd->usesDoubleBufferedGLContext = d->glFormat.doubleBuffer();
- }
- return d->valid;
-}
-
-bool QGLContext::isValid() const
-{
- Q_D(const QGLContext);
- return d->valid;
-}
-
-void QGLContext::setValid(bool valid)
-{
- Q_D(QGLContext);
- d->valid = valid;
-}
-
-bool QGLContext::isSharing() const
-{
- Q_D(const QGLContext);
- return d->group->isSharing();
-}
-
-QGLFormat QGLContext::format() const
-{
- Q_D(const QGLContext);
- return d->glFormat;
-}
-
-QGLFormat QGLContext::requestedFormat() const
-{
- Q_D(const QGLContext);
- return d->reqFormat;
-}
-
- QPaintDevice* QGLContext::device() const
-{
- Q_D(const QGLContext);
- return d->paintDevice;
-}
-
-bool QGLContext::deviceIsPixmap() const
-{
- Q_D(const QGLContext);
- return !d->readback_target_size.isEmpty();
-}
-
-
-bool QGLContext::windowCreated() const
-{
- Q_D(const QGLContext);
- return d->crWin;
-}
-
-
-void QGLContext::setWindowCreated(bool on)
-{
- Q_D(QGLContext);
- d->crWin = on;
-}
-
-bool QGLContext::initialized() const
-{
- Q_D(const QGLContext);
- return d->initDone;
-}
-
-void QGLContext::setInitialized(bool on)
-{
- Q_D(QGLContext);
- d->initDone = on;
-}
-
-const QGLContext* QGLContext::currentContext()
-{
- if (const QOpenGLContext *threadContext = QOpenGLContext::currentContext()) {
- return QGLContext::fromOpenGLContext(const_cast<QOpenGLContext *>(threadContext));
- }
- return 0;
-}
-
-void QGLContextPrivate::setCurrentContext(QGLContext *context)
-{
- Q_UNUSED(context);
-}
-
-/*!
- Moves the QGLContext to the given \a thread.
-
- Enables calling swapBuffers() and makeCurrent() on the context in
- the given thread.
-*/
-void QGLContext::moveToThread(QThread *thread)
-{
- Q_D(QGLContext);
- if (d->guiGlContext)
- d->guiGlContext->moveToThread(thread);
-}
-
-/*!
- \fn bool QGLContext::chooseContext(const QGLContext* shareContext = 0)
-
- This semi-internal function is called by create(). It creates a
- system-dependent OpenGL handle that matches the format() of \a
- shareContext as closely as possible, returning true if successful
- or false if a suitable handle could not be found.
-
- On Windows, it calls the virtual function choosePixelFormat(),
- which finds a matching pixel format identifier. On X11, it calls
- the virtual function chooseVisual() which finds an appropriate X
- visual. On other platforms it may work differently.
-*/
-bool QGLContext::chooseContext(const QGLContext* shareContext)
-{
- Q_D(QGLContext);
- if(!d->paintDevice || d->paintDevice->devType() != QInternal::Widget) {
- // Unlike in Qt 4, the only possible target is a widget backed by an OpenGL-based
- // QWindow. Pixmaps in particular are not supported anymore as paint devices since
- // starting from Qt 5 QPixmap is raster-backed on almost all platforms.
- d->valid = false;
- }else {
- QWidget *widget = static_cast<QWidget *>(d->paintDevice);
- QGLFormat glformat = format();
- QSurfaceFormat winFormat = QGLFormat::toSurfaceFormat(glformat);
- if (widget->testAttribute(Qt::WA_TranslucentBackground))
- winFormat.setAlphaBufferSize(qMax(winFormat.alphaBufferSize(), 8));
-
- QWindow *window = widget->windowHandle();
- if (!window->handle()
- || window->surfaceType() != QWindow::OpenGLSurface
- || window->requestedFormat() != winFormat)
- {
- window->setSurfaceType(QWindow::OpenGLSurface);
- window->setFormat(winFormat);
- window->destroy();
- window->create();
- }
-
- if (d->ownContext)
- delete d->guiGlContext;
- d->ownContext = true;
- QOpenGLContext *shareGlContext = shareContext ? shareContext->d_func()->guiGlContext : 0;
- d->guiGlContext = new QOpenGLContext;
- d->guiGlContext->setFormat(winFormat);
- d->guiGlContext->setShareContext(shareGlContext);
- d->valid = d->guiGlContext->create();
-
- if (d->valid)
- d->guiGlContext->setQGLContextHandle(this, 0);
-
- d->glFormat = QGLFormat::fromSurfaceFormat(d->guiGlContext->format());
- d->setupSharing();
- }
-
-
- return d->valid;
-}
-
-/*!
- \fn void QGLContext::reset()
-
- Resets the context and makes it invalid.
-
- \sa create(), isValid()
-*/
-void QGLContext::reset()
-{
- Q_D(QGLContext);
- if (!d->valid)
- return;
- d->cleanup();
-
- d->crWin = false;
- d->sharing = false;
- d->valid = false;
- d->transpColor = QColor();
- d->initDone = false;
- QGLContextGroup::removeShare(this);
- if (d->guiGlContext) {
- if (QOpenGLContext::currentContext() == d->guiGlContext)
- doneCurrent();
- if (d->ownContext) {
- if (d->guiGlContext->thread() == QThread::currentThread())
- delete d->guiGlContext;
- else
- d->guiGlContext->deleteLater();
- } else
- d->guiGlContext->setQGLContextHandle(0,0);
- d->guiGlContext = 0;
- }
- d->ownContext = false;
-}
-
-/*!
- \fn void QGLContext::makeCurrent()
-
- Makes this context the current OpenGL rendering context. All GL
- functions you call operate on this context until another context
- is made current.
-
- In some very rare cases the underlying call may fail. If this
- occurs an error message is output to stderr.
-
- If you call this from a thread other than the main UI thread,
- make sure you've first pushed the context to the relevant thread
- from the UI thread using moveToThread().
-*/
-void QGLContext::makeCurrent()
-{
- Q_D(QGLContext);
- if (!d->paintDevice || d->paintDevice->devType() != QInternal::Widget)
- return;
-
- QWidget *widget = static_cast<QWidget *>(d->paintDevice);
- if (!widget->windowHandle())
- return;
-
- if (d->guiGlContext->makeCurrent(widget->windowHandle())) {
- if (!d->workaroundsCached) {
- d->workaroundsCached = true;
- const char *renderer = reinterpret_cast<const char *>(d->guiGlContext->functions()->glGetString(GL_RENDERER));
- if (renderer && strstr(renderer, "Mali")) {
- d->workaround_brokenFBOReadBack = true;
- }
- }
- }
-}
-
-/*!
- \fn void QGLContext::swapBuffers() const
-
- Call this to finish a frame of OpenGL rendering, and make sure to
- call makeCurrent() again before issuing any further OpenGL commands,
- for example as part of a new frame.
-*/
-void QGLContext::swapBuffers() const
-{
- Q_D(const QGLContext);
- if (!d->paintDevice || d->paintDevice->devType() != QInternal::Widget)
- return;
-
- QWidget *widget = static_cast<QWidget *>(d->paintDevice);
- if (!widget->windowHandle())
- return;
-
- d->guiGlContext->swapBuffers(widget->windowHandle());
-}
-
-/*!
- \fn void QGLContext::doneCurrent()
-
- Makes no GL context the current context. Normally, you do not need
- to call this function; QGLContext calls it as necessary.
-*/
-void QGLContext::doneCurrent()
-{
- Q_D(QGLContext);
- d->guiGlContext->doneCurrent();
-}
-
-/*!
- \fn QPaintDevice* QGLContext::device() const
-
- Returns the paint device set for this context.
-
- \sa QGLContext::QGLContext()
-*/
-
-/*****************************************************************************
- QGLWidget implementation
- *****************************************************************************/
-
-
-/*!
- \class QGLWidget
- \inmodule QtOpenGL
- \obsolete
-
- \brief The QGLWidget class is a widget for rendering OpenGL graphics.
-
- QGLWidget provides functionality for displaying OpenGL graphics
- integrated into a Qt application. It is very simple to use. You
- inherit from it and use the subclass like any other QWidget,
- except that you have the choice between using QPainter and
- standard OpenGL rendering commands.
-
- \note This class is part of the legacy \l {Qt OpenGL} module and,
- like the other \c QGL classes, should be avoided in the new
- applications. Instead, starting from Qt 5.4, prefer using
- QOpenGLWidget and the \c QOpenGL classes.
-
- QGLWidget provides three convenient virtual functions that you can
- reimplement in your subclass to perform the typical OpenGL tasks:
-
- \list
- \li paintGL() - Renders the OpenGL scene. Gets called whenever the widget
- needs to be updated.
- \li resizeGL() - Sets up the OpenGL viewport, projection, etc. Gets
- called whenever the widget has been resized (and also when it
- is shown for the first time because all newly created widgets get a
- resize event automatically).
- \li initializeGL() - Sets up the OpenGL rendering context, defines display
- lists, etc. Gets called once before the first time resizeGL() or
- paintGL() is called.
- \endlist
-
- Here is a rough outline of how a QGLWidget subclass might look:
-
- \snippet code/src_opengl_qgl.cpp 8
-
- If you need to trigger a repaint from places other than paintGL()
- (a typical example is when using \l{QTimer}{timers} to
- animate scenes), you should call the widget's updateGL() function.
-
- Your widget's OpenGL rendering context is made current when
- paintGL(), resizeGL(), or initializeGL() is called. If you need to
- call the standard OpenGL API functions from other places (e.g. in
- your widget's constructor or in your own paint functions), you
- must call makeCurrent() first.
-
- QGLWidget provides functions for requesting a new display
- \l{QGLFormat}{format} and you can also create widgets with
- customized rendering \l{QGLContext}{contexts}.
-
- You can also share OpenGL display lists between QGLWidget objects (see
- the documentation of the QGLWidget constructors for details).
-
- Note that under Windows, the QGLContext belonging to a QGLWidget
- has to be recreated when the QGLWidget is reparented. This is
- necessary due to limitations on the Windows platform. This will
- most likely cause problems for users that have subclassed and
- installed their own QGLContext on a QGLWidget. It is possible to
- work around this issue by putting the QGLWidget inside a dummy
- widget and then reparenting the dummy widget, instead of the
- QGLWidget. This will side-step the issue altogether, and is what
- we recommend for users that need this kind of functionality.
-
- On \macos, when Qt is built with Cocoa support, a QGLWidget
- can't have any sibling widgets placed ontop of itself. This is due
- to limitations in the Cocoa API and is not supported by Apple.
-
- \section1 Overlays
-
- The QGLWidget creates a GL overlay context in addition to the
- normal context if overlays are supported by the underlying system.
-
- If you want to use overlays, you specify it in the
- \l{QGLFormat}{format}. (Note: Overlay must be requested in the format
- passed to the QGLWidget constructor.) Your GL widget should also
- implement some or all of these virtual methods:
-
- \list
- \li paintOverlayGL()
- \li resizeOverlayGL()
- \li initializeOverlayGL()
- \endlist
-
- These methods work in the same way as the normal paintGL() etc.
- functions, except that they will be called when the overlay
- context is made current. You can explicitly make the overlay
- context current by using makeOverlayCurrent(), and you can access
- the overlay context directly (e.g. to ask for its transparent
- color) by calling overlayContext().
-
- On X servers in which the default visual is in an overlay plane,
- non-GL Qt windows can also be used for overlays.
-
- \section1 Painting Techniques
-
- As described above, subclass QGLWidget to render pure 3D content in the
- following way:
-
- \list
- \li Reimplement the QGLWidget::initializeGL() and QGLWidget::resizeGL() to
- set up the OpenGL state and provide a perspective transformation.
- \li Reimplement QGLWidget::paintGL() to paint the 3D scene, calling only
- OpenGL functions to draw on the widget.
- \endlist
-
- It is also possible to draw 2D graphics onto a QGLWidget subclass, it is necessary
- to reimplement QGLWidget::paintEvent() and do the following:
-
- \list
- \li Construct a QPainter object.
- \li Initialize it for use on the widget with the QPainter::begin() function.
- \li Draw primitives using QPainter's member functions.
- \li Call QPainter::end() to finish painting.
- \endlist
-
- \section1 Threading
-
- As of Qt version 4.8, support for doing threaded GL rendering has
- been improved. There are three scenarios that we currently support:
- \list
- \li 1. Buffer swapping in a thread.
-
- Swapping buffers in a double buffered context may be a
- synchronous, locking call that may be a costly operation in some
- GL implementations. Especially so on embedded devices. It's not
- optimal to have the CPU idling while the GPU is doing a buffer
- swap. In those cases it is possible to do the rendering in the
- main thread and do the actual buffer swap in a separate
- thread. This can be done with the following steps:
-
- 1. Call doneCurrent() in the main thread when the rendering is
- finished.
-
- 2. Call QGLContext::moveToThread(swapThread) to transfer ownership
- of the context to the swapping thread.
-
- 3. Notify the swapping thread that it can grab the context.
-
- 4. Make the rendering context current in the swapping thread with
- makeCurrent() and then call swapBuffers().
-
- 5. Call doneCurrent() in the swapping thread.
-
- 6. Call QGLContext::moveToThread(qApp->thread()) and notify the
- main thread that swapping is done.
-
- Doing this will free up the main thread so that it can continue
- with, for example, handling UI events or network requests. Even if
- there is a context swap involved, it may be preferable compared to
- having the main thread wait while the GPU finishes the swap
- operation. Note that this is highly implementation dependent.
-
- \li 2. Texture uploading in a thread.
-
- Doing texture uploads in a thread may be very useful for
- applications handling large amounts of images that needs to be
- displayed, like for instance a photo gallery application. This is
- supported in Qt through the existing bindTexture() API. A simple
- way of doing this is to create two sharing QGLWidgets. One is made
- current in the main GUI thread, while the other is made current in
- the texture upload thread. The widget in the uploading thread is
- never shown, it is only used for sharing textures with the main
- thread. For each texture that is bound via bindTexture(), notify
- the main thread so that it can start using the texture.
-
- \li 3. Using QPainter to draw into a QGLWidget in a thread.
-
- In Qt 4.8, it is possible to draw into a QGLWidget using a
- QPainter in a separate thread. Note that this is also possible for
- QGLPixelBuffers and QGLFramebufferObjects. Since this is only
- supported in the GL 2 paint engine, OpenGL 2.0 or OpenGL ES 2.0 is
- required.
-
- QGLWidgets can only be created in the main GUI thread. This means
- a call to doneCurrent() is necessary to release the GL context
- from the main thread, before the widget can be drawn into by
- another thread. You then need to call QGLContext::moveToThread()
- to transfer ownership of the context to the thread in which you
- want to make it current.
- Also, the main GUI thread will dispatch resize and
- paint events to a QGLWidget when the widget is resized, or parts
- of it becomes exposed or needs redrawing. It is therefore
- necessary to handle those events because the default
- implementations inside QGLWidget will try to make the QGLWidget's
- context current, which again will interfere with any threads
- rendering into the widget. Reimplement QGLWidget::paintEvent() and
- QGLWidget::resizeEvent() to notify the rendering thread that a
- resize or update is necessary, and be careful not to call the base
- class implementation. If you are rendering an animation, it might
- not be necessary to handle the paint event at all since the
- rendering thread is doing regular updates. Then it would be enough
- to reimplement QGLWidget::paintEvent() to do nothing.
-
- \endlist
-
- As a general rule when doing threaded rendering: be aware that
- binding and releasing contexts in different threads have to be
- synchronized by the user. A GL rendering context can only be
- current in one thread at any time. If you try to open a QPainter
- on a QGLWidget and the widget's rendering context is current in
- another thread, it will fail.
-
- In addition to this, rendering using raw GL calls in a separate
- thread is supported.
-
- \e{OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other
- countries.}
-
- \sa QOpenGLWidget, QGLPixelBuffer
-*/
-
-/*!
- Constructs an OpenGL widget with a \a parent widget.
-
- The \l{QGLFormat::defaultFormat()}{default format} is
- used. The widget will be \l{isValid()}{invalid} if the
- system has no \l{QGLFormat::hasOpenGL()}{OpenGL support}.
-
- The \a parent and widget flag, \a f, arguments are passed
- to the QWidget constructor.
-
- If \a shareWidget is a valid QGLWidget, this widget will share
- OpenGL display lists and texture objects with \a shareWidget. But
- if \a shareWidget and this widget have different \l {format()}
- {formats}, sharing might not be possible. You can check whether
- sharing is in effect by calling isSharing().
-
- The initialization of OpenGL rendering state, etc. should be done
- by overriding the initializeGL() function, rather than in the
- constructor of your QGLWidget subclass.
-
- \sa QGLFormat::defaultFormat(), {Textures Example}
-*/
-
-QGLWidget::QGLWidget(QWidget *parent, const QGLWidget* shareWidget, Qt::WindowFlags f)
- : QWidget(*(new QGLWidgetPrivate), parent, f)
-{
- Q_D(QGLWidget);
- d->init(new QGLContext(QGLFormat::defaultFormat(), this), shareWidget);
-}
-
-/*!
- \internal
- */
-QGLWidget::QGLWidget(QGLWidgetPrivate &dd, const QGLFormat &format, QWidget *parent, const QGLWidget *shareWidget, Qt::WindowFlags f)
- : QWidget(dd, parent, f)
-{
- Q_D(QGLWidget);
- d->init(new QGLContext(format, this), shareWidget);
-
-}
-
-
-/*!
- Constructs an OpenGL widget with parent \a parent.
-
- The \a format argument specifies the desired
- \l{QGLFormat}{rendering options}.
- If the underlying OpenGL/Window system
- cannot satisfy all the features requested in \a format, the
- nearest subset of features will be used. After creation, the
- format() method will return the actual format obtained.
-
- The widget will be \l{isValid()}{invalid} if the system
- has no \l{QGLFormat::hasOpenGL()}{OpenGL support}.
-
- The \a parent and widget flag, \a f, arguments are passed
- to the QWidget constructor.
-
- If \a shareWidget is a valid QGLWidget, this widget will share
- OpenGL display lists and texture objects with \a shareWidget. But
- if \a shareWidget and this widget have different \l {format()}
- {formats}, sharing might not be possible. You can check whether
- sharing is in effect by calling isSharing().
-
- The initialization of OpenGL rendering state, etc. should be done
- by overriding the initializeGL() function, rather than in the
- constructor of your QGLWidget subclass.
-
- \sa QGLFormat::defaultFormat(), isValid()
-*/
-
-QGLWidget::QGLWidget(const QGLFormat &format, QWidget *parent, const QGLWidget* shareWidget,
- Qt::WindowFlags f)
- : QWidget(*(new QGLWidgetPrivate), parent, f)
-{
- Q_D(QGLWidget);
- d->init(new QGLContext(format, this), shareWidget);
-}
-
-/*!
- Constructs an OpenGL widget with parent \a parent.
-
- The \a context argument is a pointer to the QGLContext that
- you wish to be bound to this widget. This allows you to pass in
- your own QGLContext sub-classes.
-
- The widget will be \l{isValid()}{invalid} if the system
- has no \l{QGLFormat::hasOpenGL()}{OpenGL support}.
-
- The \a parent and widget flag, \a f, arguments are passed
- to the QWidget constructor.
-
- If \a shareWidget is a valid QGLWidget, this widget will share
- OpenGL display lists and texture objects with \a shareWidget. But
- if \a shareWidget and this widget have different \l {format()}
- {formats}, sharing might not be possible. You can check whether
- sharing is in effect by calling isSharing().
-
- The initialization of OpenGL rendering state, etc. should be done
- by overriding the initializeGL() function, rather than in the
- constructor of your QGLWidget subclass.
-
- \sa QGLFormat::defaultFormat(), isValid()
-*/
-QGLWidget::QGLWidget(QGLContext *context, QWidget *parent, const QGLWidget *shareWidget,
- Qt::WindowFlags f)
- : QWidget(*(new QGLWidgetPrivate), parent, f)
-{
- Q_D(QGLWidget);
- d->init(context, shareWidget);
-}
-
-/*!
- Destroys the widget.
-*/
-
-QGLWidget::~QGLWidget()
-{
- Q_D(QGLWidget);
- delete d->glcx;
- d->glcx = 0;
- d->cleanupColormaps();
-}
-
-/*!
- \fn QGLFormat QGLWidget::format() const
-
- Returns the format of the contained GL rendering context.
-*/
-
-/*!
- \fn bool QGLWidget::doubleBuffer() const
-
- Returns \c true if the contained GL rendering context has double
- buffering; otherwise returns \c false.
-
- \sa QGLFormat::doubleBuffer()
-*/
-
-/*!
- \fn void QGLWidget::setAutoBufferSwap(bool on)
-
- If \a on is true automatic GL buffer swapping is switched on;
- otherwise it is switched off.
-
- If \a on is true and the widget is using a double-buffered format,
- the background and foreground GL buffers will automatically be
- swapped after each paintGL() call.
-
- The buffer auto-swapping is on by default.
-
- \sa autoBufferSwap(), doubleBuffer(), swapBuffers()
-*/
-
-/*!
- \fn bool QGLWidget::autoBufferSwap() const
-
- Returns \c true if the widget is doing automatic GL buffer swapping;
- otherwise returns \c false.
-
- \sa setAutoBufferSwap()
-*/
-
-/*!
- \fn QFunctionPointer QGLContext::getProcAddress(const QString &proc) const
-
- Returns a function pointer to the GL extension function passed in
- \a proc. \nullptr is returned if a pointer to the function could not be
- obtained.
-*/
-QFunctionPointer QGLContext::getProcAddress(const QString &procName) const
-{
- Q_D(const QGLContext);
- return d->guiGlContext->getProcAddress(procName.toLatin1());
-}
-
-/*!
- \fn bool QGLWidget::isValid() const
-
- Returns \c true if the widget has a valid GL rendering context;
- otherwise returns \c false. A widget will be invalid if the system
- has no \l{QGLFormat::hasOpenGL()}{OpenGL support}.
-*/
-
-bool QGLWidget::isValid() const
-{
- Q_D(const QGLWidget);
- return d->glcx && d->glcx->isValid();
-}
-
-/*!
- \fn bool QGLWidget::isSharing() const
-
- Returns \c true if this widget's GL context is shared with another GL
- context, otherwise false is returned. Context sharing might not be
- possible if the widgets use different formats.
-
- \sa format()
-*/
-
-bool QGLWidget::isSharing() const
-{
- Q_D(const QGLWidget);
- return d->glcx->isSharing();
-}
-
-/*!
- \fn void QGLWidget::makeCurrent()
-
- Makes this widget the current widget for OpenGL operations, i.e.
- makes the widget's rendering context the current OpenGL rendering
- context.
-*/
-
-void QGLWidget::makeCurrent()
-{
- Q_D(QGLWidget);
- d->makeCurrent();
-}
-
-bool QGLWidgetPrivate::makeCurrent()
-{
- glcx->makeCurrent();
- return QGLContext::currentContext() == glcx;
-}
-
-/*!
- \fn void QGLWidget::doneCurrent()
-
- Makes no GL context the current context. Normally, you do not need
- to call this function; QGLContext calls it as necessary. However,
- it may be useful in multithreaded environments.
-*/
-
-void QGLWidget::doneCurrent()
-{
- Q_D(QGLWidget);
- d->glcx->doneCurrent();
-}
-
-/*!
- \fn void QGLWidget::swapBuffers()
-
- Swaps the screen contents with an off-screen buffer. This only
- works if the widget's format specifies double buffer mode.
-
- Normally, there is no need to explicitly call this function
- because it is done automatically after each widget repaint, i.e.
- each time after paintGL() has been executed.
-
- \sa doubleBuffer(), setAutoBufferSwap(), QGLFormat::setDoubleBuffer()
-*/
-
-void QGLWidget::swapBuffers()
-{
- Q_D(QGLWidget);
- d->glcx->swapBuffers();
-}
-
-
-/*!
- \fn const QGLContext* QGLWidget::overlayContext() const
-
- Returns the overlay context of this widget, or \nullptr if this
- widget has no overlay.
-
- \sa context()
-*/
-const QGLContext* QGLWidget::overlayContext() const
-{
- return nullptr;
-}
-
-/*!
- \fn void QGLWidget::makeOverlayCurrent()
-
- Makes the overlay context of this widget current. Use this if you
- need to issue OpenGL commands to the overlay context outside of
- initializeOverlayGL(), resizeOverlayGL(), and paintOverlayGL().
-
- Does nothing if this widget has no overlay.
-
- \sa makeCurrent()
-*/
-void QGLWidget::makeOverlayCurrent()
-{
-}
-
-/*!
- \obsolete
-
- Sets a new format for this widget.
-
- If the underlying OpenGL/Window system cannot satisfy all the
- features requested in \a format, the nearest subset of features will
- be used. After creation, the format() method will return the actual
- rendering context format obtained.
-
- The widget will be assigned a new QGLContext, and the initializeGL()
- function will be executed for this new context before the first
- resizeGL() or paintGL().
-
- This method will try to keep display list and texture object sharing
- in effect with other QGLWidget objects, but changing the format might make
- sharing impossible. Use isSharing() to see if sharing is still in
- effect.
-
- \sa format(), isSharing(), isValid()
-*/
-
-void QGLWidget::setFormat(const QGLFormat &format)
-{
- setContext(new QGLContext(format,this));
-}
-
-
-
-
-/*!
- \fn QGLContext *QGLWidget::context() const
-
- Returns the context of this widget.
-
- It is possible that the context is not valid (see isValid()), for
- example, if the underlying hardware does not support the format
- attributes that were requested.
-*/
-
-/*!
- \fn void QGLWidget::setContext(QGLContext *context,
- const QGLContext* shareContext,
- bool deleteOldContext)
- \obsolete
-
- Sets a new context for this widget. The QGLContext \a context must
- be created using \e new. QGLWidget will delete \a context when
- another context is set or when the widget is destroyed.
-
- If \a context is invalid, QGLContext::create() is performed on
- it. The initializeGL() function will then be executed for the new
- context before the first resizeGL() or paintGL().
-
- If \a context is invalid, this method will try to keep display list
- and texture object sharing in effect, or (if \a shareContext points
- to a valid context) start display list and texture object sharing
- with that context, but sharing might be impossible if the two
- contexts have different \l {format()} {formats}. Use isSharing() to
- see whether sharing is in effect.
-
- If \a deleteOldContext is true (the default), the existing context
- will be deleted. You may use false here if you have kept a pointer
- to the old context (as returned by context()), and want to restore
- that context later.
-
- \note This function is obsolete and should no longer be used. If you were
- using it to recreate the context for a QGLWidget, you should instead create a
- new QGLWidget or use the QOpenGLContext API in conjunction with QWindow.
- There is currently no officially supported way to substitute QGLWidget's
- context with your own implementation of QGLContext.
-
- \sa context(), isSharing()
-*/
-void QGLWidget::setContext(QGLContext *context,
- const QGLContext* shareContext,
- bool deleteOldContext)
-{
- Q_D(QGLWidget);
- if (context == 0) {
- qWarning("QGLWidget::setContext: Cannot set null context");
- return;
- }
-
- if (context->device() == 0) // a context may refere to more than 1 window.
- context->setDevice(this); //but its better to point to 1 of them than none of them.
-
- QGLContext* oldcx = d->glcx;
- d->glcx = context;
-
- if (!d->glcx->isValid())
- d->glcx->create(shareContext ? shareContext : oldcx);
-
- if (deleteOldContext)
- delete oldcx;
-}
-
-/*!
- \fn void QGLWidget::updateGL()
-
- Updates the widget by calling glDraw().
-*/
-
-void QGLWidget::updateGL()
-{
- Q_D(QGLWidget);
- const bool targetIsOffscreen = !d->glcx->d_ptr->readback_target_size.isEmpty();
- if (updatesEnabled() && (testAttribute(Qt::WA_Mapped) || targetIsOffscreen))
- glDraw();
-}
-
-
-/*!
- \fn void QGLWidget::updateOverlayGL()
-
- Updates the widget's overlay (if any). Will cause the virtual
- function paintOverlayGL() to be executed.
-
- The widget's rendering context will become the current context and
- initializeGL() will be called if it hasn't already been called.
-*/
-void QGLWidget::updateOverlayGL()
-{
-}
-
-/*!
- This virtual function is called once before the first call to
- paintGL() or resizeGL(), and then once whenever the widget has
- been assigned a new QGLContext. Reimplement it in a subclass.
-
- This function should set up any required OpenGL context rendering
- flags, defining display lists, etc.
-
- There is no need to call makeCurrent() because this has already
- been done when this function is called.
-*/
-
-void QGLWidget::initializeGL()
-{
-}
-
-
-/*!
- This virtual function is called whenever the widget needs to be
- painted. Reimplement it in a subclass.
-
- There is no need to call makeCurrent() because this has already
- been done when this function is called.
-*/
-
-void QGLWidget::paintGL()
-{
- qgl_functions()->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-}
-
-
-/*!
- \fn void QGLWidget::resizeGL(int width , int height)
-
- This virtual function is called whenever the widget has been
- resized. The new size is passed in \a width and \a height.
- Reimplement it in a subclass.
-
- There is no need to call makeCurrent() because this has already
- been done when this function is called.
-*/
-
-void QGLWidget::resizeGL(int, int)
-{
-}
-
-
-
-/*!
- This virtual function is used in the same manner as initializeGL()
- except that it operates on the widget's overlay context instead of
- the widget's main context. This means that initializeOverlayGL()
- is called once before the first call to paintOverlayGL() or
- resizeOverlayGL(). Reimplement it in a subclass.
-
- This function should set up any required OpenGL context rendering
- flags, defining display lists, etc. for the overlay context.
-
- There is no need to call makeOverlayCurrent() because this has
- already been done when this function is called.
-*/
-
-void QGLWidget::initializeOverlayGL()
-{
-}
-
-
-/*!
- This virtual function is used in the same manner as paintGL()
- except that it operates on the widget's overlay context instead of
- the widget's main context. This means that paintOverlayGL() is
- called whenever the widget's overlay needs to be painted.
- Reimplement it in a subclass.
-
- There is no need to call makeOverlayCurrent() because this has
- already been done when this function is called.
-*/
-
-void QGLWidget::paintOverlayGL()
-{
-}
-
-
-/*!
- \fn void QGLWidget::resizeOverlayGL(int width , int height)
-
- This virtual function is used in the same manner as paintGL()
- except that it operates on the widget's overlay context instead of
- the widget's main context. This means that resizeOverlayGL() is
- called whenever the widget has been resized. The new size is
- passed in \a width and \a height. Reimplement it in a subclass.
-
- There is no need to call makeOverlayCurrent() because this has
- already been done when this function is called.
-*/
-
-void QGLWidget::resizeOverlayGL(int, int)
-{
-}
-
-/*!\reimp
-*/
-bool QGLWidget::event(QEvent *e)
-{
- Q_D(QGLWidget);
-
- // A re-parent will destroy the window and re-create it. We should not reset the context while it happens.
- if (e->type() == QEvent::ParentAboutToChange)
- d->parent_changing = true;
-
- if (e->type() == QEvent::ParentChange)
- d->parent_changing = false;
-
- return QWidget::event(e);
-}
-
-/*!
- \fn void QGLWidget::paintEvent(QPaintEvent *event)
-
- Handles paint events passed in the \a event parameter. Will cause
- the virtual paintGL() function to be called.
-
- The widget's rendering context will become the current context and
- initializeGL() will be called if it hasn't already been called.
-*/
-
-void QGLWidget::paintEvent(QPaintEvent *)
-{
- if (updatesEnabled()) {
- glDraw();
- updateOverlayGL();
- }
-}
-
-
-/*!
- \fn void QGLWidget::resizeEvent(QResizeEvent *event)
-
- Handles resize events that are passed in the \a event parameter.
- Calls the virtual function resizeGL().
-*/
-void QGLWidget::resizeEvent(QResizeEvent *e)
-{
- Q_D(QGLWidget);
-
- QWidget::resizeEvent(e);
- if (!isValid())
- return;
- if (!d->makeCurrent())
- return;
- if (!d->glcx->initialized())
- glInit();
- const qreal scaleFactor = (window() && window()->windowHandle()) ?
- window()->windowHandle()->devicePixelRatio() : 1.0;
-
- resizeGL(width() * scaleFactor, height() * scaleFactor);
-}
-
-/*!
- Renders the current scene on a pixmap and returns the pixmap.
-
- You can use this method on both visible and invisible QGLWidget objects.
-
- Internally the function renders into a framebuffer object and performs pixel
- readback. This has a performance penalty, meaning that this function is not
- suitable to be called at a high frequency.
-
- After creating and binding the framebuffer object, the function will call
- initializeGL(), resizeGL(), and paintGL(). On the next normal update
- initializeGL() and resizeGL() will be triggered again since the size of the
- destination pixmap and the QGLWidget's size may differ.
-
- The size of the pixmap will be \a w pixels wide and \a h pixels high unless
- one of these parameters is 0 (the default), in which case the pixmap will
- have the same size as the widget.
-
- Care must be taken when using framebuffer objects in paintGL() in
- combination with this function. To switch back to the default framebuffer,
- use QGLFramebufferObject::bindDefault(). Binding FBO 0 is wrong since
- renderPixmap() uses a custom framebuffer instead of the one provided by the
- windowing system.
-
- \a useContext is ignored. Historically this parameter enabled the usage of
- the existing GL context. This is not supported anymore since additional
- contexts are never created.
-
- Overlays are not rendered onto the pixmap.
-
- If the GL rendering context and the desktop have different bit
- depths, the result will most likely look surprising.
-
- Note that the creation of display lists, modifications of the view
- frustum etc. should be done from within initializeGL(). If this is
- not done, the temporary QGLContext will not be initialized
- properly, and the rendered pixmap may be incomplete/corrupted.
-*/
-
-QPixmap QGLWidget::renderPixmap(int w, int h, bool useContext)
-{
- Q_UNUSED(useContext);
- Q_D(QGLWidget);
-
- QSize sz = size();
- if ((w > 0) && (h > 0))
- sz = QSize(w, h);
-
- QPixmap pm;
- if (d->glcx->isValid()) {
- d->glcx->makeCurrent();
- QGLFramebufferObject fbo(sz, QGLFramebufferObject::CombinedDepthStencil);
- fbo.bind();
- d->glcx->setInitialized(false);
- uint prevDefaultFbo = d->glcx->d_ptr->default_fbo;
- d->glcx->d_ptr->default_fbo = fbo.handle();
- d->glcx->d_ptr->readback_target_size = sz;
- updateGL();
- fbo.release();
- pm = QPixmap::fromImage(fbo.toImage());
- d->glcx->d_ptr->default_fbo = prevDefaultFbo;
- d->glcx->setInitialized(false);
- d->glcx->d_ptr->readback_target_size = QSize();
- }
-
- return pm;
-}
-
-/*!
- Returns an image of the frame buffer. If \a withAlpha is true the
- alpha channel is included.
-
- Depending on your hardware, you can explicitly select which color
- buffer to grab with a glReadBuffer() call before calling this
- function.
-
- On QNX the back buffer is not preserved when swapBuffers() is called. The back buffer
- where this function reads from, might thus not contain the same content as the front buffer.
- In order to retrieve what is currently visible on the screen, swapBuffers()
- has to be executed prior to this function call.
-*/
-QImage QGLWidget::grabFrameBuffer(bool withAlpha)
-{
- makeCurrent();
- QImage res;
- qreal pixelRatio = devicePixelRatioF();
- int w = pixelRatio * width();
- int h = pixelRatio * height();
- if (format().rgba())
- res = qt_gl_read_frame_buffer(QSize(w, h), format().alpha(), withAlpha);
- res.setDevicePixelRatio(pixelRatio);
- return res;
-}
-
-
-
-/*!
- Initializes OpenGL for this widget's context. Calls the virtual
- function initializeGL().
-*/
-
-void QGLWidget::glInit()
-{
- Q_D(QGLWidget);
- if (!isValid())
- return;
- if (!d->makeCurrent())
- return;
- initializeGL();
- d->glcx->setInitialized(true);
-}
-
-
-/*!
- Executes the virtual function paintGL().
-
- The widget's rendering context will become the current context and
- initializeGL() will be called if it hasn't already been called.
-*/
-
-void QGLWidget::glDraw()
-{
- Q_D(QGLWidget);
- if (!isValid())
- return;
- if (!d->makeCurrent())
- return;
-#ifndef QT_OPENGL_ES
- if (d->glcx->deviceIsPixmap() && !d->glcx->contextHandle()->isOpenGLES())
- qgl1_functions()->glDrawBuffer(GL_FRONT);
-#endif
- QSize readback_target_size = d->glcx->d_ptr->readback_target_size;
- if (!d->glcx->initialized()) {
- glInit();
- const qreal scaleFactor = (window() && window()->windowHandle()) ?
- window()->windowHandle()->devicePixelRatio() : 1.0;
- int w, h;
- if (readback_target_size.isEmpty()) {
- w = d->glcx->device()->width() * scaleFactor;
- h = d->glcx->device()->height() * scaleFactor;
- } else {
- w = readback_target_size.width();
- h = readback_target_size.height();
- }
- resizeGL(w, h); // New context needs this "resize"
- }
- paintGL();
- if (doubleBuffer() && readback_target_size.isEmpty()) {
- if (d->autoSwap)
- swapBuffers();
- } else {
- qgl_functions()->glFlush();
- }
-}
-
-/*!
- Convenience function for specifying a drawing color to OpenGL.
- Calls glColor4 (in RGBA mode) or glIndex (in color-index mode)
- with the color \a c. Applies to this widgets GL context.
-
- \note This function is not supported on OpenGL/ES 2.0 systems.
-
- \sa qglClearColor(), QGLContext::currentContext(), QColor
-*/
-
-void QGLWidget::qglColor(const QColor& c) const
-{
-#if !defined(QT_OPENGL_ES_2)
-#ifdef QT_OPENGL_ES
- qgl_functions()->glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF());
-#else
- Q_D(const QGLWidget);
- const QGLContext *ctx = QGLContext::currentContext();
- if (ctx && !ctx->contextHandle()->isOpenGLES()) {
- if (ctx->format().rgba())
- qgl1_functions()->glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF());
- else if (!d->cmap.isEmpty()) { // QGLColormap in use?
- int i = d->cmap.find(c.rgb());
- if (i < 0)
- i = d->cmap.findNearest(c.rgb());
- qgl1_functions()->glIndexi(i);
- } else
- qgl1_functions()->glIndexi(ctx->colorIndex(c));
- }
-#endif //QT_OPENGL_ES
-#else
- Q_UNUSED(c);
-#endif //QT_OPENGL_ES_2
-}
-
-/*!
- Convenience function for specifying the clearing color to OpenGL.
- Calls glClearColor (in RGBA mode) or glClearIndex (in color-index
- mode) with the color \a c. Applies to this widgets GL context.
-
- \sa qglColor(), QGLContext::currentContext(), QColor
-*/
-
-void QGLWidget::qglClearColor(const QColor& c) const
-{
-#ifdef QT_OPENGL_ES
- qgl_functions()->glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
-#else
- Q_D(const QGLWidget);
- const QGLContext *ctx = QGLContext::currentContext();
- if (ctx && !ctx->contextHandle()->isOpenGLES()) {
- if (ctx->format().rgba())
- qgl_functions()->glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
- else if (!d->cmap.isEmpty()) { // QGLColormap in use?
- int i = d->cmap.find(c.rgb());
- if (i < 0)
- i = d->cmap.findNearest(c.rgb());
- qgl1_functions()->glClearIndex(i);
- } else {
- qgl1_functions()->glClearIndex(ctx->colorIndex(c));
- }
- } else {
- qgl_functions()->glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
- }
-#endif
-}
-
-
-/*!
- Converts the image \a img into the unnamed format expected by
- OpenGL functions such as glTexImage2D(). The returned image is not
- usable as a QImage, but QImage::width(), QImage::height() and
- QImage::bits() may be used with OpenGL. The GL format used is
- \c GL_RGBA.
-
- \omit ###
-
- \l opengl/texture example
- The following few lines are from the texture example. Most of the
- code is irrelevant, so we just quote the relevant bits:
-
- \quotefromfile opengl/texture/gltexobj.cpp
- \skipto tex1
- \printline tex1
- \printline gllogo.bmp
-
- We create \e tex1 (and another variable) for OpenGL, and load a real
- image into \e buf.
-
- \skipto convertToGLFormat
- \printline convertToGLFormat
-
- A few lines later, we convert \e buf into OpenGL format and store it
- in \e tex1.
-
- \skipto glTexImage2D
- \printline glTexImage2D
- \printline tex1.bits
-
- Note the dimension restrictions for texture images as described in
- the glTexImage2D() documentation. The width must be 2^m + 2*border
- and the height 2^n + 2*border where m and n are integers and
- border is either 0 or 1.
-
- Another function in the same example uses \e tex1 with OpenGL.
-
- \endomit
-*/
-
-QImage QGLWidget::convertToGLFormat(const QImage& img)
-{
- QImage res(img.size(), QImage::Format_ARGB32);
- convertToGLFormatHelper(res, img.convertToFormat(QImage::Format_ARGB32), GL_RGBA);
- return res;
-}
-
-
-/*!
- \fn QGLColormap & QGLWidget::colormap() const
-
- Returns the colormap for this widget.
-
- Usually it is only top-level widgets that can have different
- colormaps installed. Asking for the colormap of a child widget
- will return the colormap for the child's top-level widget.
-
- If no colormap has been set for this widget, the QGLColormap
- returned will be empty.
-
- \sa setColormap(), QGLColormap::isEmpty()
-*/
-const QGLColormap & QGLWidget::colormap() const
-{
- Q_D(const QGLWidget);
- return d->cmap;
-}
-
-/*!
- \fn void QGLWidget::setColormap(const QGLColormap & cmap)
-
- Set the colormap for this widget to \a cmap. Usually it is only
- top-level widgets that can have colormaps installed.
-
- \sa colormap()
-*/
-void QGLWidget::setColormap(const QGLColormap & c)
-{
- Q_UNUSED(c);
-}
-
-#ifndef QT_OPENGL_ES
-
-static void qt_save_gl_state()
-{
- QOpenGLFunctions *funcs = qgl_functions();
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
-
- gl1funcs->glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
- gl1funcs->glPushAttrib(GL_ALL_ATTRIB_BITS);
- gl1funcs->glMatrixMode(GL_TEXTURE);
- gl1funcs->glPushMatrix();
- gl1funcs->glLoadIdentity();
- gl1funcs->glMatrixMode(GL_PROJECTION);
- gl1funcs->glPushMatrix();
- gl1funcs->glMatrixMode(GL_MODELVIEW);
- gl1funcs->glPushMatrix();
-
- gl1funcs->glShadeModel(GL_FLAT);
- funcs->glDisable(GL_CULL_FACE);
- funcs->glDisable(GL_LIGHTING);
- funcs->glDisable(GL_STENCIL_TEST);
- funcs->glDisable(GL_DEPTH_TEST);
- funcs->glEnable(GL_BLEND);
- funcs->glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-}
-
-static void qt_restore_gl_state()
-{
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
-
- gl1funcs->glMatrixMode(GL_TEXTURE);
- gl1funcs->glPopMatrix();
- gl1funcs->glMatrixMode(GL_PROJECTION);
- gl1funcs->glPopMatrix();
- gl1funcs->glMatrixMode(GL_MODELVIEW);
- gl1funcs->glPopMatrix();
- gl1funcs->glPopAttrib();
- gl1funcs->glPopClientAttrib();
-}
-
-static void qt_gl_draw_text(QPainter *p, int x, int y, const QString &str,
- const QFont &font)
-{
- GLfloat color[4];
- qgl_functions()->glGetFloatv(GL_CURRENT_COLOR, &color[0]);
-
- QColor col;
- col.setRgbF(color[0], color[1], color[2],color[3]);
- QPen old_pen = p->pen();
- QFont old_font = p->font();
-
- p->setPen(col);
- p->setFont(font);
- p->drawText(x, y, str);
-
- p->setPen(old_pen);
- p->setFont(old_font);
-}
-
-#endif // !QT_OPENGL_ES
-
-/*!
- Renders the string \a str into the GL context of this widget.
-
- \a x and \a y are specified in window coordinates, with the origin
- in the upper left-hand corner of the window. If \a font is not
- specified, the currently set application font will be used to
- render the string. To change the color of the rendered text you can
- use the glColor() call (or the qglColor() convenience function),
- just before the renderText() call.
-
- \note This function clears the stencil buffer.
-
- \note This function is not supported on OpenGL/ES systems.
-
- \note This function temporarily disables depth-testing when the
- text is drawn.
-
- \note This function can only be used inside a
- QPainter::beginNativePainting()/QPainter::endNativePainting() block
- if a painter is active on the QGLWidget.
-*/
-
-void QGLWidget::renderText(int x, int y, const QString &str, const QFont &font)
-{
-#ifndef QT_OPENGL_ES
- Q_D(QGLWidget);
- if (!d->glcx->contextHandle()->isOpenGLES()) {
- Q_D(QGLWidget);
- if (str.isEmpty() || !isValid())
- return;
-
- QOpenGLFunctions *funcs = qgl_functions();
- GLint view[4];
- bool use_scissor_testing = funcs->glIsEnabled(GL_SCISSOR_TEST);
- if (!use_scissor_testing)
- funcs->glGetIntegerv(GL_VIEWPORT, &view[0]);
- int width = d->glcx->device()->width();
- int height = d->glcx->device()->height();
- bool auto_swap = autoBufferSwap();
-
- QPaintEngine *engine = paintEngine();
-
- qt_save_gl_state();
-
- QPainter *p;
- bool reuse_painter = false;
- if (engine->isActive()) {
- reuse_painter = true;
- p = engine->painter();
-
- funcs->glDisable(GL_DEPTH_TEST);
- funcs->glViewport(0, 0, width, height);
- } else {
- setAutoBufferSwap(false);
- // disable glClear() as a result of QPainter::begin()
- d->disable_clear_on_painter_begin = true;
- p = new QPainter(this);
- }
-
- QRect viewport(view[0], view[1], view[2], view[3]);
- if (!use_scissor_testing && viewport != rect()) {
- // if the user hasn't set a scissor box, we set one that
- // covers the current viewport
- funcs->glScissor(view[0], view[1], view[2], view[3]);
- funcs->glEnable(GL_SCISSOR_TEST);
- } else if (use_scissor_testing) {
- // use the scissor box set by the user
- funcs->glEnable(GL_SCISSOR_TEST);
- }
-
- qt_gl_draw_text(p, x, y, str, font);
-
- if (!reuse_painter) {
- p->end();
- delete p;
- setAutoBufferSwap(auto_swap);
- d->disable_clear_on_painter_begin = false;
- }
-
- qt_restore_gl_state();
-
- return;
- }
-#else // QT_OPENGL_ES
- Q_UNUSED(x);
- Q_UNUSED(y);
- Q_UNUSED(str);
- Q_UNUSED(font);
-#endif
- qWarning("QGLWidget::renderText is not supported under OpenGL/ES");
-}
-
-/*! \overload
-
- \a x, \a y and \a z are specified in scene or object coordinates
- relative to the currently set projection and model matrices. This
- can be useful if you want to annotate models with text labels and
- have the labels move with the model as it is rotated etc.
-
- \note This function is not supported on OpenGL/ES systems.
-
- \note If depth testing is enabled before this function is called,
- then the drawn text will be depth-tested against the models that
- have already been drawn in the scene. Use \c{glDisable(GL_DEPTH_TEST)}
- before calling this function to annotate the models without
- depth-testing the text.
-
- \note This function can only be used inside a
- QPainter::beginNativePainting()/QPainter::endNativePainting() block
- if a painter is active on the QGLWidget.
-*/
-void QGLWidget::renderText(double x, double y, double z, const QString &str, const QFont &font)
-{
-#ifndef QT_OPENGL_ES
- Q_D(QGLWidget);
- if (!d->glcx->contextHandle()->isOpenGLES()) {
- Q_D(QGLWidget);
- if (str.isEmpty() || !isValid())
- return;
-
- QOpenGLFunctions *funcs = qgl_functions();
- bool auto_swap = autoBufferSwap();
-
- int width = d->glcx->device()->width();
- int height = d->glcx->device()->height();
- GLdouble model[4 * 4], proj[4 * 4];
- GLint view[4];
- QOpenGLFunctions_1_1 *gl1funcs = qgl1_functions();
- gl1funcs->glGetDoublev(GL_MODELVIEW_MATRIX, &model[0]);
- gl1funcs->glGetDoublev(GL_PROJECTION_MATRIX, &proj[0]);
- funcs->glGetIntegerv(GL_VIEWPORT, &view[0]);
- 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()->devicePixelRatioF();
- win_x /= dpr;
- win_y /= dpr;
- win_y = height - win_y; // y is inverted
-
- QPaintEngine *engine = paintEngine();
-
- QPainter *p;
- bool reuse_painter = false;
- bool use_depth_testing = funcs->glIsEnabled(GL_DEPTH_TEST);
- bool use_scissor_testing = funcs->glIsEnabled(GL_SCISSOR_TEST);
-
- qt_save_gl_state();
-
- if (engine->isActive()) {
- reuse_painter = true;
- p = engine->painter();
- } else {
- setAutoBufferSwap(false);
- // disable glClear() as a result of QPainter::begin()
- d->disable_clear_on_painter_begin = true;
- p = new QPainter(this);
- }
-
- QRect viewport(view[0], view[1], view[2], view[3]);
- if (!use_scissor_testing && viewport != rect()) {
- funcs->glScissor(view[0], view[1], view[2], view[3]);
- funcs->glEnable(GL_SCISSOR_TEST);
- } else if (use_scissor_testing) {
- funcs->glEnable(GL_SCISSOR_TEST);
- }
- funcs->glViewport(0, 0, width * dpr, height * dpr);
- gl1funcs->glAlphaFunc(GL_GREATER, 0.0);
- funcs->glEnable(GL_ALPHA_TEST);
- if (use_depth_testing)
- funcs->glEnable(GL_DEPTH_TEST);
-
- // The only option in Qt 5 is the shader-based OpenGL 2 paint engine.
- // Setting fixed pipeline transformations is futile. Instead, pass the
- // extra values directly and let the engine figure the matrices out.
- static_cast<QGL2PaintEngineEx *>(p->paintEngine())->setTranslateZ(-2 * win_z);
-
- qt_gl_draw_text(p, qRound(win_x), qRound(win_y), str, font);
-
- static_cast<QGL2PaintEngineEx *>(p->paintEngine())->setTranslateZ(0);
-
- if (!reuse_painter) {
- p->end();
- delete p;
- setAutoBufferSwap(auto_swap);
- d->disable_clear_on_painter_begin = false;
- }
-
- qt_restore_gl_state();
-
- return;
- }
-#else // QT_OPENGL_ES
- Q_UNUSED(x);
- Q_UNUSED(y);
- Q_UNUSED(z);
- Q_UNUSED(str);
- Q_UNUSED(font);
-#endif
- qWarning("QGLWidget::renderText is not supported under OpenGL/ES");
-}
-
-QGLFormat QGLWidget::format() const
-{
- Q_D(const QGLWidget);
- return d->glcx->format();
-}
-
-QGLContext *QGLWidget::context() const
-{
- Q_D(const QGLWidget);
- return d->glcx;
-}
-
-bool QGLWidget::doubleBuffer() const
-{
- Q_D(const QGLWidget);
- return d->glcx->d_ptr->glFormat.testOption(QGL::DoubleBuffer);
-}
-
-void QGLWidget::setAutoBufferSwap(bool on)
-{
- Q_D(QGLWidget);
- d->autoSwap = on;
-}
-
-bool QGLWidget::autoBufferSwap() const
-{
- Q_D(const QGLWidget);
- return d->autoSwap;
-}
-
-/*!
- Calls QGLContext:::bindTexture(\a image, \a target, \a format) on the currently
- set context.
-
- \sa deleteTexture()
-*/
-GLuint QGLWidget::bindTexture(const QImage &image, GLenum target, GLint format)
-{
- if (image.isNull())
- return 0;
-
- Q_D(QGLWidget);
- return d->glcx->bindTexture(image, target, format, QGLContext::DefaultBindOption);
-}
-
-/*!
- \overload
- \since 4.6
-
- The binding \a options are a set of options used to decide how to
- bind the texture to the context.
- */
-GLuint QGLWidget::bindTexture(const QImage &image, GLenum target, GLint format, QGLContext::BindOptions options)
-{
- if (image.isNull())
- return 0;
-
- Q_D(QGLWidget);
- return d->glcx->bindTexture(image, target, format, options);
-}
-
-
-/*!
- Calls QGLContext:::bindTexture(\a pixmap, \a target, \a format) on the currently
- set context.
-
- \sa deleteTexture()
-*/
-GLuint QGLWidget::bindTexture(const QPixmap &pixmap, GLenum target, GLint format)
-{
- if (pixmap.isNull())
- return 0;
-
- Q_D(QGLWidget);
- return d->glcx->bindTexture(pixmap, target, format, QGLContext::DefaultBindOption);
-}
-
-/*!
- \overload
- \since 4.6
-
- Generates and binds a 2D GL texture to the current context, based
- on \a pixmap. The generated texture id is returned and can be used in
-
- The binding \a options are a set of options used to decide how to
- bind the texture to the context.
- */
-GLuint QGLWidget::bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
- QGLContext::BindOptions options)
-{
- Q_D(QGLWidget);
- return d->glcx->bindTexture(pixmap, target, format, options);
-}
-
-/*! \overload
-
- Calls QGLContext::bindTexture(\a fileName) on the currently set context.
-
- \sa deleteTexture()
-*/
-GLuint QGLWidget::bindTexture(const QString &fileName)
-{
- Q_D(QGLWidget);
- return d->glcx->bindTexture(fileName);
-}
-
-/*!
- Calls QGLContext::deleteTexture(\a id) on the currently set
- context.
-
- \sa bindTexture()
-*/
-void QGLWidget::deleteTexture(GLuint id)
-{
- Q_D(QGLWidget);
- d->glcx->deleteTexture(id);
-}
-
-/*!
- \since 4.4
-
- Calls the corresponding QGLContext::drawTexture() with
- \a target, \a textureId, and \a textureTarget for this
- widget's context.
-*/
-void QGLWidget::drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget)
-{
- Q_D(QGLWidget);
- d->glcx->drawTexture(target, textureId, textureTarget);
-}
-
-/*!
- \since 4.4
-
- Calls the corresponding QGLContext::drawTexture() with
- \a point, \a textureId, and \a textureTarget for this
- widget's context.
-*/
-void QGLWidget::drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget)
-{
- Q_D(QGLWidget);
- d->glcx->drawTexture(point, textureId, textureTarget);
-}
-
-Q_GLOBAL_STATIC(QGLEngineThreadStorage<QGL2PaintEngineEx>, qt_gl_2_engine)
-
-Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine()
-{
- return qt_gl_2_engine()->engine();
-}
-
-/*!
- \internal
-
- Returns the GL widget's paint engine.
-*/
-QPaintEngine *QGLWidget::paintEngine() const
-{
- return qt_qgl_paint_engine();
-}
-
-void QGLWidgetPrivate::init(QGLContext *context, const QGLWidget *shareWidget)
-{
- Q_Q(QGLWidget);
- q->setAttribute(Qt::WA_PaintOnScreen);
- q->setAttribute(Qt::WA_NoSystemBackground);
- q->setAutoFillBackground(true); // for compatibility
-
- mustHaveWindowHandle = 1;
- q->setAttribute(Qt::WA_NativeWindow);
- q->setWindowFlag(Qt::MSWindowsOwnDC);
-
- initContext(context, shareWidget);
-}
-
-/*
- This is the shared initialization for all platforms. Called from QGLWidgetPrivate::init()
-*/
-void QGLWidgetPrivate::initContext(QGLContext *context, const QGLWidget* shareWidget)
-{
- Q_Q(QGLWidget);
-
- glDevice.setWidget(q);
-
- glcx = 0;
- autoSwap = true;
-
- if (context && !context->device())
- context->setDevice(q);
- q->setContext(context, shareWidget ? shareWidget->context() : 0);
-
- if (!glcx)
- glcx = new QGLContext(QGLFormat::defaultFormat(), q);
-}
-
-bool QGLWidgetPrivate::renderCxPm(QPixmap*)
-{
- return false;
-}
-
-/*! \internal
- Free up any allocated colormaps. This fn is only called for
- top-level widgets.
-*/
-void QGLWidgetPrivate::cleanupColormaps()
-{
-}
-
-void QGLContextGroup::addShare(const QGLContext *context, const QGLContext *share) {
- Q_ASSERT(context && share);
- if (context->d_ptr->group == share->d_ptr->group)
- return;
-
- // Make sure 'context' is not already shared with another group of contexts.
- Q_ASSERT(context->d_ptr->group->m_refs.loadRelaxed() == 1);
-
- // Free 'context' group resources and make it use the same resources as 'share'.
- QGLContextGroup *group = share->d_ptr->group;
- delete context->d_ptr->group;
- context->d_ptr->group = group;
- group->m_refs.ref();
-
- // Maintain a list of all the contexts in each group of sharing contexts.
- // The list is empty if the "share" context wasn't sharing already.
- if (group->m_shares.isEmpty())
- group->m_shares.append(share);
- group->m_shares.append(context);
-}
-
-void QGLContextGroup::removeShare(const QGLContext *context) {
- // Remove the context from the group.
- QGLContextGroup *group = context->d_ptr->group;
- if (group->m_shares.isEmpty())
- return;
- group->m_shares.removeAll(context);
-
- // Update context group representative.
- Q_ASSERT(group->m_shares.size() != 0);
- if (group->m_context == context)
- group->m_context = group->m_shares.at(0);
-
- // If there is only one context left, then make the list empty.
- if (group->m_shares.size() == 1)
- group->m_shares.clear();
-}
-
-QSize QGLTexture::bindCompressedTexture
- (const QString& fileName, const char *format)
-{
- QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly))
- return QSize();
- QByteArray contents = file.readAll();
- file.close();
- return bindCompressedTexture
- (contents.constData(), contents.size(), format);
-}
-
-// PVR header format for container files that store textures compressed
-// with the ETC1, PVRTC2, and PVRTC4 encodings. Format information from the
-// PowerVR SDK at http://www.imgtec.com/powervr/insider/powervr-sdk.asp
-// "PVRTexTool Reference Manual, version 1.11f".
-struct PvrHeader
-{
- quint32 headerSize;
- quint32 height;
- quint32 width;
- quint32 mipMapCount;
- quint32 flags;
- quint32 dataSize;
- quint32 bitsPerPixel;
- quint32 redMask;
- quint32 greenMask;
- quint32 blueMask;
- quint32 alphaMask;
- quint32 magic;
- quint32 surfaceCount;
-};
-
-#define PVR_MAGIC 0x21525650 // "PVR!" in little-endian
-
-#define PVR_FORMAT_MASK 0x000000FF
-#define PVR_FORMAT_PVRTC2 0x00000018
-#define PVR_FORMAT_PVRTC4 0x00000019
-#define PVR_FORMAT_ETC1 0x00000036
-
-#define PVR_HAS_MIPMAPS 0x00000100
-#define PVR_TWIDDLED 0x00000200
-#define PVR_NORMAL_MAP 0x00000400
-#define PVR_BORDER_ADDED 0x00000800
-#define PVR_CUBE_MAP 0x00001000
-#define PVR_FALSE_COLOR_MIPMAPS 0x00002000
-#define PVR_VOLUME_TEXTURE 0x00004000
-#define PVR_ALPHA_IN_TEXTURE 0x00008000
-#define PVR_VERTICAL_FLIP 0x00010000
-
-#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG
-#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
-#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
-#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
-#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
-#endif
-
-#ifndef GL_ETC1_RGB8_OES
-#define GL_ETC1_RGB8_OES 0x8D64
-#endif
-
-bool QGLTexture::canBindCompressedTexture
- (const char *buf, int len, const char *format, bool *hasAlpha)
-{
- if (QSysInfo::ByteOrder != QSysInfo::LittleEndian) {
- // Compressed texture loading only supported on little-endian
- // systems such as x86 and ARM at the moment.
- return false;
- }
- if (!format) {
- // Auto-detect the format from the header.
- if (len >= 4 && !qstrncmp(buf, "DDS ", 4)) {
- *hasAlpha = true;
- return true;
- } else if (len >= 52 && !qstrncmp(buf + 44, "PVR!", 4)) {
- const PvrHeader *pvrHeader =
- reinterpret_cast<const PvrHeader *>(buf);
- *hasAlpha = (pvrHeader->alphaMask != 0);
- return true;
- }
- } else {
- // Validate the format against the header.
- if (!qstricmp(format, "DDS")) {
- if (len >= 4 && !qstrncmp(buf, "DDS ", 4)) {
- *hasAlpha = true;
- return true;
- }
- } else if (!qstricmp(format, "PVR") || !qstricmp(format, "ETC1")) {
- if (len >= 52 && !qstrncmp(buf + 44, "PVR!", 4)) {
- const PvrHeader *pvrHeader =
- reinterpret_cast<const PvrHeader *>(buf);
- *hasAlpha = (pvrHeader->alphaMask != 0);
- return true;
- }
- }
- }
- return false;
-}
-
-#define ctx QGLContext::currentContext()
-
-QSize QGLTexture::bindCompressedTexture
- (const char *buf, int len, const char *format)
-{
- if (QSysInfo::ByteOrder != QSysInfo::LittleEndian) {
- // Compressed texture loading only supported on little-endian
- // systems such as x86 and ARM at the moment.
- return QSize();
- }
- if (!format) {
- // Auto-detect the format from the header.
- if (len >= 4 && !qstrncmp(buf, "DDS ", 4))
- return bindCompressedTextureDDS(buf, len);
- else if (len >= 52 && !qstrncmp(buf + 44, "PVR!", 4))
- return bindCompressedTexturePVR(buf, len);
- } else {
- // Validate the format against the header.
- if (!qstricmp(format, "DDS")) {
- if (len >= 4 && !qstrncmp(buf, "DDS ", 4))
- return bindCompressedTextureDDS(buf, len);
- } else if (!qstricmp(format, "PVR") || !qstricmp(format, "ETC1")) {
- if (len >= 52 && !qstrncmp(buf + 44, "PVR!", 4))
- return bindCompressedTexturePVR(buf, len);
- }
- }
- return QSize();
-}
-
-QSize QGLTexture::bindCompressedTextureDDS(const char *buf, int len)
-{
- // We only support 2D texture loading at present.
- if (target != GL_TEXTURE_2D)
- return QSize();
-
- // Bail out if the necessary extension is not present.
- if (!qgl_extensions()->hasOpenGLExtension(QOpenGLExtensions::DDSTextureCompression)) {
- qWarning("QGLContext::bindTexture(): DDS texture compression is not supported.");
- return QSize();
- }
-
- const DDSFormat *ddsHeader = reinterpret_cast<const DDSFormat *>(buf + 4);
- if (!ddsHeader->dwLinearSize) {
- qWarning("QGLContext::bindTexture(): DDS image size is not valid.");
- return QSize();
- }
-
- int blockSize = 16;
- GLenum format;
-
- switch(ddsHeader->ddsPixelFormat.dwFourCC) {
- case FOURCC_DXT1:
- format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
- blockSize = 8;
- break;
- case FOURCC_DXT3:
- format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
- break;
- case FOURCC_DXT5:
- format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
- break;
- default:
- qWarning("QGLContext::bindTexture(): DDS image format not supported.");
- return QSize();
- }
-
- const GLubyte *pixels =
- reinterpret_cast<const GLubyte *>(buf + ddsHeader->dwSize + 4);
-
- QOpenGLFunctions *funcs = qgl_functions();
- funcs->glGenTextures(1, &id);
- funcs->glBindTexture(GL_TEXTURE_2D, id);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-
- int size;
- int offset = 0;
- int available = len - int(ddsHeader->dwSize + 4);
- int w = ddsHeader->dwWidth;
- int h = ddsHeader->dwHeight;
-
- // load mip-maps
- for(int i = 0; i < (int) ddsHeader->dwMipMapCount; ++i) {
- if (w == 0) w = 1;
- if (h == 0) h = 1;
-
- size = ((w+3)/4) * ((h+3)/4) * blockSize;
- if (size > available)
- break;
- qgl_extensions()->glCompressedTexImage2D(GL_TEXTURE_2D, i, format, w, h, 0,
- size, pixels + offset);
- offset += size;
- available -= size;
-
- // half size for each mip-map level
- w = w/2;
- h = h/2;
- }
-
- // DDS images are not inverted.
- options &= ~QGLContext::InvertedYBindOption;
-
- return QSize(ddsHeader->dwWidth, ddsHeader->dwHeight);
-}
-
-QSize QGLTexture::bindCompressedTexturePVR(const char *buf, int len)
-{
- // We only support 2D texture loading at present. Cube maps later.
- if (target != GL_TEXTURE_2D)
- return QSize();
-
- // Determine which texture format we will be loading.
- const PvrHeader *pvrHeader = reinterpret_cast<const PvrHeader *>(buf);
- GLenum textureFormat;
- quint32 minWidth, minHeight;
- switch (pvrHeader->flags & PVR_FORMAT_MASK) {
- case PVR_FORMAT_PVRTC2:
- if (pvrHeader->alphaMask)
- textureFormat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
- else
- textureFormat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
- minWidth = 16;
- minHeight = 8;
- break;
-
- case PVR_FORMAT_PVRTC4:
- if (pvrHeader->alphaMask)
- textureFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
- else
- textureFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
- minWidth = 8;
- minHeight = 8;
- break;
-
- case PVR_FORMAT_ETC1:
- textureFormat = GL_ETC1_RGB8_OES;
- minWidth = 4;
- minHeight = 4;
- break;
-
- default:
- qWarning("QGLContext::bindTexture(): PVR image format 0x%x not supported.", int(pvrHeader->flags & PVR_FORMAT_MASK));
- return QSize();
- }
-
- // Bail out if the necessary extension is not present.
- if (textureFormat == GL_ETC1_RGB8_OES) {
- if (!qgl_extensions()->hasOpenGLExtension(QOpenGLExtensions::ETC1TextureCompression)) {
- qWarning("QGLContext::bindTexture(): ETC1 texture compression is not supported.");
- return QSize();
- }
- } else {
- if (!qgl_extensions()->hasOpenGLExtension(QOpenGLExtensions::PVRTCTextureCompression)) {
- qWarning("QGLContext::bindTexture(): PVRTC texture compression is not supported.");
- return QSize();
- }
- }
-
- // Boundary check on the buffer size.
- quint32 bufferSize = pvrHeader->headerSize + pvrHeader->dataSize;
- if (bufferSize > quint32(len)) {
- qWarning("QGLContext::bindTexture(): PVR image size is not valid.");
- return QSize();
- }
-
- // Create the texture.
- QOpenGLFunctions *funcs = qgl_functions();
- funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- funcs->glGenTextures(1, &id);
- funcs->glBindTexture(GL_TEXTURE_2D, id);
- if (pvrHeader->mipMapCount) {
- if ((options & QGLContext::LinearFilteringBindOption) != 0) {
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- } else {
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
- }
- } else if ((options & QGLContext::LinearFilteringBindOption) != 0) {
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- } else {
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- }
-
- // Load the compressed mipmap levels.
- const GLubyte *buffer =
- reinterpret_cast<const GLubyte *>(buf + pvrHeader->headerSize);
- bufferSize = pvrHeader->dataSize;
- quint32 level = 0;
- quint32 width = pvrHeader->width;
- quint32 height = pvrHeader->height;
- while (bufferSize > 0 && level <= pvrHeader->mipMapCount) {
- quint32 size =
- (qMax(width, minWidth) * qMax(height, minHeight) *
- pvrHeader->bitsPerPixel) / 8;
- if (size > bufferSize)
- break;
- qgl_extensions()->glCompressedTexImage2D(GL_TEXTURE_2D, GLint(level), textureFormat,
- GLsizei(width), GLsizei(height), 0,
- GLsizei(size), buffer);
- width /= 2;
- height /= 2;
- buffer += size;
- ++level;
- }
-
- // Restore the default pixel alignment for later texture uploads.
- funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
-
- // Set the invert flag for the texture. The "vertical flip"
- // flag in PVR is the opposite sense to our sense of inversion.
- options.setFlag(QGLContext::InvertedYBindOption, !(pvrHeader->flags & PVR_VERTICAL_FLIP));
-
- return QSize(pvrHeader->width, pvrHeader->height);
-}
-
-#undef ctx
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qgl.h b/src/opengl/qgl.h
deleted file mode 100644
index f5accbeb3c..0000000000
--- a/src/opengl/qgl.h
+++ /dev/null
@@ -1,524 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGL_H
-#define QGL_H
-
-#ifndef QT_NO_OPENGL
-
-#include <QtGui/qopengl.h>
-#include <QtWidgets/qwidget.h>
-#include <QtGui/qpaintengine.h>
-#include <QtOpenGL/qglcolormap.h>
-#include <QtCore/qmap.h>
-#include <QtCore/qscopedpointer.h>
-
-#include <QtGui/QSurfaceFormat>
-
-QT_BEGIN_NAMESPACE
-
-
-
-
-class QPixmap;
-class QGLWidgetPrivate;
-class QGLContextPrivate;
-
-// Namespace class:
-namespace QGL
-{
- enum FormatOption {
- DoubleBuffer = 0x0001,
- DepthBuffer = 0x0002,
- Rgba = 0x0004,
- AlphaChannel = 0x0008,
- AccumBuffer = 0x0010,
- StencilBuffer = 0x0020,
- StereoBuffers = 0x0040,
- DirectRendering = 0x0080,
- HasOverlay = 0x0100,
- SampleBuffers = 0x0200,
- DeprecatedFunctions = 0x0400,
- SingleBuffer = DoubleBuffer << 16,
- NoDepthBuffer = DepthBuffer << 16,
- ColorIndex = Rgba << 16,
- NoAlphaChannel = AlphaChannel << 16,
- NoAccumBuffer = AccumBuffer << 16,
- NoStencilBuffer = StencilBuffer << 16,
- NoStereoBuffers = StereoBuffers << 16,
- IndirectRendering = DirectRendering << 16,
- NoOverlay = HasOverlay << 16,
- NoSampleBuffers = SampleBuffers << 16,
- NoDeprecatedFunctions = DeprecatedFunctions << 16
- };
- Q_DECLARE_FLAGS(FormatOptions, FormatOption)
-}
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGL::FormatOptions)
-
-class QGLFormatPrivate;
-
-class Q_OPENGL_EXPORT QGLFormat
-{
-public:
- QGLFormat();
- QGLFormat(QGL::FormatOptions options, int plane = 0);
- QGLFormat(const QGLFormat &other);
- QGLFormat &operator=(const QGLFormat &other);
- ~QGLFormat();
-
- void setDepthBufferSize(int size);
- int depthBufferSize() const;
-
- void setAccumBufferSize(int size);
- int accumBufferSize() const;
-
- void setRedBufferSize(int size);
- int redBufferSize() const;
-
- void setGreenBufferSize(int size);
- int greenBufferSize() const;
-
- void setBlueBufferSize(int size);
- int blueBufferSize() const;
-
- void setAlphaBufferSize(int size);
- int alphaBufferSize() const;
-
- void setStencilBufferSize(int size);
- int stencilBufferSize() const;
-
- void setSampleBuffers(bool enable);
- bool sampleBuffers() const;
-
- void setSamples(int numSamples);
- int samples() const;
-
- void setSwapInterval(int interval);
- int swapInterval() const;
-
- bool doubleBuffer() const;
- void setDoubleBuffer(bool enable);
- bool depth() const;
- void setDepth(bool enable);
- bool rgba() const;
- void setRgba(bool enable);
- bool alpha() const;
- void setAlpha(bool enable);
- bool accum() const;
- void setAccum(bool enable);
- bool stencil() const;
- void setStencil(bool enable);
- bool stereo() const;
- void setStereo(bool enable);
- bool directRendering() const;
- void setDirectRendering(bool enable);
- bool hasOverlay() const;
- void setOverlay(bool enable);
-
- int plane() const;
- void setPlane(int plane);
-
- void setOption(QGL::FormatOptions opt);
- bool testOption(QGL::FormatOptions opt) const;
-
- static QGLFormat defaultFormat();
- static void setDefaultFormat(const QGLFormat& f);
-
- static QGLFormat defaultOverlayFormat();
- static void setDefaultOverlayFormat(const QGLFormat& f);
-
- static bool hasOpenGL();
- static bool hasOpenGLOverlays();
-
- void setVersion(int major, int minor);
- int majorVersion() const;
- int minorVersion() const;
-
- enum OpenGLContextProfile {
- NoProfile,
- CoreProfile,
- CompatibilityProfile
- };
-
- void setProfile(OpenGLContextProfile profile);
- OpenGLContextProfile profile() const;
-
- enum OpenGLVersionFlag {
- OpenGL_Version_None = 0x00000000,
- OpenGL_Version_1_1 = 0x00000001,
- OpenGL_Version_1_2 = 0x00000002,
- OpenGL_Version_1_3 = 0x00000004,
- OpenGL_Version_1_4 = 0x00000008,
- OpenGL_Version_1_5 = 0x00000010,
- OpenGL_Version_2_0 = 0x00000020,
- OpenGL_Version_2_1 = 0x00000040,
- OpenGL_ES_Common_Version_1_0 = 0x00000080,
- OpenGL_ES_CommonLite_Version_1_0 = 0x00000100,
- OpenGL_ES_Common_Version_1_1 = 0x00000200,
- OpenGL_ES_CommonLite_Version_1_1 = 0x00000400,
- OpenGL_ES_Version_2_0 = 0x00000800,
- OpenGL_Version_3_0 = 0x00001000,
- OpenGL_Version_3_1 = 0x00002000,
- OpenGL_Version_3_2 = 0x00004000,
- OpenGL_Version_3_3 = 0x00008000,
- OpenGL_Version_4_0 = 0x00010000,
- OpenGL_Version_4_1 = 0x00020000,
- OpenGL_Version_4_2 = 0x00040000,
- OpenGL_Version_4_3 = 0x00080000
- };
- Q_DECLARE_FLAGS(OpenGLVersionFlags, OpenGLVersionFlag)
-
- static OpenGLVersionFlags openGLVersionFlags();
-
- static QGLFormat fromSurfaceFormat(const QSurfaceFormat &format);
- static QSurfaceFormat toSurfaceFormat(const QGLFormat &format);
-private:
- QGLFormatPrivate *d;
-
- void detach();
-
- friend Q_OPENGL_EXPORT bool operator==(const QGLFormat&, const QGLFormat&);
- friend Q_OPENGL_EXPORT bool operator!=(const QGLFormat&, const QGLFormat&);
-#ifndef QT_NO_DEBUG_STREAM
- friend Q_OPENGL_EXPORT QDebug operator<<(QDebug, const QGLFormat &);
-#endif
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGLFormat::OpenGLVersionFlags)
-
-Q_OPENGL_EXPORT bool operator==(const QGLFormat&, const QGLFormat&);
-Q_OPENGL_EXPORT bool operator!=(const QGLFormat&, const QGLFormat&);
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_OPENGL_EXPORT QDebug operator<<(QDebug, const QGLFormat &);
-#endif
-
-class QGLFunctions;
-
-class Q_OPENGL_EXPORT QGLContext
-{
- Q_DECLARE_PRIVATE(QGLContext)
-public:
- QGLContext(const QGLFormat& format, QPaintDevice* device);
- QGLContext(const QGLFormat& format);
- virtual ~QGLContext();
-
- virtual bool create(const QGLContext* shareContext = nullptr);
- bool isValid() const;
- bool isSharing() const;
- void reset();
-
- static bool areSharing(const QGLContext *context1, const QGLContext *context2);
-
- QGLFormat format() const;
- QGLFormat requestedFormat() const;
- void setFormat(const QGLFormat& format);
-
- void moveToThread(QThread *thread);
-
- virtual void makeCurrent();
- virtual void doneCurrent();
-
- virtual void swapBuffers() const;
-
- QGLFunctions *functions() const;
-
- enum BindOption {
- NoBindOption = 0x0000,
- InvertedYBindOption = 0x0001,
- MipmapBindOption = 0x0002,
- PremultipliedAlphaBindOption = 0x0004,
- LinearFilteringBindOption = 0x0008,
-
- MemoryManagedBindOption = 0x0010, // internal flag
- CanFlipNativePixmapBindOption = 0x0020, // internal flag
- TemporarilyCachedBindOption = 0x0040, // internal flag
-
- DefaultBindOption = LinearFilteringBindOption
- | InvertedYBindOption
- | MipmapBindOption,
- InternalBindOption = MemoryManagedBindOption
- | PremultipliedAlphaBindOption
- };
- Q_DECLARE_FLAGS(BindOptions, BindOption)
-
- GLuint bindTexture(const QImage &image, GLenum target, GLint format,
- BindOptions options);
- GLuint bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
- BindOptions options);
-
- GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D,
- GLint format = GL_RGBA);
- GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D,
- GLint format = GL_RGBA);
- GLuint bindTexture(const QString &fileName);
-
- void deleteTexture(GLuint tx_id);
-
- void drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
- void drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
-
- static void setTextureCacheLimit(int size);
- static int textureCacheLimit();
-
- QFunctionPointer getProcAddress(const QString &proc) const;
- QPaintDevice* device() const;
- QColor overlayTransparentColor() const;
-
- static const QGLContext* currentContext();
-
- static QGLContext *fromOpenGLContext(QOpenGLContext *platformContext);
- QOpenGLContext *contextHandle() const;
-
-protected:
- virtual bool chooseContext(const QGLContext* shareContext = nullptr);
-
- bool deviceIsPixmap() const;
- bool windowCreated() const;
- void setWindowCreated(bool on);
- bool initialized() const;
- void setInitialized(bool on);
-
- uint colorIndex(const QColor& c) const;
- void setValid(bool valid);
- void setDevice(QPaintDevice *pDev);
-
-protected:
- static QGLContext* currentCtx;
-
-private:
- QGLContext(QOpenGLContext *windowContext);
-
- QScopedPointer<QGLContextPrivate> d_ptr;
-
- friend class QGLPixelBuffer;
- friend class QGLPixelBufferPrivate;
- friend class QGLWidget;
- friend class QGLWidgetPrivate;
- friend class QGLGlyphCache;
- friend class QGL2PaintEngineEx;
- friend class QGL2PaintEngineExPrivate;
- friend class QGLEngineShaderManager;
- friend class QGLTextureGlyphCache;
- friend struct QGLGlyphTexture;
- friend class QGLContextGroup;
- friend class QGLPixmapBlurFilter;
- friend class QGLTexture;
- friend QGLFormat::OpenGLVersionFlags QGLFormat::openGLVersionFlags();
- friend class QGLFramebufferObject;
- friend class QGLFramebufferObjectPrivate;
- friend class QGLFBOGLPaintDevice;
- friend class QGLPaintDevice;
- friend class QGLWidgetGLPaintDevice;
- friend class QX11GLSharedContexts;
- friend class QGLContextResourceBase;
- friend class QSGDistanceFieldGlyphCache;
-private:
- Q_DISABLE_COPY(QGLContext)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGLContext::BindOptions)
-
-class Q_OPENGL_EXPORT QGLWidget : public QWidget
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QGLWidget)
-public:
- explicit QGLWidget(QWidget* parent=nullptr,
- const QGLWidget* shareWidget = nullptr, Qt::WindowFlags f=Qt::WindowFlags());
- explicit QGLWidget(QGLContext *context, QWidget* parent=nullptr,
- const QGLWidget* shareWidget = nullptr, Qt::WindowFlags f=Qt::WindowFlags());
- explicit QGLWidget(const QGLFormat& format, QWidget* parent=nullptr,
- const QGLWidget* shareWidget = nullptr, Qt::WindowFlags f=Qt::WindowFlags());
- ~QGLWidget();
-
- void qglColor(const QColor& c) const;
- void qglClearColor(const QColor& c) const;
-
- bool isValid() const;
- bool isSharing() const;
-
- void makeCurrent();
- void doneCurrent();
-
- bool doubleBuffer() const;
- void swapBuffers();
-
- QGLFormat format() const;
- void setFormat(const QGLFormat& format);
-
- QGLContext* context() const;
- void setContext(QGLContext* context, const QGLContext* shareContext = nullptr,
- bool deleteOldContext = true);
-
- QPixmap renderPixmap(int w = 0, int h = 0, bool useContext = false);
- QImage grabFrameBuffer(bool withAlpha = false);
-
- void makeOverlayCurrent();
- const QGLContext* overlayContext() const;
-
- static QImage convertToGLFormat(const QImage& img);
-
- const QGLColormap & colormap() const;
- void setColormap(const QGLColormap & map);
-
- void renderText(int x, int y, const QString & str,
- const QFont & fnt = QFont());
- void renderText(double x, double y, double z, const QString & str,
- const QFont & fnt = QFont());
- QPaintEngine *paintEngine() const override;
-
- GLuint bindTexture(const QImage &image, GLenum target, GLint format,
- QGLContext::BindOptions options);
- GLuint bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
- QGLContext::BindOptions options);
-
- GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D,
- GLint format = GL_RGBA);
- GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D,
- GLint format = GL_RGBA);
-
- GLuint bindTexture(const QString &fileName);
-
- void deleteTexture(GLuint tx_id);
-
- void drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
- void drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
-
-public Q_SLOTS:
- virtual void updateGL();
- virtual void updateOverlayGL();
-
-protected:
- bool event(QEvent *) override;
- virtual void initializeGL();
- virtual void resizeGL(int w, int h);
- virtual void paintGL();
-
- virtual void initializeOverlayGL();
- virtual void resizeOverlayGL(int w, int h);
- virtual void paintOverlayGL();
-
- void setAutoBufferSwap(bool on);
- bool autoBufferSwap() const;
-
- void paintEvent(QPaintEvent*) override;
- void resizeEvent(QResizeEvent*) override;
-
- virtual void glInit();
- virtual void glDraw();
-
- QGLWidget(QGLWidgetPrivate &dd,
- const QGLFormat &format = QGLFormat(),
- QWidget *parent = nullptr,
- const QGLWidget* shareWidget = nullptr,
- Qt::WindowFlags f = Qt::WindowFlags());
-private:
- Q_DISABLE_COPY(QGLWidget)
-
- friend class QGLDrawable;
- friend class QGLPixelBuffer;
- friend class QGLPixelBufferPrivate;
- friend class QGLContext;
- friend class QGLContextPrivate;
- friend class QGLOverlayWidget;
- friend class QGLPaintDevice;
- friend class QGLWidgetGLPaintDevice;
-};
-
-
-//
-// QGLFormat inline functions
-//
-
-inline bool QGLFormat::doubleBuffer() const
-{
- return testOption(QGL::DoubleBuffer);
-}
-
-inline bool QGLFormat::depth() const
-{
- return testOption(QGL::DepthBuffer);
-}
-
-inline bool QGLFormat::rgba() const
-{
- return testOption(QGL::Rgba);
-}
-
-inline bool QGLFormat::alpha() const
-{
- return testOption(QGL::AlphaChannel);
-}
-
-inline bool QGLFormat::accum() const
-{
- return testOption(QGL::AccumBuffer);
-}
-
-inline bool QGLFormat::stencil() const
-{
- return testOption(QGL::StencilBuffer);
-}
-
-inline bool QGLFormat::stereo() const
-{
- return testOption(QGL::StereoBuffers);
-}
-
-inline bool QGLFormat::directRendering() const
-{
- return testOption(QGL::DirectRendering);
-}
-
-inline bool QGLFormat::hasOverlay() const
-{
- return testOption(QGL::HasOverlay);
-}
-
-inline bool QGLFormat::sampleBuffers() const
-{
- return testOption(QGL::SampleBuffers);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_OPENGL
-#endif // QGL_H
diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h
deleted file mode 100644
index 4e52c0f5e9..0000000000
--- a/src/opengl/qgl_p.h
+++ /dev/null
@@ -1,556 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGL_P_H
-#define QGL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QGLWidget class. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtOpenGL/qgl.h"
-#include "QtOpenGL/qglcolormap.h"
-#include "QtCore/qmap.h"
-#include "QtCore/qthread.h"
-#include "QtCore/qthreadstorage.h"
-#include "QtCore/qhashfunctions.h"
-#include "QtCore/qatomic.h"
-#include "QtWidgets/private/qwidget_p.h"
-#include "QtGui/private/qopenglcontext_p.h"
-#include "QtGui/private/qopenglextensions_p.h"
-#include "qcache.h"
-#include "qglpaintdevice_p.h"
-
-#include <QtGui/QOpenGLContext>
-
-QT_BEGIN_NAMESPACE
-
-class QGLContext;
-class QGLOverlayWidget;
-class QPixmap;
-class QOpenGLExtensions;
-
-class QGLFormatPrivate
-{
-public:
- QGLFormatPrivate()
- : ref(1)
- {
- opts = QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba | QGL::DirectRendering
- | QGL::StencilBuffer | QGL::DeprecatedFunctions;
- pln = 0;
- depthSize = accumSize = stencilSize = redSize = greenSize = blueSize = alphaSize = -1;
- numSamples = -1;
- swapInterval = -1;
- majorVersion = 2;
- minorVersion = 0;
- profile = QGLFormat::NoProfile;
- }
- QGLFormatPrivate(const QGLFormatPrivate *other)
- : ref(1),
- opts(other->opts),
- pln(other->pln),
- depthSize(other->depthSize),
- accumSize(other->accumSize),
- stencilSize(other->stencilSize),
- redSize(other->redSize),
- greenSize(other->greenSize),
- blueSize(other->blueSize),
- alphaSize(other->alphaSize),
- numSamples(other->numSamples),
- swapInterval(other->swapInterval),
- majorVersion(other->majorVersion),
- minorVersion(other->minorVersion),
- profile(other->profile)
- {
- }
- QAtomicInt ref;
- QGL::FormatOptions opts;
- int pln;
- int depthSize;
- int accumSize;
- int stencilSize;
- int redSize;
- int greenSize;
- int blueSize;
- int alphaSize;
- int numSamples;
- int swapInterval;
- int majorVersion;
- int minorVersion;
- QGLFormat::OpenGLContextProfile profile;
-};
-
-class Q_OPENGL_EXPORT QGLWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QGLWidget)
-public:
- QGLWidgetPrivate() : QWidgetPrivate()
- , disable_clear_on_painter_begin(false)
- , parent_changing(false)
- {
- }
-
- ~QGLWidgetPrivate() {}
-
- void init(QGLContext *context, const QGLWidget* shareWidget);
- void initContext(QGLContext *context, const QGLWidget* shareWidget);
- bool renderCxPm(QPixmap *pixmap);
- void cleanupColormaps();
- void aboutToDestroy() override {
- if (glcx && !parent_changing)
- glcx->reset();
- }
-
- bool makeCurrent();
-
- QGLContext *glcx;
- QGLWidgetGLPaintDevice glDevice;
- bool autoSwap;
-
- QGLColormap cmap;
-
- bool disable_clear_on_painter_begin;
- bool parent_changing;
-};
-
-// QGLContextPrivate has the responsibility of creating context groups.
-// QGLContextPrivate maintains the reference counter and destroys
-// context groups when needed.
-class QGLContextGroup
-{
-public:
- ~QGLContextGroup();
-
- const QGLContext *context() const {return m_context;}
- bool isSharing() const { return m_shares.size() >= 2; }
- QList<const QGLContext *> shares() const { return m_shares; }
-
- static void addShare(const QGLContext *context, const QGLContext *share);
- static void removeShare(const QGLContext *context);
-
-private:
- QGLContextGroup(const QGLContext *context);
-
- const QGLContext *m_context; // context group's representative
- QList<const QGLContext *> m_shares;
- QAtomicInt m_refs;
-
- friend class QGLContext;
- friend class QGLContextPrivate;
- friend class QGLContextGroupResourceBase;
-};
-
-// Get the context that resources for "ctx" will transfer to once
-// "ctx" is destroyed. Returns null if nothing is sharing with ctx.
-const QGLContext *qt_gl_transfer_context(const QGLContext *);
-
-/*
- QGLTemporaryContext - the main objective of this class is to have a way of
- creating a GL context and making it current, without going via QGLWidget
- and friends. At certain points during GL initialization we need a current
- context in order decide what GL features are available, and to resolve GL
- extensions. Having a light-weight way of creating such a context saves
- initial application startup time, and it doesn't wind up creating recursive
- conflicts.
- The class currently uses a private d pointer to hide the platform specific
- types. This could possibly been done inline with #ifdef'ery, but it causes
- major headaches on e.g. X11 due to namespace pollution.
-*/
-class QGLTemporaryContextPrivate;
-class QGLTemporaryContext {
-public:
- explicit QGLTemporaryContext(bool directRendering = true, QWidget *parent = nullptr);
- ~QGLTemporaryContext();
-
-private:
- QScopedPointer<QGLTemporaryContextPrivate> d;
-};
-
-class QGLTexture;
-class QGLTextureDestroyer;
-
-// This probably needs to grow to GL_MAX_VERTEX_ATTRIBS, but 3 is ok for now as that's
-// all the GL2 engine uses:
-#define QT_GL_VERTEX_ARRAY_TRACKED_COUNT 3
-
-class QGLContextResourceBase;
-
-class QGLContextPrivate
-{
- Q_DECLARE_PUBLIC(QGLContext)
-public:
- explicit QGLContextPrivate(QGLContext *context);
- ~QGLContextPrivate();
- QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format,
- QGLContext::BindOptions options);
- QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format, const qint64 key,
- QGLContext::BindOptions options);
- QGLTexture *bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
- QGLContext::BindOptions options);
- QGLTexture *textureCacheLookup(const qint64 key, GLenum target);
- void init(QPaintDevice *dev, const QGLFormat &format);
- int maxTextureSize();
-
- void cleanup();
-
- void setVertexAttribArrayEnabled(int arrayIndex, bool enabled = true);
- void syncGlState(); // Makes sure the GL context's state is what we think it is
- void swapRegion(const QRegion &region);
-
- QOpenGLContext *guiGlContext;
- // true if QGLContext owns the QOpenGLContext (for who deletes who)
- bool ownContext;
-
- void setupSharing();
- void refreshCurrentFbo();
- void setCurrentFbo(GLuint fbo);
-
- QGLFormat glFormat;
- QGLFormat reqFormat;
- GLuint fbo;
-
- uint valid : 1;
- uint sharing : 1;
- uint initDone : 1;
- uint crWin : 1;
- uint internal_context : 1;
- uint version_flags_cached : 1;
-
- // workarounds for driver/hw bugs on different platforms
- uint workaround_needsFullClearOnEveryFrame : 1;
- uint workaround_brokenFBOReadBack : 1;
- uint workaround_brokenTexSubImage : 1;
- uint workaroundsCached : 1;
-
- uint workaround_brokenTextureFromPixmap : 1;
- uint workaround_brokenTextureFromPixmap_init : 1;
-
- uint workaround_brokenAlphaTexSubImage : 1;
- uint workaround_brokenAlphaTexSubImage_init : 1;
-
- QPaintDevice *paintDevice;
- QSize readback_target_size;
- QColor transpColor;
- QGLContext *q_ptr;
- QGLFormat::OpenGLVersionFlags version_flags;
-
- QGLContextGroup *group;
- GLint max_texture_size;
-
- GLuint current_fbo;
- GLuint default_fbo;
- QPaintEngine *active_engine;
- QGLTextureDestroyer *texture_destroyer;
-
- QGLFunctions *functions;
-
- bool vertexAttributeArraysEnabledState[QT_GL_VERTEX_ARRAY_TRACKED_COUNT];
-
- static inline QGLContextGroup *contextGroup(const QGLContext *ctx) { return ctx->d_ptr->group; }
-
- static void setCurrentContext(QGLContext *context);
-};
-
-// Temporarily make a context current if not already current or
-// shared with the current contex. The previous context is made
-// current when the object goes out of scope.
-class Q_OPENGL_EXPORT QGLShareContextScope
-{
-public:
- QGLShareContextScope(const QGLContext *ctx)
- : m_oldContext(nullptr)
- {
- QGLContext *currentContext = const_cast<QGLContext *>(QGLContext::currentContext());
- if (currentContext != ctx && !QGLContext::areSharing(ctx, currentContext)) {
- m_oldContext = currentContext;
- m_ctx = const_cast<QGLContext *>(ctx);
- m_ctx->makeCurrent();
- } else {
- m_ctx = currentContext;
- }
- }
-
- operator QGLContext *()
- {
- return m_ctx;
- }
-
- QGLContext *operator->()
- {
- return m_ctx;
- }
-
- ~QGLShareContextScope()
- {
- if (m_oldContext)
- m_oldContext->makeCurrent();
- }
-
-private:
- QGLContext *m_oldContext;
- QGLContext *m_ctx;
-};
-
-QT_END_NAMESPACE
-Q_DECLARE_METATYPE(GLuint)
-QT_BEGIN_NAMESPACE
-
-class Q_OPENGL_EXPORT QGLTextureDestroyer
-{
-public:
- void emitFreeTexture(QGLContext *context, QPlatformPixmap *, GLuint id) {
- if (context->contextHandle())
- (new QOpenGLSharedResourceGuard(context->contextHandle(), id, freeTextureFunc))->free();
- }
-
-private:
- static void freeTextureFunc(QOpenGLFunctions *, GLuint id) {
- QOpenGLContext::currentContext()->functions()->glDeleteTextures(1, &id);
- }
-};
-
-class Q_OPENGL_EXPORT QGLSignalProxy : public QObject
-{
- Q_OBJECT
-public:
- void emitAboutToDestroyContext(const QGLContext *context) {
- emit aboutToDestroyContext(context);
- }
- static QGLSignalProxy *instance();
-Q_SIGNALS:
- void aboutToDestroyContext(const QGLContext *context);
-};
-
-class QGLTexture {
-public:
- explicit QGLTexture(QGLContext *ctx = nullptr, GLuint tx_id = 0, GLenum tx_target = GL_TEXTURE_2D,
- QGLContext::BindOptions opt = QGLContext::DefaultBindOption)
- : context(ctx),
- id(tx_id),
- target(tx_target),
- options(opt)
- {}
-
- ~QGLTexture() {
- if (options & QGLContext::MemoryManagedBindOption) {
- Q_ASSERT(context);
- QPlatformPixmap *boundPixmap = nullptr;
- context->d_ptr->texture_destroyer->emitFreeTexture(context, boundPixmap, id);
- }
- }
-
- QGLContext *context;
- GLuint id;
- GLenum target;
-
- QGLContext::BindOptions options;
-
- bool canBindCompressedTexture
- (const char *buf, int len, const char *format, bool *hasAlpha);
- QSize bindCompressedTexture
- (const QString& fileName, const char *format = nullptr);
- QSize bindCompressedTexture
- (const char *buf, int len, const char *format = nullptr);
- QSize bindCompressedTextureDDS(const char *buf, int len);
- QSize bindCompressedTexturePVR(const char *buf, int len);
-};
-
-struct QGLTextureCacheKey {
- qint64 key;
- QGLContextGroup *group;
-};
-
-inline bool operator==(const QGLTextureCacheKey &a, const QGLTextureCacheKey &b)
-{
- return a.key == b.key && a.group == b.group;
-}
-
-inline uint qHash(const QGLTextureCacheKey &key)
-{
- return qHash(key.key) ^ qHash(key.group);
-}
-
-
-class Q_AUTOTEST_EXPORT QGLTextureCache {
-public:
- QGLTextureCache();
- ~QGLTextureCache();
-
- void insert(QGLContext *ctx, qint64 key, QGLTexture *texture, int cost);
- void remove(qint64 key);
- inline int size();
- inline void setMaxCost(int newMax);
- inline int maxCost();
- inline QGLTexture* getTexture(QGLContext *ctx, qint64 key);
-
- bool remove(QGLContext *ctx, GLuint textureId);
- void removeContextTextures(QGLContext *ctx);
- static QGLTextureCache *instance();
- static void cleanupTexturesForCacheKey(qint64 cacheKey);
- static void cleanupTexturesForPixampData(QPlatformPixmap* pixmap);
- static void cleanupBeforePixmapDestruction(QPlatformPixmap* pixmap);
-
-private:
- QCache<QGLTextureCacheKey, QGLTexture> m_cache;
- QReadWriteLock m_lock;
-};
-
-int QGLTextureCache::size() {
- QReadLocker locker(&m_lock);
- return m_cache.size();
-}
-
-void QGLTextureCache::setMaxCost(int newMax)
-{
- QWriteLocker locker(&m_lock);
- m_cache.setMaxCost(newMax);
-}
-
-int QGLTextureCache::maxCost()
-{
- QReadLocker locker(&m_lock);
- return m_cache.maxCost();
-}
-
-QGLTexture* QGLTextureCache::getTexture(QGLContext *ctx, qint64 key)
-{
- // Can't be a QReadLocker since QCache::object() modifies the cache (reprioritizes the object)
- QWriteLocker locker(&m_lock);
- const QGLTextureCacheKey cacheKey = {key, QGLContextPrivate::contextGroup(ctx)};
- return m_cache.object(cacheKey);
-}
-
-Q_OPENGL_EXPORT extern QPaintEngine* qt_qgl_paint_engine();
-
-QOpenGLExtensions* qgl_extensions();
-bool qgl_hasFeature(QOpenGLFunctions::OpenGLFeature feature);
-bool qgl_hasExtension(QOpenGLExtensions::OpenGLExtension extension);
-
-// Put a guard around a GL object identifier and its context.
-// When the context goes away, a shared context will be used
-// in its place. If there are no more shared contexts, then
-// the identifier is returned as zero - it is assumed that the
-// context destruction cleaned up the identifier in this case.
-class QGLSharedResourceGuardBase : public QOpenGLSharedResource
-{
-public:
- QGLSharedResourceGuardBase(QGLContext *context, GLuint id)
- : QOpenGLSharedResource(context->contextHandle()->shareGroup())
- , m_id(id)
- {
- }
-
- GLuint id() const
- {
- return m_id;
- }
-
-protected:
- void invalidateResource() override
- {
- m_id = 0;
- }
-
- void freeResource(QOpenGLContext *context) override
- {
- if (m_id) {
- freeResource(QGLContext::fromOpenGLContext(context), m_id);
- }
- }
-
- virtual void freeResource(QGLContext *ctx, GLuint id) = 0;
-
-private:
- GLuint m_id;
-};
-
-template <typename Func>
-class QGLSharedResourceGuard : public QGLSharedResourceGuardBase
-{
-public:
- QGLSharedResourceGuard(QGLContext *context, GLuint id, Func func)
- : QGLSharedResourceGuardBase(context, id)
- , m_func(func)
- {
- }
-
-protected:
- void freeResource(QGLContext *ctx, GLuint id) override
- {
- m_func(ctx, id);
- }
-
-private:
- Func m_func;
-};
-
-template <typename Func>
-QGLSharedResourceGuardBase *createSharedResourceGuard(QGLContext *context, GLuint id, Func cleanupFunc)
-{
- return new QGLSharedResourceGuard<Func>(context, id, cleanupFunc);
-}
-
-// this is a class that wraps a QThreadStorage object for storing
-// thread local instances of the GL 1 and GL 2 paint engines
-
-template <class T>
-class QGLEngineThreadStorage
-{
-public:
- QPaintEngine *engine() {
- QPaintEngine *&localEngine = storage.localData();
- if (!localEngine)
- localEngine = new T;
- return localEngine;
- }
-
-private:
- QThreadStorage<QPaintEngine *> storage;
-};
-QT_END_NAMESPACE
-
-#endif // QGL_P_H
diff --git a/src/opengl/qglbuffer.cpp b/src/opengl/qglbuffer.cpp
deleted file mode 100644
index bb9c2affbd..0000000000
--- a/src/opengl/qglbuffer.cpp
+++ /dev/null
@@ -1,568 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtOpenGL/qgl.h>
-#include <QtOpenGL/private/qgl_p.h>
-#include <private/qopenglextensions_p.h>
-#include <QtCore/qatomic.h>
-#include "qglbuffer.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGLBuffer
- \inmodule QtOpenGL
- \brief The QGLBuffer class provides functions for creating and managing GL buffer objects.
- \since 4.7
- \obsolete
- \ingroup painting-3D
-
- Buffer objects are created in the GL server so that the
- client application can avoid uploading vertices, indices,
- texture image data, etc every time they are needed.
-
- QGLBuffer objects can be copied around as a reference to the
- underlying GL buffer object:
-
- \snippet code/src_opengl_qglbuffer.cpp 0
-
- QGLBuffer performs a shallow copy when objects are copied in this
- manner, but does not implement copy-on-write semantics. The original
- object will be affected whenever the copy is modified.
-
- \note This class has been deprecated in favor of QOpenGLBuffer.
-*/
-
-/*!
- \enum QGLBuffer::Type
- This enum defines the type of GL buffer object to create with QGLBuffer.
-
- \value VertexBuffer Vertex buffer object for use when specifying
- vertex arrays.
- \value IndexBuffer Index buffer object for use with \c{glDrawElements()}.
- \value PixelPackBuffer Pixel pack buffer object for reading pixel
- data from the GL server (for example, with \c{glReadPixels()}).
- Not supported under OpenGL/ES.
- \value PixelUnpackBuffer Pixel unpack buffer object for writing pixel
- data to the GL server (for example, with \c{glTexImage2D()}).
- Not supported under OpenGL/ES.
-*/
-
-/*!
- \enum QGLBuffer::UsagePattern
- This enum defines the usage pattern of a QGLBuffer object.
-
- \value StreamDraw The data will be set once and used a few times
- for drawing operations. Under OpenGL/ES 1.1 this is identical
- to StaticDraw.
- \value StreamRead The data will be set once and used a few times
- for reading data back from the GL server. Not supported
- under OpenGL/ES.
- \value StreamCopy The data will be set once and used a few times
- for reading data back from the GL server for use in further
- drawing operations. Not supported under OpenGL/ES.
- \value StaticDraw The data will be set once and used many times
- for drawing operations.
- \value StaticRead The data will be set once and used many times
- for reading data back from the GL server. Not supported
- under OpenGL/ES.
- \value StaticCopy The data will be set once and used many times
- for reading data back from the GL server for use in further
- drawing operations. Not supported under OpenGL/ES.
- \value DynamicDraw The data will be modified repeatedly and used
- many times for drawing operations.
- \value DynamicRead The data will be modified repeatedly and used
- many times for reading data back from the GL server.
- Not supported under OpenGL/ES.
- \value DynamicCopy The data will be modified repeatedly and used
- many times for reading data back from the GL server for
- use in further drawing operations. Not supported under OpenGL/ES.
-*/
-
-/*!
- \enum QGLBuffer::Access
- This enum defines the access mode for QGLBuffer::map().
-
- \value ReadOnly The buffer will be mapped for reading only.
- \value WriteOnly The buffer will be mapped for writing only.
- \value ReadWrite The buffer will be mapped for reading and writing.
-*/
-
-class QGLBufferPrivate
-{
-public:
- QGLBufferPrivate(QGLBuffer::Type t)
- : ref(1),
- type(t),
- guard(0),
- usagePattern(QGLBuffer::StaticDraw),
- actualUsagePattern(QGLBuffer::StaticDraw),
- funcs(0)
- {
- }
-
- QAtomicInt ref;
- QGLBuffer::Type type;
- QGLSharedResourceGuardBase *guard;
- QGLBuffer::UsagePattern usagePattern;
- QGLBuffer::UsagePattern actualUsagePattern;
- QOpenGLExtensions *funcs;
-};
-
-/*!
- Constructs a new buffer object of type QGLBuffer::VertexBuffer.
-
- Note: this constructor just creates the QGLBuffer instance. The actual
- buffer object in the GL server is not created until create() is called.
-
- \sa create()
-*/
-QGLBuffer::QGLBuffer()
- : d_ptr(new QGLBufferPrivate(QGLBuffer::VertexBuffer))
-{
-}
-
-/*!
- Constructs a new buffer object of \a type.
-
- Note: this constructor just creates the QGLBuffer instance. The actual
- buffer object in the GL server is not created until create() is called.
-
- \sa create()
-*/
-QGLBuffer::QGLBuffer(QGLBuffer::Type type)
- : d_ptr(new QGLBufferPrivate(type))
-{
-}
-
-/*!
- Constructs a shallow copy of \a other.
-
- Note: QGLBuffer does not implement copy-on-write semantics,
- so \a other will be affected whenever the copy is modified.
-*/
-QGLBuffer::QGLBuffer(const QGLBuffer &other)
- : d_ptr(other.d_ptr)
-{
- d_ptr->ref.ref();
-}
-
-#define ctx QGLContext::currentContext();
-
-/*!
- Destroys this buffer object, including the storage being
- used in the GL server.
-*/
-QGLBuffer::~QGLBuffer()
-{
- if (!d_ptr->ref.deref()) {
- destroy();
- delete d_ptr;
- }
-}
-
-/*!
- Assigns a shallow copy of \a other to this object.
-
- Note: QGLBuffer does not implement copy-on-write semantics,
- so \a other will be affected whenever the copy is modified.
-*/
-QGLBuffer &QGLBuffer::operator=(const QGLBuffer &other)
-{
- if (d_ptr != other.d_ptr) {
- other.d_ptr->ref.ref();
- if (!d_ptr->ref.deref()) {
- destroy();
- delete d_ptr;
- }
- d_ptr = other.d_ptr;
- }
- return *this;
-}
-
-/*!
- Returns the type of buffer represented by this object.
-*/
-QGLBuffer::Type QGLBuffer::type() const
-{
- Q_D(const QGLBuffer);
- return d->type;
-}
-
-/*!
- Returns the usage pattern for this buffer object.
- The default value is StaticDraw.
-
- \sa setUsagePattern()
-*/
-QGLBuffer::UsagePattern QGLBuffer::usagePattern() const
-{
- Q_D(const QGLBuffer);
- return d->usagePattern;
-}
-
-/*!
- Sets the usage pattern for this buffer object to \a value.
- This function must be called before allocate() or write().
-
- \sa usagePattern(), allocate(), write()
-*/
-void QGLBuffer::setUsagePattern(QGLBuffer::UsagePattern value)
-{
- Q_D(QGLBuffer);
- d->usagePattern = d->actualUsagePattern = value;
-}
-
-#undef ctx
-
-namespace {
- void freeBufferFunc(QGLContext *ctx, GLuint id)
- {
- Q_ASSERT(ctx);
- ctx->contextHandle()->functions()->glDeleteBuffers(1, &id);
- }
-}
-
-/*!
- Creates the buffer object in the GL server. Returns \c true if
- the object was created; false otherwise.
-
- This function must be called with a current QGLContext.
- The buffer will be bound to and can only be used in
- that context (or any other context that is shared with it).
-
- This function will return false if the GL implementation
- does not support buffers, or there is no current QGLContext.
-
- \sa isCreated(), allocate(), write(), destroy()
-*/
-bool QGLBuffer::create()
-{
- Q_D(QGLBuffer);
- if (d->guard && d->guard->id())
- return true;
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
- if (ctx) {
- delete d->funcs;
- d->funcs = new QOpenGLExtensions(ctx->contextHandle());
- if (!d->funcs->hasOpenGLFeature(QOpenGLFunctions::Buffers))
- return false;
-
- GLuint bufferId = 0;
- d->funcs->glGenBuffers(1, &bufferId);
- if (bufferId) {
- if (d->guard)
- d->guard->free();
-
- d->guard = createSharedResourceGuard(ctx, bufferId, freeBufferFunc);
- return true;
- }
- }
- return false;
-}
-
-#define ctx QGLContext::currentContext()
-
-/*!
- Returns \c true if this buffer has been created; false otherwise.
-
- \sa create(), destroy()
-*/
-bool QGLBuffer::isCreated() const
-{
- Q_D(const QGLBuffer);
- return d->guard && d->guard->id();
-}
-
-/*!
- Destroys this buffer object, including the storage being
- used in the GL server. All references to the buffer will
- become invalid.
-*/
-void QGLBuffer::destroy()
-{
- Q_D(QGLBuffer);
- if (d->guard) {
- d->guard->free();
- d->guard = 0;
- }
-}
-
-/*!
- Reads the \a count bytes in this buffer starting at \a offset
- into \a data. Returns \c true on success; false if reading from
- the buffer is not supported. Buffer reading is not supported
- under OpenGL/ES.
-
- It is assumed that this buffer has been bound to the current context.
-
- \sa write(), bind()
-*/
-bool QGLBuffer::read(int offset, void *data, int count)
-{
-#if !defined(QT_OPENGL_ES)
- Q_D(QGLBuffer);
- if (!d->funcs->hasOpenGLFeature(QOpenGLFunctions::Buffers) || !d->guard->id() || !d->funcs->d()->GetBufferSubData)
- return false;
- while (d->funcs->glGetError() != GL_NO_ERROR) ; // Clear error state.
- d->funcs->glGetBufferSubData(d->type, offset, count, data);
- return d->funcs->glGetError() == GL_NO_ERROR;
-#else
- Q_UNUSED(offset);
- Q_UNUSED(data);
- Q_UNUSED(count);
- return false;
-#endif
-}
-
-/*!
- Replaces the \a count bytes of this buffer starting at \a offset
- with the contents of \a data. Any other bytes in the buffer
- will be left unmodified.
-
- It is assumed that create() has been called on this buffer and that
- it has been bound to the current context.
-
- \sa create(), read(), allocate()
-*/
-void QGLBuffer::write(int offset, const void *data, int count)
-{
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::allocate(): buffer not created");
-#endif
- Q_D(QGLBuffer);
- if (d->guard && d->guard->id())
- d->funcs->glBufferSubData(d->type, offset, count, data);
-}
-
-/*!
- Allocates \a count bytes of space to the buffer, initialized to
- the contents of \a data. Any previous contents will be removed.
-
- It is assumed that create() has been called on this buffer and that
- it has been bound to the current context.
-
- \sa create(), read(), write()
-*/
-void QGLBuffer::allocate(const void *data, int count)
-{
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::allocate(): buffer not created");
-#endif
- Q_D(QGLBuffer);
- if (d->guard && d->guard->id())
- d->funcs->glBufferData(d->type, count, data, d->actualUsagePattern);
-}
-
-/*!
- \fn void QGLBuffer::allocate(int count)
- \overload
-
- Allocates \a count bytes of space to the buffer. Any previous
- contents will be removed.
-
- It is assumed that create() has been called on this buffer and that
- it has been bound to the current context.
-
- \sa create(), write()
-*/
-
-/*!
- Binds the buffer associated with this object to the current
- GL context. Returns \c false if binding was not possible, usually because
- type() is not supported on this GL implementation.
-
- The buffer must be bound to the same QGLContext current when create()
- was called, or to another QGLContext that is sharing with it.
- Otherwise, false will be returned from this function.
-
- \sa release(), create()
-*/
-bool QGLBuffer::bind()
-{
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::bind(): buffer not created");
-#endif
- Q_D(const QGLBuffer);
- GLuint bufferId = d->guard ? d->guard->id() : 0;
- if (bufferId) {
- if (d->guard->group() != QOpenGLContextGroup::currentContextGroup()) {
-#ifndef QT_NO_DEBUG
- qWarning("QGLBuffer::bind: buffer is not valid in the current context");
-#endif
- return false;
- }
- d->funcs->glBindBuffer(d->type, bufferId);
- return true;
- } else {
- return false;
- }
-}
-
-/*!
- Releases the buffer associated with this object from the
- current GL context.
-
- This function must be called with the same QGLContext current
- as when bind() was called on the buffer.
-
- \sa bind()
-*/
-void QGLBuffer::release()
-{
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::release(): buffer not created");
-#endif
- Q_D(const QGLBuffer);
- if (d->guard && d->guard->id())
- d->funcs->glBindBuffer(d->type, 0);
-}
-
-#undef ctx
-
-/*!
- Releases the buffer associated with \a type in the current
- QGLContext.
-
- This function is a direct call to \c{glBindBuffer(type, 0)}
- for use when the caller does not know which QGLBuffer has
- been bound to the context but wants to make sure that it
- is released.
-
- \snippet code/src_opengl_qglbuffer.cpp 1
-*/
-void QGLBuffer::release(QGLBuffer::Type type)
-{
- if (QOpenGLContext *ctx = QOpenGLContext::currentContext())
- ctx->functions()->glBindBuffer(GLenum(type), 0);
-}
-
-#define ctx QGLContext::currentContext()
-
-/*!
- Returns the GL identifier associated with this buffer; zero if
- the buffer has not been created.
-
- \sa isCreated()
-*/
-GLuint QGLBuffer::bufferId() const
-{
- Q_D(const QGLBuffer);
- return d->guard ? d->guard->id() : 0;
-}
-
-#ifndef GL_BUFFER_SIZE
-#define GL_BUFFER_SIZE 0x8764
-#endif
-
-/*!
- Returns the size of the data in this buffer, for reading operations.
- Returns -1 if fetching the buffer size is not supported, or the
- buffer has not been created.
-
- It is assumed that this buffer has been bound to the current context.
-
- \sa isCreated(), bind()
-*/
-int QGLBuffer::size() const
-{
- Q_D(const QGLBuffer);
- if (!d->guard || !d->guard->id())
- return -1;
- GLint value = -1;
- d->funcs->glGetBufferParameteriv(d->type, GL_BUFFER_SIZE, &value);
- return value;
-}
-
-/*!
- Maps the contents of this buffer into the application's memory
- space and returns a pointer to it. Returns null if memory
- mapping is not possible. The \a access parameter indicates the
- type of access to be performed.
-
- It is assumed that create() has been called on this buffer and that
- it has been bound to the current context.
-
- This function is only supported under OpenGL/ES if the
- \c{GL_OES_mapbuffer} extension is present.
-
- \sa unmap(), create(), bind()
-*/
-void *QGLBuffer::map(QGLBuffer::Access access)
-{
- Q_D(QGLBuffer);
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::map(): buffer not created");
-#endif
- if (!d->guard || !d->guard->id())
- return 0;
- return d->funcs->glMapBuffer(d->type, access);
-}
-
-/*!
- Unmaps the buffer after it was mapped into the application's
- memory space with a previous call to map(). Returns \c true if
- the unmap succeeded; false otherwise.
-
- It is assumed that this buffer has been bound to the current context,
- and that it was previously mapped with map().
-
- This function is only supported under OpenGL/ES if the
- \c{GL_OES_mapbuffer} extension is present.
-
- \sa map()
-*/
-bool QGLBuffer::unmap()
-{
- Q_D(QGLBuffer);
-#ifndef QT_NO_DEBUG
- if (!isCreated())
- qWarning("QGLBuffer::unmap(): buffer not created");
-#endif
- if (!d->guard || !d->guard->id())
- return false;
- return d->funcs->glUnmapBuffer(d->type) == GL_TRUE;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglbuffer.h b/src/opengl/qglbuffer.h
deleted file mode 100644
index daf5227c66..0000000000
--- a/src/opengl/qglbuffer.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLBUFFER_H
-#define QGLBUFFER_H
-
-#include <QtCore/qscopedpointer.h>
-#include <QtOpenGL/qgl.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QGLBufferPrivate;
-
-class Q_OPENGL_EXPORT QGLBuffer
-{
-public:
- enum Type
- {
- VertexBuffer = 0x8892, // GL_ARRAY_BUFFER
- IndexBuffer = 0x8893, // GL_ELEMENT_ARRAY_BUFFER
- PixelPackBuffer = 0x88EB, // GL_PIXEL_PACK_BUFFER
- PixelUnpackBuffer = 0x88EC // GL_PIXEL_UNPACK_BUFFER
- };
-
- QGLBuffer();
- explicit QGLBuffer(QGLBuffer::Type type);
- QGLBuffer(const QGLBuffer &other);
- ~QGLBuffer();
-
- QGLBuffer &operator=(const QGLBuffer &other);
-
- enum UsagePattern
- {
- StreamDraw = 0x88E0, // GL_STREAM_DRAW
- StreamRead = 0x88E1, // GL_STREAM_READ
- StreamCopy = 0x88E2, // GL_STREAM_COPY
- StaticDraw = 0x88E4, // GL_STATIC_DRAW
- StaticRead = 0x88E5, // GL_STATIC_READ
- StaticCopy = 0x88E6, // GL_STATIC_COPY
- DynamicDraw = 0x88E8, // GL_DYNAMIC_DRAW
- DynamicRead = 0x88E9, // GL_DYNAMIC_READ
- DynamicCopy = 0x88EA // GL_DYNAMIC_COPY
- };
-
- enum Access
- {
- ReadOnly = 0x88B8, // GL_READ_ONLY
- WriteOnly = 0x88B9, // GL_WRITE_ONLY
- ReadWrite = 0x88BA // GL_READ_WRITE
- };
-
- QGLBuffer::Type type() const;
-
- QGLBuffer::UsagePattern usagePattern() const;
- void setUsagePattern(QGLBuffer::UsagePattern value);
-
- bool create();
- bool isCreated() const;
-
- void destroy();
-
- bool bind();
- void release();
-
- static void release(QGLBuffer::Type type);
-
- GLuint bufferId() const;
-
- int size() const;
-
- bool read(int offset, void *data, int count);
- void write(int offset, const void *data, int count);
-
- void allocate(const void *data, int count);
- inline void allocate(int count) { allocate(nullptr, count); }
-
- void *map(QGLBuffer::Access access);
- bool unmap();
-
-private:
- QGLBufferPrivate *d_ptr;
-
- Q_DECLARE_PRIVATE(QGLBuffer)
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/opengl/qglcolormap.cpp b/src/opengl/qglcolormap.cpp
deleted file mode 100644
index f314a9715d..0000000000
--- a/src/opengl/qglcolormap.cpp
+++ /dev/null
@@ -1,296 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \class QGLColormap
- \brief The QGLColormap class is used for installing custom colormaps into
- a QGLWidget.
-
- \obsolete
- \inmodule QtOpenGL
- \ingroup painting-3D
- \ingroup shared
-
- QGLColormap provides a platform independent way of specifying and
- installing indexed colormaps for a QGLWidget. QGLColormap is
- especially useful when using the OpenGL color-index mode.
-
- Under X11 you must use an X server that supports either a \c
- PseudoColor or \c DirectColor visual class. If your X server
- currently only provides a \c GrayScale, \c TrueColor, \c
- StaticColor or \c StaticGray visual, you will not be able to
- allocate colorcells for writing. If this is the case, try setting
- your X server to 8 bit mode. It should then provide you with at
- least a \c PseudoColor visual. Note that you may experience
- colormap flashing if your X server is running in 8 bit mode.
-
- The size() of the colormap is always set to 256
- colors. Note that under Windows you can also install colormaps
- in child widgets.
-
- This class uses \l{implicit sharing} as a memory and speed
- optimization.
-
- Example of use:
- \snippet code/src_opengl_qglcolormap.cpp 0
-
- \sa QGLWidget::setColormap(), QGLWidget::colormap()
-*/
-
-/*!
- \fn Qt::HANDLE QGLColormap::handle()
-
- \internal
-
- Returns the handle for this color map.
-*/
-
-/*!
- \fn void QGLColormap::setHandle(Qt::HANDLE handle)
-
- \internal
-
- Sets the handle for this color map to \a handle.
-*/
-
-#include "qglcolormap.h"
-
-QT_BEGIN_NAMESPACE
-
-QGLColormap::QGLColormapData QGLColormap::shared_null = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 };
-
-/*!
- Construct a QGLColormap.
-*/
-QGLColormap::QGLColormap()
- : d(&shared_null)
-{
- d->ref.ref();
-}
-
-
-/*!
- Construct a shallow copy of \a map.
-*/
-QGLColormap::QGLColormap(const QGLColormap &map)
- : d(map.d)
-{
- d->ref.ref();
-}
-
-/*!
- Dereferences the QGLColormap and deletes it if this was the last
- reference to it.
-*/
-QGLColormap::~QGLColormap()
-{
- if (!d->ref.deref())
- cleanup(d);
-}
-
-void QGLColormap::cleanup(QGLColormap::QGLColormapData *x)
-{
- delete x->cells;
- x->cells = 0;
- delete x;
-}
-
-/*!
- Assign a shallow copy of \a map to this QGLColormap.
-*/
-QGLColormap & QGLColormap::operator=(const QGLColormap &map)
-{
- map.d->ref.ref();
- if (!d->ref.deref())
- cleanup(d);
- d = map.d;
- return *this;
-}
-
-/*!
- \fn void QGLColormap::detach()
- \internal
-
- Detaches this QGLColormap from the shared block.
-*/
-
-void QGLColormap::detach_helper()
-{
- QGLColormapData *x = new QGLColormapData;
- x->ref.storeRelaxed(1);
- x->cmapHandle = 0;
- x->cells = 0;
- if (d->cells) {
- x->cells = new QVector<QRgb>(256);
- *x->cells = *d->cells;
- }
- if (!d->ref.deref())
- cleanup(d);
- d = x;
-}
-
-/*!
- Set cell at index \a idx in the colormap to color \a color.
-*/
-void QGLColormap::setEntry(int idx, QRgb color)
-{
- detach();
- if (!d->cells)
- d->cells = new QVector<QRgb>(256);
- d->cells->replace(idx, color);
-}
-
-/*!
- Set an array of cells in this colormap. \a count is the number of
- colors that should be set, \a colors is the array of colors, and
- \a base is the starting index. The first element in \a colors
- is set at \a base in the colormap.
-*/
-void QGLColormap::setEntries(int count, const QRgb *colors, int base)
-{
- detach();
- if (!d->cells)
- d->cells = new QVector<QRgb>(256);
-
- Q_ASSERT_X(colors && base >= 0 && (base + count) <= d->cells->size(), "QGLColormap::setEntries",
- "preconditions not met");
- for (int i = 0; i < count; ++i)
- setEntry(base + i, colors[i]);
-}
-
-/*!
- Returns the QRgb value in the colorcell with index \a idx.
-*/
-QRgb QGLColormap::entryRgb(int idx) const
-{
- if (d == &shared_null || !d->cells)
- return 0;
- else
- return d->cells->at(idx);
-}
-
-/*!
- \overload
-
- Set the cell with index \a idx in the colormap to color \a color.
-*/
-void QGLColormap::setEntry(int idx, const QColor &color)
-{
- setEntry(idx, color.rgb());
-}
-
-/*!
- Returns the QRgb value in the colorcell with index \a idx.
-*/
-QColor QGLColormap::entryColor(int idx) const
-{
- if (d == &shared_null || !d->cells)
- return QColor();
- else
- return QColor(d->cells->at(idx));
-}
-
-/*!
- Returns \c true if the colormap is empty or it is not in use
- by a QGLWidget; otherwise returns \c false.
-
- A colormap with no color values set is considered to be empty.
- For historical reasons, a colormap that has color values set
- but which is not in use by a QGLWidget is also considered empty.
-
- Compare size() with zero to determine if the colormap is empty
- regardless of whether it is in use by a QGLWidget or not.
-
- \sa size()
-*/
-bool QGLColormap::isEmpty() const
-{
- return d == &shared_null || d->cells == 0 || d->cells->size() == 0 || d->cmapHandle == 0;
-}
-
-
-/*!
- Returns the number of colorcells in the colormap.
-*/
-int QGLColormap::size() const
-{
- return d->cells ? d->cells->size() : 0;
-}
-
-/*!
- Returns the index of the color \a color. If \a color is not in the
- map, -1 is returned.
-*/
-int QGLColormap::find(QRgb color) const
-{
- if (d->cells)
- return d->cells->indexOf(color);
- return -1;
-}
-
-/*!
- Returns the index of the color that is the closest match to color
- \a color.
-*/
-int QGLColormap::findNearest(QRgb color) const
-{
- int idx = find(color);
- if (idx >= 0)
- return idx;
- int mapSize = size();
- int mindist = 200000;
- int r = qRed(color);
- int g = qGreen(color);
- int b = qBlue(color);
- int rx, gx, bx, dist;
- for (int i = 0; i < mapSize; ++i) {
- QRgb ci = d->cells->at(i);
- rx = r - qRed(ci);
- gx = g - qGreen(ci);
- bx = b - qBlue(ci);
- dist = rx * rx + gx * gx + bx * bx; // calculate distance
- if (dist < mindist) { // minimal?
- mindist = dist;
- idx = i;
- }
- }
- return idx;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglcolormap.h b/src/opengl/qglcolormap.h
deleted file mode 100644
index b59b56e040..0000000000
--- a/src/opengl/qglcolormap.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLCOLORMAP_H
-#define QGLCOLORMAP_H
-
-#include <QtGui/qcolor.h>
-#include <QtCore/qvector.h>
-#include <QtOpenGL/qtopenglglobal.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class Q_OPENGL_EXPORT QGLColormap
-{
-public:
- QGLColormap();
- QGLColormap(const QGLColormap &);
- ~QGLColormap();
-
- QGLColormap &operator=(const QGLColormap &);
-
- bool isEmpty() const;
- int size() const;
- void detach();
-
- void setEntries(int count, const QRgb * colors, int base = 0);
- void setEntry(int idx, QRgb color);
- void setEntry(int idx, const QColor & color);
- QRgb entryRgb(int idx) const;
- QColor entryColor(int idx) const;
- int find(QRgb color) const;
- int findNearest(QRgb color) const;
-
-protected:
- Qt::HANDLE handle() { return d ? d->cmapHandle : nullptr; }
- void setHandle(Qt::HANDLE ahandle) { d->cmapHandle = ahandle; }
-
-private:
- struct QGLColormapData {
- QBasicAtomicInt ref;
- QVector<QRgb> *cells;
- Qt::HANDLE cmapHandle;
- };
-
- QGLColormapData *d;
- static struct QGLColormapData shared_null;
- static void cleanup(QGLColormapData *x);
- void detach_helper();
-
- friend class QGLWidget;
- friend class QGLWidgetPrivate;
-};
-
-inline void QGLColormap::detach()
-{
- if (d->ref.loadRelaxed() != 1)
- detach_helper();
-}
-
-QT_END_NAMESPACE
-
-#endif // QGLCOLORMAP_H
diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp
deleted file mode 100644
index d0f82a85fa..0000000000
--- a/src/opengl/qglframebufferobject.cpp
+++ /dev/null
@@ -1,1466 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglframebufferobject.h"
-#include "qglframebufferobject_p.h"
-
-#include <qdebug.h>
-#include <private/qgl_p.h>
-#include <private/qfont_p.h>
-#include "gl2paintengineex/qpaintengineex_opengl2_p.h"
-
-#include <qimage.h>
-#include <qwindow.h>
-
-QT_BEGIN_NAMESPACE
-
-extern QImage qt_gl_read_frame_buffer(const QSize&, bool, bool);
-
-#define QGL_FUNC_CONTEXT const QGLContext *ctx = QGLContext::currentContext();
-#define QGL_FUNCP_CONTEXT const QGLContext *ctx = QGLContext::currentContext();
-
-#ifndef QT_NO_DEBUG
-#define QT_RESET_GLERROR() \
-{ \
- while (QOpenGLContext::currentContext()->functions()->glGetError() != GL_NO_ERROR) {} \
-}
-#define QT_CHECK_GLERROR() \
-{ \
- GLenum err = QOpenGLContext::currentContext()->functions()->glGetError(); \
- if (err != GL_NO_ERROR) { \
- qDebug("[%s line %d] GL Error: %d", \
- __FILE__, __LINE__, (int)err); \
- } \
-}
-#else
-#define QT_RESET_GLERROR() {}
-#define QT_CHECK_GLERROR() {}
-#endif
-
-// ####TODO Properly #ifdef this class to use #define symbols actually defined
-// by OpenGL/ES includes
-#ifndef GL_MAX_SAMPLES
-#define GL_MAX_SAMPLES 0x8D57
-#endif
-
-#ifndef GL_RENDERBUFFER_SAMPLES
-#define GL_RENDERBUFFER_SAMPLES 0x8CAB
-#endif
-
-#ifndef GL_DEPTH24_STENCIL8
-#define GL_DEPTH24_STENCIL8 0x88F0
-#endif
-
-#ifndef GL_DEPTH_COMPONENT24
-#define GL_DEPTH_COMPONENT24 0x81A6
-#endif
-
-#ifndef GL_DEPTH_COMPONENT24_OES
-#define GL_DEPTH_COMPONENT24_OES 0x81A6
-#endif
-
-#ifndef GL_READ_FRAMEBUFFER
-#define GL_READ_FRAMEBUFFER 0x8CA8
-#endif
-
-#ifndef GL_DRAW_FRAMEBUFFER
-#define GL_DRAW_FRAMEBUFFER 0x8CA9
-#endif
-
-#ifndef GL_DEPTH_STENCIL_ATTACHMENT
-#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
-#endif
-
-#ifndef GL_DEPTH_STENCIL
-#define GL_DEPTH_STENCIL 0x84F9
-#endif
-
-/*!
- \class QGLFramebufferObjectFormat
- \inmodule QtOpenGL
- \brief The QGLFramebufferObjectFormat class specifies the format of an OpenGL
- framebuffer object.
-
- \since 4.6
- \obsolete
-
- \ingroup painting-3D
-
- A framebuffer object has several characteristics:
- \list
- \li \l{setSamples()}{Number of samples per pixels.}
- \li \l{setAttachment()}{Depth and/or stencil attachments.}
- \li \l{setTextureTarget()}{Texture target.}
- \li \l{setInternalTextureFormat()}{Internal texture format.}
- \endlist
-
- Note that the desired attachments or number of samples per pixels might not
- be supported by the hardware driver. Call QGLFramebufferObject::format()
- after creating a QGLFramebufferObject to find the exact format that was
- used to create the frame buffer object.
-
- \note This class has been deprecated in favor of QOpenGLFramebufferObjectFormat.
-
- \sa QGLFramebufferObject
-*/
-
-/*!
- \internal
-*/
-void QGLFramebufferObjectFormat::detach()
-{
- if (d->ref.loadRelaxed() != 1) {
- QGLFramebufferObjectFormatPrivate *newd
- = new QGLFramebufferObjectFormatPrivate(d);
- if (!d->ref.deref())
- delete d;
- d = newd;
- }
-}
-
-/*!
- Creates a QGLFramebufferObjectFormat object for specifying
- 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.
- On OpenGL/ES systems, the default internal format is \c GL_RGBA.
-
- \sa samples(), attachment(), internalTextureFormat()
-*/
-
-QGLFramebufferObjectFormat::QGLFramebufferObjectFormat()
-{
- d = new QGLFramebufferObjectFormatPrivate;
-}
-
-/*!
- Constructs a copy of \a other.
-*/
-
-QGLFramebufferObjectFormat::QGLFramebufferObjectFormat(const QGLFramebufferObjectFormat &other)
-{
- d = other.d;
- d->ref.ref();
-}
-
-/*!
- Assigns \a other to this object.
-*/
-
-QGLFramebufferObjectFormat &QGLFramebufferObjectFormat::operator=(const QGLFramebufferObjectFormat &other)
-{
- if (d != other.d) {
- other.d->ref.ref();
- if (!d->ref.deref())
- delete d;
- d = other.d;
- }
- return *this;
-}
-
-/*!
- Destroys the QGLFramebufferObjectFormat.
-*/
-QGLFramebufferObjectFormat::~QGLFramebufferObjectFormat()
-{
- if (!d->ref.deref())
- delete d;
-}
-
-/*!
- Sets the number of samples per pixel for a multisample framebuffer object
- to \a samples. The default sample count of 0 represents a regular
- non-multisample framebuffer object.
-
- If the desired amount of samples per pixel is not supported by the hardware
- then the maximum number of samples per pixel will be used. Note that
- multisample framebuffer objects cannot be bound as textures. Also, the
- \c{GL_EXT_framebuffer_multisample} extension is required to create a
- framebuffer with more than one sample per pixel.
-
- \sa samples()
-*/
-void QGLFramebufferObjectFormat::setSamples(int samples)
-{
- detach();
- d->samples = samples;
-}
-
-/*!
- Returns the number of samples per pixel if a framebuffer object
- is a multisample framebuffer object. Otherwise, returns 0.
- The default value is 0.
-
- \sa setSamples()
-*/
-int QGLFramebufferObjectFormat::samples() const
-{
- return d->samples;
-}
-
-/*!
- \since 4.8
-
- Enables mipmapping if \a enabled is true; otherwise disables it.
-
- Mipmapping is disabled by default.
-
- If mipmapping is enabled, additional memory will be allocated for
- the mipmap levels. The mipmap levels can be updated by binding the
- texture and calling glGenerateMipmap(). Mipmapping cannot be enabled
- for multisampled framebuffer objects.
-
- \sa mipmap(), QGLFramebufferObject::texture()
-*/
-void QGLFramebufferObjectFormat::setMipmap(bool enabled)
-{
- detach();
- d->mipmap = enabled;
-}
-
-/*!
- \since 4.8
-
- Returns \c true if mipmapping is enabled.
-
- \sa setMipmap()
-*/
-bool QGLFramebufferObjectFormat::mipmap() const
-{
- return d->mipmap;
-}
-
-/*!
- Sets the attachment configuration of a framebuffer object to \a attachment.
-
- \sa attachment()
-*/
-void QGLFramebufferObjectFormat::setAttachment(QGLFramebufferObject::Attachment attachment)
-{
- detach();
- d->attachment = attachment;
-}
-
-/*!
- Returns the configuration of the depth and stencil buffers attached to
- a framebuffer object. The default is QGLFramebufferObject::NoAttachment.
-
- \sa setAttachment()
-*/
-QGLFramebufferObject::Attachment QGLFramebufferObjectFormat::attachment() const
-{
- return d->attachment;
-}
-
-/*!
- Sets the texture target of the texture attached to a framebuffer object to
- \a target. Ignored for multisample framebuffer objects.
-
- \sa textureTarget(), samples()
-*/
-void QGLFramebufferObjectFormat::setTextureTarget(GLenum target)
-{
- detach();
- d->target = target;
-}
-
-/*!
- Returns the texture target of the texture attached to a framebuffer object.
- Ignored for multisample framebuffer objects. The default is
- \c GL_TEXTURE_2D.
-
- \sa setTextureTarget(), samples()
-*/
-GLenum QGLFramebufferObjectFormat::textureTarget() const
-{
- return d->target;
-}
-
-/*!
- Sets the internal format of a framebuffer object's texture or
- multisample framebuffer object's color buffer to
- \a internalTextureFormat.
-
- \sa internalTextureFormat()
-*/
-void QGLFramebufferObjectFormat::setInternalTextureFormat(GLenum internalTextureFormat)
-{
- detach();
- d->internal_format = internalTextureFormat;
-}
-
-/*!
- Returns the internal format of a framebuffer object's texture or
- multisample framebuffer object's color buffer. The default is
- \c GL_RGBA8 on desktop OpenGL systems, and \c GL_RGBA on
- OpenGL/ES systems.
-
- \sa setInternalTextureFormat()
-*/
-GLenum QGLFramebufferObjectFormat::internalTextureFormat() const
-{
- return d->internal_format;
-}
-
-/*!
- Returns \c true if all the options of this framebuffer object format
- are the same as \a other; otherwise returns \c false.
-*/
-bool QGLFramebufferObjectFormat::operator==(const QGLFramebufferObjectFormat& other) const
-{
- if (d == other.d)
- return true;
- else
- return d->equals(other.d);
-}
-
-/*!
- Returns \c false if all the options of this framebuffer object format
- are the same as \a other; otherwise returns \c true.
-*/
-bool QGLFramebufferObjectFormat::operator!=(const QGLFramebufferObjectFormat& other) const
-{
- return !(*this == other);
-}
-
-void QGLFBOGLPaintDevice::setFBO(QGLFramebufferObject* f,
- QGLFramebufferObject::Attachment attachment)
-{
- fbo = f;
- m_thisFBO = fbo->d_func()->fbo(); // This shouldn't be needed
-
- // The context that the fbo was created in may not have depth
- // and stencil buffers, but the fbo itself might.
- fboFormat = QGLContext::currentContext()->format();
- if (attachment == QGLFramebufferObject::CombinedDepthStencil) {
- fboFormat.setDepth(true);
- fboFormat.setStencil(true);
- } else if (attachment == QGLFramebufferObject::Depth) {
- fboFormat.setDepth(true);
- fboFormat.setStencil(false);
- } else {
- fboFormat.setDepth(false);
- fboFormat.setStencil(false);
- }
-
- GLenum format = f->format().internalTextureFormat();
- reqAlpha = (format != GL_RGB
-#ifdef GL_RGB5
- && format != GL_RGB5
-#endif
-#ifdef GL_RGB8
- && format != GL_RGB8
-#endif
- );
-}
-
-QGLContext *QGLFBOGLPaintDevice::context() const
-{
- return const_cast<QGLContext *>(QGLContext::currentContext());
-}
-
-bool QGLFramebufferObjectPrivate::checkFramebufferStatus() const
-{
- QGL_FUNCP_CONTEXT;
- if (!ctx)
- return false; // Context no longer exists.
- GLenum status = ctx->contextHandle()->functions()->glCheckFramebufferStatus(GL_FRAMEBUFFER);
- switch(status) {
- case GL_NO_ERROR:
- case GL_FRAMEBUFFER_COMPLETE:
- return true;
- case GL_FRAMEBUFFER_UNSUPPORTED:
- qDebug("QGLFramebufferObject: Unsupported framebuffer format.");
- break;
- case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
- qDebug("QGLFramebufferObject: Framebuffer incomplete attachment.");
- break;
- case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, missing attachment.");
- break;
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT
- case GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, duplicate attachment.");
- break;
-#endif
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS
- case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, attached images must have same dimensions.");
- break;
-#endif
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_FORMATS
- case GL_FRAMEBUFFER_INCOMPLETE_FORMATS:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, attached images must have same format.");
- break;
-#endif
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER
- case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, missing draw buffer.");
- break;
-#endif
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER
- case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, missing read buffer.");
- break;
-#endif
-#ifdef GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE
- case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
- qDebug("QGLFramebufferObject: Framebuffer incomplete, attachments must have same number of samples per pixel.");
- break;
-#endif
- default:
- qDebug() <<"QGLFramebufferObject: An undefined error has occurred: "<< status;
- break;
- }
- return false;
-}
-
-namespace
-{
- void freeFramebufferFunc(QGLContext *ctx, GLuint id)
- {
- Q_ASSERT(ctx);
- ctx->contextHandle()->functions()->glDeleteFramebuffers(1, &id);
- }
-
- void freeRenderbufferFunc(QGLContext *ctx, GLuint id)
- {
- Q_ASSERT(ctx);
- ctx->contextHandle()->functions()->glDeleteRenderbuffers(1, &id);
- }
-
- void freeTextureFunc(QGLContext *ctx, GLuint id)
- {
- Q_UNUSED(ctx);
- ctx->contextHandle()->functions()->glDeleteTextures(1, &id);
- }
-}
-
-void QGLFramebufferObjectPrivate::init(QGLFramebufferObject *q, const QSize &sz,
- QGLFramebufferObject::Attachment attachment,
- GLenum texture_target, GLenum internal_format,
- GLint samples, bool mipmap)
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
-
- funcs.initializeOpenGLFunctions();
-
- if (!funcs.hasOpenGLFeature(QOpenGLFunctions::Framebuffers))
- return;
-
- ctx->d_ptr->refreshCurrentFbo();
-
- size = sz;
- target = texture_target;
- // texture dimensions
-
- QT_RESET_GLERROR(); // reset error state
- GLuint fbo = 0;
- funcs.glGenFramebuffers(1, &fbo);
- funcs.glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-
- GLuint texture = 0;
- GLuint color_buffer = 0;
- GLuint depth_buffer = 0;
- GLuint stencil_buffer = 0;
-
- QT_CHECK_GLERROR();
- // init texture
- if (samples == 0) {
- funcs.glGenTextures(1, &texture);
- funcs.glBindTexture(target, texture);
- funcs.glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0,
- GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- if (mipmap) {
- int width = size.width();
- int height = 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,
- GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- }
- }
- funcs.glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- funcs.glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs.glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- funcs.glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- funcs.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- target, texture, 0);
-
- QT_CHECK_GLERROR();
- valid = checkFramebufferStatus();
- funcs.glBindTexture(target, 0);
-
- color_buffer = 0;
- } else {
- mipmap = false;
- GLint maxSamples;
- funcs.glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
-
- samples = qBound(0, int(samples), int(maxSamples));
-
- funcs.glGenRenderbuffers(1, &color_buffer);
- funcs.glBindRenderbuffer(GL_RENDERBUFFER, color_buffer);
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample) && samples > 0) {
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- internal_format, size.width(), size.height());
- } else {
- samples = 0;
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, internal_format,
- size.width(), size.height());
- }
-
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_RENDERBUFFER, color_buffer);
-
- QT_CHECK_GLERROR();
- valid = checkFramebufferStatus();
-
- if (valid)
- funcs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
- }
-
- // In practice, a combined depth-stencil buffer is supported by all desktop platforms, while a
- // separate stencil buffer is not. On embedded devices however, a combined depth-stencil buffer
- // might not be supported while separate buffers are, according to QTBUG-12861.
-
- if (attachment == QGLFramebufferObject::CombinedDepthStencil
- && funcs.hasOpenGLExtension(QOpenGLExtensions::PackedDepthStencil)) {
- // depth and stencil buffer needs another extension
- funcs.glGenRenderbuffers(1, &depth_buffer);
- funcs.glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer);
- Q_ASSERT(funcs.glIsRenderbuffer(depth_buffer));
-#ifndef Q_OS_WASM
- if (samples != 0 && funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample))
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH24_STENCIL8, size.width(), size.height());
- else
- funcs.glRenderbufferStorage(GL_RENDERBUFFER,
- GL_DEPTH24_STENCIL8, size.width(), size.height());
-
- stencil_buffer = depth_buffer;
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_RENDERBUFFER, depth_buffer);
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
- GL_RENDERBUFFER, stencil_buffer);
-#else
- // webgl does not allow separate depth and stencil attachments
- if (samples != 0) {
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_STENCIL, size.width(), size.height());
- } else {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL,
- size.width(), size.height());
- }
- stencil_buffer = depth_buffer;
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
- GL_RENDERBUFFER, depth_buffer);
-#endif
-
- valid = checkFramebufferStatus();
- if (!valid) {
- funcs.glDeleteRenderbuffers(1, &depth_buffer);
- stencil_buffer = depth_buffer = 0;
- }
- }
-
- if (depth_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil
- || (attachment == QGLFramebufferObject::Depth)))
- {
- funcs.glGenRenderbuffers(1, &depth_buffer);
- funcs.glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer);
- Q_ASSERT(funcs.glIsRenderbuffer(depth_buffer));
- if (samples != 0 && funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample)) {
-#ifdef QT_OPENGL_ES
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24)) {
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT24_OES, size.width(), size.height());
- } else {
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT16, size.width(), size.height());
- }
-#else
- if (ctx->contextHandle()->isOpenGLES()) {
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24))
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT24, size.width(), size.height());
- else
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT16, size.width(), size.height());
- } else {
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
- GL_DEPTH_COMPONENT, size.width(), size.height());
- }
-#endif
- } else {
-#ifdef QT_OPENGL_ES
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24)) {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24_OES,
- size.width(), size.height());
- } else {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16,
- size.width(), size.height());
- }
-#else
- if (ctx->contextHandle()->isOpenGLES()) {
- if (funcs.hasOpenGLExtension(QOpenGLExtensions::Depth24)) {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24,
- size.width(), size.height());
- } else {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16,
- size.width(), size.height());
- }
- } else {
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, size.width(), size.height());
- }
-#endif
- }
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_RENDERBUFFER, depth_buffer);
- valid = checkFramebufferStatus();
- if (!valid) {
- funcs.glDeleteRenderbuffers(1, &depth_buffer);
- depth_buffer = 0;
- }
- }
-
- if (stencil_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil)) {
- funcs.glGenRenderbuffers(1, &stencil_buffer);
- funcs.glBindRenderbuffer(GL_RENDERBUFFER, stencil_buffer);
- Q_ASSERT(funcs.glIsRenderbuffer(stencil_buffer));
-
-#ifdef QT_OPENGL_ES
- GLenum storage = GL_STENCIL_INDEX8;
-#else
- GLenum storage = ctx->contextHandle()->isOpenGLES() ? GL_STENCIL_INDEX8 : GL_STENCIL_INDEX;
-#endif
-
- if (samples != 0 && funcs.hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample))
- funcs.glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, storage, size.width(), size.height());
- else
- funcs.glRenderbufferStorage(GL_RENDERBUFFER, storage, size.width(), size.height());
-
- funcs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
- GL_RENDERBUFFER, stencil_buffer);
- valid = checkFramebufferStatus();
- if (!valid) {
- funcs.glDeleteRenderbuffers(1, &stencil_buffer);
- stencil_buffer = 0;
- }
- }
-
- // The FBO might have become valid after removing the depth or stencil buffer.
- valid = checkFramebufferStatus();
-
- if (depth_buffer && stencil_buffer) {
- fbo_attachment = QGLFramebufferObject::CombinedDepthStencil;
- } else if (depth_buffer) {
- fbo_attachment = QGLFramebufferObject::Depth;
- } else {
- fbo_attachment = QGLFramebufferObject::NoAttachment;
- }
-
- funcs.glBindFramebuffer(GL_FRAMEBUFFER, ctx->d_ptr->current_fbo);
- if (valid) {
- fbo_guard = createSharedResourceGuard(ctx, fbo, freeFramebufferFunc);
- if (color_buffer)
- color_buffer_guard = createSharedResourceGuard(ctx, color_buffer, freeRenderbufferFunc);
- else
- texture_guard = createSharedResourceGuard(ctx, texture, freeTextureFunc);
- if (depth_buffer)
- depth_buffer_guard = createSharedResourceGuard(ctx, depth_buffer, freeRenderbufferFunc);
- if (stencil_buffer) {
- if (stencil_buffer == depth_buffer)
- stencil_buffer_guard = depth_buffer_guard;
- else
- stencil_buffer_guard = createSharedResourceGuard(ctx, stencil_buffer, freeRenderbufferFunc);
- }
- } else {
- if (color_buffer)
- funcs.glDeleteRenderbuffers(1, &color_buffer);
- else
- funcs.glDeleteTextures(1, &texture);
- if (depth_buffer)
- funcs.glDeleteRenderbuffers(1, &depth_buffer);
- if (stencil_buffer && depth_buffer != stencil_buffer)
- funcs.glDeleteRenderbuffers(1, &stencil_buffer);
- funcs.glDeleteFramebuffers(1, &fbo);
- }
- QT_CHECK_GLERROR();
-
- format.setTextureTarget(target);
- format.setSamples(int(samples));
- format.setAttachment(fbo_attachment);
- format.setInternalTextureFormat(internal_format);
- format.setMipmap(mipmap);
-
- glDevice.setFBO(q, attachment);
-}
-
-/*!
- \class QGLFramebufferObject
- \inmodule QtOpenGL
- \brief The QGLFramebufferObject class encapsulates an OpenGL framebuffer object.
- \since 4.2
-
- \obsolete
-
- \ingroup painting-3D
-
- The QGLFramebufferObject class encapsulates an OpenGL framebuffer
- object, defined by the \c{GL_EXT_framebuffer_object} extension. In
- addition it provides a rendering surface that can be painted on
- with a QPainter, rendered to using native GL calls, or both. This
- surface can be bound and used as a regular texture in your own GL
- drawing code. By default, the QGLFramebufferObject class
- generates a 2D GL texture (using the \c{GL_TEXTURE_2D} target),
- which is used as the internal rendering target.
-
- \b{It is important to have a current GL context when creating a
- QGLFramebufferObject, otherwise initialization will fail.}
-
- OpenGL framebuffer objects and pbuffers (see
- \l{QGLPixelBuffer}{QGLPixelBuffer}) can both be used to render to
- offscreen surfaces, but there are a number of advantages with
- using framebuffer objects instead of pbuffers:
-
- \list 1
- \li A framebuffer object does not require a separate rendering
- context, so no context switching will occur when switching
- rendering targets. There is an overhead involved in switching
- targets, but in general it is cheaper than a context switch to a
- pbuffer.
-
- \li Rendering to dynamic textures (i.e. render-to-texture
- functionality) works on all platforms. No need to do explicit copy
- calls from a render buffer into a texture, as was necessary on
- systems that did not support the \c{render_texture} extension.
-
- \li It is possible to attach several rendering buffers (or texture
- objects) to the same framebuffer object, and render to all of them
- without doing a context switch.
-
- \li The OpenGL framebuffer extension is a pure GL extension with no
- system dependant WGL, CGL, or GLX parts. This makes using
- framebuffer objects more portable.
- \endlist
-
- When using a QPainter to paint to a QGLFramebufferObject you should take
- care that the QGLFramebufferObject is created with the CombinedDepthStencil
- attachment for QPainter to be able to render correctly.
- Note that you need to create a QGLFramebufferObject with more than one
- sample per pixel for primitives to be antialiased when drawing using a
- QPainter. To create a multisample framebuffer object you should use one of
- the constructors that take a QGLFramebufferObjectFormat parameter, and set
- the QGLFramebufferObjectFormat::samples() property to a non-zero value.
-
- When painting to a QGLFramebufferObject using QPainter, the state of
- the current GL context will be altered by the paint engine to reflect
- its needs. Applications should not rely upon the GL state being reset
- to its original conditions, particularly the current shader program,
- GL viewport, texture units, and drawing modes.
-
- For multisample framebuffer objects a color render buffer is created,
- otherwise a texture with the specified texture target is created.
- The color render buffer or texture will have the specified internal
- format, and will be bound to the \c GL_COLOR_ATTACHMENT0
- attachment in the framebuffer object.
-
- 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 QGLContext::blitFramebuffer().
-
- \section1 Threading
-
- As of Qt 4.8, it's possible to draw into a QGLFramebufferObject
- using a QPainter in a separate thread. Note that OpenGL 2.0 or
- OpenGL ES 2.0 is required for this to work.
-
- \note This class has been deprecated in favor of QOpenGLFramebufferObject.
-*/
-
-
-/*!
- \enum QGLFramebufferObject::Attachment
- \since 4.3
-
- This enum type is used to configure the depth and stencil buffers
- attached to the framebuffer object when it is created.
-
- \value NoAttachment No attachment is added to the framebuffer object. Note that the
- OpenGL depth and stencil tests won't work when rendering to a
- framebuffer object without any depth or stencil buffers.
- This is the default value.
-
- \value CombinedDepthStencil If the \c GL_EXT_packed_depth_stencil extension is present,
- a combined depth and stencil buffer is attached.
- If the extension is not present, only a depth buffer is attached.
-
- \value Depth A depth buffer is attached to the framebuffer object.
-
- \sa attachment()
-*/
-
-
-/*! \fn QGLFramebufferObject::QGLFramebufferObject(const QSize &size, GLenum target)
-
- Constructs an OpenGL framebuffer object and binds a 2D GL texture
- to the buffer of the size \a size. The texture is bound to the
- \c GL_COLOR_ATTACHMENT0 target in the framebuffer object.
-
- The \a target parameter is used to specify the GL texture
- target. The default target is \c GL_TEXTURE_2D. Keep in mind that
- \c GL_TEXTURE_2D textures must have a power of 2 width and height
- (e.g. 256x512), unless you are using OpenGL 2.0 or higher.
-
- By default, no depth and stencil buffers are attached. This behavior
- can be toggled using one of the overloaded constructors.
-
- The default internal texture format is \c GL_RGBA8 for desktop
- OpenGL, and \c GL_RGBA for OpenGL/ES.
-
- It is important that you have a current GL context set when
- creating the QGLFramebufferObject, otherwise the initialization
- will fail.
-
- \sa size(), texture(), attachment()
-*/
-
-QGLFramebufferObject::QGLFramebufferObject(const QSize &size, GLenum target)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- d->init(this, size, NoAttachment, target,
-#ifndef QT_OPENGL_ES_2
- QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8
-#else
- GL_RGBA
-#endif
- );
-}
-
-/*! \overload
-
- Constructs an OpenGL framebuffer object and binds a 2D GL texture
- to the buffer of the given \a width and \a height.
-
- \sa size(), texture()
-*/
-QGLFramebufferObject::QGLFramebufferObject(int width, int height, GLenum target)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- d->init(this, QSize(width, height), NoAttachment, target,
-#ifndef QT_OPENGL_ES_2
- QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8
-#else
- GL_RGBA
-#endif
- );
-}
-
-/*! \overload
-
- Constructs an OpenGL framebuffer object of the given \a size based on the
- supplied \a format.
-*/
-
-QGLFramebufferObject::QGLFramebufferObject(const QSize &size, const QGLFramebufferObjectFormat &format)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- d->init(this, size, format.attachment(), format.textureTarget(), format.internalTextureFormat(),
- format.samples(), format.mipmap());
-}
-
-/*! \overload
-
- Constructs an OpenGL framebuffer object of the given \a width and \a height
- based on the supplied \a format.
-*/
-
-QGLFramebufferObject::QGLFramebufferObject(int width, int height, const QGLFramebufferObjectFormat &format)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- d->init(this, QSize(width, height), format.attachment(), format.textureTarget(),
- format.internalTextureFormat(), format.samples(), format.mipmap());
-}
-
-/*! \overload
-
- Constructs an OpenGL framebuffer object and binds a texture to the
- 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
- 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.
-
- \sa size(), texture(), attachment()
-*/
-QGLFramebufferObject::QGLFramebufferObject(int width, int height, Attachment attachment,
- GLenum target, GLenum internal_format)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- 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);
-}
-
-/*! \overload
-
- Constructs an OpenGL framebuffer object and binds a texture to the
- 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
- 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.
-
- \sa size(), texture(), attachment()
-*/
-QGLFramebufferObject::QGLFramebufferObject(const QSize &size, Attachment attachment,
- GLenum target, GLenum internal_format)
- : d_ptr(new QGLFramebufferObjectPrivate)
-{
- Q_D(QGLFramebufferObject);
- 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);
-}
-
-/*!
- \fn QGLFramebufferObject::~QGLFramebufferObject()
-
- Destroys the framebuffer object and frees any allocated resources.
-*/
-QGLFramebufferObject::~QGLFramebufferObject()
-{
- Q_D(QGLFramebufferObject);
-
- delete d->engine;
-
- if (d->texture_guard)
- d->texture_guard->free();
- if (d->color_buffer_guard)
- d->color_buffer_guard->free();
- if (d->depth_buffer_guard)
- d->depth_buffer_guard->free();
- if (d->stencil_buffer_guard && d->stencil_buffer_guard != d->depth_buffer_guard)
- d->stencil_buffer_guard->free();
- if (d->fbo_guard)
- d->fbo_guard->free();
-}
-
-/*!
- \fn bool QGLFramebufferObject::isValid() const
-
- Returns \c true if the framebuffer object is valid.
-
- The framebuffer can become invalid if the initialization process
- fails, the user attaches an invalid buffer to the framebuffer
- object, or a non-power of two width/height is specified as the
- texture size if the texture target is \c{GL_TEXTURE_2D}.
- The non-power of two limitation does not apply if the OpenGL version
- is 2.0 or higher, or if the GL_ARB_texture_non_power_of_two extension
- is present.
-
- The framebuffer can also become invalid if the QGLContext that
- the framebuffer was created within is destroyed and there are
- no other shared contexts that can take over ownership of the
- framebuffer.
-*/
-bool QGLFramebufferObject::isValid() const
-{
- Q_D(const QGLFramebufferObject);
- return d->valid && d->fbo_guard && d->fbo_guard->id();
-}
-
-/*!
- \fn bool QGLFramebufferObject::bind()
-
- Switches rendering from the default, windowing system provided
- framebuffer to this framebuffer object.
- Returns \c true upon success, false otherwise.
-
- \sa release()
-*/
-bool QGLFramebufferObject::bind()
-{
- if (!isValid())
- return false;
- Q_D(QGLFramebufferObject);
- QGL_FUNC_CONTEXT;
- if (!ctx)
- return false; // Context no longer exists.
- const QGLContext *current = QGLContext::currentContext();
-#ifdef QT_DEBUG
- if (!current ||
- QGLContextPrivate::contextGroup(current) != QGLContextPrivate::contextGroup(ctx))
- {
- qWarning("QGLFramebufferObject::bind() called from incompatible context");
- }
-#endif
- d->funcs.glBindFramebuffer(GL_FRAMEBUFFER, d->fbo());
- d->valid = d->checkFramebufferStatus();
- if (d->valid && current)
- current->d_ptr->setCurrentFbo(d->fbo());
- return d->valid;
-}
-
-/*!
- \fn bool QGLFramebufferObject::release()
-
- Switches rendering back to the default, windowing system provided
- framebuffer.
- Returns \c true upon success, false otherwise.
-
- \sa bind()
-*/
-bool QGLFramebufferObject::release()
-{
- if (!isValid())
- return false;
- Q_D(QGLFramebufferObject);
- QGL_FUNC_CONTEXT;
- if (!ctx)
- return false; // Context no longer exists.
-
- const QGLContext *current = QGLContext::currentContext();
-
-#ifdef QT_DEBUG
- if (!current ||
- QGLContextPrivate::contextGroup(current) != QGLContextPrivate::contextGroup(ctx))
- {
- qWarning("QGLFramebufferObject::release() called from incompatible context");
- }
-#endif
-
- if (current) {
- current->d_ptr->setCurrentFbo(current->d_ptr->default_fbo);
- d->funcs.glBindFramebuffer(GL_FRAMEBUFFER, current->d_ptr->default_fbo);
- }
-
- return true;
-}
-
-/*!
- \fn GLuint QGLFramebufferObject::texture() const
-
- Returns the texture id for the texture attached as the default
- rendering target in this framebuffer object. This texture id can
- be bound as a normal texture in your own GL code.
-
- If a multisample framebuffer object is used then the value returned
- from this function will be invalid.
-*/
-GLuint QGLFramebufferObject::texture() const
-{
- Q_D(const QGLFramebufferObject);
- return d->texture_guard ? d->texture_guard->id() : 0;
-}
-
-/*!
- \fn QSize QGLFramebufferObject::size() const
-
- Returns the size of the texture attached to this framebuffer
- object.
-*/
-QSize QGLFramebufferObject::size() const
-{
- Q_D(const QGLFramebufferObject);
- return d->size;
-}
-
-/*!
- Returns the format of this framebuffer object.
-*/
-QGLFramebufferObjectFormat QGLFramebufferObject::format() const
-{
- Q_D(const QGLFramebufferObject);
- return d->format;
-}
-
-/*!
- \fn QImage QGLFramebufferObject::toImage() const
-
- Returns the contents of this framebuffer object as a QImage.
-
- The returned image has a format of premultiplied ARGB32 or RGB32. The latter is used
- only when internalTextureFormat() is set to \c GL_RGB.
-
- If the rendering in the framebuffer was not done with premultiplied alpha in mind,
- create a wrapper QImage with a non-premultiplied format. This is necessary before
- performing operations like QImage::save() because otherwise the image data would get
- unpremultiplied, even though it was not premultiplied in the first place. To create
- such a wrapper without performing a copy of the pixel data, do the following:
-
- \code
- QImage fboImage(fbo.toImage());
- QImage image(fboImage.constBits(), fboImage.width(), fboImage.height(), QImage::Format_ARGB32);
- \endcode
-
- On QNX the back buffer is not preserved when a buffer swap occures. So this function
- might return old content.
-*/
-QImage QGLFramebufferObject::toImage() const
-{
- Q_D(const QGLFramebufferObject);
- if (!d->valid)
- return QImage();
-
- // qt_gl_read_frame_buffer doesn't work on a multisample FBO
- if (format().samples() != 0) {
- QGLFramebufferObject temp(size(), QGLFramebufferObjectFormat());
-
- QRect rect(QPoint(0, 0), size());
- blitFramebuffer(&temp, rect, const_cast<QGLFramebufferObject *>(this), rect);
-
- return temp.toImage();
- }
-
- bool wasBound = isBound();
- if (!wasBound)
- const_cast<QGLFramebufferObject *>(this)->bind();
- QImage image = qt_gl_read_frame_buffer(d->size, format().internalTextureFormat() != GL_RGB, true);
- if (!wasBound)
- const_cast<QGLFramebufferObject *>(this)->release();
-
- return image;
-}
-
-Q_GLOBAL_STATIC(QGLEngineThreadStorage<QGL2PaintEngineEx>, qt_buffer_2_engine)
-
-/*! \reimp */
-QPaintEngine *QGLFramebufferObject::paintEngine() const
-{
- Q_D(const QGLFramebufferObject);
- if (d->engine)
- return d->engine;
-
- QPaintEngine *engine = qt_buffer_2_engine()->engine();
- if (engine->isActive() && engine->paintDevice() != this) {
- d->engine = new QGL2PaintEngineEx;
- return d->engine;
- }
- return engine;
-}
-
-/*!
- \fn bool QGLFramebufferObject::bindDefault()
-
- Switches rendering back to the default, windowing system provided
- framebuffer.
- Returns \c true upon success, false otherwise.
-
- \sa bind(), release()
-*/
-bool QGLFramebufferObject::bindDefault()
-{
- QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
-
- if (ctx) {
- QOpenGLFunctions functions(ctx->contextHandle());
- if (!functions.hasOpenGLFeature(QOpenGLFunctions::Framebuffers))
- return false;
-
- ctx->d_ptr->setCurrentFbo(ctx->d_ptr->default_fbo);
- functions.glBindFramebuffer(GL_FRAMEBUFFER, ctx->d_ptr->default_fbo);
-#ifdef QT_DEBUG
- } else {
- qWarning("QGLFramebufferObject::bindDefault() called without current context.");
-#endif
- }
-
- return ctx != 0;
-}
-
-/*!
- \fn bool QGLFramebufferObject::hasOpenGLFramebufferObjects()
-
- Returns \c true if the OpenGL \c{GL_EXT_framebuffer_object} extension
- is present on this system; otherwise returns \c false.
-*/
-bool QGLFramebufferObject::hasOpenGLFramebufferObjects()
-{
- return qgl_hasFeature(QOpenGLFunctions::Framebuffers);
-}
-
-/*!
- \since 4.4
-
- Draws the given texture, \a textureId, to the given target rectangle,
- \a target, in OpenGL model space. The \a textureTarget should be a 2D
- texture target.
-
- The framebuffer object should be bound when calling this function.
-
- Equivalent to the corresponding QGLContext::drawTexture().
-*/
-void QGLFramebufferObject::drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget)
-{
- const_cast<QGLContext *>(QGLContext::currentContext())->drawTexture(target, textureId, textureTarget);
-}
-
-/*!
- \since 4.4
-
- Draws the given texture, \a textureId, at the given \a point in OpenGL
- model space. The \a textureTarget should be a 2D texture target.
-
- The framebuffer object should be bound when calling this function.
-
- Equivalent to the corresponding QGLContext::drawTexture().
-*/
-void QGLFramebufferObject::drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget)
-{
- const_cast<QGLContext *>(QGLContext::currentContext())->drawTexture(point, textureId, textureTarget);
-}
-
-/*! \reimp */
-int QGLFramebufferObject::metric(PaintDeviceMetric metric) const
-{
- Q_D(const QGLFramebufferObject);
-
- float dpmx = qt_defaultDpiX()*100./2.54;
- float dpmy = qt_defaultDpiY()*100./2.54;
- int w = d->size.width();
- int h = d->size.height();
- switch (metric) {
- case PdmWidth:
- return w;
-
- case PdmHeight:
- return h;
-
- case PdmWidthMM:
- return qRound(w * 1000 / dpmx);
-
- case PdmHeightMM:
- return qRound(h * 1000 / dpmy);
-
- case PdmNumColors:
- return 0;
-
- case PdmDepth:
- return 32;//d->depth;
-
- case PdmDpiX:
- return qRound(dpmx * 0.0254);
-
- case PdmDpiY:
- return qRound(dpmy * 0.0254);
-
- case PdmPhysicalDpiX:
- return qRound(dpmx * 0.0254);
-
- case PdmPhysicalDpiY:
- return qRound(dpmy * 0.0254);
-
- case QPaintDevice::PdmDevicePixelRatio:
- return 1;
-
- case QPaintDevice::PdmDevicePixelRatioScaled:
- return 1 * QPaintDevice::devicePixelRatioFScale();
-
- default:
- qWarning("QGLFramebufferObject::metric(), Unhandled metric type: %d.\n", metric);
- break;
- }
- return 0;
-}
-
-/*!
- \fn GLuint QGLFramebufferObject::handle() const
-
- Returns the GL framebuffer object handle for this framebuffer
- object (returned by the \c{glGenFrameBuffersEXT()} function). This
- handle can be used to attach new images or buffers to the
- framebuffer. The user is responsible for cleaning up and
- destroying these objects.
-*/
-GLuint QGLFramebufferObject::handle() const
-{
- Q_D(const QGLFramebufferObject);
- return d->fbo();
-}
-
-/*! \fn int QGLFramebufferObject::devType() const
- \internal
-*/
-
-
-/*!
- Returns the status of the depth and stencil buffers attached to
- this framebuffer object.
-*/
-
-QGLFramebufferObject::Attachment QGLFramebufferObject::attachment() const
-{
- Q_D(const QGLFramebufferObject);
- if (d->valid)
- return d->fbo_attachment;
- return NoAttachment;
-}
-
-/*!
- \since 4.5
-
- Returns \c true if the framebuffer object is currently bound to a context,
- otherwise false is returned.
-*/
-
-bool QGLFramebufferObject::isBound() const
-{
- Q_D(const QGLFramebufferObject);
- const QGLContext *current = QGLContext::currentContext();
- if (current) {
- current->d_ptr->refreshCurrentFbo();
- return current->d_ptr->current_fbo == d->fbo();
- }
-
- return false;
-}
-
-/*!
- \fn bool QGLFramebufferObject::hasOpenGLFramebufferBlit()
-
- \since 4.6
-
- Returns \c true if the OpenGL \c{GL_EXT_framebuffer_blit} extension
- is present on this system; otherwise returns \c false.
-
- \sa blitFramebuffer()
-*/
-bool QGLFramebufferObject::hasOpenGLFramebufferBlit()
-{
- return QOpenGLExtensions(QOpenGLContext::currentContext()).hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit);
-}
-
-/*!
- \since 4.6
-
- Blits from the \a sourceRect rectangle in the \a source framebuffer
- object to the \a targetRect rectangle in the \a target framebuffer object.
-
- If \a source or \a target is 0, the default framebuffer will be used
- instead of a framebuffer object as source or target respectively.
-
- The \a buffers parameter should be a mask consisting of any combination of
- \c GL_COLOR_BUFFER_BIT, \c GL_DEPTH_BUFFER_BIT, and
- \c GL_STENCIL_BUFFER_BIT. Any buffer type that is not present both
- in the source and target buffers is ignored.
-
- The \a sourceRect and \a targetRect rectangles may have different sizes;
- in this case \a buffers should not contain \c GL_DEPTH_BUFFER_BIT or
- \c GL_STENCIL_BUFFER_BIT. The \a filter parameter should be set to
- \c GL_LINEAR or \c GL_NEAREST, and specifies whether linear or nearest
- interpolation should be used when scaling is performed.
-
- If \a source equals \a target a copy is performed within the same buffer.
- Results are undefined if the source and target rectangles overlap and
- have different sizes. The sizes must also be the same if any of the
- framebuffer objects are multisample framebuffers.
-
- Note that the scissor test will restrict the blit area if enabled.
-
- This function will have no effect unless hasOpenGLFramebufferBlit() returns
- true.
-
- \sa hasOpenGLFramebufferBlit()
-*/
-void QGLFramebufferObject::blitFramebuffer(QGLFramebufferObject *target, const QRect &targetRect,
- QGLFramebufferObject *source, const QRect &sourceRect,
- GLbitfield buffers,
- GLenum filter)
-{
- const QGLContext *ctx = QGLContext::currentContext();
- if (!ctx || !ctx->contextHandle())
- return;
-
- QOpenGLExtensions functions(ctx->contextHandle());
- if (!functions.hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit))
- return;
-
- QSurface *surface = ctx->contextHandle()->surface();
-
- const int height = static_cast<QWindow *>(surface)->height();
-
- const int sh = source ? source->height() : height;
- const int th = target ? target->height() : height;
-
- const int sx0 = sourceRect.left();
- const int sx1 = sourceRect.left() + sourceRect.width();
- const int sy0 = sh - (sourceRect.top() + sourceRect.height());
- const int sy1 = sh - sourceRect.top();
-
- const int tx0 = targetRect.left();
- const int tx1 = targetRect.left() + targetRect.width();
- const int ty0 = th - (targetRect.top() + targetRect.height());
- const int ty1 = th - targetRect.top();
-
- ctx->d_ptr->refreshCurrentFbo();
-
- functions.glBindFramebuffer(GL_READ_FRAMEBUFFER, source ? source->handle() : 0);
- functions.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target ? target->handle() : 0);
-
- functions.glBlitFramebuffer(sx0, sy0, sx1, sy1,
- tx0, ty0, tx1, ty1,
- buffers, filter);
-
- functions.glBindFramebuffer(GL_FRAMEBUFFER, ctx->d_ptr->current_fbo);
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglframebufferobject.h b/src/opengl/qglframebufferobject.h
deleted file mode 100644
index c88063cbb5..0000000000
--- a/src/opengl/qglframebufferobject.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLFRAMEBUFFEROBJECT_H
-#define QGLFRAMEBUFFEROBJECT_H
-
-#include <QtOpenGL/qgl.h>
-#include <QtGui/qpaintdevice.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QGLFramebufferObjectPrivate;
-class QGLFramebufferObjectFormat;
-
-class Q_OPENGL_EXPORT QGLFramebufferObject : public QPaintDevice
-{
- Q_DECLARE_PRIVATE(QGLFramebufferObject)
-public:
- enum Attachment {
- NoAttachment,
- CombinedDepthStencil,
- Depth
- };
-
- QGLFramebufferObject(const QSize &size, GLenum target = GL_TEXTURE_2D);
- QGLFramebufferObject(int width, int height, GLenum target = GL_TEXTURE_2D);
-
- QGLFramebufferObject(const QSize &size, Attachment attachment,
- GLenum target = GL_TEXTURE_2D, GLenum internal_format = 0);
- QGLFramebufferObject(int width, int height, Attachment attachment,
- GLenum target = GL_TEXTURE_2D, GLenum internal_format = 0);
-
- QGLFramebufferObject(const QSize &size, const QGLFramebufferObjectFormat &format);
- QGLFramebufferObject(int width, int height, const QGLFramebufferObjectFormat &format);
-
- virtual ~QGLFramebufferObject();
-
- QGLFramebufferObjectFormat format() const;
-
- bool isValid() const;
- bool isBound() const;
- bool bind();
- bool release();
-
- GLuint texture() const;
- QSize size() const;
- QImage toImage() const;
- Attachment attachment() const;
-
- QPaintEngine *paintEngine() const override;
- GLuint handle() const;
-
- static bool bindDefault();
-
- static bool hasOpenGLFramebufferObjects();
-
- void drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
- void drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
-
- static bool hasOpenGLFramebufferBlit();
- static void blitFramebuffer(QGLFramebufferObject *target, const QRect &targetRect,
- QGLFramebufferObject *source, const QRect &sourceRect,
- GLbitfield buffers = GL_COLOR_BUFFER_BIT,
- GLenum filter = GL_NEAREST);
-
-protected:
- int metric(PaintDeviceMetric metric) const override;
- int devType() const override { return QInternal::FramebufferObject; }
-
-private:
- Q_DISABLE_COPY(QGLFramebufferObject)
- QScopedPointer<QGLFramebufferObjectPrivate> d_ptr;
- friend class QGLPaintDevice;
- friend class QGLFBOGLPaintDevice;
-};
-
-class QGLFramebufferObjectFormatPrivate;
-class Q_OPENGL_EXPORT QGLFramebufferObjectFormat
-{
-public:
- QGLFramebufferObjectFormat();
- QGLFramebufferObjectFormat(const QGLFramebufferObjectFormat &other);
- QGLFramebufferObjectFormat &operator=(const QGLFramebufferObjectFormat &other);
- ~QGLFramebufferObjectFormat();
-
- void setSamples(int samples);
- int samples() const;
-
- void setMipmap(bool enabled);
- bool mipmap() const;
-
- void setAttachment(QGLFramebufferObject::Attachment attachment);
- QGLFramebufferObject::Attachment attachment() const;
-
- void setTextureTarget(GLenum target);
- GLenum textureTarget() const;
-
- void setInternalTextureFormat(GLenum internalTextureFormat);
- GLenum internalTextureFormat() const;
-
- bool operator==(const QGLFramebufferObjectFormat& other) const;
- bool operator!=(const QGLFramebufferObjectFormat& other) const;
-
-private:
- QGLFramebufferObjectFormatPrivate *d;
-
- void detach();
-};
-
-QT_END_NAMESPACE
-
-#endif // QGLFRAMEBUFFEROBJECT_H
diff --git a/src/opengl/qglframebufferobject_p.h b/src/opengl/qglframebufferobject_p.h
deleted file mode 100644
index 9d536527c3..0000000000
--- a/src/opengl/qglframebufferobject_p.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLFRAMEBUFFEROBJECT_P_H
-#define QGLFRAMEBUFFEROBJECT_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 <qglframebufferobject.h>
-#include <private/qglpaintdevice_p.h>
-#include <private/qgl_p.h>
-#include <private/qopenglextensions_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGLFramebufferObjectFormatPrivate
-{
-public:
- QGLFramebufferObjectFormatPrivate()
- : ref(1),
- samples(0),
- attachment(QGLFramebufferObject::NoAttachment),
- target(GL_TEXTURE_2D),
- mipmap(false)
- {
-#ifndef QT_OPENGL_ES_2
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- const bool isES = ctx ? ctx->isOpenGLES() : QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL;
- internal_format = isES ? GL_RGBA : GL_RGBA8;
-#else
- internal_format = GL_RGBA;
-#endif
- }
- QGLFramebufferObjectFormatPrivate
- (const QGLFramebufferObjectFormatPrivate *other)
- : ref(1),
- samples(other->samples),
- attachment(other->attachment),
- target(other->target),
- internal_format(other->internal_format),
- mipmap(other->mipmap)
- {
- }
- bool equals(const QGLFramebufferObjectFormatPrivate *other)
- {
- return samples == other->samples &&
- attachment == other->attachment &&
- target == other->target &&
- internal_format == other->internal_format &&
- mipmap == other->mipmap;
- }
-
- QAtomicInt ref;
- int samples;
- QGLFramebufferObject::Attachment attachment;
- GLenum target;
- GLenum internal_format;
- uint mipmap : 1;
-};
-
-class QGLFBOGLPaintDevice : public QGLPaintDevice
-{
-public:
- virtual QPaintEngine* paintEngine() const override {return fbo->paintEngine();}
- virtual QSize size() const override {return fbo->size();}
- virtual QGLContext* context() const override;
- virtual QGLFormat format() const override {return fboFormat;}
- virtual bool alphaRequested() const override { return reqAlpha; }
-
- void setFBO(QGLFramebufferObject* f,
- QGLFramebufferObject::Attachment attachment);
-
-private:
- QGLFramebufferObject* fbo;
- QGLFormat fboFormat;
- bool reqAlpha;
-};
-
-class QGLFramebufferObjectPrivate
-{
-public:
- QGLFramebufferObjectPrivate() : fbo_guard(nullptr), texture_guard(nullptr), depth_buffer_guard(nullptr)
- , stencil_buffer_guard(nullptr), color_buffer_guard(nullptr)
- , valid(false), engine(nullptr) {}
- ~QGLFramebufferObjectPrivate() {}
-
- void init(QGLFramebufferObject *q, const QSize& sz,
- QGLFramebufferObject::Attachment attachment,
- GLenum internal_format, GLenum texture_target,
- GLint samples = 0, bool mipmap = false);
- bool checkFramebufferStatus() const;
- QGLSharedResourceGuardBase *fbo_guard;
- QGLSharedResourceGuardBase *texture_guard;
- QGLSharedResourceGuardBase *depth_buffer_guard;
- QGLSharedResourceGuardBase *stencil_buffer_guard;
- QGLSharedResourceGuardBase *color_buffer_guard;
- GLenum target;
- QSize size;
- QGLFramebufferObjectFormat format;
- uint valid : 1;
- QGLFramebufferObject::Attachment fbo_attachment;
- mutable QPaintEngine *engine;
- QGLFBOGLPaintDevice glDevice;
- QOpenGLExtensions funcs;
-
- inline GLuint fbo() const { return fbo_guard ? fbo_guard->id() : 0; }
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QGLFRAMEBUFFEROBJECT_P_H
diff --git a/src/opengl/qglfunctions.cpp b/src/opengl/qglfunctions.cpp
deleted file mode 100644
index b20311bec4..0000000000
--- a/src/opengl/qglfunctions.cpp
+++ /dev/null
@@ -1,1330 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglfunctions.h"
-#include "qgl_p.h"
-#include "QtGui/private/qopenglcontext_p.h"
-#include <private/qopengl_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGLFunctions
- \inmodule QtOpenGL
- \brief The QGLFunctions class provides cross-platform access to the OpenGL ES 2.0 API.
- \since 4.8
- \obsolete
- \ingroup painting-3D
-
- OpenGL ES 2.0 defines a subset of the OpenGL specification that is
- common across many desktop and embedded OpenGL implementations.
- However, it can be difficult to use the functions from that subset
- because they need to be resolved manually on desktop systems.
-
- QGLFunctions provides a guaranteed API that is available on all
- OpenGL systems and takes care of function resolution on systems
- that need it. The recommended way to use QGLFunctions is by
- direct inheritance:
-
- \snippet code/src_opengl_qglfunctions.cpp 0
-
- The \c{paintGL()} function can then use any of the OpenGL ES 2.0
- functions without explicit resolution, such as glActiveTexture()
- in the following example:
-
- \snippet code/src_opengl_qglfunctions.cpp 1
-
- QGLFunctions can also be used directly for ad-hoc invocation
- of OpenGL ES 2.0 functions on all platforms:
-
- \snippet code/src_opengl_qglfunctions.cpp 2
-
- QGLFunctions provides wrappers for all OpenGL ES 2.0 functions,
- except those like \c{glDrawArrays()}, \c{glViewport()}, and
- \c{glBindTexture()} that don't have portability issues.
-
- Including the header for QGLFunctions will also define all of
- the OpenGL ES 2.0 macro constants that are not already defined by
- the system's OpenGL headers, such as \c{GL_TEXTURE1} above.
-
- The hasOpenGLFeature() and openGLFeatures() functions can be used
- to determine if the OpenGL implementation has a major OpenGL ES 2.0
- feature. For example, the following checks if non power of two
- textures are available:
-
- \snippet code/src_opengl_qglfunctions.cpp 3
-
- \note This class has been deprecated in favor of QOpenGLFunctions.
-*/
-
-/*!
- \enum QGLFunctions::OpenGLFeature
- This enum defines OpenGL ES 2.0 features that may be optional
- on other platforms.
-
- \value Multitexture glActiveTexture() function is available.
- \value Shaders Shader functions are available.
- \value Buffers Vertex and index buffer functions are available.
- \value Framebuffers Framebuffer object functions are available.
- \value BlendColor glBlendColor() is available.
- \value BlendEquation glBlendEquation() is available.
- \value BlendEquationSeparate glBlendEquationSeparate() is available.
- \value BlendFuncSeparate glBlendFuncSeparate() is available.
- \value BlendSubtract Blend subtract mode is available.
- \value CompressedTextures Compressed texture functions are available.
- \value Multisample glSampleCoverage() function is available.
- \value StencilSeparate Separate stencil functions are available.
- \value NPOTTextures Non power of two textures are available.
-*/
-
-// Hidden private fields for additional extension data.
-struct QGLFunctionsPrivateEx : public QGLFunctionsPrivate, public QOpenGLSharedResource
-{
- QGLFunctionsPrivateEx(QOpenGLContext *context)
- : QGLFunctionsPrivate(QGLContext::fromOpenGLContext(context))
- , QOpenGLSharedResource(context->shareGroup())
- , m_features(-1)
- {
- funcs = new QOpenGLFunctions(context);
- funcs->initializeOpenGLFunctions();
- }
-
- ~QGLFunctionsPrivateEx()
- {
- delete funcs;
- }
-
- void invalidateResource() override
- {
- m_features = -1;
- }
-
- void freeResource(QOpenGLContext *) override
- {
- // no gl resources to free
- }
-
- int m_features;
-};
-
-Q_GLOBAL_STATIC(QOpenGLMultiGroupSharedResource, qt_gl_functions_resource)
-
-static QGLFunctionsPrivateEx *qt_gl_functions(const QGLContext *context = 0)
-{
- if (!context)
- context = QGLContext::currentContext();
- Q_ASSERT(context);
- QGLFunctionsPrivateEx *funcs =
- reinterpret_cast<QGLFunctionsPrivateEx *>
- (qt_gl_functions_resource()->value<QGLFunctionsPrivateEx>(context->contextHandle()));
- return funcs;
-}
-
-/*!
- Constructs a default function resolver. The resolver cannot
- be used until initializeGLFunctions() is called to specify
- the context.
-
- \sa initializeGLFunctions()
-*/
-QGLFunctions::QGLFunctions()
- : d_ptr(0)
-{
-}
-
-/*!
- Constructs a function resolver for \a context. If \a context
- is \nullptr, then the resolver will be created for the current
- QGLContext.
-
- An object constructed in this way can only be used with \a context
- and other contexts that share with it. Use initializeGLFunctions()
- to change the object's context association.
-
- \sa initializeGLFunctions()
-*/
-QGLFunctions::QGLFunctions(const QGLContext *context)
- : d_ptr(qt_gl_functions(context))
-{
-}
-
-/*!
- \fn QGLFunctions::~QGLFunctions()
-
- Destroys this function resolver.
-*/
-
-static int qt_gl_resolve_features()
-{
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- if (ctx->isOpenGLES()) {
- // OpenGL ES 2
- int features = QGLFunctions::Multitexture |
- QGLFunctions::Shaders |
- QGLFunctions::Buffers |
- QGLFunctions::Framebuffers |
- QGLFunctions::BlendColor |
- QGLFunctions::BlendEquation |
- QGLFunctions::BlendEquationSeparate |
- QGLFunctions::BlendFuncSeparate |
- QGLFunctions::BlendSubtract |
- QGLFunctions::CompressedTextures |
- QGLFunctions::Multisample |
- QGLFunctions::StencilSeparate;
- QOpenGLExtensionMatcher extensions;
- if (extensions.match("GL_OES_texture_npot"))
- features |= QGLFunctions::NPOTTextures;
- if (extensions.match("GL_IMG_texture_npot"))
- features |= QGLFunctions::NPOTTextures;
- return features;
- } else {
- // OpenGL
- int features = 0;
- QGLFormat::OpenGLVersionFlags versions = QGLFormat::openGLVersionFlags();
- QOpenGLExtensionMatcher extensions;
-
- // Recognize features by extension name.
- if (extensions.match("GL_ARB_multitexture"))
- features |= QGLFunctions::Multitexture;
- if (extensions.match("GL_ARB_shader_objects"))
- features |= QGLFunctions::Shaders;
- if (extensions.match("GL_EXT_framebuffer_object") ||
- extensions.match("GL_ARB_framebuffer_object"))
- features |= QGLFunctions::Framebuffers;
- if (extensions.match("GL_EXT_blend_color"))
- features |= QGLFunctions::BlendColor;
- if (extensions.match("GL_EXT_blend_equation_separate"))
- features |= QGLFunctions::BlendEquationSeparate;
- if (extensions.match("GL_EXT_blend_func_separate"))
- features |= QGLFunctions::BlendFuncSeparate;
- if (extensions.match("GL_EXT_blend_subtract"))
- features |= QGLFunctions::BlendSubtract;
- if (extensions.match("GL_ARB_texture_compression"))
- features |= QGLFunctions::CompressedTextures;
- if (extensions.match("GL_ARB_multisample"))
- features |= QGLFunctions::Multisample;
- if (extensions.match("GL_ARB_texture_non_power_of_two"))
- features |= QGLFunctions::NPOTTextures;
-
- // Recognize features by minimum OpenGL version.
- if (versions & QGLFormat::OpenGL_Version_1_2) {
- features |= QGLFunctions::BlendColor |
- QGLFunctions::BlendEquation;
- }
- if (versions & QGLFormat::OpenGL_Version_1_3) {
- features |= QGLFunctions::Multitexture |
- QGLFunctions::CompressedTextures |
- QGLFunctions::Multisample;
- }
- if (versions & QGLFormat::OpenGL_Version_1_4)
- features |= QGLFunctions::BlendFuncSeparate;
- if (versions & QGLFormat::OpenGL_Version_1_5)
- features |= QGLFunctions::Buffers;
- if (versions & QGLFormat::OpenGL_Version_2_0) {
- features |= QGLFunctions::Shaders |
- QGLFunctions::StencilSeparate |
- QGLFunctions::BlendEquationSeparate |
- QGLFunctions::NPOTTextures;
- }
- return features;
- }
-}
-
-/*!
- Returns the set of features that are present on this system's
- OpenGL implementation.
-
- It is assumed that the QGLContext associated with this function
- resolver is current.
-
- \sa hasOpenGLFeature()
-*/
-QGLFunctions::OpenGLFeatures QGLFunctions::openGLFeatures() const
-{
- QGLFunctionsPrivateEx *d = static_cast<QGLFunctionsPrivateEx *>(d_ptr);
- if (!d)
- return { };
- if (d->m_features == -1)
- d->m_features = qt_gl_resolve_features();
- return QGLFunctions::OpenGLFeatures(d->m_features);
-}
-
-/*!
- Returns \c true if \a feature is present on this system's OpenGL
- implementation; false otherwise.
-
- It is assumed that the QGLContext associated with this function
- resolver is current.
-
- \sa openGLFeatures()
-*/
-bool QGLFunctions::hasOpenGLFeature(QGLFunctions::OpenGLFeature feature) const
-{
- QGLFunctionsPrivateEx *d = static_cast<QGLFunctionsPrivateEx *>(d_ptr);
- if (!d)
- return false;
- if (d->m_features == -1)
- d->m_features = qt_gl_resolve_features();
- return (d->m_features & int(feature)) != 0;
-}
-
-/*!
- Initializes GL function resolution for \a context. If \a context
- is \nullptr, then the current QGLContext will be used.
-
- After calling this function, the QGLFunctions object can only be
- used with \a context and other contexts that share with it.
- Call initializeGLFunctions() again to change the object's context
- association.
-*/
-void QGLFunctions::initializeGLFunctions(const QGLContext *context)
-{
- d_ptr = qt_gl_functions(context);
-}
-
-/*!
- \fn void QGLFunctions::glActiveTexture(GLenum texture)
-
- Convenience function that calls glActiveTexture(\a texture).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glActiveTexture.xml}{glActiveTexture()}.
-*/
-
-/*!
- \fn void QGLFunctions::glAttachShader(GLuint program, GLuint shader)
-
- Convenience function that calls glAttachShader(\a program, \a shader).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glAttachShader.xml}{glAttachShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glBindAttribLocation(GLuint program, GLuint index, const char* name)
-
- Convenience function that calls glBindAttribLocation(\a program, \a index, \a name).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBindAttribLocation.xml}{glBindAttribLocation()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glBindBuffer(GLenum target, GLuint buffer)
-
- Convenience function that calls glBindBuffer(\a target, \a buffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBindBuffer.xml}{glBindBuffer()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBindFramebuffer(GLenum target, GLuint framebuffer)
-
- Convenience function that calls glBindFramebuffer(\a target, \a framebuffer).
-
- Note that Qt will translate a \a framebuffer argument of 0 to the currently
- bound QOpenGLContext's defaultFramebufferObject().
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBindFramebuffer.xml}{glBindFramebuffer()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBindRenderbuffer(GLenum target, GLuint renderbuffer)
-
- Convenience function that calls glBindRenderbuffer(\a target, \a renderbuffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBindRenderbuffer.xml}{glBindRenderbuffer()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
-
- Convenience function that calls glBlendColor(\a red, \a green, \a blue, \a alpha).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBlendColor.xml}{glBlendColor()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBlendEquation(GLenum mode)
-
- Convenience function that calls glBlendEquation(\a mode).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBlendEquation.xml}{glBlendEquation()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
-
- Convenience function that calls glBlendEquationSeparate(\a modeRGB, \a modeAlpha).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBlendEquationSeparate.xml}{glBlendEquationSeparate()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
-
- Convenience function that calls glBlendFuncSeparate(\a srcRGB, \a dstRGB, \a srcAlpha, \a dstAlpha).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBlendFuncSeparate.xml}{glBlendFuncSeparate()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBufferData(GLenum target, qopengl_GLsizeiptr size, const void* data, GLenum usage)
-
- Convenience function that calls glBufferData(\a target, \a size, \a data, \a usage).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBufferData.xml}{glBufferData()}.
-*/
-
-/*!
- \fn void QGLFunctions::glBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, const void* data)
-
- Convenience function that calls glBufferSubData(\a target, \a offset, \a size, \a data).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glBufferSubData.xml}{glBufferSubData()}.
-*/
-
-/*!
- \fn GLenum QGLFunctions::glCheckFramebufferStatus(GLenum target)
-
- Convenience function that calls glCheckFramebufferStatus(\a target).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCheckFramebufferStatus.xml}{glCheckFramebufferStatus()}.
-*/
-
-/*!
- \fn void QGLFunctions::glClearDepthf(GLclampf depth)
-
- Convenience function that calls glClearDepth(\a depth) on
- desktop OpenGL systems and glClearDepthf(\a depth) on
- embedded OpenGL ES systems.
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glClearDepthf.xml}{glClearDepthf()}.
-*/
-
-/*!
- \fn void QGLFunctions::glCompileShader(GLuint shader)
-
- Convenience function that calls glCompileShader(\a shader).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCompileShader.xml}{glCompileShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
-
- Convenience function that calls glCompressedTexImage2D(\a target, \a level, \a internalformat, \a width, \a height, \a border, \a imageSize, \a data).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCompressedTexImage2D.xml}{glCompressedTexImage2D()}.
-*/
-
-/*!
- \fn void QGLFunctions::glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
-
- Convenience function that calls glCompressedTexSubImage2D(\a target, \a level, \a xoffset, \a yoffset, \a width, \a height, \a format, \a imageSize, \a data).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCompressedTexSubImage2D.xml}{glCompressedTexSubImage2D()}.
-*/
-
-/*!
- \fn GLuint QGLFunctions::glCreateProgram()
-
- Convenience function that calls glCreateProgram().
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCreateProgram.xml}{glCreateProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn GLuint QGLFunctions::glCreateShader(GLenum type)
-
- Convenience function that calls glCreateShader(\a type).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glCreateShader.xml}{glCreateShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glDeleteBuffers(GLsizei n, const GLuint* buffers)
-
- Convenience function that calls glDeleteBuffers(\a n, \a buffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDeleteBuffers.xml}{glDeleteBuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers)
-
- Convenience function that calls glDeleteFramebuffers(\a n, \a framebuffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDeleteFramebuffers.xml}{glDeleteFramebuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glDeleteProgram(GLuint program)
-
- Convenience function that calls glDeleteProgram(\a program).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDeleteProgram.xml}{glDeleteProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers)
-
- Convenience function that calls glDeleteRenderbuffers(\a n, \a renderbuffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDeleteRenderbuffers.xml}{glDeleteRenderbuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glDeleteShader(GLuint shader)
-
- Convenience function that calls glDeleteShader(\a shader).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDeleteShader.xml}{glDeleteShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glDepthRangef(GLclampf zNear, GLclampf zFar)
-
- Convenience function that calls glDepthRange(\a zNear, \a zFar) on
- desktop OpenGL systems and glDepthRangef(\a zNear, \a zFar) on
- embedded OpenGL ES systems.
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDepthRangef.xml}{glDepthRangef()}.
-*/
-
-/*!
- \fn void QGLFunctions::glDetachShader(GLuint program, GLuint shader)
-
- Convenience function that calls glDetachShader(\a program, \a shader).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDetachShader.xml}{glDetachShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glDisableVertexAttribArray(GLuint index)
-
- Convenience function that calls glDisableVertexAttribArray(\a index).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glDisableVertexAttribArray.xml}{glDisableVertexAttribArray()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glEnableVertexAttribArray(GLuint index)
-
- Convenience function that calls glEnableVertexAttribArray(\a index).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glEnableVertexAttribArray.xml}{glEnableVertexAttribArray()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
-
- Convenience function that calls glFramebufferRenderbuffer(\a target, \a attachment, \a renderbuffertarget, \a renderbuffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glFramebufferRenderbuffer.xml}{glFramebufferRenderbuffer()}.
-*/
-
-/*!
- \fn void QGLFunctions::glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
-
- Convenience function that calls glFramebufferTexture2D(\a target, \a attachment, \a textarget, \a texture, \a level).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glFramebufferTexture2D.xml}{glFramebufferTexture2D()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGenBuffers(GLsizei n, GLuint* buffers)
-
- Convenience function that calls glGenBuffers(\a n, \a buffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGenBuffers.xml}{glGenBuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGenerateMipmap(GLenum target)
-
- Convenience function that calls glGenerateMipmap(\a target).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGenerateMipmap.xml}{glGenerateMipmap()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGenFramebuffers(GLsizei n, GLuint* framebuffers)
-
- Convenience function that calls glGenFramebuffers(\a n, \a framebuffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGenFramebuffers.xml}{glGenFramebuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
-
- Convenience function that calls glGenRenderbuffers(\a n, \a renderbuffers).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGenRenderbuffers.xml}{glGenRenderbuffers()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
-
- Convenience function that calls glGetActiveAttrib(\a program, \a index, \a bufsize, \a length, \a size, \a type, \a name).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetActiveAttrib.xml}{glGetActiveAttrib()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
-
- Convenience function that calls glGetActiveUniform(\a program, \a index, \a bufsize, \a length, \a size, \a type, \a name).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetActiveUniform.xml}{glGetActiveUniform()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
-
- Convenience function that calls glGetAttachedShaders(\a program, \a maxcount, \a count, \a shaders).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetAttachedShaders.xml}{glGetAttachedShaders()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn int QGLFunctions::glGetAttribLocation(GLuint program, const char* name)
-
- Convenience function that calls glGetAttribLocation(\a program, \a name).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetAttribLocation.xml}{glGetAttribLocation()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
-
- Convenience function that calls glGetBufferParameteriv(\a target, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetBufferParameteriv.xml}{glGetBufferParameteriv()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params)
-
- Convenience function that calls glGetFramebufferAttachmentParameteriv(\a target, \a attachment, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetFramebufferAttachmentParameteriv.xml}{glGetFramebufferAttachmentParameteriv()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGetProgramiv(GLuint program, GLenum pname, GLint* params)
-
- Convenience function that calls glGetProgramiv(\a program, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetProgramiv.xml}{glGetProgramiv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
-
- Convenience function that calls glGetProgramInfoLog(\a program, \a bufsize, \a length, \a infolog).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetProgramInfoLog.xml}{glGetProgramInfoLog()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
-
- Convenience function that calls glGetRenderbufferParameteriv(\a target, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetRenderbufferParameteriv.xml}{glGetRenderbufferParameteriv()}.
-*/
-
-/*!
- \fn void QGLFunctions::glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
-
- Convenience function that calls glGetShaderiv(\a shader, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetShaderiv.xml}{glGetShaderiv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
-
- Convenience function that calls glGetShaderInfoLog(\a shader, \a bufsize, \a length, \a infolog).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetShaderInfoLog.xml}{glGetShaderInfoLog()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
-
- Convenience function that calls glGetShaderPrecisionFormat(\a shadertype, \a precisiontype, \a range, \a precision).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetShaderPrecisionFormat.xml}{glGetShaderPrecisionFormat()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
-
- Convenience function that calls glGetShaderSource(\a shader, \a bufsize, \a length, \a source).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetShaderSource.xml}{glGetShaderSource()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetUniformfv(GLuint program, GLint location, GLfloat* params)
-
- Convenience function that calls glGetUniformfv(\a program, \a location, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetUniformfv.xml}{glGetUniformfv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetUniformiv(GLuint program, GLint location, GLint* params)
-
- Convenience function that calls glGetUniformiv(\a program, \a location, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetUniformiv.xml}{glGetUniformiv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn int QGLFunctions::glGetUniformLocation(GLuint program, const char* name)
-
- Convenience function that calls glGetUniformLocation(\a program, \a name).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetUniformLocation.xml}{glGetUniformLocation()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
-
- Convenience function that calls glGetVertexAttribfv(\a index, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetVertexAttribfv.xml}{glGetVertexAttribfv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
-
- Convenience function that calls glGetVertexAttribiv(\a index, \a pname, \a params).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetVertexAttribiv.xml}{glGetVertexAttribiv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glGetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer)
-
- Convenience function that calls glGetVertexAttribPointerv(\a index, \a pname, \a pointer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glGetVertexAttribPointerv.xml}{glGetVertexAttribPointerv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn GLboolean QGLFunctions::glIsBuffer(GLuint buffer)
-
- Convenience function that calls glIsBuffer(\a buffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glIsBuffer.xml}{glIsBuffer()}.
-*/
-
-/*!
- \fn GLboolean QGLFunctions::glIsFramebuffer(GLuint framebuffer)
-
- Convenience function that calls glIsFramebuffer(\a framebuffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glIsFramebuffer.xml}{glIsFramebuffer()}.
-*/
-
-/*!
- \fn GLboolean QGLFunctions::glIsProgram(GLuint program)
-
- Convenience function that calls glIsProgram(\a program).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glIsProgram.xml}{glIsProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn GLboolean QGLFunctions::glIsRenderbuffer(GLuint renderbuffer)
-
- Convenience function that calls glIsRenderbuffer(\a renderbuffer).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glIsRenderbuffer.xml}{glIsRenderbuffer()}.
-*/
-
-/*!
- \fn GLboolean QGLFunctions::glIsShader(GLuint shader)
-
- Convenience function that calls glIsShader(\a shader).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glIsShader.xml}{glIsShader()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glLinkProgram(GLuint program)
-
- Convenience function that calls glLinkProgram(\a program).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glLinkProgram.xml}{glLinkProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glReleaseShaderCompiler()
-
- Convenience function that calls glReleaseShaderCompiler().
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glReleaseShaderCompiler.xml}{glReleaseShaderCompiler()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
-
- Convenience function that calls glRenderbufferStorage(\a target, \a internalformat, \a width, \a height).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glRenderbufferStorage.xml}{glRenderbufferStorage()}.
-*/
-
-/*!
- \fn void QGLFunctions::glSampleCoverage(GLclampf value, GLboolean invert)
-
- Convenience function that calls glSampleCoverage(\a value, \a invert).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glSampleCoverage.xml}{glSampleCoverage()}.
-*/
-
-/*!
- \fn void QGLFunctions::glShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLint length)
-
- Convenience function that calls glShaderBinary(\a n, \a shaders, \a binaryformat, \a binary, \a length).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glShaderBinary.xml}{glShaderBinary()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glShaderSource(GLuint shader, GLsizei count, const char** string, const GLint* length)
-
- Convenience function that calls glShaderSource(\a shader, \a count, \a string, \a length).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glShaderSource.xml}{glShaderSource()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
-
- Convenience function that calls glStencilFuncSeparate(\a face, \a func, \a ref, \a mask).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glStencilFuncSeparate.xml}{glStencilFuncSeparate()}.
-*/
-
-/*!
- \fn void QGLFunctions::glStencilMaskSeparate(GLenum face, GLuint mask)
-
- Convenience function that calls glStencilMaskSeparate(\a face, \a mask).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glStencilMaskSeparate.xml}{glStencilMaskSeparate()}.
-*/
-
-/*!
- \fn void QGLFunctions::glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
-
- Convenience function that calls glStencilOpSeparate(\a face, \a fail, \a zfail, \a zpass).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glStencilOpSeparate.xml}{glStencilOpSeparate()}.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform1f(GLint location, GLfloat x)
-
- Convenience function that calls glUniform1f(\a location, \a x).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform1f.xml}{glUniform1f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform1fv(GLint location, GLsizei count, const GLfloat* v)
-
- Convenience function that calls glUniform1fv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform1fv.xml}{glUniform1fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform1i(GLint location, GLint x)
-
- Convenience function that calls glUniform1i(\a location, \a x).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform1i.xml}{glUniform1i()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform1iv(GLint location, GLsizei count, const GLint* v)
-
- Convenience function that calls glUniform1iv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform1iv.xml}{glUniform1iv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform2f(GLint location, GLfloat x, GLfloat y)
-
- Convenience function that calls glUniform2f(\a location, \a x, \a y).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform2f.xml}{glUniform2f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform2fv(GLint location, GLsizei count, const GLfloat* v)
-
- Convenience function that calls glUniform2fv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform2fv.xml}{glUniform2fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform2i(GLint location, GLint x, GLint y)
-
- Convenience function that calls glUniform2i(\a location, \a x, \a y).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform2i.xml}{glUniform2i()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform2iv(GLint location, GLsizei count, const GLint* v)
-
- Convenience function that calls glUniform2iv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform2iv.xml}{glUniform2iv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z)
-
- Convenience function that calls glUniform3f(\a location, \a x, \a y, \a z).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform3f.xml}{glUniform3f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform3fv(GLint location, GLsizei count, const GLfloat* v)
-
- Convenience function that calls glUniform3fv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform3fv.xml}{glUniform3fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform3i(GLint location, GLint x, GLint y, GLint z)
-
- Convenience function that calls glUniform3i(\a location, \a x, \a y, \a z).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform3i.xml}{glUniform3i()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform3iv(GLint location, GLsizei count, const GLint* v)
-
- Convenience function that calls glUniform3iv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform3iv.xml}{glUniform3iv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-
- Convenience function that calls glUniform4f(\a location, \a x, \a y, \a z, \a w).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform4f.xml}{glUniform4f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform4fv(GLint location, GLsizei count, const GLfloat* v)
-
- Convenience function that calls glUniform4fv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform4fv.xml}{glUniform4fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform4i(GLint location, GLint x, GLint y, GLint z, GLint w)
-
- Convenience function that calls glUniform4i(\a location, \a x, \a y, \a z, \a w).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform4i.xml}{glUniform4i()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniform4iv(GLint location, GLsizei count, const GLint* v)
-
- Convenience function that calls glUniform4iv(\a location, \a count, \a v).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniform4iv.xml}{glUniform4iv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-
- Convenience function that calls glUniformMatrix2fv(\a location, \a count, \a transpose, \a value).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniformMatrix2fv.xml}{glUniformMatrix2fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-
- Convenience function that calls glUniformMatrix3fv(\a location, \a count, \a transpose, \a value).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniformMatrix3fv.xml}{glUniformMatrix3fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-
- Convenience function that calls glUniformMatrix4fv(\a location, \a count, \a transpose, \a value).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUniformMatrix4fv.xml}{glUniformMatrix4fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glUseProgram(GLuint program)
-
- Convenience function that calls glUseProgram(\a program).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glUseProgram.xml}{glUseProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glValidateProgram(GLuint program)
-
- Convenience function that calls glValidateProgram(\a program).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glValidateProgram.xml}{glValidateProgram()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib1f(GLuint indx, GLfloat x)
-
- Convenience function that calls glVertexAttrib1f(\a indx, \a x).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib1f.xml}{glVertexAttrib1f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib1fv(GLuint indx, const GLfloat* values)
-
- Convenience function that calls glVertexAttrib1fv(\a indx, \a values).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib1fv.xml}{glVertexAttrib1fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
-
- Convenience function that calls glVertexAttrib2f(\a indx, \a x, \a y).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib2f.xml}{glVertexAttrib2f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib2fv(GLuint indx, const GLfloat* values)
-
- Convenience function that calls glVertexAttrib2fv(\a indx, \a values).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib2fv.xml}{glVertexAttrib2fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
-
- Convenience function that calls glVertexAttrib3f(\a indx, \a x, \a y, \a z).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib3f.xml}{glVertexAttrib3f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib3fv(GLuint indx, const GLfloat* values)
-
- Convenience function that calls glVertexAttrib3fv(\a indx, \a values).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib3fv.xml}{glVertexAttrib3fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-
- Convenience function that calls glVertexAttrib4f(\a indx, \a x, \a y, \a z, \a w).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib4f.xml}{glVertexAttrib4f()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttrib4fv(GLuint indx, const GLfloat* values)
-
- Convenience function that calls glVertexAttrib4fv(\a indx, \a values).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttrib4fv.xml}{glVertexAttrib4fv()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-/*!
- \fn void QGLFunctions::glVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
-
- Convenience function that calls glVertexAttribPointer(\a indx, \a size, \a type, \a normalized, \a stride, \a ptr).
-
- For more information, see the OpenGL ES 2.0 documentation for
- \l{http://www.khronos.org/opengles/sdk/docs/man/glVertexAttribPointer.xml}{glVertexAttribPointer()}.
-
- This convenience function will do nothing on OpenGL ES 1.x systems.
-*/
-
-QGLFunctionsPrivate::QGLFunctionsPrivate(const QGLContext *)
- : funcs(0)
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglfunctions.h b/src/opengl/qglfunctions.h
deleted file mode 100644
index d8c5249a1a..0000000000
--- a/src/opengl/qglfunctions.h
+++ /dev/null
@@ -1,1688 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLFUNCTIONS_H
-#define QGLFUNCTIONS_H
-
-#include <QtOpenGL/qgl.h>
-#include <QtGui/qopenglcontext.h>
-#include <QtGui/qopenglfunctions.h>
-
-QT_BEGIN_NAMESPACE
-
-struct QGLFunctionsPrivate;
-
-class Q_OPENGL_EXPORT QGLFunctions
-{
-public:
- QGLFunctions();
- explicit QGLFunctions(const QGLContext *context);
- ~QGLFunctions() {}
-
- enum OpenGLFeature
- {
- Multitexture = 0x0001,
- Shaders = 0x0002,
- Buffers = 0x0004,
- Framebuffers = 0x0008,
- BlendColor = 0x0010,
- BlendEquation = 0x0020,
- BlendEquationSeparate = 0x0040,
- BlendFuncSeparate = 0x0080,
- BlendSubtract = 0x0100,
- CompressedTextures = 0x0200,
- Multisample = 0x0400,
- StencilSeparate = 0x0800,
- NPOTTextures = 0x1000
- };
- Q_DECLARE_FLAGS(OpenGLFeatures, OpenGLFeature)
-
- QGLFunctions::OpenGLFeatures openGLFeatures() const;
- bool hasOpenGLFeature(QGLFunctions::OpenGLFeature feature) const;
-
- void initializeGLFunctions(const QGLContext *context = nullptr);
-
- void glActiveTexture(GLenum texture);
- void glAttachShader(GLuint program, GLuint shader);
- void glBindAttribLocation(GLuint program, GLuint index, const char* name);
- void glBindBuffer(GLenum target, GLuint buffer);
- void glBindFramebuffer(GLenum target, GLuint framebuffer);
- void glBindRenderbuffer(GLenum target, GLuint renderbuffer);
- void glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
- void glBlendEquation(GLenum mode);
- void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
- void glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
- void glBufferData(GLenum target, qopengl_GLsizeiptr size, const void* data, GLenum usage);
- void glBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, const void* data);
- GLenum glCheckFramebufferStatus(GLenum target);
- void glClearDepthf(GLclampf depth);
- void glCompileShader(GLuint shader);
- void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data);
- void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data);
- GLuint glCreateProgram();
- GLuint glCreateShader(GLenum type);
- void glDeleteBuffers(GLsizei n, const GLuint* buffers);
- void glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers);
- void glDeleteProgram(GLuint program);
- void glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers);
- void glDeleteShader(GLuint shader);
- void glDepthRangef(GLclampf zNear, GLclampf zFar);
- void glDetachShader(GLuint program, GLuint shader);
- void glDisableVertexAttribArray(GLuint index);
- void glEnableVertexAttribArray(GLuint index);
- void glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
- void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
- void glGenBuffers(GLsizei n, GLuint* buffers);
- void glGenerateMipmap(GLenum target);
- void glGenFramebuffers(GLsizei n, GLuint* framebuffers);
- void glGenRenderbuffers(GLsizei n, GLuint* renderbuffers);
- void glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
- void glGetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
- void glGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders);
- int glGetAttribLocation(GLuint program, const char* name);
- void glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params);
- void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params);
- void glGetProgramiv(GLuint program, GLenum pname, GLint* params);
- void glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog);
- void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params);
- void glGetShaderiv(GLuint shader, GLenum pname, GLint* params);
- void glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog);
- void glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision);
- void glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, char* source);
- void glGetUniformfv(GLuint program, GLint location, GLfloat* params);
- void glGetUniformiv(GLuint program, GLint location, GLint* params);
- int glGetUniformLocation(GLuint program, const char* name);
- void glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params);
- void glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params);
- void glGetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer);
- GLboolean glIsBuffer(GLuint buffer);
- GLboolean glIsFramebuffer(GLuint framebuffer);
- GLboolean glIsProgram(GLuint program);
- GLboolean glIsRenderbuffer(GLuint renderbuffer);
- GLboolean glIsShader(GLuint shader);
- void glLinkProgram(GLuint program);
- void glReleaseShaderCompiler();
- void glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
- void glSampleCoverage(GLclampf value, GLboolean invert);
- void glShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLint length);
- void glShaderSource(GLuint shader, GLsizei count, const char** string, const GLint* length);
- void glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
- void glStencilMaskSeparate(GLenum face, GLuint mask);
- void glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
- void glUniform1f(GLint location, GLfloat x);
- void glUniform1fv(GLint location, GLsizei count, const GLfloat* v);
- void glUniform1i(GLint location, GLint x);
- void glUniform1iv(GLint location, GLsizei count, const GLint* v);
- void glUniform2f(GLint location, GLfloat x, GLfloat y);
- void glUniform2fv(GLint location, GLsizei count, const GLfloat* v);
- void glUniform2i(GLint location, GLint x, GLint y);
- void glUniform2iv(GLint location, GLsizei count, const GLint* v);
- void glUniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z);
- void glUniform3fv(GLint location, GLsizei count, const GLfloat* v);
- void glUniform3i(GLint location, GLint x, GLint y, GLint z);
- void glUniform3iv(GLint location, GLsizei count, const GLint* v);
- void glUniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void glUniform4fv(GLint location, GLsizei count, const GLfloat* v);
- void glUniform4i(GLint location, GLint x, GLint y, GLint z, GLint w);
- void glUniform4iv(GLint location, GLsizei count, const GLint* v);
- void glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
- void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
- void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
- void glUseProgram(GLuint program);
- void glValidateProgram(GLuint program);
- void glVertexAttrib1f(GLuint indx, GLfloat x);
- void glVertexAttrib1fv(GLuint indx, const GLfloat* values);
- void glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
- void glVertexAttrib2fv(GLuint indx, const GLfloat* values);
- void glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
- void glVertexAttrib3fv(GLuint indx, const GLfloat* values);
- void glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void glVertexAttrib4fv(GLuint indx, const GLfloat* values);
- void glVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr);
-
-private:
- QGLFunctionsPrivate *d_ptr;
- static bool isInitialized(const QGLFunctionsPrivate *d) { return d != nullptr; }
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGLFunctions::OpenGLFeatures)
-
-struct QGLFunctionsPrivate
-{
- QGLFunctionsPrivate(const QGLContext *context = nullptr);
- QOpenGLFunctions *funcs;
-};
-
-inline void QGLFunctions::glActiveTexture(GLenum texture)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glActiveTexture(texture);
-}
-
-inline void QGLFunctions::glAttachShader(GLuint program, GLuint shader)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glAttachShader(program, shader);
-}
-
-inline void QGLFunctions::glBindAttribLocation(GLuint program, GLuint index, const char* name)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBindAttribLocation(program, index, name);
-}
-
-inline void QGLFunctions::glBindBuffer(GLenum target, GLuint buffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBindBuffer(target, buffer);
-}
-
-inline void QGLFunctions::glBindFramebuffer(GLenum target, GLuint framebuffer)
-{
- if (framebuffer == 0)
- framebuffer = QOpenGLContext::currentContext()->defaultFramebufferObject();
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBindFramebuffer(target, framebuffer);
-}
-
-inline void QGLFunctions::glBindRenderbuffer(GLenum target, GLuint renderbuffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBindRenderbuffer(target, renderbuffer);
-}
-
-inline void QGLFunctions::glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBlendColor(red, green, blue, alpha);
-}
-
-inline void QGLFunctions::glBlendEquation(GLenum mode)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBlendEquation(mode);
-}
-
-inline void QGLFunctions::glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBlendEquationSeparate(modeRGB, modeAlpha);
-}
-
-inline void QGLFunctions::glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
-}
-
-inline void QGLFunctions::glBufferData(GLenum target, qopengl_GLsizeiptr size, const void* data, GLenum usage)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBufferData(target, size, data, usage);
-}
-
-inline void QGLFunctions::glBufferSubData(GLenum target, qopengl_GLintptr offset, qopengl_GLsizeiptr size, const void* data)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glBufferSubData(target, offset, size, data);
-}
-
-inline GLenum QGLFunctions::glCheckFramebufferStatus(GLenum target)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glCheckFramebufferStatus(target);
-}
-
-inline void QGLFunctions::glClearDepthf(GLclampf depth)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glClearDepthf(depth);
-}
-
-inline void QGLFunctions::glCompileShader(GLuint shader)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glCompileShader(shader);
-}
-
-inline void QGLFunctions::glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
-}
-
-inline void QGLFunctions::glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
-}
-
-inline GLuint QGLFunctions::glCreateProgram()
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glCreateProgram();
-}
-
-inline GLuint QGLFunctions::glCreateShader(GLenum type)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glCreateShader(type);
-}
-
-inline void QGLFunctions::glDeleteBuffers(GLsizei n, const GLuint* buffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDeleteBuffers(n, buffers);
-}
-
-inline void QGLFunctions::glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDeleteFramebuffers(n, framebuffers);
-}
-
-inline void QGLFunctions::glDeleteProgram(GLuint program)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDeleteProgram(program);
-}
-
-inline void QGLFunctions::glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDeleteRenderbuffers(n, renderbuffers);
-}
-
-inline void QGLFunctions::glDeleteShader(GLuint shader)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDeleteShader(shader);
-}
-
-inline void QGLFunctions::glDepthRangef(GLclampf zNear, GLclampf zFar)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glDepthRangef(zNear, zFar);
-}
-
-inline void QGLFunctions::glDetachShader(GLuint program, GLuint shader)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDetachShader(program, shader);
-}
-
-inline void QGLFunctions::glDisableVertexAttribArray(GLuint index)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glDisableVertexAttribArray(index);
-}
-
-inline void QGLFunctions::glEnableVertexAttribArray(GLuint index)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glEnableVertexAttribArray(index);
-}
-
-inline void QGLFunctions::glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer);
-}
-
-inline void QGLFunctions::glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glFramebufferTexture2D(target, attachment, textarget, texture, level);
-}
-
-inline void QGLFunctions::glGenBuffers(GLsizei n, GLuint* buffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGenBuffers(n, buffers);
-}
-
-inline void QGLFunctions::glGenerateMipmap(GLenum target)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGenerateMipmap(target);
-}
-
-inline void QGLFunctions::glGenFramebuffers(GLsizei n, GLuint* framebuffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGenFramebuffers(n, framebuffers);
-}
-
-inline void QGLFunctions::glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGenRenderbuffers(n, renderbuffers);
-}
-
-inline void QGLFunctions::glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetActiveAttrib(program, index, bufsize, length, size, type, name);
-}
-
-inline void QGLFunctions::glGetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetActiveUniform(program, index, bufsize, length, size, type, name);
-}
-
-inline void QGLFunctions::glGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetAttachedShaders(program, maxcount, count, shaders);
-}
-
-inline int QGLFunctions::glGetAttribLocation(GLuint program, const char* name)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glGetAttribLocation(program, name);
-}
-
-inline void QGLFunctions::glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetBufferParameteriv(target, pname, params);
-}
-
-inline void QGLFunctions::glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetFramebufferAttachmentParameteriv(target, attachment, pname, params);
-}
-
-inline void QGLFunctions::glGetProgramiv(GLuint program, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetProgramiv(program, pname, params);
-}
-
-inline void QGLFunctions::glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetProgramInfoLog(program, bufsize, length, infolog);
-}
-
-inline void QGLFunctions::glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetRenderbufferParameteriv(target, pname, params);
-}
-
-inline void QGLFunctions::glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetShaderiv(shader, pname, params);
-}
-
-inline void QGLFunctions::glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetShaderInfoLog(shader, bufsize, length, infolog);
-}
-
-inline void QGLFunctions::glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision);
-}
-
-inline void QGLFunctions::glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetShaderSource(shader, bufsize, length, source);
-}
-
-inline void QGLFunctions::glGetUniformfv(GLuint program, GLint location, GLfloat* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetUniformfv(program, location, params);
-}
-
-inline void QGLFunctions::glGetUniformiv(GLuint program, GLint location, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetUniformiv(program, location, params);
-}
-
-inline int QGLFunctions::glGetUniformLocation(GLuint program, const char* name)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glGetUniformLocation(program, name);
-}
-
-inline void QGLFunctions::glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetVertexAttribfv(index, pname, params);
-}
-
-inline void QGLFunctions::glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetVertexAttribiv(index, pname, params);
-}
-
-inline void QGLFunctions::glGetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glGetVertexAttribPointerv(index, pname, pointer);
-}
-
-inline GLboolean QGLFunctions::glIsBuffer(GLuint buffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glIsBuffer(buffer);
-}
-
-inline GLboolean QGLFunctions::glIsFramebuffer(GLuint framebuffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glIsFramebuffer(framebuffer);
-}
-
-inline GLboolean QGLFunctions::glIsProgram(GLuint program)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glIsProgram(program);
-}
-
-inline GLboolean QGLFunctions::glIsRenderbuffer(GLuint renderbuffer)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glIsRenderbuffer(renderbuffer);
-}
-
-inline GLboolean QGLFunctions::glIsShader(GLuint shader)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- return d_ptr->funcs->glIsShader(shader);
-}
-
-inline void QGLFunctions::glLinkProgram(GLuint program)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glLinkProgram(program);
-}
-
-inline void QGLFunctions::glReleaseShaderCompiler()
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glReleaseShaderCompiler();
-}
-
-inline void QGLFunctions::glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glRenderbufferStorage(target, internalformat, width, height);
-}
-
-inline void QGLFunctions::glSampleCoverage(GLclampf value, GLboolean invert)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glSampleCoverage(value, invert);
-}
-
-inline void QGLFunctions::glShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLint length)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glShaderBinary(n, shaders, binaryformat, binary, length);
-}
-
-inline void QGLFunctions::glShaderSource(GLuint shader, GLsizei count, const char** string, const GLint* length)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glShaderSource(shader, count, string, length);
-}
-
-inline void QGLFunctions::glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glStencilFuncSeparate(face, func, ref, mask);
-}
-
-inline void QGLFunctions::glStencilMaskSeparate(GLenum face, GLuint mask)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glStencilMaskSeparate(face, mask);
-}
-
-inline void QGLFunctions::glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glStencilOpSeparate(face, fail, zfail, zpass);
-}
-
-inline void QGLFunctions::glUniform1f(GLint location, GLfloat x)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform1f(location, x);
-}
-
-inline void QGLFunctions::glUniform1fv(GLint location, GLsizei count, const GLfloat* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform1fv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform1i(GLint location, GLint x)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform1i(location, x);
-}
-
-inline void QGLFunctions::glUniform1iv(GLint location, GLsizei count, const GLint* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform1iv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform2f(GLint location, GLfloat x, GLfloat y)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform2f(location, x, y);
-}
-
-inline void QGLFunctions::glUniform2fv(GLint location, GLsizei count, const GLfloat* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform2fv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform2i(GLint location, GLint x, GLint y)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform2i(location, x, y);
-}
-
-inline void QGLFunctions::glUniform2iv(GLint location, GLsizei count, const GLint* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform2iv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform3f(location, x, y, z);
-}
-
-inline void QGLFunctions::glUniform3fv(GLint location, GLsizei count, const GLfloat* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform3fv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform3i(GLint location, GLint x, GLint y, GLint z)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform3i(location, x, y, z);
-}
-
-inline void QGLFunctions::glUniform3iv(GLint location, GLsizei count, const GLint* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform3iv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform4f(location, x, y, z, w);
-}
-
-inline void QGLFunctions::glUniform4fv(GLint location, GLsizei count, const GLfloat* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform4fv(location, count, v);
-}
-
-inline void QGLFunctions::glUniform4i(GLint location, GLint x, GLint y, GLint z, GLint w)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform4i(location, x, y, z, w);
-}
-
-inline void QGLFunctions::glUniform4iv(GLint location, GLsizei count, const GLint* v)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniform4iv(location, count, v);
-}
-
-inline void QGLFunctions::glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniformMatrix2fv(location, count, transpose, value);
-}
-
-inline void QGLFunctions::glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniformMatrix3fv(location, count, transpose, value);
-}
-
-inline void QGLFunctions::glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUniformMatrix4fv(location, count, transpose, value);
-}
-
-inline void QGLFunctions::glUseProgram(GLuint program)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glUseProgram(program);
-}
-
-inline void QGLFunctions::glValidateProgram(GLuint program)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glValidateProgram(program);
-}
-
-inline void QGLFunctions::glVertexAttrib1f(GLuint indx, GLfloat x)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib1f(indx, x);
-}
-
-inline void QGLFunctions::glVertexAttrib1fv(GLuint indx, const GLfloat* values)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib1fv(indx, values);
-}
-
-inline void QGLFunctions::glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib2f(indx, x, y);
-}
-
-inline void QGLFunctions::glVertexAttrib2fv(GLuint indx, const GLfloat* values)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib2fv(indx, values);
-}
-
-inline void QGLFunctions::glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib3f(indx, x, y, z);
-}
-
-inline void QGLFunctions::glVertexAttrib3fv(GLuint indx, const GLfloat* values)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib3fv(indx, values);
-}
-
-inline void QGLFunctions::glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib4f(indx, x, y, z, w);
-}
-
-inline void QGLFunctions::glVertexAttrib4fv(GLuint indx, const GLfloat* values)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttrib4fv(indx, values);
-}
-
-inline void QGLFunctions::glVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
-{
- Q_ASSERT(QGLFunctions::isInitialized(d_ptr));
- d_ptr->funcs->glVertexAttribPointer(indx, size, type, normalized, stride, ptr);
-}
-
-#ifndef GL_ACTIVE_ATTRIBUTE_MAX_LENGTH
-#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
-#endif
-#ifndef GL_ACTIVE_ATTRIBUTES
-#define GL_ACTIVE_ATTRIBUTES 0x8B89
-#endif
-#ifndef GL_ACTIVE_TEXTURE
-#define GL_ACTIVE_TEXTURE 0x84E0
-#endif
-#ifndef GL_ACTIVE_UNIFORM_MAX_LENGTH
-#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
-#endif
-#ifndef GL_ACTIVE_UNIFORMS
-#define GL_ACTIVE_UNIFORMS 0x8B86
-#endif
-#ifndef GL_ALIASED_LINE_WIDTH_RANGE
-#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
-#endif
-#ifndef GL_ALIASED_POINT_SIZE_RANGE
-#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
-#endif
-#ifndef GL_ALPHA
-#define GL_ALPHA 0x1906
-#endif
-#ifndef GL_ALPHA_BITS
-#define GL_ALPHA_BITS 0x0D55
-#endif
-#ifndef GL_ALWAYS
-#define GL_ALWAYS 0x0207
-#endif
-#ifndef GL_ARRAY_BUFFER
-#define GL_ARRAY_BUFFER 0x8892
-#endif
-#ifndef GL_ARRAY_BUFFER_BINDING
-#define GL_ARRAY_BUFFER_BINDING 0x8894
-#endif
-#ifndef GL_ATTACHED_SHADERS
-#define GL_ATTACHED_SHADERS 0x8B85
-#endif
-#ifndef GL_BACK
-#define GL_BACK 0x0405
-#endif
-#ifndef GL_BLEND
-#define GL_BLEND 0x0BE2
-#endif
-#ifndef GL_BLEND_COLOR
-#define GL_BLEND_COLOR 0x8005
-#endif
-#ifndef GL_BLEND_DST_ALPHA
-#define GL_BLEND_DST_ALPHA 0x80CA
-#endif
-#ifndef GL_BLEND_DST_RGB
-#define GL_BLEND_DST_RGB 0x80C8
-#endif
-#ifndef GL_BLEND_EQUATION
-#define GL_BLEND_EQUATION 0x8009
-#endif
-#ifndef GL_BLEND_EQUATION_ALPHA
-#define GL_BLEND_EQUATION_ALPHA 0x883D
-#endif
-#ifndef GL_BLEND_EQUATION_RGB
-#define GL_BLEND_EQUATION_RGB 0x8009
-#endif
-#ifndef GL_BLEND_SRC_ALPHA
-#define GL_BLEND_SRC_ALPHA 0x80CB
-#endif
-#ifndef GL_BLEND_SRC_RGB
-#define GL_BLEND_SRC_RGB 0x80C9
-#endif
-#ifndef GL_BLUE_BITS
-#define GL_BLUE_BITS 0x0D54
-#endif
-#ifndef GL_BOOL
-#define GL_BOOL 0x8B56
-#endif
-#ifndef GL_BOOL_VEC2
-#define GL_BOOL_VEC2 0x8B57
-#endif
-#ifndef GL_BOOL_VEC3
-#define GL_BOOL_VEC3 0x8B58
-#endif
-#ifndef GL_BOOL_VEC4
-#define GL_BOOL_VEC4 0x8B59
-#endif
-#ifndef GL_BUFFER_SIZE
-#define GL_BUFFER_SIZE 0x8764
-#endif
-#ifndef GL_BUFFER_USAGE
-#define GL_BUFFER_USAGE 0x8765
-#endif
-#ifndef GL_BYTE
-#define GL_BYTE 0x1400
-#endif
-#ifndef GL_CCW
-#define GL_CCW 0x0901
-#endif
-#ifndef GL_CLAMP_TO_EDGE
-#define GL_CLAMP_TO_EDGE 0x812F
-#endif
-#ifndef GL_COLOR_ATTACHMENT0
-#define GL_COLOR_ATTACHMENT0 0x8CE0
-#endif
-#ifndef GL_COLOR_BUFFER_BIT
-#define GL_COLOR_BUFFER_BIT 0x00004000
-#endif
-#ifndef GL_COLOR_CLEAR_VALUE
-#define GL_COLOR_CLEAR_VALUE 0x0C22
-#endif
-#ifndef GL_COLOR_WRITEMASK
-#define GL_COLOR_WRITEMASK 0x0C23
-#endif
-#ifndef GL_COMPILE_STATUS
-#define GL_COMPILE_STATUS 0x8B81
-#endif
-#ifndef GL_COMPRESSED_TEXTURE_FORMATS
-#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
-#endif
-#ifndef GL_CONSTANT_ALPHA
-#define GL_CONSTANT_ALPHA 0x8003
-#endif
-#ifndef GL_CONSTANT_COLOR
-#define GL_CONSTANT_COLOR 0x8001
-#endif
-#ifndef GL_CULL_FACE
-#define GL_CULL_FACE 0x0B44
-#endif
-#ifndef GL_CULL_FACE_MODE
-#define GL_CULL_FACE_MODE 0x0B45
-#endif
-#ifndef GL_CURRENT_PROGRAM
-#define GL_CURRENT_PROGRAM 0x8B8D
-#endif
-#ifndef GL_CURRENT_VERTEX_ATTRIB
-#define GL_CURRENT_VERTEX_ATTRIB 0x8626
-#endif
-#ifndef GL_CW
-#define GL_CW 0x0900
-#endif
-#ifndef GL_DECR
-#define GL_DECR 0x1E03
-#endif
-#ifndef GL_DECR_WRAP
-#define GL_DECR_WRAP 0x8508
-#endif
-#ifndef GL_DELETE_STATUS
-#define GL_DELETE_STATUS 0x8B80
-#endif
-#ifndef GL_DEPTH_ATTACHMENT
-#define GL_DEPTH_ATTACHMENT 0x8D00
-#endif
-#ifndef GL_DEPTH_BITS
-#define GL_DEPTH_BITS 0x0D56
-#endif
-#ifndef GL_DEPTH_BUFFER_BIT
-#define GL_DEPTH_BUFFER_BIT 0x00000100
-#endif
-#ifndef GL_DEPTH_CLEAR_VALUE
-#define GL_DEPTH_CLEAR_VALUE 0x0B73
-#endif
-#ifndef GL_DEPTH_COMPONENT
-#define GL_DEPTH_COMPONENT 0x1902
-#endif
-#ifndef GL_DEPTH_COMPONENT16
-#define GL_DEPTH_COMPONENT16 0x81A5
-#endif
-#ifndef GL_DEPTH_FUNC
-#define GL_DEPTH_FUNC 0x0B74
-#endif
-#ifndef GL_DEPTH_RANGE
-#define GL_DEPTH_RANGE 0x0B70
-#endif
-#ifndef GL_DEPTH_TEST
-#define GL_DEPTH_TEST 0x0B71
-#endif
-#ifndef GL_DEPTH_WRITEMASK
-#define GL_DEPTH_WRITEMASK 0x0B72
-#endif
-#ifndef GL_DITHER
-#define GL_DITHER 0x0BD0
-#endif
-#ifndef GL_DONT_CARE
-#define GL_DONT_CARE 0x1100
-#endif
-#ifndef GL_DST_ALPHA
-#define GL_DST_ALPHA 0x0304
-#endif
-#ifndef GL_DST_COLOR
-#define GL_DST_COLOR 0x0306
-#endif
-#ifndef GL_DYNAMIC_DRAW
-#define GL_DYNAMIC_DRAW 0x88E8
-#endif
-#ifndef GL_ELEMENT_ARRAY_BUFFER
-#define GL_ELEMENT_ARRAY_BUFFER 0x8893
-#endif
-#ifndef GL_ELEMENT_ARRAY_BUFFER_BINDING
-#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
-#endif
-#ifndef GL_EQUAL
-#define GL_EQUAL 0x0202
-#endif
-#ifndef GL_EXTENSIONS
-#define GL_EXTENSIONS 0x1F03
-#endif
-#ifndef GL_FALSE
-#define GL_FALSE 0
-#endif
-#ifndef GL_FASTEST
-#define GL_FASTEST 0x1101
-#endif
-#ifndef GL_FIXED
-#define GL_FIXED 0x140C
-#endif
-#ifndef GL_FLOAT
-#define GL_FLOAT 0x1406
-#endif
-#ifndef GL_FLOAT_MAT2
-#define GL_FLOAT_MAT2 0x8B5A
-#endif
-#ifndef GL_FLOAT_MAT3
-#define GL_FLOAT_MAT3 0x8B5B
-#endif
-#ifndef GL_FLOAT_MAT4
-#define GL_FLOAT_MAT4 0x8B5C
-#endif
-#ifndef GL_FLOAT_VEC2
-#define GL_FLOAT_VEC2 0x8B50
-#endif
-#ifndef GL_FLOAT_VEC3
-#define GL_FLOAT_VEC3 0x8B51
-#endif
-#ifndef GL_FLOAT_VEC4
-#define GL_FLOAT_VEC4 0x8B52
-#endif
-#ifndef GL_FRAGMENT_SHADER
-#define GL_FRAGMENT_SHADER 0x8B30
-#endif
-#ifndef GL_FRAMEBUFFER
-#define GL_FRAMEBUFFER 0x8D40
-#endif
-#ifndef GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
-#endif
-#ifndef GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
-#endif
-#ifndef GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
-#endif
-#ifndef GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
-#endif
-#ifndef GL_FRAMEBUFFER_BINDING
-#define GL_FRAMEBUFFER_BINDING 0x8CA6
-#endif
-#ifndef GL_FRAMEBUFFER_COMPLETE
-#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
-#endif
-#ifndef GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
-#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
-#endif
-#ifndef GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS
-#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9
-#endif
-#ifndef GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
-#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
-#endif
-#ifndef GL_FRAMEBUFFER_UNSUPPORTED
-#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
-#endif
-#ifndef GL_FRONT
-#define GL_FRONT 0x0404
-#endif
-#ifndef GL_FRONT_AND_BACK
-#define GL_FRONT_AND_BACK 0x0408
-#endif
-#ifndef GL_FRONT_FACE
-#define GL_FRONT_FACE 0x0B46
-#endif
-#ifndef GL_FUNC_ADD
-#define GL_FUNC_ADD 0x8006
-#endif
-#ifndef GL_FUNC_REVERSE_SUBTRACT
-#define GL_FUNC_REVERSE_SUBTRACT 0x800B
-#endif
-#ifndef GL_FUNC_SUBTRACT
-#define GL_FUNC_SUBTRACT 0x800A
-#endif
-#ifndef GL_GENERATE_MIPMAP_HINT
-#define GL_GENERATE_MIPMAP_HINT 0x8192
-#endif
-#ifndef GL_GEQUAL
-#define GL_GEQUAL 0x0206
-#endif
-#ifndef GL_GREATER
-#define GL_GREATER 0x0204
-#endif
-#ifndef GL_GREEN_BITS
-#define GL_GREEN_BITS 0x0D53
-#endif
-#ifndef GL_HIGH_FLOAT
-#define GL_HIGH_FLOAT 0x8DF2
-#endif
-#ifndef GL_HIGH_INT
-#define GL_HIGH_INT 0x8DF5
-#endif
-#ifndef GL_IMPLEMENTATION_COLOR_READ_FORMAT
-#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
-#endif
-#ifndef GL_IMPLEMENTATION_COLOR_READ_TYPE
-#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A
-#endif
-#ifndef GL_INCR
-#define GL_INCR 0x1E02
-#endif
-#ifndef GL_INCR_WRAP
-#define GL_INCR_WRAP 0x8507
-#endif
-#ifndef GL_INFO_LOG_LENGTH
-#define GL_INFO_LOG_LENGTH 0x8B84
-#endif
-#ifndef GL_INT
-#define GL_INT 0x1404
-#endif
-#ifndef GL_INT_VEC2
-#define GL_INT_VEC2 0x8B53
-#endif
-#ifndef GL_INT_VEC3
-#define GL_INT_VEC3 0x8B54
-#endif
-#ifndef GL_INT_VEC4
-#define GL_INT_VEC4 0x8B55
-#endif
-#ifndef GL_INVALID_ENUM
-#define GL_INVALID_ENUM 0x0500
-#endif
-#ifndef GL_INVALID_FRAMEBUFFER_OPERATION
-#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
-#endif
-#ifndef GL_INVALID_OPERATION
-#define GL_INVALID_OPERATION 0x0502
-#endif
-#ifndef GL_INVALID_VALUE
-#define GL_INVALID_VALUE 0x0501
-#endif
-#ifndef GL_INVERT
-#define GL_INVERT 0x150A
-#endif
-#ifndef GL_KEEP
-#define GL_KEEP 0x1E00
-#endif
-#ifndef GL_LEQUAL
-#define GL_LEQUAL 0x0203
-#endif
-#ifndef GL_LESS
-#define GL_LESS 0x0201
-#endif
-#ifndef GL_LINEAR
-#define GL_LINEAR 0x2601
-#endif
-#ifndef GL_LINEAR_MIPMAP_LINEAR
-#define GL_LINEAR_MIPMAP_LINEAR 0x2703
-#endif
-#ifndef GL_LINEAR_MIPMAP_NEAREST
-#define GL_LINEAR_MIPMAP_NEAREST 0x2701
-#endif
-#ifndef GL_LINE_LOOP
-#define GL_LINE_LOOP 0x0002
-#endif
-#ifndef GL_LINES
-#define GL_LINES 0x0001
-#endif
-#ifndef GL_LINE_STRIP
-#define GL_LINE_STRIP 0x0003
-#endif
-#ifndef GL_LINE_WIDTH
-#define GL_LINE_WIDTH 0x0B21
-#endif
-#ifndef GL_LINK_STATUS
-#define GL_LINK_STATUS 0x8B82
-#endif
-#ifndef GL_LOW_FLOAT
-#define GL_LOW_FLOAT 0x8DF0
-#endif
-#ifndef GL_LOW_INT
-#define GL_LOW_INT 0x8DF3
-#endif
-#ifndef GL_LUMINANCE
-#define GL_LUMINANCE 0x1909
-#endif
-#ifndef GL_LUMINANCE_ALPHA
-#define GL_LUMINANCE_ALPHA 0x190A
-#endif
-#ifndef GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
-#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
-#endif
-#ifndef GL_MAX_CUBE_MAP_TEXTURE_SIZE
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
-#endif
-#ifndef GL_MAX_FRAGMENT_UNIFORM_VECTORS
-#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD
-#endif
-#ifndef GL_MAX_RENDERBUFFER_SIZE
-#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
-#endif
-#ifndef GL_MAX_TEXTURE_IMAGE_UNITS
-#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
-#endif
-#ifndef GL_MAX_TEXTURE_SIZE
-#define GL_MAX_TEXTURE_SIZE 0x0D33
-#endif
-#ifndef GL_MAX_VARYING_VECTORS
-#define GL_MAX_VARYING_VECTORS 0x8DFC
-#endif
-#ifndef GL_MAX_VERTEX_ATTRIBS
-#define GL_MAX_VERTEX_ATTRIBS 0x8869
-#endif
-#ifndef GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS
-#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
-#endif
-#ifndef GL_MAX_VERTEX_UNIFORM_VECTORS
-#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB
-#endif
-#ifndef GL_MAX_VIEWPORT_DIMS
-#define GL_MAX_VIEWPORT_DIMS 0x0D3A
-#endif
-#ifndef GL_MEDIUM_FLOAT
-#define GL_MEDIUM_FLOAT 0x8DF1
-#endif
-#ifndef GL_MEDIUM_INT
-#define GL_MEDIUM_INT 0x8DF4
-#endif
-#ifndef GL_MIRRORED_REPEAT
-#define GL_MIRRORED_REPEAT 0x8370
-#endif
-#ifndef GL_NEAREST
-#define GL_NEAREST 0x2600
-#endif
-#ifndef GL_NEAREST_MIPMAP_LINEAR
-#define GL_NEAREST_MIPMAP_LINEAR 0x2702
-#endif
-#ifndef GL_NEAREST_MIPMAP_NEAREST
-#define GL_NEAREST_MIPMAP_NEAREST 0x2700
-#endif
-#ifndef GL_NEVER
-#define GL_NEVER 0x0200
-#endif
-#ifndef GL_NICEST
-#define GL_NICEST 0x1102
-#endif
-#ifndef GL_NO_ERROR
-#define GL_NO_ERROR 0
-#endif
-#ifndef GL_NONE
-#define GL_NONE 0
-#endif
-#ifndef GL_NOTEQUAL
-#define GL_NOTEQUAL 0x0205
-#endif
-#ifndef GL_NUM_COMPRESSED_TEXTURE_FORMATS
-#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
-#endif
-#ifndef GL_NUM_SHADER_BINARY_FORMATS
-#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9
-#endif
-#ifndef GL_ONE
-#define GL_ONE 1
-#endif
-#ifndef GL_ONE_MINUS_CONSTANT_ALPHA
-#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
-#endif
-#ifndef GL_ONE_MINUS_CONSTANT_COLOR
-#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
-#endif
-#ifndef GL_ONE_MINUS_DST_ALPHA
-#define GL_ONE_MINUS_DST_ALPHA 0x0305
-#endif
-#ifndef GL_ONE_MINUS_DST_COLOR
-#define GL_ONE_MINUS_DST_COLOR 0x0307
-#endif
-#ifndef GL_ONE_MINUS_SRC_ALPHA
-#define GL_ONE_MINUS_SRC_ALPHA 0x0303
-#endif
-#ifndef GL_ONE_MINUS_SRC_COLOR
-#define GL_ONE_MINUS_SRC_COLOR 0x0301
-#endif
-#ifndef GL_OUT_OF_MEMORY
-#define GL_OUT_OF_MEMORY 0x0505
-#endif
-#ifndef GL_PACK_ALIGNMENT
-#define GL_PACK_ALIGNMENT 0x0D05
-#endif
-#ifndef GL_POINTS
-#define GL_POINTS 0x0000
-#endif
-#ifndef GL_POLYGON_OFFSET_FACTOR
-#define GL_POLYGON_OFFSET_FACTOR 0x8038
-#endif
-#ifndef GL_POLYGON_OFFSET_FILL
-#define GL_POLYGON_OFFSET_FILL 0x8037
-#endif
-#ifndef GL_POLYGON_OFFSET_UNITS
-#define GL_POLYGON_OFFSET_UNITS 0x2A00
-#endif
-#ifndef GL_RED_BITS
-#define GL_RED_BITS 0x0D52
-#endif
-#ifndef GL_RENDERBUFFER
-#define GL_RENDERBUFFER 0x8D41
-#endif
-#ifndef GL_RENDERBUFFER_ALPHA_SIZE
-#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53
-#endif
-#ifndef GL_RENDERBUFFER_BINDING
-#define GL_RENDERBUFFER_BINDING 0x8CA7
-#endif
-#ifndef GL_RENDERBUFFER_BLUE_SIZE
-#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52
-#endif
-#ifndef GL_RENDERBUFFER_DEPTH_SIZE
-#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54
-#endif
-#ifndef GL_RENDERBUFFER_GREEN_SIZE
-#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51
-#endif
-#ifndef GL_RENDERBUFFER_HEIGHT
-#define GL_RENDERBUFFER_HEIGHT 0x8D43
-#endif
-#ifndef GL_RENDERBUFFER_INTERNAL_FORMAT
-#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44
-#endif
-#ifndef GL_RENDERBUFFER_RED_SIZE
-#define GL_RENDERBUFFER_RED_SIZE 0x8D50
-#endif
-#ifndef GL_RENDERBUFFER_STENCIL_SIZE
-#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55
-#endif
-#ifndef GL_RENDERBUFFER_WIDTH
-#define GL_RENDERBUFFER_WIDTH 0x8D42
-#endif
-#ifndef GL_RENDERER
-#define GL_RENDERER 0x1F01
-#endif
-#ifndef GL_REPEAT
-#define GL_REPEAT 0x2901
-#endif
-#ifndef GL_REPLACE
-#define GL_REPLACE 0x1E01
-#endif
-#ifndef GL_RGB
-#define GL_RGB 0x1907
-#endif
-#ifndef GL_RGB565
-#define GL_RGB565 0x8D62
-#endif
-#ifndef GL_RGB5_A1
-#define GL_RGB5_A1 0x8057
-#endif
-#ifndef GL_RGBA
-#define GL_RGBA 0x1908
-#endif
-#ifndef GL_RGBA4
-#define GL_RGBA4 0x8056
-#endif
-#ifndef GL_BGRA
-#define GL_BGRA 0x80E1
-#endif
-#ifndef GL_SAMPLE_ALPHA_TO_COVERAGE
-#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
-#endif
-#ifndef GL_SAMPLE_BUFFERS
-#define GL_SAMPLE_BUFFERS 0x80A8
-#endif
-#ifndef GL_SAMPLE_COVERAGE
-#define GL_SAMPLE_COVERAGE 0x80A0
-#endif
-#ifndef GL_SAMPLE_COVERAGE_INVERT
-#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
-#endif
-#ifndef GL_SAMPLE_COVERAGE_VALUE
-#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
-#endif
-#ifndef GL_SAMPLER_2D
-#define GL_SAMPLER_2D 0x8B5E
-#endif
-#ifndef GL_SAMPLER_CUBE
-#define GL_SAMPLER_CUBE 0x8B60
-#endif
-#ifndef GL_SAMPLES
-#define GL_SAMPLES 0x80A9
-#endif
-#ifndef GL_SCISSOR_BOX
-#define GL_SCISSOR_BOX 0x0C10
-#endif
-#ifndef GL_SCISSOR_TEST
-#define GL_SCISSOR_TEST 0x0C11
-#endif
-#ifndef GL_SHADER_BINARY_FORMATS
-#define GL_SHADER_BINARY_FORMATS 0x8DF8
-#endif
-#ifndef GL_SHADER_COMPILER
-#define GL_SHADER_COMPILER 0x8DFA
-#endif
-#ifndef GL_SHADER_SOURCE_LENGTH
-#define GL_SHADER_SOURCE_LENGTH 0x8B88
-#endif
-#ifndef GL_SHADER_TYPE
-#define GL_SHADER_TYPE 0x8B4F
-#endif
-#ifndef GL_SHADING_LANGUAGE_VERSION
-#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
-#endif
-#ifndef GL_SHORT
-#define GL_SHORT 0x1402
-#endif
-#ifndef GL_SRC_ALPHA
-#define GL_SRC_ALPHA 0x0302
-#endif
-#ifndef GL_SRC_ALPHA_SATURATE
-#define GL_SRC_ALPHA_SATURATE 0x0308
-#endif
-#ifndef GL_SRC_COLOR
-#define GL_SRC_COLOR 0x0300
-#endif
-#ifndef GL_STATIC_DRAW
-#define GL_STATIC_DRAW 0x88E4
-#endif
-#ifndef GL_STENCIL_ATTACHMENT
-#define GL_STENCIL_ATTACHMENT 0x8D20
-#endif
-#ifndef GL_STENCIL_BACK_FAIL
-#define GL_STENCIL_BACK_FAIL 0x8801
-#endif
-#ifndef GL_STENCIL_BACK_FUNC
-#define GL_STENCIL_BACK_FUNC 0x8800
-#endif
-#ifndef GL_STENCIL_BACK_PASS_DEPTH_FAIL
-#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
-#endif
-#ifndef GL_STENCIL_BACK_PASS_DEPTH_PASS
-#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
-#endif
-#ifndef GL_STENCIL_BACK_REF
-#define GL_STENCIL_BACK_REF 0x8CA3
-#endif
-#ifndef GL_STENCIL_BACK_VALUE_MASK
-#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
-#endif
-#ifndef GL_STENCIL_BACK_WRITEMASK
-#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
-#endif
-#ifndef GL_STENCIL_BITS
-#define GL_STENCIL_BITS 0x0D57
-#endif
-#ifndef GL_STENCIL_BUFFER_BIT
-#define GL_STENCIL_BUFFER_BIT 0x00000400
-#endif
-#ifndef GL_STENCIL_CLEAR_VALUE
-#define GL_STENCIL_CLEAR_VALUE 0x0B91
-#endif
-#ifndef GL_STENCIL_FAIL
-#define GL_STENCIL_FAIL 0x0B94
-#endif
-#ifndef GL_STENCIL_FUNC
-#define GL_STENCIL_FUNC 0x0B92
-#endif
-#ifndef GL_STENCIL_INDEX
-#define GL_STENCIL_INDEX 0x1901
-#endif
-#ifndef GL_STENCIL_INDEX8
-#define GL_STENCIL_INDEX8 0x8D48
-#endif
-#ifndef GL_STENCIL_PASS_DEPTH_FAIL
-#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95
-#endif
-#ifndef GL_STENCIL_PASS_DEPTH_PASS
-#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96
-#endif
-#ifndef GL_STENCIL_REF
-#define GL_STENCIL_REF 0x0B97
-#endif
-#ifndef GL_STENCIL_TEST
-#define GL_STENCIL_TEST 0x0B90
-#endif
-#ifndef GL_STENCIL_VALUE_MASK
-#define GL_STENCIL_VALUE_MASK 0x0B93
-#endif
-#ifndef GL_STENCIL_WRITEMASK
-#define GL_STENCIL_WRITEMASK 0x0B98
-#endif
-#ifndef GL_STREAM_DRAW
-#define GL_STREAM_DRAW 0x88E0
-#endif
-#ifndef GL_SUBPIXEL_BITS
-#define GL_SUBPIXEL_BITS 0x0D50
-#endif
-#ifndef GL_TEXTURE0
-#define GL_TEXTURE0 0x84C0
-#endif
-#ifndef GL_TEXTURE
-#define GL_TEXTURE 0x1702
-#endif
-#ifndef GL_TEXTURE10
-#define GL_TEXTURE10 0x84CA
-#endif
-#ifndef GL_TEXTURE1
-#define GL_TEXTURE1 0x84C1
-#endif
-#ifndef GL_TEXTURE11
-#define GL_TEXTURE11 0x84CB
-#endif
-#ifndef GL_TEXTURE12
-#define GL_TEXTURE12 0x84CC
-#endif
-#ifndef GL_TEXTURE13
-#define GL_TEXTURE13 0x84CD
-#endif
-#ifndef GL_TEXTURE14
-#define GL_TEXTURE14 0x84CE
-#endif
-#ifndef GL_TEXTURE15
-#define GL_TEXTURE15 0x84CF
-#endif
-#ifndef GL_TEXTURE16
-#define GL_TEXTURE16 0x84D0
-#endif
-#ifndef GL_TEXTURE17
-#define GL_TEXTURE17 0x84D1
-#endif
-#ifndef GL_TEXTURE18
-#define GL_TEXTURE18 0x84D2
-#endif
-#ifndef GL_TEXTURE19
-#define GL_TEXTURE19 0x84D3
-#endif
-#ifndef GL_TEXTURE20
-#define GL_TEXTURE20 0x84D4
-#endif
-#ifndef GL_TEXTURE2
-#define GL_TEXTURE2 0x84C2
-#endif
-#ifndef GL_TEXTURE21
-#define GL_TEXTURE21 0x84D5
-#endif
-#ifndef GL_TEXTURE22
-#define GL_TEXTURE22 0x84D6
-#endif
-#ifndef GL_TEXTURE23
-#define GL_TEXTURE23 0x84D7
-#endif
-#ifndef GL_TEXTURE24
-#define GL_TEXTURE24 0x84D8
-#endif
-#ifndef GL_TEXTURE25
-#define GL_TEXTURE25 0x84D9
-#endif
-#ifndef GL_TEXTURE26
-#define GL_TEXTURE26 0x84DA
-#endif
-#ifndef GL_TEXTURE27
-#define GL_TEXTURE27 0x84DB
-#endif
-#ifndef GL_TEXTURE28
-#define GL_TEXTURE28 0x84DC
-#endif
-#ifndef GL_TEXTURE29
-#define GL_TEXTURE29 0x84DD
-#endif
-#ifndef GL_TEXTURE_2D
-#define GL_TEXTURE_2D 0x0DE1
-#endif
-#ifndef GL_TEXTURE30
-#define GL_TEXTURE30 0x84DE
-#endif
-#ifndef GL_TEXTURE3
-#define GL_TEXTURE3 0x84C3
-#endif
-#ifndef GL_TEXTURE31
-#define GL_TEXTURE31 0x84DF
-#endif
-#ifndef GL_TEXTURE4
-#define GL_TEXTURE4 0x84C4
-#endif
-#ifndef GL_TEXTURE5
-#define GL_TEXTURE5 0x84C5
-#endif
-#ifndef GL_TEXTURE6
-#define GL_TEXTURE6 0x84C6
-#endif
-#ifndef GL_TEXTURE7
-#define GL_TEXTURE7 0x84C7
-#endif
-#ifndef GL_TEXTURE8
-#define GL_TEXTURE8 0x84C8
-#endif
-#ifndef GL_TEXTURE9
-#define GL_TEXTURE9 0x84C9
-#endif
-#ifndef GL_TEXTURE_BINDING_2D
-#define GL_TEXTURE_BINDING_2D 0x8069
-#endif
-#ifndef GL_TEXTURE_BINDING_CUBE_MAP
-#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP
-#define GL_TEXTURE_CUBE_MAP 0x8513
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_NEGATIVE_X
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_POSITIVE_X
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_POSITIVE_Y
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
-#endif
-#ifndef GL_TEXTURE_CUBE_MAP_POSITIVE_Z
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
-#endif
-#ifndef GL_TEXTURE_MAG_FILTER
-#define GL_TEXTURE_MAG_FILTER 0x2800
-#endif
-#ifndef GL_TEXTURE_MIN_FILTER
-#define GL_TEXTURE_MIN_FILTER 0x2801
-#endif
-#ifndef GL_TEXTURE_WRAP_S
-#define GL_TEXTURE_WRAP_S 0x2802
-#endif
-#ifndef GL_TEXTURE_WRAP_T
-#define GL_TEXTURE_WRAP_T 0x2803
-#endif
-#ifndef GL_TRIANGLE_FAN
-#define GL_TRIANGLE_FAN 0x0006
-#endif
-#ifndef GL_TRIANGLES
-#define GL_TRIANGLES 0x0004
-#endif
-#ifndef GL_TRIANGLE_STRIP
-#define GL_TRIANGLE_STRIP 0x0005
-#endif
-#ifndef GL_TRUE
-#define GL_TRUE 1
-#endif
-#ifndef GL_UNPACK_ALIGNMENT
-#define GL_UNPACK_ALIGNMENT 0x0CF5
-#endif
-#ifndef GL_UNSIGNED_BYTE
-#define GL_UNSIGNED_BYTE 0x1401
-#endif
-#ifndef GL_UNSIGNED_INT
-#define GL_UNSIGNED_INT 0x1405
-#endif
-#ifndef GL_UNSIGNED_SHORT
-#define GL_UNSIGNED_SHORT 0x1403
-#endif
-#ifndef GL_UNSIGNED_SHORT_4_4_4_4
-#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
-#endif
-#ifndef GL_UNSIGNED_SHORT_5_5_5_1
-#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
-#endif
-#ifndef GL_UNSIGNED_SHORT_5_6_5
-#define GL_UNSIGNED_SHORT_5_6_5 0x8363
-#endif
-#ifndef GL_VALIDATE_STATUS
-#define GL_VALIDATE_STATUS 0x8B83
-#endif
-#ifndef GL_VENDOR
-#define GL_VENDOR 0x1F00
-#endif
-#ifndef GL_VERSION
-#define GL_VERSION 0x1F02
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING
-#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_ENABLED
-#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_NORMALIZED
-#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_POINTER
-#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_SIZE
-#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_STRIDE
-#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
-#endif
-#ifndef GL_VERTEX_ATTRIB_ARRAY_TYPE
-#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
-#endif
-#ifndef GL_VERTEX_SHADER
-#define GL_VERTEX_SHADER 0x8B31
-#endif
-#ifndef GL_VIEWPORT
-#define GL_VIEWPORT 0x0BA2
-#endif
-#ifndef GL_ZERO
-#define GL_ZERO 0
-#endif
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/opengl/qglpaintdevice.cpp b/src/opengl/qglpaintdevice.cpp
deleted file mode 100644
index c5151f66bb..0000000000
--- a/src/opengl/qglpaintdevice.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qglpaintdevice_p.h>
-#include <private/qgl_p.h>
-#include <private/qglpixelbuffer_p.h>
-#include <private/qglframebufferobject_p.h>
-#include <qopenglfunctions.h>
-#include <qwindow.h>
-
-QT_BEGIN_NAMESPACE
-
-QGLPaintDevice::QGLPaintDevice()
- : m_thisFBO(0)
-{
-}
-
-QGLPaintDevice::~QGLPaintDevice()
-{
-}
-
-int QGLPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const
-{
- switch(metric) {
- case PdmWidth:
- return size().width();
- case PdmHeight:
- return size().height();
- case PdmDepth: {
- const QGLFormat f = format();
- return f.redBufferSize() + f.greenBufferSize() + f.blueBufferSize() + f.alphaBufferSize();
- }
- case PdmDevicePixelRatio:
- return 1;
- case PdmDevicePixelRatioScaled:
- return 1 * QPaintDevice::devicePixelRatioFScale();
- default:
- qWarning("QGLPaintDevice::metric() - metric %d not known", metric);
- return 0;
- }
-}
-
-void QGLPaintDevice::beginPaint()
-{
- // Make sure our context is the current one:
- QGLContext *ctx = context();
- ctx->makeCurrent();
-
- ctx->d_func()->refreshCurrentFbo();
-
- // Record the currently bound FBO so we can restore it again
- // in endPaint() and bind this device's FBO
- //
- // Note: m_thisFBO could be zero if the paint device is not
- // backed by an FBO (e.g. window back buffer). But there could
- // be a previous FBO bound to the context which we need to
- // explicitly unbind. Otherwise the painting will go into
- // the previous FBO instead of to the window.
- m_previousFBO = ctx->d_func()->current_fbo;
-
- if (m_previousFBO != m_thisFBO) {
- ctx->d_func()->setCurrentFbo(m_thisFBO);
- ctx->contextHandle()->functions()->glBindFramebuffer(GL_FRAMEBUFFER, m_thisFBO);
- }
-
- // Set the default fbo for the context to m_thisFBO so that
- // if some raw GL code between beginNativePainting() and
- // endNativePainting() calls QGLFramebufferObject::release(),
- // painting will revert to the window surface's fbo.
- ctx->d_ptr->default_fbo = m_thisFBO;
-}
-
-void QGLPaintDevice::ensureActiveTarget()
-{
- QGLContext* ctx = context();
- if (ctx != QGLContext::currentContext())
- ctx->makeCurrent();
-
- ctx->d_func()->refreshCurrentFbo();
-
- if (ctx->d_ptr->current_fbo != m_thisFBO) {
- ctx->d_func()->setCurrentFbo(m_thisFBO);
- ctx->contextHandle()->functions()->glBindFramebuffer(GL_FRAMEBUFFER, m_thisFBO);
- }
-
- ctx->d_ptr->default_fbo = m_thisFBO;
-}
-
-void QGLPaintDevice::endPaint()
-{
- // Make sure the FBO bound at beginPaint is re-bound again here:
- QGLContext *ctx = context();
- ctx->makeCurrent();
-
- ctx->d_func()->refreshCurrentFbo();
-
- if (m_previousFBO != ctx->d_func()->current_fbo) {
- ctx->d_func()->setCurrentFbo(m_previousFBO);
- ctx->contextHandle()->functions()->glBindFramebuffer(GL_FRAMEBUFFER, m_previousFBO);
- }
-
- ctx->d_ptr->default_fbo = 0;
-}
-
-QGLFormat QGLPaintDevice::format() const
-{
- return context()->format();
-}
-
-bool QGLPaintDevice::alphaRequested() const
-{
- return context()->d_func()->reqFormat.alpha();
-}
-
-bool QGLPaintDevice::isFlipped() const
-{
- return false;
-}
-
-////////////////// QGLWidgetGLPaintDevice //////////////////
-
-QGLWidgetGLPaintDevice::QGLWidgetGLPaintDevice()
-{
-}
-
-QPaintEngine* QGLWidgetGLPaintDevice::paintEngine() const
-{
- return glWidget->paintEngine();
-}
-
-void QGLWidgetGLPaintDevice::setWidget(QGLWidget* w)
-{
- glWidget = w;
-}
-
-void QGLWidgetGLPaintDevice::beginPaint()
-{
- QGLPaintDevice::beginPaint();
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- if (!glWidget->d_func()->disable_clear_on_painter_begin && glWidget->autoFillBackground()) {
- if (glWidget->testAttribute(Qt::WA_TranslucentBackground))
- funcs->glClearColor(0.0, 0.0, 0.0, 0.0);
- else {
- const QColor &c = glWidget->palette().brush(glWidget->backgroundRole()).color();
- float alpha = c.alphaF();
- funcs->glClearColor(c.redF() * alpha, c.greenF() * alpha, c.blueF() * alpha, alpha);
- }
- if (context()->d_func()->workaround_needsFullClearOnEveryFrame)
- funcs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
- else
- funcs->glClear(GL_COLOR_BUFFER_BIT);
- }
-}
-
-void QGLWidgetGLPaintDevice::endPaint()
-{
- if (glWidget->autoBufferSwap())
- glWidget->swapBuffers();
- QGLPaintDevice::endPaint();
-}
-
-
-QSize QGLWidgetGLPaintDevice::size() const
-{
- return glWidget->size() * (glWidget->windowHandle() ?
- glWidget->windowHandle()->devicePixelRatio() : qApp->devicePixelRatio());
-}
-
-QGLContext* QGLWidgetGLPaintDevice::context() const
-{
- return const_cast<QGLContext*>(glWidget->context());
-}
-
-// returns the QGLPaintDevice for the given QPaintDevice
-QGLPaintDevice* QGLPaintDevice::getDevice(QPaintDevice* pd)
-{
- QGLPaintDevice* glpd = 0;
-
- switch(pd->devType()) {
- case QInternal::Widget:
- // Should not be called on a non-gl widget:
- Q_ASSERT(qobject_cast<QGLWidget*>(static_cast<QWidget*>(pd)));
- glpd = &(static_cast<QGLWidget*>(pd)->d_func()->glDevice);
- break;
- case QInternal::Pbuffer:
- glpd = &(static_cast<QGLPixelBuffer*>(pd)->d_func()->glDevice);
- break;
- case QInternal::FramebufferObject:
- glpd = &(static_cast<QGLFramebufferObject*>(pd)->d_func()->glDevice);
- break;
- case QInternal::Pixmap: {
- qWarning("Pixmap type not supported for GL rendering");
- break;
- }
- default:
- qWarning("QGLPaintDevice::getDevice() - Unknown device type %d", pd->devType());
- break;
- }
-
- return glpd;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp
deleted file mode 100644
index e2f434ac3c..0000000000
--- a/src/opengl/qglpixelbuffer.cpp
+++ /dev/null
@@ -1,654 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \class QGLPixelBuffer
- \inmodule QtOpenGL
- \brief The QGLPixelBuffer class encapsulates an OpenGL pbuffer.
- \since 4.1
- \obsolete
-
- \ingroup painting-3D
-
- Rendering into a pbuffer is normally done using full hardware
- acceleration. This can be significantly faster than rendering
- into a QPixmap.
-
- There are three approaches to using this class:
-
- \list 1
- \li \b{We can draw into the pbuffer and convert it to a QImage
- using toImage().} This is normally much faster than calling
- QGLWidget::renderPixmap().
-
- \li \b{We can draw into the pbuffer and copy the contents into
- an OpenGL texture using updateDynamicTexture().} This allows
- us to create dynamic textures and works on all systems
- with pbuffer support.
-
- \li \b{On systems that support it, we can bind the pbuffer to
- an OpenGL texture.} The texture is then updated automatically
- when the pbuffer contents change, eliminating the need for
- additional copy operations. This is supported only on Windows
- and \macos systems that provide the \c render_texture
- extension. Note that under Windows, a multi-sampled pbuffer
- can't be used in conjunction with the \c render_texture
- extension. If a multi-sampled pbuffer is requested under
- Windows, the \c render_texture extension is turned off for that
- pbuffer.
-
-
- \endlist
-
- \note This class has been deprecated, use QOpenGLFramebufferObject
- for offscreen rendering.
-
- \section1 Threading
-
- As of Qt 4.8, it's possible to render into a QGLPixelBuffer using
- a QPainter in a separate thread. Note that OpenGL 2.0 or OpenGL ES
- 2.0 is required for this to work.
-
- Pbuffers are provided by the OpenGL \c pbuffer extension; call
- hasOpenGLPbuffer() to find out if the system provides pbuffers.
-*/
-
-#include <private/qopenglextensions_p.h>
-
-#include <QtCore/qglobal.h>
-#include <QtGui/qopenglframebufferobject.h>
-
-#include "gl2paintengineex/qpaintengineex_opengl2_p.h"
-
-#include <qglframebufferobject.h>
-#include <qglpixelbuffer.h>
-#include <private/qglpixelbuffer_p.h>
-#include <private/qfont_p.h>
-#include <qimage.h>
-
-QT_BEGIN_NAMESPACE
-
-extern QImage qt_gl_read_frame_buffer(const QSize&, bool, bool);
-
-
-QGLContext* QGLPBufferGLPaintDevice::context() const
-{
- return pbuf->d_func()->qctx;
-}
-
-void QGLPBufferGLPaintDevice::beginPaint()
-{
- pbuf->makeCurrent();
- QGLPaintDevice::beginPaint();
-}
-
-void QGLPBufferGLPaintDevice::endPaint()
-{
- QOpenGLContext::currentContext()->functions()->glFlush();
- QGLPaintDevice::endPaint();
-}
-
-void QGLPBufferGLPaintDevice::setFbo(GLuint fbo)
-{
- m_thisFBO = fbo;
-}
-
-void QGLPBufferGLPaintDevice::setPBuffer(QGLPixelBuffer* pb)
-{
- pbuf = pb;
-}
-
-void QGLPixelBufferPrivate::common_init(const QSize &size, const QGLFormat &format, QGLWidget *shareWidget)
-{
- Q_Q(QGLPixelBuffer);
- if(init(size, format, shareWidget)) {
- req_size = size;
- req_format = format;
- req_shareWidget = shareWidget;
- invalid = false;
- glDevice.setPBuffer(q);
- }
-}
-
-/*!
- Constructs an OpenGL pbuffer of the given \a size. If no \a
- format is specified, the \l{QGLFormat::defaultFormat()}{default
- format} is used. If the \a shareWidget parameter points to a
- valid QGLWidget, the pbuffer will share its context with \a
- shareWidget.
-
- If you intend to bind this pbuffer as a dynamic texture, the width
- and height components of \c size must be powers of two (e.g., 512
- x 128).
-
- \sa size(), format()
-*/
-QGLPixelBuffer::QGLPixelBuffer(const QSize &size, const QGLFormat &format, QGLWidget *shareWidget)
- : d_ptr(new QGLPixelBufferPrivate(this))
-{
- Q_D(QGLPixelBuffer);
- d->common_init(size, format, shareWidget);
-}
-
-
-/*! \overload
-
- Constructs an OpenGL pbuffer with the \a width and \a height. If
- no \a format is specified, the
- \l{QGLFormat::defaultFormat()}{default format} is used. If the \a
- shareWidget parameter points to a valid QGLWidget, the pbuffer
- will share its context with \a shareWidget.
-
- If you intend to bind this pbuffer as a dynamic texture, the width
- and height components of \c size must be powers of two (e.g., 512
- x 128).
-
- \sa size(), format()
-*/
-QGLPixelBuffer::QGLPixelBuffer(int width, int height, const QGLFormat &format, QGLWidget *shareWidget)
- : d_ptr(new QGLPixelBufferPrivate(this))
-{
- Q_D(QGLPixelBuffer);
- d->common_init(QSize(width, height), format, shareWidget);
-}
-
-
-/*! \fn QGLPixelBuffer::~QGLPixelBuffer()
-
- Destroys the pbuffer and frees any allocated resources.
-*/
-QGLPixelBuffer::~QGLPixelBuffer()
-{
- Q_D(QGLPixelBuffer);
-
- // defined in qpaintengine_opengl.cpp
- QGLContext *current = const_cast<QGLContext *>(QGLContext::currentContext());
- if (current != d->qctx)
- makeCurrent();
- d->cleanup();
- if (current && current != d->qctx)
- current->makeCurrent();
-}
-
-/*! \fn bool QGLPixelBuffer::makeCurrent()
-
- Makes this pbuffer the current OpenGL rendering context. Returns
- true on success; otherwise returns \c false.
-
- \sa QGLContext::makeCurrent(), doneCurrent()
-*/
-
-bool QGLPixelBuffer::makeCurrent()
-{
- Q_D(QGLPixelBuffer);
- if (d->invalid)
- return false;
- d->qctx->makeCurrent();
- if (!d->fbo) {
- QOpenGLFramebufferObjectFormat format;
- if (d->req_format.stencil())
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- else if (d->req_format.depth())
- format.setAttachment(QOpenGLFramebufferObject::Depth);
- if (d->req_format.sampleBuffers())
- format.setSamples(d->req_format.samples());
- d->fbo = new QOpenGLFramebufferObject(d->req_size, format);
- d->fbo->bind();
- d->glDevice.setFbo(d->fbo->handle());
- QOpenGLContext::currentContext()->functions()->glViewport(0, 0, d->req_size.width(), d->req_size.height());
- }
- return true;
-}
-
-/*! \fn bool QGLPixelBuffer::doneCurrent()
-
- Makes no context the current OpenGL context. Returns \c true on
- success; otherwise returns \c false.
-*/
-
-bool QGLPixelBuffer::doneCurrent()
-{
- Q_D(QGLPixelBuffer);
- if (d->invalid)
- return false;
- d->qctx->doneCurrent();
- return true;
-}
-
-/*!
- Returns the context of this pixelbuffer.
-*/
-QGLContext *QGLPixelBuffer::context() const
-{
- Q_D(const QGLPixelBuffer);
- return d->qctx;
-}
-
-/*!
- \fn GLuint QGLPixelBuffer::generateDynamicTexture() const
-
- Generates and binds a 2D GL texture that is the same size as the
- pbuffer, and returns the texture's ID. This can be used in
- conjunction with bindToDynamicTexture() and
- updateDynamicTexture().
-
- \sa size()
-*/
-
-/*! \fn bool QGLPixelBuffer::bindToDynamicTexture(GLuint texture_id)
-
- Binds the texture specified by \a texture_id to this pbuffer.
- Returns \c true on success; otherwise returns \c false.
-
- The texture must be of the same size and format as the pbuffer.
-
- To unbind the texture, call releaseFromDynamicTexture(). While
- the texture is bound, it is updated automatically when the
- pbuffer contents change, eliminating the need for additional copy
- operations.
-
- Example:
-
- \snippet code/src_opengl_qglpixelbuffer.cpp 0
-
- \warning This function uses the \c {render_texture} extension,
- which is currently not supported under X11. An alternative that
- works on all systems (including X11) is to manually copy the
- pbuffer contents to a texture using updateDynamicTexture().
-
- \warning For the bindToDynamicTexture() call to succeed on the
- \macos, the pbuffer needs a shared context, i.e. the
- QGLPixelBuffer must be created with a share widget.
-
- \sa generateDynamicTexture(), releaseFromDynamicTexture()
-*/
-
-/*! \fn void QGLPixelBuffer::releaseFromDynamicTexture()
-
- Releases the pbuffer from any previously bound texture.
-
- \sa bindToDynamicTexture()
-*/
-
-/*! \fn bool QGLPixelBuffer::hasOpenGLPbuffers()
-
- Returns \c true if the OpenGL \c pbuffer extension is present on
- this system; otherwise returns \c false.
-*/
-
-/*!
- Copies the pbuffer contents into the texture specified with \a
- texture_id.
-
- The texture must be of the same size and format as the pbuffer.
-
- Example:
-
- \snippet code/src_opengl_qglpixelbuffer.cpp 1
-
- An alternative on Windows and \macos systems that support the
- \c render_texture extension is to use bindToDynamicTexture() to
- get dynamic updates of the texture.
-
- \sa generateDynamicTexture(), bindToDynamicTexture()
-*/
-void QGLPixelBuffer::updateDynamicTexture(GLuint texture_id) const
-{
- Q_D(const QGLPixelBuffer);
- if (d->invalid || !d->fbo)
- return;
-
- const QGLContext *ctx = QGLContext::currentContext();
- if (!ctx)
- return;
-
-#undef glBindFramebuffer
-
-#ifndef GL_READ_FRAMEBUFFER
-#define GL_READ_FRAMEBUFFER 0x8CA8
-#endif
-
-#ifndef GL_DRAW_FRAMEBUFFER
-#define GL_DRAW_FRAMEBUFFER 0x8CA9
-#endif
-
- QOpenGLExtensions extensions(ctx->contextHandle());
-
- ctx->d_ptr->refreshCurrentFbo();
-
- if (d->blit_fbo) {
- QOpenGLFramebufferObject::blitFramebuffer(d->blit_fbo, d->fbo);
- extensions.glBindFramebuffer(GL_READ_FRAMEBUFFER, d->blit_fbo->handle());
- }
-
- extensions.glBindTexture(GL_TEXTURE_2D, texture_id);
-#ifndef QT_OPENGL_ES
- GLenum format = ctx->contextHandle()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
- extensions.glCopyTexImage2D(GL_TEXTURE_2D, 0, format, 0, 0, d->req_size.width(), d->req_size.height(), 0);
-#else
- extensions.glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, d->req_size.width(), d->req_size.height(), 0);
-#endif
-
- if (d->blit_fbo)
- extensions.glBindFramebuffer(GL_READ_FRAMEBUFFER, ctx->d_func()->current_fbo);
-}
-
-/*!
- Returns the size of the pbuffer.
-*/
-QSize QGLPixelBuffer::size() const
-{
- Q_D(const QGLPixelBuffer);
- return d->req_size;
-}
-
-/*!
- Returns the contents of the pbuffer as a QImage.
-*/
-QImage QGLPixelBuffer::toImage() const
-{
- Q_D(const QGLPixelBuffer);
- if (d->invalid)
- return QImage();
-
- const_cast<QGLPixelBuffer *>(this)->makeCurrent();
- if (d->fbo)
- d->fbo->bind();
- return qt_gl_read_frame_buffer(d->req_size, d->format.alpha(), true);
-}
-
-/*!
- Returns the native pbuffer handle.
-*/
-Qt::HANDLE QGLPixelBuffer::handle() const
-{
- Q_D(const QGLPixelBuffer);
- if (d->invalid)
- return 0;
- return (Qt::HANDLE) d->pbuf;
-}
-
-/*!
- Returns \c true if this pbuffer is valid; otherwise returns \c false.
-*/
-bool QGLPixelBuffer::isValid() const
-{
- Q_D(const QGLPixelBuffer);
- return !d->invalid;
-}
-
-Q_GLOBAL_STATIC(QGLEngineThreadStorage<QGL2PaintEngineEx>, qt_buffer_2_engine)
-
-/*! \reimp */
-QPaintEngine *QGLPixelBuffer::paintEngine() const
-{
- return qt_buffer_2_engine()->engine();
-}
-
-/*! \reimp */
-int QGLPixelBuffer::metric(PaintDeviceMetric metric) const
-{
- Q_D(const QGLPixelBuffer);
-
- float dpmx = qt_defaultDpiX()*100./2.54;
- float dpmy = qt_defaultDpiY()*100./2.54;
- int w = d->req_size.width();
- int h = d->req_size.height();
- switch (metric) {
- case PdmWidth:
- return w;
-
- case PdmHeight:
- return h;
-
- case PdmWidthMM:
- return qRound(w * 1000 / dpmx);
-
- case PdmHeightMM:
- return qRound(h * 1000 / dpmy);
-
- case PdmNumColors:
- return 0;
-
- case PdmDepth:
- return 32;//d->depth;
-
- case PdmDpiX:
- return qRound(dpmx * 0.0254);
-
- case PdmDpiY:
- return qRound(dpmy * 0.0254);
-
- case PdmPhysicalDpiX:
- return qRound(dpmx * 0.0254);
-
- case PdmPhysicalDpiY:
- return qRound(dpmy * 0.0254);
-
- case QPaintDevice::PdmDevicePixelRatio:
- return 1;
-
- case QPaintDevice::PdmDevicePixelRatioScaled:
- return QPaintDevice::devicePixelRatioFScale();
-
- default:
- qWarning("QGLPixelBuffer::metric(), Unhandled metric type: %d\n", metric);
- break;
- }
- return 0;
-}
-
-/*!
- Generates and binds a 2D GL texture to the current context, based
- on \a image. The generated texture id is returned and can be used
- in later glBindTexture() calls.
-
- The \a target parameter specifies the texture target.
-
- Equivalent to calling QGLContext::bindTexture().
-
- \sa deleteTexture()
-*/
-GLuint QGLPixelBuffer::bindTexture(const QImage &image, GLenum target)
-{
- Q_D(QGLPixelBuffer);
-#ifndef QT_OPENGL_ES
- GLenum format = QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
- return d->qctx->bindTexture(image, target, GLint(format));
-#else
- return d->qctx->bindTexture(image, target, GL_RGBA);
-#endif
-}
-
-/*! \overload
-
- Generates and binds a 2D GL texture based on \a pixmap.
-
- Equivalent to calling QGLContext::bindTexture().
-
- \sa deleteTexture()
-*/
-GLuint QGLPixelBuffer::bindTexture(const QPixmap &pixmap, GLenum target)
-{
- Q_D(QGLPixelBuffer);
-#ifndef QT_OPENGL_ES
- GLenum format = QOpenGLContext::currentContext()->isOpenGLES() ? GL_RGBA : GL_RGBA8;
- return d->qctx->bindTexture(pixmap, target, GLint(format));
-#else
- return d->qctx->bindTexture(pixmap, target, GL_RGBA);
-#endif
-}
-
-/*! \overload
-
- Reads the DirectDrawSurface (DDS) compressed file \a fileName and
- generates a 2D GL texture from it.
-
- Equivalent to calling QGLContext::bindTexture().
-
- \sa deleteTexture()
-*/
-GLuint QGLPixelBuffer::bindTexture(const QString &fileName)
-{
- Q_D(QGLPixelBuffer);
- return d->qctx->bindTexture(fileName);
-}
-
-/*!
- Removes the texture identified by \a texture_id from the texture cache.
-
- Equivalent to calling QGLContext::deleteTexture().
- */
-void QGLPixelBuffer::deleteTexture(GLuint texture_id)
-{
- Q_D(QGLPixelBuffer);
- d->qctx->deleteTexture(texture_id);
-}
-
-/*!
- \since 4.4
-
- Draws the given texture, \a textureId, to the given target rectangle,
- \a target, in OpenGL model space. The \a textureTarget should be a 2D
- texture target.
-
- Equivalent to the corresponding QGLContext::drawTexture().
-*/
-void QGLPixelBuffer::drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget)
-{
- Q_D(QGLPixelBuffer);
- d->qctx->drawTexture(target, textureId, textureTarget);
-}
-
-/*!
- \since 4.4
-
- Draws the given texture, \a textureId, at the given \a point in OpenGL model
- space. The textureTarget parameter should be a 2D texture target.
-
- Equivalent to the corresponding QGLContext::drawTexture().
-*/
-void QGLPixelBuffer::drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget)
-{
- Q_D(QGLPixelBuffer);
- d->qctx->drawTexture(point, textureId, textureTarget);
-}
-
-/*!
- Returns the format of the pbuffer. The format may be different
- from the one that was requested.
-*/
-QGLFormat QGLPixelBuffer::format() const
-{
- Q_D(const QGLPixelBuffer);
- return d->format;
-}
-
-/*! \fn int QGLPixelBuffer::devType() const
- \internal
-*/
-
-bool QGLPixelBufferPrivate::init(const QSize &, const QGLFormat &f, QGLWidget *shareWidget)
-{
- widget = new QGLWidget(f, 0, shareWidget);
- widget->resize(1, 1);
- qctx = const_cast<QGLContext *>(widget->context());
- return widget->isValid();
-}
-
-bool QGLPixelBufferPrivate::cleanup()
-{
- delete fbo;
- fbo = 0;
- delete blit_fbo;
- blit_fbo = 0;
- delete widget;
- widget = 0;
- return true;
-}
-
-bool QGLPixelBuffer::bindToDynamicTexture(GLuint texture_id)
-{
- Q_UNUSED(texture_id);
- return false;
-}
-
-void QGLPixelBuffer::releaseFromDynamicTexture()
-{
-}
-
-GLuint QGLPixelBuffer::generateDynamicTexture() const
-{
- Q_D(const QGLPixelBuffer);
- if (!d->fbo)
- return 0;
-
- if (d->fbo->format().samples() > 0
- && QOpenGLExtensions(QOpenGLContext::currentContext())
- .hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit))
- {
- if (!d->blit_fbo)
- const_cast<QOpenGLFramebufferObject *&>(d->blit_fbo) = new QOpenGLFramebufferObject(d->req_size);
- } else {
- return d->fbo->texture();
- }
-
- GLuint texture;
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
-
- funcs->glGenTextures(1, &texture);
- funcs->glBindTexture(GL_TEXTURE_2D, texture);
-
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, d->req_size.width(), d->req_size.height(), 0,
- GL_RGBA, GL_UNSIGNED_BYTE, 0);
-
- return texture;
-}
-
-bool QGLPixelBuffer::hasOpenGLPbuffers()
-{
- return QGLFramebufferObject::hasOpenGLFramebufferObjects();
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglpixelbuffer.h b/src/opengl/qglpixelbuffer.h
deleted file mode 100644
index f5d7929c35..0000000000
--- a/src/opengl/qglpixelbuffer.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLPIXELBUFFER_H
-#define QGLPIXELBUFFER_H
-
-#include <QtOpenGL/qgl.h>
-#include <QtGui/qpaintdevice.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QGLPixelBufferPrivate;
-
-class Q_OPENGL_EXPORT QGLPixelBuffer : public QPaintDevice
-{
- Q_DECLARE_PRIVATE(QGLPixelBuffer)
-public:
- QGLPixelBuffer(const QSize &size, const QGLFormat &format = QGLFormat::defaultFormat(),
- QGLWidget *shareWidget = nullptr);
- QGLPixelBuffer(int width, int height, const QGLFormat &format = QGLFormat::defaultFormat(),
- QGLWidget *shareWidget = nullptr);
- virtual ~QGLPixelBuffer();
-
- bool isValid() const;
- bool makeCurrent();
- bool doneCurrent();
-
- QGLContext *context() const;
-
- GLuint generateDynamicTexture() const;
- bool bindToDynamicTexture(GLuint texture);
- void releaseFromDynamicTexture();
- void updateDynamicTexture(GLuint texture_id) const;
-
- GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D);
- GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D);
- GLuint bindTexture(const QString &fileName);
- void deleteTexture(GLuint texture_id);
-
- void drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
- void drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
-
- QSize size() const;
- Qt::HANDLE handle() const;
- QImage toImage() const;
-
- QPaintEngine *paintEngine() const override;
- QGLFormat format() const;
-
- static bool hasOpenGLPbuffers();
-
-protected:
- int metric(PaintDeviceMetric metric) const override;
- int devType() const override { return QInternal::Pbuffer; }
-
-private:
- Q_DISABLE_COPY(QGLPixelBuffer)
- QScopedPointer<QGLPixelBufferPrivate> d_ptr;
- friend class QGLDrawable;
- friend class QGLPaintDevice;
- friend class QGLPBufferGLPaintDevice;
- friend class QGLContextPrivate;
-};
-
-QT_END_NAMESPACE
-
-#endif // QGLPIXELBUFFER_H
diff --git a/src/opengl/qglpixelbuffer_p.h b/src/opengl/qglpixelbuffer_p.h
deleted file mode 100644
index 2729ade2b6..0000000000
--- a/src/opengl/qglpixelbuffer_p.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLPIXELBUFFER_P_H
-#define QGLPIXELBUFFER_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 "QtOpenGL/qglpixelbuffer.h"
-#include <private/qgl_p.h>
-#include <private/qglpaintdevice_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QEglContext;
-class QOpenGLFramebufferObject;
-
-class QGLPBufferGLPaintDevice : public QGLPaintDevice
-{
-public:
- QPaintEngine* paintEngine() const override {return pbuf->paintEngine();}
- QSize size() const override {return pbuf->size();}
- QGLContext* context() const override;
- void beginPaint() override;
- void endPaint() override;
- void setPBuffer(QGLPixelBuffer* pb);
- void setFbo(GLuint fbo);
-private:
- QGLPixelBuffer* pbuf;
-};
-
-class QGLPixelBufferPrivate {
- Q_DECLARE_PUBLIC(QGLPixelBuffer)
-public:
- QGLPixelBufferPrivate(QGLPixelBuffer *q) : q_ptr(q), invalid(true), qctx(nullptr), widget(nullptr), fbo(nullptr), blit_fbo(nullptr), pbuf(nullptr), ctx(nullptr)
- {
- }
- bool init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget);
- void common_init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget);
- bool cleanup();
-
- QGLPixelBuffer *q_ptr;
- bool invalid;
- QGLContext *qctx;
- QGLPBufferGLPaintDevice glDevice;
- QGLWidget *widget;
- QOpenGLFramebufferObject *fbo;
- QOpenGLFramebufferObject *blit_fbo;
- QGLFormat format;
-
- QGLFormat req_format;
- QPointer<QGLWidget> req_shareWidget;
- QSize req_size;
-
- //stubs
- void *pbuf;
- void *ctx;
-};
-
-QT_END_NAMESPACE
-
-#endif // QGLPIXELBUFFER_P_H
diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp
deleted file mode 100644
index 35f60318be..0000000000
--- a/src/opengl/qglshaderprogram.cpp
+++ /dev/null
@@ -1,3237 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglshaderprogram.h"
-#include <private/qopenglextensions_p.h>
-#include "qgl_p.h"
-#include <QtCore/private/qobject_p.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qfile.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qvector.h>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGLShaderProgram
- \inmodule QtOpenGL
- \brief The QGLShaderProgram class allows OpenGL shader programs to be linked and used.
- \since 4.6
- \obsolete
- \ingroup painting-3D
-
- \section1 Introduction
-
- This class supports shader programs written in the OpenGL Shading
- Language (GLSL) and in the OpenGL/ES Shading Language (GLSL/ES).
-
- QGLShader and QGLShaderProgram shelter the programmer from the details of
- compiling and linking vertex and fragment shaders.
-
- The following example creates a vertex shader program using the
- supplied source \c{code}. Once compiled and linked, the shader
- program is activated in the current QGLContext by calling
- QGLShaderProgram::bind():
-
- \snippet code/src_opengl_qglshaderprogram.cpp 0
-
- \section1 Writing Portable Shaders
-
- Shader programs can be difficult to reuse across OpenGL implementations
- because of varying levels of support for standard vertex attributes and
- uniform variables. In particular, GLSL/ES lacks all of the
- standard variables that are present on desktop OpenGL systems:
- \c{gl_Vertex}, \c{gl_Normal}, \c{gl_Color}, and so on. Desktop OpenGL
- lacks the variable qualifiers \c{highp}, \c{mediump}, and \c{lowp}.
-
- The QGLShaderProgram class makes the process of writing portable shaders
- easier by prefixing all shader programs with the following lines on
- desktop OpenGL:
-
- \code
- #define highp
- #define mediump
- #define lowp
- \endcode
-
- This makes it possible to run most GLSL/ES shader programs
- on desktop systems. The programmer should restrict themselves
- to just features that are present in GLSL/ES, and avoid
- standard variable names that only work on the desktop.
-
- \section1 Simple Shader Example
-
- \snippet code/src_opengl_qglshaderprogram.cpp 1
-
- With the above shader program active, we can draw a green triangle
- as follows:
-
- \snippet code/src_opengl_qglshaderprogram.cpp 2
-
- \section1 Binary Shaders and Programs
-
- Binary shaders may be specified using \c{glShaderBinary()} on
- the return value from QGLShader::shaderId(). The QGLShader instance
- containing the binary can then be added to the shader program with
- addShader() and linked in the usual fashion with link().
-
- Binary programs may be specified using \c{glProgramBinaryOES()}
- on the return value from programId(). Then the application should
- call link(), which will notice that the program has already been
- specified and linked, allowing other operations to be performed
- on the shader program.
-
- \note This class has been deprecated in favor of QOpenGLShaderProgram.
-
- \sa QGLShader
-*/
-
-/*!
- \class QGLShader
- \inmodule QtOpenGL
- \brief The QGLShader class allows OpenGL shaders to be compiled.
- \since 4.6
- \obsolete
- \ingroup painting-3D
-
- This class supports shaders written in the OpenGL Shading Language (GLSL)
- and in the OpenGL/ES Shading Language (GLSL/ES).
-
- QGLShader and QGLShaderProgram shelter the programmer from the details of
- compiling and linking vertex and fragment shaders.
-
- \note This class has been deprecated in favor of QOpenGLShader.
-
- \sa QGLShaderProgram
-*/
-
-/*!
- \enum QGLShader::ShaderTypeBit
- This enum specifies the type of QGLShader that is being created.
-
- \value Vertex Vertex shader written in the OpenGL Shading Language (GLSL).
- \value Fragment Fragment shader written in the OpenGL Shading Language (GLSL).
- \value Geometry Geometry shaders written in the OpenGL Shading
- Language (GLSL), based on the GL_EXT_geometry_shader4 extension.
-*/
-
-#ifndef GL_FRAGMENT_SHADER
-#define GL_FRAGMENT_SHADER 0x8B30
-#endif
-#ifndef GL_VERTEX_SHADER
-#define GL_VERTEX_SHADER 0x8B31
-#endif
-#ifndef GL_COMPILE_STATUS
-#define GL_COMPILE_STATUS 0x8B81
-#endif
-#ifndef GL_LINK_STATUS
-#define GL_LINK_STATUS 0x8B82
-#endif
-#ifndef GL_INFO_LOG_LENGTH
-#define GL_INFO_LOG_LENGTH 0x8B84
-#endif
-#ifndef GL_ACTIVE_UNIFORMS
-#define GL_ACTIVE_UNIFORMS 0x8B86
-#endif
-#ifndef GL_ACTIVE_UNIFORM_MAX_LENGTH
-#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
-#endif
-#ifndef GL_ACTIVE_ATTRIBUTES
-#define GL_ACTIVE_ATTRIBUTES 0x8B89
-#endif
-#ifndef GL_ACTIVE_ATTRIBUTE_MAX_LENGTH
-#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
-#endif
-#ifndef GL_CURRENT_VERTEX_ATTRIB
-#define GL_CURRENT_VERTEX_ATTRIB 0x8626
-#endif
-#ifndef GL_SHADER_SOURCE_LENGTH
-#define GL_SHADER_SOURCE_LENGTH 0x8B88
-#endif
-#ifndef GL_SHADER_BINARY_FORMATS
-#define GL_SHADER_BINARY_FORMATS 0x8DF8
-#endif
-#ifndef GL_NUM_SHADER_BINARY_FORMATS
-#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9
-#endif
-
-class QGLShaderPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGLShader)
-public:
- QGLShaderPrivate(const QGLContext *ctx, QGLShader::ShaderType type)
- : shaderGuard(0)
- , shaderType(type)
- , compiled(false)
- , glfuncs(new QOpenGLFunctions(ctx->contextHandle()))
- {
- }
- ~QGLShaderPrivate();
-
- QGLSharedResourceGuardBase *shaderGuard;
- QGLShader::ShaderType shaderType;
- bool compiled;
- QString log;
-
- QOpenGLFunctions *glfuncs;
-
- bool create();
- bool compile(QGLShader *q);
- void deleteShader();
-};
-
-namespace {
- void freeShaderFunc(QGLContext *ctx, GLuint id)
- {
- Q_ASSERT(ctx);
- ctx->contextHandle()->functions()->glDeleteShader(id);
- }
-}
-
-#define ctx QGLContext::currentContext()
-
-QGLShaderPrivate::~QGLShaderPrivate()
-{
- delete glfuncs;
- if (shaderGuard)
- shaderGuard->free();
-}
-
-bool QGLShaderPrivate::create()
-{
- QGLContext *context = const_cast<QGLContext *>(QGLContext::currentContext());
- if (!context)
- return false;
-
- if (glfuncs->hasOpenGLFeature(QOpenGLFunctions::Shaders)) {
- GLuint shader;
- if (shaderType == QGLShader::Vertex)
- shader = glfuncs->glCreateShader(GL_VERTEX_SHADER);
-#if !defined(QT_OPENGL_ES_2)
- else if (shaderType == QGLShader::Geometry
- && !context->contextHandle()->isOpenGLES())
- shader = glfuncs->glCreateShader(GL_GEOMETRY_SHADER_EXT);
-#endif
- else
- shader = glfuncs->glCreateShader(GL_FRAGMENT_SHADER);
- if (!shader) {
- qWarning("Could not create shader of type %d.", int(shaderType));
- return false;
- }
- shaderGuard = createSharedResourceGuard(context, shader, freeShaderFunc);
- return true;
- } else {
- return false;
- }
-}
-
-bool QGLShaderPrivate::compile(QGLShader *q)
-{
- GLuint shader = shaderGuard ? shaderGuard->id() : 0;
- if (!shader)
- return false;
- glfuncs->glCompileShader(shader);
- GLint value = 0;
- glfuncs->glGetShaderiv(shader, GL_COMPILE_STATUS, &value);
- compiled = (value != 0);
- value = 0;
- glfuncs->glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &value);
- if (!compiled && value > 1) {
- char *logbuf = new char [value];
- GLint len;
- glfuncs->glGetShaderInfoLog(shader, value, &len, logbuf);
- log = QString::fromLatin1(logbuf);
- QString name = q->objectName();
-
- const char *types[] = {
- "Fragment",
- "Vertex",
- "Geometry",
- ""
- };
-
- const char *type = types[3];
- if (shaderType == QGLShader::Fragment)
- type = types[0];
- else if (shaderType == QGLShader::Vertex)
- type = types[1];
- else if (shaderType == QGLShader::Geometry)
- type = types[2];
-
- if (name.isEmpty())
- qWarning("QGLShader::compile(%s): %s", type, qPrintable(log));
- else
- qWarning("QGLShader::compile(%s)[%s]: %s", type, qPrintable(name), qPrintable(log));
-
- delete [] logbuf;
- }
- return compiled;
-}
-
-void QGLShaderPrivate::deleteShader()
-{
- if (shaderGuard) {
- shaderGuard->free();
- shaderGuard = 0;
- }
-}
-
-/*!
- Constructs a new QGLShader object of the specified \a type
- and attaches it to \a parent. If shader programs are not supported,
- QGLShaderProgram::hasOpenGLShaderPrograms() will return false.
-
- This constructor is normally followed by a call to compileSourceCode()
- or compileSourceFile().
-
- The shader will be associated with the current QGLContext.
-
- \sa compileSourceCode(), compileSourceFile()
-*/
-QGLShader::QGLShader(QGLShader::ShaderType type, QObject *parent)
- : QObject(*new QGLShaderPrivate(QGLContext::currentContext(), type), parent)
-{
- Q_D(QGLShader);
- d->create();
-}
-
-/*!
- Constructs a new QGLShader object of the specified \a type
- and attaches it to \a parent. If shader programs are not supported,
- then QGLShaderProgram::hasOpenGLShaderPrograms() will return false.
-
- This constructor is normally followed by a call to compileSourceCode()
- or compileSourceFile().
-
- The shader will be associated with \a context.
-
- \sa compileSourceCode(), compileSourceFile()
-*/
-QGLShader::QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent)
- : QObject(*new QGLShaderPrivate(context ? context : QGLContext::currentContext(), type), parent)
-{
- Q_D(QGLShader);
-#ifndef QT_NO_DEBUG
- if (context && !QGLContext::areSharing(context, QGLContext::currentContext())) {
- qWarning("QGLShader::QGLShader: \'context\' must be the current context or sharing with it.");
- return;
- }
-#endif
- d->create();
-}
-
-/*!
- Deletes this shader. If the shader has been attached to a
- QGLShaderProgram object, then the actual shader will stay around
- until the QGLShaderProgram is destroyed.
-*/
-QGLShader::~QGLShader()
-{
-}
-
-/*!
- Returns the type of this shader.
-*/
-QGLShader::ShaderType QGLShader::shaderType() const
-{
- Q_D(const QGLShader);
- return d->shaderType;
-}
-
-// The precision qualifiers are useful on OpenGL/ES systems,
-// but usually not present on desktop systems. Define the
-// keywords to empty strings on desktop systems.
-#if !defined(QT_OPENGL_ES) || defined(QT_OPENGL_FORCE_SHADER_DEFINES)
-#define QGL_DEFINE_QUALIFIERS 1
-static const char qualifierDefines[] =
- "#define lowp\n"
- "#define mediump\n"
- "#define highp\n";
-
-#else
-
-// The "highp" qualifier doesn't exist in fragment shaders
-// on all ES platforms. When it doesn't exist, use "mediump".
-#define QGL_REDEFINE_HIGHP 1
-static const char redefineHighp[] =
- "#ifndef GL_FRAGMENT_PRECISION_HIGH\n"
- "#define highp mediump\n"
- "#endif\n";
-#endif
-
-/*!
- Sets the \a source code for this shader and compiles it.
- Returns \c true if the source was successfully compiled, false otherwise.
-
- \sa compileSourceFile()
-*/
-bool QGLShader::compileSourceCode(const char *source)
-{
- Q_D(QGLShader);
- if (d->shaderGuard && d->shaderGuard->id()) {
- QVarLengthArray<const char *, 4> src;
- QVarLengthArray<GLint, 4> srclen;
- int headerLen = 0;
- while (source && source[headerLen] == '#') {
- // Skip #version and #extension directives at the start of
- // the shader code. We need to insert the qualifierDefines
- // and redefineHighp just after them.
- if (qstrncmp(source + headerLen, "#version", 8) != 0 &&
- qstrncmp(source + headerLen, "#extension", 10) != 0) {
- break;
- }
- while (source[headerLen] != '\0' && source[headerLen] != '\n')
- ++headerLen;
- if (source[headerLen] == '\n')
- ++headerLen;
- }
- if (headerLen > 0) {
- src.append(source);
- srclen.append(GLint(headerLen));
- }
-#ifdef QGL_DEFINE_QUALIFIERS
- if (!QOpenGLContext::currentContext()->isOpenGLES()) {
- src.append(qualifierDefines);
- srclen.append(GLint(sizeof(qualifierDefines) - 1));
- }
-#endif
-#ifdef QGL_REDEFINE_HIGHP
- if (d->shaderType == Fragment
- && QOpenGLContext::currentContext()->isOpenGLES()) {
- src.append(redefineHighp);
- srclen.append(GLint(sizeof(redefineHighp) - 1));
- }
-#endif
- src.append(source + headerLen);
- srclen.append(GLint(qstrlen(source + headerLen)));
- d->glfuncs->glShaderSource(d->shaderGuard->id(), src.size(), src.data(), srclen.data());
- return d->compile(this);
- } else {
- return false;
- }
-}
-
-/*!
- \overload
-
- Sets the \a source code for this shader and compiles it.
- Returns \c true if the source was successfully compiled, false otherwise.
-
- \sa compileSourceFile()
-*/
-bool QGLShader::compileSourceCode(const QByteArray& source)
-{
- return compileSourceCode(source.constData());
-}
-
-/*!
- \overload
-
- Sets the \a source code for this shader and compiles it.
- Returns \c true if the source was successfully compiled, false otherwise.
-
- \sa compileSourceFile()
-*/
-bool QGLShader::compileSourceCode(const QString& source)
-{
- return compileSourceCode(source.toLatin1().constData());
-}
-
-/*!
- Sets the source code for this shader to the contents of \a fileName
- and compiles it. Returns \c true if the file could be opened and the
- source compiled, false otherwise.
-
- \sa compileSourceCode()
-*/
-bool QGLShader::compileSourceFile(const QString& fileName)
-{
- QFile file(fileName);
- if (!file.open(QFile::ReadOnly)) {
- qWarning() << "QGLShader: Unable to open file" << fileName;
- return false;
- }
-
- QByteArray contents = file.readAll();
- return compileSourceCode(contents.constData());
-}
-
-/*!
- Returns the source code for this shader.
-
- \sa compileSourceCode()
-*/
-QByteArray QGLShader::sourceCode() const
-{
- Q_D(const QGLShader);
- GLuint shader = d->shaderGuard ? d->shaderGuard->id() : 0;
- if (!shader)
- return QByteArray();
- GLint size = 0;
- d->glfuncs->glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &size);
- if (size <= 0)
- return QByteArray();
- GLint len = 0;
- char *source = new char [size];
- d->glfuncs->glGetShaderSource(shader, size, &len, source);
- QByteArray src(source);
- delete [] source;
- return src;
-}
-
-/*!
- Returns \c true if this shader has been compiled; false otherwise.
-
- \sa compileSourceCode(), compileSourceFile()
-*/
-bool QGLShader::isCompiled() const
-{
- Q_D(const QGLShader);
- return d->compiled;
-}
-
-/*!
- Returns the errors and warnings that occurred during the last compile.
-
- \sa compileSourceCode(), compileSourceFile()
-*/
-QString QGLShader::log() const
-{
- Q_D(const QGLShader);
- return d->log;
-}
-
-/*!
- Returns the OpenGL identifier associated with this shader.
-
- \sa QGLShaderProgram::programId()
-*/
-GLuint QGLShader::shaderId() const
-{
- Q_D(const QGLShader);
- return d->shaderGuard ? d->shaderGuard->id() : 0;
-}
-
-#undef ctx
-
-class ShaderProgramOpenGLFunctions : public QOpenGLFunctions
-{
-public:
- ShaderProgramOpenGLFunctions()
- : QOpenGLFunctions()
- , glProgramParameteri(0)
- {
- }
-
- typedef void (QOPENGLF_APIENTRYP type_glProgramParameteri)(GLuint program, GLenum pname, GLint value);
-
- void initializeGeometryShaderFunctions()
- {
- QOpenGLContext *context = QOpenGLContext::currentContext();
- if (!context->isOpenGLES()) {
- glProgramParameteri = (type_glProgramParameteri)
- context->getProcAddress("glProgramParameteri");
-
- if (!glProgramParameteri) {
- glProgramParameteri = (type_glProgramParameteri)
- context->getProcAddress("glProgramParameteriEXT");
- }
- }
- }
-
- type_glProgramParameteri glProgramParameteri;
-};
-
-class QGLShaderProgramPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGLShaderProgram)
-public:
- QGLShaderProgramPrivate(const QGLContext *)
- : programGuard(0)
- , linked(false)
- , inited(false)
- , removingShaders(false)
- , geometryVertexCount(64)
- , geometryInputType(0)
- , geometryOutputType(0)
- , glfuncs(new ShaderProgramOpenGLFunctions)
- {
- }
- ~QGLShaderProgramPrivate();
-
- QGLSharedResourceGuardBase *programGuard;
- bool linked;
- bool inited;
- bool removingShaders;
-
- int geometryVertexCount;
- GLenum geometryInputType;
- GLenum geometryOutputType;
-
- QString log;
- QList<QGLShader *> shaders;
- QList<QGLShader *> anonShaders;
-
- ShaderProgramOpenGLFunctions *glfuncs;
-
- bool hasShader(QGLShader::ShaderType type) const;
-};
-
-namespace {
- void freeProgramFunc(QGLContext *ctx, GLuint id)
- {
- Q_ASSERT(ctx);
- ctx->contextHandle()->functions()->glDeleteProgram(id);
- }
-}
-
-
-QGLShaderProgramPrivate::~QGLShaderProgramPrivate()
-{
- delete glfuncs;
- if (programGuard)
- programGuard->free();
-}
-
-bool QGLShaderProgramPrivate::hasShader(QGLShader::ShaderType type) const
-{
- for (QGLShader *shader : shaders) {
- if (shader->shaderType() == type)
- return true;
- }
- return false;
-}
-
-#define ctx QGLContext::currentContext()
-
-/*!
- Constructs a new shader program and attaches it to \a parent.
- The program will be invalid until addShader() is called.
-
- The shader program will be associated with the current QGLContext.
-
- \sa addShader()
-*/
-QGLShaderProgram::QGLShaderProgram(QObject *parent)
- : QObject(*new QGLShaderProgramPrivate(QGLContext::currentContext()), parent)
-{
-}
-
-/*!
- Constructs a new shader program and attaches it to \a parent.
- The program will be invalid until addShader() is called.
-
- The shader program will be associated with \a context.
-
- \sa addShader()
-*/
-QGLShaderProgram::QGLShaderProgram(const QGLContext *context, QObject *parent)
- : QObject(*new QGLShaderProgramPrivate(context), parent)
-{
-}
-
-/*!
- Deletes this shader program.
-*/
-QGLShaderProgram::~QGLShaderProgram()
-{
-}
-
-bool QGLShaderProgram::init()
-{
- Q_D(QGLShaderProgram);
- if ((d->programGuard && d->programGuard->id()) || d->inited)
- return true;
- d->inited = true;
- QGLContext *context = const_cast<QGLContext *>(QGLContext::currentContext());
- if (!context)
- return false;
- d->glfuncs->initializeOpenGLFunctions();
- d->glfuncs->initializeGeometryShaderFunctions();
- if (d->glfuncs->hasOpenGLFeature(QOpenGLFunctions::Shaders)) {
- GLuint program = d->glfuncs->glCreateProgram();
- if (!program) {
- qWarning("QGLShaderProgram: could not create shader program");
- return false;
- }
- if (d->programGuard)
- delete d->programGuard;
- d->programGuard = createSharedResourceGuard(context, program, freeProgramFunc);
- return true;
- } else {
- qWarning("QGLShaderProgram: shader programs are not supported");
- return false;
- }
-}
-
-/*!
- Adds a compiled \a shader to this shader program. Returns \c true
- if the shader could be added, or false otherwise.
-
- Ownership of the \a shader object remains with the caller.
- It will not be deleted when this QGLShaderProgram instance
- is deleted. This allows the caller to add the same shader
- to multiple shader programs.
-
- \sa addShaderFromSourceCode(), addShaderFromSourceFile()
- \sa removeShader(), link(), removeAllShaders()
-*/
-bool QGLShaderProgram::addShader(QGLShader *shader)
-{
- Q_D(QGLShaderProgram);
- if (!init())
- return false;
- if (d->shaders.contains(shader))
- return true; // Already added to this shader program.
- if (d->programGuard && d->programGuard->id() && shader) {
- if (!shader->d_func()->shaderGuard || !shader->d_func()->shaderGuard->id())
- return false;
- if (d->programGuard->group() != shader->d_func()->shaderGuard->group()) {
- qWarning("QGLShaderProgram::addShader: Program and shader are not associated with same context.");
- return false;
- }
- d->glfuncs->glAttachShader(d->programGuard->id(), shader->d_func()->shaderGuard->id());
- d->linked = false; // Program needs to be relinked.
- d->shaders.append(shader);
- connect(shader, SIGNAL(destroyed()), this, SLOT(shaderDestroyed()));
- return true;
- } else {
- return false;
- }
-}
-
-/*!
- Compiles \a source as a shader of the specified \a type and
- adds it to this shader program. Returns \c true if compilation
- was successful, false otherwise. The compilation errors
- and warnings will be made available via log().
-
- This function is intended to be a short-cut for quickly
- adding vertex and fragment shaders to a shader program without
- creating an instance of QGLShader first.
-
- \sa addShader(), addShaderFromSourceFile()
- \sa removeShader(), link(), log(), removeAllShaders()
-*/
-bool QGLShaderProgram::addShaderFromSourceCode(QGLShader::ShaderType type, const char *source)
-{
- Q_D(QGLShaderProgram);
- if (!init())
- return false;
- QGLShader *shader = new QGLShader(type, this);
- if (!shader->compileSourceCode(source)) {
- d->log = shader->log();
- delete shader;
- return false;
- }
- d->anonShaders.append(shader);
- return addShader(shader);
-}
-
-/*!
- \overload
-
- Compiles \a source as a shader of the specified \a type and
- adds it to this shader program. Returns \c true if compilation
- was successful, false otherwise. The compilation errors
- and warnings will be made available via log().
-
- This function is intended to be a short-cut for quickly
- adding vertex and fragment shaders to a shader program without
- creating an instance of QGLShader first.
-
- \sa addShader(), addShaderFromSourceFile()
- \sa removeShader(), link(), log(), removeAllShaders()
-*/
-bool QGLShaderProgram::addShaderFromSourceCode(QGLShader::ShaderType type, const QByteArray& source)
-{
- return addShaderFromSourceCode(type, source.constData());
-}
-
-/*!
- \overload
-
- Compiles \a source as a shader of the specified \a type and
- adds it to this shader program. Returns \c true if compilation
- was successful, false otherwise. The compilation errors
- and warnings will be made available via log().
-
- This function is intended to be a short-cut for quickly
- adding vertex and fragment shaders to a shader program without
- creating an instance of QGLShader first.
-
- \sa addShader(), addShaderFromSourceFile()
- \sa removeShader(), link(), log(), removeAllShaders()
-*/
-bool QGLShaderProgram::addShaderFromSourceCode(QGLShader::ShaderType type, const QString& source)
-{
- return addShaderFromSourceCode(type, source.toLatin1().constData());
-}
-
-/*!
- Compiles the contents of \a fileName as a shader of the specified
- \a type and adds it to this shader program. Returns \c true if
- compilation was successful, false otherwise. The compilation errors
- and warnings will be made available via log().
-
- This function is intended to be a short-cut for quickly
- adding vertex and fragment shaders to a shader program without
- creating an instance of QGLShader first.
-
- \sa addShader(), addShaderFromSourceCode()
-*/
-bool QGLShaderProgram::addShaderFromSourceFile
- (QGLShader::ShaderType type, const QString& fileName)
-{
- Q_D(QGLShaderProgram);
- if (!init())
- return false;
- QGLShader *shader = new QGLShader(type, this);
- if (!shader->compileSourceFile(fileName)) {
- d->log = shader->log();
- delete shader;
- return false;
- }
- d->anonShaders.append(shader);
- return addShader(shader);
-}
-
-/*!
- Removes \a shader from this shader program. The object is not deleted.
-
- The shader program must be valid in the current QGLContext.
-
- \sa addShader(), link(), removeAllShaders()
-*/
-void QGLShaderProgram::removeShader(QGLShader *shader)
-{
- Q_D(QGLShaderProgram);
- if (d->programGuard && d->programGuard->id()
- && shader && shader->d_func()->shaderGuard)
- {
- d->glfuncs->glDetachShader(d->programGuard->id(), shader->d_func()->shaderGuard->id());
- }
- d->linked = false; // Program needs to be relinked.
- if (shader) {
- d->shaders.removeAll(shader);
- d->anonShaders.removeAll(shader);
- disconnect(shader, SIGNAL(destroyed()), this, SLOT(shaderDestroyed()));
- }
-}
-
-/*!
- Returns a list of all shaders that have been added to this shader
- program using addShader().
-
- \sa addShader(), removeShader()
-*/
-QList<QGLShader *> QGLShaderProgram::shaders() const
-{
- Q_D(const QGLShaderProgram);
- return d->shaders;
-}
-
-/*!
- Removes all of the shaders that were added to this program previously.
- The QGLShader objects for the shaders will not be deleted if they
- were constructed externally. QGLShader objects that are constructed
- internally by QGLShaderProgram will be deleted.
-
- \sa addShader(), removeShader()
-*/
-void QGLShaderProgram::removeAllShaders()
-{
- Q_D(QGLShaderProgram);
- d->removingShaders = true;
- if (d->programGuard) {
- if (const auto programGuardId = d->programGuard->id()) {
- for (QGLShader *shader : qAsConst(d->shaders)) {
- if (shader && shader->d_func()->shaderGuard)
- d->glfuncs->glDetachShader(programGuardId, shader->d_func()->shaderGuard->id());
- }
- }
- }
- // Delete shader objects that were created anonymously.
- qDeleteAll(d->anonShaders);
- d->shaders.clear();
- d->anonShaders.clear();
- d->linked = false; // Program needs to be relinked.
- d->removingShaders = false;
-}
-
-/*!
- Links together the shaders that were added to this program with
- addShader(). Returns \c true if the link was successful or
- false otherwise. If the link failed, the error messages can
- be retrieved with log().
-
- Subclasses can override this function to initialize attributes
- and uniform variables for use in specific shader programs.
-
- If the shader program was already linked, calling this
- function again will force it to be re-linked.
-
- \sa addShader(), log()
-*/
-bool QGLShaderProgram::link()
-{
- Q_D(QGLShaderProgram);
- GLuint program = d->programGuard ? d->programGuard->id() : 0;
- if (!program)
- return false;
-
- GLint value;
- if (d->shaders.isEmpty()) {
- // If there are no explicit shaders, then it is possible that the
- // application added a program binary with glProgramBinaryOES(),
- // or otherwise populated the shaders itself. Check to see if the
- // program is already linked and bail out if so.
- value = 0;
- d->glfuncs->glGetProgramiv(program, GL_LINK_STATUS, &value);
- d->linked = (value != 0);
- if (d->linked)
- return true;
- }
-
-#if !defined(QT_OPENGL_ES_2)
- // Set up the geometry shader parameters
- if (!QOpenGLContext::currentContext()->isOpenGLES()
- && d->glfuncs->glProgramParameteri) {
- for (QGLShader *shader : qAsConst(d->shaders)) {
- if (shader->shaderType() & QGLShader::Geometry) {
- d->glfuncs->glProgramParameteri(program, GL_GEOMETRY_INPUT_TYPE_EXT,
- d->geometryInputType);
- d->glfuncs->glProgramParameteri(program, GL_GEOMETRY_OUTPUT_TYPE_EXT,
- d->geometryOutputType);
- d->glfuncs->glProgramParameteri(program, GL_GEOMETRY_VERTICES_OUT_EXT,
- d->geometryVertexCount);
- break;
- }
- }
- }
-#endif
-
- d->glfuncs->glLinkProgram(program);
- value = 0;
- d->glfuncs->glGetProgramiv(program, GL_LINK_STATUS, &value);
- d->linked = (value != 0);
- value = 0;
- d->glfuncs->glGetProgramiv(program, GL_INFO_LOG_LENGTH, &value);
- d->log = QString();
- if (value > 1) {
- char *logbuf = new char [value];
- GLint len;
- d->glfuncs->glGetProgramInfoLog(program, value, &len, logbuf);
- d->log = QString::fromLatin1(logbuf);
- QString name = objectName();
- if (!d->linked) {
- if (name.isEmpty())
- qWarning() << "QGLShader::link:" << d->log;
- else
- qWarning() << "QGLShader::link[" << name << "]:" << d->log;
- }
- delete [] logbuf;
- }
- return d->linked;
-}
-
-/*!
- Returns \c true if this shader program has been linked; false otherwise.
-
- \sa link()
-*/
-bool QGLShaderProgram::isLinked() const
-{
- Q_D(const QGLShaderProgram);
- return d->linked;
-}
-
-/*!
- Returns the errors and warnings that occurred during the last link()
- or addShader() with explicitly specified source code.
-
- \sa link()
-*/
-QString QGLShaderProgram::log() const
-{
- Q_D(const QGLShaderProgram);
- return d->log;
-}
-
-/*!
- Binds this shader program to the active QGLContext and makes
- it the current shader program. Any previously bound shader program
- is released. This is equivalent to calling \c{glUseProgram()} on
- programId(). Returns \c true if the program was successfully bound;
- false otherwise. If the shader program has not yet been linked,
- or it needs to be re-linked, this function will call link().
-
- \sa link(), release()
-*/
-bool QGLShaderProgram::bind()
-{
- Q_D(QGLShaderProgram);
- GLuint program = d->programGuard ? d->programGuard->id() : 0;
- if (!program)
- return false;
- if (!d->linked && !link())
- return false;
-#ifndef QT_NO_DEBUG
- if (d->programGuard->group() != QOpenGLContextGroup::currentContextGroup()) {
- qWarning("QGLShaderProgram::bind: program is not valid in the current context.");
- return false;
- }
-#endif
- d->glfuncs->glUseProgram(program);
- return true;
-}
-
-#undef ctx
-#define ctx QGLContext::currentContext()
-
-/*!
- Releases the active shader program from the current QGLContext.
- This is equivalent to calling \c{glUseProgram(0)}.
-
- \sa bind()
-*/
-void QGLShaderProgram::release()
-{
- Q_D(QGLShaderProgram);
-#ifndef QT_NO_DEBUG
- if (d->programGuard && d->programGuard->group() != QOpenGLContextGroup::currentContextGroup())
- qWarning("QGLShaderProgram::release: program is not valid in the current context.");
-#endif
- d->glfuncs->glUseProgram(0);
-}
-
-/*!
- Returns the OpenGL identifier associated with this shader program.
-
- \sa QGLShader::shaderId()
-*/
-GLuint QGLShaderProgram::programId() const
-{
- Q_D(const QGLShaderProgram);
- GLuint id = d->programGuard ? d->programGuard->id() : 0;
- if (id)
- return id;
-
- // Create the identifier if we don't have one yet. This is for
- // applications that want to create the attached shader configuration
- // themselves, particularly those using program binaries.
- if (!const_cast<QGLShaderProgram *>(this)->init())
- return 0;
- return d->programGuard ? d->programGuard->id() : 0;
-}
-
-/*!
- Binds the attribute \a name to the specified \a location. This
- function can be called before or after the program has been linked.
- Any attributes that have not been explicitly bound when the program
- is linked will be assigned locations automatically.
-
- When this function is called after the program has been linked,
- the program will need to be relinked for the change to take effect.
-
- \sa attributeLocation()
-*/
-void QGLShaderProgram::bindAttributeLocation(const char *name, int location)
-{
- Q_D(QGLShaderProgram);
- if (!init() || !d->programGuard || !d->programGuard->id())
- return;
- d->glfuncs->glBindAttribLocation(d->programGuard->id(), location, name);
- d->linked = false; // Program needs to be relinked.
-}
-
-/*!
- \overload
-
- Binds the attribute \a name to the specified \a location. This
- function can be called before or after the program has been linked.
- Any attributes that have not been explicitly bound when the program
- is linked will be assigned locations automatically.
-
- When this function is called after the program has been linked,
- the program will need to be relinked for the change to take effect.
-
- \sa attributeLocation()
-*/
-void QGLShaderProgram::bindAttributeLocation(const QByteArray& name, int location)
-{
- bindAttributeLocation(name.constData(), location);
-}
-
-/*!
- \overload
-
- Binds the attribute \a name to the specified \a location. This
- function can be called before or after the program has been linked.
- Any attributes that have not been explicitly bound when the program
- is linked will be assigned locations automatically.
-
- When this function is called after the program has been linked,
- the program will need to be relinked for the change to take effect.
-
- \sa attributeLocation()
-*/
-void QGLShaderProgram::bindAttributeLocation(const QString& name, int location)
-{
- bindAttributeLocation(name.toLatin1().constData(), location);
-}
-
-/*!
- Returns the location of the attribute \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- attribute for this shader program.
-
- \sa uniformLocation(), bindAttributeLocation()
-*/
-int QGLShaderProgram::attributeLocation(const char *name) const
-{
- Q_D(const QGLShaderProgram);
- if (d->linked && d->programGuard && d->programGuard->id()) {
- return d->glfuncs->glGetAttribLocation(d->programGuard->id(), name);
- } else {
- qWarning() << "QGLShaderProgram::attributeLocation(" << name
- << "): shader program is not linked";
- return -1;
- }
-}
-
-/*!
- \overload
-
- Returns the location of the attribute \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- attribute for this shader program.
-
- \sa uniformLocation(), bindAttributeLocation()
-*/
-int QGLShaderProgram::attributeLocation(const QByteArray& name) const
-{
- return attributeLocation(name.constData());
-}
-
-/*!
- \overload
-
- Returns the location of the attribute \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- attribute for this shader program.
-
- \sa uniformLocation(), bindAttributeLocation()
-*/
-int QGLShaderProgram::attributeLocation(const QString& name) const
-{
- return attributeLocation(name.toLatin1().constData());
-}
-
-/*!
- Sets the attribute at \a location in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, GLfloat value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glVertexAttrib1fv(location, &value);
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, GLfloat value)
-{
- setAttributeValue(attributeLocation(name), value);
-}
-
-/*!
- Sets the attribute at \a location in the current context to
- the 2D vector (\a x, \a y).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, GLfloat x, GLfloat y)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[2] = {x, y};
- d->glfuncs->glVertexAttrib2fv(location, values);
- }
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to
- the 2D vector (\a x, \a y).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, GLfloat x, GLfloat y)
-{
- setAttributeValue(attributeLocation(name), x, y);
-}
-
-/*!
- Sets the attribute at \a location in the current context to
- the 3D vector (\a x, \a y, \a z).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (int location, GLfloat x, GLfloat y, GLfloat z)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[3] = {x, y, z};
- d->glfuncs->glVertexAttrib3fv(location, values);
- }
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to
- the 3D vector (\a x, \a y, \a z).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (const char *name, GLfloat x, GLfloat y, GLfloat z)
-{
- setAttributeValue(attributeLocation(name), x, y, z);
-}
-
-/*!
- Sets the attribute at \a location in the current context to
- the 4D vector (\a x, \a y, \a z, \a w).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {x, y, z, w};
- d->glfuncs->glVertexAttrib4fv(location, values);
- }
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to
- the 4D vector (\a x, \a y, \a z, \a w).
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- setAttributeValue(attributeLocation(name), x, y, z, w);
-}
-
-/*!
- Sets the attribute at \a location in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, const QVector2D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glVertexAttrib2fv(location, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, const QVector2D& value)
-{
- setAttributeValue(attributeLocation(name), value);
-}
-
-/*!
- Sets the attribute at \a location in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, const QVector3D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glVertexAttrib3fv(location, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, const QVector3D& value)
-{
- setAttributeValue(attributeLocation(name), value);
-}
-
-/*!
- Sets the attribute at \a location in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, const QVector4D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glVertexAttrib4fv(location, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, const QVector4D& value)
-{
- setAttributeValue(attributeLocation(name), value);
-}
-
-/*!
- Sets the attribute at \a location in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(int location, const QColor& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(value.redF()), GLfloat(value.greenF()),
- GLfloat(value.blueF()), GLfloat(value.alphaF())};
- d->glfuncs->glVertexAttrib4fv(location, values);
- }
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to \a value.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue(const char *name, const QColor& value)
-{
- setAttributeValue(attributeLocation(name), value);
-}
-
-/*!
- Sets the attribute at \a location in the current context to the
- contents of \a values, which contains \a columns elements, each
- consisting of \a rows elements. The \a rows value should be
- 1, 2, 3, or 4. This function is typically used to set matrix
- values and column vectors.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (int location, const GLfloat *values, int columns, int rows)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (rows < 1 || rows > 4) {
- qWarning() << "QGLShaderProgram::setAttributeValue: rows" << rows << "not supported";
- return;
- }
- if (location != -1) {
- while (columns-- > 0) {
- if (rows == 1)
- d->glfuncs->glVertexAttrib1fv(location, values);
- else if (rows == 2)
- d->glfuncs->glVertexAttrib2fv(location, values);
- else if (rows == 3)
- d->glfuncs->glVertexAttrib3fv(location, values);
- else
- d->glfuncs->glVertexAttrib4fv(location, values);
- values += rows;
- ++location;
- }
- }
-}
-
-/*!
- \overload
-
- Sets the attribute called \a name in the current context to the
- contents of \a values, which contains \a columns elements, each
- consisting of \a rows elements. The \a rows value should be
- 1, 2, 3, or 4. This function is typically used to set matrix
- values and column vectors.
-
- \sa setUniformValue()
-*/
-void QGLShaderProgram::setAttributeValue
- (const char *name, const GLfloat *values, int columns, int rows)
-{
- setAttributeValue(attributeLocation(name), values, columns, rows);
-}
-
-/*!
- Sets an array of vertex \a values on the attribute at \a location
- in this shader program. The \a tupleSize indicates the number of
- components per vertex (1, 2, 3, or 4), and the \a stride indicates
- the number of bytes between vertices. A default \a stride value
- of zero indicates that the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (int location, const GLfloat *values, int tupleSize, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, tupleSize, GL_FLOAT, GL_FALSE,
- stride, values);
- }
-}
-
-/*!
- Sets an array of 2D vertex \a values on the attribute at \a location
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (int location, const QVector2D *values, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE,
- stride, values);
- }
-}
-
-/*!
- Sets an array of 3D vertex \a values on the attribute at \a location
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (int location, const QVector3D *values, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, 3, GL_FLOAT, GL_FALSE,
- stride, values);
- }
-}
-
-/*!
- Sets an array of 4D vertex \a values on the attribute at \a location
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (int location, const QVector4D *values, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, 4, GL_FLOAT, GL_FALSE,
- stride, values);
- }
-}
-
-/*!
- Sets an array of vertex \a values on the attribute at \a location
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The \a type indicates the type of elements in the \a values array,
- usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a tupleSize
- indicates the number of components per vertex: 1, 2, 3, or 4.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- The setAttributeBuffer() function can be used to set the attribute
- array to an offset within a vertex buffer.
-
- \note Normalization will be enabled. If this is not desired, call
- glVertexAttribPointer directly through QGLFunctions.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray(), setAttributeBuffer()
- \since 4.7
-*/
-void QGLShaderProgram::setAttributeArray
- (int location, GLenum type, const void *values, int tupleSize, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, tupleSize, type, GL_TRUE,
- stride, values);
- }
-}
-
-/*!
- \overload
-
- Sets an array of vertex \a values on the attribute called \a name
- in this shader program. The \a tupleSize indicates the number of
- components per vertex (1, 2, 3, or 4), and the \a stride indicates
- the number of bytes between vertices. A default \a stride value
- of zero indicates that the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on \a name. Otherwise the value specified with setAttributeValue()
- for \a name will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (const char *name, const GLfloat *values, int tupleSize, int stride)
-{
- setAttributeArray(attributeLocation(name), values, tupleSize, stride);
-}
-
-/*!
- \overload
-
- Sets an array of 2D vertex \a values on the attribute called \a name
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on \a name. Otherwise the value specified with setAttributeValue()
- for \a name will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (const char *name, const QVector2D *values, int stride)
-{
- setAttributeArray(attributeLocation(name), values, stride);
-}
-
-/*!
- \overload
-
- Sets an array of 3D vertex \a values on the attribute called \a name
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on \a name. Otherwise the value specified with setAttributeValue()
- for \a name will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (const char *name, const QVector3D *values, int stride)
-{
- setAttributeArray(attributeLocation(name), values, stride);
-}
-
-/*!
- \overload
-
- Sets an array of 4D vertex \a values on the attribute called \a name
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The array will become active when enableAttributeArray() is called
- on \a name. Otherwise the value specified with setAttributeValue()
- for \a name will be used.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray()
-*/
-void QGLShaderProgram::setAttributeArray
- (const char *name, const QVector4D *values, int stride)
-{
- setAttributeArray(attributeLocation(name), values, stride);
-}
-
-/*!
- \overload
-
- Sets an array of vertex \a values on the attribute called \a name
- in this shader program. The \a stride indicates the number of bytes
- between vertices. A default \a stride value of zero indicates that
- the vertices are densely packed in \a values.
-
- The \a type indicates the type of elements in the \a values array,
- usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a tupleSize
- indicates the number of components per vertex: 1, 2, 3, or 4.
-
- The array will become active when enableAttributeArray() is called
- on the \a name. Otherwise the value specified with
- setAttributeValue() for \a name will be used.
-
- The setAttributeBuffer() function can be used to set the attribute
- array to an offset within a vertex buffer.
-
- \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
- \sa disableAttributeArray(), setAttributeBuffer()
- \since 4.7
-*/
-void QGLShaderProgram::setAttributeArray
- (const char *name, GLenum type, const void *values, int tupleSize, int stride)
-{
- setAttributeArray(attributeLocation(name), type, values, tupleSize, stride);
-}
-
-/*!
- Sets an array of vertex values on the attribute at \a location in
- this shader program, starting at a specific \a offset in the
- currently bound vertex buffer. The \a stride indicates the number
- of bytes between vertices. A default \a stride value of zero
- indicates that the vertices are densely packed in the value array.
-
- The \a type indicates the type of elements in the vertex value
- array, usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a
- tupleSize indicates the number of components per vertex: 1, 2, 3,
- or 4.
-
- The array will become active when enableAttributeArray() is called
- on the \a location. Otherwise the value specified with
- setAttributeValue() for \a location will be used.
-
- \note Normalization will be enabled. If this is not desired, call
- glVertexAttribPointer directly though QGLFunctions.
-
- \sa setAttributeArray()
- \since 4.7
-*/
-void QGLShaderProgram::setAttributeBuffer
- (int location, GLenum type, int offset, int tupleSize, int stride)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- d->glfuncs->glVertexAttribPointer(location, tupleSize, type, GL_TRUE, stride,
- reinterpret_cast<const void *>(qintptr(offset)));
- }
-}
-
-/*!
- \overload
-
- Sets an array of vertex values on the attribute called \a name
- in this shader program, starting at a specific \a offset in the
- currently bound vertex buffer. The \a stride indicates the number
- of bytes between vertices. A default \a stride value of zero
- indicates that the vertices are densely packed in the value array.
-
- The \a type indicates the type of elements in the vertex value
- array, usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a
- tupleSize indicates the number of components per vertex: 1, 2, 3,
- or 4.
-
- The array will become active when enableAttributeArray() is called
- on the \a name. Otherwise the value specified with
- setAttributeValue() for \a name will be used.
-
- \sa setAttributeArray()
- \since 4.7
-*/
-void QGLShaderProgram::setAttributeBuffer
- (const char *name, GLenum type, int offset, int tupleSize, int stride)
-{
- setAttributeBuffer(attributeLocation(name), type, offset, tupleSize, stride);
-}
-
-/*!
- Enables the vertex array at \a location in this shader program
- so that the value set by setAttributeArray() on \a location
- will be used by the shader program.
-
- \sa disableAttributeArray(), setAttributeArray(), setAttributeValue()
- \sa setUniformValue()
-*/
-void QGLShaderProgram::enableAttributeArray(int location)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glEnableVertexAttribArray(location);
-}
-
-/*!
- \overload
-
- Enables the vertex array called \a name in this shader program
- so that the value set by setAttributeArray() on \a name
- will be used by the shader program.
-
- \sa disableAttributeArray(), setAttributeArray(), setAttributeValue()
- \sa setUniformValue()
-*/
-void QGLShaderProgram::enableAttributeArray(const char *name)
-{
- enableAttributeArray(attributeLocation(name));
-}
-
-/*!
- Disables the vertex array at \a location in this shader program
- that was enabled by a previous call to enableAttributeArray().
-
- \sa enableAttributeArray(), setAttributeArray(), setAttributeValue()
- \sa setUniformValue()
-*/
-void QGLShaderProgram::disableAttributeArray(int location)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glDisableVertexAttribArray(location);
-}
-
-/*!
- \overload
-
- Disables the vertex array called \a name in this shader program
- that was enabled by a previous call to enableAttributeArray().
-
- \sa enableAttributeArray(), setAttributeArray(), setAttributeValue()
- \sa setUniformValue()
-*/
-void QGLShaderProgram::disableAttributeArray(const char *name)
-{
- disableAttributeArray(attributeLocation(name));
-}
-
-/*!
- Returns the location of the uniform variable \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- uniform variable for this shader program.
-
- \sa attributeLocation()
-*/
-int QGLShaderProgram::uniformLocation(const char *name) const
-{
- Q_D(const QGLShaderProgram);
- Q_UNUSED(d);
- if (d->linked && d->programGuard && d->programGuard->id()) {
- return d->glfuncs->glGetUniformLocation(d->programGuard->id(), name);
- } else {
- qWarning() << "QGLShaderProgram::uniformLocation(" << name
- << "): shader program is not linked";
- return -1;
- }
-}
-
-/*!
- \overload
-
- Returns the location of the uniform variable \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- uniform variable for this shader program.
-
- \sa attributeLocation()
-*/
-int QGLShaderProgram::uniformLocation(const QByteArray& name) const
-{
- return uniformLocation(name.constData());
-}
-
-/*!
- \overload
-
- Returns the location of the uniform variable \a name within this shader
- program's parameter list. Returns -1 if \a name is not a valid
- uniform variable for this shader program.
-
- \sa attributeLocation()
-*/
-int QGLShaderProgram::uniformLocation(const QString& name) const
-{
- return uniformLocation(name.toLatin1().constData());
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, GLfloat value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform1fv(location, 1, &value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, GLfloat value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, GLint value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform1i(location, value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, GLint value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
- This function should be used when setting sampler values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, GLuint value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform1i(location, value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value. This function should be used when setting sampler values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, GLuint value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the 2D vector (\a x, \a y).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, GLfloat x, GLfloat y)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[2] = {x, y};
- d->glfuncs->glUniform2fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context to
- the 2D vector (\a x, \a y).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, GLfloat x, GLfloat y)
-{
- setUniformValue(uniformLocation(name), x, y);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the 3D vector (\a x, \a y, \a z).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue
- (int location, GLfloat x, GLfloat y, GLfloat z)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[3] = {x, y, z};
- d->glfuncs->glUniform3fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context to
- the 3D vector (\a x, \a y, \a z).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue
- (const char *name, GLfloat x, GLfloat y, GLfloat z)
-{
- setUniformValue(uniformLocation(name), x, y, z);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the 4D vector (\a x, \a y, \a z, \a w).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue
- (int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {x, y, z, w};
- d->glfuncs->glUniform4fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context to
- the 4D vector (\a x, \a y, \a z, \a w).
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue
- (const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- setUniformValue(uniformLocation(name), x, y, z, w);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QVector2D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform2fv(location, 1, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QVector2D& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QVector3D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform3fv(location, 1, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QVector3D& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QVector4D& value)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform4fv(location, 1, reinterpret_cast<const GLfloat *>(&value));
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QVector4D& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the red, green, blue, and alpha components of \a color.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QColor& color)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(color.redF()), GLfloat(color.greenF()),
- GLfloat(color.blueF()), GLfloat(color.alphaF())};
- d->glfuncs->glUniform4fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context to
- the red, green, blue, and alpha components of \a color.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QColor& color)
-{
- setUniformValue(uniformLocation(name), color);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the x and y coordinates of \a point.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QPoint& point)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(point.x()), GLfloat(point.y())};
- d->glfuncs->glUniform2fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable associated with \a name in the current
- context to the x and y coordinates of \a point.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QPoint& point)
-{
- setUniformValue(uniformLocation(name), point);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the x and y coordinates of \a point.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QPointF& point)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(point.x()), GLfloat(point.y())};
- d->glfuncs->glUniform2fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable associated with \a name in the current
- context to the x and y coordinates of \a point.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QPointF& point)
-{
- setUniformValue(uniformLocation(name), point);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the width and height of the given \a size.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QSize& size)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(size.width()), GLfloat(size.height())};
- d->glfuncs->glUniform2fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable associated with \a name in the current
- context to the width and height of the given \a size.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QSize& size)
-{
- setUniformValue(uniformLocation(name), size);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to
- the width and height of the given \a size.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QSizeF& size)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1) {
- GLfloat values[4] = {GLfloat(size.width()), GLfloat(size.height())};
- d->glfuncs->glUniform2fv(location, 1, values);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable associated with \a name in the current
- context to the width and height of the given \a size.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QSizeF& size)
-{
- setUniformValue(uniformLocation(name), size);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 2x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix2x2& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniformMatrix2fv(location, 1, GL_FALSE, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 2x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x2& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 2x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix2x3& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform3fv(location, 2, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 2x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x3& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 2x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix2x4& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform4fv(location, 2, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 2x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x4& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 3x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix3x2& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform2fv(location, 3, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 3x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x2& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 3x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix3x3& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniformMatrix3fv(location, 1, GL_FALSE, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 3x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x3& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 3x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix3x4& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform4fv(location, 3, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 3x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x4& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 4x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix4x2& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform2fv(location, 4, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 4x2 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x2& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 4x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix4x3& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniform3fv(location, 4, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 4x3 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x3& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context
- to a 4x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const QMatrix4x4& value)
-{
- Q_D(QGLShaderProgram);
- d->glfuncs->glUniformMatrix4fv(location, 1, GL_FALSE, value.constData());
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 4x4 matrix \a value.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x4& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable at \a location in the current context
- to a 2x2 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
- \since 4.7
-*/
-void QGLShaderProgram::setUniformValue(int location, const GLfloat value[2][2])
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniformMatrix2fv(location, 1, GL_FALSE, value[0]);
-}
-
-/*!
- \overload
-
- Sets the uniform variable at \a location in the current context
- to a 3x3 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
- \since 4.7
-*/
-void QGLShaderProgram::setUniformValue(int location, const GLfloat value[3][3])
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniformMatrix3fv(location, 1, GL_FALSE, value[0]);
-}
-
-/*!
- \overload
-
- Sets the uniform variable at \a location in the current context
- to a 4x4 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(int location, const GLfloat value[4][4])
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniformMatrix4fv(location, 1, GL_FALSE, value[0]);
-}
-
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 2x2 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
- \since 4.7
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[2][2])
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 3x3 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
- \since 4.7
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[3][3])
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context
- to a 4x4 matrix \a value. The matrix elements must be specified
- in column-major order.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[4][4])
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable at \a location in the current context to a
- 3x3 transformation matrix \a value that is specified as a QTransform value.
-
- To set a QTransform value as a 4x4 matrix in a shader, use
- \c{setUniformValue(location, QMatrix4x4(value))}.
-*/
-void QGLShaderProgram::setUniformValue(int location, const QTransform& value)
-{
- Q_D(QGLShaderProgram);
- if (location != -1) {
- GLfloat mat[3][3] = {
- {GLfloat(value.m11()), GLfloat(value.m12()), GLfloat(value.m13())},
- {GLfloat(value.m21()), GLfloat(value.m22()), GLfloat(value.m23())},
- {GLfloat(value.m31()), GLfloat(value.m32()), GLfloat(value.m33())}
- };
- d->glfuncs->glUniformMatrix3fv(location, 1, GL_FALSE, mat[0]);
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable called \a name in the current context to a
- 3x3 transformation matrix \a value that is specified as a QTransform value.
-
- To set a QTransform value as a 4x4 matrix in a shader, use
- \c{setUniformValue(name, QMatrix4x4(value))}.
-*/
-void QGLShaderProgram::setUniformValue
- (const char *name, const QTransform& value)
-{
- setUniformValue(uniformLocation(name), value);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const GLint *values, int count)
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniform1iv(location, count, values);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray
- (const char *name, const GLint *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count elements of \a values. This overload
- should be used when setting an array of sampler values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const GLuint *values, int count)
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniform1iv(location, count, reinterpret_cast<const GLint *>(values));
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count elements of \a values. This overload
- should be used when setting an array of sampler values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray
- (const char *name, const GLuint *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count elements of \a values. Each element
- has \a tupleSize components. The \a tupleSize must be 1, 2, 3, or 4.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const GLfloat *values, int count, int tupleSize)
-{
- Q_D(QGLShaderProgram);
- if (location != -1) {
- if (tupleSize == 1)
- d->glfuncs->glUniform1fv(location, count, values);
- else if (tupleSize == 2)
- d->glfuncs->glUniform2fv(location, count, values);
- else if (tupleSize == 3)
- d->glfuncs->glUniform3fv(location, count, values);
- else if (tupleSize == 4)
- d->glfuncs->glUniform4fv(location, count, values);
- else
- qWarning() << "QGLShaderProgram::setUniformValue: size" << tupleSize << "not supported";
- }
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count elements of \a values. Each element
- has \a tupleSize components. The \a tupleSize must be 1, 2, 3, or 4.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray
- (const char *name, const GLfloat *values, int count, int tupleSize)
-{
- setUniformValueArray(uniformLocation(name), values, count, tupleSize);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 2D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QVector2D *values, int count)
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniform2fv(location, count, reinterpret_cast<const GLfloat *>(values));
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 2D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QVector2D *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 3D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QVector3D *values, int count)
-{
- Q_D(QGLShaderProgram);
- if (location != -1)
- d->glfuncs->glUniform3fv(location, count, reinterpret_cast<const GLfloat *>(values));
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 3D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QVector3D *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 4D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QVector4D *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- if (location != -1)
- d->glfuncs->glUniform4fv(location, count, reinterpret_cast<const GLfloat *>(values));
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 4D vector elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QVector4D *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-// We have to repack matrix arrays from qreal to GLfloat.
-#define setUniformMatrixArray(func,location,values,count,type,cols,rows) \
- if (location == -1 || count <= 0) \
- return; \
- if (sizeof(type) == sizeof(GLfloat) * cols * rows) { \
- func(location, count, GL_FALSE, \
- reinterpret_cast<const GLfloat *>(values[0].constData())); \
- } else { \
- QVarLengthArray<GLfloat> temp(cols * rows * count); \
- for (int index = 0; index < count; ++index) { \
- for (int index2 = 0; index2 < (cols * rows); ++index2) { \
- temp.data()[cols * rows * index + index2] = \
- values[index].constData()[index2]; \
- } \
- } \
- func(location, count, GL_FALSE, temp.constData()); \
- }
-#define setUniformGenericMatrixArray(colfunc,location,values,count,type,cols,rows) \
- if (location == -1 || count <= 0) \
- return; \
- if (sizeof(type) == sizeof(GLfloat) * cols * rows) { \
- const GLfloat *data = reinterpret_cast<const GLfloat *> \
- (values[0].constData()); \
- colfunc(location, count * cols, data); \
- } else { \
- QVarLengthArray<GLfloat> temp(cols * rows * count); \
- for (int index = 0; index < count; ++index) { \
- for (int index2 = 0; index2 < (cols * rows); ++index2) { \
- temp.data()[cols * rows * index + index2] = \
- values[index].constData()[index2]; \
- } \
- } \
- colfunc(location, count * cols, temp.constData()); \
- }
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 2x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x2 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformMatrixArray
- (d->glfuncs->glUniformMatrix2fv, location, values, count, QMatrix2x2, 2, 2);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 2x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x2 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 2x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x3 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform3fv, location, values, count,
- QMatrix2x3, 2, 3);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 2x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x3 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 2x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x4 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform4fv, location, values, count,
- QMatrix2x4, 2, 4);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 2x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x4 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 3x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x2 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform2fv, location, values, count,
- QMatrix3x2, 3, 2);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 3x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x2 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 3x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x3 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformMatrixArray
- (d->glfuncs->glUniformMatrix3fv, location, values, count, QMatrix3x3, 3, 3);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 3x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x3 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 3x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x4 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform4fv, location, values, count,
- QMatrix3x4, 3, 4);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 3x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x4 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 4x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x2 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform2fv, location, values, count,
- QMatrix4x2, 4, 2);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 4x2 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x2 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 4x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x3 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformGenericMatrixArray
- (d->glfuncs->glUniform3fv, location, values, count,
- QMatrix4x3, 4, 3);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 4x3 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x3 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-/*!
- Sets the uniform variable array at \a location in the current
- context to the \a count 4x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x4 *values, int count)
-{
- Q_D(QGLShaderProgram);
- Q_UNUSED(d);
- setUniformMatrixArray
- (d->glfuncs->glUniformMatrix4fv, location, values, count, QMatrix4x4, 4, 4);
-}
-
-/*!
- \overload
-
- Sets the uniform variable array called \a name in the current
- context to the \a count 4x4 matrix elements of \a values.
-
- \sa setAttributeValue()
-*/
-void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x4 *values, int count)
-{
- setUniformValueArray(uniformLocation(name), values, count);
-}
-
-#undef ctx
-
-/*!
- Returns the hardware limit for how many vertices a geometry shader
- can output.
-
- \since 4.7
-
- \sa setGeometryOutputVertexCount()
-*/
-int QGLShaderProgram::maxGeometryOutputVertices() const
-{
- GLint n = 0;
-#if !defined(QT_OPENGL_ES_2)
- Q_D(const QGLShaderProgram);
- if (!QOpenGLContext::currentContext()->isOpenGLES())
- d->glfuncs->glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &n);
-#endif
- return n;
-}
-
-/*!
- Sets the maximum number of vertices the current geometry shader
- program will produce, if active, to \a count.
-
- \since 4.7
-
- This parameter takes effect the next time the program is linked.
-*/
-void QGLShaderProgram::setGeometryOutputVertexCount(int count)
-{
-#ifndef QT_NO_DEBUG
- int max = maxGeometryOutputVertices();
- if (count > max) {
- qWarning("QGLShaderProgram::setGeometryOutputVertexCount: count: %d higher than maximum: %d",
- count, max);
- }
-#endif
- d_func()->geometryVertexCount = count;
-}
-
-
-/*!
- Returns the maximum number of vertices the current geometry shader
- program will produce, if active.
-
- \since 4.7
-
- This parameter takes effect the ntext time the program is linked.
-*/
-int QGLShaderProgram::geometryOutputVertexCount() const
-{
- return d_func()->geometryVertexCount;
-}
-
-
-/*!
- Sets the input type from \a inputType.
-
- This parameter takes effect the next time the program is linked.
-*/
-void QGLShaderProgram::setGeometryInputType(GLenum inputType)
-{
- d_func()->geometryInputType = inputType;
-}
-
-
-/*!
- Returns the geometry shader input type, if active.
-
- This parameter takes effect the next time the program is linked.
-
- \since 4.7
- */
-
-GLenum QGLShaderProgram::geometryInputType() const
-{
- return d_func()->geometryInputType;
-}
-
-
-/*!
- Sets the output type from the geometry shader, if active, to
- \a outputType.
-
- This parameter takes effect the next time the program is linked.
-
- \since 4.7
-*/
-void QGLShaderProgram::setGeometryOutputType(GLenum outputType)
-{
- d_func()->geometryOutputType = outputType;
-}
-
-
-/*!
- Returns the geometry shader output type, if active.
-
- This parameter takes effect the next time the program is linked.
-
- \since 4.7
- */
-GLenum QGLShaderProgram::geometryOutputType() const
-{
- return d_func()->geometryOutputType;
-}
-
-
-/*!
- Returns \c true if shader programs written in the OpenGL Shading
- Language (GLSL) are supported on this system; false otherwise.
-
- The \a context is used to resolve the GLSL extensions.
- If \a context is \nullptr, then QGLContext::currentContext() is
- used.
-*/
-bool QGLShaderProgram::hasOpenGLShaderPrograms(const QGLContext *context)
-{
-#if !defined(QT_OPENGL_ES_2)
- if (!context)
- context = QGLContext::currentContext();
- if (!context)
- return false;
-
- QOpenGLFunctions functions(context->contextHandle());
- return functions.hasOpenGLFeature(QOpenGLFunctions::Shaders);
-#else
- Q_UNUSED(context);
- return true;
-#endif
-}
-
-/*!
- \internal
-*/
-void QGLShaderProgram::shaderDestroyed()
-{
- Q_D(QGLShaderProgram);
- QGLShader *shader = qobject_cast<QGLShader *>(sender());
- if (shader && !d->removingShaders)
- removeShader(shader);
-}
-
-
-#undef ctx
-#undef context
-
-/*!
- Returns \c true if shader programs of type \a type are supported on
- this system; false otherwise.
-
- The \a context is used to resolve the GLSL extensions.
- If \a context is \nullptr, then QGLContext::currentContext() is
- used.
-
- \since 4.7
-*/
-bool QGLShader::hasOpenGLShaders(ShaderType type, const QGLContext *context)
-{
- if (!context)
- context = QGLContext::currentContext();
- if (!context)
- return false;
-
- if ((type & ~(Geometry | Vertex | Fragment)) || type == 0)
- return false;
-
- QOpenGLFunctions functions(context->contextHandle());
- bool resolved = functions.hasOpenGLFeature(QOpenGLFunctions::Shaders);
- if (!resolved)
- return false;
-
- if ((type & Geometry) && !QByteArray((const char *) functions.glGetString(GL_EXTENSIONS)).contains("GL_EXT_geometry_shader4"))
- return false;
-
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h
deleted file mode 100644
index 3ce88197d2..0000000000
--- a/src/opengl/qglshaderprogram.h
+++ /dev/null
@@ -1,303 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QGLSHADERPROGRAM_H
-#define QGLSHADERPROGRAM_H
-
-#include <QtOpenGL/qgl.h>
-#include <QtGui/qvector2d.h>
-#include <QtGui/qvector3d.h>
-#include <QtGui/qvector4d.h>
-#include <QtGui/qmatrix4x4.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QGLShaderProgram;
-class QGLShaderPrivate;
-
-class Q_OPENGL_EXPORT QGLShader : public QObject
-{
- Q_OBJECT
-public:
- enum ShaderTypeBit
- {
- Vertex = 0x0001,
- Fragment = 0x0002,
- Geometry = 0x0004
- };
- Q_DECLARE_FLAGS(ShaderType, ShaderTypeBit)
-
- explicit QGLShader(QGLShader::ShaderType type, QObject *parent = nullptr);
- QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent = nullptr);
- virtual ~QGLShader();
-
- QGLShader::ShaderType shaderType() const;
-
- bool compileSourceCode(const char *source);
- bool compileSourceCode(const QByteArray& source);
- bool compileSourceCode(const QString& source);
- bool compileSourceFile(const QString& fileName);
-
- QByteArray sourceCode() const;
-
- bool isCompiled() const;
- QString log() const;
-
- GLuint shaderId() const;
-
- static bool hasOpenGLShaders(ShaderType type, const QGLContext *context = nullptr);
-
-private:
- friend class QGLShaderProgram;
-
- Q_DISABLE_COPY(QGLShader)
- Q_DECLARE_PRIVATE(QGLShader)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGLShader::ShaderType)
-
-
-class QGLShaderProgramPrivate;
-
-class Q_OPENGL_EXPORT QGLShaderProgram : public QObject
-{
- Q_OBJECT
-public:
- explicit QGLShaderProgram(QObject *parent = nullptr);
- explicit QGLShaderProgram(const QGLContext *context, QObject *parent = nullptr);
- virtual ~QGLShaderProgram();
-
- bool addShader(QGLShader *shader);
- void removeShader(QGLShader *shader);
- QList<QGLShader *> shaders() const;
-
- bool addShaderFromSourceCode(QGLShader::ShaderType type, const char *source);
- bool addShaderFromSourceCode(QGLShader::ShaderType type, const QByteArray& source);
- bool addShaderFromSourceCode(QGLShader::ShaderType type, const QString& source);
- bool addShaderFromSourceFile(QGLShader::ShaderType type, const QString& fileName);
-
- void removeAllShaders();
-
- virtual bool link();
- bool isLinked() const;
- QString log() const;
-
- bool bind();
- void release();
-
- GLuint programId() const;
-
- int maxGeometryOutputVertices() const;
-
- void setGeometryOutputVertexCount(int count);
- int geometryOutputVertexCount() const;
-
- void setGeometryInputType(GLenum inputType);
- GLenum geometryInputType() const;
-
- void setGeometryOutputType(GLenum outputType);
- GLenum geometryOutputType() const;
-
- void bindAttributeLocation(const char *name, int location);
- void bindAttributeLocation(const QByteArray& name, int location);
- void bindAttributeLocation(const QString& name, int location);
-
- int attributeLocation(const char *name) const;
- int attributeLocation(const QByteArray& name) const;
- int attributeLocation(const QString& name) const;
-
- void setAttributeValue(int location, GLfloat value);
- void setAttributeValue(int location, GLfloat x, GLfloat y);
- void setAttributeValue(int location, GLfloat x, GLfloat y, GLfloat z);
- void setAttributeValue(int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void setAttributeValue(int location, const QVector2D& value);
- void setAttributeValue(int location, const QVector3D& value);
- void setAttributeValue(int location, const QVector4D& value);
- void setAttributeValue(int location, const QColor& value);
- void setAttributeValue(int location, const GLfloat *values, int columns, int rows);
-
- void setAttributeValue(const char *name, GLfloat value);
- void setAttributeValue(const char *name, GLfloat x, GLfloat y);
- void setAttributeValue(const char *name, GLfloat x, GLfloat y, GLfloat z);
- void setAttributeValue(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void setAttributeValue(const char *name, const QVector2D& value);
- void setAttributeValue(const char *name, const QVector3D& value);
- void setAttributeValue(const char *name, const QVector4D& value);
- void setAttributeValue(const char *name, const QColor& value);
- void setAttributeValue(const char *name, const GLfloat *values, int columns, int rows);
-
- void setAttributeArray
- (int location, const GLfloat *values, int tupleSize, int stride = 0);
- void setAttributeArray
- (int location, const QVector2D *values, int stride = 0);
- void setAttributeArray
- (int location, const QVector3D *values, int stride = 0);
- void setAttributeArray
- (int location, const QVector4D *values, int stride = 0);
- void setAttributeArray
- (int location, GLenum type, const void *values, int tupleSize, int stride = 0);
- void setAttributeArray
- (const char *name, const GLfloat *values, int tupleSize, int stride = 0);
- void setAttributeArray
- (const char *name, const QVector2D *values, int stride = 0);
- void setAttributeArray
- (const char *name, const QVector3D *values, int stride = 0);
- void setAttributeArray
- (const char *name, const QVector4D *values, int stride = 0);
- void setAttributeArray
- (const char *name, GLenum type, const void *values, int tupleSize, int stride = 0);
-
- void setAttributeBuffer
- (int location, GLenum type, int offset, int tupleSize, int stride = 0);
- void setAttributeBuffer
- (const char *name, GLenum type, int offset, int tupleSize, int stride = 0);
-
- void enableAttributeArray(int location);
- void enableAttributeArray(const char *name);
- void disableAttributeArray(int location);
- void disableAttributeArray(const char *name);
-
- int uniformLocation(const char *name) const;
- int uniformLocation(const QByteArray& name) const;
- int uniformLocation(const QString& name) const;
-
- void setUniformValue(int location, GLfloat value);
- void setUniformValue(int location, GLint value);
- void setUniformValue(int location, GLuint value);
- void setUniformValue(int location, GLfloat x, GLfloat y);
- void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z);
- void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void setUniformValue(int location, const QVector2D& value);
- void setUniformValue(int location, const QVector3D& value);
- void setUniformValue(int location, const QVector4D& value);
- void setUniformValue(int location, const QColor& color);
- void setUniformValue(int location, const QPoint& point);
- void setUniformValue(int location, const QPointF& point);
- void setUniformValue(int location, const QSize& size);
- void setUniformValue(int location, const QSizeF& size);
- void setUniformValue(int location, const QMatrix2x2& value);
- void setUniformValue(int location, const QMatrix2x3& value);
- void setUniformValue(int location, const QMatrix2x4& value);
- void setUniformValue(int location, const QMatrix3x2& value);
- void setUniformValue(int location, const QMatrix3x3& value);
- void setUniformValue(int location, const QMatrix3x4& value);
- void setUniformValue(int location, const QMatrix4x2& value);
- void setUniformValue(int location, const QMatrix4x3& value);
- void setUniformValue(int location, const QMatrix4x4& value);
- void setUniformValue(int location, const GLfloat value[2][2]);
- void setUniformValue(int location, const GLfloat value[3][3]);
- void setUniformValue(int location, const GLfloat value[4][4]);
- void setUniformValue(int location, const QTransform& value);
-
- void setUniformValue(const char *name, GLfloat value);
- void setUniformValue(const char *name, GLint value);
- void setUniformValue(const char *name, GLuint value);
- void setUniformValue(const char *name, GLfloat x, GLfloat y);
- void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z);
- void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void setUniformValue(const char *name, const QVector2D& value);
- void setUniformValue(const char *name, const QVector3D& value);
- void setUniformValue(const char *name, const QVector4D& value);
- void setUniformValue(const char *name, const QColor& color);
- void setUniformValue(const char *name, const QPoint& point);
- void setUniformValue(const char *name, const QPointF& point);
- void setUniformValue(const char *name, const QSize& size);
- void setUniformValue(const char *name, const QSizeF& size);
- void setUniformValue(const char *name, const QMatrix2x2& value);
- void setUniformValue(const char *name, const QMatrix2x3& value);
- void setUniformValue(const char *name, const QMatrix2x4& value);
- void setUniformValue(const char *name, const QMatrix3x2& value);
- void setUniformValue(const char *name, const QMatrix3x3& value);
- void setUniformValue(const char *name, const QMatrix3x4& value);
- void setUniformValue(const char *name, const QMatrix4x2& value);
- void setUniformValue(const char *name, const QMatrix4x3& value);
- void setUniformValue(const char *name, const QMatrix4x4& value);
- void setUniformValue(const char *name, const GLfloat value[2][2]);
- void setUniformValue(const char *name, const GLfloat value[3][3]);
- void setUniformValue(const char *name, const GLfloat value[4][4]);
- void setUniformValue(const char *name, const QTransform& value);
-
- void setUniformValueArray(int location, const GLfloat *values, int count, int tupleSize);
- void setUniformValueArray(int location, const GLint *values, int count);
- void setUniformValueArray(int location, const GLuint *values, int count);
- void setUniformValueArray(int location, const QVector2D *values, int count);
- void setUniformValueArray(int location, const QVector3D *values, int count);
- void setUniformValueArray(int location, const QVector4D *values, int count);
- void setUniformValueArray(int location, const QMatrix2x2 *values, int count);
- void setUniformValueArray(int location, const QMatrix2x3 *values, int count);
- void setUniformValueArray(int location, const QMatrix2x4 *values, int count);
- void setUniformValueArray(int location, const QMatrix3x2 *values, int count);
- void setUniformValueArray(int location, const QMatrix3x3 *values, int count);
- void setUniformValueArray(int location, const QMatrix3x4 *values, int count);
- void setUniformValueArray(int location, const QMatrix4x2 *values, int count);
- void setUniformValueArray(int location, const QMatrix4x3 *values, int count);
- void setUniformValueArray(int location, const QMatrix4x4 *values, int count);
-
- void setUniformValueArray(const char *name, const GLfloat *values, int count, int tupleSize);
- void setUniformValueArray(const char *name, const GLint *values, int count);
- void setUniformValueArray(const char *name, const GLuint *values, int count);
- void setUniformValueArray(const char *name, const QVector2D *values, int count);
- void setUniformValueArray(const char *name, const QVector3D *values, int count);
- void setUniformValueArray(const char *name, const QVector4D *values, int count);
- void setUniformValueArray(const char *name, const QMatrix2x2 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix2x3 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix2x4 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix3x2 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix3x3 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix3x4 *values, int count);
- void setUniformValueArray(const char *name, const QMatrix4x2 *values, int count);
- 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 = nullptr);
-
-private Q_SLOTS:
- void shaderDestroyed();
-
-private:
- Q_DISABLE_COPY(QGLShaderProgram)
- Q_DECLARE_PRIVATE(QGLShaderProgram)
-
- bool init();
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/opengl/qgraphicsshadereffect.cpp b/src/opengl/qgraphicsshadereffect.cpp
deleted file mode 100644
index 97b83a6b3d..0000000000
--- a/src/opengl/qgraphicsshadereffect.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qgraphicsshadereffect_p.h"
-
-#include "qglshaderprogram.h"
-#include "gl2paintengineex/qglcustomshaderstage_p.h"
-#define QGL_HAVE_CUSTOM_SHADERS 1
-#include <QtGui/qpainter.h>
-#include <QtWidgets/qgraphicsitem.h>
-#include <private/qgraphicseffect_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*#
- \class QGraphicsShaderEffect
- \inmodule QtOpenGL
- \brief The QGraphicsShaderEffect class is the base class for creating
- custom GLSL shader effects in a QGraphicsScene.
- \since 4.6
- \ingroup multimedia
- \ingroup graphicsview-api
-
- The specific effect is defined by a fragment of GLSL source code
- supplied to setPixelShaderFragment(). This source code must define a
- function with the signature
- \c{lowp vec4 customShader(lowp sampler2D imageTexture, highp vec2 textureCoords)}
- that returns the source pixel value
- to use in the paint engine's shader program. The shader fragment
- is linked with the regular shader code used by the GL2 paint engine
- to construct a complete QGLShaderProgram.
-
- The following example shader converts the incoming pixmap to
- grayscale and then applies a colorize operation using the
- \c effectColor value:
-
- \snippet code/src_opengl_qgraphicsshadereffect.cpp 0
-
- To use this shader code, it is necessary to define a subclass
- of QGraphicsShaderEffect as follows:
-
- \snippet code/src_opengl_qgraphicsshadereffect.cpp 1
-
- The setUniforms() function is called when the effect is about
- to be used for drawing to give the subclass the opportunity to
- set effect-specific uniform variables.
-
- QGraphicsShaderEffect is only supported when the GL2 paint engine
- is in use. When any other paint engine is in use (GL1, raster, etc),
- the drawItem() method will draw its item argument directly with
- no effect applied.
-
- \sa QGraphicsEffect
-*/
-
-static const char qglslDefaultImageFragmentShader[] = "\
- lowp vec4 customShader(lowp sampler2D imageTexture, highp vec2 textureCoords) { \
- return texture2D(imageTexture, textureCoords); \
- }\n";
-
-#ifdef QGL_HAVE_CUSTOM_SHADERS
-
-class QGLCustomShaderEffectStage : public QGLCustomShaderStage
-{
-public:
- QGLCustomShaderEffectStage
- (QGraphicsShaderEffect *e, const QByteArray& source)
- : QGLCustomShaderStage(),
- effect(e)
- {
- setSource(source);
- }
-
- void setUniforms(QGLShaderProgram *program) override;
-
- QGraphicsShaderEffect *effect;
-};
-
-void QGLCustomShaderEffectStage::setUniforms(QGLShaderProgram *program)
-{
- effect->setUniforms(program);
-}
-
-#endif
-
-class QGraphicsShaderEffectPrivate : public QGraphicsEffectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsShaderEffect)
-public:
- QGraphicsShaderEffectPrivate()
- : pixelShaderFragment(qglslDefaultImageFragmentShader)
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- , customShaderStage(0)
-#endif
- {
- }
-
- QByteArray pixelShaderFragment;
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- QGLCustomShaderEffectStage *customShaderStage;
-#endif
-};
-
-/*#
- Constructs a shader effect and attaches it to \a parent.
-*/
-QGraphicsShaderEffect::QGraphicsShaderEffect(QObject *parent)
- : QGraphicsEffect(*new QGraphicsShaderEffectPrivate(), parent)
-{
-}
-
-/*#
- Destroys this shader effect.
-*/
-QGraphicsShaderEffect::~QGraphicsShaderEffect()
-{
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- Q_D(QGraphicsShaderEffect);
- delete d->customShaderStage;
-#endif
-}
-
-/*#
- Returns the source code for the pixel shader fragment for
- this shader effect. The default is a shader that copies
- its incoming pixmap directly to the output with no effect
- applied.
-
- \sa setPixelShaderFragment()
-*/
-QByteArray QGraphicsShaderEffect::pixelShaderFragment() const
-{
- Q_D(const QGraphicsShaderEffect);
- return d->pixelShaderFragment;
-}
-
-/*#
- Sets the source code for the pixel shader fragment for
- this shader effect to \a code.
-
- The \a code must define a GLSL function with the signature
- \c{lowp vec4 customShader(lowp sampler2D imageTexture, highp vec2 textureCoords)}
- that returns the source pixel value to use in the paint engine's
- shader program. The following is the default pixel shader fragment,
- which draws a pixmap with no effect applied:
-
- \snippet code/src_opengl_qgraphicsshadereffect.cpp 2
-
- \sa pixelShaderFragment(), setUniforms()
-*/
-void QGraphicsShaderEffect::setPixelShaderFragment(const QByteArray& code)
-{
- Q_D(QGraphicsShaderEffect);
- if (d->pixelShaderFragment != code) {
- d->pixelShaderFragment = code;
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- delete d->customShaderStage;
- d->customShaderStage = 0;
-#endif
- }
-}
-
-/*#
- \reimp
-*/
-void QGraphicsShaderEffect::draw(QPainter *painter)
-{
- Q_D(QGraphicsShaderEffect);
-
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- // Set the custom shader on the paint engine. The setOnPainter()
- // call may fail if the paint engine is not GL2. In that case,
- // we fall through to drawing the pixmap normally.
- if (!d->customShaderStage) {
- d->customShaderStage = new QGLCustomShaderEffectStage
- (this, d->pixelShaderFragment);
- }
- bool usingShader = d->customShaderStage->setOnPainter(painter);
-
- QPoint offset;
- if (sourceIsPixmap()) {
- // No point in drawing in device coordinates (pixmap will be scaled anyways).
- const QPixmap pixmap = sourcePixmap(Qt::LogicalCoordinates, &offset);
- painter->drawPixmap(offset, pixmap);
- } else {
- // Draw pixmap in device coordinates to avoid pixmap scaling.
- const QPixmap pixmap = sourcePixmap(Qt::DeviceCoordinates, &offset);
- QTransform restoreTransform = painter->worldTransform();
- painter->setWorldTransform(QTransform());
- painter->drawPixmap(offset, pixmap);
- painter->setWorldTransform(restoreTransform);
- }
-
- // Remove the custom shader to return to normal painting operations.
- if (usingShader)
- d->customShaderStage->removeFromPainter(painter);
-#else
- drawSource(painter);
-#endif
-}
-
-/*#
- Sets the custom uniform variables on this shader effect to
- be dirty. The setUniforms() function will be called the next
- time the shader program corresponding to this effect is used.
-
- This function is typically called by subclasses when an
- effect-specific parameter is changed by the application.
-
- \sa setUniforms()
-*/
-void QGraphicsShaderEffect::setUniformsDirty()
-{
-#ifdef QGL_HAVE_CUSTOM_SHADERS
- Q_D(QGraphicsShaderEffect);
- if (d->customShaderStage)
- d->customShaderStage->setUniformsDirty();
-#endif
-}
-
-/*#
- Sets custom uniform variables on the current GL context when
- \a program is about to be used by the paint engine.
-
- This function should be overridden if the shader set with
- setPixelShaderFragment() has additional parameters beyond
- those that the paint engine normally sets itself.
-
- \sa setUniformsDirty()
-*/
-void QGraphicsShaderEffect::setUniforms(QGLShaderProgram *program)
-{
- Q_UNUSED(program);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/opengl/qopengldebug.cpp b/src/opengl/qopengldebug.cpp
index 310006feaf..a69f6069dc 100644
--- a/src/gui/opengl/qopengldebug.cpp
+++ b/src/opengl/qopengldebug.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtGui module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE
/*!
\class QOpenGLDebugMessage
\brief The QOpenGLDebugMessage class wraps an OpenGL debug message.
- \inmodule QtGui
+ \inmodule QtOpenGL
\reentrant
\since 5.1
\ingroup shared
@@ -72,7 +72,7 @@ QT_BEGIN_NAMESPACE
/*!
\class QOpenGLDebugLogger
\brief The QOpenGLDebugLogger enables logging of OpenGL debugging messages.
- \inmodule QtGui
+ \inmodule QtOpenGL
\since 5.1
\ingroup painting-3D
diff --git a/src/gui/opengl/qopengldebug.h b/src/opengl/qopengldebug.h
index 7363985d60..fef2782302 100644
--- a/src/gui/opengl/qopengldebug.h
+++ b/src/opengl/qopengldebug.h
@@ -3,7 +3,7 @@
** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtGui module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -40,7 +40,7 @@
#ifndef QOPENGLDEBUG_H
#define QOPENGLDEBUG_H
-#include <QtGui/qtguiglobal.h>
+#include <QtOpenGL/qtopenglglobal.h>
#ifndef QT_NO_OPENGL
@@ -63,7 +63,7 @@ class QOpenGLDebugLogger;
class QOpenGLDebugLoggerPrivate;
class QOpenGLDebugMessagePrivate;
-class Q_GUI_EXPORT QOpenGLDebugMessage
+class Q_OPENGL_EXPORT QOpenGLDebugMessage
{
public:
enum Source {
@@ -145,15 +145,15 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QOpenGLDebugMessage::Types)
Q_DECLARE_OPERATORS_FOR_FLAGS(QOpenGLDebugMessage::Severities)
#ifndef QT_NO_DEBUG_STREAM
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, const QOpenGLDebugMessage &message);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Source source);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Type type);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Severity severity);
+Q_OPENGL_EXPORT QDebug operator<<(QDebug debug, const QOpenGLDebugMessage &message);
+Q_OPENGL_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Source source);
+Q_OPENGL_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Type type);
+Q_OPENGL_EXPORT QDebug operator<<(QDebug debug, QOpenGLDebugMessage::Severity severity);
#endif
class QOpenGLDebugLoggerPrivate;
-class Q_GUI_EXPORT QOpenGLDebugLogger : public QObject
+class Q_OPENGL_EXPORT QOpenGLDebugLogger : public QObject
{
Q_OBJECT
Q_PROPERTY(LoggingMode loggingMode READ loggingMode)
diff --git a/src/gui/opengl/qopenglqueryhelper_p.h b/src/opengl/qopenglqueryhelper_p.h
index ad91ca9f96..f3ed997f98 100644
--- a/src/gui/opengl/qopenglqueryhelper_p.h
+++ b/src/opengl/qopenglqueryhelper_p.h
@@ -3,7 +3,7 @@
** Copyright (C) 2013 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtGui module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
diff --git a/src/gui/opengl/qopengltimerquery.cpp b/src/opengl/qopengltimerquery.cpp
index a4e10b42f7..44955d48fc 100644
--- a/src/gui/opengl/qopengltimerquery.cpp
+++ b/src/opengl/qopengltimerquery.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2013 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtGui module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -238,7 +238,7 @@ GLuint64 QOpenGLTimerQueryPrivate::result() const
/*!
\class QOpenGLTimerQuery
\brief The QOpenGLTimerQuery class wraps an OpenGL timer query object.
- \inmodule QtGui
+ \inmodule QtOpenGL
\since 5.1
\ingroup painting-3D
@@ -645,7 +645,7 @@ void QOpenGLTimeMonitorPrivate::reset()
/*!
\class QOpenGLTimeMonitor
\brief The QOpenGLTimeMonitor class wraps a sequence of OpenGL timer query objects.
- \inmodule QtGui
+ \inmodule QtOpenGL
\since 5.1
\ingroup painting-3D
diff --git a/src/gui/opengl/qopengltimerquery.h b/src/opengl/qopengltimerquery.h
index 27da74a3fb..a779240108 100644
--- a/src/gui/opengl/qopengltimerquery.h
+++ b/src/opengl/qopengltimerquery.h
@@ -3,7 +3,7 @@
** Copyright (C) 2013 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtGui module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -40,7 +40,7 @@
#ifndef QOPENGLTIMERQUERY_H
#define QOPENGLTIMERQUERY_H
-#include <QtGui/qtguiglobal.h>
+#include <QtOpenGL/qtopenglglobal.h>
#if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_2)
@@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE
class QOpenGLTimerQueryPrivate;
-class Q_GUI_EXPORT QOpenGLTimerQuery : public QObject
+class Q_OPENGL_EXPORT QOpenGLTimerQuery : public QObject
{
Q_OBJECT
@@ -79,7 +79,7 @@ private:
class QOpenGLTimeMonitorPrivate;
-class Q_GUI_EXPORT QOpenGLTimeMonitor : public QObject
+class Q_OPENGL_EXPORT QOpenGLTimeMonitor : public QObject
{
Q_OBJECT
diff --git a/src/widgets/kernel/qopenglwidget.cpp b/src/opengl/qopenglwidget.cpp
index 90622fd21e..a6c63ae034 100644
--- a/src/widgets/kernel/qopenglwidget.cpp
+++ b/src/opengl/qopenglwidget.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtWidgets module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -59,7 +59,7 @@ QT_BEGIN_NAMESPACE
/*!
\class QOpenGLWidget
- \inmodule QtWidgets
+ \inmodule QtOpenGL
\since 5.4
\brief The QOpenGLWidget class is a widget for rendering OpenGL graphics.
diff --git a/src/widgets/kernel/qopenglwidget.h b/src/opengl/qopenglwidget.h
index 9eb4a9ba5a..b331880b5d 100644
--- a/src/widgets/kernel/qopenglwidget.h
+++ b/src/opengl/qopenglwidget.h
@@ -3,7 +3,7 @@
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the QtWidgets module of the Qt Toolkit.
+** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -40,7 +40,7 @@
#ifndef QOPENGLWIDGET_H
#define QOPENGLWIDGET_H
-#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtOpenGL/qtopenglglobal.h>
#ifndef QT_NO_OPENGL
@@ -52,7 +52,7 @@ QT_BEGIN_NAMESPACE
class QOpenGLWidgetPrivate;
-class Q_WIDGETS_EXPORT QOpenGLWidget : public QWidget
+class Q_OPENGL_EXPORT QOpenGLWidget : public QWidget
{
Q_OBJECT
Q_DECLARE_PRIVATE(QOpenGLWidget)
diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
index 64ceb69c23..ca78063f08 100644
--- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
+++ b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
@@ -1354,50 +1354,65 @@ static inline FT_Matrix QTransformToFTMatrix(const QTransform &matrix)
return m;
}
-QFontEngineFT::QGlyphSet *QFontEngineFT::loadGlyphSet(const QTransform &matrix)
+QFontEngineFT::QGlyphSet *QFontEngineFT::TransformedGlyphSets::findSet(const QTransform &matrix, const QFontDef &fontDef)
{
- if (matrix.type() > QTransform::TxShear || !cacheEnabled)
- return nullptr;
-
- // FT_Set_Transform only supports scalable fonts
- if (!FT_IS_SCALABLE(freetype->face))
- return matrix.type() <= QTransform::TxTranslate ? &defaultGlyphSet : nullptr;
-
FT_Matrix m = QTransformToFTMatrix(matrix);
- QGlyphSet *gs = nullptr;
-
- for (int i = 0; i < transformedGlyphSets.count(); ++i) {
- const QGlyphSet &g = transformedGlyphSets.at(i);
- if (g.transformationMatrix.xx == m.xx
- && g.transformationMatrix.xy == m.xy
- && g.transformationMatrix.yx == m.yx
- && g.transformationMatrix.yy == m.yy) {
+ int i = 0;
+ for (; i < nSets; ++i) {
+ QGlyphSet *g = sets[i];
+ if (!g)
+ break;
+ if (g->transformationMatrix.xx == m.xx
+ && g->transformationMatrix.xy == m.xy
+ && g->transformationMatrix.yx == m.yx
+ && g->transformationMatrix.yy == m.yy) {
// found a match, move it to the front
- transformedGlyphSets.move(i, 0);
- gs = &transformedGlyphSets[0];
- break;
+ moveToFront(i);
+ return g;
}
}
- if (!gs) {
- // don't cache more than 10 transformations
- if (transformedGlyphSets.count() >= 10) {
- transformedGlyphSets.move(transformedGlyphSets.size() - 1, 0);
- } else {
- transformedGlyphSets.prepend(QGlyphSet());
- }
- gs = &transformedGlyphSets[0];
- gs->clear();
- gs->transformationMatrix = m;
- gs->outline_drawing = fontDef.pixelSize * fontDef.pixelSize * qAbs(matrix.determinant()) > QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE;
- }
+ // don't cache more than nSets transformations
+ if (i == nSets)
+ // reuse the last set
+ --i;
+ moveToFront(nSets - 1);
+ if (!sets[0])
+ sets[0] = new QGlyphSet;
+ QGlyphSet *gs = sets[0];
+ gs->clear();
+ gs->transformationMatrix = m;
+ gs->outline_drawing = fontDef.pixelSize * fontDef.pixelSize * qAbs(matrix.determinant()) > QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE;
Q_ASSERT(gs != nullptr);
return gs;
}
+void QFontEngineFT::TransformedGlyphSets::moveToFront(int i)
+{
+ QGlyphSet *g = sets[i];
+ while (i > 0) {
+ sets[i] = sets[i - 1];
+ --i;
+ }
+ sets[0] = g;
+}
+
+
+QFontEngineFT::QGlyphSet *QFontEngineFT::loadGlyphSet(const QTransform &matrix)
+{
+ if (matrix.type() > QTransform::TxShear || !cacheEnabled)
+ return 0;
+
+ // FT_Set_Transform only supports scalable fonts
+ if (!FT_IS_SCALABLE(freetype->face))
+ return matrix.type() <= QTransform::TxTranslate ? &defaultGlyphSet : nullptr;
+
+ return transformedGlyphSets.findSet(matrix, fontDef);
+}
+
void QFontEngineFT::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
{
FT_Face face = lockFace(Unscaled);
diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h b/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h
index 2e3aef6979..8019588bf5 100644
--- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h
+++ b/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h
@@ -63,6 +63,8 @@
#include <qmutex.h>
+#include <string.h>
+
QT_BEGIN_NAMESPACE
class QFontEngineFTRawFont;
@@ -170,6 +172,7 @@ public:
inline bool isGlyphMissing(glyph_t index) const { return missing_glyphs.contains(index); }
inline void setGlyphMissing(glyph_t index) const { missing_glyphs.insert(index); }
private:
+ Q_DISABLE_COPY(QGlyphSet);
mutable QHash<GlyphAndSubPixelPosition, Glyph *> glyph_data; // maps from glyph index to glyph data
mutable QSet<glyph_t> missing_glyphs;
mutable Glyph *fast_glyph_data[256]; // for fast lookup of glyphs < 256
@@ -310,7 +313,18 @@ private:
GlyphFormat defaultFormat;
FT_Matrix matrix;
- QList<QGlyphSet> transformedGlyphSets;
+ struct TransformedGlyphSets {
+ enum { nSets = 10 };
+ QGlyphSet *sets[nSets];
+
+ QGlyphSet *findSet(const QTransform &matrix, const QFontDef &fontDef);
+ TransformedGlyphSets() { std::fill(&sets[0], &sets[nSets], nullptr); }
+ ~TransformedGlyphSets() { qDeleteAll(&sets[0], &sets[nSets]); }
+ private:
+ void moveToFront(int i);
+ Q_DISABLE_COPY(TransformedGlyphSets);
+ };
+ TransformedGlyphSets transformedGlyphSets;
mutable QGlyphSet defaultGlyphSet;
QFontEngine::FaceId face_id;
@@ -326,6 +340,9 @@ private:
QFixed scalableBitmapScaleFactor;
};
+Q_DECLARE_TYPEINFO(QFontEngineFT::QGlyphSet, Q_MOVABLE_TYPE);
+
+
inline uint qHash(const QFontEngineFT::GlyphAndSubPixelPosition &g)
{
return (g.glyph << 8) | (g.subPixelPosition * 10).round().toInt();
diff --git a/src/platformsupport/kmsconvenience/qkmsdevice.cpp b/src/platformsupport/kmsconvenience/qkmsdevice.cpp
index 18f7b5e23b..8cd7f9b368 100644
--- a/src/platformsupport/kmsconvenience/qkmsdevice.cpp
+++ b/src/platformsupport/kmsconvenience/qkmsdevice.cpp
@@ -396,7 +396,7 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources,
drmFormat = DRM_FORMAT_XRGB8888;
drmFormatExplicit = false;
}
- qCDebug(qLcKmsDebug) << "Format is" << hex << drmFormat << dec << "requested_by_user =" << drmFormatExplicit
+ qCDebug(qLcKmsDebug) << "Format is" << Qt::hex << drmFormat << Qt::dec << "requested_by_user =" << drmFormatExplicit
<< "for output" << connectorName;
const QString cloneSource = userConnectorConfig.value(QStringLiteral("clones")).toString();
diff --git a/src/platformsupport/linuxofono/linuxofono.pro b/src/platformsupport/linuxofono/linuxofono.pro
new file mode 100644
index 0000000000..1bc5b10225
--- /dev/null
+++ b/src/platformsupport/linuxofono/linuxofono.pro
@@ -0,0 +1,15 @@
+TARGET = QtLinuxOfonoSupport
+MODULE = linuxofono_support
+
+QT = core dbus
+CONFIG += static internal_module
+
+DEFINES += QT_NO_CAST_FROM_ASCII
+
+HEADERS += \
+ qofonoservice_linux_p.h
+
+SOURCES += \
+ qofonoservice_linux.cpp
+
+load(qt_module)
diff --git a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp b/src/platformsupport/linuxofono/qofonoservice_linux.cpp
index 05f9b3ca17..792c703966 100644
--- a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
+++ b/src/platformsupport/linuxofono/qofonoservice_linux.cpp
@@ -148,7 +148,7 @@ QOfonoModemInterface::QOfonoModemInterface(const QString &dbusPathName, QObject
{
QDBusConnection::systemBus().connect(QLatin1String(OFONO_SERVICE),
path(),
- OFONO_MODEM_INTERFACE,
+ QLatin1String(OFONO_MODEM_INTERFACE),
QLatin1String("PropertyChanged"),
this,SLOT(propertyChanged(QString,QDBusVariant)));
}
diff --git a/src/plugins/bearer/linux_common/qofonoservice_linux_p.h b/src/platformsupport/linuxofono/qofonoservice_linux_p.h
index 62df5d4fa7..62df5d4fa7 100644
--- a/src/plugins/bearer/linux_common/qofonoservice_linux_p.h
+++ b/src/platformsupport/linuxofono/qofonoservice_linux_p.h
diff --git a/src/platformsupport/platformsupport.pro b/src/platformsupport/platformsupport.pro
index 877665ff06..4b41b29c12 100644
--- a/src/platformsupport/platformsupport.pro
+++ b/src/platformsupport/platformsupport.pro
@@ -45,3 +45,7 @@ darwin {
qtConfig(vulkan): \
SUBDIRS += vkconvenience
+
+!android:linux*:qtHaveModule(dbus) \
+ SUBDIRS += linuxofono
+
diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp
index ccf2180dc5..6fadea5d28 100644
--- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp
+++ b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp
@@ -48,7 +48,9 @@
#include <QDebug>
#include <QtEndian>
#include <QBuffer>
-#include <private/qkeysequence_p.h>
+#if QT_CONFIG(shortcut)
+# include <private/qkeysequence_p.h>
+#endif
#include <qpa/qplatformmenu.h>
#include "qdbusplatformmenu_p.h"
diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h
index 8a31f82fb0..aa0f303416 100644
--- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h
+++ b/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h
@@ -96,7 +96,7 @@ public:
void setChecked(bool isChecked) override;
bool hasExclusiveGroup() const { return m_hasExclusiveGroup; }
void setHasExclusiveGroup(bool hasExclusiveGroup) override;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
QKeySequence shortcut() const { return m_shortcut; }
void setShortcut(const QKeySequence& shortcut) override;
#endif
@@ -123,7 +123,9 @@ private:
bool m_hasExclusiveGroup : 1;
short /*unused*/ : 6;
short m_dbusID : 16;
+#if QT_CONFIG(shortcut)
QKeySequence m_shortcut;
+#endif
};
class QDBusPlatformMenu : public QPlatformMenu
diff --git a/src/plugins/bearer/android/src/qandroidbearerengine.cpp b/src/plugins/bearer/android/src/qandroidbearerengine.cpp
index a43ed69570..ad9895e0cf 100644
--- a/src/plugins/bearer/android/src/qandroidbearerengine.cpp
+++ b/src/plugins/bearer/android/src/qandroidbearerengine.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "qandroidbearerengine.h"
-#include "../../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include "wrappers/androidconnectivitymanager.h"
#ifndef QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/android/src/qandroidbearerengine.h b/src/plugins/bearer/android/src/qandroidbearerengine.h
index 837b02232d..867d04d886 100644
--- a/src/plugins/bearer/android/src/qandroidbearerengine.h
+++ b/src/plugins/bearer/android/src/qandroidbearerengine.h
@@ -40,7 +40,7 @@
#ifndef QANDROIDBEARERENGINE_H
#define QANDROIDBEARERENGINE_H
-#include "../../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include <QAbstractEventDispatcher>
#include <QAbstractNativeEventFilter>
diff --git a/src/plugins/bearer/android/src/src.pro b/src/plugins/bearer/android/src/src.pro
index eb0738386c..fcd599dffe 100644
--- a/src/plugins/bearer/android/src/src.pro
+++ b/src/plugins/bearer/android/src/src.pro
@@ -2,13 +2,10 @@ TARGET = qandroidbearer
QT = core-private network-private
-HEADERS += qandroidbearerengine.h \
- ../../qnetworksession_impl.h \
- ../../qbearerengine_impl.h
+HEADERS += qandroidbearerengine.h
SOURCES += main.cpp \
- qandroidbearerengine.cpp \
- ../../qnetworksession_impl.cpp
+ qandroidbearerengine.cpp
include(wrappers/wrappers.pri)
diff --git a/src/plugins/bearer/connman/connman.pro b/src/plugins/bearer/connman/connman.pro
index 065ed11dad..03e94cfe6a 100644
--- a/src/plugins/bearer/connman/connman.pro
+++ b/src/plugins/bearer/connman/connman.pro
@@ -1,18 +1,13 @@
TARGET = qconnmanbearer
-QT = core network-private dbus
+QT = core network-private dbus linuxofono_support_private
HEADERS += qconnmanservice_linux_p.h \
- ../linux_common/qofonoservice_linux_p.h \
- qconnmanengine.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h
+ qconnmanengine.h
SOURCES += main.cpp \
qconnmanservice_linux.cpp \
- ../linux_common/qofonoservice_linux.cpp \
- qconnmanengine.cpp \
- ../qnetworksession_impl.cpp
+ qconnmanengine.cpp
OTHER_FILES += connman.json
diff --git a/src/plugins/bearer/connman/qconnmanengine.cpp b/src/plugins/bearer/connman/qconnmanengine.cpp
index 8b2076bd18..a673834825 100644
--- a/src/plugins/bearer/connman/qconnmanengine.cpp
+++ b/src/plugins/bearer/connman/qconnmanengine.cpp
@@ -39,7 +39,7 @@
#include "qconnmanengine.h"
#include "qconnmanservice_linux_p.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
diff --git a/src/plugins/bearer/connman/qconnmanengine.h b/src/plugins/bearer/connman/qconnmanengine.h
index ef80d38fa2..969eed45b1 100644
--- a/src/plugins/bearer/connman/qconnmanengine.h
+++ b/src/plugins/bearer/connman/qconnmanengine.h
@@ -51,10 +51,10 @@
// We mean it.
//
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include "qconnmanservice_linux_p.h"
-#include "../linux_common/qofonoservice_linux_p.h"
+#include <private/qofonoservice_linux_p.h>
#include <QMap>
#include <QVariant>
diff --git a/src/plugins/bearer/corewlan/corewlan.pro b/src/plugins/bearer/corewlan/corewlan.pro
index 1dc09ebdd6..4f08eaba71 100644
--- a/src/plugins/bearer/corewlan/corewlan.pro
+++ b/src/plugins/bearer/corewlan/corewlan.pro
@@ -7,12 +7,9 @@ qtConfig(corewlan) {
LIBS += -framework CoreWLAN -framework Security
}
-HEADERS += qcorewlanengine.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h
+HEADERS += qcorewlanengine.h
-SOURCES += main.cpp \
- ../qnetworksession_impl.cpp
+SOURCES += main.cpp
OBJECTIVE_SOURCES += qcorewlanengine.mm
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.h b/src/plugins/bearer/corewlan/qcorewlanengine.h
index 6dddee66a4..8775474c09 100644
--- a/src/plugins/bearer/corewlan/qcorewlanengine.h
+++ b/src/plugins/bearer/corewlan/qcorewlanengine.h
@@ -40,7 +40,7 @@
#ifndef QCOREWLANENGINE_H
#define QCOREWLANENGINE_H
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include <QMap>
#include <QTimer>
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm
index 66f2ed017b..01c6df74d5 100644
--- a/src/plugins/bearer/corewlan/qcorewlanengine.mm
+++ b/src/plugins/bearer/corewlan/qcorewlanengine.mm
@@ -38,7 +38,7 @@
****************************************************************************/
#include "qcorewlanengine.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
diff --git a/src/plugins/bearer/generic/generic.pro b/src/plugins/bearer/generic/generic.pro
index f30bdc4951..14b858b301 100644
--- a/src/plugins/bearer/generic/generic.pro
+++ b/src/plugins/bearer/generic/generic.pro
@@ -3,11 +3,8 @@ TARGET = qgenericbearer
QT = core-private network-private
HEADERS += qgenericengine.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h \
../platformdefs_win.h
SOURCES += qgenericengine.cpp \
- ../qnetworksession_impl.cpp \
main.cpp
OTHER_FILES += generic.json
diff --git a/src/plugins/bearer/generic/qgenericengine.cpp b/src/plugins/bearer/generic/qgenericengine.cpp
index b1f28849a7..a5fba15789 100644
--- a/src/plugins/bearer/generic/qgenericengine.cpp
+++ b/src/plugins/bearer/generic/qgenericengine.cpp
@@ -41,7 +41,7 @@
#define WIN32_LEAN_AND_MEAN 1
#include "qgenericengine.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
diff --git a/src/plugins/bearer/generic/qgenericengine.h b/src/plugins/bearer/generic/qgenericengine.h
index 79c71ca7a3..6b8fb4cd0f 100644
--- a/src/plugins/bearer/generic/qgenericengine.h
+++ b/src/plugins/bearer/generic/qgenericengine.h
@@ -40,7 +40,7 @@
#ifndef QGENERICENGINE_H
#define QGENERICENGINE_H
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include <QMap>
#include <QTimer>
diff --git a/src/plugins/bearer/nativewifi/nativewifi.pro b/src/plugins/bearer/nativewifi/nativewifi.pro
index da7f2da353..41bde99341 100644
--- a/src/plugins/bearer/nativewifi/nativewifi.pro
+++ b/src/plugins/bearer/nativewifi/nativewifi.pro
@@ -3,13 +3,10 @@ TARGET = qnativewifibearer
QT = core-private network-private
HEADERS += qnativewifiengine.h \
- platformdefs.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h
+ platformdefs.h
SOURCES += main.cpp \
- qnativewifiengine.cpp \
- ../qnetworksession_impl.cpp
+ qnativewifiengine.cpp
OTHER_FILES += nativewifi.json
diff --git a/src/plugins/bearer/nativewifi/qnativewifiengine.cpp b/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
index 777b4eea59..ca8700e63b 100644
--- a/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
+++ b/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
@@ -39,7 +39,7 @@
#include "qnativewifiengine.h"
#include "platformdefs.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
diff --git a/src/plugins/bearer/nativewifi/qnativewifiengine.h b/src/plugins/bearer/nativewifi/qnativewifiengine.h
index ab8d949c9a..24e97bf6df 100644
--- a/src/plugins/bearer/nativewifi/qnativewifiengine.h
+++ b/src/plugins/bearer/nativewifi/qnativewifiengine.h
@@ -51,7 +51,7 @@
// We mean it.
//
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include <QtCore/qtimer.h>
diff --git a/src/plugins/bearer/networkmanager/networkmanager.pro b/src/plugins/bearer/networkmanager/networkmanager.pro
index e71c93f66f..3ca217f974 100644
--- a/src/plugins/bearer/networkmanager/networkmanager.pro
+++ b/src/plugins/bearer/networkmanager/networkmanager.pro
@@ -1,18 +1,13 @@
TARGET = qnmbearer
-QT = core network-private dbus
+QT = core network-private dbus linuxofono_support_private
HEADERS += qnetworkmanagerservice.h \
- qnetworkmanagerengine.h \
- ../linux_common/qofonoservice_linux_p.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h
+ qnetworkmanagerengine.h
SOURCES += main.cpp \
qnetworkmanagerservice.cpp \
- qnetworkmanagerengine.cpp \
- ../linux_common/qofonoservice_linux.cpp \
- ../qnetworksession_impl.cpp
+ qnetworkmanagerengine.cpp
OTHER_FILES += networkmanager.json
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
index 85a9f9b9e0..cba2221587 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
@@ -39,7 +39,7 @@
#include "qnetworkmanagerengine.h"
#include "qnetworkmanagerservice.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
@@ -53,7 +53,6 @@
#include <QDBusInterface>
#include <QDBusMessage>
#include <QDBusReply>
-#include "../linux_common/qofonoservice_linux_p.h"
#ifndef QT_NO_DBUS
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
index a95c68abdf..c624d6087d 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
@@ -51,11 +51,11 @@
// We mean it.
//
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include "qnetworkmanagerservice.h"
-#include "../linux_common/qofonoservice_linux_p.h"
+#include <private/qofonoservice_linux_p.h>
#include <QMap>
#include <QVariant>
diff --git a/src/plugins/bearer/nla/nla.pro b/src/plugins/bearer/nla/nla.pro
index 76f3279d25..2582dc7cd4 100644
--- a/src/plugins/bearer/nla/nla.pro
+++ b/src/plugins/bearer/nla/nla.pro
@@ -5,13 +5,10 @@ QT = core core-private network network-private
QMAKE_USE_PRIVATE += ws2_32
HEADERS += qnlaengine.h \
- ../platformdefs_win.h \
- ../qnetworksession_impl.h \
- ../qbearerengine_impl.h
+ ../platformdefs_win.h
SOURCES += main.cpp \
- qnlaengine.cpp \
- ../qnetworksession_impl.cpp
+ qnlaengine.cpp
OTHER_FILES += nla.json
diff --git a/src/plugins/bearer/nla/qnlaengine.cpp b/src/plugins/bearer/nla/qnlaengine.cpp
index e1e60389f1..ab3c0d0e3a 100644
--- a/src/plugins/bearer/nla/qnlaengine.cpp
+++ b/src/plugins/bearer/nla/qnlaengine.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "qnlaengine.h"
-#include "../qnetworksession_impl.h"
+#include <private/qnetworksession_impl_p.h>
#include <QtNetwork/private/qnetworkconfiguration_p.h>
diff --git a/src/plugins/bearer/nla/qnlaengine.h b/src/plugins/bearer/nla/qnlaengine.h
index ab014ff776..90efa50201 100644
--- a/src/plugins/bearer/nla/qnlaengine.h
+++ b/src/plugins/bearer/nla/qnlaengine.h
@@ -51,7 +51,7 @@
// We mean it.
//
-#include "../qbearerengine_impl.h"
+#include <private/qbearerengine_impl_p.h>
#include <QtNetwork/private/qnativesocketengine_p.h>
diff --git a/src/plugins/platforms/android/android.pro b/src/plugins/platforms/android/android.pro
index 730247cd7f..61cac51633 100644
--- a/src/plugins/platforms/android/android.pro
+++ b/src/plugins/platforms/android/android.pro
@@ -16,7 +16,6 @@ INCLUDEPATH += \
$$QT_SOURCE_TREE/src/3rdparty/android
SOURCES += $$PWD/main.cpp \
- $$PWD/androidplatformplugin.cpp \
$$PWD/androidcontentfileengine.cpp \
$$PWD/androiddeadlockprotector.cpp \
$$PWD/androidjnimain.cpp \
diff --git a/src/plugins/platforms/android/androidplatformplugin.cpp b/src/plugins/platforms/android/androidplatformplugin.cpp
deleted file mode 100644
index 297e167f47..0000000000
--- a/src/plugins/platforms/android/androidplatformplugin.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qpa/qplatformintegrationplugin.h>
-#include "qandroidplatformintegration.h"
-
-QT_BEGIN_NAMESPACE
-
-class QAndroidPlatformIntegrationPlugin: public QPlatformIntegrationPlugin
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "android.json")
-public:
- QPlatformIntegration *create(const QString &key, const QStringList &paramList) override;
-};
-
-
-QPlatformIntegration *QAndroidPlatformIntegrationPlugin::create(const QString &key, const QStringList &paramList)
-{
- Q_UNUSED(paramList);
- if (!key.compare(QLatin1String("android"), Qt::CaseInsensitive))
- return new QAndroidPlatformIntegration(paramList);
- return 0;
-}
-
-QT_END_NAMESPACE
-#include "androidplatformplugin.moc"
-
diff --git a/src/plugins/platforms/android/main.cpp b/src/plugins/platforms/android/main.cpp
index c304fc8d69..4841d0425c 100644
--- a/src/plugins/platforms/android/main.cpp
+++ b/src/plugins/platforms/android/main.cpp
@@ -61,3 +61,4 @@ QPlatformIntegration *QAndroidIntegrationPlugin::create(const QString& system, c
}
QT_END_NAMESPACE
+#include "main.moc"
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.h b/src/plugins/platforms/cocoa/qcocoaintegration.h
index 0c14e07551..30838ba254 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.h
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.h
@@ -128,6 +128,8 @@ public:
void beep() const override;
+ void closePopups(QWindow *forWindow = nullptr);
+
private Q_SLOTS:
void focusWindowChanged(QWindow *);
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.mm b/src/plugins/platforms/cocoa/qcocoaintegration.mm
index 61308d6bf9..a77b97f538 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.mm
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.mm
@@ -487,6 +487,19 @@ void QCocoaIntegration::beep() const
NSBeep();
}
+void QCocoaIntegration::closePopups(QWindow *forWindow)
+{
+ for (auto it = m_popupWindowStack.begin(); it != m_popupWindowStack.end();) {
+ auto *popup = *it;
+ if (!forWindow || popup->window()->transientParent() == forWindow) {
+ it = m_popupWindowStack.erase(it);
+ QWindowSystemInterface::handleCloseEvent<QWindowSystemInterface::SynchronousDelivery>(popup->window());
+ } else {
+ ++it;
+ }
+ }
+}
+
void QCocoaIntegration::focusWindowChanged(QWindow *focusWindow)
{
// Don't revert icon just because we lost focus
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.h b/src/plugins/platforms/cocoa/qcocoawindow.h
index fef72bc496..1e46cd2dde 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.h
+++ b/src/plugins/platforms/cocoa/qcocoawindow.h
@@ -151,6 +151,7 @@ public:
Q_NOTIFICATION_HANDLER(NSWindowDidEndLiveResizeNotification) void windowDidEndLiveResize();
Q_NOTIFICATION_HANDLER(NSWindowDidBecomeKeyNotification) void windowDidBecomeKey();
Q_NOTIFICATION_HANDLER(NSWindowDidResignKeyNotification) void windowDidResignKey();
+ Q_NOTIFICATION_HANDLER(NSWindowWillMiniaturizeNotification) void windowWillMiniaturize();
Q_NOTIFICATION_HANDLER(NSWindowDidMiniaturizeNotification) void windowDidMiniaturize();
Q_NOTIFICATION_HANDLER(NSWindowDidDeminiaturizeNotification) void windowDidDeminiaturize();
Q_NOTIFICATION_HANDLER(NSWindowWillEnterFullScreenNotification) void windowWillEnterFullScreen();
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.mm b/src/plugins/platforms/cocoa/qcocoawindow.mm
index 69d192b4f5..ad232d6d80 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.mm
+++ b/src/plugins/platforms/cocoa/qcocoawindow.mm
@@ -71,14 +71,6 @@ enum {
defaultWindowHeight = 160
};
-static void qt_closePopups()
-{
- while (QCocoaWindow *popup = QCocoaIntegration::instance()->popPopupWindow()) {
- QWindowSystemInterface::handleCloseEvent(popup->window());
- QWindowSystemInterface::flushWindowSystemEvents();
- }
-}
-
Q_LOGGING_CATEGORY(lcCocoaNotifications, "qt.qpa.cocoa.notifications");
static void qRegisterNotificationCallbacks()
@@ -803,6 +795,11 @@ void QCocoaWindow::windowDidExitFullScreen()
}
}
+void QCocoaWindow::windowWillMiniaturize()
+{
+ QCocoaIntegration::instance()->closePopups(window());
+}
+
void QCocoaWindow::windowDidMiniaturize()
{
if (!isContentView())
@@ -1141,7 +1138,7 @@ void QCocoaWindow::viewDidChangeGlobalFrame()
void QCocoaWindow::windowWillMove()
{
// Close any open popups on window move
- qt_closePopups();
+ QCocoaIntegration::instance()->closePopups();
}
void QCocoaWindow::windowDidMove()
@@ -1270,7 +1267,7 @@ void QCocoaWindow::windowWillClose()
{
// Close any open popups on window closing.
if (window() && !windowIsPopupType(window()->type()))
- qt_closePopups();
+ QCocoaIntegration::instance()->closePopups();
}
// ----------------------- NSWindowDelegate callbacks -----------------------
diff --git a/src/plugins/platforms/windows/qwindowsglcontext.cpp b/src/plugins/platforms/windows/qwindowsglcontext.cpp
index f2d31d5783..d9521e7e08 100644
--- a/src/plugins/platforms/windows/qwindowsglcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowsglcontext.cpp
@@ -329,7 +329,7 @@ static inline bool
static void describeFormats(HDC hdc)
{
const int pfiMax = QOpenGLStaticContext::opengl32.describePixelFormat(hdc, 0, 0, nullptr);
- for (int i = 0; i < pfiMax; i++) {
+ for (int i = 1; i <= pfiMax; i++) {
PIXELFORMATDESCRIPTOR pfd;
initPixelFormatDescriptor(&pfd);
QOpenGLStaticContext::opengl32.describePixelFormat(hdc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
diff --git a/src/plugins/platforms/windows/qwindowswindow.cpp b/src/plugins/platforms/windows/qwindowswindow.cpp
index a7aad15749..04596b2d4d 100644
--- a/src/plugins/platforms/windows/qwindowswindow.cpp
+++ b/src/plugins/platforms/windows/qwindowswindow.cpp
@@ -269,7 +269,7 @@ QDebug operator<<(QDebug d, const GUID &guid)
static void formatBriefRectangle(QDebug &d, const QRect &r)
{
- d << r.width() << 'x' << r.height() << forcesign << r.x() << r.y() << noforcesign;
+ d << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
}
static void formatBriefMargins(QDebug &d, const QMargins &m)
@@ -918,7 +918,7 @@ QMargins QWindowsGeometryHint::frameOnPrimaryScreen(DWORD style, DWORD exStyle)
const QMargins result(qAbs(rect.left), qAbs(rect.top),
qAbs(rect.right), qAbs(rect.bottom));
qCDebug(lcQpaWindows).nospace() << __FUNCTION__ << " style="
- << showbase << hex << style << " exStyle=" << exStyle << dec << noshowbase
+ << Qt::showbase << Qt::hex << style << " exStyle=" << exStyle << Qt::dec << Qt::noshowbase
<< ' ' << rect << ' ' << result;
return result;
}
diff --git a/src/plugins/platforms/xcb/qxcbeventqueue.h b/src/plugins/platforms/xcb/qxcbeventqueue.h
index 11d0b8e963..e7327b3fd6 100644
--- a/src/plugins/platforms/xcb/qxcbeventqueue.h
+++ b/src/plugins/platforms/xcb/qxcbeventqueue.h
@@ -49,6 +49,7 @@
#include <xcb/xcb.h>
#include <atomic>
+#include <limits>
QT_BEGIN_NAMESPACE
@@ -106,7 +107,7 @@ public:
bool peekEventQueue(PeekerCallback peeker, void *peekerData = nullptr,
PeekOptions option = PeekDefault, qint32 peekerId = -1);
- void waitForNewEvents(unsigned long time = ULONG_MAX);
+ void waitForNewEvents(unsigned long time = std::numeric_limits<unsigned long>::max());
private:
QXcbEventNode *qXcbEventNodeFactory(xcb_generic_event_t *event);
diff --git a/src/plugins/sqldrivers/psql/qsql_psql.cpp b/src/plugins/sqldrivers/psql/qsql_psql.cpp
index d735d29fc7..27841d9494 100644
--- a/src/plugins/sqldrivers/psql/qsql_psql.cpp
+++ b/src/plugins/sqldrivers/psql/qsql_psql.cpp
@@ -1684,12 +1684,6 @@ void QPSQLDriver::_q_handleNotification(int)
if (notify->extra)
payload = d->isUtf8 ? QString::fromUtf8(notify->extra) : QString::fromLatin1(notify->extra);
#endif
-#if QT_DEPRECATED_SINCE(5, 15)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit notification(name);
-QT_WARNING_POP
-#endif
QSqlDriver::NotificationSource source = (notify->be_pid == PQbackendPID(d->connection)) ? QSqlDriver::SelfSource : QSqlDriver::OtherSource;
emit notification(name, source, payload);
}
diff --git a/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp b/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp
index 65d3f0a580..5ef76eec21 100644
--- a/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp
+++ b/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp
@@ -1043,15 +1043,8 @@ QStringList QSQLiteDriver::subscribedToNotifications() const
void QSQLiteDriver::handleNotification(const QString &tableName, qint64 rowid)
{
Q_D(const QSQLiteDriver);
- if (d->notificationid.contains(tableName)) {
-#if QT_DEPRECATED_SINCE(5, 15)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit notification(tableName);
-QT_WARNING_POP
-#endif
+ if (d->notificationid.contains(tableName))
emit notification(tableName, QSqlDriver::UnknownSource, QVariant(rowid));
- }
}
QT_END_NAMESPACE
diff --git a/src/plugins/styles/android/qandroidstyle.cpp b/src/plugins/styles/android/qandroidstyle.cpp
index 086df92322..1d0838daec 100644
--- a/src/plugins/styles/android/qandroidstyle.cpp
+++ b/src/plugins/styles/android/qandroidstyle.cpp
@@ -248,7 +248,7 @@ QAndroidStyle::ItemType QAndroidStyle::qtControl(QStyle::PrimitiveElement primit
case QStyle::PE_FrameLineEdit:
return QC_EditText;
- case QStyle::PE_IndicatorViewItemCheck:
+ case QStyle::PE_IndicatorItemViewItemCheck:
case QStyle::PE_IndicatorCheckBox:
return QC_Checkbox;
diff --git a/src/plugins/styles/mac/qmacstyle_mac.mm b/src/plugins/styles/mac/qmacstyle_mac.mm
index 5aa7befb84..f0bc51b796 100644
--- a/src/plugins/styles/mac/qmacstyle_mac.mm
+++ b/src/plugins/styles/mac/qmacstyle_mac.mm
@@ -3257,7 +3257,7 @@ void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPai
CGContextRestoreGState(cg);
break; }
- case PE_IndicatorViewItemCheck:
+ case PE_IndicatorItemViewItemCheck:
case PE_IndicatorRadioButton:
case PE_IndicatorCheckBox: {
const bool isEnabled = opt->state & State_Enabled;
diff --git a/src/sql/kernel/qsqlcachedresult.cpp b/src/sql/kernel/qsqlcachedresult.cpp
index c335d7d8fe..1e76154f82 100644
--- a/src/sql/kernel/qsqlcachedresult.cpp
+++ b/src/sql/kernel/qsqlcachedresult.cpp
@@ -60,14 +60,6 @@ QT_BEGIN_NAMESPACE
static const uint initial_cache_size = 128;
-QSqlCachedResultPrivate::QSqlCachedResultPrivate(QSqlCachedResult *q, const QSqlDriver *drv)
- : QSqlResultPrivate(q, drv),
- rowCacheEnd(0),
- colCount(0),
- atEnd(false)
-{
-}
-
void QSqlCachedResultPrivate::cleanup()
{
cache.clear();
diff --git a/src/sql/kernel/qsqlcachedresult_p.h b/src/sql/kernel/qsqlcachedresult_p.h
index 543a902554..1bca1fd090 100644
--- a/src/sql/kernel/qsqlcachedresult_p.h
+++ b/src/sql/kernel/qsqlcachedresult_p.h
@@ -101,7 +101,8 @@ class Q_SQL_EXPORT QSqlCachedResultPrivate: public QSqlResultPrivate
Q_DECLARE_PUBLIC(QSqlCachedResult)
public:
- QSqlCachedResultPrivate(QSqlCachedResult *q, const QSqlDriver *drv);
+ using QSqlResultPrivate::QSqlResultPrivate;
+
bool canSeek(int i) const;
inline int cacheCount() const;
void init(int count, bool fo);
@@ -110,9 +111,9 @@ public:
void revertLast();
QSqlCachedResult::ValueCache cache;
- int rowCacheEnd;
- int colCount;
- bool atEnd;
+ int rowCacheEnd = 0;
+ int colCount = 0;
+ bool atEnd = false;
};
QT_END_NAMESPACE
diff --git a/src/sql/kernel/qsqldriver.cpp b/src/sql/kernel/qsqldriver.cpp
index fcd3c70a04..adf4421c89 100644
--- a/src/sql/kernel/qsqldriver.cpp
+++ b/src/sql/kernel/qsqldriver.cpp
@@ -51,11 +51,10 @@ QT_BEGIN_NAMESPACE
static QString prepareIdentifier(const QString &identifier,
QSqlDriver::IdentifierType type, const QSqlDriver *driver)
{
- Q_ASSERT( driver != nullptr );
+ Q_ASSERT(driver != nullptr);
QString ret = identifier;
- if (!driver->isIdentifierEscaped(identifier, type)) {
+ if (!driver->isIdentifierEscaped(identifier, type))
ret = driver->escapeIdentifier(identifier, type);
- }
return ret;
}
diff --git a/src/sql/kernel/qsqldriver.h b/src/sql/kernel/qsqldriver.h
index ca9f7dc51e..31de63be15 100644
--- a/src/sql/kernel/qsqldriver.h
+++ b/src/sql/kernel/qsqldriver.h
@@ -100,7 +100,7 @@ public:
virtual QStringList tables(QSql::TableType tableType) const;
virtual QSqlIndex primaryIndex(const QString &tableName) const;
virtual QSqlRecord record(const QString &tableName) const;
- virtual QString formatValue(const QSqlField& field, bool trimStrings = false) const;
+ virtual QString formatValue(const QSqlField &field, bool trimStrings = false) const;
virtual QString escapeIdentifier(const QString &identifier, IdentifierType type) const;
virtual QString sqlStatement(StatementType type, const QString &tableName,
@@ -113,12 +113,12 @@ public:
virtual void close() = 0;
virtual QSqlResult *createResult() const = 0;
- virtual bool open(const QString& db,
- const QString& user = QString(),
- const QString& password = QString(),
- const QString& host = QString(),
+ virtual bool open(const QString &db,
+ const QString &user = QString(),
+ const QString &password = QString(),
+ const QString &host = QString(),
int port = -1,
- const QString& connOpts = QString()) = 0;
+ const QString &connOpts = QString()) = 0;
virtual bool subscribeToNotification(const QString &name);
virtual bool unsubscribeFromNotification(const QString &name);
virtual QStringList subscribedToNotifications() const;
@@ -135,10 +135,6 @@ public Q_SLOTS:
virtual bool cancelQuery();
Q_SIGNALS:
-#if QT_DEPRECATED_SINCE(5, 15)
- QT_DEPRECATED_X("Use the 3-args version of notification() instead.")
- void notification(const QString &name);
-#endif
void notification(const QString &name, QSqlDriver::NotificationSource source, const QVariant &payload);
protected:
diff --git a/src/sql/kernel/qsqldriver_p.h b/src/sql/kernel/qsqldriver_p.h
index c8ec961124..614fbf69a1 100644
--- a/src/sql/kernel/qsqldriver_p.h
+++ b/src/sql/kernel/qsqldriver_p.h
@@ -63,19 +63,16 @@ class QSqlDriverPrivate : public QObjectPrivate
Q_DECLARE_PUBLIC(QSqlDriver)
public:
- QSqlDriverPrivate()
- : QObjectPrivate(),
- isOpen(false),
- isOpenError(false),
- precisionPolicy(QSql::LowPrecisionDouble),
- dbmsType(QSqlDriver::UnknownDbms)
- { }
+ QSqlDriverPrivate(QSqlDriver::DbmsType dbmstype = QSqlDriver::UnknownDbms)
+ : QObjectPrivate()
+ , dbmsType(dbmstype)
+ {}
- uint isOpen;
- uint isOpenError;
QSqlError error;
- QSql::NumericalPrecisionPolicy precisionPolicy;
+ QSql::NumericalPrecisionPolicy precisionPolicy = QSql::LowPrecisionDouble;
QSqlDriver::DbmsType dbmsType;
+ bool isOpen = false;
+ bool isOpenError = false;
};
QT_END_NAMESPACE
diff --git a/src/sql/kernel/qsqlindex.cpp b/src/sql/kernel/qsqlindex.cpp
index 60b0ef6965..5781f24b5c 100644
--- a/src/sql/kernel/qsqlindex.cpp
+++ b/src/sql/kernel/qsqlindex.cpp
@@ -44,9 +44,6 @@
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/qsqlquery.cpp b/src/sql/kernel/qsqlquery.cpp
index 34a3ba3755..ce6c997919 100644
--- a/src/sql/kernel/qsqlquery.cpp
+++ b/src/sql/kernel/qsqlquery.cpp
@@ -261,7 +261,7 @@ QSqlQuery::QSqlQuery(const QSqlQuery& other)
/*!
\internal
*/
-static void qInit(QSqlQuery *q, const QString& query, QSqlDatabase db)
+static void qInit(QSqlQuery *q, const QString& query, const QSqlDatabase &db)
{
QSqlDatabase database = db;
if (!database.isValid())
@@ -281,7 +281,7 @@ static void qInit(QSqlQuery *q, const QString& query, QSqlDatabase db)
\sa QSqlDatabase
*/
-QSqlQuery::QSqlQuery(const QString& query, QSqlDatabase db)
+QSqlQuery::QSqlQuery(const QString& query, const QSqlDatabase &db)
{
d = QSqlQueryPrivate::shared_null();
qInit(this, query, db);
@@ -294,7 +294,7 @@ QSqlQuery::QSqlQuery(const QString& query, QSqlDatabase db)
\sa QSqlDatabase
*/
-QSqlQuery::QSqlQuery(QSqlDatabase db)
+QSqlQuery::QSqlQuery(const QSqlDatabase &db)
{
d = QSqlQueryPrivate::shared_null();
qInit(this, QString(), db);
diff --git a/src/sql/kernel/qsqlquery.h b/src/sql/kernel/qsqlquery.h
index cbbc25c4ec..3be04c492c 100644
--- a/src/sql/kernel/qsqlquery.h
+++ b/src/sql/kernel/qsqlquery.h
@@ -59,8 +59,8 @@ class Q_SQL_EXPORT QSqlQuery
{
public:
explicit QSqlQuery(QSqlResult *r);
- explicit QSqlQuery(const QString& query = QString(), QSqlDatabase db = QSqlDatabase());
- explicit QSqlQuery(QSqlDatabase db);
+ explicit QSqlQuery(const QString& query = QString(), const QSqlDatabase &db = QSqlDatabase());
+ explicit QSqlQuery(const QSqlDatabase &db);
QSqlQuery(const QSqlQuery& other);
QSqlQuery& operator=(const QSqlQuery& other);
~QSqlQuery();
diff --git a/src/sql/kernel/qsqlresult_p.h b/src/sql/kernel/qsqlresult_p.h
index f0816a7fb5..3b9697046d 100644
--- a/src/sql/kernel/qsqlresult_p.h
+++ b/src/sql/kernel/qsqlresult_p.h
@@ -79,16 +79,9 @@ class Q_SQL_EXPORT QSqlResultPrivate
public:
QSqlResultPrivate(QSqlResult *q, const QSqlDriver *drv)
: q_ptr(q),
- sqldriver(const_cast<QSqlDriver*>(drv)),
- idx(QSql::BeforeFirstRow),
- active(false),
- isSel(false),
- forwardOnly(false),
- precisionPolicy(QSql::LowPrecisionDouble),
- bindCount(0),
- binds(QSqlResult::PositionalBinding)
+ sqldriver(const_cast<QSqlDriver *>(drv))
{ }
- virtual ~QSqlResultPrivate() { }
+ virtual ~QSqlResultPrivate() = default;
void clearValues()
{
@@ -111,7 +104,7 @@ public:
void clear()
{
clearValues();
- clearIndex();;
+ clearIndex();
}
virtual QString fieldSerial(int) const;
@@ -119,27 +112,27 @@ public:
QString namedToPositionalBinding(const QString &query);
QString holderAt(int index) const;
- QSqlResult *q_ptr;
+ QSqlResult *q_ptr = nullptr;
QPointer<QSqlDriver> sqldriver;
- int idx;
QString sql;
- bool active;
- bool isSel;
QSqlError error;
- bool forwardOnly;
- QSql::NumericalPrecisionPolicy precisionPolicy;
-
- int bindCount;
- QSqlResult::BindingSyntax binds;
QString executedQuery;
QHash<int, QSql::ParamType> types;
QVector<QVariant> values;
- typedef QHash<QString, QVector<int> > IndexMap;
+ using IndexMap = QHash<QString, QVector<int> >;
IndexMap indexes;
- typedef QVector<QHolder> QHolderVector;
+ using QHolderVector = QVector<QHolder>;
QHolderVector holders;
+
+ QSqlResult::BindingSyntax binds = QSqlResult::PositionalBinding;
+ QSql::NumericalPrecisionPolicy precisionPolicy = QSql::LowPrecisionDouble;
+ int idx = QSql::BeforeFirstRow;
+ int bindCount = 0;
+ bool active = false;
+ bool isSel = false;
+ bool forwardOnly = false;
};
QT_END_NAMESPACE
diff --git a/src/sql/models/qsqlrelationaltablemodel.cpp b/src/sql/models/qsqlrelationaltablemodel.cpp
index 20adec6a3b..4f5f00bf96 100644
--- a/src/sql/models/qsqlrelationaltablemodel.cpp
+++ b/src/sql/models/qsqlrelationaltablemodel.cpp
@@ -161,7 +161,7 @@ struct QRelation
class QRelatedTableModel : public QSqlTableModel
{
public:
- QRelatedTableModel(QRelation *rel, QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase());
+ QRelatedTableModel(QRelation *rel, QObject *parent = nullptr, const QSqlDatabase &db = QSqlDatabase());
bool select() override;
private:
bool firstSelect;
@@ -245,7 +245,7 @@ bool QRelation::isValid()
-QRelatedTableModel::QRelatedTableModel(QRelation *rel, QObject *parent, QSqlDatabase db) :
+QRelatedTableModel::QRelatedTableModel(QRelation *rel, QObject *parent, const QSqlDatabase &db) :
QSqlTableModel(parent, db), firstSelect(true), relation(rel)
{
}
@@ -410,7 +410,7 @@ void QSqlRelationalTableModelPrivate::clearCache()
and the database connection to \a db. If \a db is not valid, the
default database connection will be used.
*/
-QSqlRelationalTableModel::QSqlRelationalTableModel(QObject *parent, QSqlDatabase db)
+QSqlRelationalTableModel::QSqlRelationalTableModel(QObject *parent, const QSqlDatabase &db)
: QSqlTableModel(*new QSqlRelationalTableModelPrivate, parent, db)
{
}
diff --git a/src/sql/models/qsqlrelationaltablemodel.h b/src/sql/models/qsqlrelationaltablemodel.h
index 1929bd320a..2ebadaabd1 100644
--- a/src/sql/models/qsqlrelationaltablemodel.h
+++ b/src/sql/models/qsqlrelationaltablemodel.h
@@ -91,7 +91,7 @@ public:
};
explicit QSqlRelationalTableModel(QObject *parent = nullptr,
- QSqlDatabase db = QSqlDatabase());
+ const QSqlDatabase &db = QSqlDatabase());
virtual ~QSqlRelationalTableModel();
QVariant data(const QModelIndex &item, int role = Qt::DisplayRole) const override;
diff --git a/src/sql/models/qsqltablemodel.cpp b/src/sql/models/qsqltablemodel.cpp
index 4b29492134..4d20915c09 100644
--- a/src/sql/models/qsqltablemodel.cpp
+++ b/src/sql/models/qsqltablemodel.cpp
@@ -291,7 +291,7 @@ bool QSqlTableModelPrivate::exec(const QString &stmt, bool prepStatement,
The default edit strategy is \l OnRowChange.
*/
-QSqlTableModel::QSqlTableModel(QObject *parent, QSqlDatabase db)
+QSqlTableModel::QSqlTableModel(QObject *parent, const QSqlDatabase &db)
: QSqlQueryModel(*new QSqlTableModelPrivate, parent)
{
Q_D(QSqlTableModel);
@@ -300,7 +300,7 @@ QSqlTableModel::QSqlTableModel(QObject *parent, QSqlDatabase db)
/*! \internal
*/
-QSqlTableModel::QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent, QSqlDatabase db)
+QSqlTableModel::QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent, const QSqlDatabase &db)
: QSqlQueryModel(dd, parent)
{
Q_D(QSqlTableModel);
diff --git a/src/sql/models/qsqltablemodel.h b/src/sql/models/qsqltablemodel.h
index eba27e60ec..1ac8bd9b04 100644
--- a/src/sql/models/qsqltablemodel.h
+++ b/src/sql/models/qsqltablemodel.h
@@ -62,7 +62,7 @@ class Q_SQL_EXPORT QSqlTableModel: public QSqlQueryModel
public:
enum EditStrategy {OnFieldChange, OnRowChange, OnManualSubmit};
- explicit QSqlTableModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase());
+ explicit QSqlTableModel(QObject *parent = nullptr, const QSqlDatabase &db = QSqlDatabase());
virtual ~QSqlTableModel();
virtual void setTable(const QString &tableName);
@@ -127,7 +127,7 @@ Q_SIGNALS:
void beforeDelete(int row);
protected:
- QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase());
+ QSqlTableModel(QSqlTableModelPrivate &dd, QObject *parent = nullptr, const QSqlDatabase &db = QSqlDatabase());
virtual bool updateRowInTable(int row, const QSqlRecord &values);
virtual bool insertRowIntoTable(const QSqlRecord &values);
diff --git a/src/testlib/qtestblacklist.cpp b/src/testlib/qtestblacklist.cpp
index 9b7c2495d4..91258e9ec4 100644
--- a/src/testlib/qtestblacklist.cpp
+++ b/src/testlib/qtestblacklist.cpp
@@ -190,10 +190,20 @@ static QSet<QByteArray> activeConditions()
if (!distributionName.isEmpty()) {
if (result.find(distributionName) == result.end())
result.insert(distributionName);
+ // backwards compatibility with Qt 5
+ if (distributionName == "macos") {
+ if (result.find(distributionName) == result.end())
+ result.insert("osx");
+ }
if (!distributionRelease.isEmpty()) {
QByteArray versioned = distributionName + "-" + distributionRelease;
if (result.find(versioned) == result.end())
result.insert(versioned);
+ if (distributionName == "macos") {
+ QByteArray versioned = "osx-" + distributionRelease;
+ if (result.find(versioned) == result.end())
+ result.insert(versioned);
+ }
}
}
diff --git a/src/testlib/qtestkeyboard.h b/src/testlib/qtestkeyboard.h
index e8a7e0d5f5..1882c858c1 100644
--- a/src/testlib/qtestkeyboard.h
+++ b/src/testlib/qtestkeyboard.h
@@ -54,7 +54,9 @@
#include <QtGui/qguiapplication.h>
#include <QtGui/qwindow.h>
#include <QtGui/qevent.h>
-#include <QtGui/qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/qkeysequence.h>
+#endif
#ifdef QT_WIDGETS_LIB
#include <QtWidgets/qwidget.h>
diff --git a/src/tools/androiddeployqt/main.cpp b/src/tools/androiddeployqt/main.cpp
index d993518665..9912539a84 100644
--- a/src/tools/androiddeployqt/main.cpp
+++ b/src/tools/androiddeployqt/main.cpp
@@ -128,6 +128,7 @@ struct Options
, jarSigner(false)
, installApk(false)
, uninstallApk(false)
+ , qmlImportScannerBinaryPath()
{}
enum DeploymentMechanism
@@ -231,6 +232,9 @@ struct Options
QStringList initClasses;
QStringList permissions;
QStringList features;
+
+ // Override qml import scanner path
+ QString qmlImportScannerBinaryPath;
};
static const QHash<QByteArray, QByteArray> elfArchitecures = {
@@ -523,6 +527,8 @@ Options parseOptions()
options.jarSigner = true;
} else if (argument.compare(QLatin1String("--aux-mode"), Qt::CaseInsensitive) == 0) {
options.auxMode = true;
+ } else if (argument.compare(QLatin1String("--qml-importscanner-binary"), Qt::CaseInsensitive) == 0) {
+ options.qmlImportScannerBinaryPath = arguments.at(++i).trimmed();
}
}
@@ -606,6 +612,10 @@ void printHelp()
" dependencies into the build directory and update the XML templates.\n"
" The project will not be built or installed.\n"
" --apk <path/where/to/copy/the/apk>: Path where to copy the built apk.\n"
+ " --qml-importscanner-binary <path/to/qmlimportscanner>: Override the\n"
+ " default qmlimportscanner binary path. By default the\n"
+ " qmlimportscanner binary is located using the Qt directory\n"
+ " specified in the input file.\n"
" --help: Displays this information.\n\n",
qPrintable(QCoreApplication::arguments().at(0))
);
@@ -927,6 +937,12 @@ bool readInputFile(Options *options)
}
{
+ const QJsonValue qmlImportScannerBinaryPath = jsonObject.value(QLatin1String("qml-importscanner-binary"));
+ if (!qmlImportScannerBinaryPath.isUndefined())
+ options->qmlImportScannerBinaryPath = qmlImportScannerBinaryPath.toString();
+ }
+
+ {
const QJsonValue applicationBinary = jsonObject.value(QLatin1String("application-binary"));
if (applicationBinary.isUndefined()) {
fprintf(stderr, "No application binary defined in json file.\n");
@@ -1703,10 +1719,15 @@ bool scanImports(Options *options, QSet<QString> *usedDependencies)
if (options->verbose)
fprintf(stdout, "Scanning for QML imports.\n");
- QString qmlImportScanner = options->qtInstallDirectory + QLatin1String("/bin/qmlimportscanner");
+ QString qmlImportScanner;
+ if (!options->qmlImportScannerBinaryPath.isEmpty()) {
+ qmlImportScanner = options->qmlImportScannerBinaryPath;
+ } else {
+ options->qtInstallDirectory + QLatin1String("/bin/qmlimportscanner");
#if defined(Q_OS_WIN32)
- qmlImportScanner += QLatin1String(".exe");
+ qmlImportScanner += QLatin1String(".exe");
#endif
+ }
if (!QFile::exists(qmlImportScanner)) {
fprintf(stderr, "qmlimportscanner not found: %s\n", qPrintable(qmlImportScanner));
diff --git a/src/tools/bootstrap/bootstrap.pro b/src/tools/bootstrap/bootstrap.pro
index bfd199a8ba..b68bed436e 100644
--- a/src/tools/bootstrap/bootstrap.pro
+++ b/src/tools/bootstrap/bootstrap.pro
@@ -103,7 +103,6 @@ SOURCES += \
../../corelib/tools/qcommandlineoption.cpp \
../../corelib/tools/qcryptographichash.cpp \
../../corelib/tools/qhash.cpp \
- ../../corelib/tools/qlist.cpp \
../../corelib/tools/qmap.cpp \
../../corelib/tools/qringbuffer.cpp \
../../corelib/tools/qpoint.cpp \
diff --git a/src/tools/moc/collectjson.cpp b/src/tools/moc/collectjson.cpp
index 4029bca5e9..fe499151cb 100644
--- a/src/tools/moc/collectjson.cpp
+++ b/src/tools/moc/collectjson.cpp
@@ -83,7 +83,9 @@ int collectJson(const QStringList &jsonFiles, const QString &outputFile)
}
}
- for (const QString &jsonFile: jsonFiles) {
+ QStringList jsonFilesSorted = jsonFiles;
+ jsonFilesSorted.sort();
+ for (const QString &jsonFile : qAsConst(jsonFilesSorted)) {
QFile f(jsonFile);
if (!f.open(QIODevice::ReadOnly)) {
fprintf(stderr, "Error opening %s for reading\n", qPrintable(jsonFile));
diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp
index 034e846918..43bbe5ad02 100644
--- a/src/tools/moc/generator.cpp
+++ b/src/tools/moc/generator.cpp
@@ -194,7 +194,6 @@ static bool qualifiedNameEquals(const QByteArray &qualifiedName, const QByteArra
void Generator::generateCode()
{
- bool isQt = (cdef->classname == "Qt");
bool isQObject = (cdef->classname == "QObject");
bool isConstructible = !cdef->constructorList.isEmpty();
@@ -237,7 +236,7 @@ void Generator::generateCode()
//
const int constCharArraySizeLimit = 65535;
fprintf(out, "struct qt_meta_stringdata_%s_t {\n", qualifiedClassNameIdentifier.constData());
- fprintf(out, " QByteArrayData data[%d];\n", strings.size());
+ fprintf(out, " const uint offsetsAndSize[%d];\n", strings.size()*2);
{
int stringDataLength = 0;
int stringDataCounter = 0;
@@ -260,11 +259,8 @@ void Generator::generateCode()
// stringdata.stringdata member, and 2) the stringdata.data index of the
// QByteArrayData being defined. This calculation relies on the
// QByteArrayData::data() implementation returning simply "this + offset".
- fprintf(out, "#define QT_MOC_LITERAL(idx, ofs, len) \\\n"
- " Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\\n"
- " qptrdiff(offsetof(qt_meta_stringdata_%s_t, stringdata0) + ofs \\\n"
- " - idx * sizeof(QByteArrayData)) \\\n"
- " )\n",
+ fprintf(out, "#define QT_MOC_LITERAL(ofs, len) \\\n"
+ " uint(offsetof(qt_meta_stringdata_%s_t, stringdata0) + ofs), len \n",
qualifiedClassNameIdentifier.constData());
fprintf(out, "static const qt_meta_stringdata_%s_t qt_meta_stringdata_%s = {\n",
@@ -274,7 +270,7 @@ void Generator::generateCode()
int idx = 0;
for (int i = 0; i < strings.size(); ++i) {
const QByteArray &str = strings.at(i);
- fprintf(out, "QT_MOC_LITERAL(%d, %d, %d)", i, idx, str.length());
+ fprintf(out, "QT_MOC_LITERAL(%d, %d)", idx, str.length());
if (i != strings.size() - 1)
fputc(',', out);
const QByteArray comment = str.length() > 32 ? str.left(29) + "..." : str;
@@ -452,7 +448,7 @@ void Generator::generateCode()
//
// Generate internal qt_static_metacall() function
//
- const bool hasStaticMetaCall = !isQt &&
+ const bool hasStaticMetaCall =
(cdef->hasQObject || !cdef->methodList.isEmpty()
|| !cdef->propertyList.isEmpty() || !cdef->constructorList.isEmpty());
if (hasStaticMetaCall)
@@ -534,10 +530,7 @@ void Generator::generateCode()
//
// Finally create and initialize the static meta object
//
- if (isQt)
- fprintf(out, "QT_INIT_METAOBJECT const QMetaObject QObject::staticQtMetaObject = { {\n");
- else
- fprintf(out, "QT_INIT_METAOBJECT const QMetaObject %s::staticMetaObject = { {\n", cdef->qualified.constData());
+ fprintf(out, "QT_INIT_METAOBJECT const QMetaObject %s::staticMetaObject = { {\n", cdef->qualified.constData());
if (isQObject)
fprintf(out, " nullptr,\n");
@@ -547,7 +540,7 @@ void Generator::generateCode()
fprintf(out, " QtPrivate::MetaObjectForType<%s>::value(),\n", purestSuperClass.constData());
else
fprintf(out, " nullptr,\n");
- fprintf(out, " qt_meta_stringdata_%s.data,\n"
+ fprintf(out, " qt_meta_stringdata_%s.offsetsAndSize,\n"
" qt_meta_data_%s,\n", qualifiedClassNameIdentifier.constData(),
qualifiedClassNameIdentifier.constData());
if (hasStaticMetaCall)
@@ -561,9 +554,6 @@ void Generator::generateCode()
fprintf(out, " qt_meta_extradata_%s,\n", qualifiedClassNameIdentifier.constData());
fprintf(out, " nullptr\n} };\n\n");
- if(isQt)
- return;
-
if (!cdef->hasQObject)
return;
@@ -1219,18 +1209,22 @@ void Generator::generateStaticMetacall()
fprintf(out, "%s(", f.name.constData());
int offset = 1;
- int argsCount = f.arguments.count();
- for (int j = 0; j < argsCount; ++j) {
- const ArgumentDef &a = f.arguments.at(j);
- if (j)
- fprintf(out, ",");
- fprintf(out, "(*reinterpret_cast< %s>(_a[%d]))",a.typeNameForCast.constData(), offset++);
- isUsed_a = true;
- }
- if (f.isPrivateSignal) {
- if (argsCount > 0)
- fprintf(out, ", ");
- fprintf(out, "%s", "QPrivateSignal()");
+ if (f.isRawSlot) {
+ fprintf(out, "QMethodRawArguments{ _a }");
+ } else {
+ int argsCount = f.arguments.count();
+ for (int j = 0; j < argsCount; ++j) {
+ const ArgumentDef &a = f.arguments.at(j);
+ if (j)
+ fprintf(out, ",");
+ fprintf(out, "(*reinterpret_cast< %s>(_a[%d]))",a.typeNameForCast.constData(), offset++);
+ isUsed_a = true;
+ }
+ if (f.isPrivateSignal) {
+ if (argsCount > 0)
+ fprintf(out, ", ");
+ fprintf(out, "%s", "QPrivateSignal()");
+ }
}
fprintf(out, ");");
if (f.normalizedType != "void") {
diff --git a/src/tools/moc/moc.cpp b/src/tools/moc/moc.cpp
index d7a1af0a18..7b132493f8 100644
--- a/src/tools/moc/moc.cpp
+++ b/src/tools/moc/moc.cpp
@@ -328,6 +328,11 @@ void Moc::parseFunctionArguments(FunctionDef *def)
def->arguments.removeLast();
def->isPrivateSignal = true;
}
+ if (def->arguments.size() == 1
+ && def->arguments.constLast().normalizedType == "QMethodRawArguments") {
+ def->arguments.removeLast();
+ def->isRawSlot = true;
+ }
}
bool Moc::testFunctionAttribute(FunctionDef *def)
diff --git a/src/tools/moc/moc.h b/src/tools/moc/moc.h
index 5d1ae0ad6d..1d70fa154b 100644
--- a/src/tools/moc/moc.h
+++ b/src/tools/moc/moc.h
@@ -115,6 +115,7 @@ struct FunctionDef
bool isConstructor = false;
bool isDestructor = false;
bool isAbstract = false;
+ bool isRawSlot = false;
QJsonObject toJson() const;
static void accessToJson(QJsonObject *obj, Access acs);
diff --git a/src/tools/qdbusxml2cpp/qdbusxml2cpp.cpp b/src/tools/qdbusxml2cpp/qdbusxml2cpp.cpp
index 9cf753a3f1..69d46632d2 100644
--- a/src/tools/qdbusxml2cpp/qdbusxml2cpp.cpp
+++ b/src/tools/qdbusxml2cpp/qdbusxml2cpp.cpp
@@ -72,9 +72,8 @@ static const char includeList[] =
static const char forwardDeclarations[] =
"QT_BEGIN_NAMESPACE\n"
+ "#include <QtCore/qcontainerfwd.h>\n"
"class QByteArray;\n"
- "template<class T> class QList;\n"
- "template<class Key, class Value> class QMap;\n"
"class QString;\n"
"class QStringList;\n"
"class QVariant;\n"
diff --git a/src/tools/uic/cpp/cppwriteinitialization.h b/src/tools/uic/cpp/cppwriteinitialization.h
index ab996a2800..0a6ddbb3c8 100644
--- a/src/tools/uic/cpp/cppwriteinitialization.h
+++ b/src/tools/uic/cpp/cppwriteinitialization.h
@@ -85,7 +85,7 @@ namespace CPP {
struct WriteInitialization : public TreeWalker
{
- using DomPropertyList = QList<DomProperty*>;
+ using DomPropertyList = QVector<DomProperty*>;
using DomPropertyMap = QHash<QString, DomProperty*>;
WriteInitialization(Uic *uic);
diff --git a/src/tools/uic/main.cpp b/src/tools/uic/main.cpp
index d6c63de869..6f342fb398 100644
--- a/src/tools/uic/main.cpp
+++ b/src/tools/uic/main.cpp
@@ -80,10 +80,6 @@ int runUic(int argc, char *argv[])
noImplicitIncludesOption.setDescription(QStringLiteral("Disable generation of #include-directives."));
parser.addOption(noImplicitIncludesOption);
- QCommandLineOption noStringLiteralOption(QStringList() << QStringLiteral("s") << QStringLiteral("no-stringliteral"));
- noStringLiteralOption.setDescription(QStringLiteral("Deprecated. The use of this option won't take any effect."));
- parser.addOption(noStringLiteralOption);
-
QCommandLineOption postfixOption(QStringLiteral("postfix"));
postfixOption.setDescription(QStringLiteral("Postfix to add to all generated classnames."));
postfixOption.setValueName(QStringLiteral("postfix"));
@@ -134,9 +130,6 @@ int runUic(int argc, char *argv[])
}
language::setLanguage(language);
- if (parser.isSet(noStringLiteralOption))
- fprintf(stderr, "The -s, --no-stringliteral option is deprecated and it won't take any effect.\n");
-
QString inputFile;
if (!parser.positionalArguments().isEmpty())
inputFile = parser.positionalArguments().at(0);
diff --git a/src/tools/uic/qclass_lib_map.h b/src/tools/uic/qclass_lib_map.h
index 8cebe65a00..841144133f 100644
--- a/src/tools/uic/qclass_lib_map.h
+++ b/src/tools/uic/qclass_lib_map.h
@@ -635,7 +635,6 @@ QT_CLASS_LIB(QIconEngineFactoryInterface, QtGui, qiconengineplugin.h)
QT_CLASS_LIB(QIconEnginePlugin, QtGui, qiconengineplugin.h)
QT_CLASS_LIB(QIconEngineFactoryInterfaceV2, QtGui, qiconengineplugin.h)
QT_CLASS_LIB(QIconEnginePluginV2, QtGui, qiconengineplugin.h)
-QT_CLASS_LIB(QImageTextKeyLang, QtGui, qimage.h)
QT_CLASS_LIB(QImage, QtGui, qimage.h)
QT_CLASS_LIB(QImageIOHandler, QtGui, qimageiohandler.h)
QT_CLASS_LIB(QImageIOHandlerFactoryInterface, QtGui, qimageiohandler.h)
@@ -644,9 +643,6 @@ QT_CLASS_LIB(QImageReader, QtGui, qimagereader.h)
QT_CLASS_LIB(QImageWriter, QtGui, qimagewriter.h)
QT_CLASS_LIB(QMovie, QtGui, qmovie.h)
QT_CLASS_LIB(QPicture, QtGui, qpicture.h)
-QT_CLASS_LIB(QPictureIO, QtGui, qpicture.h)
-QT_CLASS_LIB(QPictureFormatInterface, QtGui, qpictureformatplugin.h)
-QT_CLASS_LIB(QPictureFormatPlugin, QtGui, qpictureformatplugin.h)
QT_CLASS_LIB(QPixmap, QtGui, qpixmap.h)
QT_CLASS_LIB(QPixmapCache, QtGui, qpixmapcache.h)
QT_CLASS_LIB(QAbstractItemDelegate, QtWidgets, qabstractitemdelegate.h)
diff --git a/src/tools/uic/ui4.cpp b/src/tools/uic/ui4.cpp
index f52a8bd7d4..ed00e2c3fd 100644
--- a/src/tools/uic/ui4.cpp
+++ b/src/tools/uic/ui4.cpp
@@ -862,13 +862,13 @@ void DomActionGroup::setElementActionGroup(const QVector<DomActionGroup *> &a)
m_actionGroup = a;
}
-void DomActionGroup::setElementProperty(const QList<DomProperty *> &a)
+void DomActionGroup::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
}
-void DomActionGroup::setElementAttribute(const QList<DomProperty *> &a)
+void DomActionGroup::setElementAttribute(const QVector<DomProperty *> &a)
{
m_children |= Attribute;
m_attribute = a;
@@ -944,13 +944,13 @@ void DomAction::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomAction::setElementProperty(const QList<DomProperty *> &a)
+void DomAction::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
}
-void DomAction::setElementAttribute(const QList<DomProperty *> &a)
+void DomAction::setElementAttribute(const QVector<DomProperty *> &a)
{
m_children |= Attribute;
m_attribute = a;
@@ -1058,13 +1058,13 @@ void DomButtonGroup::write(QXmlStreamWriter &writer, const QString &tagName) con
writer.writeEndElement();
}
-void DomButtonGroup::setElementProperty(const QList<DomProperty *> &a)
+void DomButtonGroup::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
}
-void DomButtonGroup::setElementAttribute(const QList<DomProperty *> &a)
+void DomButtonGroup::setElementAttribute(const QVector<DomProperty *> &a)
{
m_children |= Attribute;
m_attribute = a;
@@ -1717,13 +1717,13 @@ void DomLayout::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomLayout::setElementProperty(const QList<DomProperty *> &a)
+void DomLayout::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
}
-void DomLayout::setElementAttribute(const QList<DomProperty *> &a)
+void DomLayout::setElementAttribute(const QVector<DomProperty *> &a)
{
m_children |= Attribute;
m_attribute = a;
@@ -1938,7 +1938,7 @@ void DomRow::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomRow::setElementProperty(const QList<DomProperty *> &a)
+void DomRow::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
@@ -1983,7 +1983,7 @@ void DomColumn::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomColumn::setElementProperty(const QList<DomProperty *> &a)
+void DomColumn::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
@@ -2059,7 +2059,7 @@ void DomItem::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomItem::setElementProperty(const QList<DomProperty *> &a)
+void DomItem::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
@@ -2268,13 +2268,13 @@ void DomWidget::setElementClass(const QStringList &a)
m_class = a;
}
-void DomWidget::setElementProperty(const QList<DomProperty *> &a)
+void DomWidget::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
}
-void DomWidget::setElementAttribute(const QList<DomProperty *> &a)
+void DomWidget::setElementAttribute(const QVector<DomProperty *> &a)
{
m_children |= Attribute;
m_attribute = a;
@@ -2386,7 +2386,7 @@ void DomSpacer::write(QXmlStreamWriter &writer, const QString &tagName) const
writer.writeEndElement();
}
-void DomSpacer::setElementProperty(const QList<DomProperty *> &a)
+void DomSpacer::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
@@ -5984,7 +5984,7 @@ void DomDesignerData::write(QXmlStreamWriter &writer, const QString &tagName) co
writer.writeEndElement();
}
-void DomDesignerData::setElementProperty(const QList<DomProperty *> &a)
+void DomDesignerData::setElementProperty(const QVector<DomProperty *> &a)
{
m_children |= Property;
m_property = a;
diff --git a/src/tools/uic/ui4.h b/src/tools/uic/ui4.h
index 94cdb40b6f..90b17f7027 100644
--- a/src/tools/uic/ui4.h
+++ b/src/tools/uic/ui4.h
@@ -472,11 +472,11 @@ public:
inline QVector<DomActionGroup *> elementActionGroup() const { return m_actionGroup; }
void setElementActionGroup(const QVector<DomActionGroup *> &a);
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
- inline QList<DomProperty*> elementAttribute() const { return m_attribute; }
- void setElementAttribute(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementAttribute() const { return m_attribute; }
+ void setElementAttribute(const QVector<DomProperty *> &a);
private:
// attribute data
@@ -487,8 +487,8 @@ private:
uint m_children = 0;
QVector<DomAction *> m_action;
QVector<DomActionGroup *> m_actionGroup;
- QList<DomProperty*> m_property;
- QList<DomProperty*> m_attribute;
+ QVector<DomProperty *> m_property;
+ QVector<DomProperty *> m_attribute;
enum Child {
Action = 1,
@@ -519,11 +519,11 @@ public:
inline void clearAttributeMenu() { m_has_attr_menu = false; }
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
- inline QList<DomProperty*> elementAttribute() const { return m_attribute; }
- void setElementAttribute(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementAttribute() const { return m_attribute; }
+ void setElementAttribute(const QVector<DomProperty *> &a);
private:
// attribute data
@@ -535,8 +535,8 @@ private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
- QList<DomProperty*> m_attribute;
+ QVector<DomProperty *> m_property;
+ QVector<DomProperty *> m_attribute;
enum Child {
Property = 1,
@@ -581,11 +581,11 @@ public:
inline void clearAttributeName() { m_has_attr_name = false; }
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
- inline QList<DomProperty*> elementAttribute() const { return m_attribute; }
- void setElementAttribute(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementAttribute() const { return m_attribute; }
+ void setElementAttribute(const QVector<DomProperty *> &a);
private:
// attribute data
@@ -594,8 +594,8 @@ private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
- QList<DomProperty*> m_attribute;
+ QVector<DomProperty *> m_property;
+ QVector<DomProperty *> m_attribute;
enum Child {
Property = 1,
@@ -891,11 +891,11 @@ public:
inline void clearAttributeColumnMinimumWidth() { m_has_attr_columnMinimumWidth = false; }
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
- inline QList<DomProperty*> elementAttribute() const { return m_attribute; }
- void setElementAttribute(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementAttribute() const { return m_attribute; }
+ void setElementAttribute(const QVector<DomProperty *> &a);
inline QVector<DomLayoutItem *> elementItem() const { return m_item; }
void setElementItem(const QVector<DomLayoutItem *> &a);
@@ -925,8 +925,8 @@ private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
- QList<DomProperty*> m_attribute;
+ QVector<DomProperty *> m_property;
+ QVector<DomProperty *> m_attribute;
QVector<DomLayoutItem *> m_item;
enum Child {
@@ -1023,14 +1023,14 @@ public:
void write(QXmlStreamWriter &writer, const QString &tagName = QString()) const;
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
+ QVector<DomProperty *> m_property;
enum Child {
Property = 1
@@ -1047,14 +1047,14 @@ public:
void write(QXmlStreamWriter &writer, const QString &tagName = QString()) const;
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
+ QVector<DomProperty *> m_property;
enum Child {
Property = 1
@@ -1082,8 +1082,8 @@ public:
inline void clearAttributeColumn() { m_has_attr_column = false; }
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
inline QVector<DomItem *> elementItem() const { return m_item; }
void setElementItem(const QVector<DomItem *> &a);
@@ -1098,7 +1098,7 @@ private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
+ QVector<DomProperty *> m_property;
QVector<DomItem *> m_item;
enum Child {
@@ -1136,11 +1136,11 @@ public:
inline QStringList elementClass() const { return m_class; }
void setElementClass(const QStringList &a);
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
- inline QList<DomProperty*> elementAttribute() const { return m_attribute; }
- void setElementAttribute(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementAttribute() const { return m_attribute; }
+ void setElementAttribute(const QVector<DomProperty *> &a);
inline QVector<DomRow *> elementRow() const { return m_row; }
void setElementRow(const QVector<DomRow *> &a);
@@ -1183,8 +1183,8 @@ private:
// child element data
uint m_children = 0;
QStringList m_class;
- QList<DomProperty*> m_property;
- QList<DomProperty*> m_attribute;
+ QVector<DomProperty *> m_property;
+ QVector<DomProperty *> m_attribute;
QVector<DomRow *> m_row;
QVector<DomColumn *> m_column;
QVector<DomItem *> m_item;
@@ -1227,8 +1227,8 @@ public:
inline void clearAttributeName() { m_has_attr_name = false; }
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
private:
// attribute data
@@ -1237,7 +1237,7 @@ private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
+ QVector<DomProperty *> m_property;
enum Child {
Property = 1
@@ -2805,14 +2805,14 @@ public:
void write(QXmlStreamWriter &writer, const QString &tagName = QString()) const;
// child element accessors
- inline QList<DomProperty*> elementProperty() const { return m_property; }
- void setElementProperty(const QList<DomProperty *> &a);
+ inline QVector<DomProperty *> elementProperty() const { return m_property; }
+ void setElementProperty(const QVector<DomProperty *> &a);
private:
// child element data
uint m_children = 0;
- QList<DomProperty*> m_property;
+ QVector<DomProperty *> m_property;
enum Child {
Property = 1
diff --git a/src/tools/uic/utils.h b/src/tools/uic/utils.h
index 34c4ab23d4..bd543c7bb7 100644
--- a/src/tools/uic/utils.h
+++ b/src/tools/uic/utils.h
@@ -42,7 +42,7 @@ inline bool toBool(const QString &str)
inline QString toString(const DomString *str)
{ return str ? str->text() : QString(); }
-inline QHash<QString, DomProperty *> propertyMap(const QList<DomProperty *> &properties)
+inline QHash<QString, DomProperty *> propertyMap(const QVector<DomProperty *> &properties)
{
QHash<QString, DomProperty *> map;
for (DomProperty *p : properties)
diff --git a/src/widgets/accessible/qaccessiblewidget.cpp b/src/widgets/accessible/qaccessiblewidget.cpp
index 68ad855c7c..1a7372728d 100644
--- a/src/widgets/accessible/qaccessiblewidget.cpp
+++ b/src/widgets/accessible/qaccessiblewidget.cpp
@@ -41,7 +41,6 @@
#ifndef QT_NO_ACCESSIBILITY
-#include "qaction.h"
#include "qapplication.h"
#if QT_CONFIG(groupbox)
#include "qgroupbox.h"
diff --git a/src/widgets/configure.json b/src/widgets/configure.json
index 0a68f082a2..cab120098a 100644
--- a/src/widgets/configure.json
+++ b/src/widgets/configure.json
@@ -26,14 +26,6 @@
}
},
- "tests": {
- "uxtheme": {
- "label": "uxtheme.h",
- "type": "files",
- "files": [ "uxtheme.h" ]
- }
- },
-
"features": {
"gtk3": {
"label": "GTK+",
@@ -56,7 +48,7 @@
},
"style-windowsvista": {
"label": "WindowsVista",
- "condition": "features.style-windows && features.animation && config.win32 && !config.winrt && tests.uxtheme",
+ "condition": "features.style-windows && features.animation && config.win32 && !config.winrt",
"output": [ "privateFeature", "styles" ]
},
"style-android": {
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index f0bd08a778..ca2b783f55 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -49,7 +49,9 @@
#include <qfontmetrics.h>
#include <qaction.h>
#include <qheaderview.h>
-#include <qshortcut.h>
+#if QT_CONFIG(shortcut)
+# include <qshortcut.h>
+#endif
#include <qgridlayout.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
@@ -344,7 +346,9 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
QT_BEGIN_INCLUDE_NAMESPACE
#include <QMetaEnum>
-#include <qshortcut.h>
+#if QT_CONFIG(shortcut)
+# include <qshortcut.h>
+#endif
QT_END_INCLUDE_NAMESPACE
/*!
diff --git a/src/widgets/dialogs/qprogressdialog.cpp b/src/widgets/dialogs/qprogressdialog.cpp
index 40548e22a5..aaa4430c39 100644
--- a/src/widgets/dialogs/qprogressdialog.cpp
+++ b/src/widgets/dialogs/qprogressdialog.cpp
@@ -39,7 +39,9 @@
#include "qprogressdialog.h"
-#include "qshortcut.h"
+#if QT_CONFIG(shortcut)
+# include "qshortcut.h"
+#endif
#include "qpainter.h"
#include "qdrawutil.h"
#include "qlabel.h"
diff --git a/src/widgets/doc/snippets/javastyle.cpp b/src/widgets/doc/snippets/javastyle.cpp
index 3d1b1e0030..54a4ade921 100644
--- a/src/widgets/doc/snippets/javastyle.cpp
+++ b/src/widgets/doc/snippets/javastyle.cpp
@@ -2130,7 +2130,7 @@ void JavaStyle::drawPrimitive(PrimitiveElement element,
painter->restore();
break;
}
- case PE_IndicatorViewItemCheck: {
+ case PE_IndicatorItemViewItemCheck: {
break;
}
case PE_FrameWindow: {
diff --git a/src/widgets/doc/src/widgets-and-layouts/styles.qdoc b/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
index 645da5bca2..faaf4e5479 100644
--- a/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
@@ -1837,7 +1837,7 @@
item views keep the dimensions on individual sections. Also
note that the delegates may use the style to paint decorations
and frames around items. QItemDelegate, for instance, draws
- \c PE_FrameFocusRect and \c PE_IndicatorViewItemCheck.
+ \c PE_FrameFocusRect and \c PE_IndicatorItemViewItemCheck.
\image javastyle/header.png
diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp
index 6f1eb4b346..b410ba82c2 100644
--- a/src/widgets/graphicsview/qgraphicsitem.cpp
+++ b/src/widgets/graphicsview/qgraphicsitem.cpp
@@ -1580,13 +1580,8 @@ QGraphicsItem::~QGraphicsItem()
p->wasDeleted = true;
if (p->declarativeData) {
p->wasDeleted = true; // needed, so that destroying the declarative data does the right thing
- if (static_cast<QAbstractDeclarativeDataImpl*>(p->declarativeData)->ownedByQml1) {
- if (QAbstractDeclarativeData::destroyed_qml1)
- QAbstractDeclarativeData::destroyed_qml1(p->declarativeData, o);
- } else {
- if (QAbstractDeclarativeData::destroyed)
- QAbstractDeclarativeData::destroyed(p->declarativeData, o);
- }
+ if (QAbstractDeclarativeData::destroyed)
+ QAbstractDeclarativeData::destroyed(p->declarativeData, o);
p->declarativeData = nullptr;
p->wasDeleted = false;
}
diff --git a/src/widgets/graphicsview/qgraphicsscene.h b/src/widgets/graphicsview/qgraphicsscene.h
index d36a871533..e72ed99a7b 100644
--- a/src/widgets/graphicsview/qgraphicsscene.h
+++ b/src/widgets/graphicsview/qgraphicsscene.h
@@ -54,7 +54,6 @@ QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
-template<typename T> class QList;
class QFocusEvent;
class QFont;
class QFontMetrics;
diff --git a/src/widgets/graphicsview/qgraphicssceneindex_p.h b/src/widgets/graphicsview/qgraphicssceneindex_p.h
index b494c52671..e13c2a3cd3 100644
--- a/src/widgets/graphicsview/qgraphicssceneindex_p.h
+++ b/src/widgets/graphicsview/qgraphicssceneindex_p.h
@@ -67,7 +67,6 @@ QT_BEGIN_NAMESPACE
class QGraphicsSceneIndexPrivate;
class QPointF;
class QRectF;
-template<typename T> class QList;
typedef bool (*QGraphicsSceneIndexIntersector)(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
const QTransform &deviceTransform, const void *data);
diff --git a/src/widgets/graphicsview/qgraphicswidget.h b/src/widgets/graphicsview/qgraphicswidget.h
index 8223b921c9..6c5171cc02 100644
--- a/src/widgets/graphicsview/qgraphicswidget.h
+++ b/src/widgets/graphicsview/qgraphicswidget.h
@@ -42,6 +42,9 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtGui/qfont.h>
+#if QT_CONFIG(action)
+# include <QtWidgets/qaction.h>
+#endif
#include <QtWidgets/qgraphicslayoutitem.h>
#include <QtWidgets/qgraphicsitem.h>
#include <QtGui/qpalette.h>
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index c9379f9a8a..4aca923151 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -112,7 +112,7 @@ void QListModel::insert(int row, QListWidgetItem *item)
QList<QListWidgetItem*>::iterator it;
it = sortedInsertionIterator(items.begin(), items.end(),
item->view->sortOrder(), item);
- row = qMax(it - items.begin(), 0);
+ row = qMax<qsizetype>(it - items.begin(), 0);
} else {
if (row < 0)
row = 0;
@@ -398,7 +398,7 @@ void QListModel::ensureSorted(int column, Qt::SortOrder order, int start, int en
--tmpitepos;
lit = tmp.begin() + tmpitepos;
lit = sortedInsertionIterator(lit, tmp.end(), order, item);
- int newRow = qMax(lit - tmp.begin(), 0);
+ int newRow = qMax<qsizetype>(lit - tmp.begin(), 0);
lit = tmp.insert(lit, item);
if (newRow != oldRow) {
changed = true;
diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp
index ddb31523fd..4908ad6ad2 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -646,7 +646,7 @@ void QTreeModel::ensureSorted(int column, Qt::SortOrder order,
lit = lst.begin() + tmpitepos;
lit = sortedInsertionIterator(lit, lst.end(), order, item);
- int newRow = qMax(lit - lst.begin(), 0);
+ int newRow = qMax<qsizetype>(lit - lst.begin(), 0);
if ((newRow < oldRow) && !(*item < *lst.at(oldRow - 1)) && !(*lst.at(oldRow - 1) < *item ))
newRow = oldRow;
diff --git a/src/widgets/kernel/kernel.pri b/src/widgets/kernel/kernel.pri
index 693af7eb80..a960280959 100644
--- a/src/widgets/kernel/kernel.pri
+++ b/src/widgets/kernel/kernel.pri
@@ -7,9 +7,6 @@ KERNEL_P= kernel
HEADERS += \
kernel/qtwidgetsglobal.h \
kernel/qtwidgetsglobal_p.h \
- kernel/qaction.h \
- kernel/qaction_p.h \
- kernel/qactiongroup.h \
kernel/qapplication.h \
kernel/qapplication_p.h \
kernel/qwidgetrepaintmanager_p.h \
@@ -20,13 +17,10 @@ HEADERS += \
kernel/qlayout_p.h \
kernel/qlayoutengine_p.h \
kernel/qlayoutitem.h \
- kernel/qshortcut.h \
- kernel/qsizepolicy.h \
+ kernel/qsizepolicy.h \
kernel/qstackedlayout.h \
kernel/qwidget.h \
kernel/qwidget_p.h \
- kernel/qwidgetaction.h \
- kernel/qwidgetaction_p.h \
kernel/qgesture.h \
kernel/qgesture_p.h \
kernel/qstandardgestures_p.h \
@@ -38,8 +32,6 @@ HEADERS += \
kernel/qtestsupport_widgets.h
SOURCES += \
- kernel/qaction.cpp \
- kernel/qactiongroup.cpp \
kernel/qapplication.cpp \
kernel/qwidgetrepaintmanager.cpp \
kernel/qboxlayout.cpp \
@@ -47,11 +39,9 @@ SOURCES += \
kernel/qlayout.cpp \
kernel/qlayoutengine.cpp \
kernel/qlayoutitem.cpp \
- kernel/qshortcut.cpp \
kernel/qsizepolicy.cpp \
kernel/qstackedlayout.cpp \
kernel/qwidget.cpp \
- kernel/qwidgetaction.cpp \
kernel/qgesture.cpp \
kernel/qstandardgestures.cpp \
kernel/qgesturerecognizer.cpp \
@@ -67,9 +57,15 @@ macx: {
SOURCES += kernel/qmacgesturerecognizer.cpp
}
-qtConfig(opengl) {
- HEADERS += kernel/qopenglwidget.h
- SOURCES += kernel/qopenglwidget.cpp
+qtConfig(action) {
+ HEADERS += kernel/qaction.h \
+ kernel/qaction_p.h \
+ kernel/qactiongroup.h \
+ kernel/qwidgetaction.h \
+ kernel/qwidgetaction_p.h
+ SOURCES += kernel/qaction.cpp \
+ kernel/qactiongroup.cpp \
+ kernel/qwidgetaction.cpp
}
qtConfig(formlayout) {
@@ -77,6 +73,11 @@ qtConfig(formlayout) {
SOURCES += kernel/qformlayout.cpp
}
+qtConfig(shortcut) {
+ HEADERS += kernel/qshortcut.h
+ SOURCES += kernel/qshortcut.cpp
+}
+
qtConfig(tooltip) {
HEADERS += kernel/qtooltip.h
SOURCES += kernel/qtooltip.cpp
diff --git a/src/widgets/kernel/qaction.cpp b/src/widgets/kernel/qaction.cpp
index 64b0d69f6d..934fe576d1 100644
--- a/src/widgets/kernel/qaction.cpp
+++ b/src/widgets/kernel/qaction.cpp
@@ -40,52 +40,29 @@
#include "qaction.h"
#include "qactiongroup.h"
-#ifndef QT_NO_ACTION
#include "qaction_p.h"
#include "qapplication.h"
#include "qevent.h"
#include "qlist.h"
#include "qstylehints.h"
-#include <private/qshortcutmap_p.h>
+#if QT_CONFIG(shortcut)
+# include <private/qshortcutmap_p.h>
+#endif
#include <private/qguiapplication_p.h>
#if QT_CONFIG(menu)
#include <private/qmenu_p.h>
#endif
#include <private/qdebug_p.h>
-#define QAPP_CHECK(functionName) \
- if (Q_UNLIKELY(!QCoreApplication::instance())) { \
- qWarning("QAction: Initialize Q(Gui)Application before calling '" functionName "'."); \
- return; \
- }
QT_BEGIN_NAMESPACE
-/*
- internal: guesses a descriptive text from a text suited for a menu entry
- */
-static QString qt_strippedText(QString s)
-{
- s.remove(QLatin1String("..."));
- for (int i = 0; i < s.size(); ++i) {
- if (s.at(i) == QLatin1Char('&'))
- s.remove(i, 1);
- }
- return s.trimmed();
-}
-
-
-QActionPrivate::QActionPrivate() :
#if QT_CONFIG(shortcut)
- autorepeat(1),
-#endif
- enabled(1), forceDisabled(0), visible(1), forceInvisible(0), checkable(0),
- checked(0), separator(0), fontSet(false),
- iconVisibleInMenu(-1), shortcutVisibleInContextMenu(-1)
+QShortcutMap::ContextMatcher QActionPrivate::contextMatcher() const
{
+ return qWidgetShortcutContextMatcher;
}
-
-QActionPrivate::~QActionPrivate() = default;
+#endif // QT_CONFIG(shortcut)
bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
{
@@ -102,84 +79,6 @@ bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
return false;
}
-void QActionPrivate::sendDataChanged()
-{
- Q_Q(QAction);
- QActionEvent e(QEvent::ActionChanged, q);
- for (int i = 0; i < widgets.size(); ++i) {
- QWidget *w = widgets.at(i);
- QCoreApplication::sendEvent(w, &e);
- }
-#if QT_CONFIG(graphicsview)
- for (int i = 0; i < graphicsWidgets.size(); ++i) {
- QGraphicsWidget *w = graphicsWidgets.at(i);
- QCoreApplication::sendEvent(w, &e);
- }
-#endif
- QCoreApplication::sendEvent(q, &e);
-
- emit q->changed();
-}
-
-#if QT_CONFIG(shortcut)
-void QActionPrivate::redoGrab(QShortcutMap &map)
-{
- Q_Q(QAction);
- if (shortcutId)
- map.removeShortcut(shortcutId, q);
- if (shortcut.isEmpty())
- return;
- shortcutId = map.addShortcut(q, shortcut, shortcutContext, qWidgetShortcutContextMatcher);
- if (!enabled)
- map.setShortcutEnabled(false, shortcutId, q);
- if (!autorepeat)
- map.setShortcutAutoRepeat(false, shortcutId, q);
-}
-
-void QActionPrivate::redoGrabAlternate(QShortcutMap &map)
-{
- Q_Q(QAction);
- for(int i = 0; i < alternateShortcutIds.count(); ++i) {
- if (const int id = alternateShortcutIds.at(i))
- map.removeShortcut(id, q);
- }
- alternateShortcutIds.clear();
- if (alternateShortcuts.isEmpty())
- return;
- for(int i = 0; i < alternateShortcuts.count(); ++i) {
- const QKeySequence& alternate = alternateShortcuts.at(i);
- if (!alternate.isEmpty())
- alternateShortcutIds.append(map.addShortcut(q, alternate, shortcutContext, qWidgetShortcutContextMatcher));
- else
- alternateShortcutIds.append(0);
- }
- if (!enabled) {
- for(int i = 0; i < alternateShortcutIds.count(); ++i) {
- const int id = alternateShortcutIds.at(i);
- map.setShortcutEnabled(false, id, q);
- }
- }
- if (!autorepeat) {
- for(int i = 0; i < alternateShortcutIds.count(); ++i) {
- const int id = alternateShortcutIds.at(i);
- map.setShortcutAutoRepeat(false, id, q);
- }
- }
-}
-
-void QActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map)
-{
- Q_Q(QAction);
- if (shortcutId)
- map.setShortcutEnabled(enable, shortcutId, q);
- for(int i = 0; i < alternateShortcutIds.count(); ++i) {
- if (const int id = alternateShortcutIds.at(i))
- map.setShortcutEnabled(enable, id, q);
- }
-}
-#endif // QT_NO_SHORTCUT
-
-
/*!
\class QAction
\brief The QAction class provides an abstract user interface
@@ -323,12 +222,26 @@ QAction::QAction(const QIcon &icon, const QString &text, QObject* parent)
\internal
*/
QAction::QAction(QActionPrivate &dd, QObject *parent)
- : QObject(dd, parent)
+ : QGuiAction(dd, parent)
+{
+}
+
+/*!
+ \reimp
+*/
+
+bool QAction::event(QEvent *e)
{
Q_D(QAction);
- d->group = qobject_cast<QActionGroup *>(parent);
- if (d->group)
- d->group->addAction(this);
+ if (e->type() == QEvent::ActionChanged) {
+ for (auto w : qAsConst(d->widgets))
+ QCoreApplication::sendEvent(w, e);
+#if QT_CONFIG(graphicsview)
+ for (auto gw : qAsConst(d->graphicsWidgets))
+ QCoreApplication::sendEvent(gw, e);
+#endif
+ }
+ return QGuiAction::event(e);
}
/*!
@@ -368,190 +281,6 @@ QList<QGraphicsWidget *> QAction::associatedGraphicsWidgets() const
}
#endif
-#if QT_CONFIG(shortcut)
-/*!
- \property QAction::shortcut
- \brief the action's primary shortcut key
-
- Valid keycodes for this property can be found in \l Qt::Key and
- \l Qt::Modifier. There is no default shortcut key.
-*/
-void QAction::setShortcut(const QKeySequence &shortcut)
-{
- QAPP_CHECK("setShortcut");
-
- Q_D(QAction);
- if (d->shortcut == shortcut)
- return;
-
- d->shortcut = shortcut;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
- d->sendDataChanged();
-}
-
-/*!
- \since 4.2
-
- Sets \a shortcuts as the list of shortcuts that trigger the
- action. The first element of the list is the primary shortcut.
-
- \sa shortcut
-*/
-void QAction::setShortcuts(const QList<QKeySequence> &shortcuts)
-{
- Q_D(QAction);
-
- QList <QKeySequence> listCopy = shortcuts;
-
- QKeySequence primary;
- if (!listCopy.isEmpty())
- primary = listCopy.takeFirst();
-
- if (d->shortcut == primary && d->alternateShortcuts == listCopy)
- return;
-
- QAPP_CHECK("setShortcuts");
-
- d->shortcut = primary;
- d->alternateShortcuts = listCopy;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
- d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
- d->sendDataChanged();
-}
-
-/*!
- \since 4.2
-
- Sets a platform dependent list of shortcuts based on the \a key.
- The result of calling this function will depend on the currently running platform.
- Note that more than one shortcut can assigned by this action.
- If only the primary shortcut is required, use setShortcut instead.
-
- \sa QKeySequence::keyBindings()
-*/
-void QAction::setShortcuts(QKeySequence::StandardKey key)
-{
- QList <QKeySequence> list = QKeySequence::keyBindings(key);
- setShortcuts(list);
-}
-
-/*!
- Returns the primary shortcut.
-
- \sa setShortcuts()
-*/
-QKeySequence QAction::shortcut() const
-{
- Q_D(const QAction);
- return d->shortcut;
-}
-
-/*!
- \since 4.2
-
- Returns the list of shortcuts, with the primary shortcut as
- the first element of the list.
-
- \sa setShortcuts()
-*/
-QList<QKeySequence> QAction::shortcuts() const
-{
- Q_D(const QAction);
- QList <QKeySequence> shortcuts;
- if (!d->shortcut.isEmpty())
- shortcuts << d->shortcut;
- if (!d->alternateShortcuts.isEmpty())
- shortcuts << d->alternateShortcuts;
- return shortcuts;
-}
-
-/*!
- \property QAction::shortcutContext
- \brief the context for the action's shortcut
-
- Valid values for this property can be found in \l Qt::ShortcutContext.
- The default value is Qt::WindowShortcut.
-*/
-void QAction::setShortcutContext(Qt::ShortcutContext context)
-{
- Q_D(QAction);
- if (d->shortcutContext == context)
- return;
- QAPP_CHECK("setShortcutContext");
- d->shortcutContext = context;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
- d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
- d->sendDataChanged();
-}
-
-Qt::ShortcutContext QAction::shortcutContext() const
-{
- Q_D(const QAction);
- return d->shortcutContext;
-}
-
-/*!
- \property QAction::autoRepeat
- \brief whether the action can auto repeat
- \since 4.2
-
- If true, the action will auto repeat when the keyboard shortcut
- combination is held down, provided that keyboard auto repeat is
- enabled on the system.
- The default value is true.
-*/
-void QAction::setAutoRepeat(bool on)
-{
- Q_D(QAction);
- if (d->autorepeat == on)
- return;
- QAPP_CHECK("setAutoRepeat");
- d->autorepeat = on;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
- d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
- d->sendDataChanged();
-}
-
-bool QAction::autoRepeat() const
-{
- Q_D(const QAction);
- return d->autorepeat;
-}
-#endif // QT_NO_SHORTCUT
-
-/*!
- \property QAction::font
- \brief the action's font
-
- The font property is used to render the text set on the
- QAction. The font will can be considered a hint as it will not be
- consulted in all cases based upon application and style.
-
- By default, this property contains the application's default font.
-
- \sa QAction::setText(), QStyle
-*/
-void QAction::setFont(const QFont &font)
-{
- Q_D(QAction);
- if (d->font == font)
- return;
-
- d->fontSet = true;
- d->font = font;
- d->sendDataChanged();
-}
-
-QFont QAction::font() const
-{
- Q_D(const QAction);
- return d->font;
-}
-
-
-/*!
- Destroys the object and frees allocated resources.
-*/
QAction::~QAction()
{
Q_D(QAction);
@@ -565,76 +294,17 @@ QAction::~QAction()
w->removeAction(this);
}
#endif
- if (d->group)
- d->group->removeAction(this);
-#if QT_CONFIG(shortcut)
- if (d->shortcutId && qApp) {
- QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->shortcutId, this);
- for(int i = 0; i < d->alternateShortcutIds.count(); ++i) {
- const int id = d->alternateShortcutIds.at(i);
- QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(id, this);
- }
- }
-#endif
}
/*!
- Sets this action group to \a group. The action will be automatically
- added to the group's list of actions.
-
- Actions within the group will be mutually exclusive.
-
- \sa QActionGroup, QAction::actionGroup()
-*/
-void QAction::setActionGroup(QActionGroup *group)
-{
- Q_D(QAction);
- if(group == d->group)
- return;
+ Returns the action group for this action. If no action group manages
+ this action then \nullptr will be returned.
- if(d->group)
- d->group->removeAction(this);
- d->group = group;
- if(group)
- group->addAction(this);
- d->sendDataChanged();
-}
-
-/*!
- Returns the action group for this action. If no action group manages
- this action then 0 will be returned.
-
- \sa QActionGroup, QAction::setActionGroup()
-*/
+ \sa QActionGroup, QAction::setActionGroup()
+ */
QActionGroup *QAction::actionGroup() const
{
- Q_D(const QAction);
- return d->group;
-}
-
-
-/*!
- \property QAction::icon
- \brief the action's icon
-
- In toolbars, the icon is used as the tool button icon; in menus,
- it is displayed to the left of the menu text. There is no default
- icon.
-
- If a null icon (QIcon::isNull()) is passed into this function,
- the icon of the action is cleared.
-*/
-void QAction::setIcon(const QIcon &icon)
-{
- Q_D(QAction);
- d->icon = icon;
- d->sendDataChanged();
-}
-
-QIcon QAction::icon() const
-{
- Q_D(const QAction);
- return d->icon;
+ return static_cast<QActionGroup *>(guiActionGroup());
}
#if QT_CONFIG(menu)
@@ -667,460 +337,6 @@ void QAction::setMenu(QMenu *menu)
#endif // QT_CONFIG(menu)
/*!
- If \a b is true then this action will be considered a separator.
-
- How a separator is represented depends on the widget it is inserted
- into. Under most circumstances the text, submenu, and icon will be
- ignored for separator actions.
-
- \sa QAction::isSeparator()
-*/
-void QAction::setSeparator(bool b)
-{
- Q_D(QAction);
- if (d->separator == b)
- return;
-
- d->separator = b;
- d->sendDataChanged();
-}
-
-/*!
- Returns \c true if this action is a separator action; otherwise it
- returns \c false.
-
- \sa QAction::setSeparator()
-*/
-bool QAction::isSeparator() const
-{
- Q_D(const QAction);
- return d->separator;
-}
-
-/*!
- \property QAction::text
- \brief the action's descriptive text
-
- If the action is added to a menu, the menu option will consist of
- the icon (if there is one), the text, and the shortcut (if there
- is one). If the text is not explicitly set in the constructor, or
- by using setText(), the action's description icon text will be
- used as text. There is no default text.
-
- \sa iconText
-*/
-void QAction::setText(const QString &text)
-{
- Q_D(QAction);
- if (d->text == text)
- return;
-
- d->text = text;
- d->sendDataChanged();
-}
-
-QString QAction::text() const
-{
- Q_D(const QAction);
- QString s = d->text;
- if(s.isEmpty()) {
- s = d->iconText;
- s.replace(QLatin1Char('&'), QLatin1String("&&"));
- }
- return s;
-}
-
-
-
-
-
-/*!
- \property QAction::iconText
- \brief the action's descriptive icon text
-
- If QToolBar::toolButtonStyle is set to a value that permits text to
- be displayed, the text defined held in this property appears as a
- label in the relevant tool button.
-
- It also serves as the default text in menus and tooltips if the action
- has not been defined with setText() or setToolTip(), and will
- also be used in toolbar buttons if no icon has been defined using setIcon().
-
- If the icon text is not explicitly set, the action's normal text will be
- used for the icon text.
-
- By default, this property contains an empty string.
-
- \sa setToolTip(), setStatusTip()
-*/
-void QAction::setIconText(const QString &text)
-{
- Q_D(QAction);
- if (d->iconText == text)
- return;
-
- d->iconText = text;
- d->sendDataChanged();
-}
-
-QString QAction::iconText() const
-{
- Q_D(const QAction);
- if (d->iconText.isEmpty())
- return qt_strippedText(d->text);
- return d->iconText;
-}
-
-/*!
- \property QAction::toolTip
- \brief the action's tooltip
-
- This text is used for the tooltip. If no tooltip is specified,
- the action's text is used.
-
- By default, this property contains the action's text.
-
- \sa setStatusTip(), setShortcut()
-*/
-void QAction::setToolTip(const QString &tooltip)
-{
- Q_D(QAction);
- if (d->tooltip == tooltip)
- return;
-
- d->tooltip = tooltip;
- d->sendDataChanged();
-}
-
-QString QAction::toolTip() const
-{
- Q_D(const QAction);
- if (d->tooltip.isEmpty()) {
- if (!d->text.isEmpty())
- return qt_strippedText(d->text);
- return qt_strippedText(d->iconText);
- }
- return d->tooltip;
-}
-
-/*!
- \property QAction::statusTip
- \brief the action's status tip
-
- The status tip is displayed on all status bars provided by the
- action's top-level parent widget.
-
- By default, this property contains an empty string.
-
- \sa setToolTip(), showStatusText()
-*/
-void QAction::setStatusTip(const QString &statustip)
-{
- Q_D(QAction);
- if (d->statustip == statustip)
- return;
-
- d->statustip = statustip;
- d->sendDataChanged();
-}
-
-QString QAction::statusTip() const
-{
- Q_D(const QAction);
- return d->statustip;
-}
-
-/*!
- \property QAction::whatsThis
- \brief the action's "What's This?" help text
-
- The "What's This?" text is used to provide a brief description of
- the action. The text may contain rich text. There is no default
- "What's This?" text.
-
- \sa QWhatsThis
-*/
-void QAction::setWhatsThis(const QString &whatsthis)
-{
- Q_D(QAction);
- if (d->whatsthis == whatsthis)
- return;
-
- d->whatsthis = whatsthis;
- d->sendDataChanged();
-}
-
-QString QAction::whatsThis() const
-{
- Q_D(const QAction);
- return d->whatsthis;
-}
-
-/*!
- \enum QAction::Priority
- \since 4.6
-
- This enum defines priorities for actions in user interface.
-
- \value LowPriority The action should not be prioritized in
- the user interface.
-
- \value NormalPriority
-
- \value HighPriority The action should be prioritized in
- the user interface.
-
- \sa priority
-*/
-
-
-/*!
- \property QAction::priority
- \since 4.6
-
- \brief the actions's priority in the user interface.
-
- This property can be set to indicate how the action should be prioritized
- in the user interface.
-
- For instance, when toolbars have the Qt::ToolButtonTextBesideIcon
- mode set, then actions with LowPriority will not show the text
- labels.
-*/
-void QAction::setPriority(Priority priority)
-{
- Q_D(QAction);
- if (d->priority == priority)
- return;
-
- d->priority = priority;
- d->sendDataChanged();
-}
-
-QAction::Priority QAction::priority() const
-{
- Q_D(const QAction);
- return d->priority;
-}
-
-/*!
- \property QAction::checkable
- \brief whether the action is a checkable action
-
- A checkable action is one which has an on/off state. For example,
- in a word processor, a Bold toolbar button may be either on or
- off. An action which is not a toggle action is a command action;
- a command action is simply executed, e.g. file save.
- By default, this property is \c false.
-
- In some situations, the state of one toggle action should depend
- on the state of others. For example, "Left Align", "Center" and
- "Right Align" toggle actions are mutually exclusive. To achieve
- exclusive toggling, add the relevant toggle actions to a
- QActionGroup with the QActionGroup::exclusive property set to
- true.
-
- \sa QAction::setChecked()
-*/
-void QAction::setCheckable(bool b)
-{
- Q_D(QAction);
- if (d->checkable == b)
- return;
-
- d->checkable = b;
- d->checked = false;
- d->sendDataChanged();
-}
-
-bool QAction::isCheckable() const
-{
- Q_D(const QAction);
- return d->checkable;
-}
-
-/*!
- \fn void QAction::toggle()
-
- This is a convenience function for the \l checked property.
- Connect to it to change the checked state to its opposite state.
-*/
-void QAction::toggle()
-{
- Q_D(QAction);
- setChecked(!d->checked);
-}
-
-/*!
- \property QAction::checked
- \brief whether the action is checked.
-
- Only checkable actions can be checked. By default, this is false
- (the action is unchecked).
-
- \note The notifier signal for this property is toggled(). As toggling
- a QAction changes its state, it will also emit a changed() signal.
-
- \sa checkable, toggled()
-*/
-void QAction::setChecked(bool b)
-{
- Q_D(QAction);
- if (!d->checkable || d->checked == b)
- return;
-
- QPointer<QAction> guard(this);
- d->checked = b;
- d->sendDataChanged();
- if (guard)
- emit toggled(b);
-}
-
-bool QAction::isChecked() const
-{
- Q_D(const QAction);
- return d->checked;
-}
-
-/*!
- \fn void QAction::setDisabled(bool b)
-
- This is a convenience function for the \l enabled property, that
- is useful for signals--slots connections. If \a b is true the
- action is disabled; otherwise it is enabled.
-*/
-
-/*!
- \property QAction::enabled
- \brief whether the action is enabled
-
- Disabled actions cannot be chosen by the user. They do not
- disappear from menus or toolbars, but they are displayed in a way
- which indicates that they are unavailable. For example, they might
- be displayed using only shades of gray.
-
- \uicontrol{What's This?} help on disabled actions is still available, provided
- that the QAction::whatsThis property is set.
-
- An action will be disabled when all widgets to which it is added
- (with QWidget::addAction()) are disabled or not visible. When an
- action is disabled, it is not possible to trigger it through its
- shortcut.
-
- By default, this property is \c true (actions are enabled).
-
- \sa text
-*/
-void QAction::setEnabled(bool b)
-{
- Q_D(QAction);
- if (b == d->enabled && b != d->forceDisabled)
- return;
- d->forceDisabled = !b;
- if (b && (!d->visible || (d->group && !d->group->isEnabled())))
- return;
- QAPP_CHECK("setEnabled");
- d->enabled = b;
-#if QT_CONFIG(shortcut)
- d->setShortcutEnabled(b, QGuiApplicationPrivate::instance()->shortcutMap);
-#endif
- d->sendDataChanged();
-}
-
-bool QAction::isEnabled() const
-{
- Q_D(const QAction);
- return d->enabled;
-}
-
-/*!
- \property QAction::visible
- \brief whether the action can be seen (e.g. in menus and toolbars)
-
- If \e visible is true the action can be seen (e.g. in menus and
- toolbars) and chosen by the user; if \e visible is false the
- action cannot be seen or chosen by the user.
-
- Actions which are not visible are \e not grayed out; they do not
- appear at all.
-
- By default, this property is \c true (actions are visible).
-*/
-void QAction::setVisible(bool b)
-{
- Q_D(QAction);
- if (b == d->visible && b != d->forceInvisible)
- return;
- QAPP_CHECK("setVisible");
- d->forceInvisible = !b;
- d->visible = b;
- d->enabled = b && !d->forceDisabled && (!d->group || d->group->isEnabled()) ;
-#if QT_CONFIG(shortcut)
- d->setShortcutEnabled(d->enabled, QGuiApplicationPrivate::instance()->shortcutMap);
-#endif
- d->sendDataChanged();
-}
-
-
-bool QAction::isVisible() const
-{
- Q_D(const QAction);
- return d->visible;
-}
-
-/*!
- \reimp
-*/
-bool
-QAction::event(QEvent *e)
-{
-#if QT_CONFIG(shortcut)
- if (e->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- Q_ASSERT_X(se->key() == d_func()->shortcut || d_func()->alternateShortcuts.contains(se->key()),
- "QAction::event",
- "Received shortcut event from incorrect shortcut");
- if (se->isAmbiguous())
- qWarning("QAction::event: Ambiguous shortcut overload: %s", se->key().toString(QKeySequence::NativeText).toLatin1().constData());
- else
- activate(Trigger);
- return true;
- }
-#endif
- return QObject::event(e);
-}
-
-/*!
- Returns the user data as set in QAction::setData.
-
- \sa setData()
-*/
-QVariant
-QAction::data() const
-{
- Q_D(const QAction);
- return d->userData;
-}
-
-/*!
- \fn void QAction::setData(const QVariant &userData)
-
- Sets the action's internal data to the given \a userData.
-
- \sa data()
-*/
-void
-QAction::setData(const QVariant &data)
-{
- Q_D(QAction);
- if (d->userData == data)
- return;
- d->userData = data;
- d->sendDataChanged();
-}
-
-
-/*!
Updates the relevant status bar for the \a widget specified by sending a
QStatusTipEvent to its parent widget. Returns \c true if an event was sent;
otherwise returns \c false.
@@ -1135,233 +351,4 @@ QAction::showStatusText(QWidget *widget)
return d_func()->showStatusText(widget, statusTip());
}
-/*!
- Sends the relevant signals for ActionEvent \a event.
-
- Action based widgets use this API to cause the QAction
- to emit signals as well as emitting their own.
-*/
-void QAction::activate(ActionEvent event)
-{
- Q_D(QAction);
- if(event == Trigger) {
- QPointer<QObject> guard = this;
- if(d->checkable) {
- // the checked action of an exclusive group may not be unchecked
- if (d->checked && (d->group
- && d->group->exclusionPolicy() == QActionGroup::ExclusionPolicy::Exclusive
- && d->group->checkedAction() == this)) {
- if (!guard.isNull())
- emit triggered(true);
- return;
- }
- setChecked(!d->checked);
- }
- if (!guard.isNull())
- emit triggered(d->checked);
- } else if(event == Hover) {
- emit hovered();
- }
-}
-
-/*!
- \fn void QAction::triggered(bool checked)
-
- This signal is emitted when an action is activated by the user;
- for example, when the user clicks a menu option, toolbar button,
- or presses an action's shortcut key combination, or when trigger()
- was called. Notably, it is \e not emitted when setChecked() or
- toggle() is called.
-
- If the action is checkable, \a checked is true if the action is
- checked, or false if the action is unchecked.
-
- \sa QAction::activate(), QAction::toggled(), checked
-*/
-
-/*!
- \fn void QAction::toggled(bool checked)
-
- This signal is emitted whenever a checkable action changes its
- isChecked() status. This can be the result of a user interaction,
- or because setChecked() was called. As setChecked() changes the
- QAction, it emits changed() in addition to toggled().
-
- \a checked is true if the action is checked, or false if the
- action is unchecked.
-
- \sa QAction::activate(), QAction::triggered(), checked
-*/
-
-/*!
- \fn void QAction::hovered()
-
- This signal is emitted when an action is highlighted by the user;
- for example, when the user pauses with the cursor over a menu option,
- toolbar button, or presses an action's shortcut key combination.
-
- \sa QAction::activate()
-*/
-
-/*!
- \fn void QAction::changed()
-
- This signal is emitted when an action has changed. If you
- are only interested in actions in a given widget, you can
- watch for QWidget::actionEvent() sent with an
- QEvent::ActionChanged.
-
- \sa QWidget::actionEvent()
-*/
-
-/*!
- \enum QAction::ActionEvent
-
- This enum type is used when calling QAction::activate()
-
- \value Trigger this will cause the QAction::triggered() signal to be emitted.
-
- \value Hover this will cause the QAction::hovered() signal to be emitted.
-*/
-
-/*!
- \property QAction::menuRole
- \brief the action's menu role
- \since 4.2
-
- This indicates what role the action serves in the application menu on
- \macos. By default all actions have the TextHeuristicRole, which means that
- the action is added based on its text (see QMenuBar for more information).
-
- The menu role can only be changed before the actions are put into the menu
- bar in \macos (usually just before the first application window is
- shown).
-*/
-void QAction::setMenuRole(MenuRole menuRole)
-{
- Q_D(QAction);
- if (d->menuRole == menuRole)
- return;
-
- d->menuRole = menuRole;
- d->sendDataChanged();
-}
-
-QAction::MenuRole QAction::menuRole() const
-{
- Q_D(const QAction);
- return d->menuRole;
-}
-
-/*!
- \property QAction::iconVisibleInMenu
- \brief Whether or not an action should show an icon in a menu
- \since 4.4
-
- In some applications, it may make sense to have actions with icons in the
- toolbar, but not in menus. If true, the icon (if valid) is shown in the menu, when it
- is false, it is not shown.
-
- The default is to follow whether the Qt::AA_DontShowIconsInMenus attribute
- is set for the application. Explicitly settings this property overrides
- the presence (or abscence) of the attribute.
-
- For example:
- \snippet code/src_gui_kernel_qaction.cpp 0
-
- \sa QAction::icon, QCoreApplication::setAttribute()
-*/
-void QAction::setIconVisibleInMenu(bool visible)
-{
- Q_D(QAction);
- if (d->iconVisibleInMenu == -1 || visible != bool(d->iconVisibleInMenu)) {
- int oldValue = d->iconVisibleInMenu;
- d->iconVisibleInMenu = visible;
- // Only send data changed if we really need to.
- if (oldValue != -1
- || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus)) {
- d->sendDataChanged();
- }
- }
-}
-
-bool QAction::isIconVisibleInMenu() const
-{
- Q_D(const QAction);
- if (d->iconVisibleInMenu == -1) {
- return !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus);
- }
- return d->iconVisibleInMenu;
-}
-
-/*!
- \property QAction::shortcutVisibleInContextMenu
- \brief Whether or not an action should show a shortcut in a context menu
- \since 5.10
-
- In some applications, it may make sense to have actions with shortcuts in
- context menus. If true, the shortcut (if valid) is shown when the action is
- shown via a context menu, when it is false, it is not shown.
-
- The default is to follow whether the Qt::AA_DontShowShortcutsInContextMenus attribute
- is set for the application, falling back to the widget style hint.
- Explicitly setting this property overrides the presence (or abscence) of the attribute.
-
- \sa QAction::shortcut, QCoreApplication::setAttribute()
-*/
-void QAction::setShortcutVisibleInContextMenu(bool visible)
-{
- Q_D(QAction);
- if (d->shortcutVisibleInContextMenu == -1 || visible != bool(d->shortcutVisibleInContextMenu)) {
- int oldValue = d->shortcutVisibleInContextMenu;
- d->shortcutVisibleInContextMenu = visible;
- // Only send data changed if we really need to.
- if (oldValue != -1
- || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)) {
- d->sendDataChanged();
- }
- }
-}
-
-bool QAction::isShortcutVisibleInContextMenu() const
-{
- Q_D(const QAction);
- if (d->shortcutVisibleInContextMenu == -1) {
- return !QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)
- && QGuiApplication::styleHints()->showShortcutsInContextMenus();
- }
- return d->shortcutVisibleInContextMenu;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_WIDGETS_EXPORT QDebug operator<<(QDebug d, const QAction *action)
-{
- QDebugStateSaver saver(d);
- d.nospace();
- d << "QAction(" << static_cast<const void *>(action);
- if (action) {
- d << " text=" << action->text();
- if (!action->toolTip().isEmpty())
- d << " toolTip=" << action->toolTip();
- if (action->isCheckable())
- d << " checked=" << action->isChecked();
-#if QT_CONFIG(shortcut)
- if (!action->shortcut().isEmpty())
- d << " shortcut=" << action->shortcut();
-#endif
- d << " menuRole=";
- QtDebugUtils::formatQEnum(d, action->menuRole());
- d << " visible=" << action->isVisible();
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // QT_NO_DEBUG_STREAM
-
QT_END_NAMESPACE
-
-#include "moc_qaction.cpp"
-
-#endif // QT_NO_ACTION
diff --git a/src/widgets/kernel/qaction.h b/src/widgets/kernel/qaction.h
index 258a1ea0a0..808ee9065d 100644
--- a/src/widgets/kernel/qaction.h
+++ b/src/widgets/kernel/qaction.h
@@ -41,137 +41,39 @@
#define QACTION_H
#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtGui/qkeysequence.h>
+#include <QtGui/qguiaction.h>
#include <QtCore/qstring.h>
#include <QtWidgets/qwidget.h>
#include <QtCore/qvariant.h>
-#include <QtGui/qicon.h>
-
-QT_BEGIN_NAMESPACE
+QT_REQUIRE_CONFIG(action);
-#ifndef QT_NO_ACTION
+QT_BEGIN_NAMESPACE
class QMenu;
class QActionGroup;
class QActionPrivate;
class QGraphicsWidget;
-class Q_WIDGETS_EXPORT QAction : public QObject
+class Q_WIDGETS_EXPORT QAction : public QGuiAction
{
Q_OBJECT
Q_DECLARE_PRIVATE(QAction)
-
- Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable NOTIFY changed)
- Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY changed)
- Q_PROPERTY(QIcon icon READ icon WRITE setIcon NOTIFY changed)
- Q_PROPERTY(QString text READ text WRITE setText NOTIFY changed)
- Q_PROPERTY(QString iconText READ iconText WRITE setIconText NOTIFY changed)
- Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip NOTIFY changed)
- Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip NOTIFY changed)
- Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis NOTIFY changed)
- Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY changed)
-#if QT_CONFIG(shortcut)
- Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut NOTIFY changed)
- Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext NOTIFY changed)
- Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat NOTIFY changed)
-#endif
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY changed)
- Q_PROPERTY(MenuRole menuRole READ menuRole WRITE setMenuRole NOTIFY changed)
- Q_PROPERTY(bool iconVisibleInMenu READ isIconVisibleInMenu WRITE setIconVisibleInMenu NOTIFY changed)
- Q_PROPERTY(bool shortcutVisibleInContextMenu READ isShortcutVisibleInContextMenu WRITE setShortcutVisibleInContextMenu NOTIFY changed)
- Q_PROPERTY(Priority priority READ priority WRITE setPriority)
-
public:
- // note this is copied into qplatformmenu.h, which must stay in sync
- enum MenuRole { NoRole = 0, TextHeuristicRole, ApplicationSpecificRole, AboutQtRole,
- AboutRole, PreferencesRole, QuitRole };
- Q_ENUM(MenuRole)
- enum Priority { LowPriority = 0,
- NormalPriority = 128,
- HighPriority = 256};
- Q_ENUM(Priority)
- explicit QAction(QObject *parent = nullptr);
- explicit QAction(const QString &text, QObject *parent = nullptr);
- explicit QAction(const QIcon &icon, const QString &text, QObject *parent = nullptr);
-
+ QAction(QObject* parent = nullptr);
+ QAction(const QString &text, QObject* parent = nullptr);
+ QAction(const QIcon &icon, const QString &text, QObject* parent);
~QAction();
- void setActionGroup(QActionGroup *group);
QActionGroup *actionGroup() const;
- void setIcon(const QIcon &icon);
- QIcon icon() const;
-
- void setText(const QString &text);
- QString text() const;
-
- void setIconText(const QString &text);
- QString iconText() const;
-
- void setToolTip(const QString &tip);
- QString toolTip() const;
-
- void setStatusTip(const QString &statusTip);
- QString statusTip() const;
-
- void setWhatsThis(const QString &what);
- QString whatsThis() const;
-
- void setPriority(Priority priority);
- Priority priority() const;
#if QT_CONFIG(menu)
QMenu *menu() const;
void setMenu(QMenu *menu);
#endif
- void setSeparator(bool b);
- bool isSeparator() const;
-
-#if QT_CONFIG(shortcut)
- void setShortcut(const QKeySequence &shortcut);
- QKeySequence shortcut() const;
-
- void setShortcuts(const QList<QKeySequence> &shortcuts);
- void setShortcuts(QKeySequence::StandardKey);
- QList<QKeySequence> shortcuts() const;
-
- void setShortcutContext(Qt::ShortcutContext context);
- Qt::ShortcutContext shortcutContext() const;
-
- void setAutoRepeat(bool);
- bool autoRepeat() const;
-#endif
-
- void setFont(const QFont &font);
- QFont font() const;
-
- void setCheckable(bool);
- bool isCheckable() const;
-
- QVariant data() const;
- void setData(const QVariant &var);
-
- bool isChecked() const;
-
- bool isEnabled() const;
-
- bool isVisible() const;
-
- enum ActionEvent { Trigger, Hover };
- void activate(ActionEvent event);
bool showStatusText(QWidget *widget = nullptr);
- void setMenuRole(MenuRole menuRole);
- MenuRole menuRole() const;
-
- void setIconVisibleInMenu(bool visible);
- bool isIconVisibleInMenu() const;
-
- void setShortcutVisibleInContextMenu(bool show);
- bool isShortcutVisibleInContextMenu() const;
-
QWidget *parentWidget() const;
QList<QWidget *> associatedWidgets() const;
@@ -180,30 +82,14 @@ public:
#endif
protected:
- bool event(QEvent *) override;
QAction(QActionPrivate &dd, QObject *parent);
-
-public Q_SLOTS:
- void trigger() { activate(Trigger); }
- void hover() { activate(Hover); }
- void setChecked(bool);
- void toggle();
- void setEnabled(bool);
- inline void setDisabled(bool b) { setEnabled(!b); }
- void setVisible(bool);
-
-Q_SIGNALS:
- void changed();
- void triggered(bool checked = false);
- void hovered();
- void toggled(bool);
+ bool event(QEvent *) override;
private:
Q_DISABLE_COPY(QAction)
friend class QGraphicsWidget;
friend class QWidget;
- friend class QActionGroup;
friend class QMenu;
friend class QMenuPrivate;
friend class QMenuBar;
@@ -221,8 +107,6 @@ QT_BEGIN_INCLUDE_NAMESPACE
#include <QtWidgets/qactiongroup.h>
QT_END_INCLUDE_NAMESPACE
-#endif // QT_NO_ACTION
-
QT_END_NAMESPACE
#endif // QACTION_H
diff --git a/src/widgets/kernel/qaction_p.h b/src/widgets/kernel/qaction_p.h
index 6b6ca8076f..b865769372 100644
--- a/src/widgets/kernel/qaction_p.h
+++ b/src/widgets/kernel/qaction_p.h
@@ -52,6 +52,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include <QtGui/private/qguiaction_p.h>
#include "QtWidgets/qaction.h"
#if QT_CONFIG(menu)
#include "QtWidgets/qmenu.h"
@@ -68,12 +69,15 @@ QT_BEGIN_NAMESPACE
class QShortcutMap;
-class Q_WIDGETS_EXPORT QActionPrivate : public QObjectPrivate
+class Q_WIDGETS_EXPORT QActionPrivate : public QGuiActionPrivate
{
Q_DECLARE_PUBLIC(QAction)
public:
- QActionPrivate();
- ~QActionPrivate();
+ QActionPrivate() = default;
+
+#if QT_CONFIG(shortcut)
+ QShortcutMap::ContextMatcher contextMatcher() const override;
+#endif
static QActionPrivate *get(QAction *q)
{
@@ -82,50 +86,11 @@ public:
bool showStatusText(QWidget *w, const QString &str);
- QPointer<QActionGroup> group;
- QString text;
- QString iconText;
- QIcon icon;
- QString tooltip;
- QString statustip;
- QString whatsthis;
-#if QT_CONFIG(shortcut)
- QKeySequence shortcut;
- QList<QKeySequence> alternateShortcuts;
-#endif
- QVariant userData;
-#if QT_CONFIG(shortcut)
- int shortcutId = 0;
- QVector<int> alternateShortcutIds;
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut;
- uint autorepeat : 1;
-#endif
- QFont font;
QPointer<QMenu> menu;
- uint enabled : 1, forceDisabled : 1;
- uint visible : 1, forceInvisible : 1;
- uint checkable : 1;
- uint checked : 1;
- uint separator : 1;
- uint fontSet : 1;
-
- int iconVisibleInMenu : 2; // Only has values -1, 0, and 1
- int shortcutVisibleInContextMenu : 2; // Only has values -1, 0, and 1
-
- QAction::MenuRole menuRole = QAction::TextHeuristicRole;
- QAction::Priority priority = QAction::NormalPriority;
-
QWidgetList widgets;
#if QT_CONFIG(graphicsview)
QList<QGraphicsWidget *> graphicsWidgets;
#endif
-#if QT_CONFIG(shortcut)
- void redoGrab(QShortcutMap &map);
- void redoGrabAlternate(QShortcutMap &map);
- void setShortcutEnabled(bool enable, QShortcutMap &map);
-#endif // QT_NO_SHORTCUT
-
- void sendDataChanged();
};
#endif // QT_NO_ACTION
diff --git a/src/widgets/kernel/qactiongroup.cpp b/src/widgets/kernel/qactiongroup.cpp
index d51fb778c4..cc900cbb0f 100644
--- a/src/widgets/kernel/qactiongroup.cpp
+++ b/src/widgets/kernel/qactiongroup.cpp
@@ -38,70 +38,32 @@
****************************************************************************/
#include "qactiongroup.h"
+#include <QtGui/private/qguiactiongroup_p.h>
-#ifndef QT_NO_ACTION
-
-#include "qaction_p.h"
-#include "qevent.h"
-#include "qlist.h"
+#include "qaction.h"
QT_BEGIN_NAMESPACE
-class QActionGroupPrivate : public QObjectPrivate
+class QActionGroupPrivate : public QGuiActionGroupPrivate
{
Q_DECLARE_PUBLIC(QActionGroup)
public:
- QActionGroupPrivate() : enabled(1),
- visible(1),
- exclusionPolicy(QActionGroup::ExclusionPolicy::Exclusive)
- {
- }
- QList<QAction *> actions;
- QPointer<QAction> current;
- uint enabled : 1;
- uint visible : 1;
- QActionGroup::ExclusionPolicy exclusionPolicy;
-
-private:
- void _q_actionTriggered(); //private slot
- void _q_actionChanged(); //private slot
- void _q_actionHovered(); //private slot
+ void emitSignal(Signal, QGuiAction *) override;
};
-void QActionGroupPrivate::_q_actionChanged()
+void QActionGroupPrivate::emitSignal(Signal s, QGuiAction *action)
{
Q_Q(QActionGroup);
- QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionChanged", "internal error");
- if (exclusionPolicy != QActionGroup::ExclusionPolicy::None) {
- if (action->isChecked()) {
- if (action != current) {
- if(current)
- current->setChecked(false);
- current = action;
- }
- } else if (action == current) {
- current = nullptr;
- }
+ switch (s) {
+ case QGuiActionGroupPrivate::Triggered:
+ emit q->triggered(static_cast<QAction *>(action));
+ break;
+ case QGuiActionGroupPrivate::Hovered:
+ emit q->hovered(static_cast<QAction *>(action));
+ break;
}
}
-void QActionGroupPrivate::_q_actionTriggered()
-{
- Q_Q(QActionGroup);
- QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionTriggered", "internal error");
- emit q->triggered(action);
-}
-
-void QActionGroupPrivate::_q_actionHovered()
-{
- Q_Q(QActionGroup);
- QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionHovered", "internal error");
- emit q->hovered(action);
-}
-
/*!
\class QActionGroup
\brief The QActionGroup class groups actions together.
@@ -154,27 +116,6 @@ void QActionGroupPrivate::_q_actionHovered()
*/
/*!
- \enum QActionGroup::ExclusionPolicy
-
- This enum specifies the different policies that can be used to
- control how the group performs exclusive checking on checkable actions.
-
- \value None
- The actions in the group can be checked independently of each other.
-
- \value Exclusive
- Exactly one action can be checked at any one time.
- This is the default policy.
-
- \value ExclusiveOptional
- At most one action can be checked at any one time. The actions
- can also be all unchecked.
-
- \sa exclusionPolicy
- \since 5.14
-*/
-
-/*!
Constructs an action group for the \a parent object.
The action group is exclusive by default. Call setExclusive(false)
@@ -182,53 +123,24 @@ void QActionGroupPrivate::_q_actionHovered()
but allow unchecking the active action call instead
setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional)
*/
-QActionGroup::QActionGroup(QObject* parent) : QObject(*new QActionGroupPrivate, parent)
+QActionGroup::QActionGroup(QObject* parent) :
+ QGuiActionGroup(*new QActionGroupPrivate, parent)
{
}
/*!
Destroys the action group.
*/
-QActionGroup::~QActionGroup()
+QActionGroup::~QActionGroup() = default;
+
+QAction *QActionGroup::checkedAction() const
{
+ return static_cast<QAction *>(checkedGuiAction());
}
-/*!
- \fn QAction *QActionGroup::addAction(QAction *action)
-
- Adds the \a action to this group, and returns it.
-
- Normally an action is added to a group by creating it with the
- group as its parent, so this function is not usually used.
-
- \sa QAction::setActionGroup()
-*/
-QAction *QActionGroup::addAction(QAction* a)
+QAction *QActionGroup::addAction(QAction *a)
{
- Q_D(QActionGroup);
- if(!d->actions.contains(a)) {
- d->actions.append(a);
- QObject::connect(a, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
- QObject::connect(a, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
- QObject::connect(a, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
- }
- if(!a->d_func()->forceDisabled) {
- a->setEnabled(d->enabled);
- a->d_func()->forceDisabled = false;
- }
- if(!a->d_func()->forceInvisible) {
- a->setVisible(d->visible);
- a->d_func()->forceInvisible = false;
- }
- if(a->isChecked())
- d->current = a;
- QActionGroup *oldGroup = a->d_func()->group;
- if(oldGroup != this) {
- if (oldGroup)
- oldGroup->removeAction(a);
- a->d_func()->group = this;
- a->d_func()->sendDataChanged();
- }
+ QGuiActionGroup::addAction(a);
return a;
}
@@ -261,185 +173,16 @@ QAction *QActionGroup::addAction(const QIcon &icon, const QString &text)
}
/*!
- Removes the \a action from this group. The action will have no
- parent as a result.
-
- \sa QAction::setActionGroup()
-*/
-void QActionGroup::removeAction(QAction *action)
-{
- Q_D(QActionGroup);
- if (d->actions.removeAll(action)) {
- if (action == d->current)
- d->current = nullptr;
- QObject::disconnect(action, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
- QObject::disconnect(action, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
- QObject::disconnect(action, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
- action->d_func()->group = nullptr;
- }
-}
-
-/*!
Returns the list of this groups's actions. This may be empty.
*/
QList<QAction*> QActionGroup::actions() const
{
- Q_D(const QActionGroup);
- return d->actions;
+ QList<QAction*> result;
+ const auto baseActions = guiActions();
+ result.reserve(baseActions.size());
+ for (auto baseAction : baseActions)
+ result.append(static_cast<QAction*>(baseAction));
+ return result;
}
-/*!
- \brief Enable or disable the group exclusion checking
-
- This is a convenience method that calls
- setExclusionPolicy(ExclusionPolicy::Exclusive) when \a b is true,
- else setExclusionPolicy(QActionGroup::ExclusionPolicy::None).
-
- \sa QActionGroup::exclusionPolicy
-*/
-void QActionGroup::setExclusive(bool b)
-{
- setExclusionPolicy(b ? QActionGroup::ExclusionPolicy::Exclusive
- : QActionGroup::ExclusionPolicy::None);
-}
-
-/*!
- \brief Returns true if the group is exclusive
-
- The group is exclusive if the ExclusionPolicy is either Exclusive
- or ExclusionOptional.
-
-*/
-bool QActionGroup::isExclusive() const
-{
- return exclusionPolicy() != QActionGroup::ExclusionPolicy::None;
-}
-
-/*!
- \property QActionGroup::exclusionPolicy
- \brief This property holds the group exclusive checking policy
-
- If exclusionPolicy is set to Exclusive, only one checkable
- action in the action group can ever be active at any time. If the user
- chooses another checkable action in the group, the one they chose becomes
- active and the one that was active becomes inactive. If exclusionPolicy is
- set to ExclusionOptional the group is exclusive but the active checkable
- action in the group can be unchecked leaving the group with no actions
- checked.
-
- \sa QAction::checkable
- \since 5.14
-*/
-void QActionGroup::setExclusionPolicy(QActionGroup::ExclusionPolicy policy)
-{
- Q_D(QActionGroup);
- d->exclusionPolicy = policy;
-}
-
-QActionGroup::ExclusionPolicy QActionGroup::exclusionPolicy() const
-{
- Q_D(const QActionGroup);
- return d->exclusionPolicy;
-}
-
-/*!
- \fn void QActionGroup::setDisabled(bool b)
-
- This is a convenience function for the \l enabled property, that
- is useful for signals--slots connections. If \a b is true the
- action group is disabled; otherwise it is enabled.
-*/
-
-/*!
- \property QActionGroup::enabled
- \brief whether the action group is enabled
-
- Each action in the group will be enabled or disabled unless it
- has been explicitly disabled.
-
- \sa QAction::setEnabled()
-*/
-void QActionGroup::setEnabled(bool b)
-{
- Q_D(QActionGroup);
- d->enabled = b;
- for (auto action : qAsConst(d->actions)) {
- if (!action->d_func()->forceDisabled) {
- action->setEnabled(b);
- action->d_func()->forceDisabled = false;
- }
- }
-}
-
-bool QActionGroup::isEnabled() const
-{
- Q_D(const QActionGroup);
- return d->enabled;
-}
-
-/*!
- Returns the currently checked action in the group, or \nullptr if
- none are checked.
-*/
-QAction *QActionGroup::checkedAction() const
-{
- Q_D(const QActionGroup);
- return d->current;
-}
-
-/*!
- \property QActionGroup::visible
- \brief whether the action group is visible
-
- Each action in the action group will match the visible state of
- this group unless it has been explicitly hidden.
-
- \sa QAction::setEnabled()
-*/
-void QActionGroup::setVisible(bool b)
-{
- Q_D(QActionGroup);
- d->visible = b;
- for (auto action : qAsConst(d->actions)) {
- if (!action->d_func()->forceInvisible) {
- action->setVisible(b);
- action->d_func()->forceInvisible = false;
- }
- }
-}
-
-bool QActionGroup::isVisible() const
-{
- Q_D(const QActionGroup);
- return d->visible;
-}
-
-/*!
- \fn void QActionGroup::triggered(QAction *action)
-
- This signal is emitted when the given \a action in the action
- group is activated by the user; for example, when the user clicks
- a menu option, toolbar button, or presses an action's shortcut key
- combination.
-
- Connect to this signal for command actions.
-
- \sa QAction::activate()
-*/
-
-/*!
- \fn void QActionGroup::hovered(QAction *action)
-
- This signal is emitted when the given \a action in the action
- group is highlighted by the user; for example, when the user
- pauses with the cursor over a menu option, toolbar button, or
- presses an action's shortcut key combination.
-
- \sa QAction::activate()
-*/
-
QT_END_NAMESPACE
-
-#include "moc_qactiongroup.cpp"
-
-#endif // QT_NO_ACTION
diff --git a/src/widgets/kernel/qactiongroup.h b/src/widgets/kernel/qactiongroup.h
index 90f488bedb..0a6a85f093 100644
--- a/src/widgets/kernel/qactiongroup.h
+++ b/src/widgets/kernel/qactiongroup.h
@@ -41,54 +41,31 @@
#define QACTIONGROUP_H
#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtGui/qguiactiongroup.h>
#include <QtWidgets/qaction.h>
-QT_BEGIN_NAMESPACE
-
+QT_REQUIRE_CONFIG(action);
-#ifndef QT_NO_ACTION
+QT_BEGIN_NAMESPACE
class QActionGroupPrivate;
-class Q_WIDGETS_EXPORT QActionGroup : public QObject
+class Q_WIDGETS_EXPORT QActionGroup : public QGuiActionGroup
{
Q_OBJECT
Q_DECLARE_PRIVATE(QActionGroup)
- Q_PROPERTY(QActionGroup::ExclusionPolicy exclusionPolicy READ exclusionPolicy WRITE setExclusionPolicy)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible)
-
public:
- enum class ExclusionPolicy {
- None,
- Exclusive,
- ExclusiveOptional
- };
- Q_ENUM(ExclusionPolicy)
-
explicit QActionGroup(QObject* parent);
~QActionGroup();
- QAction *addAction(QAction* a);
- QAction *addAction(const QString &text);
- QAction *addAction(const QIcon &icon, const QString &text);
- void removeAction(QAction *a);
- QList<QAction*> actions() const;
-
QAction *checkedAction() const;
- bool isExclusive() const;
- bool isEnabled() const;
- bool isVisible() const;
- ExclusionPolicy exclusionPolicy() const;
+ QAction *addAction(QAction *a);
+ QAction *addAction(const QString &text);
+ QAction *addAction(const QIcon &icon, const QString &text);
-public Q_SLOTS:
- void setEnabled(bool);
- inline void setDisabled(bool b) { setEnabled(!b); }
- void setVisible(bool);
- void setExclusive(bool);
- void setExclusionPolicy(ExclusionPolicy policy);
+ QList<QAction*> actions() const;
Q_SIGNALS:
void triggered(QAction *);
@@ -96,13 +73,8 @@ Q_SIGNALS:
private:
Q_DISABLE_COPY(QActionGroup)
- Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
- Q_PRIVATE_SLOT(d_func(), void _q_actionChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_actionHovered())
};
-#endif // QT_NO_ACTION
-
QT_END_NAMESPACE
#endif // QACTIONGROUP_H
diff --git a/src/widgets/kernel/qapplication.h b/src/widgets/kernel/qapplication.h
index 27e743a28d..d7cc4489c4 100644
--- a/src/widgets/kernel/qapplication.h
+++ b/src/widgets/kernel/qapplication.h
@@ -58,7 +58,6 @@ class QDesktopWidget;
class QStyle;
class QEventLoop;
class QIcon;
-template <typename T> class QList;
class QLocale;
class QPlatformNativeInterface;
diff --git a/src/widgets/kernel/qshortcut.cpp b/src/widgets/kernel/qshortcut.cpp
index 039699a004..4a2f8d66c2 100644
--- a/src/widgets/kernel/qshortcut.cpp
+++ b/src/widgets/kernel/qshortcut.cpp
@@ -40,7 +40,6 @@
#include "qshortcut.h"
#include "private/qwidget_p.h"
-#ifndef QT_NO_SHORTCUT
#include <qevent.h>
#if QT_CONFIG(whatsthis)
#include <qwhatsthis.h>
@@ -53,25 +52,21 @@
#endif
#include <qapplication.h>
#include <private/qapplication_p.h>
+#include "private/qguishortcut_p.h"
#include <private/qshortcutmap_p.h>
-#include <private/qaction_p.h>
+#if QT_CONFIG(action)
+# include <private/qaction_p.h>
+#endif
#include <private/qwidgetwindow_p.h>
#include <qpa/qplatformmenu.h>
QT_BEGIN_NAMESPACE
-#define QAPP_CHECK(functionName) \
- if (Q_UNLIKELY(!qApp)) { \
- qWarning("QShortcut: Initialize QApplication before calling '" functionName "'."); \
- return; \
- }
-
-
static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window);
#if QT_CONFIG(graphicsview)
static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window);
#endif
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window);
#endif
@@ -108,7 +103,7 @@ bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
if (!active_window)
return false;
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
if (auto a = qobject_cast<QAction *>(object))
return correctActionContext(context, a, active_window);
#endif
@@ -284,7 +279,7 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
}
#endif
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window)
{
const QWidgetList &widgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->widgets;
@@ -332,7 +327,7 @@ static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidge
#endif
return false;
}
-#endif // QT_NO_ACTION
+#endif // QT_CONFIG(action)
/*!
@@ -395,29 +390,62 @@ static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidge
Returns the shortcut's parent widget.
*/
-/*!
- \fn void QShortcut::activated()
+/*
+ \internal
+ Private data accessed through d-pointer.
+*/
+class QShortcutPrivate : public QGuiShortcutPrivate
+{
+ Q_DECLARE_PUBLIC(QShortcut)
+public:
+ QShortcutPrivate() = default;
- This signal is emitted when the user types the shortcut's key
- sequence.
+ QShortcutMap::ContextMatcher contextMatcher() const override
+ { return qWidgetShortcutContextMatcher; }
- \sa activatedAmbiguously()
-*/
+ bool handleWhatsThis() override;
-/*!
- \fn void QShortcut::activatedAmbiguously()
+ QString sc_whatsthis;
+};
- When a key sequence is being typed at the keyboard, it is said to
- be ambiguous as long as it matches the start of more than one
- shortcut.
+bool QShortcutPrivate::handleWhatsThis()
+{
+#if QT_CONFIG(whatsthis)
+ const bool result = QWhatsThis::inWhatsThisMode();
+ if (result)
+ QWhatsThis::showText(QCursor::pos(), sc_whatsthis);
+ return result;
+#else
+ return false;
+#endif
+}
- When a shortcut's key sequence is completed,
- activatedAmbiguously() is emitted if the key sequence is still
- ambiguous (i.e., it is the start of one or more other shortcuts).
- The activated() signal is not emitted in this case.
+/*!
+ Constructs a QShortcut object for the \a parent widget. Since no
+ shortcut key sequence is specified, the shortcut will not emit any
+ signals.
- \sa activated()
+ \sa setKey()
*/
+QShortcut::QShortcut(QWidget *parent)
+ : QGuiShortcut(*new QShortcutPrivate, parent)
+{
+}
+
+/*!
+ Constructs a QShortcut object for the \a parent widget. The shortcut
+ operates on its parent, listening for \l{QShortcutEvent}s that
+ match the \a key sequence. Depending on the ambiguity of the
+ event, the shortcut will call the \a member function, or the \a
+ ambiguousMember function, if the key press was in the shortcut's
+ \a shortcutContext.
+*/
+QShortcut::QShortcut(const QKeySequence &key, QWidget *parent,
+ const char *member, const char *ambiguousMember,
+ Qt::ShortcutContext shortcutContext)
+ : QGuiShortcut(*new QShortcutPrivate, key, parent, member, ambiguousMember, shortcutContext)
+{
+}
/*!
\fn template<typename Functor>
@@ -489,177 +517,6 @@ static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidge
will not be called.
*/
-/*
- \internal
- Private data accessed through d-pointer.
-*/
-class QShortcutPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QShortcut)
-public:
- QShortcutPrivate() = default;
- QKeySequence sc_sequence;
- Qt::ShortcutContext sc_context = Qt::WindowShortcut;
- bool sc_enabled = true;
- bool sc_autorepeat = true;
- int sc_id = 0;
- QString sc_whatsthis;
- void redoGrab(QShortcutMap &map);
-};
-
-void QShortcutPrivate::redoGrab(QShortcutMap &map)
-{
- Q_Q(QShortcut);
- if (Q_UNLIKELY(!parent)) {
- qWarning("QShortcut: No widget parent defined");
- return;
- }
-
- if (sc_id)
- map.removeShortcut(sc_id, q);
- if (sc_sequence.isEmpty())
- return;
- sc_id = map.addShortcut(q, sc_sequence, sc_context, qWidgetShortcutContextMatcher);
- if (!sc_enabled)
- map.setShortcutEnabled(false, sc_id, q);
- if (!sc_autorepeat)
- map.setShortcutAutoRepeat(false, sc_id, q);
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. Since no
- shortcut key sequence is specified, the shortcut will not emit any
- signals.
-
- \sa setKey()
-*/
-QShortcut::QShortcut(QWidget *parent)
- : QObject(*new QShortcutPrivate, parent)
-{
- Q_ASSERT(parent != nullptr);
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. The shortcut
- operates on its parent, listening for \l{QShortcutEvent}s that
- match the \a key sequence. Depending on the ambiguity of the
- event, the shortcut will call the \a member function, or the \a
- ambiguousMember function, if the key press was in the shortcut's
- \a shortcutContext.
-*/
-QShortcut::QShortcut(const QKeySequence &key, QWidget *parent,
- const char *member, const char *ambiguousMember,
- Qt::ShortcutContext shortcutContext)
- : QShortcut(parent)
-{
- QAPP_CHECK("QShortcut");
-
- Q_D(QShortcut);
- d->sc_context = shortcutContext;
- d->sc_sequence = key;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
- if (member)
- connect(this, SIGNAL(activated()), parent, member);
- if (ambiguousMember)
- connect(this, SIGNAL(activatedAmbiguously()), parent, ambiguousMember);
-}
-
-/*!
- Destroys the shortcut.
-*/
-QShortcut::~QShortcut()
-{
- Q_D(QShortcut);
- if (qApp)
- QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->sc_id, this);
-}
-
-/*!
- \property QShortcut::key
- \brief the shortcut's key sequence
-
- This is a key sequence with an optional combination of Shift, Ctrl,
- and Alt. The key sequence may be supplied in a number of ways:
-
- \snippet code/src_gui_kernel_qshortcut.cpp 1
-
- By default, this property contains an empty key sequence.
-*/
-void QShortcut::setKey(const QKeySequence &key)
-{
- Q_D(QShortcut);
- if (d->sc_sequence == key)
- return;
- QAPP_CHECK("setKey");
- d->sc_sequence = key;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
-}
-
-QKeySequence QShortcut::key() const
-{
- Q_D(const QShortcut);
- return d->sc_sequence;
-}
-
-/*!
- \property QShortcut::enabled
- \brief whether the shortcut is enabled
-
- An enabled shortcut emits the activated() or activatedAmbiguously()
- signal when a QShortcutEvent occurs that matches the shortcut's
- key() sequence.
-
- If the application is in \c WhatsThis mode the shortcut will not emit
- the signals, but will show the "What's This?" text instead.
-
- By default, this property is \c true.
-
- \sa whatsThis
-*/
-void QShortcut::setEnabled(bool enable)
-{
- Q_D(QShortcut);
- if (d->sc_enabled == enable)
- return;
- QAPP_CHECK("setEnabled");
- d->sc_enabled = enable;
- QGuiApplicationPrivate::instance()->shortcutMap.setShortcutEnabled(enable, d->sc_id, this);
-}
-
-bool QShortcut::isEnabled() const
-{
- Q_D(const QShortcut);
- return d->sc_enabled;
-}
-
-/*!
- \property QShortcut::context
- \brief the context in which the shortcut is valid
-
- A shortcut's context decides in which circumstances a shortcut is
- allowed to be triggered. The normal context is Qt::WindowShortcut,
- which allows the shortcut to trigger if the parent (the widget
- containing the shortcut) is a subwidget of the active top-level
- window.
-
- By default, this property is set to Qt::WindowShortcut.
-*/
-void QShortcut::setContext(Qt::ShortcutContext context)
-{
- Q_D(QShortcut);
- if(d->sc_context == context)
- return;
- QAPP_CHECK("setContext");
- d->sc_context = context;
- d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
-}
-
-Qt::ShortcutContext QShortcut::context() const
-{
- Q_D(const QShortcut);
- return d->sc_context;
-}
-
/*!
\property QShortcut::whatsThis
\brief the shortcut's "What's This?" help text
@@ -687,67 +544,8 @@ QString QShortcut::whatsThis() const
}
/*!
- \property QShortcut::autoRepeat
- \brief whether the shortcut can auto repeat
- \since 4.2
-
- If true, the shortcut will auto repeat when the keyboard shortcut
- combination is held down, provided that keyboard auto repeat is
- enabled on the system.
- The default value is true.
-*/
-void QShortcut::setAutoRepeat(bool on)
-{
- Q_D(QShortcut);
- if (d->sc_autorepeat == on)
- return;
- QAPP_CHECK("setAutoRepeat");
- d->sc_autorepeat = on;
- QGuiApplicationPrivate::instance()->shortcutMap.setShortcutAutoRepeat(on, d->sc_id, this);
-}
-
-bool QShortcut::autoRepeat() const
-{
- Q_D(const QShortcut);
- return d->sc_autorepeat;
-}
-
-/*!
- Returns the shortcut's ID.
-
- \sa QShortcutEvent::shortcutId()
-*/
-int QShortcut::id() const
-{
- Q_D(const QShortcut);
- return d->sc_id;
-}
-
-/*!
- \internal
+ Destroys the shortcut.
*/
-bool QShortcut::event(QEvent *e)
-{
- Q_D(QShortcut);
- if (d->sc_enabled && e->type() == QEvent::Shortcut) {
- auto se = static_cast<QShortcutEvent *>(e);
- if (se->shortcutId() == d->sc_id && se->key() == d->sc_sequence){
-#if QT_CONFIG(whatsthis)
- if (QWhatsThis::inWhatsThisMode()) {
- QWhatsThis::showText(QCursor::pos(), d->sc_whatsthis);
- } else
-#endif
- if (se->isAmbiguous())
- emit activatedAmbiguously();
- else
- emit activated();
- return true;
- }
- }
- return QObject::event(e);
-}
-#endif // QT_NO_SHORTCUT
+QShortcut::~QShortcut() = default;
QT_END_NAMESPACE
-
-#include "moc_qshortcut.cpp"
diff --git a/src/widgets/kernel/qshortcut.h b/src/widgets/kernel/qshortcut.h
index 4f9c5ba0f7..6c92f87c46 100644
--- a/src/widgets/kernel/qshortcut.h
+++ b/src/widgets/kernel/qshortcut.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -42,28 +42,23 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qwidget.h>
-#include <QtGui/qkeysequence.h>
-
-QT_BEGIN_NAMESPACE
+#include <QtGui/qguishortcut.h>
+QT_REQUIRE_CONFIG(shortcut);
-#ifndef QT_NO_SHORTCUT
+QT_BEGIN_NAMESPACE
class QShortcutPrivate;
-class Q_WIDGETS_EXPORT QShortcut : public QObject
+class Q_WIDGETS_EXPORT QShortcut : public QGuiShortcut
{
Q_OBJECT
- Q_DECLARE_PRIVATE(QShortcut)
- Q_PROPERTY(QKeySequence key READ key WRITE setKey)
Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
- Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat)
- Q_PROPERTY(Qt::ShortcutContext context READ context WRITE setContext)
+ Q_DECLARE_PRIVATE(QShortcut)
public:
explicit QShortcut(QWidget *parent);
- QShortcut(const QKeySequence &key, QWidget *parent,
- const char *member = nullptr, const char *ambiguousMember = nullptr,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
+ explicit QShortcut(const QKeySequence& key, QWidget *parent,
+ const char *member = nullptr, const char *ambiguousMember = nullptr,
+ Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
#ifdef Q_CLANG_QDOC
template<typename Functor>
QShortcut(const QKeySequence &key, QWidget *parent,
@@ -122,36 +117,13 @@ public:
#endif
~QShortcut();
- void setKey(const QKeySequence& key);
- QKeySequence key() const;
-
- void setEnabled(bool enable);
- bool isEnabled() const;
-
- void setContext(Qt::ShortcutContext context);
- Qt::ShortcutContext context() const;
-
void setWhatsThis(const QString &text);
QString whatsThis() const;
- void setAutoRepeat(bool on);
- bool autoRepeat() const;
-
- int id() const;
-
inline QWidget *parentWidget() const
{ return static_cast<QWidget *>(QObject::parent()); }
-
-Q_SIGNALS:
- void activated();
- void activatedAmbiguously();
-
-protected:
- bool event(QEvent *e) override;
};
-#endif // QT_NO_SHORTCUT
-
QT_END_NAMESPACE
#endif // QSHORTCUT_H
diff --git a/src/widgets/kernel/qt_widgets_pch.h b/src/widgets/kernel/qt_widgets_pch.h
index b70941950b..3551f19e80 100644
--- a/src/widgets/kernel/qt_widgets_pch.h
+++ b/src/widgets/kernel/qt_widgets_pch.h
@@ -53,7 +53,9 @@
#include <qabstractbutton.h>
#include <qabstractscrollarea.h>
#include <qabstractslider.h>
-#include <qaction.h>
+#if QT_CONFIG(action)
+# include <qaction.h>
+#endif
#include <qcommonstyle.h>
#include <qlayout.h>
#include <qstyle.h>
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 767a1d2a8a..2160e54b8f 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -88,7 +88,9 @@
#include "qwidget_p.h"
#include <QtGui/private/qwindow_p.h>
-#include "qaction_p.h"
+#if QT_CONFIG(action)
+# include "qaction_p.h"
+#endif
#include "qlayout_p.h"
#if QT_CONFIG(graphicsview)
#include "QtWidgets/qgraphicsproxywidget.h"
@@ -1513,13 +1515,8 @@ QWidget::~QWidget()
if (d->declarativeData) {
d->wasDeleted = true; // needed, so that destroying the declarative data does the right thing
- if (static_cast<QAbstractDeclarativeDataImpl*>(d->declarativeData)->ownedByQml1) {
- if (QAbstractDeclarativeData::destroyed_qml1)
- QAbstractDeclarativeData::destroyed_qml1(d->declarativeData, this);
- } else {
- if (QAbstractDeclarativeData::destroyed)
- QAbstractDeclarativeData::destroyed(d->declarativeData, this);
- }
+ if (QAbstractDeclarativeData::destroyed)
+ QAbstractDeclarativeData::destroyed(d->declarativeData, this);
d->declarativeData = nullptr; // don't activate again in ~QObject
d->wasDeleted = false;
}
@@ -1853,7 +1850,7 @@ void QWidgetPrivate::propagatePaletteChange()
if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
inheritedPaletteResolveMask = 0;
}
- int mask = data.pal.resolve() | inheritedPaletteResolveMask;
+ QPalette::ResolveMask mask = data.pal.resolve() | inheritedPaletteResolveMask;
const bool useStyleSheetPropagationInWidgetStyles =
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
@@ -4377,7 +4374,7 @@ void QWidget::setPalette(const QPalette &palette)
widget's palette are implicitly imposed on this widget by the user). Note
that this font does not take into account the palette set on \a w itself.
*/
-QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
+QPalette QWidgetPrivate::naturalWidgetPalette(QPalette::ResolveMask inheritedMask) const
{
Q_Q(const QWidget);
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index 415a738eb4..5117fa94c8 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -53,7 +53,9 @@
#include <QtGui/qregion.h>
#include <QtGui/qbrush.h>
#include <QtGui/qcursor.h>
-#include <QtGui/qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/qkeysequence.h>
+#endif
#ifdef QT_INCLUDE_COMPAT
#include <QtGui/qevent.h>
diff --git a/src/widgets/kernel/qwidget_p.h b/src/widgets/kernel/qwidget_p.h
index 6915782cb3..0d0077548c 100644
--- a/src/widgets/kernel/qwidget_p.h
+++ b/src/widgets/kernel/qwidget_p.h
@@ -299,7 +299,7 @@ public:
void setPalette_helper(const QPalette &);
void resolvePalette();
- QPalette naturalWidgetPalette(uint inheritedMask) const;
+ QPalette naturalWidgetPalette(QPalette::ResolveMask inheritedMask) const;
void setMask_sys(const QRegion &);
@@ -672,7 +672,7 @@ public:
// Other variables.
uint directFontResolveMask;
uint inheritedFontResolveMask;
- uint inheritedPaletteResolveMask;
+ QPalette::ResolveMask inheritedPaletteResolveMask;
short leftmargin;
short topmargin;
short rightmargin;
diff --git a/src/widgets/kernel/qwidgetaction.cpp b/src/widgets/kernel/qwidgetaction.cpp
index 9649e51b92..12250983f7 100644
--- a/src/widgets/kernel/qwidgetaction.cpp
+++ b/src/widgets/kernel/qwidgetaction.cpp
@@ -40,7 +40,6 @@
#include "qwidgetaction.h"
#include "qdebug.h"
-#ifndef QT_NO_ACTION
#include "qwidgetaction_p.h"
QT_BEGIN_NAMESPACE
@@ -282,5 +281,3 @@ QList<QWidget *> QWidgetAction::createdWidgets() const
QT_END_NAMESPACE
#include "moc_qwidgetaction.cpp"
-
-#endif // QT_NO_ACTION
diff --git a/src/widgets/kernel/qwidgetaction.h b/src/widgets/kernel/qwidgetaction.h
index 4769332a23..4d302e8c61 100644
--- a/src/widgets/kernel/qwidgetaction.h
+++ b/src/widgets/kernel/qwidgetaction.h
@@ -43,10 +43,9 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qaction.h>
-QT_BEGIN_NAMESPACE
-
+QT_REQUIRE_CONFIG(action);
-#ifndef QT_NO_ACTION
+QT_BEGIN_NAMESPACE
class QWidgetActionPrivate;
@@ -78,8 +77,6 @@ private:
friend class QToolBar;
};
-#endif // QT_NO_ACTION
-
QT_END_NAMESPACE
#endif // QWIDGETACTION_H
diff --git a/src/widgets/kernel/qwidgetaction_p.h b/src/widgets/kernel/qwidgetaction_p.h
index 1fbcf236a1..0e633a65e4 100644
--- a/src/widgets/kernel/qwidgetaction_p.h
+++ b/src/widgets/kernel/qwidgetaction_p.h
@@ -54,6 +54,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qaction_p.h"
+QT_REQUIRE_CONFIG(action);
+
QT_BEGIN_NAMESPACE
class QWidgetActionPrivate : public QActionPrivate
diff --git a/src/widgets/styles/qfusionstyle.cpp b/src/widgets/styles/qfusionstyle.cpp
index 8da21a2e11..c4bc52aa87 100644
--- a/src/widgets/styles/qfusionstyle.cpp
+++ b/src/widgets/styles/qfusionstyle.cpp
@@ -3191,7 +3191,7 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
break;
case CT_MenuItem:
if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- int w = newSize.width();
+ int w = size.width(); // Don't rely of QCommonStyle's width calculation here
int maxpmw = menuItem->maxIconWidth;
int tabSpacing = 20;
if (menuItem->text.contains(QLatin1Char('\t')))
diff --git a/src/widgets/styles/qstyle.cpp b/src/widgets/styles/qstyle.cpp
index d2f5ac76f9..e462d0696b 100644
--- a/src/widgets/styles/qstyle.cpp
+++ b/src/widgets/styles/qstyle.cpp
@@ -638,7 +638,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
indicator or button bevel.
\omitvalue PE_IndicatorViewItemCheck
- \value PE_FrameStatusBar Obsolete. Use PE_FrameStatusBarItem instead.
\value PE_PanelButtonCommand Button used to initiate an action, for
example, a QPushButton.
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index ee234457f5..b51bcbe8d6 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -142,9 +142,6 @@ public:
PE_FrameLineEdit,
PE_FrameMenu,
PE_FrameStatusBarItem,
-#if QT_DEPRECATED_SINCE(5, 13) // ### Qt 6: remove
- PE_FrameStatusBar Q_DECL_ENUMERATOR_DEPRECATED = PE_FrameStatusBarItem,
-#endif
PE_FrameTabWidget,
PE_FrameWindow,
PE_FrameButtonBevel,
@@ -165,9 +162,6 @@ public:
PE_IndicatorBranch,
PE_IndicatorButtonDropDown,
PE_IndicatorItemViewItemCheck,
-#if QT_DEPRECATED_SINCE(5, 13) // ### Qt 6: remove
- PE_IndicatorViewItemCheck Q_DECL_ENUMERATOR_DEPRECATED = PE_IndicatorItemViewItemCheck,
-#endif
PE_IndicatorCheckBox,
PE_IndicatorDockWidgetResizeHandle,
PE_IndicatorHeaderArrow,
diff --git a/src/widgets/styles/qstyleoption.cpp b/src/widgets/styles/qstyleoption.cpp
index aca4eec0e7..5a2ca2f2e7 100644
--- a/src/widgets/styles/qstyleoption.cpp
+++ b/src/widgets/styles/qstyleoption.cpp
@@ -1776,7 +1776,7 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
\value Exclusive The item is an exclusive check item (like a radio button).
\value NonExclusive The item is a non-exclusive check item (like a check box).
- \sa checkType, QAction::checkable, QAction::checked, QActionGroup::exclusionPolicy
+ \sa checkType, QGuiAction::checkable, QGuiAction::checked, QGuiActionGroup::exclusionPolicy
*/
/*!
diff --git a/src/widgets/styles/qstylesheetstyle_p.h b/src/widgets/styles/qstylesheetstyle_p.h
index c5266558af..81c532bf6a 100644
--- a/src/widgets/styles/qstylesheetstyle_p.h
+++ b/src/widgets/styles/qstylesheetstyle_p.h
@@ -194,7 +194,7 @@ public:
template <typename T>
struct Tampered {
T oldWidgetValue;
- uint resolveMask;
+ decltype(std::declval<T>().resolve()) resolveMask;
// only call this function on an rvalue *this (it mangles oldWidgetValue)
T reverted(T current)
diff --git a/src/widgets/util/qundostack.cpp b/src/widgets/util/qundostack.cpp
index f188b8298a..8974f11a13 100644
--- a/src/widgets/util/qundostack.cpp
+++ b/src/widgets/util/qundostack.cpp
@@ -443,7 +443,7 @@ const QUndoCommand *QUndoCommand::child(int index) const
\sa QUndoCommand, QUndoView
*/
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
QUndoAction::QUndoAction(const QString &prefix, QObject *parent)
: QAction(parent)
@@ -473,7 +473,7 @@ void QUndoAction::setTextFormat(const QString &textFormat, const QString &defaul
m_defaultText = defaultText;
}
-#endif // QT_NO_ACTION
+#endif // QT_CONFIG(action)
/*! \internal
Sets the current index to \a idx, emitting appropriate signals. If \a clean is true,
diff --git a/src/widgets/util/qundostack_p.h b/src/widgets/util/qundostack_p.h
index 05c9e0d27e..c44cdd6603 100644
--- a/src/widgets/util/qundostack_p.h
+++ b/src/widgets/util/qundostack_p.h
@@ -44,7 +44,9 @@
#include <private/qobject_p.h>
#include <QtCore/qlist.h>
#include <QtCore/qstring.h>
-#include <QtWidgets/qaction.h>
+#if QT_CONFIG(action)
+# include <QtWidgets/qaction.h>
+#endif
#include "qundostack.h"
diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp
index 022f41738c..29d28847f3 100644
--- a/src/widgets/widgets/qabstractbutton.cpp
+++ b/src/widgets/widgets/qabstractbutton.cpp
@@ -52,7 +52,6 @@
#include "qpainter.h"
#include "qapplication.h"
#include "qstyle.h"
-#include "qaction.h"
#ifndef QT_NO_ACCESSIBILITY
#include "qaccessible.h"
#endif
diff --git a/src/widgets/widgets/qabstractbutton.h b/src/widgets/widgets/qabstractbutton.h
index 50c94654f3..d44da2f4f3 100644
--- a/src/widgets/widgets/qabstractbutton.h
+++ b/src/widgets/widgets/qabstractbutton.h
@@ -42,7 +42,9 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtGui/qicon.h>
-#include <QtGui/qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <QtGui/qkeysequence.h>
+#endif
#include <QtWidgets/qwidget.h>
QT_REQUIRE_CONFIG(abstractbutton);
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index 4f89d7f542..1b80f90c74 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -170,7 +170,7 @@ public:
void setItemDelegate(QAbstractItemDelegate *delegate);
QAbstractItemModel *model() const;
- void setModel(QAbstractItemModel *model);
+ virtual void setModel(QAbstractItemModel *model);
QModelIndex rootModelIndex() const;
void setRootModelIndex(const QModelIndex &index);
diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp
index 5f415aca42..e4abb89636 100644
--- a/src/widgets/widgets/qdatetimeedit.cpp
+++ b/src/widgets/widgets/qdatetimeedit.cpp
@@ -53,6 +53,9 @@
#include <qlayout.h>
#include <qset.h>
#include <qstyle.h>
+#if QT_CONFIG(timezone)
+#include <QTimeZone>
+#endif
#include <algorithm>
@@ -218,8 +221,8 @@ QDateTimeEdit::~QDateTimeEdit()
\property QDateTimeEdit::dateTime
\brief The QDateTime that is set in the QDateTimeEdit.
- When setting this property the timespec of the QDateTimeEdit remains the same
- and the timespec of the new QDateTime is ignored.
+ When setting this property, the new QDateTime is converted to the timespec of
+ the QDateTimeEdit, which thus remains unchanged.
By default, this property is set to the start of 2000 CE. It can only be set
to a valid QDateTime value. If any operation causes this property to have an
@@ -243,11 +246,14 @@ void QDateTimeEdit::setDateTime(const QDateTime &datetime)
{
Q_D(QDateTimeEdit);
if (datetime.isValid()) {
+ QDateTime when = d->convertTimeSpec(datetime);
+ Q_ASSERT(when.timeSpec() == d->spec);
+
d->clearCache();
- const QDate date = datetime.date();
+ const QDate date = when.date();
if (!(d->sections & DateSections_Mask))
setDateRange(date, date);
- d->setValue(QDateTime(date, datetime.time(), d->spec), EmitIfChanged);
+ d->setValue(when, EmitIfChanged);
}
}
@@ -1706,6 +1712,25 @@ QDateTimeEditPrivate::QDateTimeEditPrivate()
#endif
}
+QDateTime QDateTimeEditPrivate::convertTimeSpec(const QDateTime &datetime)
+{
+ Q_ASSERT(value.toDateTime().timeSpec() == spec);
+ switch (spec) {
+ case Qt::UTC:
+ return datetime.toUTC();
+ case Qt::LocalTime:
+ return datetime.toLocalTime();
+ case Qt::OffsetFromUTC:
+ return datetime.toOffsetFromUtc(value.toDateTime().offsetFromUtc());
+#if QT_CONFIG(timezone)
+ case Qt::TimeZone:
+ return datetime.toTimeZone(value.toDateTime().timeZone());
+#endif
+ }
+ Q_UNREACHABLE();
+}
+
+// FIXME: architecturaly incompatible with OffsetFromUTC or TimeZone as spec (QTBUG-80417).
void QDateTimeEditPrivate::updateTimeSpec()
{
minimum = minimum.toDateTime().toTimeSpec(spec);
@@ -2337,33 +2362,6 @@ void QDateTimeEdit::paintEvent(QPaintEvent *event)
style()->drawComplexControl(QStyle::CC_ComboBox, &optCombo, &p, this);
}
-/*
- Returns the string for AM and PM markers.
-
- If a translation for "AM" and "PM" is installed, then use that.
- Otherwise, use the default implementation, which uses the locale.
-*/
-QString QDateTimeEditPrivate::getAmPmText(AmPm ap, Case cs) const
-{
- QString original;
- QString translated;
- if (ap == AmText) {
- original = QLatin1String(cs == UpperCase ? "AM" : "am");
- translated = (cs == UpperCase ? QDateTimeParser::tr("AM") : QDateTimeParser::tr("am"));
- } else {
- original = QLatin1String(cs == UpperCase ? "PM" : "pm");
- translated = (cs == UpperCase ? QDateTimeParser::tr("PM") : QDateTimeParser::tr("pm"));
- }
-
- // This logic fails if a translation exists but doesn't change the string,
- // which we can accept as a corner-case for which a locale-derived answer
- // will be acceptable.
- if (original != translated)
- return translated;
-
- return QDateTimeParser::getAmPmText(ap, cs);
-}
-
int QDateTimeEditPrivate::absoluteIndex(QDateTimeEdit::Section s, int index) const
{
for (int i=0; i<sectionNodes.size(); ++i) {
diff --git a/src/widgets/widgets/qdatetimeedit_p.h b/src/widgets/widgets/qdatetimeedit_p.h
index dcf8863c8b..0a4433846f 100644
--- a/src/widgets/widgets/qdatetimeedit_p.h
+++ b/src/widgets/widgets/qdatetimeedit_p.h
@@ -97,7 +97,6 @@ public:
QDateTime getMinimum() const override { return minimum.toDateTime(); }
QDateTime getMaximum() const override { return maximum.toDateTime(); }
QLocale locale() const override { return q_func()->locale(); }
- QString getAmPmText(AmPm ap, Case cs) const override;
int cursorPosition() const override { return edit ? edit->cursorPosition() : -1; }
int absoluteIndex(QDateTimeEdit::Section s, int index) const;
@@ -110,6 +109,7 @@ public:
void updateCache(const QVariant &val, const QString &str) const;
+ QDateTime convertTimeSpec(const QDateTime &datetime);
void updateTimeSpec();
QString valueToText(const QVariant &var) const { return textFromValue(var); }
diff --git a/src/widgets/widgets/qlabel.cpp b/src/widgets/widgets/qlabel.cpp
index 77d117775a..7bd7283adf 100644
--- a/src/widgets/widgets/qlabel.cpp
+++ b/src/widgets/widgets/qlabel.cpp
@@ -47,7 +47,6 @@
#include "qstyle.h"
#include "qstyleoption.h"
#include <limits.h>
-#include "qaction.h"
#include "qclipboard.h"
#include <qdebug.h>
#include <qurl.h>
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index 19a95be0ff..bd5e0b047e 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -40,7 +40,9 @@
#include "qlineedit.h"
#include "qlineedit_p.h"
-#include "qaction.h"
+#if QT_CONFIG(action)
+# include "qaction.h"
+#endif
#include "qapplication.h"
#include "qclipboard.h"
#if QT_CONFIG(draganddrop)
@@ -78,7 +80,7 @@
#endif
#include "private/qstylesheetstyle_p.h"
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
#include "private/qapplication_p.h"
#include "private/qshortcutmap_p.h"
#include "qkeysequence.h"
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index feb34ef403..29e0ae3b39 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -47,7 +47,9 @@
#if QT_CONFIG(draganddrop)
#include "qdrag.h"
#endif
-#include "qwidgetaction.h"
+#if QT_CONFIG(action)
+# include "qwidgetaction.h"
+#endif
#include "qclipboard.h"
#ifndef QT_NO_ACCESSIBILITY
#include "qaccessible.h"
@@ -370,7 +372,7 @@ void QLineEditIconButton::actionEvent(QActionEvent *e)
{
switch (e->type()) {
case QEvent::ActionChanged: {
- const QAction *action = e->action();
+ const auto *action = e->action();
if (isVisibleTo(parentWidget()) != action->isVisible()) {
setVisible(action->isVisible());
if (QLineEditPrivate *lep = lineEditPrivate())
@@ -545,7 +547,8 @@ void QLineEditPrivate::positionSideWidgets()
}
}
-QLineEditPrivate::SideWidgetLocation QLineEditPrivate::findSideWidget(const QAction *a) const
+#if QT_CONFIG(action)
+QLineEditPrivate::SideWidgetLocation QLineEditPrivate::findSideWidget(const QGuiAction *a) const
{
int i = 0;
for (const auto &e : leadingSideWidgets) {
@@ -574,12 +577,10 @@ QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineE
QWidget *w = nullptr;
// Store flags about QWidgetAction here since removeAction() may be called from ~QAction,
// in which a qobject_cast<> no longer works.
-#if QT_CONFIG(action)
if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(newAction)) {
if ((w = widgetAction->requestWidget(q)))
flags |= SideWidgetCreatedByWidgetAction;
}
-#endif
if (!w) {
#if QT_CONFIG(toolbutton)
QLineEditIconButton *toolButton = new QLineEditIconButton(q);
@@ -634,9 +635,8 @@ QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineE
return w;
}
-void QLineEditPrivate::removeAction(QAction *action)
+void QLineEditPrivate::removeAction(QGuiAction *action)
{
-#if QT_CONFIG(action)
Q_Q(QLineEdit);
const auto location = findSideWidget(action);
if (!location.isValid())
@@ -652,10 +652,8 @@ void QLineEditPrivate::removeAction(QAction *action)
if (!hasSideWidgets()) // Last widget, remove connection
QObject::disconnect(q, SIGNAL(textChanged(QString)), q, SLOT(_q_textChanged(QString)));
q->update();
-#else
- Q_UNUSED(action);
-#endif // QT_CONFIG(action)
}
+#endif // QT_CONFIG(action)
static int effectiveTextMargin(int defaultMargin, const QLineEditPrivate::SideWidgetEntryList &widgets,
const QLineEditPrivate::SideWidgetParameters &parameters)
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 5ae402b992..9fe571b4bb 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -238,8 +238,10 @@ public:
QString placeholderText;
+#if QT_CONFIG(action)
QWidget *addAction(QAction *newAction, QAction *before, QLineEdit::ActionPosition, int flags = 0);
- void removeAction(QAction *action);
+ void removeAction(QGuiAction *action);
+#endif
SideWidgetParameters sideWidgetParameters() const;
QIcon clearButtonIcon() const;
void setClearButtonEnabled(bool enabled);
@@ -261,7 +263,9 @@ private:
};
friend class QTypeInfo<SideWidgetLocation>;
- SideWidgetLocation findSideWidget(const QAction *a) const;
+#if QT_CONFIG(action)
+ SideWidgetLocation findSideWidget(const QGuiAction *a) const;
+#endif
SideWidgetEntryList leadingSideWidgets;
SideWidgetEntryList trailingSideWidgets;
diff --git a/src/widgets/widgets/qmdisubwindow.cpp b/src/widgets/widgets/qmdisubwindow.cpp
index 84568c35db..f8460a4718 100644
--- a/src/widgets/widgets/qmdisubwindow.cpp
+++ b/src/widgets/widgets/qmdisubwindow.cpp
@@ -162,7 +162,9 @@
#include <QDebug>
#include <QMdiArea>
#include <QScopedValueRollback>
-#include <QAction>
+#if QT_CONFIG(action)
+# include <qaction.h>
+#endif
#if QT_CONFIG(menu)
#include <QMenu>
#endif
@@ -895,7 +897,7 @@ QMdiSubWindowPrivate::QMdiSubWindowPrivate()
*/
void QMdiSubWindowPrivate::_q_updateStaysOnTopHint()
{
-#ifndef QT_NO_ACTION
+#if QT_CONFIG(action)
Q_Q(QMdiSubWindow);
if (QAction *senderAction = qobject_cast<QAction *>(q->sender())) {
if (senderAction->isChecked()) {
@@ -906,7 +908,7 @@ void QMdiSubWindowPrivate::_q_updateStaysOnTopHint()
q->lower();
}
}
-#endif // QT_NO_ACTION
+#endif // QT_CONFIG(action)
}
/*!
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index 8ba5b98fa9..fc7e2dbbcb 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -157,10 +157,11 @@ public:
Q_D(QTornOffMenu);
if(menu != d->causedMenu)
return;
+ auto action = static_cast<QAction *>(act->action());
if (act->type() == QEvent::ActionAdded) {
- insertAction(act->before(), act->action());
+ insertAction(static_cast<QAction *>(act->before()), action);
} else if (act->type() == QEvent::ActionRemoved)
- removeAction(act->action());
+ removeAction(action);
}
void actionEvent(QActionEvent *e) override
{
@@ -403,7 +404,9 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
//calculate size
QFontMetrics qfm = q->fontMetrics();
bool previousWasSeparator = true; // this is true to allow removing the leading separators
+#if QT_CONFIG(shortcut)
const bool contextMenu = isContextMenu();
+#endif
for(int i = 0; i <= lastVisibleAction; i++) {
QAction *action = actions.at(i);
const bool isSection = action->isSeparator() && (!action->text().isEmpty() || !action->icon().isNull());
@@ -434,12 +437,12 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
if (t != -1) {
tabWidth = qMax(int(tabWidth), qfm.horizontalAdvance(s.mid(t+1)));
s = s.left(t);
- #ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
} else if (action->isShortcutVisibleInContextMenu() || !contextMenu) {
QKeySequence seq = action->shortcut();
if (!seq.isEmpty())
tabWidth = qMax(int(tabWidth), qfm.horizontalAdvance(seq.toString(QKeySequence::NativeText)));
- #endif
+#endif
}
sz.setWidth(fm.boundingRect(QRect(), Qt::TextSingleLine | Qt::TextShowMnemonic, s).width());
sz.setHeight(qMax(fm.height(), qfm.height()));
@@ -1769,12 +1772,14 @@ QAction *QMenu::addAction(const QIcon &icon, const QString &text)
\sa QWidget::addAction()
*/
-QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut)
+QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut
+#endif
+ )
{
QAction *action = new QAction(text, this);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut);
-#else
+#if QT_CONFIG(shortcut)
action->setShortcut(shortcut);
#endif
QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
@@ -1862,12 +1867,14 @@ QAction *QMenu::addAction(const QString &text, const QObject *receiver, const ch
\sa QWidget::addAction()
*/
QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver,
- const char* member, const QKeySequence &shortcut)
+ const char* member
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut
+#endif
+ )
{
QAction *action = new QAction(icon, text, this);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut);
-#else
+#if QT_CONFIG(shortcut)
action->setShortcut(shortcut);
#endif
QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
@@ -3543,15 +3550,16 @@ void QMenu::actionEvent(QActionEvent *e)
wa->releaseWidget(widget);
}
}
- d->widgetItems.remove(e->action());
+ d->widgetItems.remove(static_cast<QAction *>(e->action()));
}
if (!d->platformMenu.isNull()) {
+ auto action = static_cast<QAction *>(e->action());
if (e->type() == QEvent::ActionAdded) {
QPlatformMenuItem *beforeItem = e->before()
? d->platformMenu->menuItemForTag(reinterpret_cast<quintptr>(e->before()))
: nullptr;
- d->insertActionInPlatformMenu(e->action(), beforeItem);
+ d->insertActionInPlatformMenu(action, beforeItem);
} else if (e->type() == QEvent::ActionRemoved) {
QPlatformMenuItem *menuItem = d->platformMenu->menuItemForTag(reinterpret_cast<quintptr>(e->action()));
d->platformMenu->removeMenuItem(menuItem);
@@ -3559,7 +3567,7 @@ void QMenu::actionEvent(QActionEvent *e)
} else if (e->type() == QEvent::ActionChanged) {
QPlatformMenuItem *menuItem = d->platformMenu->menuItemForTag(reinterpret_cast<quintptr>(e->action()));
if (menuItem) {
- d->copyActionToPlatformItem(e->action(), menuItem);
+ d->copyActionToPlatformItem(action, menuItem);
d->platformMenu->syncMenuItem(menuItem);
}
}
diff --git a/src/widgets/widgets/qmenu.h b/src/widgets/widgets/qmenu.h
index 84ab9e027a..35d5a865ff 100644
--- a/src/widgets/widgets/qmenu.h
+++ b/src/widgets/widgets/qmenu.h
@@ -78,8 +78,17 @@ public:
using QWidget::addAction;
QAction *addAction(const QString &text);
QAction *addAction(const QIcon &icon, const QString &text);
- QAction *addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut = 0);
- QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut = 0);
+
+ QAction *addAction(const QString &text, const QObject *receiver, const char* member
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ );
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ );
#ifdef Q_CLANG_QDOC
template<typename Functor>
@@ -95,12 +104,14 @@ public:
template<class Obj, typename Func1>
inline typename std::enable_if<!std::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)
+ addAction(const QString &text, const Obj *object, Func1 slot
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ )
{
QAction *result = addAction(text);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut)
-#else
+#if QT_CONFIG(shortcut)
result->setShortcut(shortcut);
#endif
connect(result, &QAction::triggered, object, std::move(slot));
@@ -108,12 +119,14 @@ public:
}
// 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)
+ inline QAction *addAction(const QString &text, Func1 slot
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ )
{
QAction *result = addAction(text);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut)
-#else
+#if QT_CONFIG(shortcut)
result->setShortcut(shortcut);
#endif
connect(result, &QAction::triggered, std::move(slot));
@@ -123,12 +136,15 @@ public:
template<class Obj, typename Func1>
inline typename std::enable_if<!std::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)
+ addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ )
+
{
QAction *result = addAction(actionIcon, text);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut)
-#else
+#if QT_CONFIG(shortcut)
result->setShortcut(shortcut);
#endif
connect(result, &QAction::triggered, object, std::move(slot));
@@ -136,12 +152,14 @@ public:
}
// 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)
+ inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot
+#if QT_CONFIG(shortcut)
+ , const QKeySequence &shortcut = {}
+#endif
+ )
{
QAction *result = addAction(actionIcon, text);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut)
-#else
+#if QT_CONFIG(shortcut)
result->setShortcut(shortcut);
#endif
connect(result, &QAction::triggered, std::move(slot));
diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp
index ccd91ebee1..59c8af30b4 100644
--- a/src/widgets/widgets/qmenubar.cpp
+++ b/src/widgets/widgets/qmenubar.cpp
@@ -1289,21 +1289,22 @@ void QMenuBar::actionEvent(QActionEvent *e)
if (!nativeMenuBar)
return;
+ auto action = static_cast<QAction *>(e->action());
if (e->type() == QEvent::ActionAdded) {
- QPlatformMenu *menu = d->getPlatformMenu(e->action());
+ QPlatformMenu *menu = d->getPlatformMenu(action);
if (menu) {
- d->copyActionToPlatformMenu(e->action(), menu);
+ d->copyActionToPlatformMenu(action, menu);
- QPlatformMenu *beforeMenu = d->findInsertionPlatformMenu(e->action());
+ QPlatformMenu *beforeMenu = d->findInsertionPlatformMenu(action);
d->platformMenuBar->insertMenu(menu, beforeMenu);
}
} else if (e->type() == QEvent::ActionRemoved) {
- QPlatformMenu *menu = d->getPlatformMenu(e->action());
+ QPlatformMenu *menu = d->getPlatformMenu(action);
if (menu)
d->platformMenuBar->removeMenu(menu);
} else if (e->type() == QEvent::ActionChanged) {
QPlatformMenu *cur = d->platformMenuBar->menuForTag(reinterpret_cast<quintptr>(e->action()));
- QPlatformMenu *menu = d->getPlatformMenu(e->action());
+ QPlatformMenu *menu = d->getPlatformMenu(action);
// the menu associated with the action can change, need to
// remove and/or insert the new platform menu
@@ -1311,13 +1312,13 @@ void QMenuBar::actionEvent(QActionEvent *e)
if (cur)
d->platformMenuBar->removeMenu(cur);
if (menu) {
- d->copyActionToPlatformMenu(e->action(), menu);
+ d->copyActionToPlatformMenu(action, menu);
- QPlatformMenu *beforeMenu = d->findInsertionPlatformMenu(e->action());
+ QPlatformMenu *beforeMenu = d->findInsertionPlatformMenu(action);
d->platformMenuBar->insertMenu(menu, beforeMenu);
}
} else if (menu) {
- d->copyActionToPlatformMenu(e->action(), menu);
+ d->copyActionToPlatformMenu(action, menu);
d->platformMenuBar->syncMenu(menu);
}
}
diff --git a/src/widgets/widgets/qsplitter.h b/src/widgets/widgets/qsplitter.h
index ec980d9ee3..658914ae39 100644
--- a/src/widgets/widgets/qsplitter.h
+++ b/src/widgets/widgets/qsplitter.h
@@ -50,7 +50,6 @@ QT_BEGIN_NAMESPACE
class QSplitterPrivate;
class QTextStream;
-template <typename T> class QList;
class QSplitterHandle;
diff --git a/src/widgets/widgets/qtoolbar.cpp b/src/widgets/widgets/qtoolbar.cpp
index b4e90c7d71..f35c02f2fb 100644
--- a/src/widgets/widgets/qtoolbar.cpp
+++ b/src/widgets/widgets/qtoolbar.cpp
@@ -961,7 +961,7 @@ QAction *QToolBar::actionAt(const QPoint &p) const
void QToolBar::actionEvent(QActionEvent *event)
{
Q_D(QToolBar);
- QAction *action = event->action();
+ auto action = static_cast<QAction *>(event->action());
QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(action);
switch (event->type()) {
diff --git a/src/widgets/widgets/qtoolbarlayout.cpp b/src/widgets/widgets/qtoolbarlayout.cpp
index d77ba3c13e..93aded6876 100644
--- a/src/widgets/widgets/qtoolbarlayout.cpp
+++ b/src/widgets/widgets/qtoolbarlayout.cpp
@@ -207,7 +207,7 @@ void QToolBarLayout::insertAction(int index, QAction *action)
}
}
-int QToolBarLayout::indexOf(QAction *action) const
+int QToolBarLayout::indexOf(const QGuiAction *action) const
{
for (int i = 0; i < items.count(); ++i) {
if (items.at(i)->action == action)
diff --git a/src/widgets/widgets/qtoolbarlayout_p.h b/src/widgets/widgets/qtoolbarlayout_p.h
index b5dc121b93..1a406a3d29 100644
--- a/src/widgets/widgets/qtoolbarlayout_p.h
+++ b/src/widgets/widgets/qtoolbarlayout_p.h
@@ -96,7 +96,7 @@ public:
QSize sizeHint() const override;
void insertAction(int index, QAction *action);
- int indexOf(QAction *action) const;
+ int indexOf(const QGuiAction *action) const;
using QLayout::indexOf; // bring back the hidden members
bool layoutActions(const QSize &size);
diff --git a/src/widgets/widgets/qtoolbutton.cpp b/src/widgets/widgets/qtoolbutton.cpp
index 263fe5d8ce..127960b23c 100644
--- a/src/widgets/widgets/qtoolbutton.cpp
+++ b/src/widgets/widgets/qtoolbutton.cpp
@@ -466,7 +466,7 @@ void QToolButton::paintEvent(QPaintEvent *)
void QToolButton::actionEvent(QActionEvent *event)
{
Q_D(QToolButton);
- QAction *action = event->action();
+ auto action = static_cast<QAction *>(event->action());
switch (event->type()) {
case QEvent::ActionChanged:
if (action == d->defaultAction)
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index bb28db7fac..49a1a02867 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -92,7 +92,7 @@
#include <QtGui/qaccessible.h>
#include <QtCore/qmetaobject.h>
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
#include "private/qapplication_p.h"
#include "private/qshortcutmap_p.h"
#include <qkeysequence.h>
diff --git a/src/xml/dom/qdom.cpp b/src/xml/dom/qdom.cpp
index bbc877eead..90e97f512c 100644
--- a/src/xml/dom/qdom.cpp
+++ b/src/xml/dom/qdom.cpp
@@ -4474,7 +4474,7 @@ bool QDomElement::hasAttribute(const QString& name) const
\sa setAttributeNS(), attributeNodeNS(), setAttributeNodeNS(), attribute()
*/
-QString QDomElement::attributeNS(const QString nsURI, const QString& localName, const QString& defValue) const
+QString QDomElement::attributeNS(const QString& nsURI, const QString& localName, const QString& defValue) const
{
if (!impl)
return defValue;
@@ -4493,7 +4493,7 @@ QString QDomElement::attributeNS(const QString nsURI, const QString& localName,
\sa attributeNS(), setAttributeNodeNS(), setAttribute()
*/
-void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, const QString& value)
+void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, const QString& value)
{
if (!impl)
return;
@@ -4501,13 +4501,13 @@ void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, cons
}
/*!
- \fn void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, int value)
+ \fn void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, int value)
\overload
*/
/*!
- \fn void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, uint value)
+ \fn void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, uint value)
\overload
*/
@@ -4515,7 +4515,7 @@ void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, cons
/*!
\overload
*/
-void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, qlonglong value)
+void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, qlonglong value)
{
if (!impl)
return;
@@ -4527,7 +4527,7 @@ void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, qlon
/*!
\overload
*/
-void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, qulonglong value)
+void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, qulonglong value)
{
if (!impl)
return;
@@ -4539,7 +4539,7 @@ void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, qulo
/*!
\overload
*/
-void QDomElement::setAttributeNS(const QString nsURI, const QString& qName, double value)
+void QDomElement::setAttributeNS(const QString& nsURI, const QString& qName, double value)
{
if (!impl)
return;
diff --git a/src/xml/dom/qdom.h b/src/xml/dom/qdom.h
index d50c5e8394..9f34290121 100644
--- a/src/xml/dom/qdom.h
+++ b/src/xml/dom/qdom.h
@@ -508,15 +508,15 @@ public:
QDomNodeList elementsByTagName(const QString& tagname) const;
bool hasAttribute(const QString& name) const;
- QString attributeNS(const QString nsURI, const QString& localName, const QString& defValue = QString()) const;
- void setAttributeNS(const QString nsURI, const QString& qName, const QString& value);
- inline void setAttributeNS(const QString nsURI, const QString& qName, int value)
+ QString attributeNS(const QString& nsURI, const QString& localName, const QString& defValue = QString()) const;
+ void setAttributeNS(const QString& nsURI, const QString& qName, const QString& value);
+ inline void setAttributeNS(const QString& nsURI, const QString& qName, int value)
{ setAttributeNS(nsURI, qName, qlonglong(value)); }
- inline void setAttributeNS(const QString nsURI, const QString& qName, uint value)
+ inline void setAttributeNS(const QString& nsURI, const QString& qName, uint value)
{ setAttributeNS(nsURI, qName, qulonglong(value)); }
- void setAttributeNS(const QString nsURI, const QString& qName, qlonglong value);
- void setAttributeNS(const QString nsURI, const QString& qName, qulonglong value);
- void setAttributeNS(const QString nsURI, const QString& qName, double value);
+ void setAttributeNS(const QString& nsURI, const QString& qName, qlonglong value);
+ void setAttributeNS(const QString& nsURI, const QString& qName, qulonglong value);
+ void setAttributeNS(const QString& nsURI, const QString& qName, double value);
void removeAttributeNS(const QString& nsURI, const QString& localName);
QDomAttr attributeNodeNS(const QString& nsURI, const QString& localName);
QDomAttr setAttributeNodeNS(const QDomAttr& newAttr);
diff --git a/sync.profile b/sync.profile
index 0292bf0dc2..6371530814 100644
--- a/sync.profile
+++ b/sync.profile
@@ -29,6 +29,7 @@
"QtKmsSupport" => "$basedir/src/platformsupport/kmsconvenience",
"QtEdidSupport" => "$basedir/src/platformsupport/edid",
"QtVulkanSupport" => "$basedir/src/platformsupport/vkconvenience",
+ "QtLinuxOfonoSupport" => "$basedir/src/platformsupport/linuxofono",
"QtPlatformHeaders" => "$basedir/src/platformheaders",
"QtANGLE/KHR" => "!$basedir/src/3rdparty/angle/include/KHR",
"QtANGLE/GLES2" => "!$basedir/src/3rdparty/angle/include/GLES2",
@@ -52,6 +53,7 @@
"qconfig.h" => "QtConfig",
"qplugin.h" => "QtPlugin",
"qalgorithms.h" => "QtAlgorithms",
+ "qlist.h" => "QList",
"qcontainerfwd.h" => "QtContainerFwd",
"qdebug.h" => "QtDebug",
"qevent.h" => "QtEvents",
diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro
index 9eb741edac..c9d1da8649 100644
--- a/tests/auto/auto.pro
+++ b/tests/auto/auto.pro
@@ -1,5 +1,9 @@
TEMPLATE = subdirs
+# Tests with developer-build started failing on qemu-armv7/armv8 after commit
+# b88acae7a8e773c307e44f84da037d01d19e60f7 in qt5.
+boot2qt:qtConfig(private_tests): return()
+
SUBDIRS += \
corelib \
dbus \
diff --git a/tests/auto/concurrent/qtconcurrentfilter/qtconcurrentfilter.pro b/tests/auto/concurrent/qtconcurrentfilter/qtconcurrentfilter.pro
index 15345d40db..b372923310 100644
--- a/tests/auto/concurrent/qtconcurrentfilter/qtconcurrentfilter.pro
+++ b/tests/auto/concurrent/qtconcurrentfilter/qtconcurrentfilter.pro
@@ -2,5 +2,4 @@ CONFIG += testcase
TARGET = tst_qtconcurrentfilter
QT = core testlib concurrent
SOURCES = tst_qtconcurrentfilter.cpp
-DEFINES += QT_STRICT_ITERATORS
DEFINES -= QT_NO_LINKED_LIST
diff --git a/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp b/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
index 84ebd46886..8c4e1c16f3 100644
--- a/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
+++ b/tests/auto/concurrent/qtconcurrentfilter/tst_qtconcurrentfilter.cpp
@@ -714,16 +714,17 @@ void tst_QtConcurrentFilter::filteredReduced()
QCOMPARE(sum, 6);
}
+ auto push_back = static_cast<void (QVector<int>::*)(const int &)>(&QVector<int>::push_back);
// functor-member
{
- QList<int> list2 = QtConcurrent::filteredReduced(list, KeepEvenIntegers(), &QList<int>::push_back, QtConcurrent::OrderedReduce);
+ QList<int> list2 = QtConcurrent::filteredReduced(list, KeepEvenIntegers(), push_back, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
QList<int> list2 = QtConcurrent::filteredReduced(list.begin(),
list.end(),
KeepEvenIntegers(),
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
@@ -731,19 +732,19 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<int> list2 = QtConcurrent::filteredReduced(list.constBegin(),
list.constEnd(),
KeepEvenIntegers(),
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
- QList<int> list2 = QtConcurrent::blockingFilteredReduced(list, KeepEvenIntegers(), &QList<int>::push_back, QtConcurrent::OrderedReduce);
+ QList<int> list2 = QtConcurrent::blockingFilteredReduced(list, KeepEvenIntegers(), push_back, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
QList<int> list2 = QtConcurrent::blockingFilteredReduced(list.begin(),
list.end(),
KeepEvenIntegers(),
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
@@ -751,7 +752,7 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<int> list2 = QtConcurrent::blockingFilteredReduced(list.constBegin(),
list.constEnd(),
KeepEvenIntegers(),
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
@@ -805,12 +806,15 @@ void tst_QtConcurrentFilter::filteredReduced()
}
// member-member
+
+ auto push_back_number = static_cast<void (QVector<Number>::*)(const Number &)>(&QVector<Number>::push_back);
+
{
QList<Number> numbers;
numbers << 1 << 2 << 3 << 4;
QList<Number> list2 = QtConcurrent::filteredReduced(numbers,
&Number::isEven,
- &QList<Number>::push_back, QtConcurrent::OrderedReduce);
+ push_back_number, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
{
@@ -819,7 +823,7 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<Number> list2 = QtConcurrent::filteredReduced(numbers.begin(),
numbers.end(),
&Number::isEven,
- &QList<Number>::push_back,
+ push_back_number,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
@@ -829,7 +833,7 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<Number> list2 = QtConcurrent::filteredReduced(numbers.constBegin(),
numbers.constEnd(),
&Number::isEven,
- &QList<Number>::push_back,
+ push_back_number,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
@@ -838,7 +842,7 @@ void tst_QtConcurrentFilter::filteredReduced()
numbers << 1 << 2 << 3 << 4;
QList<Number> list2 = QtConcurrent::blockingFilteredReduced(numbers,
&Number::isEven,
- &QList<Number>::push_back, QtConcurrent::OrderedReduce);
+ push_back_number, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
{
@@ -847,7 +851,7 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<Number> list2 = QtConcurrent::blockingFilteredReduced(numbers.begin(),
numbers.end(),
&Number::isEven,
- &QList<Number>::push_back,
+ push_back_number,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
@@ -857,21 +861,21 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<Number> list2 = QtConcurrent::blockingFilteredReduced(numbers.constBegin(),
numbers.constEnd(),
&Number::isEven,
- &QList<Number>::push_back,
+ push_back_number,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<Number>() << 2 << 4);
}
// function-member
{
- QList<int> list2 = QtConcurrent::filteredReduced(list, keepEvenIntegers, &QList<int>::push_back, QtConcurrent::OrderedReduce);
+ QList<int> list2 = QtConcurrent::filteredReduced(list, keepEvenIntegers, push_back, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
QList<int> list2 = QtConcurrent::filteredReduced(list.begin(),
list.end(),
keepEvenIntegers,
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
@@ -879,19 +883,19 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<int> list2 = QtConcurrent::filteredReduced(list.constBegin(),
list.constEnd(),
keepEvenIntegers,
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
- QList<int> list2 = QtConcurrent::blockingFilteredReduced(list, keepEvenIntegers, &QList<int>::push_back, QtConcurrent::OrderedReduce);
+ QList<int> list2 = QtConcurrent::blockingFilteredReduced(list, keepEvenIntegers, push_back, QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
{
QList<int> list2 = QtConcurrent::blockingFilteredReduced(list.begin(),
list.end(),
keepEvenIntegers,
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
@@ -899,7 +903,7 @@ void tst_QtConcurrentFilter::filteredReduced()
QList<int> list2 = QtConcurrent::blockingFilteredReduced(list.constBegin(),
list.constEnd(),
keepEvenIntegers,
- &QList<int>::push_back,
+ push_back,
QtConcurrent::OrderedReduce);
QCOMPARE(list2, QList<int>() << 2 << 4);
}
diff --git a/tests/auto/concurrent/qtconcurrentmap/qtconcurrentmap.pro b/tests/auto/concurrent/qtconcurrentmap/qtconcurrentmap.pro
index 717d103e44..170881177d 100644
--- a/tests/auto/concurrent/qtconcurrentmap/qtconcurrentmap.pro
+++ b/tests/auto/concurrent/qtconcurrentmap/qtconcurrentmap.pro
@@ -2,7 +2,6 @@ CONFIG += testcase
TARGET = tst_qtconcurrentmap
QT = core testlib concurrent
SOURCES = tst_qtconcurrentmap.cpp
-DEFINES += QT_STRICT_ITERATORS
DEFINES -= QT_NO_LINKED_LIST
# Force C++17 if available
diff --git a/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp b/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
index 383de0b2ce..d9cbae1ac2 100644
--- a/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
+++ b/tests/auto/concurrent/qtconcurrentmap/tst_qtconcurrentmap.cpp
@@ -1381,11 +1381,13 @@ void tst_QtConcurrentMap::mappedReduced()
QCOMPARE(sum3, 14);
}
+ auto push_back = static_cast<void (QVector<int>::*)(const int &)>(&QVector<int>::push_back);
+
// functor-member
{
QList<int> list2 = QtConcurrent::mappedReduced(list,
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list2, QList<int>() << 1 << 4 << 9);
@@ -1393,14 +1395,14 @@ void tst_QtConcurrentMap::mappedReduced()
QList<int> list3 = QtConcurrent::mappedReduced(list.constBegin(),
list.constEnd(),
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list3, QList<int>() << 1 << 4 << 9);
QList<int> list4 = QtConcurrent::mappedReduced(QList<int>(list),
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list4, QList<int>() << 1 << 4 << 9);
@@ -1463,20 +1465,20 @@ void tst_QtConcurrentMap::mappedReduced()
{
QList<int> list2 = QtConcurrent::mappedReduced(numberList,
&Number::toInt,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list2, QList<int>() << 1 << 2 << 3);
QList<int> list3 = QtConcurrent::mappedReduced(numberList.constBegin(),
numberList.constEnd(),
&Number::toInt,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list3, QList<int>() << 1 << 2 << 3);
QList<int> list4 = QtConcurrent::mappedReduced(QList<Number>(numberList),
&Number::toInt,
- &QList<int>::push_back, OrderedReduce);
+ push_back, OrderedReduce);
QCOMPARE(list4, QList<int>() << 1 << 2 << 3);
}
{
@@ -1503,7 +1505,7 @@ void tst_QtConcurrentMap::mappedReduced()
{
QList<int> list2 = QtConcurrent::mappedReduced(list,
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list2, QList<int>() << 1 << 4 << 9);
@@ -1511,14 +1513,14 @@ void tst_QtConcurrentMap::mappedReduced()
QList<int> list3 = QtConcurrent::mappedReduced(list.constBegin(),
list.constEnd(),
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list3, QList<int>() << 1 << 4 << 9);
QList<int> list4 = QtConcurrent::mappedReduced(QList<int>(list),
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list4, QList<int>() << 1 << 4 << 9);
@@ -1759,11 +1761,13 @@ void tst_QtConcurrentMap::blocking_mappedReduced()
QCOMPARE(sum3, 14);
}
+ auto push_back = static_cast<void (QVector<int>::*)(const int &)>(&QVector<int>::push_back);
+
// functor-member
{
QList<int> list2 = QtConcurrent::blockingMappedReduced(list,
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list2, QList<int>() << 1 << 4 << 9);
@@ -1771,14 +1775,14 @@ void tst_QtConcurrentMap::blocking_mappedReduced()
QList<int> list3 = QtConcurrent::blockingMappedReduced(list.constBegin(),
list.constEnd(),
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list3, QList<int>() << 1 << 4 << 9);
QList<int> list4 = QtConcurrent::blockingMappedReduced(QList<int>(list),
IntSquare(),
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list4, QList<int>() << 1 << 4 << 9);
@@ -1842,20 +1846,20 @@ void tst_QtConcurrentMap::blocking_mappedReduced()
{
QList<int> list2 = QtConcurrent::blockingMappedReduced(numberList,
&Number::toInt,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list2, QList<int>() << 1 << 2 << 3);
QList<int> list3 = QtConcurrent::blockingMappedReduced(numberList.constBegin(),
numberList.constEnd(),
&Number::toInt,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list3, QList<int>() << 1 << 2 << 3);
QList<int> list4 = QtConcurrent::blockingMappedReduced(QList<Number>(numberList),
&Number::toInt,
- &QList<int>::push_back, OrderedReduce);
+ push_back, OrderedReduce);
QCOMPARE(list4, QList<int>() << 1 << 2 << 3);
}
{
@@ -1882,7 +1886,7 @@ void tst_QtConcurrentMap::blocking_mappedReduced()
{
QList<int> list2 = QtConcurrent::blockingMappedReduced(list,
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list2, QList<int>() << 1 << 4 << 9);
@@ -1890,14 +1894,14 @@ void tst_QtConcurrentMap::blocking_mappedReduced()
QList<int> list3 = QtConcurrent::blockingMappedReduced(list.constBegin(),
list.constEnd(),
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list3, QList<int>() << 1 << 4 << 9);
QList<int> list4 = QtConcurrent::blockingMappedReduced(QList<int>(list),
intSquare,
- &QList<int>::push_back,
+ push_back,
OrderedReduce);
QCOMPARE(list, QList<int>() << 1 << 2 << 3);
QCOMPARE(list4, QList<int>() << 1 << 4 << 9);
@@ -2118,7 +2122,6 @@ public:
};
Q_DECLARE_METATYPE(QVector<MemFnTester>);
-Q_DECLARE_METATYPE(QList<MemFnTester>);
void tst_QtConcurrentMap::functionOverloads()
{
diff --git a/tests/auto/concurrent/qtconcurrentmedian/qtconcurrentmedian.pro b/tests/auto/concurrent/qtconcurrentmedian/qtconcurrentmedian.pro
index 0d07642028..59e22d24a1 100644
--- a/tests/auto/concurrent/qtconcurrentmedian/qtconcurrentmedian.pro
+++ b/tests/auto/concurrent/qtconcurrentmedian/qtconcurrentmedian.pro
@@ -2,4 +2,3 @@ CONFIG += testcase
TARGET = tst_qtconcurrentmedian
QT = core testlib concurrent
SOURCES = tst_qtconcurrentmedian.cpp
-DEFINES += QT_STRICT_ITERATORS
diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
index b33dec8a61..047130d5ea 100644
--- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
+++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp
@@ -49,7 +49,6 @@ private slots:
void qConstructorFunction();
void qCoreAppStartupFunction();
void qCoreAppStartupFunctionRestart();
- void qAlignOf();
void integerForSize();
void qprintable();
void qprintable_data();
@@ -434,106 +433,6 @@ template <class T> struct AlignmentInStruct { T dummy; };
typedef int (*fun) ();
typedef int (Empty::*memFun) ();
-#define TEST_AlignOf(type, alignment) \
- do { \
- TEST_AlignOf_impl(type, alignment); \
- \
- TEST_AlignOf_impl(type &, alignment); \
- TEST_AlignOf_RValueRef(type &&, alignment); \
- \
- TEST_AlignOf_impl(type [5], alignment); \
- TEST_AlignOf_impl(type (&) [5], alignment); \
- \
- TEST_AlignOf_impl(AlignmentInStruct<type>, alignment); \
- \
- /* Some internal sanity validation, just for fun */ \
- TEST_AlignOf_impl(AlignmentInStruct<type [5]>, alignment); \
- TEST_AlignOf_impl(AlignmentInStruct<type &>, Q_ALIGNOF(void *)); \
- TEST_AlignOf_impl(AlignmentInStruct<type (&) [5]>, \
- Q_ALIGNOF(void *)); \
- TEST_AlignOf_RValueRef(AlignmentInStruct<type &&>, \
- Q_ALIGNOF(void *)); \
- } while (false) \
- /**/
-
-#define TEST_AlignOf_RValueRef(type, alignment) \
- TEST_AlignOf_impl(type, alignment)
-
-#define TEST_AlignOf_impl(type, alignment) \
- do { \
- QCOMPARE(Q_ALIGNOF(type), size_t(alignment)); \
- /* Compare to native operator for compilers that support it,
- otherwise... erm... check consistency! :-) */ \
- QCOMPARE(alignof(type), Q_ALIGNOF(type)); \
- } while (false)
- /**/
-
-void tst_QGlobal::qAlignOf()
-{
- // Built-in types, except 64-bit integers and double
- TEST_AlignOf(char, 1);
- TEST_AlignOf(signed char, 1);
- TEST_AlignOf(unsigned char, 1);
- TEST_AlignOf(qint8, 1);
- TEST_AlignOf(quint8, 1);
- TEST_AlignOf(qint16, 2);
- TEST_AlignOf(quint16, 2);
- TEST_AlignOf(qint32, 4);
- TEST_AlignOf(quint32, 4);
- TEST_AlignOf(void *, sizeof(void *));
-
- // Depends on platform and compiler, disabling test for now
- // TEST_AlignOf(long double, 16);
-
- // Empty struct
- TEST_AlignOf(Empty, 1);
-
- // Function pointers
- TEST_AlignOf(fun, Q_ALIGNOF(void *));
- TEST_AlignOf(memFun, Q_ALIGNOF(void *));
-
-
- // 64-bit integers and double
- TEST_AlignOf_impl(qint64, 8);
- TEST_AlignOf_impl(quint64, 8);
- TEST_AlignOf_impl(double, 8);
-
- TEST_AlignOf_impl(qint64 &, 8);
- TEST_AlignOf_impl(quint64 &, 8);
- TEST_AlignOf_impl(double &, 8);
-
- TEST_AlignOf_RValueRef(qint64 &&, 8);
- TEST_AlignOf_RValueRef(quint64 &&, 8);
- TEST_AlignOf_RValueRef(double &&, 8);
-
- // 32-bit x86 ABI idiosyncrasies
-#if defined(Q_PROCESSOR_X86_32) && !defined(Q_OS_WIN)
- TEST_AlignOf_impl(AlignmentInStruct<qint64>, 4);
-#else
- TEST_AlignOf_impl(AlignmentInStruct<qint64>, 8);
-#endif
-
- TEST_AlignOf_impl(AlignmentInStruct<quint64>, Q_ALIGNOF(AlignmentInStruct<qint64>));
- TEST_AlignOf_impl(AlignmentInStruct<double>, Q_ALIGNOF(AlignmentInStruct<qint64>));
-
- // 32-bit x86 ABI, Clang disagrees with gcc
-#if !defined(Q_PROCESSOR_X86_32) || !defined(Q_CC_CLANG) || defined(Q_OS_ANDROID)
- TEST_AlignOf_impl(qint64 [5], Q_ALIGNOF(qint64));
-#else
- TEST_AlignOf_impl(qint64 [5], Q_ALIGNOF(AlignmentInStruct<qint64>));
-#endif
-
- TEST_AlignOf_impl(qint64 (&) [5], Q_ALIGNOF(qint64 [5]));
- TEST_AlignOf_impl(quint64 [5], Q_ALIGNOF(quint64 [5]));
- TEST_AlignOf_impl(quint64 (&) [5], Q_ALIGNOF(quint64 [5]));
- TEST_AlignOf_impl(double [5], Q_ALIGNOF(double [5]));
- TEST_AlignOf_impl(double (&) [5], Q_ALIGNOF(double [5]));
-}
-
-#undef TEST_AlignOf
-#undef TEST_AlignOf_RValueRef
-#undef TEST_AlignOf_impl
-
void tst_QGlobal::integerForSize()
{
// compile-only test:
diff --git a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
index 09ef0ea44f..ebb9a0a44c 100644
--- a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
+++ b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
@@ -116,7 +116,7 @@ static DWORD createSymbolicLink(const QString &symLinkName, const QString &targe
reinterpret_cast<const wchar_t*>(nativeTarget.utf16()), flags) == FALSE) {
result = GetLastError();
QTextStream(errorMessage) << "CreateSymbolicLink(" << nativeSymLinkName << ", "
- << nativeTarget << ", 0x" << hex << flags << dec << ") failed with error " << result
+ << nativeTarget << ", 0x" << Qt::hex << flags << Qt::dec << ") failed with error " << result
<< ": " << qt_error_string(int(result));
}
return result;
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+mac/test5 b/tests/auto/corelib/io/qfileselector/platforms/+mac/test5
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+mac/test5
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+osx/test4 b/tests/auto/corelib/io/qfileselector/platforms/+osx/test4
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+osx/test4
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+mac/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+ios/test
index e69de29bb2..e69de29bb2 100644
--- a/tests/auto/corelib/io/qfileselector/platforms/+mac/test
+++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+ios/test
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+ios/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+ios/test
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+ios/test
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+macos/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+macos/test
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+macos/test
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/+macos/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/+macos/test
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/+macos/test
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/test
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/+osx/test
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/test
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+mac/test
+++ /dev/null
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+osx/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+macos/test
index e69de29bb2..e69de29bb2 100644
--- a/tests/auto/corelib/io/qfileselector/platforms/+osx/test
+++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+darwin/+macos/test
diff --git a/tests/auto/corelib/io/qfileselector/qfileselector.qrc b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
index 54b2e0a0e2..f3b3ede575 100644
--- a/tests/auto/corelib/io/qfileselector/qfileselector.qrc
+++ b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
@@ -1,65 +1,51 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/">
- <file>extras/test</file>
- <file>extras/test2</file>
- <file>extras/+custom1/test</file>
- <file>extras/+custom1/test3</file>
- <file>extras/+custom2/test</file>
- <file>extras/+custom3/test</file>
- <file>extras/+custom3/+custom2/test</file>
- <file>extras/+custom3/+custom4/test</file>
- <file>extras/+custom3/+custom5/test</file>
- <file>extras/+custom5/+custom3/test</file>
-
- <!-- platforms/test: deepest possible selection -->
- <file>platforms/test</file>
- <file>platforms/+unix/+android/test</file>
- <file>platforms/+unix/+darwin/+mac/+ios/test</file>
- <file>platforms/+unix/+darwin/+mac/+osx/+macos/test</file>
- <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/+qnx/test</file>
- <file>platforms/+unix/test</file>
- <file>platforms/+windows/+wince/test</file>
- <file>platforms/+windows/+winnt/test</file>
- <file>platforms/+windows/+winrt/test</file>
- <file>platforms/+windows/test</file>
- <file>platforms/+android/test</file>
- <file>platforms/+ios/test</file>
- <file>platforms/+macos/test</file>
- <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/+qnx/test</file>
- <file>platforms/+wince/test</file>
- <file>platforms/+winrt/test</file>
-
- <!-- platforms/test2: shallow selection for the deepest selector -->
- <file>platforms/test2</file>
- <file>platforms/+android/test2</file>
- <file>platforms/+ios/test2</file>
- <file>platforms/+macos/test2</file>
- <file>platforms/+haiku/test2</file>
- <file>platforms/+linux/test2</file>
- <file>platforms/+qnx/test2</file>
- <file>platforms/+wince/test2</file>
- <file>platforms/+winnt/test2</file>
- <file>platforms/+winrt/test2</file>
-
- <!-- platforms/test3: selection for the family only -->
- <file>platforms/test3</file>
- <file>platforms/+windows/test3</file>
- <file>platforms/+unix/test3</file>
-
- <!-- platforms/test4 and 5: special cases for macOS -->
- <file>platforms/test4</file>
- <file>platforms/+osx/test4</file>
- <file>platforms/test5</file>
- <file>platforms/+mac/test5</file>
-</qresource>
+<RCC>
+ <qresource prefix="/">
+ <file>extras/test</file>
+ <file>extras/test2</file>
+ <file>extras/+custom1/test</file>
+ <file>extras/+custom1/test3</file>
+ <file>extras/+custom2/test</file>
+ <file>extras/+custom3/test</file>
+ <file>extras/+custom3/+custom2/test</file>
+ <file>extras/+custom3/+custom4/test</file>
+ <file>extras/+custom3/+custom5/test</file>
+ <file>extras/+custom5/+custom3/test</file>
+ <file>platforms/test</file>
+ <file>platforms/+unix/+android/test</file>
+ <file>platforms/+unix/+darwin/test</file>
+ <file>platforms/+unix/+haiku/test</file>
+ <file>platforms/+unix/+linux/test</file>
+ <file>platforms/+unix/+qnx/test</file>
+ <file>platforms/+unix/test</file>
+ <file>platforms/+windows/+wince/test</file>
+ <file>platforms/+windows/+winnt/test</file>
+ <file>platforms/+windows/+winrt/test</file>
+ <file>platforms/+windows/test</file>
+ <file>platforms/+android/test</file>
+ <file>platforms/+ios/test</file>
+ <file>platforms/+macos/test</file>
+ <file>platforms/+darwin/test</file>
+ <file>platforms/+haiku/test</file>
+ <file>platforms/+linux/test</file>
+ <file>platforms/+qnx/test</file>
+ <file>platforms/+wince/test</file>
+ <file>platforms/+winrt/test</file>
+ <file>platforms/test2</file>
+ <file>platforms/+android/test2</file>
+ <file>platforms/+ios/test2</file>
+ <file>platforms/+macos/test2</file>
+ <file>platforms/+haiku/test2</file>
+ <file>platforms/+linux/test2</file>
+ <file>platforms/+qnx/test2</file>
+ <file>platforms/+wince/test2</file>
+ <file>platforms/+winnt/test2</file>
+ <file>platforms/+winrt/test2</file>
+ <file>platforms/test3</file>
+ <file>platforms/+windows/test3</file>
+ <file>platforms/+unix/test3</file>
+ <file>platforms/test4</file>
+ <file>platforms/test5</file>
+ <file>platforms/+unix/+darwin/+macos/test</file>
+ <file>platforms/+unix/+darwin/+ios/test</file>
+ </qresource>
</RCC>
diff --git a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
index 11b1fdaeeb..bac7a69e0f 100644
--- a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
+++ b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
@@ -126,14 +126,6 @@ void tst_QFileSelector::basicTest_data()
QTest::newRow("platform3") << QString(":/platforms/test3") << QStringList()
<< expectedPlatform3File;
-#ifdef Q_OS_MACOS
- // special case for compatibility code
- QTest::newRow("osx-compat") << QString(":/platforms/test4") << QStringList()
- << ":/platforms/+osx/test4";
- QTest::newRow("mac-compat") << QString(":/platforms/test5") << QStringList()
- << ":/platforms/+mac/test5";
-#endif
-
QString resourceTestPath(":/extras/test");
QString custom1("custom1");
QTest::newRow("custom1-noselector") << resourceTestPath << QStringList()
diff --git a/tests/auto/corelib/io/qsettings/tst_qsettings.cpp b/tests/auto/corelib/io/qsettings/tst_qsettings.cpp
index 0f07ba4bb2..c969e72c18 100644
--- a/tests/auto/corelib/io/qsettings/tst_qsettings.cpp
+++ b/tests/auto/corelib/io/qsettings/tst_qsettings.cpp
@@ -39,7 +39,9 @@
#include <QtCore/QDir>
#include <QtCore/QThread>
#include <QtCore/QSysInfo>
-#include <QtGui/QKeySequence>
+#if QT_CONFIG(shortcut)
+# include <QtGui/QKeySequence>
+#endif
#include <QtCore>
#include <QtGui>
@@ -1364,6 +1366,7 @@ void tst_QSettings::testVariantTypes()
dt.setOffsetFromUtc(3600);
testVal("key14", dt, QDateTime, DateTime);
+#if QT_CONFIG(shortcut)
// We store key sequences as strings instead of binary variant blob, for improved
// readability in the resulting format.
if (format >= QSettings::InvalidFormat) {
@@ -1373,6 +1376,7 @@ void tst_QSettings::testVariantTypes()
QKeySequence(Qt::ControlModifier + Qt::Key_F1).toString(QKeySequence::NativeText),
QString, String);
}
+#endif // QT_CONFIG(shortcut)
#undef testVal
}
diff --git a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
index 60000316cc..c83e7af503 100644
--- a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
+++ b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
@@ -1320,13 +1320,13 @@ void tst_QMetaObject::normalizedSignature_data()
QTest::newRow("function ptr spaces") << "void foo( void ( * ) ( void ))" << "void foo(void(*)())";
QTest::newRow("function ptr void*") << "void foo(void(*)(void*))" << "void foo(void(*)(void*))";
QTest::newRow("function ptr void* spaces") << "void foo( void ( * ) ( void * ))" << "void foo(void(*)(void*))";
- QTest::newRow("template args") << " void foo( QMap<a, a>, QList<b>) "
- << "void foo(QMap<a,a>,QList<b>)";
+ QTest::newRow("template args") << " void foo( QMap<a, a>, QVector<b>) "
+ << "void foo(QMap<a,a>,QVector<b>)";
QTest::newRow("void template args") << " void foo( Foo<void>, Bar<void> ) "
<< "void foo(Foo<void>,Bar<void>)";
QTest::newRow("void* template args") << " void foo( Foo<void*>, Bar<void *> ) "
<< "void foo(Foo<void*>,Bar<void*>)";
- QTest::newRow("rettype") << "QList<int, int> foo()" << "QList<int,int>foo()";
+ QTest::newRow("rettype") << "QVector<int, int> foo()" << "QVector<int,int>foo()";
QTest::newRow("rettype void template") << "Foo<void> foo()" << "Foo<void>foo()";
QTest::newRow("const rettype") << "const QString *foo()" << "const QString*foo()";
QTest::newRow("const ref") << "const QString &foo()" << "const QString&foo()";
@@ -1337,15 +1337,16 @@ void tst_QMetaObject::normalizedSignature_data()
QTest::newRow("const4") << "void foo(const int)" << "void foo(int)";
QTest::newRow("const5") << "void foo(const int, int const, const int &, int const &)"
<< "void foo(int,int,int,int)";
- QTest::newRow("const6") << "void foo(QList<const int>)" << "void foo(QList<const int>)";
- QTest::newRow("const7") << "void foo(QList<const int*>)" << "void foo(QList<const int*>)";
- QTest::newRow("const8") << "void foo(QList<int const*>)" << "void foo(QList<const int*>)";
+ QTest::newRow("const6") << "void foo(QVector<const int>)" << "void foo(QVector<const int>)";
+ QTest::newRow("const7") << "void foo(QVector<const int*>)" << "void foo(QVector<const int*>)";
+ QTest::newRow("const8") << "void foo(QVector<int const*>)" << "void foo(QVector<const int*>)";
QTest::newRow("const9") << "void foo(const Foo<Bar>)" << "void foo(Foo<Bar>)";
QTest::newRow("const10") << "void foo(Foo<Bar>const)" << "void foo(Foo<Bar>)";
QTest::newRow("const11") << "void foo(Foo<Bar> *const)" << "void foo(Foo<Bar>*const)";
QTest::newRow("const12") << "void foo(Foo<Bar>const*const *const)" << "void foo(Foo<Bar>*const*const)";
QTest::newRow("const13") << "void foo(const Foo<Bar>&)" << "void foo(Foo<Bar>)";
QTest::newRow("const14") << "void foo(Foo<Bar>const&)" << "void foo(Foo<Bar>)";
+ QTest::newRow("QList") << "void foo(QList<int>)" << "void foo(QVector<int>)";
QTest::newRow("invalid1") << "a( b" << "a(b";
}
@@ -1367,13 +1368,13 @@ void tst_QMetaObject::normalizedType_data()
QTest::newRow("white") << " int " << "int";
QTest::newRow("const1") << "int const *" << "const int*";
QTest::newRow("const2") << "const int *" << "const int*";
- QTest::newRow("template1") << "QList<int const *>" << "QList<const int*>";
- QTest::newRow("template2") << "QList<const int *>" << "QList<const int*>";
+ QTest::newRow("template1") << "QVector<int const *>" << "QVector<const int*>";
+ QTest::newRow("template2") << "QVector<const int *>" << "QVector<const int*>";
QTest::newRow("template3") << "QMap<QString, int>" << "QMap<QString,int>";
QTest::newRow("template4") << "const QMap<QString, int> &" << "QMap<QString,int>";
- QTest::newRow("template5") << "QList< ::Foo::Bar>" << "QList< ::Foo::Bar>";
- QTest::newRow("template6") << "QList<::Foo::Bar>" << "QList<::Foo::Bar>";
- QTest::newRow("template7") << "QList<QList<int> >" << "QList<QList<int> >";
+ QTest::newRow("template5") << "QVector< ::Foo::Bar>" << "QVector< ::Foo::Bar>";
+ QTest::newRow("template6") << "QVector<::Foo::Bar>" << "QVector<::Foo::Bar>";
+ QTest::newRow("template7") << "QVector<QVector<int> >" << "QVector<QVector<int> >";
QTest::newRow("template8") << "QMap<const int, const short*>" << "QMap<const int,const short*>";
QTest::newRow("template9") << "QPair<const QPair<int, int const *> , QPair<QHash<int, const char*> > >" << "QPair<const QPair<int,const int*>,QPair<QHash<int,const char*> > >";
QTest::newRow("value1") << "const QString &" << "QString";
@@ -1387,6 +1388,7 @@ void tst_QMetaObject::normalizedType_data()
QTest::newRow("struct2") << "struct foo const*" << "const foo*";
QTest::newRow("enum") << "enum foo" << "foo";
QTest::newRow("void") << "void" << "void";
+ QTest::newRow("QList") << "QList<int>" << "QVector<int>";
}
void tst_QMetaObject::normalizedType()
diff --git a/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp b/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
index 9fe7d63727..14719f36f8 100644
--- a/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
+++ b/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
@@ -1702,9 +1702,10 @@ void tst_QMetaObjectBuilder::classNameFirstInStringData()
builder.setClassName(QByteArrayLiteral("TestClass"));
QMetaObject *mo = builder.toMetaObject();
- QByteArrayDataPtr header;
- header.ptr = const_cast<QByteArrayData*>(mo->d.stringdata);
- QCOMPARE(QByteArray(header), QByteArrayLiteral("TestClass"));
+ uint offset = mo->d.stringdata[0];
+ uint len = mo->d.stringdata[1];
+ QByteArray className(reinterpret_cast<const char *>(mo->d.stringdata) + offset, len);
+ QCOMPARE(className, QByteArrayLiteral("TestClass"));
free(mo);
}
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
index 19b3289390..4e30f210b1 100644
--- a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
@@ -120,8 +120,6 @@ private slots:
void constRefs();
void convertCustomType_data();
void convertCustomType();
- void compareCustomType_data();
- void compareCustomType();
void compareCustomEqualOnlyType();
void customDebugStream();
void unknownType();
@@ -574,12 +572,14 @@ void tst_QMetaType::typeName_data()
QTest::newRow("124125534") << 124125534 << QString();
// automatic registration
- QTest::newRow("QList<int>") << ::qMetaTypeId<QList<int> >() << QString::fromLatin1("QList<int>");
QTest::newRow("QHash<int,int>") << ::qMetaTypeId<QHash<int, int> >() << QString::fromLatin1("QHash<int,int>");
QTest::newRow("QMap<int,int>") << ::qMetaTypeId<QMap<int, int> >() << QString::fromLatin1("QMap<int,int>");
- QTest::newRow("QVector<QList<int>>") << ::qMetaTypeId<QVector<QList<int> > >() << QString::fromLatin1("QVector<QList<int> >");
QTest::newRow("QVector<QMap<int,int>>") << ::qMetaTypeId<QVector<QMap<int, int> > >() << QString::fromLatin1("QVector<QMap<int,int> >");
+ // automatic registration with automatic QList to QVector aliasing
+ QTest::newRow("QList<int>") << ::qMetaTypeId<QList<int> >() << QString::fromLatin1("QVector<int>");
+ QTest::newRow("QVector<QList<int>>") << ::qMetaTypeId<QVector<QList<int> > >() << QString::fromLatin1("QVector<QVector<int> >");
+
QTest::newRow("CustomQObject*") << ::qMetaTypeId<CustomQObject*>() << QString::fromLatin1("CustomQObject*");
QTest::newRow("CustomGadget") << ::qMetaTypeId<CustomGadget>() << QString::fromLatin1("CustomGadget");
QTest::newRow("CustomGadget*") << ::qMetaTypeId<CustomGadget*>() << QString::fromLatin1("CustomGadget*");
@@ -1032,9 +1032,9 @@ static void testConstructHelper()
typedef typename MetaEnumToType<ID>::Type Type;
QMetaType info(ID);
int size = info.sizeOf();
- void *storage1 = qMallocAligned(size, Q_ALIGNOF(Type));
+ void *storage1 = qMallocAligned(size, alignof(Type));
void *actual1 = QMetaType::construct(ID, storage1, /*copy=*/0);
- void *storage2 = qMallocAligned(size, Q_ALIGNOF(Type));
+ void *storage2 = qMallocAligned(size, alignof(Type));
void *actual2 = info.construct(storage2, /*copy=*/0);
QCOMPARE(actual1, storage1);
QCOMPARE(actual2, storage2);
@@ -1186,9 +1186,9 @@ static void testConstructCopyHelper()
QMetaType info(ID);
int size = QMetaType::sizeOf(ID);
QCOMPARE(info.sizeOf(), size);
- void *storage1 = qMallocAligned(size, Q_ALIGNOF(Type));
+ void *storage1 = qMallocAligned(size, alignof(Type));
void *actual1 = QMetaType::construct(ID, storage1, expected);
- void *storage2 = qMallocAligned(size, Q_ALIGNOF(Type));
+ void *storage2 = qMallocAligned(size, alignof(Type));
void *actual2 = info.construct(storage2, expected);
QCOMPARE(actual1, storage1);
QCOMPARE(actual2, storage2);
@@ -2017,7 +2017,7 @@ void tst_QMetaType::metaObject_data()
QTest::newRow("MyGadget") << ::qMetaTypeId<MyGadget>() << &MyGadget::staticMetaObject << true << false << false;
QTest::newRow("MyGadget*") << ::qMetaTypeId<MyGadget*>() << &MyGadget::staticMetaObject << false << true << false;
QTest::newRow("MyEnum") << ::qMetaTypeId<MyGadget::MyEnum>() << &MyGadget::staticMetaObject << false << false << false;
- QTest::newRow("Qt::ScrollBarPolicy") << ::qMetaTypeId<Qt::ScrollBarPolicy>() << &QObject::staticQtMetaObject << false << false << false;
+ QTest::newRow("Qt::ScrollBarPolicy") << ::qMetaTypeId<Qt::ScrollBarPolicy>() << &Qt::staticMetaObject << false << false << false;
QTest::newRow("MyQObjectFromGadget*") << ::qMetaTypeId<MyQObjectFromGadget*>() << &MyQObjectFromGadget::staticMetaObject << false << false << true;
QTest::newRow("GadgetDerivedAndTyped<int>") << ::qMetaTypeId<GadgetDerivedAndTyped<int>>() << &GadgetDerivedAndTyped<int>::staticMetaObject << true << false << false;
@@ -2139,7 +2139,7 @@ struct CustomConvertibleType
};
bool operator<(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
-{ return lhs.m_foo < rhs.m_foo; }
+{ return lhs.m_foo.toString() < rhs.m_foo.toString(); }
bool operator==(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
{ return lhs.m_foo == rhs.m_foo; }
bool operator!=(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
@@ -2429,43 +2429,6 @@ void tst_QMetaType::convertCustomType()
QCOMPARE(v.value<CustomConvertibleType2>().m_foo, testCustom.m_foo);
}
-void tst_QMetaType::compareCustomType_data()
-{
- QMetaType::registerComparators<CustomConvertibleType>();
-
- QTest::addColumn<QVariantList>("unsorted");
- QTest::addColumn<QVariantList>("sorted");
-
- QTest::newRow("int") << (QVariantList() << 37 << 458 << 1 << 243 << -4 << 383)
- << (QVariantList() << -4 << 1 << 37 << 243 << 383 << 458);
-
- QTest::newRow("dobule") << (QVariantList() << 4934.93 << 0.0 << 302.39 << -39.0)
- << (QVariantList() << -39.0 << 0.0 << 302.39 << 4934.93);
-
- QTest::newRow("QString") << (QVariantList() << "Hello" << "World" << "this" << "is" << "a" << "test")
- << (QVariantList() << "a" << "Hello" << "is" << "test" << "this" << "World");
-
- QTest::newRow("QTime") << (QVariantList() << QTime(14, 39) << QTime(0, 0) << QTime(18, 18) << QTime(9, 27))
- << (QVariantList() << QTime(0, 0) << QTime(9, 27) << QTime(14, 39) << QTime(18, 18));
-
- QTest::newRow("QDate") << (QVariantList() << QDate(2013, 3, 23) << QDate(1900, 12, 1) << QDate(2001, 2, 2) << QDate(1982, 12, 16))
- << (QVariantList() << QDate(1900, 12, 1) << QDate(1982, 12, 16) << QDate(2001, 2, 2) << QDate(2013, 3, 23));
-
- QTest::newRow("mixed") << (QVariantList() << "Hello" << "World" << QChar('a') << 38 << QChar('z') << -39 << 4.6)
- << (QVariantList() << -39 << 4.6 << 38 << QChar('a') << "Hello" << "World" << QChar('z'));
-
- QTest::newRow("custom") << (QVariantList() << QVariant::fromValue(CustomConvertibleType(1)) << QVariant::fromValue(CustomConvertibleType(100)) << QVariant::fromValue(CustomConvertibleType(50)))
- << (QVariantList() << QVariant::fromValue(CustomConvertibleType(1)) << QVariant::fromValue(CustomConvertibleType(50)) << QVariant::fromValue(CustomConvertibleType(100)));
-}
-
-void tst_QMetaType::compareCustomType()
-{
- QFETCH(QVariantList, unsorted);
- QFETCH(QVariantList, sorted);
- std::sort(unsorted.begin(), unsorted.end());
- QCOMPARE(unsorted, sorted);
-}
-
void tst_QMetaType::compareCustomEqualOnlyType()
{
int metaTypeId = qRegisterMetaType<CustomEqualsOnlyType>();
@@ -2487,11 +2450,6 @@ void tst_QMetaType::compareCustomEqualOnlyType()
QCOMPARE(variant100, variant100x);
QCOMPARE(variant100, variant100);
- // compare always fails
- QVERIFY(!(variant50 < variant50));
- QVERIFY(!(variant50 < variant100));
- QVERIFY(!(variant100 < variant50));
-
// check QMetaType::compare works/doesn't crash for equals only comparators
bool wasSuccess = QMetaType::compare(variant50.constData(), variant50.constData(),
metaTypeId, &result);
diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
index 21615d6ec4..5ce70f7a0e 100644
--- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
+++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
@@ -81,9 +81,6 @@ private slots:
void senderTest();
void declareInterface();
void qpointerResetBeforeDestroyedSignal();
-#ifndef QT_NO_USERDATA
- void testUserData();
-#endif
void childDeletesItsSibling();
void dynamicProperties();
void floatProperty();
@@ -463,7 +460,7 @@ void tst_QObject::connectSlotsByName()
sender.setObjectName("Sender");
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::connectSlotsByName: No matching signal for on_child_signal()");
- QTest::ignoreMessage(QtWarningMsg, "QMetaObject::connectSlotsByName: Connecting slot on_Sender_signalManyParams() with the first of the following compatible signals: (\"signalManyParams(int,int,int,QString,bool)\", \"signalManyParams(int,int,int,QString,bool,bool)\")");
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::connectSlotsByName: Connecting slot on_Sender_signalManyParams() with the first of the following compatible signals: QVector(\"signalManyParams(int,int,int,QString,bool)\", \"signalManyParams(int,int,int,QString,bool,bool)\")");
QMetaObject::connectSlotsByName(&receiver);
receiver.called_slots.clear();
@@ -2341,51 +2338,6 @@ void tst_QObject::declareInterface()
}
-#ifndef QT_NO_USERDATA
-class CustomData : public QObjectUserData
-{
-public:
- int id;
-};
-
-void tst_QObject::testUserData()
-{
- const int USER_DATA_COUNT = 100;
- int user_data_ids[USER_DATA_COUNT];
-
- // Register a few
- for (int i=0; i<USER_DATA_COUNT; ++i) {
- user_data_ids[i] = QObject::registerUserData();
- }
-
- // Randomize the table a bit
- for (int i=0; i<100; ++i) {
- int p1 = QRandomGenerator::global()->bounded(USER_DATA_COUNT);
- int p2 = QRandomGenerator::global()->bounded(USER_DATA_COUNT);
-
- int tmp = user_data_ids[p1];
- user_data_ids[p1] = user_data_ids[p2];
- user_data_ids[p2] = tmp;
- }
-
- // insert the user data into an object
- QObject my_test_object;
- for (int i=0; i<USER_DATA_COUNT; ++i) {
- CustomData *data = new CustomData;
- data->id = user_data_ids[i];
- my_test_object.setUserData(data->id, data);
- }
-
- // verify that all ids and positions are matching
- for (int i=0; i<USER_DATA_COUNT; ++i) {
- int id = user_data_ids[i];
- CustomData *data = static_cast<CustomData *>(my_test_object.userData(id));
- QVERIFY(data != nullptr);
- QCOMPARE(data->id, id);
- }
-}
-#endif // QT_NO_USERDATA
-
class DestroyedListener : public QObject
{
Q_OBJECT
@@ -6974,8 +6926,7 @@ void tst_QObject::noDeclarativeParentChangedOnDestruction()
QObject *parent = new QObject;
QObject *child = new QObject;
- QAbstractDeclarativeDataImpl dummy;
- dummy.ownedByQml1 = false;
+ QAbstractDeclarativeData dummy;
QObjectPrivate::get(child)->declarativeData = &dummy;
parentChangeCalled = false;
diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
index 45eb61f6e4..9f022b3b14 100644
--- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
+++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
@@ -190,8 +190,6 @@ private slots:
void operator_eq_eq_data();
void operator_eq_eq();
void operator_eq_eq_rhs();
- void compareNumbers_data() const;
- void compareNumbers() const;
void typeName_data();
void typeName();
@@ -270,9 +268,6 @@ private slots:
void enums();
void metaEnums();
- void compareSanity_data();
- void compareSanity();
- void compareRich();
void nullConvert();
@@ -1730,344 +1725,6 @@ void tst_QVariant::operator_eq_eq_rhs()
#endif
}
-void tst_QVariant::compareNumbers_data() const
-{
- typedef signed char schar;
- QTest::addColumn<QVariant>("v1");
- QTest::addColumn<QVariant>("v2");
- QTest::addColumn<int>("expected");
-
- // sanity checking: same types
- QTest::newRow("bool1") << QVariant(false) << QVariant(false) << 0;
- QTest::newRow("bool2") << QVariant(true) << QVariant(true) << 0;
- QTest::newRow("bool3") << QVariant(false) << QVariant(true) << -1;
- QTest::newRow("bool4") << QVariant(true) << QVariant(false) << +1;
-
- QTest::newRow("char1") << QVariant::fromValue(char(0)) << QVariant::fromValue(char(0)) << 0;
- QTest::newRow("char2") << QVariant::fromValue(CHAR_MAX) << QVariant::fromValue(CHAR_MAX) << 0;
- QTest::newRow("char3") << QVariant::fromValue(CHAR_MIN) << QVariant::fromValue(CHAR_MIN) << 0;
- QTest::newRow("char4") << QVariant::fromValue(CHAR_MIN) << QVariant::fromValue(CHAR_MAX) << -1;
- QTest::newRow("char5") << QVariant::fromValue(CHAR_MAX) << QVariant::fromValue(CHAR_MIN) << +1;
-
- QTest::newRow("schar1") << QVariant::fromValue(schar(0)) << QVariant::fromValue(schar(0)) << 0;
- QTest::newRow("schar2") << QVariant::fromValue(SCHAR_MAX) << QVariant::fromValue(SCHAR_MAX) << 0;
- QTest::newRow("schar3") << QVariant::fromValue(SCHAR_MIN) << QVariant::fromValue(SCHAR_MIN) << 0;
- QTest::newRow("schar4") << QVariant::fromValue(SCHAR_MIN) << QVariant::fromValue(SCHAR_MAX) << -1;
- QTest::newRow("schar5") << QVariant::fromValue(SCHAR_MAX) << QVariant::fromValue(SCHAR_MIN) << +1;
-
- QTest::newRow("uchar1") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(uchar(0)) << 0;
- QTest::newRow("uchar2") << QVariant::fromValue(UCHAR_MAX) << QVariant::fromValue(UCHAR_MAX) << 0;
- QTest::newRow("uchar3") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(UCHAR_MAX) << -1;
- QTest::newRow("uchar4") << QVariant::fromValue(UCHAR_MAX) << QVariant::fromValue(uchar(0)) << +1;
-
- QTest::newRow("short1") << QVariant::fromValue(short(0)) << QVariant::fromValue(short(0)) << 0;
- QTest::newRow("short2") << QVariant::fromValue(SHRT_MAX) << QVariant::fromValue(SHRT_MAX) << 0;
- QTest::newRow("short3") << QVariant::fromValue(SHRT_MIN) << QVariant::fromValue(SHRT_MIN) << 0;
- QTest::newRow("short4") << QVariant::fromValue(SHRT_MIN) << QVariant::fromValue(SHRT_MAX) << -1;
- QTest::newRow("short5") << QVariant::fromValue(SHRT_MAX) << QVariant::fromValue(SHRT_MIN) << +1;
-
- QTest::newRow("ushort1") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(ushort(0)) << 0;
- QTest::newRow("ushort2") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(USHRT_MAX) << 0;
- QTest::newRow("ushort3") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(USHRT_MAX) << -1;
- QTest::newRow("ushort4") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(ushort(0)) << +1;
-
- QTest::newRow("int1") << QVariant::fromValue(int(0)) << QVariant::fromValue(int(0)) << 0;
- QTest::newRow("int2") << QVariant::fromValue(INT_MAX) << QVariant::fromValue(INT_MAX) << 0;
- QTest::newRow("int3") << QVariant::fromValue(INT_MIN) << QVariant::fromValue(INT_MIN) << 0;
- QTest::newRow("int4") << QVariant::fromValue(INT_MIN) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("int5") << QVariant::fromValue(INT_MAX) << QVariant::fromValue(INT_MIN) << +1;
-
- QTest::newRow("uint1") << QVariant::fromValue(uint(0)) << QVariant::fromValue(uint(0)) << 0;
- QTest::newRow("uint2") << QVariant::fromValue(UINT_MAX) << QVariant::fromValue(UINT_MAX) << 0;
- QTest::newRow("uint3") << QVariant::fromValue(uint(0)) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("uint4") << QVariant::fromValue(UINT_MAX) << QVariant::fromValue(uint(0)) << +1;
-
- QTest::newRow("long1") << QVariant::fromValue(long(0)) << QVariant::fromValue(long(0)) << 0;
- QTest::newRow("long2") << QVariant::fromValue(LONG_MAX) << QVariant::fromValue(LONG_MAX) << 0;
- QTest::newRow("long3") << QVariant::fromValue(LONG_MIN) << QVariant::fromValue(LONG_MIN) << 0;
- QTest::newRow("long4") << QVariant::fromValue(LONG_MIN) << QVariant::fromValue(LONG_MAX) << -1;
- QTest::newRow("long5") << QVariant::fromValue(LONG_MAX) << QVariant::fromValue(LONG_MIN) << +1;
-
- QTest::newRow("ulong1") << QVariant::fromValue(ulong(0)) << QVariant::fromValue(ulong(0)) << 0;
- QTest::newRow("ulong2") << QVariant::fromValue(ULONG_MAX) << QVariant::fromValue(ULONG_MAX) << 0;
- QTest::newRow("ulong3") << QVariant::fromValue(ulong(0)) << QVariant::fromValue(ULONG_MAX) << -1;
- QTest::newRow("ulong4") << QVariant::fromValue(ULONG_MAX) << QVariant::fromValue(ulong(0)) << +1;
-
- QTest::newRow("llong1") << QVariant::fromValue(qlonglong(0)) << QVariant::fromValue(qlonglong(0)) << 0;
- QTest::newRow("llong2") << QVariant::fromValue(LLONG_MAX) << QVariant::fromValue(LLONG_MAX) << 0;
- QTest::newRow("llong3") << QVariant::fromValue(LLONG_MIN) << QVariant::fromValue(LLONG_MIN) << 0;
- QTest::newRow("llong4") << QVariant::fromValue(LLONG_MIN) << QVariant::fromValue(LLONG_MAX) << -1;
- QTest::newRow("llong5") << QVariant::fromValue(LLONG_MAX) << QVariant::fromValue(LLONG_MIN) << +1;
-
- QTest::newRow("ullong1") << QVariant::fromValue(qulonglong(0)) << QVariant::fromValue(qulonglong(0)) << 0;
- QTest::newRow("ullong2") << QVariant::fromValue(ULLONG_MAX) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("ullong3") << QVariant::fromValue(qulonglong(0)) << QVariant::fromValue(ULLONG_MAX) << -1;
- QTest::newRow("ullong4") << QVariant::fromValue(ULLONG_MAX) << QVariant::fromValue(qulonglong(0)) << +1;
-
- QTest::newRow("float1") << QVariant::fromValue(0.f) << QVariant::fromValue(0.f) << 0;
- QTest::newRow("float2") << QVariant::fromValue(-1.f) << QVariant::fromValue(0.f) << -1;
- QTest::newRow("float3") << QVariant::fromValue(0.f) << QVariant::fromValue(-1.f) << +1;
- QTest::newRow("float4") << QVariant::fromValue(-float(qInf())) << QVariant::fromValue(0.f) << -1;
- QTest::newRow("float5") << QVariant::fromValue(0.f) << QVariant::fromValue(-float(qInf())) << +1;
- QTest::newRow("float6") << QVariant::fromValue(-float(qInf())) << QVariant::fromValue(-float(qInf())) << 0;
- QTest::newRow("float7") << QVariant::fromValue(float(qInf())) << QVariant::fromValue(float(qInf())) << 0;
-
- QTest::newRow("double1") << QVariant::fromValue(0.) << QVariant::fromValue(0.) << 0;
- QTest::newRow("double2") << QVariant::fromValue(-1.) << QVariant::fromValue(0.) << -1;
- QTest::newRow("double3") << QVariant::fromValue(0.) << QVariant::fromValue(-1.) << +1;
- QTest::newRow("double4") << QVariant::fromValue(-qInf()) << QVariant::fromValue(0.) << -1;
- QTest::newRow("double5") << QVariant::fromValue(0.) << QVariant::fromValue(-qInf()) << +1;
- QTest::newRow("double6") << QVariant::fromValue(-double(qInf())) << QVariant::fromValue(-qInf()) << 0;
- QTest::newRow("double7") << QVariant::fromValue(qInf()) << QVariant::fromValue(qInf()) << 0;
- QTest::newRow("double8") << QVariant::fromValue(-qInf()) << QVariant::fromValue(qInf()) << -1;
- QTest::newRow("double9") << QVariant::fromValue(qQNaN()) << QVariant::fromValue(0.) << INT_MAX;
- QTest::newRow("double10") << QVariant::fromValue(0.) << QVariant::fromValue(qQNaN()) << INT_MAX;
- QTest::newRow("double11") << QVariant::fromValue(qQNaN()) << QVariant::fromValue(qQNaN()) << INT_MAX;
-
- // mixed comparisons
- // fp + fp
- QTest::newRow("float+double1") << QVariant::fromValue(0.f) << QVariant::fromValue(0.) << 0;
- QTest::newRow("float+double2") << QVariant::fromValue(-1.f) << QVariant::fromValue(0.) << -1;
- QTest::newRow("float+double3") << QVariant::fromValue(0.f) << QVariant::fromValue(-1.) << +1;
- QTest::newRow("float+double4") << QVariant::fromValue(-float(qInf())) << QVariant::fromValue(0.) << -1;
- QTest::newRow("float+double5") << QVariant::fromValue(0.f) << QVariant::fromValue(-qInf()) << +1;
- QTest::newRow("float+double6") << QVariant::fromValue(-float(qInf())) << QVariant::fromValue(-qInf()) << 0;
- QTest::newRow("float+double7") << QVariant::fromValue(float(qInf())) << QVariant::fromValue(qInf()) << 0;
- QTest::newRow("float+double8") << QVariant::fromValue(-float(qInf())) << QVariant::fromValue(qInf()) << -1;
- QTest::newRow("float+double9") << QVariant::fromValue(qQNaN()) << QVariant::fromValue(0.) << INT_MAX;
- QTest::newRow("float+double10") << QVariant::fromValue(0.) << QVariant::fromValue(qQNaN()) << INT_MAX;
- QTest::newRow("float+double11") << QVariant::fromValue(qQNaN()) << QVariant::fromValue(qQNaN()) << INT_MAX;
-
- // fp + int
- QTest::newRow("float+int1") << QVariant::fromValue(0.f) << QVariant::fromValue(0) << 0;
- QTest::newRow("double+int1") << QVariant::fromValue(0.) << QVariant::fromValue(0) << 0;
- QTest::newRow("float+int2") << QVariant::fromValue(-1.f) << QVariant::fromValue(0) << -1;
- QTest::newRow("double+int2") << QVariant::fromValue(-1.) << QVariant::fromValue(0) << -1;
- QTest::newRow("float+int3") << QVariant::fromValue(0.f) << QVariant::fromValue(-1) << +1;
- QTest::newRow("double+int3") << QVariant::fromValue(0.) << QVariant::fromValue(-1) << +1;
- QTest::newRow("float+int4") << QVariant::fromValue(1.5f) << QVariant::fromValue(1) << +1;
- QTest::newRow("double+int4") << QVariant::fromValue(1.5) << QVariant::fromValue(1) << +1;
- QTest::newRow("double+int5") << QVariant::fromValue(qInf()) << QVariant::fromValue(1) << +1;
-
- // fp + uint
- QTest::newRow("float+uint1") << QVariant::fromValue(0.f) << QVariant::fromValue(0U) << 0;
- QTest::newRow("double+uint1") << QVariant::fromValue(0.) << QVariant::fromValue(0U) << 0;
- QTest::newRow("float+uint2") << QVariant::fromValue(-1.f) << QVariant::fromValue(0U) << -1;
- QTest::newRow("double+uint2") << QVariant::fromValue(-1.) << QVariant::fromValue(0U) << -1;
- QTest::newRow("float+uint3") << QVariant::fromValue(0.f) << QVariant::fromValue(1U) << -1;
- QTest::newRow("double+uint3") << QVariant::fromValue(0.) << QVariant::fromValue(1U) << -1;
- QTest::newRow("float+uint4") << QVariant::fromValue(1.5f) << QVariant::fromValue(1U) << +1;
- QTest::newRow("double+uint4") << QVariant::fromValue(1.5) << QVariant::fromValue(1U) << +1;
-
- // lower ranked + int
- QTest::newRow("bool+int1") << QVariant::fromValue(false) << QVariant::fromValue(0) << 0;
- QTest::newRow("bool+int2") << QVariant::fromValue(false) << QVariant::fromValue(1) << -1;
- QTest::newRow("bool+int3") << QVariant::fromValue(true) << QVariant::fromValue(0) << +1;
- QTest::newRow("bool+int4") << QVariant::fromValue(true) << QVariant::fromValue(1) << 0;
- QTest::newRow("bool+int5") << QVariant::fromValue(true) << QVariant::fromValue(2) << -1;
-
- QTest::newRow("char+int1") << QVariant::fromValue(char(0)) << QVariant::fromValue(0) << 0;
- QTest::newRow("char+int2") << QVariant::fromValue(char(0)) << QVariant::fromValue(1) << -1;
- QTest::newRow("char+int3") << QVariant::fromValue(char(1)) << QVariant::fromValue(0) << +1;
- QTest::newRow("char+int4") << QVariant::fromValue(char(1)) << QVariant::fromValue(1) << 0;
- if (std::numeric_limits<char>::is_signed) {
- QTest::newRow("char+int5") << QVariant::fromValue(char(-1)) << QVariant::fromValue(0) << -1;
- QTest::newRow("char+int6") << QVariant::fromValue(char(-1)) << QVariant::fromValue(-1) << 0;
- }
-
- QTest::newRow("schar+int1") << QVariant::fromValue(schar(0)) << QVariant::fromValue(0) << 0;
- QTest::newRow("schar+int2") << QVariant::fromValue(schar(0)) << QVariant::fromValue(1) << -1;
- QTest::newRow("schar+int3") << QVariant::fromValue(schar(1)) << QVariant::fromValue(0) << +1;
- QTest::newRow("schar+int4") << QVariant::fromValue(schar(1)) << QVariant::fromValue(1) << 0;
- QTest::newRow("schar+int5") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(0) << -1;
- QTest::newRow("schar+int6") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(-1) << 0;
-
- QTest::newRow("uchar+int1") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(0) << 0;
- QTest::newRow("uchar+int2") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(1) << -1;
- QTest::newRow("uchar+int3") << QVariant::fromValue(uchar(1)) << QVariant::fromValue(0) << +1;
- QTest::newRow("uchar+int4") << QVariant::fromValue(uchar(1)) << QVariant::fromValue(1) << 0;
-
- QTest::newRow("short+int1") << QVariant::fromValue(short(0)) << QVariant::fromValue(0) << 0;
- QTest::newRow("short+int2") << QVariant::fromValue(short(0)) << QVariant::fromValue(1) << -1;
- QTest::newRow("short+int3") << QVariant::fromValue(short(1)) << QVariant::fromValue(0) << +1;
- QTest::newRow("short+int4") << QVariant::fromValue(short(1)) << QVariant::fromValue(1) << 0;
- QTest::newRow("short+int5") << QVariant::fromValue(short(-1)) << QVariant::fromValue(0) << -1;
- QTest::newRow("short+int6") << QVariant::fromValue(short(-1)) << QVariant::fromValue(-1) << 0;
-
- QTest::newRow("ushort+int1") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(0) << 0;
- QTest::newRow("ushort+int2") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(1) << -1;
- QTest::newRow("ushort+int3") << QVariant::fromValue(ushort(1)) << QVariant::fromValue(0) << +1;
- QTest::newRow("ushort+int4") << QVariant::fromValue(ushort(1)) << QVariant::fromValue(1) << 0;
-
- // lower ranked + uint (without sign change)
- QTest::newRow("bool+uint1") << QVariant::fromValue(false) << QVariant::fromValue(0U) << 0;
- QTest::newRow("bool+uint2") << QVariant::fromValue(false) << QVariant::fromValue(1U) << -1;
- QTest::newRow("bool+uint3") << QVariant::fromValue(true) << QVariant::fromValue(0U) << +1;
- QTest::newRow("bool+uint4") << QVariant::fromValue(true) << QVariant::fromValue(1U) << 0;
- QTest::newRow("bool+uint5") << QVariant::fromValue(true) << QVariant::fromValue(2U) << -1;
-
- QTest::newRow("char+uint1") << QVariant::fromValue(char(0)) << QVariant::fromValue(0U) << 0;
- QTest::newRow("char+uint2") << QVariant::fromValue(char(0)) << QVariant::fromValue(1U) << -1;
- QTest::newRow("char+uint3") << QVariant::fromValue(char(1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("char+uint4") << QVariant::fromValue(char(1)) << QVariant::fromValue(1U) << 0;
-
- QTest::newRow("schar+uint1") << QVariant::fromValue(schar(0)) << QVariant::fromValue(0U) << 0;
- QTest::newRow("schar+uint2") << QVariant::fromValue(schar(0)) << QVariant::fromValue(1U) << -1;
- QTest::newRow("schar+uint3") << QVariant::fromValue(schar(1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("schar+uint4") << QVariant::fromValue(schar(1)) << QVariant::fromValue(1U) << 0;
-
- QTest::newRow("uchar+uint1") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(0U) << 0;
- QTest::newRow("uchar+uint2") << QVariant::fromValue(uchar(0)) << QVariant::fromValue(1U) << -1;
- QTest::newRow("uchar+uint3") << QVariant::fromValue(uchar(1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("uchar+uint4") << QVariant::fromValue(uchar(1)) << QVariant::fromValue(1U) << 0;
-
- QTest::newRow("short+uint1") << QVariant::fromValue(short(0)) << QVariant::fromValue(0U) << 0;
- QTest::newRow("short+uint2") << QVariant::fromValue(short(0)) << QVariant::fromValue(1U) << -1;
- QTest::newRow("short+uint3") << QVariant::fromValue(short(1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("short+uint4") << QVariant::fromValue(short(1)) << QVariant::fromValue(1U) << 0;
-
- QTest::newRow("ushort+uint1") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(0U) << 0;
- QTest::newRow("ushort+uint2") << QVariant::fromValue(ushort(0)) << QVariant::fromValue(1U) << -1;
- QTest::newRow("ushort+uint3") << QVariant::fromValue(ushort(1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("ushort+uint4") << QVariant::fromValue(ushort(1)) << QVariant::fromValue(1U) << 0;
-
- // int + qlonglong
- QTest::newRow("int+qlonglong1") << QVariant::fromValue(0) << QVariant::fromValue(Q_INT64_C(0)) << 0;
- QTest::newRow("int+qlonglong2") << QVariant::fromValue(1) << QVariant::fromValue(Q_INT64_C(0)) << +1;
- QTest::newRow("int+qlonglong3") << QVariant::fromValue(0) << QVariant::fromValue(Q_INT64_C(1)) << -1;
- QTest::newRow("int+qlonglong4") << QVariant::fromValue(1) << QVariant::fromValue(Q_INT64_C(1)) << 0;
- QTest::newRow("int+qlonglong5") << QVariant::fromValue(0) << QVariant::fromValue(Q_INT64_C(-1)) << +1;
- QTest::newRow("int+qlonglong6") << QVariant::fromValue(-1) << QVariant::fromValue(Q_INT64_C(0)) << -1;
- QTest::newRow("int+qlonglong7") << QVariant::fromValue(-1) << QVariant::fromValue(Q_INT64_C(-1)) << 0;
-
- // uint + qulonglong
- QTest::newRow("uint+qulonglong1") << QVariant::fromValue(0U) << QVariant::fromValue(Q_UINT64_C(0)) << 0;
- QTest::newRow("uint+qulonglong2") << QVariant::fromValue(1U) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("uint+qulonglong3") << QVariant::fromValue(0U) << QVariant::fromValue(Q_UINT64_C(1)) << -1;
- QTest::newRow("uint+qulonglong4") << QVariant::fromValue(1U) << QVariant::fromValue(Q_UINT64_C(1)) << 0;
-
- // int + uint (without sign change)
- QTest::newRow("int+uint1") << QVariant::fromValue(0) << QVariant::fromValue(0U) << 0;
- QTest::newRow("int+uint2") << QVariant::fromValue(1) << QVariant::fromValue(0U) << +1;
- QTest::newRow("int+uint3") << QVariant::fromValue(0) << QVariant::fromValue(1U) << -1;
- QTest::newRow("int+uint4") << QVariant::fromValue(1) << QVariant::fromValue(1U) << 0;
-
- // uint + qlonglong
- QTest::newRow("uint+qlonglong1") << QVariant::fromValue(0U) << QVariant::fromValue(Q_INT64_C(0)) << 0;
- QTest::newRow("uint+qlonglong2") << QVariant::fromValue(1U) << QVariant::fromValue(Q_INT64_C(0)) << +1;
- QTest::newRow("uint+qlonglong3") << QVariant::fromValue(0U) << QVariant::fromValue(Q_INT64_C(1)) << -1;
- QTest::newRow("uint+qlonglong4") << QVariant::fromValue(1U) << QVariant::fromValue(Q_INT64_C(1)) << 0;
- QTest::newRow("uint+qlonglong5") << QVariant::fromValue(0U) << QVariant::fromValue(Q_INT64_C(-1)) << +1;
-
- // boundary conditions
- QTest::newRow("charmax+intmax") << QVariant::fromValue(CHAR_MAX) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("charmax+uintmax") << QVariant::fromValue(CHAR_MAX) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("scharmax+intmax") << QVariant::fromValue(SCHAR_MAX) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("scharmax+uintmax") << QVariant::fromValue(SCHAR_MAX) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("ucharmax+intmax") << QVariant::fromValue(UCHAR_MAX) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("ucharmax+uintmax") << QVariant::fromValue(UCHAR_MAX) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("shortmax+intmax") << QVariant::fromValue(SHRT_MAX) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("shortmax+uintmax") << QVariant::fromValue(SHRT_MAX) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("ushortmax+intmax") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(INT_MAX) << -1;
- QTest::newRow("ushortmax+uintmax") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(UINT_MAX) << -1;
-
- QTest::newRow("intmin+qlonglongmin") << QVariant::fromValue(INT_MIN) << QVariant::fromValue(LLONG_MIN) << +1;
- QTest::newRow("intmax+uintmax") << QVariant::fromValue(INT_MAX) << QVariant::fromValue(UINT_MAX) << -1;
- QTest::newRow("intmax+qlonglongmax") << QVariant::fromValue(INT_MAX) << QVariant::fromValue(LLONG_MAX) << -1;
- QTest::newRow("uintmax+qlonglongmax") << QVariant::fromValue(UINT_MAX) << QVariant::fromValue(LLONG_MAX) << -1;
- QTest::newRow("intmax+qulonglongmax") << QVariant::fromValue(INT_MAX) << QVariant::fromValue(ULLONG_MAX) << -1;
- QTest::newRow("qlonglongmax+qulonglongmax") << QVariant::fromValue(LLONG_MAX) << QVariant::fromValue(ULLONG_MAX) << -1;
- QTest::newRow("uintmax+qlonglongmin") << QVariant::fromValue(UINT_MAX) << QVariant::fromValue(LLONG_MIN) << +1;
-
- // check for no sign-extension issues
- QTest::newRow("ushortmax+intzero") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(0) << +1;
- QTest::newRow("ushortmax+qlonglongzero") << QVariant::fromValue(USHRT_MAX) << QVariant::fromValue(Q_INT64_C(0)) << +1;
- QTest::newRow("uintmax+qlonglongzero") << QVariant::fromValue(UINT_MAX) << QVariant::fromValue(Q_INT64_C(0)) << +1;
-
- // sign changes
- // the tests below check that a signed negative number sign-changes to a non-zero unsigned number and that
- // signed -1 sign-changes to unsigned maximum (all bits set, ~0). This works on two's complement machines
- // (all that Qt supports), and would also work on one's complement.
- if (std::numeric_limits<char>::is_signed) {
- QTest::newRow("signchange-char+uint") << QVariant::fromValue(char(-1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-char+uintmax") << QVariant::fromValue(char(-1)) << QVariant::fromValue(UINT_MAX) << 0;
- QTest::newRow("signchange-charmin+uint") << QVariant::fromValue(CHAR_MIN) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-char+qulonglong") << QVariant::fromValue(char(-1)) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-char+qulonglongmax") << QVariant::fromValue(char(-1)) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("signchange-charmin+qulonglong") << QVariant::fromValue(CHAR_MIN) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- }
- QTest::newRow("signchange-schar+uint") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-schar+uintmax") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(UINT_MAX) << 0;
- QTest::newRow("signchange-scharmin+uint") << QVariant::fromValue(SCHAR_MIN) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-schar+qulonglong") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-schar+qulonglongmax") << QVariant::fromValue(schar(-1)) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("signchange-scharmin+qulonglong") << QVariant::fromValue(SCHAR_MIN) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-short+uint") << QVariant::fromValue(short(-1)) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-short+uintmax") << QVariant::fromValue(short(-1)) << QVariant::fromValue(UINT_MAX) << 0;
- QTest::newRow("signchange-shortmin+uint") << QVariant::fromValue(SHRT_MIN) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-short+qulonglong") << QVariant::fromValue(short(-1)) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-short+qulonglongmax") << QVariant::fromValue(short(-1)) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("signchange-shortmin+qulonglong") << QVariant::fromValue(SHRT_MIN) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-int+uint") << QVariant::fromValue(-1) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-int+uintmax") << QVariant::fromValue(-1) << QVariant::fromValue(UINT_MAX) << 0;
- QTest::newRow("signchange-intmin+uint") << QVariant::fromValue(INT_MIN) << QVariant::fromValue(0U) << +1;
- QTest::newRow("signchange-int+qulonglong") << QVariant::fromValue(-1) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-int+qulonglongmax") << QVariant::fromValue(-1) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("signchange-intmin+qulonglong") << QVariant::fromValue(INT_MIN) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- // no qlonglong+uint, since that should promote to qlonglong and then the comparison is signed (tested above)
- QTest::newRow("signchange-qlonglong+qulonglong") << QVariant::fromValue(Q_INT64_C(-1)) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
- QTest::newRow("signchange-qlonglong+qulonglongmax") << QVariant::fromValue(Q_INT64_C(-1)) << QVariant::fromValue(ULLONG_MAX) << 0;
- QTest::newRow("signchange-qlonglongmin+qulonglong") << QVariant::fromValue(LLONG_MIN) << QVariant::fromValue(Q_UINT64_C(0)) << +1;
-}
-
-void tst_QVariant::compareNumbers() const
-{
- QFETCH(QVariant, v1);
- QFETCH(QVariant, v2);
- QFETCH(int, expected);
-
- if (expected == -1) {
- QVERIFY(v1 < v2);
- QVERIFY(v1 <= v2);
- QVERIFY(!(v1 == v2));
- QVERIFY(!(v1 > v2));
- QVERIFY(!(v1 >= v2));
-
- QVERIFY(!(v2 < v1));
- QVERIFY(!(v2 <= v1));
- QVERIFY(!(v2 == v1));
- QVERIFY(v2 >= v1);
- QVERIFY(v2 > v1);
- } else if (expected == 0) {
- QVERIFY(!(v1 < v2));
- QVERIFY(v1 <= v2);
- QCOMPARE(v1, v2);
- QVERIFY(!(v1 > v2));
- QVERIFY(v1 >= v2);
-
- QVERIFY(!(v2 < v1));
- QVERIFY(v2 <= v1);
- QCOMPARE(v2, v1);
- QVERIFY(v2 >= v1);
- QVERIFY(!(v2 > v1));
- } else if (expected == +1) {
- QVERIFY(!(v1 < v2));
- QVERIFY(!(v1 <= v2));
- QVERIFY(!(v1 == v2));
- QVERIFY(v1 > v2);
- QVERIFY(v1 >= v2);
-
- QVERIFY(v2 < v1);
- QVERIFY(v2 <= v1);
- QVERIFY(!(v2 == v1));
- QVERIFY(!(v2 >= v1));
- QVERIFY(!(v2 > v1));
- } else {
- // unorderable (NaN)
- QVERIFY(!(v1 == v2));
- }
-}
-
void tst_QVariant::typeName_data()
{
QTest::addColumn<int>("type");
@@ -3961,8 +3618,7 @@ Q_DECLARE_METATYPE(Convertible);
struct BigConvertible {
double d;
- double dummy;
- double dummy2;
+ double dummy[sizeof(QVariant) / sizeof(double)];
operator int() const { return (int)d; }
operator double() const { return d; }
operator QString() const { return QString::number(d); }
@@ -4863,86 +4519,6 @@ void tst_QVariant::metaEnums()
METAENUMS_TEST(MetaEnumTest_Enum8_value);
}
-void tst_QVariant::compareSanity_data()
-{
- QTest::addColumn<QVariant>("value1");
- QTest::addColumn<QVariant>("value2");
-
- QTest::newRow( "int <>/== QUrl" ) << QVariant( 97 ) << QVariant(QUrl("a"));
- QTest::newRow( "int <>/== QChar" ) << QVariant( 97 ) << QVariant(QChar('a'));
- QTest::newRow( "int <>/== QString" ) << QVariant( 97 ) << QVariant(QString("a"));
- QTest::newRow( "QUrl <>/== QChar" ) << QVariant(QUrl("a")) << QVariant(QChar('a'));
- QTest::newRow( "QUrl <>/== QString" ) << QVariant(QUrl("a")) << QVariant(QString("a"));
- QTest::newRow( "QChar <>/== QString" ) << QVariant(QChar('a')) << QVariant(QString("a"));
-}
-
-void tst_QVariant::compareSanity()
-{
- QFETCH(QVariant, value1);
- QFETCH(QVariant, value2);
-
- if (value1 == value2) {
- QVERIFY(!(value1 < value2) && !(value1 > value2));
- } else {
- QVERIFY(value1 != value2);
- QVERIFY((value1 < value2) || (value1 > value2));
- }
-}
-
-static void richComparison(const QVariant& less, const QVariant& more)
-{
- QVERIFY(less.type() == more.type());
-
- QVERIFY(less < more);
- QVERIFY(!(more < less));
-
- QVERIFY(more > less);
- QVERIFY(!(less > more));
-
- QVERIFY(less <= more);
- QVERIFY(!(more <= less));
- QVERIFY(less <= less);
-
- QVERIFY(more >= less);
- QVERIFY(!(less >= more));
- QVERIFY(more >= more);
-}
-
-void tst_QVariant::compareRich()
-{
- richComparison(QUuid("{49d8ad2a-2ee8-4c3d-949f-1b5a3765ddf0}"),
- QUuid("{f6d56824-16e9-4543-a375-add2877c2d05}"));
- richComparison(QByteArray::fromRawData("a", 1),
- QByteArray::fromRawData("b", 1));
- richComparison(QStringLiteral("a"), QStringLiteral("b"));
- richComparison(QLatin1String("a"), QLatin1String("b"));
- richComparison(QChar('a'), QChar('b'));
- richComparison(QDate(2016, 7, 23), QDate(2016, 7, 24));
- richComparison(QTime(0, 0), QTime(0, 1));
- richComparison(QDateTime(QDate(2016, 7, 23), QTime(0, 0)),
- QDateTime(QDate(2016, 7, 23), QTime(0, 1)));
-
- richComparison(QStringList(), QStringList() << QStringLiteral("a"));
- richComparison(QStringList(), QStringList() << QStringLiteral("a")
- << QStringLiteral("b"));
- richComparison(QStringList() << QStringLiteral("a"),
- QStringList() << QStringLiteral("b"));
- richComparison(QStringList() << QStringLiteral("a"),
- QStringList() << QStringLiteral("b")
- << QStringLiteral("c"));
- richComparison(QStringList() << QStringLiteral("a")
- << QStringLiteral("c"),
- QStringList() << QStringLiteral("b"));
- richComparison(QStringList() << QStringLiteral("a")
- << QStringLiteral("c"),
- QStringList() << QStringLiteral("b")
- << QStringLiteral("d"));
- richComparison(QStringList() << QStringLiteral("a")
- << QStringLiteral("c"),
- QStringList() << QStringLiteral("a")
- << QStringLiteral("d"));
-}
-
void tst_QVariant::nullConvert()
{
// Test quirks with QVariants different types of null states.
diff --git a/tests/auto/corelib/serialization/json/tst_qtjson.cpp b/tests/auto/corelib/serialization/json/tst_qtjson.cpp
index 45f815f810..4c85482c6a 100644
--- a/tests/auto/corelib/serialization/json/tst_qtjson.cpp
+++ b/tests/auto/corelib/serialization/json/tst_qtjson.cpp
@@ -52,6 +52,8 @@ private Q_SLOTS:
void testNumbers_3();
void testNumbers_4();
+ void testNumberComparisons();
+
void testObjectSimple();
void testObjectSmallKeys();
void testArraySimple();
@@ -218,26 +220,32 @@ void tst_QtJson::testNumbers()
{
int numbers[] = {
0,
- -1,
1,
+ 2,
+ -1,
+ -2,
+ (1<<25),
(1<<26),
(1<<27),
(1<<28),
+ -(1<<25),
-(1<<26),
-(1<<27),
-(1<<28),
(1<<26) - 1,
(1<<27) - 1,
(1<<28) - 1,
+ (1<<29) - 1,
-((1<<26) - 1),
-((1<<27) - 1),
- -((1<<28) - 1)
+ -((1<<28) - 1),
+ -((1<<29) - 1)
};
int n = sizeof(numbers)/sizeof(int);
QJsonArray array;
for (int i = 0; i < n; ++i)
- array.append((double)numbers[i]);
+ array.append(numbers[i]);
QByteArray serialized = QJsonDocument(array).toJson();
QJsonDocument json = QJsonDocument::fromJson(serialized);
@@ -246,8 +254,10 @@ void tst_QtJson::testNumbers()
QCOMPARE(array.size(), array2.size());
for (int i = 0; i < array.size(); ++i) {
QCOMPARE(array.at(i).type(), QJsonValue::Double);
+ QCOMPARE(array.at(i).toInt(), numbers[i]);
QCOMPARE(array.at(i).toDouble(), (double)numbers[i]);
QCOMPARE(array2.at(i).type(), QJsonValue::Double);
+ QCOMPARE(array2.at(i).toInt(), numbers[i]);
QCOMPARE(array2.at(i).toDouble(), (double)numbers[i]);
}
}
@@ -255,8 +265,10 @@ void tst_QtJson::testNumbers()
{
qint64 numbers[] = {
0,
- -1,
1,
+ 2,
+ -1,
+ -2,
(1ll<<54),
(1ll<<55),
(1ll<<56),
@@ -266,15 +278,21 @@ void tst_QtJson::testNumbers()
(1ll<<54) - 1,
(1ll<<55) - 1,
(1ll<<56) - 1,
+ (1ll<<57) - 1,
+ (1ll<<58) - 1,
+ (1ll<<59) + 1001,
-((1ll<<54) - 1),
-((1ll<<55) - 1),
- -((1ll<<56) - 1)
+ -((1ll<<56) - 1),
+ -((1ll<<57) - 1),
+ -((1ll<<58) - 1),
+ -((1ll<<59) + 1001),
};
int n = sizeof(numbers)/sizeof(qint64);
QJsonArray array;
for (int i = 0; i < n; ++i)
- array.append((double)numbers[i]);
+ array.append(QJsonValue(numbers[i]));
QByteArray serialized = QJsonDocument(array).toJson();
QJsonDocument json = QJsonDocument::fromJson(serialized);
@@ -283,8 +301,10 @@ void tst_QtJson::testNumbers()
QCOMPARE(array.size(), array2.size());
for (int i = 0; i < array.size(); ++i) {
QCOMPARE(array.at(i).type(), QJsonValue::Double);
+ QCOMPARE(array.at(i).toInteger(), numbers[i]);
QCOMPARE(array.at(i).toDouble(), (double)numbers[i]);
QCOMPARE(array2.at(i).type(), QJsonValue::Double);
+ QCOMPARE(array2.at(i).toInteger(), numbers[i]);
QCOMPARE(array2.at(i).toDouble(), (double)numbers[i]);
}
}
@@ -422,6 +442,46 @@ void tst_QtJson::testNumbers_4()
" -18446744073709552000\n"
"]\n";
QCOMPARE(json, expected);
+
+ QJsonArray array2;
+ array2 << QJsonValue(Q_INT64_C(+1000000000000000));
+ array2 << QJsonValue(Q_INT64_C(-1000000000000000));
+ array2 << QJsonValue(Q_INT64_C(+9007199254740992));
+ array2 << QJsonValue(Q_INT64_C(-9007199254740992));
+ array2 << QJsonValue(Q_INT64_C(+9223372036854775807));
+ array2 << QJsonValue(Q_INT64_C(-9223372036854775807));
+ const QByteArray json2(QJsonDocument(array2).toJson());
+ const QByteArray expected2 =
+ "[\n"
+ " 1000000000000000,\n"
+ " -1000000000000000,\n"
+ " 9007199254740992,\n"
+ " -9007199254740992,\n"
+ " 9223372036854775807,\n"
+ " -9223372036854775807\n"
+ "]\n";
+ QCOMPARE(json2, expected2);
+}
+
+void tst_QtJson::testNumberComparisons()
+{
+ // QJsonValues created using doubles only have double precision
+ QJsonValue llMinDbl(-9223372036854775807.0);
+ QJsonValue llMinPlus1Dbl(-9223372036854775806.0);
+ QCOMPARE(llMinDbl == llMinPlus1Dbl, -9223372036854775807.0 == -9223372036854775806.0); // true
+
+ // QJsonValues created using qint64 have full qint64 precision
+ QJsonValue llMin(Q_INT64_C(-9223372036854775807));
+ QJsonValue llMinPlus1(Q_INT64_C(-9223372036854775806));
+ QCOMPARE(llMin == llMinPlus1, Q_INT64_C(-9223372036854775807) == Q_INT64_C(-9223372036854775806)); // false
+
+ // The different storage formats should be able to compare as their C++ versions (all true)
+ QCOMPARE(llMin == llMinDbl, Q_INT64_C(-9223372036854775807) == -9223372036854775807.0);
+ QCOMPARE(llMinDbl == llMin, -9223372036854775807.0 == Q_INT64_C(-9223372036854775807));
+ QCOMPARE(llMinPlus1 == llMinPlus1Dbl, Q_INT64_C(-9223372036854775806) == -9223372036854775806.0);
+ QCOMPARE(llMinPlus1Dbl == llMinPlus1, -9223372036854775806.0 == Q_INT64_C(-9223372036854775806));
+ QCOMPARE(llMinPlus1 == llMinDbl, Q_INT64_C(-9223372036854775806) == -9223372036854775807.0);
+ QCOMPARE(llMinPlus1Dbl == llMin, -9223372036854775806.0 == Q_INT64_C(-9223372036854775807));
}
void tst_QtJson::testObjectSimple()
@@ -1162,8 +1222,8 @@ void tst_QtJson::fromVariant_data()
bool boolValue = true;
int intValue = -1;
uint uintValue = 1;
- long long longlongValue = -2;
- unsigned long long ulonglongValue = 2;
+ qlonglong longlongValue = -2;
+ qulonglong ulonglongValue = 2;
float floatValue = 3.3f;
double doubleValue = 4.4;
QString stringValue("str");
@@ -1209,7 +1269,7 @@ void tst_QtJson::fromVariant_data()
QTest::newRow("nullptr") << QVariant::fromValue(nullptr) << QJsonValue(QJsonValue::Null);
QTest::newRow("bool") << QVariant(boolValue) << QJsonValue(boolValue);
QTest::newRow("int") << QVariant(intValue) << QJsonValue(intValue);
- QTest::newRow("uint") << QVariant(uintValue) << QJsonValue(static_cast<double>(uintValue));
+ QTest::newRow("uint") << QVariant(uintValue) << QJsonValue(static_cast<qint64>(uintValue));
QTest::newRow("longlong") << QVariant(longlongValue) << QJsonValue(longlongValue);
QTest::newRow("ulonglong") << QVariant(ulonglongValue) << QJsonValue(static_cast<double>(ulonglongValue));
QTest::newRow("float") << QVariant(floatValue) << QJsonValue(floatValue);
diff --git a/tests/auto/corelib/serialization/qcborvalue_json/tst_qcborvalue_json.cpp b/tests/auto/corelib/serialization/qcborvalue_json/tst_qcborvalue_json.cpp
index 56245a7173..76f2bb924a 100644
--- a/tests/auto/corelib/serialization/qcborvalue_json/tst_qcborvalue_json.cpp
+++ b/tests/auto/corelib/serialization/qcborvalue_json/tst_qcborvalue_json.cpp
@@ -97,9 +97,12 @@ void tst_QCborValue_Json::toVariant_data()
add(1, 1, 1);
add(-1, -1, -1);
add(0., 0., 0.);
+ add(2., 2., 2.);
add(1.25, 1.25, 1.25);
add(-1.25, -1.25, -1.25);
add("Hello", "Hello", "Hello");
+ add(std::numeric_limits<qint64>::max(), std::numeric_limits<qint64>::max(), std::numeric_limits<qint64>::max());
+ add(std::numeric_limits<qint64>::min(), std::numeric_limits<qint64>::min(), std::numeric_limits<qint64>::min());
// converts to string in JSON:
add(QByteArray("Hello"), QByteArray("Hello"), "SGVsbG8");
@@ -123,14 +126,6 @@ void tst_QCborValue_Json::toVariant_data()
<< QVariant(qQNaN())
<< QJsonValue();
- // large integral values lose precision in JSON
- QTest::newRow("Integer:max") << QCborValue(std::numeric_limits<qint64>::max())
- << QVariant(std::numeric_limits<qint64>::max())
- << QJsonValue(std::numeric_limits<qint64>::max());
- QTest::newRow("Integer:min") << QCborValue(std::numeric_limits<qint64>::min())
- << QVariant(std::numeric_limits<qint64>::min())
- << QJsonValue(std::numeric_limits<qint64>::min());
-
// empty arrays and maps
add(QCborArray(), QVariantList(), QJsonArray());
add(QCborMap(), QVariantMap(), QJsonObject());
@@ -257,6 +252,10 @@ void tst_QCborValue_Json::fromJson_data()
QTest::newRow("0") << QCborValue(0) << QJsonValue(0.);
QTest::newRow("1") << QCborValue(1) << QJsonValue(1);
QTest::newRow("1.5") << QCborValue(1.5) << QJsonValue(1.5);
+ QTest::newRow("Integer:max") << QCborValue(std::numeric_limits<qint64>::max())
+ << QJsonValue(std::numeric_limits<qint64>::max());
+ QTest::newRow("Integer:min") << QCborValue(std::numeric_limits<qint64>::min())
+ << QJsonValue(std::numeric_limits<qint64>::min());
QTest::newRow("string") << QCborValue("Hello") << QJsonValue("Hello");
QTest::newRow("array") << QCborValue(QCborValue::Array) << QJsonValue(QJsonValue::Array);
QTest::newRow("map") << QCborValue(QCborValue::Map) << QJsonValue(QJsonValue::Object);
diff --git a/tests/auto/corelib/serialization/qdatastream/tst_qdatastream.cpp b/tests/auto/corelib/serialization/qdatastream/tst_qdatastream.cpp
index 8197c386c5..d402e3f63b 100644
--- a/tests/auto/corelib/serialization/qdatastream/tst_qdatastream.cpp
+++ b/tests/auto/corelib/serialization/qdatastream/tst_qdatastream.cpp
@@ -2327,6 +2327,7 @@ void tst_QDataStream::setVersion()
QDataStream latest;
QFETCH(int, vers);
+#if QT_CONFIG(shortcut)
/*
Test QKeySequence.
*/
@@ -2351,6 +2352,7 @@ void tst_QDataStream::setVersion()
}
QCOMPARE(deadbeef, 0xDEADBEEF);
}
+#endif // QT_CONFIG(shortcut)
/*
Test QPalette.
diff --git a/tests/auto/corelib/text/qbytearray/tst_qbytearray.cpp b/tests/auto/corelib/text/qbytearray/tst_qbytearray.cpp
index 48dd7a241e..e3009a78fb 100644
--- a/tests/auto/corelib/text/qbytearray/tst_qbytearray.cpp
+++ b/tests/auto/corelib/text/qbytearray/tst_qbytearray.cpp
@@ -149,36 +149,17 @@ private slots:
void stdString();
};
-static const struct StaticByteArrays {
- struct Standard {
- QByteArrayData data;
- const char string[8];
- } standard;
- struct NotNullTerminated {
- QByteArrayData data;
- const char string[8];
- } notNullTerminated;
- struct Shifted {
- QByteArrayData data;
- const char dummy; // added to change offset of string
- const char string[8];
- } shifted;
- struct ShiftedNotNullTerminated {
- QByteArrayData data;
- const char dummy; // added to change offset of string
- const char string[8];
- } shiftedNotNullTerminated;
-
-} statics = {{Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(4), "data"}
- ,{Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(4), "dataBAD"}
- ,{Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(4, sizeof(QByteArrayData) + sizeof(char)), 0, "data"}
- ,{Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(4, sizeof(QByteArrayData) + sizeof(char)), 0, "dataBAD"}
- };
-
-static const QByteArrayDataPtr staticStandard = { const_cast<QByteArrayData *>(&statics.standard.data) };
-static const QByteArrayDataPtr staticNotNullTerminated = { const_cast<QByteArrayData *>(&statics.notNullTerminated.data) };
-static const QByteArrayDataPtr staticShifted = { const_cast<QByteArrayData *>(&statics.shifted.data) };
-static const QByteArrayDataPtr staticShiftedNotNullTerminated = { const_cast<QByteArrayData *>(&statics.shiftedNotNullTerminated.data) };
+static const QArrayData staticDataFlags = { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 };
+static const QByteArray::DataPointer staticStandard = {
+ static_cast<QTypedArrayData<char> *>(const_cast<QArrayData *>(&staticDataFlags)),
+ const_cast<char *>("data"),
+ 4
+};
+static const QByteArray::DataPointer staticNotNullTerminated = {
+ static_cast<QTypedArrayData<char> *>(const_cast<QArrayData *>(&staticDataFlags)),
+ const_cast<char *>("dataBAD"),
+ 4
+};
template <class T> const T &verifyZeroTermination(const T &t) { return t; }
@@ -186,11 +167,10 @@ QByteArray verifyZeroTermination(const QByteArray &ba)
{
// This test does some evil stuff, it's all supposed to work.
- QByteArray::DataPtr baDataPtr = const_cast<QByteArray &>(ba).data_ptr();
+ QByteArray::DataPointer baDataPtr = const_cast<QByteArray &>(ba).data_ptr();
// Skip if isStatic() or fromRawData(), as those offer no guarantees
- if (baDataPtr->ref.isStatic()
- || baDataPtr->offset != QByteArray().data_ptr()->offset)
+ if (baDataPtr->isStatic() || baDataPtr->flags() & QArrayData::RawDataType)
return ba;
int baSize = ba.size();
@@ -201,7 +181,7 @@ QByteArray verifyZeroTermination(const QByteArray &ba)
.arg(baTerminator, 2, 16, QChar('0')).toLatin1();
// Skip mutating checks on shared strings
- if (baDataPtr->ref.isShared())
+ if (baDataPtr->isShared())
return ba;
const char *baData = ba.constData();
@@ -253,11 +233,11 @@ void tst_QByteArray::qChecksum_data()
QTest::addColumn<uint>("checksum");
// Examples from ISO 14443-3
- QTest::newRow("1") << QByteArray("\x00\x00") << 2U << Qt::ChecksumItuV41 << 0x1EA0U;
- QTest::newRow("2") << QByteArray("\x12\x34") << 2U << Qt::ChecksumItuV41 << 0xCF26U;
- QTest::newRow("3") << QByteArray("\x00\x00\x00") << 3U << Qt::ChecksumIso3309 << 0xC6CCU;
- QTest::newRow("4") << QByteArray("\x0F\xAA\xFF") << 3U << Qt::ChecksumIso3309 << 0xD1FCU;
- QTest::newRow("5") << QByteArray("\x0A\x12\x34\x56") << 4U << Qt::ChecksumIso3309 << 0xF62CU;
+ QTest::newRow("1") << QByteArray("\x00\x00", 2) << 2U << Qt::ChecksumItuV41 << 0x1EA0U;
+ QTest::newRow("2") << QByteArray("\x12\x34", 2) << 2U << Qt::ChecksumItuV41 << 0xCF26U;
+ QTest::newRow("3") << QByteArray("\x00\x00\x00", 3) << 3U << Qt::ChecksumIso3309 << 0xC6CCU;
+ QTest::newRow("4") << QByteArray("\x0F\xAA\xFF", 3) << 3U << Qt::ChecksumIso3309 << 0xD1FCU;
+ QTest::newRow("5") << QByteArray("\x0A\x12\x34\x56", 4) << 4U << Qt::ChecksumIso3309 << 0xF62CU;
}
void tst_QByteArray::qChecksum()
@@ -267,6 +247,7 @@ void tst_QByteArray::qChecksum()
QFETCH(Qt::ChecksumType, standard);
QFETCH(uint, checksum);
+ QCOMPARE(data.length(), int(len));
if (standard == Qt::ChecksumIso3309) {
QCOMPARE(::qChecksum(data.constData(), len), static_cast<quint16>(checksum));
}
@@ -1054,9 +1035,7 @@ void tst_QByteArray::prependExtended_data()
QTest::addColumn<QByteArray>("array");
QTest::newRow("literal") << QByteArray(QByteArrayLiteral("data"));
QTest::newRow("standard") << QByteArray(staticStandard);
- QTest::newRow("shifted") << QByteArray(staticShifted);
QTest::newRow("notNullTerminated") << QByteArray(staticNotNullTerminated);
- QTest::newRow("shiftedNotNullTerminated") << QByteArray(staticShiftedNotNullTerminated);
QTest::newRow("non static data") << QByteArray("data");
QTest::newRow("from raw data") << QByteArray::fromRawData("data", 4);
QTest::newRow("from raw data not terminated") << QByteArray::fromRawData("dataBAD", 4);
@@ -2122,21 +2101,13 @@ void tst_QByteArray::repeated_data() const
<< QByteArray(staticStandard)
<< QByteArray("datadatadatadata")
<< 4;
- QTest::newRow("static shifted not null terminated")
- << QByteArray(staticShiftedNotNullTerminated)
- << QByteArray("datadatadatadata")
- << 4;
- QTest::newRow("static shifted")
- << QByteArray(staticShifted)
- << QByteArray("datadatadatadata")
- << 4;
}
void tst_QByteArray::byteRefDetaching() const
{
{
QByteArray str = "str";
- QByteArray copy;
+ QByteArray copy = str;
copy[0] = 'S';
QCOMPARE(str, QByteArray("str"));
@@ -2266,7 +2237,7 @@ void tst_QByteArray::movablity()
const int newSize = size + 2;
const bool newIsEmpty = false;
const bool newIsNull = false;
- const int newCapacity = 16;
+ const int newCapacity = memSpace.capacity();
// move back memSpace -> array
array.~QByteArray();
@@ -2301,8 +2272,7 @@ void tst_QByteArray::literals()
QVERIFY(str.length() == 4);
QVERIFY(str == "abcd");
- QVERIFY(str.data_ptr()->ref.isStatic());
- QVERIFY(str.data_ptr()->offset == sizeof(QByteArrayData));
+ QVERIFY(str.data_ptr()->isStatic());
const char *s = str.constData();
QByteArray str2 = str;
diff --git a/tests/auto/corelib/text/qstring/tst_qstring.cpp b/tests/auto/corelib/text/qstring/tst_qstring.cpp
index f86fbc5988..84e12cd46b 100644
--- a/tests/auto/corelib/text/qstring/tst_qstring.cpp
+++ b/tests/auto/corelib/text/qstring/tst_qstring.cpp
@@ -607,11 +607,10 @@ QString verifyZeroTermination(const QString &str)
{
// This test does some evil stuff, it's all supposed to work.
- QString::DataPtr strDataPtr = const_cast<QString &>(str).data_ptr();
+ QString::DataPointer strDataPtr = const_cast<QString &>(str).data_ptr();
// Skip if isStatic() or fromRawData(), as those offer no guarantees
- if (strDataPtr->ref.isStatic()
- || strDataPtr->offset != QString().data_ptr()->offset)
+ if (strDataPtr->isStatic() || !strDataPtr->isMutable())
return str;
int strSize = str.size();
@@ -622,7 +621,7 @@ QString verifyZeroTermination(const QString &str)
.arg(strTerminator.unicode(), 4, 16, QChar('0'));
// Skip mutating checks on shared strings
- if (strDataPtr->ref.isShared())
+ if (strDataPtr->isShared())
return str;
const QChar *strData = str.constData();
@@ -986,28 +985,6 @@ void tst_QString::acc_01()
f[7]='F';
QCOMPARE(text[7],'!');
- a="";
- a[0]='A';
- QCOMPARE(a, QLatin1String("A"));
- QCOMPARE(a.length(),1);
- a[1]='B';
- QCOMPARE(a, QLatin1String("AB"));
- QCOMPARE(a.length(),2);
- a[2]='C';
- QCOMPARE(a, QLatin1String("ABC"));
- QCOMPARE(a.length(),3);
- a = QString();
- QVERIFY(a.isNull());
- a[0]='A';
- QCOMPARE(a, QLatin1String("A"));
- QCOMPARE(a.length(),1);
- a[1]='B';
- QCOMPARE(a, QLatin1String("AB"));
- QCOMPARE(a.length(),2);
- a[2]='C';
- QCOMPARE(a, QLatin1String("ABC"));
- QCOMPARE(a.length(),3);
-
a="123";
b="456";
a[0]=a[1];
@@ -4071,8 +4048,9 @@ void tst_QString::setRawData()
QVERIFY(cstr.constData() == ptr);
QVERIFY(cstr == QString(ptr, 1));
+ QSKIP("This is currently not working.");
// This actually tests the recycling of the shared data object
- QString::DataPtr csd = cstr.data_ptr();
+ QString::DataPointer csd = cstr.data_ptr();
cstr.setRawData(ptr2, 1);
QVERIFY(cstr.isDetached());
QVERIFY(cstr.constData() == ptr2);
@@ -6418,7 +6396,7 @@ void tst_QString::QCharRefDetaching() const
{
{
QString str = QString::fromLatin1("str");
- QString copy;
+ QString copy = str;
copy[0] = QLatin1Char('S');
QCOMPARE(str, QString::fromLatin1("str"));
@@ -6639,8 +6617,7 @@ void tst_QString::literals()
QVERIFY(str.length() == 4);
QVERIFY(str == QLatin1String("abcd"));
- QVERIFY(str.data_ptr()->ref.isStatic());
- QVERIFY(str.data_ptr()->offset == sizeof(QStringData));
+ QVERIFY(str.data_ptr()->isStatic());
const QChar *s = str.constData();
QString str2 = str;
diff --git a/tests/auto/corelib/text/qstringref/tst_qstringref.cpp b/tests/auto/corelib/text/qstringref/tst_qstringref.cpp
index 6f01947131..20d5426bf7 100644
--- a/tests/auto/corelib/text/qstringref/tst_qstringref.cpp
+++ b/tests/auto/corelib/text/qstringref/tst_qstringref.cpp
@@ -87,6 +87,7 @@ private slots:
void mid();
void split_data();
void split();
+ void nullToString();
};
static QStringRef emptyRef()
@@ -2177,6 +2178,18 @@ void tst_QStringRef::split()
}
}
+void tst_QStringRef::nullToString()
+{
+ QStringRef nullRef;
+ QVERIFY(nullRef.isNull());
+ QVERIFY(nullRef.toString().isNull());
+
+ QString str;
+ nullRef = &str;
+ QVERIFY(nullRef.isNull());
+ QVERIFY(nullRef.toString().isNull());
+}
+
QTEST_APPLESS_MAIN(tst_QStringRef)
#include "tst_qstringref.moc"
diff --git a/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp b/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
index bef491d5f0..22ee7d17b7 100644
--- a/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
+++ b/tests/auto/corelib/thread/qatomicint/tst_qatomicint.cpp
@@ -237,28 +237,23 @@ template <typename T> struct TypeInStruct { T type; };
void tst_QAtomicInt::alignment()
{
-#ifdef Q_ALIGNOF
- // this will cause a build error if the alignment isn't the same
- char dummy1[Q_ALIGNOF(QBasicAtomicInt) == Q_ALIGNOF(TypeInStruct<int>) ? 1 : -1];
- char dummy2[Q_ALIGNOF(QAtomicInt) == Q_ALIGNOF(TypeInStruct<int>) ? 1 : -1];
- (void)dummy1; (void)dummy2;
+ Q_STATIC_ASSERT(alignof(QBasicAtomicInt) == alignof(TypeInStruct<int>));
+ Q_STATIC_ASSERT(alignof(QBasicAtomicInt) == alignof(TypeInStruct<int>));
#ifdef Q_ATOMIC_INT32_IS_SUPPORTED
- QCOMPARE(Q_ALIGNOF(QBasicAtomicInteger<int>), Q_ALIGNOF(TypeInStruct<int>));
+ QCOMPARE(alignof(QBasicAtomicInteger<int>), alignof(TypeInStruct<int>));
#endif
#ifdef Q_ATOMIC_INT16_IS_SUPPORTED
- QCOMPARE(Q_ALIGNOF(QBasicAtomicInteger<short>), Q_ALIGNOF(TypeInStruct<short>));
+ QCOMPARE(alignof(QBasicAtomicInteger<short>), alignof(TypeInStruct<short>));
#endif
#ifdef Q_ATOMIC_INT8_IS_SUPPORTED
- QCOMPARE(Q_ALIGNOF(QBasicAtomicInteger<char>), Q_ALIGNOF(TypeInStruct<char>));
+ QCOMPARE(alignof(QBasicAtomicInteger<char>), alignof(TypeInStruct<char>));
#endif
#ifdef Q_ATOMIC_INT64_IS_SUPPORTED
- QCOMPARE(Q_ALIGNOF(QBasicAtomicInteger<qlonglong>), Q_ALIGNOF(TypeInStruct<qlonglong>));
-#endif
-
+ QCOMPARE(alignof(QBasicAtomicInteger<qlonglong>), alignof(TypeInStruct<qlonglong>));
#endif
}
diff --git a/tests/auto/corelib/thread/qatomicpointer/tst_qatomicpointer.cpp b/tests/auto/corelib/thread/qatomicpointer/tst_qatomicpointer.cpp
index a699cf6202..9e12e7ccce 100644
--- a/tests/auto/corelib/thread/qatomicpointer/tst_qatomicpointer.cpp
+++ b/tests/auto/corelib/thread/qatomicpointer/tst_qatomicpointer.cpp
@@ -108,11 +108,7 @@ void tst_QAtomicPointer::warningFree()
void tst_QAtomicPointer::alignment()
{
-#ifdef Q_ALIGNOF
- // this will cause a build error if the alignment isn't the same
- char dummy[Q_ALIGNOF(QBasicAtomicPointer<void>) == Q_ALIGNOF(void*) ? 1 : -1];
- (void)dummy;
-#endif
+ Q_STATIC_ASSERT(alignof(QBasicAtomicPointer<void>) == alignof(void*));
}
void tst_QAtomicPointer::constructor()
diff --git a/tests/auto/corelib/thread/qfuture/qfuture.pro b/tests/auto/corelib/thread/qfuture/qfuture.pro
index 1f21130af7..fe097edf20 100644
--- a/tests/auto/corelib/thread/qfuture/qfuture.pro
+++ b/tests/auto/corelib/thread/qfuture/qfuture.pro
@@ -2,5 +2,4 @@ CONFIG += testcase
TARGET = tst_qfuture
QT = core core-private testlib
SOURCES = tst_qfuture.cpp
-DEFINES += QT_STRICT_ITERATORS
DEFINES -= QT_NO_JAVA_STYLE_ITERATORS
diff --git a/tests/auto/corelib/thread/qresultstore/qresultstore.pro b/tests/auto/corelib/thread/qresultstore/qresultstore.pro
index bbebe0976b..80e79b1c1a 100644
--- a/tests/auto/corelib/thread/qresultstore/qresultstore.pro
+++ b/tests/auto/corelib/thread/qresultstore/qresultstore.pro
@@ -2,4 +2,3 @@ CONFIG += testcase
TARGET = tst_qresultstore
QT = core-private testlib
SOURCES = tst_qresultstore.cpp
-DEFINES += QT_STRICT_ITERATORS
diff --git a/tests/auto/corelib/tools/collections/collections.pro b/tests/auto/corelib/tools/collections/collections.pro
index e0f9f0a0ea..d5e4e226b5 100644
--- a/tests/auto/corelib/tools/collections/collections.pro
+++ b/tests/auto/corelib/tools/collections/collections.pro
@@ -5,5 +5,4 @@ QT = core testlib
# This test does not work with strict iterators
DEFINES -= QT_NO_LINKED_LIST
-DEFINES -= QT_STRICT_ITERATORS
DEFINES -= QT_NO_JAVA_STYLE_ITERATORS
diff --git a/tests/auto/corelib/tools/collections/tst_collections.cpp b/tests/auto/corelib/tools/collections/tst_collections.cpp
index e79a4dba29..023b22b4ba 100644
--- a/tests/auto/corelib/tools/collections/tst_collections.cpp
+++ b/tests/auto/corelib/tools/collections/tst_collections.cpp
@@ -84,10 +84,6 @@ void foo()
#include "qvector.h"
#include "qqueue.h"
-QT_BEGIN_NAMESPACE
-template class QList<int>;
-QT_END_NAMESPACE
-
class tst_Collections : public QObject
{
Q_OBJECT
@@ -551,19 +547,12 @@ void tst_Collections::list()
list << "foo" << "bar";
QVERIFY(!list.isEmpty());
- list.insert(-1, "lessthanzero");
- QCOMPARE(list.at(0), QString("lessthanzero"));
-
list.insert(0, "atzero");
QCOMPARE(list.at(0), QString("atzero"));
int listCount = list.count();
list.insert(listCount, "atcount");
QCOMPARE(list.at(listCount), QString("atcount"));
-
- listCount = list.count();
- list.insert(listCount + 1, "beyondcount");
- QCOMPARE(list.at(listCount), QString("beyondcount"));
}
{
@@ -2337,12 +2326,6 @@ void populate(QLinkedList<int> &container)
}
template <>
-void populate(QVector<int> &container)
-{
- container << 1 << 2 << 4 << 8;
-}
-
-template <>
void populate(QMap<int, int> &container)
{
container.insert(1, 1);
@@ -3214,9 +3197,7 @@ void tst_Collections::forwardDeclared()
{ typedef QSet<T1> C; C *x = 0; /* C::iterator i; */ C::const_iterator j; Q_UNUSED(x) }
}
-#if defined(Q_ALIGNOF) && defined(Q_DECL_ALIGN)
-
-class Q_DECL_ALIGN(4) Aligned4
+class alignas(4) Aligned4
{
char i;
public:
@@ -3228,7 +3209,7 @@ public:
inline bool operator<(const Aligned4 &other) const { return i < other.i; }
friend inline int qHash(const Aligned4 &a) { return qHash(a.i); }
};
-Q_STATIC_ASSERT(Q_ALIGNOF(Aligned4) % 4 == 0);
+Q_STATIC_ASSERT(alignof(Aligned4) % 4 == 0);
#if defined(Q_PROCESSOR_ARM)
# if defined(Q_COMPILER_ALIGNAS) && defined(__BIGGEST_ALIGNMENT__)
@@ -3242,7 +3223,7 @@ Q_STATIC_ASSERT(Q_ALIGNOF(Aligned4) % 4 == 0);
# define BIGGEST_ALIGNMENT_TO_TEST 128
#endif
-class Q_DECL_ALIGN(BIGGEST_ALIGNMENT_TO_TEST) AlignedBiggest
+class alignas(BIGGEST_ALIGNMENT_TO_TEST) AlignedBiggest
{
char i;
public:
@@ -3254,7 +3235,7 @@ public:
inline bool operator<(const AlignedBiggest &other) const { return i < other.i; }
friend inline int qHash(const AlignedBiggest &a) { return qHash(a.i); }
};
-Q_STATIC_ASSERT(Q_ALIGNOF(AlignedBiggest) % BIGGEST_ALIGNMENT_TO_TEST == 0);
+Q_STATIC_ASSERT(alignof(AlignedBiggest) % BIGGEST_ALIGNMENT_TO_TEST == 0);
template<typename C>
void testVectorAlignment()
@@ -3325,13 +3306,6 @@ void tst_Collections::alignment()
testAssociativeContainerAlignment<QHash<AlignedBiggest, AlignedBiggest> >();
}
-#else
-void tst_Collections::alignment()
-{
- QSKIP("Compiler doesn't support necessary extension keywords");
-}
-#endif
-
#ifndef QT_NO_TEMPLATE_TEMPLATE_PARAMETERS
template<template<class> class C>
@@ -3510,9 +3484,6 @@ void tst_Collections::foreach_2()
QCOMPARE(varl1.count(), intlist.count());
QCOMPARE(varl2.count(), intlist.count());
QCOMPARE(varl3.count(), intlist.count());
- foreach_test_arrays(varl1);
- foreach_test_arrays(varl2);
- foreach_test_arrays(varl3);
QVarLengthArray<QString> varl4;
QVarLengthArray<QString, 3> varl5;
@@ -3525,9 +3496,6 @@ void tst_Collections::foreach_2()
QCOMPARE(varl4.count(), strlist.count());
QCOMPARE(varl5.count(), strlist.count());
QCOMPARE(varl6.count(), strlist.count());
- foreach_test_arrays(varl4);
- foreach_test_arrays(varl5);
- foreach_test_arrays(varl6);
}
struct IntOrString
@@ -3615,30 +3583,8 @@ template<class Container> void insert_remove_loop_impl()
}
-//Add insert(int, int, T) so it has the same interface as QVector and QVarLengthArray for the test.
template<typename T>
-struct ExtList : QList<T> {
- using QList<T>::insert;
- void insert(int before, int n, const T&x) {
- while (n--) {
- this->insert(before, x );
- }
- }
- void insert(typename QList<T>::iterator before, int n, const T&x) {
- while (n--) {
- before = this->insert(before, x);
- }
- }
-
- void remove(int i) {
- this->removeAt(i);
- }
- void remove(int i, int n) {
- while (n--) {
- this->removeAt(i);
- }
- }
-};
+using ExtList = QList<T>;
void tst_Collections::insert_remove_loop()
{
diff --git a/tests/auto/corelib/tools/containerapisymmetry/containerapisymmetry.pro b/tests/auto/corelib/tools/containerapisymmetry/containerapisymmetry.pro
index e46d51761e..efdb7fc2df 100644
--- a/tests/auto/corelib/tools/containerapisymmetry/containerapisymmetry.pro
+++ b/tests/auto/corelib/tools/containerapisymmetry/containerapisymmetry.pro
@@ -3,6 +3,4 @@ TARGET = tst_containerapisymmetry
SOURCES += tst_containerapisymmetry.cpp
QT = core testlib
-# This test does not work with strict iterators
-DEFINES -= QT_STRICT_ITERATORS
DEFINES -= QT_NO_LINKED_LIST
diff --git a/tests/auto/corelib/tools/containerapisymmetry/tst_containerapisymmetry.cpp b/tests/auto/corelib/tools/containerapisymmetry/tst_containerapisymmetry.cpp
index 88c0c5055c..0e4517e740 100644
--- a/tests/auto/corelib/tools/containerapisymmetry/tst_containerapisymmetry.cpp
+++ b/tests/auto/corelib/tools/containerapisymmetry/tst_containerapisymmetry.cpp
@@ -580,9 +580,6 @@ template<typename ... T>
struct ContainerDuplicatedValuesStrategy<VarLengthArray<T...>> : ContainerAcceptsDuplicateValues {};
template<typename ... T>
-struct ContainerDuplicatedValuesStrategy<QList<T...>> : ContainerAcceptsDuplicateValues {};
-
-template<typename ... T>
struct ContainerDuplicatedValuesStrategy<std::list<T...>> : ContainerAcceptsDuplicateValues {};
#if COMPILER_HAS_STDLIB_INCLUDE(<forward_list>)
@@ -798,8 +795,6 @@ template <> QStringView make(int size) { return QStringView(s_string).left(siz
template <> QLatin1String make(int size) { return QLatin1String("\1\2\3\4\5\6\7", size); }
template <typename T> T clean(T &&t) { return std::forward<T>(t); }
-inline QChar clean(QCharRef ch) { return ch; }
-inline char clean(QByteRef ch) { return ch; }
inline char clean(QLatin1Char ch) { return ch.toLatin1(); }
template <typename Container>
diff --git a/tests/auto/corelib/tools/qarraydata/simplevector.h b/tests/auto/corelib/tools/qarraydata/simplevector.h
index 9dd8b05796..94cee5d887 100644
--- a/tests/auto/corelib/tools/qarraydata/simplevector.h
+++ b/tests/auto/corelib/tools/qarraydata/simplevector.h
@@ -76,25 +76,32 @@ public:
{
}
- explicit SimpleVector(Data *ptr)
- : d(ptr)
+ template <size_t N>
+ explicit SimpleVector(QStaticArrayData<T, N> &ptr)
+ : d(static_cast<Data *>(&ptr.header), ptr.data, N)
+ {
+ }
+
+ SimpleVector(Data *header, T *data, size_t len = 0)
+ : d(header, data, len)
+ {
+ }
+
+ explicit SimpleVector(QPair<Data*, T*> ptr, size_t len = 0)
+ : d(ptr, len)
{
}
- bool empty() const { return d->size == 0; }
+ bool empty() const { return d.size == 0; }
bool isNull() const { return d.isNull(); }
bool isEmpty() const { return this->empty(); }
- bool isStatic() const { return d->ref.isStatic(); }
- bool isShared() const { return d->ref.isShared(); }
+ bool isStatic() const { return d->isStatic(); }
+ bool isShared() const { return d->isShared(); }
bool isSharedWith(const SimpleVector &other) const { return d == other.d; }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- bool isSharable() const { return d->ref.isSharable(); }
- void setSharable(bool sharable) { d.setSharable(sharable); }
-#endif
- size_t size() const { return d->size; }
- size_t capacity() const { return d->alloc; }
+ size_t size() const { return d.size; }
+ size_t capacity() const { return d->constAllocatedCapacity(); }
iterator begin() { detach(); return d->begin(); }
iterator end() { detach(); return d->end(); }
@@ -143,10 +150,10 @@ public:
return;
if (n <= capacity()) {
- if (d->capacityReserved)
+ if (d->flags() & Data::CapacityReserved)
return;
- if (!d->ref.isShared()) {
- d->capacityReserved = 1;
+ if (!d->isShared()) {
+ d->flags() |= Data::CapacityReserved;
return;
}
}
@@ -163,7 +170,7 @@ public:
if (size() == newSize)
return;
- if (d.needsDetach() || newSize > capacity()) {
+ if (d->needsDetach() || newSize > capacity()) {
SimpleVector detached(Data::allocate(
d->detachCapacity(newSize), d->detachFlags()));
if (newSize) {
@@ -199,11 +206,11 @@ public:
return;
T *const begin = d->begin();
- if (d.needsDetach()
+ if (d->needsDetach()
|| capacity() - size() < size_t(last - first)) {
SimpleVector detached(Data::allocate(
d->detachCapacity(size() + (last - first)),
- d->detachFlags() | Data::Grow));
+ d->detachFlags() | Data::GrowsForward));
detached.d->copyAppend(first, last);
detached.d->copyAppend(begin, begin + d->size);
@@ -220,11 +227,11 @@ public:
if (first == last)
return;
- if (d.needsDetach()
+ if (d->needsDetach()
|| capacity() - size() < size_t(last - first)) {
SimpleVector detached(Data::allocate(
d->detachCapacity(size() + (last - first)),
- d->detachFlags() | Data::Grow));
+ d->detachFlags() | Data::GrowsForward));
if (d->size) {
const T *const begin = constBegin();
@@ -260,11 +267,11 @@ public:
const iterator begin = d->begin();
const iterator where = begin + position;
const iterator end = begin + d->size;
- if (d.needsDetach()
+ if (d->needsDetach()
|| capacity() - size() < size_t(last - first)) {
SimpleVector detached(Data::allocate(
d->detachCapacity(size() + (last - first)),
- d->detachFlags() | Data::Grow));
+ d->detachFlags() | Data::GrowsForward));
if (position)
detached.d->copyAppend(begin, where);
@@ -298,7 +305,7 @@ public:
const T *const begin = d->begin();
const T *const end = begin + d->size;
- if (d.needsDetach()) {
+ if (d->needsDetach()) {
SimpleVector detached(Data::allocate(
d->detachCapacity(size() - (last - first)),
d->detachFlags()));
@@ -332,7 +339,7 @@ public:
}
static SimpleVector fromRawData(const T *data, size_t size,
- QArrayData::AllocationOptions options = Data::Default)
+ QArrayData::ArrayOptions options = Data::DefaultRawFlags)
{
return SimpleVector(Data::fromRawData(data, size, options));
}
diff --git a/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp b/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp
index 25e2f21d03..1366eebf97 100644
--- a/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp
+++ b/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp
@@ -37,11 +37,8 @@ struct SharedNullVerifier
{
SharedNullVerifier()
{
- Q_ASSERT(QArrayData::shared_null[0].ref.isStatic());
- Q_ASSERT(QArrayData::shared_null[0].ref.isShared());
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- Q_ASSERT(QArrayData::shared_null[0].ref.isSharable());
-#endif
+ Q_ASSERT(QArrayData::shared_null[0].isStatic());
+ Q_ASSERT(QArrayData::shared_null[0].isShared());
}
};
@@ -59,7 +56,6 @@ class tst_QArrayData : public QObject
private slots:
void referenceCounting();
void sharedNullEmpty();
- void staticData();
void simpleVector();
void simpleVectorReserve_data();
void simpleVectorReserve();
@@ -73,8 +69,6 @@ private slots:
void gccBug43247();
void arrayOps();
void arrayOps2();
- void setSharable_data();
- void setSharable();
void fromRawData_data();
void fromRawData();
void literals();
@@ -89,70 +83,42 @@ void tst_QArrayData::referenceCounting()
{
{
// Reference counting initialized to 1 (owned)
- QArrayData array = { { Q_BASIC_ATOMIC_INITIALIZER(1) }, 0, 0, 0, 0 };
+ QArrayData array = { Q_BASIC_ATOMIC_INITIALIZER(1), QArrayData::DefaultRawFlags, 0 };
- QCOMPARE(array.ref.atomic.loadRelaxed(), 1);
+ QCOMPARE(array.ref_.loadRelaxed(), 1);
- QVERIFY(!array.ref.isStatic());
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(array.ref.isSharable());
-#endif
+ QVERIFY(!array.isStatic());
- QVERIFY(array.ref.ref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 2);
+ QVERIFY(array.ref());
+ QCOMPARE(array.ref_.loadRelaxed(), 2);
- QVERIFY(array.ref.deref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 1);
+ QVERIFY(array.deref());
+ QCOMPARE(array.ref_.loadRelaxed(), 1);
- QVERIFY(array.ref.ref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 2);
+ QVERIFY(array.ref());
+ QCOMPARE(array.ref_.loadRelaxed(), 2);
- QVERIFY(array.ref.deref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 1);
+ QVERIFY(array.deref());
+ QCOMPARE(array.ref_.loadRelaxed(), 1);
- QVERIFY(!array.ref.deref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 0);
+ QVERIFY(!array.deref());
+ QCOMPARE(array.ref_.loadRelaxed(), 0);
// Now would be a good time to free/release allocated data
}
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- {
- // Reference counting initialized to 0 (non-sharable)
- QArrayData array = { { Q_BASIC_ATOMIC_INITIALIZER(0) }, 0, 0, 0, 0 };
-
- QCOMPARE(array.ref.atomic.loadRelaxed(), 0);
-
- QVERIFY(!array.ref.isStatic());
- QVERIFY(!array.ref.isSharable());
-
- QVERIFY(!array.ref.ref());
- // Reference counting fails, data should be copied
- QCOMPARE(array.ref.atomic.loadRelaxed(), 0);
-
- QVERIFY(!array.ref.deref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), 0);
-
- // Free/release data
- }
-#endif
-
{
// Reference counting initialized to -1 (static read-only data)
- QArrayData array = { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, 0, 0 };
+ QArrayData array = { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 };
- QCOMPARE(array.ref.atomic.loadRelaxed(), -1);
+ QCOMPARE(array.ref_.loadRelaxed(), -1);
- QVERIFY(array.ref.isStatic());
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(array.ref.isSharable());
-#endif
+ QVERIFY(array.isStatic());
- QVERIFY(array.ref.ref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), -1);
+ QVERIFY(array.ref());
+ QCOMPARE(array.ref_.loadRelaxed(), -1);
- QVERIFY(array.ref.deref());
- QCOMPARE(array.ref.atomic.loadRelaxed(), -1);
+ QVERIFY(array.deref());
+ QCOMPARE(array.ref_.loadRelaxed(), -1);
}
}
@@ -160,74 +126,39 @@ void tst_QArrayData::referenceCounting()
void tst_QArrayData::sharedNullEmpty()
{
QArrayData *null = const_cast<QArrayData *>(QArrayData::shared_null);
- QArrayData *empty = QArrayData::allocate(1, Q_ALIGNOF(QArrayData), 0);
-
- QVERIFY(null->ref.isStatic());
- QVERIFY(null->ref.isShared());
+ QArrayData *empty;
+ QArrayData::allocate(&empty, 1, alignof(QArrayData), 0);
- QVERIFY(empty->ref.isStatic());
- QVERIFY(empty->ref.isShared());
+ QVERIFY(null->isStatic());
+ QVERIFY(null->isShared());
- QCOMPARE(null->ref.atomic.loadRelaxed(), -1);
- QCOMPARE(empty->ref.atomic.loadRelaxed(), -1);
+ QVERIFY(empty->isStatic());
+ QVERIFY(empty->isShared());
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(null->ref.isSharable());
- QVERIFY(empty->ref.isSharable());
-#endif
+ QCOMPARE(null->ref_.loadRelaxed(), -1);
+ QCOMPARE(empty->ref_.loadRelaxed(), -1);
- QVERIFY(null->ref.ref());
- QVERIFY(empty->ref.ref());
+ QCOMPARE(null->ref_.loadRelaxed(), -1);
+ QCOMPARE(empty->ref_.loadRelaxed(), -1);
- QCOMPARE(null->ref.atomic.loadRelaxed(), -1);
- QCOMPARE(empty->ref.atomic.loadRelaxed(), -1);
+ QVERIFY(null->deref());
+ QVERIFY(empty->deref());
- QVERIFY(null->ref.deref());
- QVERIFY(empty->ref.deref());
-
- QCOMPARE(null->ref.atomic.loadRelaxed(), -1);
- QCOMPARE(empty->ref.atomic.loadRelaxed(), -1);
+ QCOMPARE(null->ref_.loadRelaxed(), -1);
+ QCOMPARE(empty->ref_.loadRelaxed(), -1);
QVERIFY(null != empty);
- QCOMPARE(null->size, 0);
- QCOMPARE(null->alloc, 0u);
- QCOMPARE(null->capacityReserved, 0u);
+ QCOMPARE(null->allocatedCapacity(), size_t(0));
- QCOMPARE(empty->size, 0);
- QCOMPARE(empty->alloc, 0u);
- QCOMPARE(empty->capacityReserved, 0u);
-}
-
-void tst_QArrayData::staticData()
-{
- QStaticArrayData<char, 10> charArray = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(char, 10),
- { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }
- };
- QStaticArrayData<int, 10> intArray = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(int, 10),
- { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
- };
- QStaticArrayData<double, 10> doubleArray = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(double, 10),
- { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f }
- };
-
- QCOMPARE(charArray.header.size, 10);
- QCOMPARE(intArray.header.size, 10);
- QCOMPARE(doubleArray.header.size, 10);
-
- QCOMPARE(charArray.header.data(), reinterpret_cast<void *>(&charArray.data));
- QCOMPARE(intArray.header.data(), reinterpret_cast<void *>(&intArray.data));
- QCOMPARE(doubleArray.header.data(), reinterpret_cast<void *>(&doubleArray.data));
+ QCOMPARE(empty->allocatedCapacity(), size_t(0));
}
void tst_QArrayData::simpleVector()
{
- QArrayData data0 = { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, 0, 0 };
+ QArrayData data0 = { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 };
QStaticArrayData<int, 7> data1 = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(int, 7),
+ { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 },
{ 0, 1, 2, 3, 4, 5, 6 }
};
@@ -235,10 +166,10 @@ void tst_QArrayData::simpleVector()
SimpleVector<int> v1;
SimpleVector<int> v2(v1);
- SimpleVector<int> v3(static_cast<QTypedArrayData<int> *>(&data0));
- SimpleVector<int> v4(static_cast<QTypedArrayData<int> *>(&data1.header));
- SimpleVector<int> v5(static_cast<QTypedArrayData<int> *>(&data0));
- SimpleVector<int> v6(static_cast<QTypedArrayData<int> *>(&data1.header));
+ SimpleVector<int> v3(static_cast<QTypedArrayData<int> *>(&data0), 0, 0);
+ SimpleVector<int> v4(data1);
+ SimpleVector<int> v5(static_cast<QTypedArrayData<int> *>(&data0), 0, 0);
+ SimpleVector<int> v6(data1);
SimpleVector<int> v7(10, 5);
SimpleVector<int> v8(array, array + sizeof(array)/sizeof(*array));
@@ -302,17 +233,6 @@ void tst_QArrayData::simpleVector()
QVERIFY(!v7.isShared());
QVERIFY(!v8.isShared());
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(v1.isSharable());
- QVERIFY(v2.isSharable());
- QVERIFY(v3.isSharable());
- QVERIFY(v4.isSharable());
- QVERIFY(v5.isSharable());
- QVERIFY(v6.isSharable());
- QVERIFY(v7.isSharable());
- QVERIFY(v8.isSharable());
-#endif
-
QVERIFY(v1.isSharedWith(v2));
QVERIFY(v1.isSharedWith(v3));
QVERIFY(v1.isSharedWith(v4));
@@ -494,71 +414,6 @@ void tst_QArrayData::simpleVector()
for (int i = 0; i < 120; ++i)
QCOMPARE(v1[i], v8[i % 10]);
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- {
- v7.setSharable(true);
- QVERIFY(v7.isSharable());
-
- SimpleVector<int> copy1(v7);
- QVERIFY(copy1.isSharedWith(v7));
-
- v7.setSharable(false);
- QVERIFY(!v7.isSharable());
-
- QVERIFY(!copy1.isSharedWith(v7));
- QCOMPARE(v7.size(), copy1.size());
- for (size_t i = 0; i < copy1.size(); ++i)
- QCOMPARE(v7[i], copy1[i]);
-
- SimpleVector<int> clone(v7);
- QVERIFY(!clone.isSharedWith(v7));
- QCOMPARE(clone.size(), copy1.size());
- for (size_t i = 0; i < copy1.size(); ++i)
- QCOMPARE(clone[i], copy1[i]);
-
- v7.setSharable(true);
- QVERIFY(v7.isSharable());
-
- SimpleVector<int> copy2(v7);
- QVERIFY(copy2.isSharedWith(v7));
- }
-
- {
- SimpleVector<int> null;
- SimpleVector<int> empty(0, 5);
-
- QVERIFY(null.isSharable());
- QVERIFY(empty.isSharable());
-
- null.setSharable(true);
- empty.setSharable(true);
-
- QVERIFY(null.isSharable());
- QVERIFY(empty.isSharable());
-
- QVERIFY(null.isEmpty());
- QVERIFY(empty.isEmpty());
-
- null.setSharable(false);
- empty.setSharable(false);
-
- QVERIFY(!null.isSharable());
- QVERIFY(!empty.isSharable());
-
- QVERIFY(null.isEmpty());
- QVERIFY(empty.isEmpty());
-
- null.setSharable(true);
- empty.setSharable(true);
-
- QVERIFY(null.isSharable());
- QVERIFY(empty.isSharable());
-
- QVERIFY(null.isEmpty());
- QVERIFY(empty.isEmpty());
- }
-#endif
}
Q_DECLARE_METATYPE(SimpleVector<int>)
@@ -574,11 +429,13 @@ void tst_QArrayData::simpleVectorReserve_data()
QTest::newRow("non-empty") << SimpleVector<int>(5, 42) << size_t(5) << size_t(5);
static const QStaticArrayData<int, 15> array = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(int, 15),
+ { Q_BASIC_ATOMIC_INITIALIZER(-1), QArrayData::StaticDataFlags, 0 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } };
- QArrayDataPointerRef<int> p = {
+ const QArrayDataPointerRef<int> p = {
static_cast<QTypedArrayData<int> *>(
- const_cast<QArrayData *>(&array.header)) };
+ const_cast<QArrayData *>(&array.header)),
+ const_cast<int *>(array.data),
+ sizeof(array.data) / sizeof(array.data[0]) };
QTest::newRow("static") << SimpleVector<int>(p) << size_t(0) << size_t(15);
QTest::newRow("raw-data") << SimpleVector<int>::fromRawData(array.data, 15) << size_t(0) << size_t(15);
@@ -641,15 +498,14 @@ struct Deallocator
};
Q_DECLARE_METATYPE(const QArrayData *)
-Q_DECLARE_METATYPE(QArrayData::AllocationOptions)
+Q_DECLARE_METATYPE(QArrayData::ArrayOptions)
void tst_QArrayData::allocate_data()
{
QTest::addColumn<size_t>("objectSize");
QTest::addColumn<size_t>("alignment");
- QTest::addColumn<QArrayData::AllocationOptions>("allocateOptions");
+ QTest::addColumn<QArrayData::ArrayOptions>("allocateOptions");
QTest::addColumn<bool>("isCapacityReserved");
- QTest::addColumn<bool>("isSharable"); // ### Qt6: remove
QTest::addColumn<const QArrayData *>("commonEmpty");
struct {
@@ -657,35 +513,24 @@ void tst_QArrayData::allocate_data()
size_t objectSize;
size_t alignment;
} types[] = {
- { "char", sizeof(char), Q_ALIGNOF(char) },
- { "short", sizeof(short), Q_ALIGNOF(short) },
- { "void *", sizeof(void *), Q_ALIGNOF(void *) }
+ { "char", sizeof(char), alignof(char) },
+ { "short", sizeof(short), alignof(short) },
+ { "void *", sizeof(void *), alignof(void *) }
};
- QArrayData *shared_empty = QArrayData::allocate(0, Q_ALIGNOF(QArrayData), 0);
+ QArrayData *shared_empty;
+ QArrayData::allocate(&shared_empty, 1, alignof(QArrayData), 0);
QVERIFY(shared_empty);
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QArrayData *unsharable_empty = QArrayData::allocate(0, Q_ALIGNOF(QArrayData), 0, QArrayData::Unsharable);
- QVERIFY(unsharable_empty);
-#endif
-
struct {
char const *description;
- QArrayData::AllocationOptions allocateOptions;
+ QArrayData::ArrayOptions allocateOptions;
bool isCapacityReserved;
- bool isSharable;
const QArrayData *commonEmpty;
} options[] = {
- { "Default", QArrayData::Default, false, true, shared_empty },
- { "Reserved", QArrayData::CapacityReserved, true, true, shared_empty },
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- { "Reserved | Unsharable",
- QArrayData::CapacityReserved | QArrayData::Unsharable, true, false,
- unsharable_empty },
- { "Unsharable", QArrayData::Unsharable, false, false, unsharable_empty },
-#endif
- { "Grow", QArrayData::Grow, false, true, shared_empty }
+ { "Default", QArrayData::DefaultAllocationFlags, false, shared_empty },
+ { "Reserved", QArrayData::CapacityReserved, true, shared_empty },
+ { "Grow", QArrayData::GrowsForward, false, shared_empty }
};
for (size_t i = 0; i < sizeof(types)/sizeof(types[0]); ++i)
@@ -696,47 +541,45 @@ void tst_QArrayData::allocate_data()
+ QLatin1String(options[j].description)))
<< types[i].objectSize << types[i].alignment
<< options[j].allocateOptions << options[j].isCapacityReserved
- << options[j].isSharable << options[j].commonEmpty;
+ << options[j].commonEmpty;
}
void tst_QArrayData::allocate()
{
QFETCH(size_t, objectSize);
QFETCH(size_t, alignment);
- QFETCH(QArrayData::AllocationOptions, allocateOptions);
+ QFETCH(QArrayData::ArrayOptions, allocateOptions);
QFETCH(bool, isCapacityReserved);
QFETCH(const QArrayData *, commonEmpty);
// Minimum alignment that can be requested is that of QArrayData.
// Typically, this alignment is sizeof(void *) and ensured by malloc.
- size_t minAlignment = qMax(alignment, Q_ALIGNOF(QArrayData));
+ size_t minAlignment = qMax(alignment, alignof(QArrayData));
// Shared Empty
- QCOMPARE(QArrayData::allocate(objectSize, minAlignment, 0,
- QArrayData::AllocationOptions(allocateOptions)), commonEmpty);
+ QArrayData *empty;
+ QCOMPARE((QArrayData::allocate(&empty, objectSize, minAlignment, 0,
+ QArrayData::ArrayOptions(allocateOptions)), empty), commonEmpty);
Deallocator keeper(objectSize, minAlignment);
keeper.headers.reserve(1024);
for (int capacity = 1; capacity <= 1024; capacity <<= 1) {
- QArrayData *data = QArrayData::allocate(objectSize, minAlignment,
- capacity, QArrayData::AllocationOptions(allocateOptions));
+ QArrayData *data;
+ void *dataPointer = QArrayData::allocate(&data, objectSize, minAlignment,
+ capacity, QArrayData::ArrayOptions(allocateOptions));
+
keeper.headers.append(data);
- QCOMPARE(data->size, 0);
- if (allocateOptions & QArrayData::Grow)
- QVERIFY(data->alloc > uint(capacity));
+ if (allocateOptions & QArrayData::GrowsForward)
+ QVERIFY(data->allocatedCapacity() > uint(capacity));
else
- QCOMPARE(data->alloc, uint(capacity));
- QCOMPARE(data->capacityReserved, uint(isCapacityReserved));
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QFETCH(bool, isSharable);
- QCOMPARE(data->ref.isSharable(), isSharable);
-#endif
+ QCOMPARE(data->allocatedCapacity(), size_t(capacity));
+ QCOMPARE(bool(data->flags & QArrayData::CapacityReserved), isCapacityReserved);
// Check that the allocated array can be used. Best tested with a
// memory checker, such as valgrind, running.
- ::memset(data->data(), 'A', objectSize * capacity);
+ ::memset(dataPointer, 'A', objectSize * capacity);
}
}
@@ -744,47 +587,40 @@ void tst_QArrayData::reallocate()
{
QFETCH(size_t, objectSize);
QFETCH(size_t, alignment);
- QFETCH(QArrayData::AllocationOptions, allocateOptions);
+ QFETCH(QArrayData::ArrayOptions, allocateOptions);
QFETCH(bool, isCapacityReserved);
- // Maximum alignment that can be requested is that of QArrayData,
- // otherwise, we can't use reallocate().
- Q_ASSERT(alignment <= Q_ALIGNOF(QArrayData));
-
// Minimum alignment that can be requested is that of QArrayData.
// Typically, this alignment is sizeof(void *) and ensured by malloc.
- size_t minAlignment = qMax(alignment, Q_ALIGNOF(QArrayData));
+ size_t minAlignment = qMax(alignment, alignof(QArrayData));
int capacity = 10;
Deallocator keeper(objectSize, minAlignment);
- QArrayData *data = QArrayData::allocate(objectSize, minAlignment, capacity,
- QArrayData::AllocationOptions(allocateOptions) & ~QArrayData::Grow);
+ QArrayData *data;
+ void *dataPointer = QArrayData::allocate(&data, objectSize, minAlignment, capacity,
+ QArrayData::ArrayOptions(allocateOptions) & ~QArrayData::GrowsForward);
keeper.headers.append(data);
- memset(data->data(), 'A', objectSize * capacity);
- data->size = capacity;
+ memset(dataPointer, 'A', objectSize * capacity);
// now try to reallocate
int newCapacity = 40;
- data = QArrayData::reallocateUnaligned(data, objectSize, newCapacity,
- QArrayData::AllocationOptions(allocateOptions));
+ auto pair = QArrayData::reallocateUnaligned(data, dataPointer, objectSize, newCapacity,
+ QArrayData::ArrayOptions(allocateOptions));
+ data = pair.first;
+ dataPointer = pair.second;
QVERIFY(data);
keeper.headers.clear();
keeper.headers.append(data);
- QCOMPARE(data->size, capacity);
- if (allocateOptions & QArrayData::Grow)
- QVERIFY(data->alloc > uint(newCapacity));
+ if (allocateOptions & QArrayData::GrowsForward)
+ QVERIFY(data->allocatedCapacity() > size_t(newCapacity));
else
- QCOMPARE(data->alloc, uint(newCapacity));
- QCOMPARE(data->capacityReserved, uint(isCapacityReserved));
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QFETCH(bool, isSharable);
- QCOMPARE(data->ref.isSharable(), isSharable);
-#endif
+ QCOMPARE(data->allocatedCapacity(), size_t(newCapacity));
+ QCOMPARE(!(data->flags & QArrayData::CapacityReserved), !isCapacityReserved);
for (int i = 0; i < capacity; ++i)
- QCOMPARE(static_cast<char *>(data->data())[i], 'A');
+ QCOMPARE(static_cast<char *>(dataPointer)[i], 'A');
}
class Unaligned
@@ -808,95 +644,52 @@ void tst_QArrayData::alignment()
// Minimum alignment that can be requested is that of QArrayData.
// Typically, this alignment is sizeof(void *) and ensured by malloc.
- size_t minAlignment = qMax(alignment, Q_ALIGNOF(QArrayData));
+ size_t minAlignment = qMax(alignment, alignof(QArrayData));
Deallocator keeper(sizeof(Unaligned), minAlignment);
keeper.headers.reserve(100);
for (int i = 0; i < 100; ++i) {
- QArrayData *data = QArrayData::allocate(sizeof(Unaligned),
- minAlignment, 8, QArrayData::Default);
+ QArrayData *data;
+ void *dataPointer = QArrayData::allocate(&data, sizeof(Unaligned),
+ minAlignment, 8, QArrayData::DefaultAllocationFlags);
keeper.headers.append(data);
QVERIFY(data);
- QCOMPARE(data->size, 0);
- QVERIFY(data->alloc >= uint(8));
+ QVERIFY(data->allocatedCapacity() >= uint(8));
// These conditions should hold as long as header and array are
// allocated together
- QVERIFY(data->offset >= qptrdiff(sizeof(QArrayData)));
- QVERIFY(data->offset <= qptrdiff(sizeof(QArrayData)
- + minAlignment - Q_ALIGNOF(QArrayData)));
+ qptrdiff offset = reinterpret_cast<char *>(dataPointer) -
+ reinterpret_cast<char *>(data);
+ QVERIFY(offset >= qptrdiff(sizeof(QArrayData)));
+ QVERIFY(offset <= qptrdiff(sizeof(QArrayData)
+ + minAlignment - alignof(QArrayData)));
// Data is aligned
- QCOMPARE(quintptr(quintptr(data->data()) % alignment), quintptr(0u));
+ QCOMPARE(quintptr(quintptr(dataPointer) % alignment), quintptr(0u));
// Check that the allocated array can be used. Best tested with a
// memory checker, such as valgrind, running.
- ::memset(data->data(), 'A', sizeof(Unaligned) * 8);
+ ::memset(dataPointer, 'A', sizeof(Unaligned) * 8);
}
}
void tst_QArrayData::typedData()
{
- QStaticArrayData<int, 10> data = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(int, 10),
- { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
- };
- QCOMPARE(data.header.size, 10);
-
- {
- QTypedArrayData<int> *array =
- static_cast<QTypedArrayData<int> *>(&data.header);
- QCOMPARE(array->data(), data.data);
-
- int j = 0;
- for (QTypedArrayData<int>::iterator iter = array->begin();
- iter != array->end(); ++iter, ++j)
- QCOMPARE((const int *)iter, data.data + j);
- QCOMPARE(j, 10);
- }
-
- {
- const QTypedArrayData<int> *array =
- static_cast<const QTypedArrayData<int> *>(&data.header);
-
- QCOMPARE(array->data(), data.data);
-
- int j = 0;
- for (QTypedArrayData<int>::const_iterator iter = array->begin();
- iter != array->end(); ++iter, ++j)
- QCOMPARE((const int *)iter, data.data + j);
- QCOMPARE(j, 10);
- }
-
- {
- QTypedArrayData<int> *null = QTypedArrayData<int>::sharedNull();
- QTypedArrayData<int> *empty = QTypedArrayData<int>::allocate(0);
-
- QVERIFY(null != empty);
-
- QCOMPARE(null->size, 0);
- QCOMPARE(empty->size, 0);
-
- QCOMPARE(null->begin(), null->end());
- QCOMPARE(empty->begin(), empty->end());
- }
-
-
{
Deallocator keeper(sizeof(char),
- Q_ALIGNOF(QTypedArrayData<char>::AlignmentDummy));
- QArrayData *array = QTypedArrayData<char>::allocate(10);
+ alignof(QTypedArrayData<char>::AlignmentDummy));
+ QPair<QTypedArrayData<char> *, char *> pair = QTypedArrayData<char>::allocate(10);
+ QArrayData *array = pair.first;
keeper.headers.append(array);
QVERIFY(array);
- QCOMPARE(array->size, 0);
- QCOMPARE(array->alloc, 10u);
+ QCOMPARE(array->allocatedCapacity(), size_t(10));
// Check that the allocated array can be used. Best tested with a
// memory checker, such as valgrind, running.
- ::memset(array->data(), 0, 10 * sizeof(char));
+ ::memset(pair.second, 0, 10 * sizeof(char));
keeper.headers.clear();
QTypedArrayData<short>::deallocate(array);
@@ -906,17 +699,17 @@ void tst_QArrayData::typedData()
{
Deallocator keeper(sizeof(short),
- Q_ALIGNOF(QTypedArrayData<short>::AlignmentDummy));
- QArrayData *array = QTypedArrayData<short>::allocate(10);
+ alignof(QTypedArrayData<short>::AlignmentDummy));
+ QPair<QTypedArrayData<short> *, short *> pair = QTypedArrayData<short>::allocate(10);
+ QArrayData *array = pair.first;
keeper.headers.append(array);
QVERIFY(array);
- QCOMPARE(array->size, 0);
- QCOMPARE(array->alloc, 10u);
+ QCOMPARE(array->allocatedCapacity(), size_t(10));
// Check that the allocated array can be used. Best tested with a
// memory checker, such as valgrind, running.
- ::memset(array->data(), 0, 10 * sizeof(short));
+ ::memset(pair.second, 0, 10 * sizeof(short));
keeper.headers.clear();
QTypedArrayData<short>::deallocate(array);
@@ -926,17 +719,17 @@ void tst_QArrayData::typedData()
{
Deallocator keeper(sizeof(double),
- Q_ALIGNOF(QTypedArrayData<double>::AlignmentDummy));
- QArrayData *array = QTypedArrayData<double>::allocate(10);
+ alignof(QTypedArrayData<double>::AlignmentDummy));
+ QPair<QTypedArrayData<double> *, double *> pair = QTypedArrayData<double>::allocate(10);
+ QArrayData *array = pair.first;
keeper.headers.append(array);
QVERIFY(array);
- QCOMPARE(array->size, 0);
- QCOMPARE(array->alloc, 10u);
+ QCOMPARE(array->allocatedCapacity(), size_t(10));
// Check that the allocated array can be used. Best tested with a
// memory checker, such as valgrind, running.
- ::memset(array->data(), 0, 10 * sizeof(double));
+ ::memset(pair.second, 0, 10 * sizeof(double));
keeper.headers.clear();
QTypedArrayData<double>::deallocate(array);
@@ -1354,136 +1147,6 @@ static inline bool arrayIsFilledWith(const QArrayDataPointer<int> &array,
return true;
}
-void tst_QArrayData::setSharable_data()
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QTest::addColumn<QArrayDataPointer<int> >("array");
- QTest::addColumn<size_t>("size");
- QTest::addColumn<size_t>("capacity");
- QTest::addColumn<bool>("isCapacityReserved");
- QTest::addColumn<int>("fillValue");
-
- QArrayDataPointer<int> null;
- QArrayDataPointer<int> empty; empty.clear();
-
- static QStaticArrayData<int, 10> staticArrayData = {
- Q_STATIC_ARRAY_DATA_HEADER_INITIALIZER(int, 10),
- { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }
- };
-
- QArrayDataPointer<int> emptyReserved(QTypedArrayData<int>::allocate(5,
- QArrayData::CapacityReserved));
- QArrayDataPointer<int> nonEmpty(QTypedArrayData<int>::allocate(5,
- QArrayData::Default));
- QArrayDataPointer<int> nonEmptyExtraCapacity(
- QTypedArrayData<int>::allocate(10, QArrayData::Default));
- QArrayDataPointer<int> nonEmptyReserved(QTypedArrayData<int>::allocate(15,
- QArrayData::CapacityReserved));
- QArrayDataPointer<int> staticArray(
- static_cast<QTypedArrayData<int> *>(&staticArrayData.header));
- QArrayDataPointer<int> rawData(
- QTypedArrayData<int>::fromRawData(staticArrayData.data, 10));
-
- nonEmpty->copyAppend(5, 1);
- nonEmptyExtraCapacity->copyAppend(5, 1);
- nonEmptyReserved->copyAppend(7, 2);
-
- QTest::newRow("shared-null") << null << size_t(0) << size_t(0) << false << 0;
- QTest::newRow("shared-empty") << empty << size_t(0) << size_t(0) << false << 0;
- // unsharable-empty implicitly tested in shared-empty
- QTest::newRow("empty-reserved") << emptyReserved << size_t(0) << size_t(5) << true << 0;
- QTest::newRow("non-empty") << nonEmpty << size_t(5) << size_t(5) << false << 1;
- QTest::newRow("non-empty-extra-capacity") << nonEmptyExtraCapacity << size_t(5) << size_t(10) << false << 1;
- QTest::newRow("non-empty-reserved") << nonEmptyReserved << size_t(7) << size_t(15) << true << 2;
- QTest::newRow("static-array") << staticArray << size_t(10) << size_t(0) << false << 3;
- QTest::newRow("raw-data") << rawData << size_t(10) << size_t(0) << false << 3;
-#endif
-}
-
-void tst_QArrayData::setSharable()
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QFETCH(QArrayDataPointer<int>, array);
- QFETCH(size_t, size);
- QFETCH(size_t, capacity);
- QFETCH(bool, isCapacityReserved);
- QFETCH(int, fillValue);
-
- QVERIFY(array->ref.isShared()); // QTest has a copy
- QVERIFY(array->ref.isSharable());
-
- QCOMPARE(size_t(array->size), size);
- QCOMPARE(size_t(array->alloc), capacity);
- QCOMPARE(bool(array->capacityReserved), isCapacityReserved);
- QVERIFY(arrayIsFilledWith(array, fillValue, size));
-
- // shared-null becomes shared-empty, may otherwise detach
- array.setSharable(true);
-
- QVERIFY(array->ref.isSharable());
- QVERIFY(arrayIsFilledWith(array, fillValue, size));
-
- {
- QArrayDataPointer<int> copy(array);
- QVERIFY(array->ref.isShared());
- QVERIFY(array->ref.isSharable());
- QCOMPARE(copy.data(), array.data());
- }
-
- // Unshare, must detach
- array.setSharable(false);
-
- // Immutability (alloc == 0) is lost on detach, as is additional capacity
- // if capacityReserved flag is not set.
- if ((capacity == 0 && size != 0)
- || (!isCapacityReserved && capacity > size))
- capacity = size;
-
- QVERIFY(!array->ref.isShared());
- QVERIFY(!array->ref.isSharable());
-
- QCOMPARE(size_t(array->size), size);
- QCOMPARE(size_t(array->alloc), capacity);
- QCOMPARE(bool(array->capacityReserved), isCapacityReserved);
- QVERIFY(arrayIsFilledWith(array, fillValue, size));
-
- {
- QArrayDataPointer<int> copy(array);
- QVERIFY(!array->ref.isShared());
- QVERIFY(!array->ref.isSharable());
-
- // Null/empty is always shared
- QCOMPARE(copy->ref.isShared(), !(size || isCapacityReserved));
- QVERIFY(copy->ref.isSharable());
-
- QCOMPARE(size_t(copy->size), size);
- QCOMPARE(size_t(copy->alloc), capacity);
- QCOMPARE(bool(copy->capacityReserved), isCapacityReserved);
- QVERIFY(arrayIsFilledWith(copy, fillValue, size));
- }
-
- // Make sharable, again
- array.setSharable(true);
-
- QCOMPARE(array->ref.isShared(), !(size || isCapacityReserved));
- QVERIFY(array->ref.isSharable());
-
- QCOMPARE(size_t(array->size), size);
- QCOMPARE(size_t(array->alloc), capacity);
- QCOMPARE(bool(array->capacityReserved), isCapacityReserved);
- QVERIFY(arrayIsFilledWith(array, fillValue, size));
-
- {
- QArrayDataPointer<int> copy(array);
- QVERIFY(array->ref.isShared());
- QCOMPARE(copy.data(), array.data());
- }
-
- QCOMPARE(array->ref.isShared(), !(size || isCapacityReserved));
- QVERIFY(array->ref.isSharable());
-#endif
-}
-
struct ResetOnDtor
{
ResetOnDtor()
@@ -1517,7 +1180,7 @@ void fromRawData_impl()
{
// Default: Immutable, sharable
SimpleVector<T> raw = SimpleVector<T>::fromRawData(array,
- sizeof(array)/sizeof(array[0]), QArrayData::Default);
+ sizeof(array)/sizeof(array[0]), QArrayData::DefaultRawFlags);
QCOMPARE(raw.size(), size_t(11));
QCOMPARE((const T *)raw.constBegin(), array);
@@ -1531,37 +1194,6 @@ void fromRawData_impl()
QCOMPARE(raw.back(), T(11));
QVERIFY((const T *)raw.constBegin() != array);
}
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- {
- // Immutable, unsharable
- SimpleVector<T> raw = SimpleVector<T>::fromRawData(array,
- sizeof(array)/sizeof(array[0]), QArrayData::Unsharable);
-
- QCOMPARE(raw.size(), size_t(11));
- QCOMPARE((const T *)raw.constBegin(), array);
- QCOMPARE((const T *)raw.constEnd(), (const T *)(array + sizeof(array)/sizeof(array[0])));
-
- SimpleVector<T> copy(raw);
- QVERIFY(!copy.isSharedWith(raw));
- QVERIFY(!raw.isShared());
-
- QCOMPARE(copy.size(), size_t(11));
-
- for (size_t i = 0; i < 11; ++i) {
- QCOMPARE(const_(copy)[i], const_(raw)[i]);
- QCOMPARE(const_(copy)[i], T(i + 1));
- }
-
- QCOMPARE(raw.size(), size_t(11));
- QCOMPARE((const T *)raw.constBegin(), array);
- QCOMPARE((const T *)raw.constEnd(), (const T *)(array + sizeof(array)/sizeof(array[0])));
-
- // Detach
- QCOMPARE(raw.back(), T(11));
- QVERIFY((const T *)raw.constBegin() != array);
- }
-#endif
}
void tst_QArrayData::fromRawData_data()
@@ -1593,17 +1225,17 @@ void tst_QArrayData::literals()
{
{
QArrayDataPointer<char> d = Q_ARRAY_LITERAL(char, "ABCDEFGHIJ");
- QCOMPARE(d->size, 10 + 1);
+ QCOMPARE(d.size, 10u + 1u);
for (int i = 0; i < 10; ++i)
- QCOMPARE(d->data()[i], char('A' + i));
+ QCOMPARE(d.data()[i], char('A' + i));
}
{
// wchar_t is not necessarily 2-bytes
QArrayDataPointer<wchar_t> d = Q_ARRAY_LITERAL(wchar_t, L"ABCDEFGHIJ");
- QCOMPARE(d->size, 10 + 1);
+ QCOMPARE(d.size, 10u + 1u);
for (int i = 0; i < 10; ++i)
- QCOMPARE(d->data()[i], wchar_t('A' + i));
+ QCOMPARE(d.data()[i], wchar_t('A' + i));
}
{
@@ -1615,10 +1247,6 @@ void tst_QArrayData::literals()
// v.capacity() is unspecified, for now
QVERIFY(v.isStatic());
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(v.isSharable());
-#endif
QCOMPARE((void*)(const char*)(v.constBegin() + v.size()), (void*)(const char*)v.constEnd());
for (int i = 0; i < 10; ++i)
@@ -1645,26 +1273,26 @@ void tst_QArrayData::variadicLiterals()
{
QArrayDataPointer<int> d =
Q_ARRAY_LITERAL(int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
- QCOMPARE(d->size, 10);
+ QCOMPARE(d.size, 10u);
for (int i = 0; i < 10; ++i)
- QCOMPARE(d->data()[i], i);
+ QCOMPARE(d.data()[i], i);
}
{
QArrayDataPointer<char> d = Q_ARRAY_LITERAL(char,
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
- QCOMPARE(d->size, 10);
+ QCOMPARE(d.size, 10u);
for (int i = 0; i < 10; ++i)
- QCOMPARE(d->data()[i], char('A' + i));
+ QCOMPARE(d.data()[i], char('A' + i));
}
{
QArrayDataPointer<const char *> d = Q_ARRAY_LITERAL(const char *,
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
- QCOMPARE(d->size, 10);
+ QCOMPARE(d.size, 10u);
for (int i = 0; i < 10; ++i) {
- QCOMPARE(d->data()[i][0], char('A' + i));
- QCOMPARE(d->data()[i][1], '\0');
+ QCOMPARE(d.data()[i][0], char('A' + i));
+ QCOMPARE(d.data()[i][1], '\0');
}
}
@@ -1677,10 +1305,6 @@ void tst_QArrayData::variadicLiterals()
// v.capacity() is unspecified, for now
QVERIFY(v.isStatic());
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QVERIFY(v.isSharable());
-#endif
QCOMPARE((const int *)(v.constBegin() + v.size()), (const int *)v.constEnd());
for (int i = 0; i < 7; ++i)
diff --git a/tests/auto/corelib/tools/qarraydata_strictiterators/qarraydata_strictiterators.pro b/tests/auto/corelib/tools/qarraydata_strictiterators/qarraydata_strictiterators.pro
deleted file mode 100644
index b01fbd84d1..0000000000
--- a/tests/auto/corelib/tools/qarraydata_strictiterators/qarraydata_strictiterators.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-include(../qarraydata/qarraydata.pro)
-TARGET = tst_qarraydata_strictiterators
-DEFINES += QT_STRICT_ITERATORS=1 tst_QArrayData=tst_QArrayData_StrictIterators
diff --git a/tests/auto/corelib/tools/qbitarray/tst_qbitarray.cpp b/tests/auto/corelib/tools/qbitarray/tst_qbitarray.cpp
index 9a7c099228..b2c7915aa0 100644
--- a/tests/auto/corelib/tools/qbitarray/tst_qbitarray.cpp
+++ b/tests/auto/corelib/tools/qbitarray/tst_qbitarray.cpp
@@ -86,6 +86,9 @@ private slots:
void resize();
void fromBits_data();
void fromBits();
+
+ void toUInt32_data();
+ void toUInt32();
};
void tst_QBitArray::size_data()
@@ -667,5 +670,95 @@ void tst_QBitArray::fromBits()
QCOMPARE(QBitArray::fromBits(fromBits.bits(), fromBits.size()), expected);
}
+void tst_QBitArray::toUInt32_data()
+{
+ QTest::addColumn<QBitArray>("data");
+ QTest::addColumn<int>("endianness");
+ QTest::addColumn<bool>("check");
+ QTest::addColumn<quint32>("result");
+
+ QTest::newRow("ctor") << QBitArray()
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(0);
+
+ QTest::newRow("empty") << QBitArray(0)
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(0);
+
+ QTest::newRow("LittleEndian4") << QStringToQBitArray(QString("0111"))
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(14);
+
+ QTest::newRow("BigEndian4") << QStringToQBitArray(QString("0111"))
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << true
+ << quint32(7);
+
+ QTest::newRow("LittleEndian8") << QStringToQBitArray(QString("01111111"))
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(254);
+
+ QTest::newRow("BigEndian8") << QStringToQBitArray(QString("01111111"))
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << true
+ << quint32(127);
+
+ QTest::newRow("LittleEndian16") << QStringToQBitArray(QString("0111111111111111"))
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(65534);
+
+ QTest::newRow("BigEndian16") << QStringToQBitArray(QString("0111111111111111"))
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << true
+ << quint32(32767);
+
+ QTest::newRow("LittleEndian31") << QBitArray(31, true)
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(2147483647);
+
+ QTest::newRow("BigEndian31") << QBitArray(31, true)
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << true
+ << quint32(2147483647);
+
+ QTest::newRow("LittleEndian32") << QBitArray(32, true)
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << true
+ << quint32(4294967295);
+
+ QTest::newRow("BigEndian32") << QBitArray(32, true)
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << true
+ << quint32(4294967295);
+
+ QTest::newRow("LittleEndian33") << QBitArray(33, true)
+ << static_cast<int>(QSysInfo::Endian::LittleEndian)
+ << false
+ << quint32(0);
+
+ QTest::newRow("BigEndian33") << QBitArray(33, true)
+ << static_cast<int>(QSysInfo::Endian::BigEndian)
+ << false
+ << quint32(0);
+}
+
+void tst_QBitArray::toUInt32()
+{
+ QFETCH(QBitArray, data);
+ QFETCH(int, endianness);
+ QFETCH(bool, check);
+ QFETCH(quint32, result);
+ bool ok = false;
+
+ QCOMPARE(data.toUInt32(static_cast<QSysInfo::Endian>(endianness), &ok), result);
+ QCOMPARE(ok, check);
+}
+
QTEST_APPLESS_MAIN(tst_QBitArray)
#include "tst_qbitarray.moc"
diff --git a/tests/auto/corelib/tools/qflatmap/qflatmap.pro b/tests/auto/corelib/tools/qflatmap/qflatmap.pro
new file mode 100644
index 0000000000..3927cee30c
--- /dev/null
+++ b/tests/auto/corelib/tools/qflatmap/qflatmap.pro
@@ -0,0 +1,4 @@
+CONFIG += testcase
+TARGET = tst_qflatmap
+QT = core-private testlib
+SOURCES = tst_qflatmap.cpp
diff --git a/tests/auto/corelib/tools/qflatmap/tst_qflatmap.cpp b/tests/auto/corelib/tools/qflatmap/tst_qflatmap.cpp
new file mode 100644
index 0000000000..a5ae6f5f44
--- /dev/null
+++ b/tests/auto/corelib/tools/qflatmap/tst_qflatmap.cpp
@@ -0,0 +1,453 @@
+/****************************************************************************
+**
+** Copyright (C) 2020 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:GPL-EXCEPT$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3 as published by the Free Software
+** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtTest/QtTest>
+
+#include <private/qflatmap_p.h>
+#include <qbytearray.h>
+#include <qstring.h>
+#include <qstringview.h>
+#include <qvarlengtharray.h>
+#include <qvector.h>
+
+#include <algorithm>
+#include <list>
+#include <tuple>
+
+class tst_QFlatMap : public QObject
+{
+ Q_OBJECT
+private slots:
+ void constructing();
+ void constAccess();
+ void insertion();
+ void removal();
+ void extraction();
+ void iterators();
+ void statefulComparator();
+ void transparency();
+ void viewIterators();
+ void varLengthArray();
+};
+
+void tst_QFlatMap::constructing()
+{
+ using Map = QFlatMap<int, QByteArray>;
+ Map fmDefault;
+ QVERIFY(fmDefault.isEmpty());
+ QCOMPARE(fmDefault.size(), Map::size_type(0));
+ QCOMPARE(fmDefault.size(), fmDefault.count());
+
+ auto key_compare = fmDefault.key_comp();
+ auto selfbuilt_value_compare
+ = [&key_compare](const Map::value_type &a, const Map::value_type &b)
+ {
+ return key_compare(a.first, b.first);
+ };
+ auto value_compare = fmDefault.value_comp();
+
+ Map::key_container_type kv = { 6, 2, 1 };
+ Map::mapped_container_type mv = { "foo", "bar", "baz" };
+ Map fmCopy{kv, mv};
+ QCOMPARE(fmCopy.size(), Map::size_type(3));
+ QVERIFY(std::is_sorted(fmCopy.begin(), fmCopy.end(), selfbuilt_value_compare));
+ QVERIFY(std::is_sorted(fmCopy.begin(), fmCopy.end(), value_compare));
+
+ Map fmMove{
+ Map::key_container_type{ 6, 2, 1 },
+ Map::mapped_container_type{ "foo", "bar", "baz" }
+ };
+ QCOMPARE(fmMove.size(), Map::size_type(3));
+ QVERIFY(std::is_sorted(fmMove.begin(), fmMove.end(), value_compare));
+
+ auto fmInitList = Map{ { 1, 2 }, { "foo", "bar" } };
+ QVERIFY(std::is_sorted(fmInitList.begin(), fmInitList.end(), value_compare));
+
+ auto fmRange = Map(fmCopy.begin(), fmCopy.end());
+ QVERIFY(std::is_sorted(fmRange.begin(), fmRange.end(), value_compare));
+
+ kv.clear();
+ mv.clear();
+ std::vector<Map::value_type> sv;
+ for (auto it = fmRange.begin(); it != fmRange.end(); ++it) {
+ kv.push_back(it->first);
+ mv.push_back(it->second);
+ sv.push_back(*it);
+ }
+ auto fmFromSortedVectorCopy = Map(Qt::OrderedUniqueRange, kv, mv);
+ auto fmFromSortedVectorMove = Map(Qt::OrderedUniqueRange, Map::key_container_type(kv),
+ Map::mapped_container_type(mv));
+ auto fmFromSortedInitList = Map(Qt::OrderedUniqueRange, { { 1, "foo" }, { 2, "bar" } });
+ auto fmFromSortedRange = Map(Qt::OrderedUniqueRange, sv.begin(), sv.end());
+}
+
+void tst_QFlatMap::constAccess()
+{
+ using Map = QFlatMap<QByteArray, QByteArray>;
+ const Map m{ { { "foo", "FOO" }, { "bar", "BAR" } } };
+
+ const std::vector<Map::value_type> v{ { "foo", "FOO" }, { "bar", "BAR" } };
+
+ QCOMPARE(m.value("foo").data(), "FOO");
+ QCOMPARE(m.value("bar").data(), "BAR");
+ QCOMPARE(m.value("nix"), QByteArray());
+ QCOMPARE(m.value("nix", "NIX").data(), "NIX");
+ QCOMPARE(m["foo"].data(), "FOO");
+ QCOMPARE(m["bar"].data(), "BAR");
+ QCOMPARE(m["nix"], QByteArray());
+ QVERIFY(m.contains("foo"));
+ QVERIFY(!m.contains("nix"));
+}
+
+void tst_QFlatMap::insertion()
+{
+ using Map = QFlatMap<QByteArray, QByteArray>;
+ Map m;
+ QByteArray foo = "foo";
+ m[foo] = foo.toUpper();
+ m["bar"] = "BAR";
+ m["baz"] = "BAZ";
+ QVERIFY(m.insert("oof", "eek").second);
+ QVERIFY(!m.insert("oof", "OOF").second);
+ const std::vector<Map::value_type> container = { { "bla", "BLA" }, { "blubb", "BLUBB" } };
+ m.insert(container.begin(), container.end());
+ QCOMPARE(m.value("foo").data(), "FOO");
+ QCOMPARE(m.value("bar").data(), "BAR");
+ QCOMPARE(m.value("baz").data(), "BAZ");
+ QCOMPARE(m.value("oof").data(), "OOF");
+ QCOMPARE(m.value("bla").data(), "BLA");
+ QCOMPARE(m.value("blubb").data(), "BLUBB");
+
+ Map::value_type a1[] = { { "narf", "NARF" },
+ { "zort", "ZORT" },
+ { "troz", "TROZ" } };
+ Map::value_type a2[] = { { "gnampf", "GNAMPF" },
+ { "narf", "NARFFFF" },
+ { "narf", "NARFFFFF" },
+ { "narf", "NARFFFFFF" } };
+ m.insert(std::begin(a1), std::end(a1));
+ m.insert(Qt::OrderedUniqueRange, std::begin(a2), std::end(a2));
+ QCOMPARE(m.size(), 10);
+ QCOMPARE(m.value("narf").data(), "NARFFFFFF");
+ QCOMPARE(m.value("gnampf").data(), "GNAMPF");
+}
+
+void tst_QFlatMap::extraction()
+{
+ using Map = QFlatMap<int, QByteArray>;
+ Map::key_container_type expectedKeys = { 1, 2, 3 };
+ Map::mapped_container_type expectedValues = { "een", "twee", "dree" };
+ Map m(expectedKeys, expectedValues);
+ auto keys = m.keys();
+ auto values = m.values();
+ QCOMPARE(keys, expectedKeys);
+ QCOMPARE(values, expectedValues);
+ Map::containers c = std::move(m).extract();
+ QCOMPARE(c.keys, expectedKeys);
+ QCOMPARE(c.values, expectedValues);
+}
+
+void tst_QFlatMap::iterators()
+{
+ using Map = QFlatMap<int, QByteArray>;
+ auto m = Map{ { 1, "foo" }, { 2, "bar" }, { 3, "baz" } };
+ {
+ // forward / backward
+ Map::iterator a = m.begin();
+ QVERIFY(a != m.end());
+ QCOMPARE(a.key(), 1);
+ QCOMPARE(a.value(), "foo");
+ ++a;
+ QCOMPARE(a.key(), 2);
+ QCOMPARE(a.value(), "bar");
+ Map::iterator b = a++;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ QCOMPARE(std::tie(b.key(), b.value()), std::make_tuple(2, "bar"));
+ QCOMPARE(++a, m.end());
+ --a;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ a.value() = "buzz";
+ b = a--;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+ QCOMPARE(std::tie(b.key(), b.value()), std::make_tuple(3, "buzz"));
+ b.value() = "baz";
+
+ // random access
+ a = m.begin();
+ a += 2;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ a = m.begin() + 1;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+ a = 1 + m.begin();
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+ a = m.end() - 1;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ b = m.end();
+ b -= 1;
+ QCOMPARE(std::tie(b.key(), b.value()), std::make_tuple(3, "baz"));
+ QCOMPARE(m.end() - m.begin(), m.size());
+
+ // comparison
+ a = m.begin() + m.size() - 1;
+ b = m.end() - 1;
+ QVERIFY(a == b);
+ a = m.begin();
+ b = m.end();
+ QVERIFY(a < b);
+ QVERIFY(a <= b);
+ QVERIFY(b > a);
+ QVERIFY(b >= a);
+ a = b;
+ QVERIFY(!(a < b));
+ QVERIFY(a <= b);
+ QVERIFY(!(b > a));
+ QVERIFY(b >= a);
+
+ // de-referencing
+ a = m.begin();
+ auto ref0 = *a;
+ QCOMPARE(ref0.first, 1);
+ QCOMPARE(ref0.second, "foo");
+ auto ref1 = a[1];
+ QCOMPARE(ref1.first, 2);
+ QCOMPARE(ref1.second, "bar");
+ }
+ {
+ // forward / backward
+ Map::const_iterator a = m.cbegin();
+ QVERIFY(a != m.cend());
+ QCOMPARE(a.key(), 1);
+ QCOMPARE(a.value(), "foo");
+ ++a;
+ QCOMPARE(a.key(), 2);
+ QCOMPARE(a.value(), "bar");
+ Map::const_iterator b = a++;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ QCOMPARE(std::tie(b.key(), b.value()), std::make_tuple(2, "bar"));
+ QCOMPARE(++a, m.cend());
+ --a;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ b = a--;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+
+ // random access
+ a = m.cbegin();
+ a += 2;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ a = m.cbegin() + 1;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+ a = 1 + m.cbegin();
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(2, "bar"));
+ a = m.cend() - 1;
+ QCOMPARE(std::tie(a.key(), a.value()), std::make_tuple(3, "baz"));
+ b = m.cend();
+ b -= 1;
+ QCOMPARE(std::tie(b.key(), b.value()), std::make_tuple(3, "baz"));
+ QCOMPARE(m.cend() - m.cbegin(), m.size());
+
+ // comparison
+ a = m.cbegin() + m.size() - 1;
+ b = m.cend() - 1;
+ QVERIFY(a == b);
+ a = m.cbegin();
+ b = m.cend();
+ QVERIFY(a < b);
+ QVERIFY(a <= b);
+ QVERIFY(b > a);
+ QVERIFY(b >= a);
+ a = b;
+ QVERIFY(!(a < b));
+ QVERIFY(a <= b);
+ QVERIFY(!(b > a));
+ QVERIFY(b >= a);
+
+ // de-referencing
+ a = m.cbegin();
+ auto ref0 = *a;
+ QCOMPARE(ref0.first, 1);
+ QCOMPARE(ref0.second, "foo");
+ auto ref1 = a[1];
+ QCOMPARE(ref1.first, 2);
+ QCOMPARE(ref1.second, "bar");
+ }
+ {
+ Map::iterator it = m.begin();
+ Map::const_iterator cit = it;
+ Q_UNUSED(it);
+ Q_UNUSED(cit);
+ }
+ {
+ std::list<Map::value_type> revlst;
+ std::copy(m.begin(), m.end(), std::front_inserter(revlst));
+ std::vector<Map::value_type> v0;
+ std::copy(revlst.begin(), revlst.end(), std::back_inserter(v0));
+ std::vector<Map::value_type> v1;
+ std::copy(m.rbegin(), m.rend(), std::back_inserter(v1));
+ const Map cm = m;
+ std::vector<Map::value_type> v2;
+ std::copy(cm.rbegin(), cm.rend(), std::back_inserter(v2));
+ std::vector<Map::value_type> v3;
+ std::copy(m.crbegin(), m.crend(), std::back_inserter(v3));
+ QCOMPARE(v0, v1);
+ QCOMPARE(v1, v2);
+ QCOMPARE(v2, v3);
+ }
+}
+
+void tst_QFlatMap::removal()
+{
+ using Map = QFlatMap<int, QByteArray>;
+ Map m({ { 2, "bar" }, { 3, "baz" }, { 1, "foo" } });
+ QCOMPARE(m.value(2).data(), "bar");
+ QCOMPARE(m.take(2).data(), "bar");
+ QVERIFY(!m.contains(2));
+ QCOMPARE(m.size(), Map::size_type(2));
+ QVERIFY(m.remove(1));
+ QVERIFY(!m.contains(1));
+ QVERIFY(!m.remove(1));
+ QCOMPARE(m.size(), Map::size_type(1));
+ m.clear();
+ QVERIFY(m.isEmpty());
+ QVERIFY(m.empty());
+
+ m[1] = "een";
+ m[2] = "twee";
+ m[3] = "dree";
+ auto it = m.lower_bound(1);
+ QCOMPARE(it.key(), 1);
+ it = m.erase(it);
+ QCOMPARE(it.key(), 2);
+ QVERIFY(!m.contains(1));
+}
+
+void tst_QFlatMap::statefulComparator()
+{
+ struct CountingCompare {
+ mutable int count = 0;
+
+ bool operator()(const QString &lhs, const QString &rhs) const
+ {
+ ++count;
+ return lhs < rhs;
+ }
+ };
+
+ using Map = QFlatMap<QString, QString, CountingCompare>;
+ auto m1 = Map{ { "en", "een"}, { "to", "twee" }, { "tre", "dree" } };
+ QVERIFY(m1.key_comp().count > 0);
+ auto m2 = Map(m1.key_comp());
+ QCOMPARE(m2.key_comp().count, m1.key_comp().count);
+ m2.insert(m1.begin(), m1.end());
+ QVERIFY(m2.key_comp().count > m1.key_comp().count);
+}
+
+void tst_QFlatMap::transparency()
+{
+ struct StringViewCompare
+ {
+ using is_transparent = void;
+ bool operator()(const QStringView &lhs, const QStringView &rhs) const
+ {
+ return lhs < rhs;
+ }
+ };
+
+ using Map = QFlatMap<QString, QString, StringViewCompare>;
+ auto m = Map{ { "one", "een" }, { "two", "twee" }, { "three", "dree" } };
+
+ const QString numbers = "one two three";
+ const QStringView sv1{numbers.constData(), 3};
+ const QStringView sv2{numbers.constData() + 4, 3};
+ const QStringView sv3{numbers.constData() + 8, 5};
+ QCOMPARE(m.lower_bound(sv1).value(), "een");
+ QCOMPARE(m.lower_bound(sv2).value(), "twee");
+ QCOMPARE(m.lower_bound(sv3).value(), "dree");
+}
+
+void tst_QFlatMap::viewIterators()
+{
+ using Map = QFlatMap<QByteArray, QByteArray>;
+ Map m({ { "yksi", "een"}, { "kaksi", "twee" }, { "kolme", "dree" } });
+ {
+ std::vector<QByteArray> keys;
+ std::transform(m.begin(), m.end(), std::back_inserter(keys),
+ [](const Map::value_type &v)
+ {
+ return v.first;
+ });
+ auto it = keys.begin();
+ QCOMPARE(*it, "kaksi");
+ QCOMPARE(it->length(), 5);
+ ++it;
+ QCOMPARE(*it, "kolme");
+ it++;
+ QCOMPARE(*it, "yksi");
+ ++it;
+ QCOMPARE(it, keys.end());
+ --it;
+ QCOMPARE(*it, "yksi");
+ it--;
+ QCOMPARE(*it, "kolme");
+ }
+ {
+ std::vector<QByteArray> values;
+ std::transform(m.begin(), m.end(), std::back_inserter(values),
+ [](const Map::value_type &v)
+ {
+ return v.second;
+ });
+ auto it = values.begin();
+ QCOMPARE(*it, "twee");
+ QCOMPARE(it->length(), 4);
+ ++it;
+ QCOMPARE(*it, "dree");
+ it++;
+ QCOMPARE(*it, "een");
+ ++it;
+ QCOMPARE(it, values.end());
+ --it;
+ QCOMPARE(*it, "een");
+ it--;
+ QCOMPARE(*it, "dree");
+ }
+}
+
+void tst_QFlatMap::varLengthArray()
+{
+ using Map = QFlatMap<int, QByteArray, std::less<int>,
+ QVarLengthArray<int, 1024>, QVarLengthArray<QByteArray, 1024>>;
+ Map m{ { 2, "twee" } };
+ m.insert(1, "een");
+ m.remove(1);
+ QVERIFY(!m.isEmpty());
+ m.remove(2);
+ QVERIFY(m.isEmpty());
+}
+
+QTEST_APPLESS_MAIN(tst_QFlatMap)
+#include "tst_qflatmap.moc"
diff --git a/tests/auto/corelib/tools/qhash/tst_qhash.cpp b/tests/auto/corelib/tools/qhash/tst_qhash.cpp
index b98ac38288..91cd3eb0bd 100644
--- a/tests/auto/corelib/tools/qhash/tst_qhash.cpp
+++ b/tests/auto/corelib/tools/qhash/tst_qhash.cpp
@@ -1373,13 +1373,6 @@ void tst_QHash::noNeedlessRehashes()
void tst_QHash::const_shared_null()
{
QHash<int, QString> hash2;
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QHash<int, QString> hash1;
- hash1.setSharable(false);
- QVERIFY(hash1.isDetached());
-
- hash2.setSharable(true);
-#endif
QVERIFY(!hash2.isDetached());
}
diff --git a/tests/auto/corelib/tools/qhash_strictiterators/qhash_strictiterators.pro b/tests/auto/corelib/tools/qhash_strictiterators/qhash_strictiterators.pro
deleted file mode 100644
index 715e9bf0c9..0000000000
--- a/tests/auto/corelib/tools/qhash_strictiterators/qhash_strictiterators.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-include(../qhash/qhash.pro)
-TARGET = tst_qhash_strictiterators
-DEFINES += QT_STRICT_ITERATORS tst_QHash=tst_QHash_StrictIterators
diff --git a/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp b/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
index df42b5dea9..ed0abff456 100644
--- a/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
+++ b/tests/auto/corelib/tools/qlinkedlist/tst_qlinkedlist.cpp
@@ -225,8 +225,6 @@ private slots:
void constSharedNullInt() const;
void constSharedNullMovable() const;
void constSharedNullComplex() const;
-
- void setSharableInt() const;
private:
template<typename T> void length() const;
template<typename T> void first() const;
@@ -1048,13 +1046,6 @@ template<typename T>
void tst_QLinkedList::constSharedNull() const
{
QLinkedList<T> list2;
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QLinkedList<T> list1;
- list1.setSharable(false);
- QVERIFY(list1.isDetached());
-
- list2.setSharable(true);
-#endif
QVERIFY(!list2.isDetached());
}
@@ -1077,57 +1068,5 @@ void tst_QLinkedList::constSharedNullComplex() const
QCOMPARE(liveCount, Complex::getLiveCount());
}
-
-void tst_QLinkedList::setSharableInt() const
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QLinkedList<int> orglist;
- orglist << 0 << 1 << 2 << 3 << 4 << 5;
- int size = 6;
-
- QLinkedList<int> list;
- list = orglist;
-
- QVERIFY(!list.isDetached());
- list.setSharable(true);
-
- QCOMPARE(list.size(), size);
-
- {
- QLinkedList<int> copy(list);
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(list));
- }
-
- list.setSharable(false);
- QVERIFY(list.isDetached() || list.isSharedWith(QLinkedList<int>()));
-
- {
- QLinkedList<int> copy(list);
-
- QVERIFY(copy.isDetached() || copy.isSharedWith(QLinkedList<int>()));
- QCOMPARE(copy.size(), size);
- QCOMPARE(copy, list);
- }
-
- list.setSharable(true);
-
- {
- QLinkedList<int> copy(list);
-
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(list));
- }
-
- QLinkedList<int>::const_iterator it = list.constBegin();
- for (int i = 0; i < list.size(); ++i) {
- QCOMPARE(int(*it), i);
- ++it;
- }
-
- QCOMPARE(list.size(), size);
-#endif
-}
-
QTEST_APPLESS_MAIN(tst_QLinkedList)
#include "tst_qlinkedlist.moc"
diff --git a/tests/auto/corelib/tools/qlist/.gitignore b/tests/auto/corelib/tools/qlist/.gitignore
deleted file mode 100644
index df208b6e78..0000000000
--- a/tests/auto/corelib/tools/qlist/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-tst_qlist
diff --git a/tests/auto/corelib/tools/qlist/qlist.pro b/tests/auto/corelib/tools/qlist/qlist.pro
deleted file mode 100644
index 118c607880..0000000000
--- a/tests/auto/corelib/tools/qlist/qlist.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qlist
-QT = core testlib
-qtConfig(c++14): CONFIG += c++14
-qtConfig(c++1z): CONFIG += c++1z
-SOURCES = $$PWD/tst_qlist.cpp
diff --git a/tests/auto/corelib/tools/qlist/tst_qlist.cpp b/tests/auto/corelib/tools/qlist/tst_qlist.cpp
deleted file mode 100644
index cc9a3a16d1..0000000000
--- a/tests/auto/corelib/tools/qlist/tst_qlist.cpp
+++ /dev/null
@@ -1,2115 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
-#include <QList>
-
-template <typename T, class MemoryLayout>
-class is_qlist_array_memory_layout {
- struct No { char c; };
- struct Yes { No n[2]; };
- Q_STATIC_ASSERT(sizeof(No) != sizeof(Yes));
- static No check(...);
- static Yes check(MemoryLayout);
-public:
- enum { value = sizeof(check(typename QList<T>::MemoryLayout())) == sizeof(Yes) };
-};
-
-struct Movable {
- Movable(char input = 'j')
- : i(input)
- , state(Constructed)
- {
- ++liveCount;
- }
- Movable(const Movable &other)
- : i(other.i)
- , state(Constructed)
- {
- check(other.state, Constructed);
- ++liveCount;
- }
-
- ~Movable()
- {
- check(state, Constructed);
- i = 0;
- --liveCount;
- state = Destructed;
- }
-
- bool operator ==(const Movable &other) const
- {
- check(state, Constructed);
- check(other.state, Constructed);
- 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);
- check(other.state, Constructed);
- i = other.i;
- return *this;
- }
- char i;
-
- static int getLiveCount() { return liveCount; }
-private:
- static int liveCount;
-
- enum State { Constructed = 106, Destructed = 110 };
- uchar state;
-
- static void check(const uchar state1, const uchar state2)
- {
- QCOMPARE(state1, state2);
- }
-};
-
-Q_STATIC_ASSERT(sizeof(Movable) < sizeof(void*));
-
-int Movable::liveCount = 0;
-
-QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(Movable, Q_MOVABLE_TYPE);
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(Movable);
-
-int qHash(const Movable& movable)
-{
- return qHash(movable.i);
-}
-
-struct Optimal
-{
- Optimal(char input = 'j')
- : i(input),
- state(Constructed)
- {
- ++liveCount;
- }
- Optimal(const Optimal &other)
- : i(other.i),
- state(Constructed)
- {
- check(other.state, Constructed);
- ++liveCount;
- }
-
- ~Optimal()
- {
- check(state, Constructed);
- i = 0;
- --liveCount;
- state = Destructed;
- }
-
- bool operator ==(const Optimal &other) const
- {
- check(state, Constructed);
- check(other.state, Constructed);
- 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);
- check(other.state, Constructed);
- i = other.i;
- return *this;
- }
- char i;
-
- static int getLiveCount() { return liveCount; }
-private:
- static int liveCount;
-
- enum State { Constructed = 106, Destructed = 110 };
- uchar state;
- char padding[sizeof(void*) - 2];
-
- static void check(const uchar state1, const uchar state2)
- {
- QCOMPARE(state1, state2);
- }
-};
-
-Q_STATIC_ASSERT(sizeof(Optimal) == sizeof(void*));
-
-int Optimal::liveCount = 0;
-
-QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(Optimal, Q_MOVABLE_TYPE);
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(Optimal);
-
-int qHash(const Optimal& key)
-{
- return qHash(key.i);
-}
-
-struct Complex
-{
- Complex(int val = 0)
- : value(val)
- , checkSum(this)
- {
- ++liveCount;
- }
-
- Complex(Complex const &other)
- : value(other.value)
- , checkSum(this)
- {
- ++liveCount;
- }
-
- Complex &operator=(Complex const &other)
- {
- check(); other.check();
-
- value = other.value;
- return *this;
- }
-
- ~Complex()
- {
- --liveCount;
- check();
- }
-
- operator int() const { return value; }
-
- bool operator==(Complex const &other) const
- {
- check(); other.check();
- return value == other.value;
- }
-
- bool operator<(Complex const &other) const
- {
- check(); other.check();
- return value < other.value;
- }
-
- void check() const
- {
- QVERIFY(this == checkSum);
- }
-
- static int getLiveCount() { return liveCount; }
-private:
- static int liveCount;
-
- int value;
- void *checkSum;
-};
-
-int Complex::liveCount = 0;
-
-Q_DECLARE_METATYPE(Complex);
-
-// Tests depend on the fact that:
-Q_STATIC_ASSERT(!QTypeInfo<int>::isStatic);
-Q_STATIC_ASSERT(!QTypeInfo<int>::isComplex);
-Q_STATIC_ASSERT(!QTypeInfo<Movable>::isStatic);
-Q_STATIC_ASSERT(QTypeInfo<Movable>::isComplex);
-Q_STATIC_ASSERT(!QTypeInfo<Optimal>::isStatic);
-Q_STATIC_ASSERT(QTypeInfo<Optimal>::isComplex);
-Q_STATIC_ASSERT(QTypeInfo<Complex>::isStatic);
-Q_STATIC_ASSERT(QTypeInfo<Complex>::isComplex);
-// iow:
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<int, QListData::NotIndirectLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<int, QListData::IndirectLayout> ::value));
-
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Optimal, QListData::InlineWithPaddingLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Optimal, QListData::NotArrayCompatibleLayout>::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Optimal, QListData::NotIndirectLayout> ::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Optimal, QListData::ArrayCompatibleLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Optimal, QListData::IndirectLayout> ::value));
-
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Movable, QListData::InlineWithPaddingLayout> ::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Movable, QListData::NotArrayCompatibleLayout>::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Movable, QListData::NotIndirectLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Movable, QListData::ArrayCompatibleLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Movable, QListData::IndirectLayout> ::value));
-
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Complex, QListData::InlineWithPaddingLayout> ::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Complex, QListData::NotArrayCompatibleLayout>::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Complex, QListData::NotIndirectLayout> ::value));
-Q_STATIC_ASSERT((!is_qlist_array_memory_layout<Complex, QListData::ArrayCompatibleLayout> ::value));
-Q_STATIC_ASSERT(( is_qlist_array_memory_layout<Complex, QListData::IndirectLayout> ::value));
-
-class tst_QList : public QObject
-{
- Q_OBJECT
-
-private slots:
- void lengthOptimal() const;
- void lengthMovable() const;
- void lengthComplex() const;
- void lengthSignature() const;
- void appendOptimal() const;
- void appendMovable() const;
- void appendComplex() const;
- void prepend() const;
- void midOptimal() const;
- void midMovable() const;
- void midComplex() const;
- void atOptimal() const;
- void atMovable() const;
- void atComplex() const;
- void firstOptimal() const;
- void firstMovable() const;
- void firstComplex() const;
- void lastOptimal() const;
- void lastMovable() const;
- void lastComplex() const;
- void constFirst() const;
- void constLast() const;
- void cpp17ctad() const;
- void beginOptimal() const;
- void beginMovable() const;
- void beginComplex() const;
- void endOptimal() const;
- void endMovable() const;
- void endComplex() const;
- void containsOptimal() const;
- void containsMovable() const;
- void containsComplex() const;
- void countOptimal() const;
- void countMovable() const;
- void countComplex() const;
- void emptyOptimal() const;
- void emptyMovable() const;
- void emptyComplex() const;
- void endsWithOptimal() const;
- void endsWithMovable() const;
- void endsWithComplex() const;
- void lastIndexOfOptimal() const;
- void lastIndexOfMovable() const;
- void lastIndexOfComplex() const;
- void moveOptimal() const;
- void moveMovable() const;
- void moveComplex() const;
- void removeAllOptimal() const;
- void removeAllMovable() const;
- void removeAllComplex() const;
- void removeAtOptimal() const;
- void removeAtMovable() const;
- void removeAtComplex() const;
- void removeOneOptimal() const;
- void removeOneMovable() const;
- void removeOneComplex() const;
- 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;
- void swapOptimal() const;
- void swapMovable() const;
- void swapComplex() const;
- void takeAtOptimal() const;
- void takeAtMovable() const;
- void takeAtComplex() const;
- void takeFirstOptimal() const;
- void takeFirstMovable() const;
- void takeFirstComplex() const;
- void takeLastOptimal() const;
- void takeLastMovable() const;
- void takeLastComplex() const;
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- void toSetOptimal() const;
- void toSetMovable() const;
- void toSetComplex() const;
- void toStdListOptimal() const;
- void toStdListMovable() const;
- void toStdListComplex() const;
-#endif
- void toVectorOptimal() const;
- void toVectorMovable() const;
- void toVectorComplex() const;
- void valueOptimal() const;
- void valueMovable() const;
- void valueComplex() const;
-
- void testOperatorsOptimal() const;
- void testOperatorsMovable() const;
- void testOperatorsComplex() const;
- void testSTLIteratorsOptimal() const;
- void testSTLIteratorsMovable() const;
- void testSTLIteratorsComplex() const;
-
- void initializeList() const;
-
- void constSharedNullOptimal() const;
- void constSharedNullMovable() const;
- void constSharedNullComplex() const;
- void setSharableInt_data() const;
- void setSharableInt() const;
- void setSharableComplex_data() const;
- void setSharableComplex() const;
- 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;
- template<typename T> void append() const;
- template<typename T> void mid() const;
- template<typename T> void at() const;
- template<typename T> void first() const;
- template<typename T> void last() const;
- template<typename T> void begin() const;
- template<typename T> void end() const;
- template<typename T> void contains() const;
- template<typename T> void count() const;
- template<typename T> void empty() const;
- 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;
- template<typename T> void takeFirst() const;
- template<typename T> void takeLast() const;
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- template<typename T> void toSet() const;
- template<typename T> void toStdList() const;
-#endif
- template<typename T> void toVector() const;
- template<typename T> void value() const;
-
- template<typename T> void testOperators() const;
- template<typename T> void testSTLIterators() const;
-
- template<typename T> void constSharedNull() const;
-
- int dummyForGuard;
-};
-
-template<typename T> struct SimpleValue
-{
- static T at(int index)
- {
- return values[index % maxSize];
- }
- static const uint maxSize = 7;
- static const T values[maxSize];
-};
-
-template<>
-const Optimal SimpleValue<Optimal>::values[] = { 10, 20, 30, 40, 100, 101, 102 };
-template<>
-const Movable SimpleValue<Movable>::values[] = { 10, 20, 30, 40, 100, 101, 102 };
-template<>
-const Complex SimpleValue<Complex>::values[] = { 10, 20, 30, 40, 100, 101, 102 };
-
-// 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)
-#define T_WEEE SimpleValue<T>::at(6)
-
-template<typename T>
-void tst_QList::length() const
-{
- /* Empty list. */
- {
- const QList<T> list;
- QCOMPARE(list.length(), 0);
- }
-
- /* One entry. */
- {
- QList<T> list;
- list.append(T_FOO);
- QCOMPARE(list.length(), 1);
- }
-
- /* Two entries. */
- {
- QList<T> list;
- list.append(T_FOO);
- list.append(T_BAR);
- QCOMPARE(list.length(), 2);
- }
-
- /* Three entries. */
- {
- QList<T> list;
- list.append(T_FOO);
- list.append(T_BAR);
- list.append(T_BAZ);
- QCOMPARE(list.length(), 3);
- }
-}
-
-void tst_QList::lengthOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- length<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::lengthMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- length<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::lengthComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- length<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-void tst_QList::lengthSignature() const
-{
- /* Constness. */
- {
- const QList<int> list;
- /* The function should be const. */
- list.length();
- }
-}
-
-template<typename T>
-void tst_QList::append() const
-{
- /* test append(const QList<T> &) function */
- T one(T_FOO);
- T two(T_BAR);
- T three(T_BAZ);
- T four(T_CAT);
- QList<T> list1;
- QList<T> list2;
- QList<T> listTotal;
- list1.append(one);
- list1.append(two);
- list2.append(three);
- list2.append(four);
- list1.append(list2);
- listTotal.append(one);
- listTotal.append(two);
- listTotal.append(three);
- listTotal.append(four);
- QCOMPARE(list1, listTotal);
-}
-
-void tst_QList::appendOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- append<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::appendMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- append<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::appendComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- append<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-void tst_QList::prepend() const
-{
- QList<int *> list;
- int *t1 = new int(0);
- list.prepend(t1);
- QVERIFY(list.size() == 1);
- QVERIFY(list.at(0) == t1);
- int *t2 = new int(0);
- list.prepend(t2);
- QVERIFY(list.size() == 2);
- QVERIFY(list.at(0) == t2);
- QVERIFY(list.at(1) == t1);
- int *t3 = new int(0);
- list.prepend(t3);
- QVERIFY(list.size() == 3);
- QVERIFY(list.at(0) == t3);
- QVERIFY(list.at(1) == t2);
- QVERIFY(list.at(2) == t1);
- list.removeAll(t2);
- delete t2;
- QVERIFY(list.size() == 2);
- QVERIFY(list.at(0) == t3);
- QVERIFY(list.at(1) == t1);
- int *t4 = new int(0);
- list.prepend(t4);
- QVERIFY(list.size() == 3);
- QVERIFY(list.at(0) == t4);
- QVERIFY(list.at(1) == t3);
- QVERIFY(list.at(2) == t1);
- qDeleteAll(list);
- list.clear();
-}
-
-template<typename T>
-void tst_QList::mid() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ << T_CAT << T_DOG << T_BLAH << T_WEEE;
-
- QCOMPARE(list.mid(3, 3),
- QList<T>() << T_CAT << T_DOG << T_BLAH);
-
- QList<T> list1;
- QCOMPARE(list1.mid(1, 1).length(), 0);
-}
-
-void tst_QList::midOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- mid<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::midMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- mid<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::midComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- mid<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::at() const
-{
- // test at() and make sure it functions correctly with some simple list manipulation.
- QList<T> list;
-
- // create a list
- list << T_FOO << T_BAR << T_BAZ;
- QVERIFY(list.size() == 3);
- QCOMPARE(list.at(0), T_FOO);
- QCOMPARE(list.at(1), T_BAR);
- QCOMPARE(list.at(2), T_BAZ);
-
- // append an item
- list << T_CAT;
- QVERIFY(list.size() == 4);
- QCOMPARE(list.at(0), T_FOO);
- QCOMPARE(list.at(1), T_BAR);
- QCOMPARE(list.at(2), T_BAZ);
- QCOMPARE(list.at(3), T_CAT);
-
- // remove an item
- list.removeAt(1);
- QVERIFY(list.size() == 3);
- QCOMPARE(list.at(0), T_FOO);
- QCOMPARE(list.at(1), T_BAZ);
- QCOMPARE(list.at(2), T_CAT);
-}
-
-void tst_QList::atOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- at<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::atMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- at<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::atComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- at<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::first() const
-{
- QList<T> list;
- list << T_FOO << T_BAR;
-
- QCOMPARE(list.first(), T_FOO);
-
- // remove an item, make sure it still works
- list.pop_front();
- QVERIFY(list.size() == 1);
- QCOMPARE(list.first(), T_BAR);
-}
-
-void tst_QList::firstOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- first<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::firstMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- first<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::firstComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- first<Complex>();
- 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));
-}
-
-void tst_QList::cpp17ctad() const
-{
-#ifdef __cpp_deduction_guides
-#define QVERIFY_IS_LIST_OF(obj, Type) \
- QVERIFY2((std::is_same<decltype(obj), QList<Type>>::value), \
- QMetaType::typeName(qMetaTypeId<decltype(obj)::value_type>()))
-#define CHECK(Type, One, Two, Three) \
- do { \
- const Type v[] = {One, Two, Three}; \
- QList v1 = {One, Two, Three}; \
- QVERIFY_IS_LIST_OF(v1, Type); \
- QList v2(v1.begin(), v1.end()); \
- QVERIFY_IS_LIST_OF(v2, Type); \
- QList v3(std::begin(v), std::end(v)); \
- QVERIFY_IS_LIST_OF(v3, Type); \
- } while (false) \
- /*end*/
- CHECK(int, 1, 2, 3);
- CHECK(double, 1.0, 2.0, 3.0);
- CHECK(QString, QStringLiteral("one"), QStringLiteral("two"), QStringLiteral("three"));
-#undef QVERIFY_IS_LIST_OF
-#undef CHECK
-#else
- QSKIP("This test requires C++17 Constructor Template Argument Deduction support enabled in the compiler.");
-#endif
-}
-
-template<typename T>
-void tst_QList::last() const
-{
- QList<T> list;
- list << T_FOO << T_BAR;
-
- QCOMPARE(list.last(), T_BAR);
-
- // remove an item, make sure it still works
- list.pop_back();
- QVERIFY(list.size() == 1);
- QCOMPARE(list.last(), T_FOO);
-}
-
-void tst_QList::lastOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- last<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::lastMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- last<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::lastComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- last<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::begin() const
-{
- QList<T> list;
- list << T_FOO << T_BAR;
-
- QCOMPARE(*list.begin(), T_FOO);
-
- // remove an item, make sure it still works
- list.pop_front();
- QVERIFY(list.size() == 1);
- QCOMPARE(*list.begin(), T_BAR);
-}
-
-void tst_QList::beginOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- begin<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::beginMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- begin<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::beginComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- begin<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::end() const
-{
- QList<T> list;
- list << T_FOO << T_BAR;
-
- QCOMPARE(*--list.end(), T_BAR);
-
- // remove an item, make sure it still works
- list.pop_back();
- QVERIFY(list.size() == 1);
- QCOMPARE(*--list.end(), T_FOO);
-}
-
-void tst_QList::endOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- end<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::endMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- end<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::endComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- end<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::contains() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- 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));
-}
-
-void tst_QList::containsOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- contains<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::containsMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- contains<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::containsComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- contains<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::count() const
-{
- QList<T> list;
-
- // starts empty
- QVERIFY(list.count() == 0);
-
- // goes up
- list.append(T_FOO);
- QVERIFY(list.count() == 1);
-
- // and up
- list.append(T_BAR);
- QVERIFY(list.count() == 2);
-
- // and down
- list.pop_back();
- QVERIFY(list.count() == 1);
-
- // and empty. :)
- list.pop_back();
- QVERIFY(list.count() == 0);
-}
-
-void tst_QList::countOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- count<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::countMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- count<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::countComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- count<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::empty() const
-{
- QList<T> list;
-
- // make sure it starts empty
- QVERIFY(list.empty());
-
- // and doesn't stay empty
- list.append(T_FOO);
- QVERIFY(!list.empty());
-
- // and goes back to being empty
- list.pop_back();
- QVERIFY(list.empty());
-}
-
-void tst_QList::emptyOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- empty<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::emptyMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- empty<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::emptyComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- empty<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::endsWith() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // test it returns correctly in both cases
- QVERIFY(list.endsWith(T_BAZ));
- QVERIFY(!list.endsWith(T_BAR));
-
- // remove an item and make sure the end item changes
- list.pop_back();
- QVERIFY(list.endsWith(T_BAR));
-}
-
-void tst_QList::endsWithOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- endsWith<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::endsWithMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- endsWith<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::endsWithComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- endsWith<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::lastIndexOf() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // one instance of the target item
- QVERIFY(list.lastIndexOf(T_BAZ) == 2);
-
- // shouldn't find this
- QVERIFY(list.lastIndexOf(T_WEEE) == -1);
-
- // multiple instances
- list.append(T_BAZ);
- list.append(T_BAZ);
- QVERIFY(list.lastIndexOf(T_BAZ) == 4);
-
- // search from the middle to find the last one
- QVERIFY(list.lastIndexOf(T_BAZ, 3) == 3);
-
- // try to find none
- QVERIFY(list.lastIndexOf(T_BAZ, 1) == -1);
-}
-
-void tst_QList::lastIndexOfOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- lastIndexOf<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::lastIndexOfMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- lastIndexOf<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::lastIndexOfComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- lastIndexOf<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::move() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // move an item
- list.move(0, list.count() - 1);
- QCOMPARE(list, QList<T>() << T_BAR << T_BAZ << T_FOO);
-
- // move it back
- list.move(list.count() - 1, 0);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ);
-
- // move an item in the middle
- list.move(1, 0);
- QCOMPARE(list, QList<T>() << T_BAR << T_FOO << T_BAZ);
-}
-
-void tst_QList::moveOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- move<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::moveMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- move<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::moveComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- move<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::removeAll() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // remove one instance
- list.removeAll(T_BAR);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAZ);
-
- // many instances
- list << T_FOO << T_BAR << T_BAZ << T_FOO << T_BAR << T_BAZ << T_FOO << T_BAR << T_BAZ;
- list.removeAll(T_BAR);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAZ << T_FOO << T_BAZ << T_FOO << T_BAZ << T_FOO << T_BAZ);
-
- // try remove something that doesn't exist
- list.removeAll(T_WEEE);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAZ << T_FOO << T_BAZ << T_FOO << T_BAZ << T_FOO << T_BAZ);
-}
-
-void tst_QList::removeAllOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- removeAll<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::removeAllMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- removeAll<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::removeAllComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- removeAll<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::removeAt() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // middle
- list.removeAt(1);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAZ);
-
- // start
- list.removeAt(0);
- QCOMPARE(list, QList<T>() << T_BAZ);
-
- // final
- list.removeAt(0);
- QCOMPARE(list, QList<T>());
-}
-
-void tst_QList::removeAtOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- removeAt<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::removeAtMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- removeAt<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::removeAtComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- removeAt<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::removeOne() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // middle
- list.removeOne(T_BAR);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAZ);
-
- // start
- list.removeOne(T_FOO);
- QCOMPARE(list, QList<T>() << T_BAZ);
-
- // last
- list.removeOne(T_BAZ);
- QCOMPARE(list, QList<T>());
-
- // make sure it really only removes one :)
- list << T_FOO << T_FOO;
- list.removeOne(T_FOO);
- QCOMPARE(list, QList<T>() << T_FOO);
-
- // try remove something that doesn't exist
- list.removeOne(T_WEEE);
- QCOMPARE(list, QList<T>() << T_FOO);
-}
-
-void tst_QList::removeOneOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- removeOne<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::removeOneMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- removeOne<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::removeOneComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- removeOne<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::replace() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // start
- list.replace(0, T_CAT);
- QCOMPARE(list, QList<T>() << T_CAT
- << T_BAR << T_BAZ);
-
- // middle
- list.replace(1, T_DOG);
- QCOMPARE(list, QList<T>() << T_CAT
- << T_DOG << T_BAZ);
-
- // end
- list.replace(2, T_BLAH);
- QCOMPARE(list, QList<T>() << T_CAT
- << T_DOG << T_BLAH);
-}
-
-void tst_QList::replaceOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- replace<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::replaceMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- replace<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::replaceComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- replace<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-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;
- list << T_FOO << T_BAR << T_BAZ;
-
- // make sure it starts ok
- QVERIFY(list.startsWith(T_FOO));
-
- // remove an item
- list.removeFirst();
- QVERIFY(list.startsWith(T_BAR));
-}
-
-void tst_QList::startsWithOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- startsWith<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::startsWithMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- startsWith<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::startsWithComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- startsWith<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::swap() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // swap
- list.swapItemsAt(0, 2);
- QCOMPARE(list, QList<T>() << T_BAZ << T_BAR << T_FOO);
-
- // swap again
- list.swapItemsAt(1, 2);
- QCOMPARE(list, QList<T>() << T_BAZ << T_FOO << T_BAR);
-
- QList<T> list2;
- list2 << T_DOG << T_BLAH;
-
- list.swap(list2);
- QCOMPARE(list, QList<T>() << T_DOG << T_BLAH);
- QCOMPARE(list2, QList<T>() << T_BAZ << T_FOO << T_BAR);
-}
-
-void tst_QList::swapOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- swap<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::swapMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- swap<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::swapComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- swap<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::takeAt() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- QCOMPARE(list.takeAt(0), T_FOO);
- QVERIFY(list.size() == 2);
- QCOMPARE(list.takeAt(1), T_BAZ);
- QVERIFY(list.size() == 1);
- QCOMPARE(list.takeAt(0), T_BAR);
- QVERIFY(list.size() == 0);
-}
-
-void tst_QList::takeAtOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- takeAt<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::takeAtMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- takeAt<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::takeAtComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- takeAt<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::takeFirst() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- QCOMPARE(list.takeFirst(), T_FOO);
- QVERIFY(list.size() == 2);
- QCOMPARE(list.takeFirst(), T_BAR);
- QVERIFY(list.size() == 1);
- QCOMPARE(list.takeFirst(), T_BAZ);
- QVERIFY(list.size() == 0);
-}
-
-void tst_QList::takeFirstOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- takeFirst<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::takeFirstMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- takeFirst<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::takeFirstComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- takeFirst<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::takeLast() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- QCOMPARE(list.takeLast(), T_BAZ);
- QCOMPARE(list.takeLast(), T_BAR);
- QCOMPARE(list.takeLast(), T_FOO);
-}
-
-void tst_QList::takeLastOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- takeLast<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::takeLastMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- takeLast<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::takeLastComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- takeLast<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-template<typename T>
-void tst_QList::toSet() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // no duplicates
- QCOMPARE(list.toSet(), QSet<T>() << T_FOO << T_BAR << T_BAZ);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ);
-
- // duplicates (is this more of a QSet test?)
- list << T_FOO << T_BAR << T_BAZ;
- QCOMPARE(list.toSet(), QSet<T>() << T_FOO << T_BAR << T_BAZ);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ
- << T_FOO << T_BAR << T_BAZ);
-}
-
-void tst_QList::toSetOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- toSet<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::toSetMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- toSet<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::toSetComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- toSet<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::toStdList() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // yuck.
- std::list<T> slist;
- slist.push_back(T_FOO);
- slist.push_back(T_BAR);
- slist.push_back(T_BAZ);
-
- QCOMPARE(list.toStdList(), slist);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ);
-}
-
-void tst_QList::toStdListOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- toStdList<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::toStdListMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- toStdList<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::toStdListComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- toStdList<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-#endif
-
-template<typename T>
-void tst_QList::toVector() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- QCOMPARE(list.toVector(), QVector<T>() << T_FOO << T_BAR << T_BAZ);
-}
-
-void tst_QList::toVectorOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- toVector<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::toVectorMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- toVector<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::toVectorComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- toVector<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::value() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- // test real values
- QCOMPARE(list.value(0), T_FOO);
- QCOMPARE(list.value(2), T_BAZ);
-
- // test empty default
- QCOMPARE(list.value(3), T());
- QCOMPARE(list.value(-1), T());
-
- // test defaults
- T defaultT(T_WEEE);
- QCOMPARE(list.value(-1, defaultT), defaultT);
- QCOMPARE(list.value(3, defaultT), defaultT);
-}
-
-void tst_QList::valueOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- value<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::valueMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- value<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::valueComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- value<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::testOperators() const
-{
- QList<T> list;
- list << T_FOO << T_BAR << T_BAZ;
-
- QList<T> listtwo;
- listtwo << T_FOO << T_BAR << T_BAZ;
-
- // test equal
- QVERIFY(list == listtwo);
-
- // not equal
- listtwo.append(T_CAT);
- QVERIFY(list != listtwo);
-
- // +=
- list += listtwo;
- QVERIFY(list.size() == 7);
- QVERIFY(listtwo.size() == 4);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ
- << T_FOO << T_BAR << T_BAZ << T_CAT);
-
- // =
- list = listtwo;
- QCOMPARE(list, listtwo);
- QCOMPARE(list, QList<T>() << T_FOO << T_BAR << T_BAZ << T_CAT);
-
- // []
- 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
-{
- const int liveCount = Optimal::getLiveCount();
- testOperators<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::testOperatorsMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- testOperators<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::testOperatorsComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- testOperators<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template<typename T>
-void tst_QList::testSTLIterators() const
-{
- QList<T> list;
-
- // create a list
- list << T_FOO << T_BAR << T_BAZ;
- typename QList<T>::iterator it = list.begin();
- QCOMPARE(*it, T_FOO); it++;
- QCOMPARE(*it, T_BAR); it++;
- QCOMPARE(*it, T_BAZ); it++;
- QCOMPARE(it, list.end()); it--;
-
- // walk backwards
- QCOMPARE(*it, T_BAZ); it--;
- QCOMPARE(*it, T_BAR); it--;
- QCOMPARE(*it, T_FOO);
-
- // test erase
- it = list.erase(it);
- QVERIFY(list.size() == 2);
- QCOMPARE(*it, T_BAR);
-
- // test multiple erase
- it = list.erase(it, it + 2);
- QVERIFY(list.size() == 0);
- QCOMPARE(it, list.end());
-
- // insert again
- it = list.insert(it, T_FOO);
- QVERIFY(list.size() == 1);
- QCOMPARE(*it, T_FOO);
-
- // insert again
- it = list.insert(it, T_BAR);
- QVERIFY(list.size() == 2);
- QCOMPARE(*it++, T_BAR);
- QCOMPARE(*it, T_FOO);
-}
-
-void tst_QList::testSTLIteratorsOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- testSTLIterators<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::testSTLIteratorsMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- testSTLIterators<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::testSTLIteratorsComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- testSTLIterators<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-void tst_QList::initializeList() const
-{
- QList<int> v1{2,3,4};
- QCOMPARE(v1, QList<int>() << 2 << 3 << 4);
- QCOMPARE(v1, (QList<int>{2,3,4}));
-
- QList<QList<int>> v2{ v1, {1}, QList<int>(), {2,3,4} };
- QList<QList<int>> v3;
- v3 << v1 << (QList<int>() << 1) << QList<int>() << v1;
- QCOMPARE(v3, v2);
-}
-
-template<typename T>
-void tst_QList::constSharedNull() const
-{
- QList<T> list2;
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QList<T> list1;
- list1.setSharable(false);
- QVERIFY(list1.isDetached());
-
- list2.setSharable(true);
-#endif
- QVERIFY(!list2.isDetached());
-}
-
-void tst_QList::constSharedNullOptimal() const
-{
- const int liveCount = Optimal::getLiveCount();
- constSharedNull<Optimal>();
- QCOMPARE(liveCount, Optimal::getLiveCount());
-}
-
-void tst_QList::constSharedNullMovable() const
-{
- const int liveCount = Movable::getLiveCount();
- constSharedNull<Movable>();
- QCOMPARE(liveCount, Movable::getLiveCount());
-}
-
-void tst_QList::constSharedNullComplex() const
-{
- const int liveCount = Complex::getLiveCount();
- constSharedNull<Complex>();
- QCOMPARE(liveCount, Complex::getLiveCount());
-}
-
-template <class T>
-void generateSetSharableData()
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QTest::addColumn<QList<T> >("list");
- QTest::addColumn<int>("size");
-
- QTest::newRow("null") << QList<T>() << 0;
- QTest::newRow("non-empty") << (QList<T>() << T(0) << T(1) << T(2) << T(3) << T(4)) << 5;
-#endif
-}
-
-template <class T>
-void runSetSharableTest()
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QFETCH(QList<T>, list);
- QFETCH(int, size);
-
- QVERIFY(!list.isDetached()); // Shared with QTest
-
- list.setSharable(true);
-
- QCOMPARE(list.size(), size);
-
- {
- QList<T> copy(list);
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(list));
- }
-
- list.setSharable(false);
- QVERIFY(list.isDetached() || list.isSharedWith(QList<T>()));
-
- {
- QList<T> copy(list);
-
- QVERIFY(copy.isDetached() || copy.isSharedWith(QList<T>()));
- QCOMPARE(copy.size(), size);
- QCOMPARE(copy, list);
- }
-
- list.setSharable(true);
-
- {
- QList<T> copy(list);
-
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(list));
- }
-
- for (int i = 0; i < list.size(); ++i)
- QCOMPARE(int(list[i]), i);
-
- QCOMPARE(list.size(), size);
-#endif
-}
-
-void tst_QList::setSharableInt_data() const
-{
- generateSetSharableData<int>();
-}
-
-void tst_QList::setSharableComplex_data() const
-{
- generateSetSharableData<Complex>();
-}
-
-void tst_QList::setSharableInt() const
-{
- runSetSharableTest<int>();
-}
-
-void tst_QList::setSharableComplex() const
-{
- runSetSharableTest<Complex>();
-}
-
-void tst_QList::eraseValidIteratorsOnSharedList() const
-{
- QList<int> a, b;
- a.push_back(10);
- a.push_back(20);
- a.push_back(30);
- QList<int>::iterator i = a.begin();
- ++i;
- b = a;
- a.erase(i);
- QCOMPARE(b.size(), 3);
- QCOMPARE(a.size(), 2);
- QCOMPARE(a.at(0), 10);
- QCOMPARE(a.at(1), 30);
-
- a.push_back(40);
- a.push_back(50);
- a.push_back(60);
- QCOMPARE(a.size(), 5);
- i = a.begin();
- b = a;
- ++i;
- QList<int>::iterator j = i;
- ++j;
- ++j;
- a.erase(i, j); // remove 3 elements
- QCOMPARE(b.size(), 5);
- QCOMPARE(a.size(), 3);
- QCOMPARE(a.at(0), 10);
- QCOMPARE(a.at(1), 50);
-}
-
-void tst_QList::insertWithValidIteratorsOnSharedList() const
-{
- QList<int> a, b;
- a.push_back(10);
- a.push_back(20);
- a.push_back(30);
- QList<int>::iterator i = a.begin();
- ++i;
- b = a;
- a.insert(i, 15);
- QCOMPARE(a.size(), b.size() + 1);
- QCOMPARE(b.at(1), 20);
- 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:
- // This test depends on QList's current behavior that ints are stored in the array itself.
- // This test would not work for QList<Complex>.
- int capacity = 100;
- QList<int> list;
- list.reserve(capacity);
- list << 0;
- int *data = &list[0];
-
- for (int i = 1; i < capacity; i++) {
- list << i;
- QCOMPARE(&list.at(0), data);
- }
-
- QList<int> copy = list;
- list.reserve(capacity / 2);
- QCOMPARE(list.size(), capacity); // we didn't shrink the size!
-
- copy = list;
- list.reserve(capacity * 2);
- QCOMPARE(list.size(), capacity);
- QVERIFY(&list.at(0) != data);
-}
-
-QTEST_APPLESS_MAIN(tst_QList)
-#include "tst_qlist.moc"
diff --git a/tests/auto/corelib/tools/qlist_strictiterators/qlist_strictiterators.pro b/tests/auto/corelib/tools/qlist_strictiterators/qlist_strictiterators.pro
deleted file mode 100644
index e39ad38919..0000000000
--- a/tests/auto/corelib/tools/qlist_strictiterators/qlist_strictiterators.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-include(../qlist/qlist.pro)
-TARGET = tst_qlist_strictiterators
-DEFINES += QT_STRICT_ITERATORS tst_QList=tst_QList_StrictIterators
diff --git a/tests/auto/corelib/tools/qmap/tst_qmap.cpp b/tests/auto/corelib/tools/qmap/tst_qmap.cpp
index c3a8a88f0c..1638ebc992 100644
--- a/tests/auto/corelib/tools/qmap/tst_qmap.cpp
+++ b/tests/auto/corelib/tools/qmap/tst_qmap.cpp
@@ -68,7 +68,6 @@ private slots:
void const_shared_null();
void equal_range();
- void setSharable();
void insert();
void insertMap();
@@ -1066,13 +1065,6 @@ void tst_QMap::qmultimap_specific()
void tst_QMap::const_shared_null()
{
QMap<int, QString> map2;
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QMap<int, QString> map1;
- map1.setSharable(false);
- QVERIFY(map1.isDetached());
-
- map2.setSharable(true);
-#endif
QVERIFY(!map2.isDetached());
}
@@ -1161,61 +1153,6 @@ const T &const_(const T &t)
return t;
}
-void tst_QMap::setSharable()
-{
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- QMap<int, QString> map;
-
- map.insert(1, "um");
- map.insert(2, "dois");
- map.insert(4, "quatro");
- map.insert(5, "cinco");
-
- map.setSharable(true);
- QCOMPARE(map.size(), 4);
- QCOMPARE(const_(map)[4], QString("quatro"));
-
- {
- QMap<int, QString> copy(map);
-
- QVERIFY(!map.isDetached());
- QVERIFY(copy.isSharedWith(map));
- sanityCheckTree(copy, __LINE__);
- }
-
- map.setSharable(false);
- sanityCheckTree(map, __LINE__);
- QVERIFY(map.isDetached());
- QCOMPARE(map.size(), 4);
- QCOMPARE(const_(map)[4], QString("quatro"));
-
- {
- QMap<int, QString> copy(map);
-
- QVERIFY(map.isDetached());
- QVERIFY(copy.isDetached());
-
- QCOMPARE(copy.size(), 4);
- QCOMPARE(const_(copy)[4], QString("quatro"));
-
- QCOMPARE(map, copy);
- sanityCheckTree(map, __LINE__);
- sanityCheckTree(copy, __LINE__);
- }
-
- map.setSharable(true);
- QCOMPARE(map.size(), 4);
- QCOMPARE(const_(map)[4], QString("quatro"));
-
- {
- QMap<int, QString> copy(map);
-
- QVERIFY(!map.isDetached());
- QVERIFY(copy.isSharedWith(map));
- }
-#endif
-}
-
void tst_QMap::insert()
{
QMap<QString, float> map;
@@ -1510,17 +1447,16 @@ void tst_QMap::testInsertMultiWithHint()
{
QMap<int, int> map;
- typedef QMap<int, int>::const_iterator cite; // Hack since we define QT_STRICT_ITERATORS
- map.insertMulti(cite(map.end()), 64, 65);
+ map.insertMulti(map.end(), 64, 65);
map[128] = 129;
map[256] = 257;
sanityCheckTree(map, __LINE__);
- map.insertMulti(cite(map.end()), 512, 513);
- map.insertMulti(cite(map.end()), 512, 513 * 2);
+ map.insertMulti(map.end(), 512, 513);
+ map.insertMulti(map.end(), 512, 513 * 2);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 5);
- map.insertMulti(cite(map.end()), 256, 258); // wrong hint
+ map.insertMulti(map.end(), 256, 258); // wrong hint
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 6);
@@ -1532,23 +1468,23 @@ void tst_QMap::testInsertMultiWithHint()
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 8);
- j = map.insertMulti(cite(j), 68, 259);
+ j = map.insertMulti(j, 68, 259);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 9);
- j = map.insertMulti(cite(j), 67, 67);
+ j = map.insertMulti(j, 67, 67);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 10);
- i = map.insertMulti(cite(i), 256, 259);
+ i = map.insertMulti(i, 256, 259);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 11);
- i = map.insertMulti(cite(i), 256, 260);
+ i = map.insertMulti(i, 256, 260);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 12);
- map.insertMulti(cite(i), 64, 67);
+ map.insertMulti(i, 64, 67);
sanityCheckTree(map, __LINE__);
QCOMPARE(map.size(), 13);
diff --git a/tests/auto/corelib/tools/qmap_strictiterators/qmap_strictiterators.pro b/tests/auto/corelib/tools/qmap_strictiterators/qmap_strictiterators.pro
deleted file mode 100644
index 6c1f4727c1..0000000000
--- a/tests/auto/corelib/tools/qmap_strictiterators/qmap_strictiterators.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-include(../qmap/qmap.pro)
-TARGET = tst_qmap_strictiterators
-DEFINES += QT_STRICT_ITERATORS tst_QMap=tst_QMap_StrictIterators
diff --git a/tests/auto/corelib/tools/qset/tst_qset.cpp b/tests/auto/corelib/tools/qset/tst_qset.cpp
index 8a545712a2..6638ad8b60 100644
--- a/tests/auto/corelib/tools/qset/tst_qset.cpp
+++ b/tests/auto/corelib/tools/qset/tst_qset.cpp
@@ -26,8 +26,6 @@
**
****************************************************************************/
-//#define QT_STRICT_ITERATORS
-
#include <QtTest/QtTest>
#include <qset.h>
#include <qdebug.h>
diff --git a/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp b/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
index a1d0100f96..6220cc766a 100644
--- a/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
+++ b/tests/auto/corelib/tools/qvarlengtharray/tst_qvarlengtharray.cpp
@@ -827,7 +827,7 @@ void tst_QVarLengthArray::operators()
// +=: not provided, emulate
//myvla += myvlatwo;
- Q_FOREACH (const QString &s, myvlatwo)
+ for (const QString &s : qAsConst(myvlatwo))
myvla.push_back(s);
QCOMPARE(myvla, combined);
diff --git a/tests/auto/corelib/tools/qvector/tst_qvector.cpp b/tests/auto/corelib/tools/qvector/tst_qvector.cpp
index 08d5a8cd50..7a69e844d4 100644
--- a/tests/auto/corelib/tools/qvector/tst_qvector.cpp
+++ b/tests/auto/corelib/tools/qvector/tst_qvector.cpp
@@ -104,7 +104,7 @@ private:
static void check(const State state1, const State state2)
{
- QCOMPARE(state1, state2);
+ QCOMPARE(int(state1), int(state2));
}
};
@@ -174,7 +174,7 @@ private:
{
// check if c object has been moved
QCOMPARE(c, c->that);
- QCOMPARE(c->state, Constructed);
+ QCOMPARE(int(c->state), int(Constructed));
}
};
QAtomicInt Custom::counter = 0;
@@ -307,22 +307,11 @@ private slots:
void reserve();
void reserveZero();
- void reallocAfterCopy_data();
- void reallocAfterCopy();
void initializeListInt();
void initializeListMovable();
void initializeListCustom();
void const_shared_null();
-#if 1
- // ### Qt6 remove this section
- void setSharableInt_data();
- void setSharableInt();
- void setSharableMovable_data();
- void setSharableMovable();
- void setSharableCustom_data();
- void setSharableCustom();
-#endif
void detachInt() const;
void detachMovable() const;
@@ -358,8 +347,6 @@ private:
template<typename T> void size() const;
template<typename T> void swap() const;
template<typename T> void initializeList();
- template<typename T> void setSharable_data() const;
- template<typename T> void setSharable() const;
template<typename T> void detach() const;
template<typename T> void detachThreadSafety() const;
};
@@ -467,24 +454,6 @@ void tst_QVector::copyConstructor() const
QVector<T> v2(v1);
QCOMPARE(v1, v2);
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v1;
- v1.setSharable(false);
- QVector<T> v2(v1);
- QVERIFY(!v1.isSharedWith(v2));
- QCOMPARE(v1, v2);
- }
- {
- QVector<T> v1;
- v1 << value1 << value2 << value3 << value4;
- v1.setSharable(false);
- QVector<T> v2(v1);
- QVERIFY(!v1.isSharedWith(v2));
- QCOMPARE(v1, v2);
- }
-#endif
}
void tst_QVector::copyConstructorInt() const
@@ -665,17 +634,6 @@ void tst_QVector::append() const
QVERIFY(v.size() == 3);
QCOMPARE(v.at(v.size() - 1), SimpleValue<T>::at(0));
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v(2);
- v.reserve(12);
- v.setSharable(false);
- v.append(SimpleValue<T>::at(0));
- QVERIFY(v.size() == 3);
- QCOMPARE(v.last(), SimpleValue<T>::at(0));
- }
-#endif
{
QVector<int> v;
v << 1 << 2 << 3;
@@ -766,16 +724,12 @@ void tst_QVector::capacity() const
myvec.remove(3);
myvec.remove(3);
myvec.remove(3);
- // TODO: is this a safe assumption? presumably it won't release memory until shrink(), but can we asser that is true?
- QVERIFY(myvec.capacity() >= 6);
myvec.squeeze();
QVERIFY(myvec.capacity() >= 3);
myvec.remove(0);
myvec.remove(0);
myvec.remove(0);
- // TODO: as above note
- QVERIFY(myvec.capacity() >= 3);
myvec.squeeze();
QVERIFY(myvec.capacity() == 0);
}
@@ -1019,20 +973,9 @@ void tst_QVector::endsWith() const
template<typename T>
void tst_QVector::eraseEmpty() const
{
- {
- QVector<T> v;
- v.erase(v.begin(), v.end());
- QCOMPARE(v.size(), 0);
- }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v;
- v.setSharable(false);
- v.erase(v.begin(), v.end());
- QCOMPARE(v.size(), 0);
- }
-#endif
+ QVector<T> v;
+ v.erase(v.begin(), v.end());
+ QCOMPARE(v.size(), 0);
}
void tst_QVector::eraseEmptyInt() const
@@ -1057,22 +1000,10 @@ void tst_QVector::eraseEmptyCustom() const
template<typename T>
void tst_QVector::eraseEmptyReserved() const
{
- {
- QVector<T> v;
- v.reserve(10);
- v.erase(v.begin(), v.end());
- QCOMPARE(v.size(), 0);
- }
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v;
- v.reserve(10);
- v.setSharable(false);
- v.erase(v.begin(), v.end());
- QCOMPARE(v.size(), 0);
- }
-#endif
+ QVector<T> v;
+ v.reserve(10);
+ v.erase(v.begin(), v.end());
+ QCOMPARE(v.size(), 0);
}
void tst_QVector::eraseEmptyReservedInt() const
@@ -1179,21 +1110,6 @@ void tst_QVector::erase(bool shared) const
if (shared)
QCOMPARE(SimpleValue<T>::vector(12), *svc.copy);
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v = SimpleValue<T>::vector(10);
- SharedVectorChecker<T> svc(v, shared);
- v.setSharable(false);
- SharedVectorChecker<T> svc2(v, shared);
- v.erase(v.begin() + 3);
- QCOMPARE(v.size(), 9);
- v.erase(v.begin(), v.end() - 1);
- QCOMPARE(v.size(), 1);
- if (shared)
- QCOMPARE(SimpleValue<T>::vector(10), *svc.copy);
- }
-#endif
}
void tst_QVector::eraseInt() const
@@ -1266,18 +1182,6 @@ template<typename T> void tst_QVector::eraseReserved() const
v.erase(v.begin() + 1, v.end() - 1);
QCOMPARE(v.size(), 2);
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- {
- QVector<T> v(10);
- v.reserve(16);
- v.setSharable(false);
- v.erase(v.begin() + 3);
- QCOMPARE(v.size(), 9);
- v.erase(v.begin(), v.end() - 1);
- QCOMPARE(v.size(), 1);
- }
-#endif
}
void tst_QVector::eraseReservedInt() const
@@ -2019,33 +1923,6 @@ void tst_QVector::resizePOD_data() const
QTest::newRow("emptyReserved") << emptyReserved << 10;
QTest::newRow("nonEmpty") << nonEmpty << 10;
QTest::newRow("nonEmptyReserved") << nonEmptyReserved << 10;
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- QVector<int> nullNotShared;
- QVector<int> emptyNotShared(0, 5);
- QVector<int> emptyReservedNotShared;
- QVector<int> nonEmptyNotShared;
- QVector<int> nonEmptyReservedNotShared;
-
- emptyReservedNotShared.reserve(10);
- nonEmptyReservedNotShared.reserve(15);
- nonEmptyNotShared << 0 << 1 << 2 << 3 << 4;
- nonEmptyReservedNotShared << 0 << 1 << 2 << 3 << 4 << 5 << 6;
- QVERIFY(emptyReservedNotShared.capacity() >= 10);
- QVERIFY(nonEmptyReservedNotShared.capacity() >= 15);
-
- emptyNotShared.setSharable(false);
- emptyReservedNotShared.setSharable(false);
- nonEmptyNotShared.setSharable(false);
- nonEmptyReservedNotShared.setSharable(false);
-
- QTest::newRow("nullNotShared") << nullNotShared << 10;
- QTest::newRow("emptyNotShared") << emptyNotShared << 10;
- QTest::newRow("emptyReservedNotShared") << emptyReservedNotShared << 10;
- QTest::newRow("nonEmptyNotShared") << nonEmptyNotShared << 10;
- QTest::newRow("nonEmptyReservedNotShared") << nonEmptyReservedNotShared << 10;
-#endif
}
void tst_QVector::resizePOD() const
@@ -2094,33 +1971,6 @@ void tst_QVector::resizeComplexMovable_data() const
QTest::newRow("emptyReserved") << emptyReserved << 10;
QTest::newRow("nonEmpty") << nonEmpty << 10;
QTest::newRow("nonEmptyReserved") << nonEmptyReserved << 10;
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- QVector<Movable> nullNotShared;
- QVector<Movable> emptyNotShared(0, 'Q');
- QVector<Movable> emptyReservedNotShared;
- QVector<Movable> nonEmptyNotShared;
- QVector<Movable> nonEmptyReservedNotShared;
-
- emptyReservedNotShared.reserve(10);
- nonEmptyReservedNotShared.reserve(15);
- nonEmptyNotShared << '0' << '1' << '2' << '3' << '4';
- nonEmptyReservedNotShared << '0' << '1' << '2' << '3' << '4' << '5' << '6';
- QVERIFY(emptyReservedNotShared.capacity() >= 10);
- QVERIFY(nonEmptyReservedNotShared.capacity() >= 15);
-
- emptyNotShared.setSharable(false);
- emptyReservedNotShared.setSharable(false);
- nonEmptyNotShared.setSharable(false);
- nonEmptyReservedNotShared.setSharable(false);
-
- QTest::newRow("nullNotShared") << nullNotShared << 10;
- QTest::newRow("emptyNotShared") << emptyNotShared << 10;
- QTest::newRow("emptyReservedNotShared") << emptyReservedNotShared << 10;
- QTest::newRow("nonEmptyNotShared") << nonEmptyNotShared << 10;
- QTest::newRow("nonEmptyReservedNotShared") << nonEmptyReservedNotShared << 10;
-#endif
}
void tst_QVector::resizeComplexMovable() const
@@ -2173,33 +2023,6 @@ void tst_QVector::resizeComplex_data() const
QTest::newRow("emptyReserved") << emptyReserved << 10;
QTest::newRow("nonEmpty") << nonEmpty << 10;
QTest::newRow("nonEmptyReserved") << nonEmptyReserved << 10;
-
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- QVector<Custom> nullNotShared;
- QVector<Custom> emptyNotShared(0, '0');
- QVector<Custom> emptyReservedNotShared;
- QVector<Custom> nonEmptyNotShared;
- QVector<Custom> nonEmptyReservedNotShared;
-
- emptyReservedNotShared.reserve(10);
- nonEmptyReservedNotShared.reserve(15);
- nonEmptyNotShared << '0' << '1' << '2' << '3' << '4';
- nonEmptyReservedNotShared << '0' << '1' << '2' << '3' << '4' << '5' << '6';
- QVERIFY(emptyReservedNotShared.capacity() >= 10);
- QVERIFY(nonEmptyReservedNotShared.capacity() >= 15);
-
- emptyNotShared.setSharable(false);
- emptyReservedNotShared.setSharable(false);
- nonEmptyNotShared.setSharable(false);
- nonEmptyReservedNotShared.setSharable(false);
-
- QTest::newRow("nullNotShared") << nullNotShared << 10;
- QTest::newRow("emptyNotShared") << emptyNotShared << 10;
- QTest::newRow("emptyReservedNotShared") << emptyReservedNotShared << 10;
- QTest::newRow("nonEmptyNotShared") << nonEmptyNotShared << 10;
- QTest::newRow("nonEmptyReservedNotShared") << nonEmptyReservedNotShared << 10;
-#endif
}
void tst_QVector::resizeComplex() const
@@ -2512,87 +2335,6 @@ void tst_QVector::reserveZero()
QVERIFY(vec.capacity() >= 1);
}
-// This is a regression test for QTBUG-11763, where memory would be reallocated
-// soon after copying a QVector.
-void tst_QVector::reallocAfterCopy_data()
-{
- QTest::addColumn<int>("capacity");
- QTest::addColumn<int>("fill_size");
- QTest::addColumn<int>("func_id");
- QTest::addColumn<int>("result1");
- QTest::addColumn<int>("result2");
- QTest::addColumn<int>("result3");
- QTest::addColumn<int>("result4");
-
- int result1, result2, result3, result4;
- int fill_size;
- for (int i = 70; i <= 100; i += 10) {
- const QByteArray prefix = "reallocAfterCopy:" + QByteArray::number(i) + ',';
- fill_size = i - 20;
- for (int j = 0; j <= 3; j++) {
- if (j == 0) { // append
- result1 = i;
- result2 = i;
- result3 = i - 19;
- result4 = i - 20;
- } else if (j == 1) { // insert(0)
- result1 = i;
- result2 = i;
- result3 = i - 19;
- result4 = i - 20;
- } else if (j == 2) { // insert(20)
- result1 = i;
- result2 = i;
- result3 = i - 19;
- result4 = i - 20;
- } else if (j == 3) { // insert(0, 10)
- result1 = i;
- result2 = i;
- result3 = i - 10;
- result4 = i - 20;
- }
- QTest::newRow((prefix + QByteArray::number(j)).constData())
- << i << fill_size << j << result1 << result2 << result3 << result4;
- }
- }
-}
-
-void tst_QVector::reallocAfterCopy()
-{
- QFETCH(int, capacity);
- QFETCH(int, fill_size);
- QFETCH(int, func_id);
- QFETCH(int, result1);
- QFETCH(int, result2);
- QFETCH(int, result3);
- QFETCH(int, result4);
-
- QVector<qreal> v1;
- QVector<qreal> v2;
-
- v1.reserve(capacity);
- v1.resize(0);
- v1.fill(qreal(1.0), fill_size);
-
- v2 = v1;
-
- // no need to test begin() and end(), there is a detach() in them
- if (func_id == 0) {
- v1.append(qreal(1.0)); //push_back is same as append
- } else if (func_id == 1) {
- v1.insert(0, qreal(1.0)); //push_front is same as prepend, insert(0)
- } else if (func_id == 2) {
- v1.insert(20, qreal(1.0));
- } else if (func_id == 3) {
- v1.insert(0, 10, qreal(1.0));
- }
-
- QCOMPARE(v1.capacity(), result1);
- QCOMPARE(v2.capacity(), result2);
- QCOMPARE(v1.size(), result3);
- QCOMPARE(v2.size(), result4);
-}
-
template<typename T>
void tst_QVector::initializeList()
{
@@ -2636,154 +2378,9 @@ void tst_QVector::initializeListCustom()
void tst_QVector::const_shared_null()
{
QVector<int> v2;
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
- // ### Qt6 remove this section
- QVector<int> v1;
- v1.setSharable(false);
- QVERIFY(v1.isDetached());
-
- v2.setSharable(true);
-#endif
QVERIFY(!v2.isDetached());
}
-#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
-// ### Qt6 remove this section
-template<typename T>
-void tst_QVector::setSharable_data() const
-{
- QTest::addColumn<QVector<T> >("vector");
- QTest::addColumn<int>("size");
- QTest::addColumn<int>("capacity");
- QTest::addColumn<bool>("isCapacityReserved");
-
- QVector<T> null;
- QVector<T> empty(0, SimpleValue<T>::at(1));
- QVector<T> emptyReserved;
- QVector<T> nonEmpty;
- QVector<T> nonEmptyReserved;
-
- emptyReserved.reserve(10);
- nonEmptyReserved.reserve(15);
-
- nonEmpty << SimpleValue<T>::at(0) << SimpleValue<T>::at(1) << SimpleValue<T>::at(2) << SimpleValue<T>::at(3) << SimpleValue<T>::at(4);
- nonEmptyReserved << SimpleValue<T>::at(0) << SimpleValue<T>::at(1) << SimpleValue<T>::at(2) << SimpleValue<T>::at(3) << SimpleValue<T>::at(4) << SimpleValue<T>::at(5) << SimpleValue<T>::at(6);
-
- QVERIFY(emptyReserved.capacity() >= 10);
- QVERIFY(nonEmptyReserved.capacity() >= 15);
-
- QTest::newRow("null") << null << 0 << 0 << false;
- QTest::newRow("empty") << empty << 0 << 0 << false;
- QTest::newRow("empty, Reserved") << emptyReserved << 0 << 10 << true;
- QTest::newRow("non-empty") << nonEmpty << 5 << 0 << false;
- QTest::newRow("non-empty, Reserved") << nonEmptyReserved << 7 << 15 << true;
-}
-
-template<typename T>
-void tst_QVector::setSharable() const
-{
- QFETCH(QVector<T>, vector);
- QFETCH(int, size);
- QFETCH(int, capacity);
- QFETCH(bool, isCapacityReserved);
-
- QVERIFY(!vector.isDetached()); // Shared with QTest
-
- vector.setSharable(true);
-
- QCOMPARE(vector.size(), size);
- if (isCapacityReserved)
- QVERIFY2(vector.capacity() >= capacity,
- qPrintable(QString("Capacity is %1, expected at least %2.")
- .arg(vector.capacity())
- .arg(capacity)));
-
- {
- QVector<T> copy(vector);
-
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(vector));
- }
-
- vector.setSharable(false);
- QVERIFY(vector.isDetached() || vector.isSharedWith(QVector<T>()));
-
- {
- QVector<T> copy(vector);
-
- QVERIFY(copy.isDetached() || copy.isEmpty() || copy.isSharedWith(QVector<T>()));
- QCOMPARE(copy.size(), size);
- if (isCapacityReserved)
- QVERIFY2(copy.capacity() >= capacity,
- qPrintable(QString("Capacity is %1, expected at least %2.")
- .arg(copy.capacity())
- .arg(capacity)));
- QCOMPARE(copy, vector);
- }
-
- vector.setSharable(true);
-
- {
- QVector<T> copy(vector);
-
- QVERIFY(!copy.isDetached());
- QVERIFY(copy.isSharedWith(vector));
- }
-
- for (int i = 0; i < vector.size(); ++i)
- QCOMPARE(vector[i], SimpleValue<T>::at(i));
-
- QCOMPARE(vector.size(), size);
- if (isCapacityReserved)
- QVERIFY2(vector.capacity() >= capacity,
- qPrintable(QString("Capacity is %1, expected at least %2.")
- .arg(vector.capacity())
- .arg(capacity)));
-}
-#else
-template<typename T> void tst_QVector::setSharable_data() const
-{
-}
-
-template<typename T> void tst_QVector::setSharable() const
-{
-}
-#endif
-
-void tst_QVector::setSharableInt_data()
-{
- setSharable_data<int>();
-}
-
-void tst_QVector::setSharableMovable_data()
-{
- setSharable_data<Movable>();
-}
-
-void tst_QVector::setSharableCustom_data()
-{
- setSharable_data<Custom>();
-}
-
-void tst_QVector::setSharableInt()
-{
- setSharable<int>();
-}
-
-void tst_QVector::setSharableMovable()
-{
- const int instancesCount = Movable::counter.loadAcquire();
- setSharable<Movable>();
- QCOMPARE(instancesCount, Movable::counter.loadAcquire());
-}
-
-void tst_QVector::setSharableCustom()
-{
- const int instancesCount = Custom::counter.loadAcquire();
- setSharable<Custom>();
- QCOMPARE(instancesCount, Custom::counter.loadAcquire());
-}
-
template<typename T>
void tst_QVector::detach() const
{
@@ -2791,7 +2388,7 @@ void tst_QVector::detach() const
// detach an empty vector
QVector<T> v;
v.detach();
- QVERIFY(v.isDetached());
+ QVERIFY(!v.isDetached());
QCOMPARE(v.size(), 0);
QCOMPARE(v.capacity(), 0);
}
@@ -2801,7 +2398,7 @@ void tst_QVector::detach() const
QVector<T> ref(v);
QVERIFY(!v.isDetached());
v.detach();
- QVERIFY(v.isDetached());
+ QVERIFY(!v.isDetached());
QCOMPARE(v.size(), 0);
QCOMPARE(v.capacity(), 0);
}
diff --git a/tests/auto/corelib/tools/qvector_strictiterators/qvector_strictiterators.pro b/tests/auto/corelib/tools/qvector_strictiterators/qvector_strictiterators.pro
deleted file mode 100644
index d6cad86aac..0000000000
--- a/tests/auto/corelib/tools/qvector_strictiterators/qvector_strictiterators.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-include(../qvector/qvector.pro)
-TARGET = tst_qvector_strictiterators
-DEFINES += QT_STRICT_ITERATORS=1 tst_QVector=tst_QVector_StrictIterators
diff --git a/tests/auto/corelib/tools/tools.pro b/tests/auto/corelib/tools/tools.pro
index 49b2a1f075..be195ea037 100644
--- a/tests/auto/corelib/tools/tools.pro
+++ b/tests/auto/corelib/tools/tools.pro
@@ -4,7 +4,6 @@ SUBDIRS=\
containerapisymmetry \
qalgorithms \
qarraydata \
- qarraydata_strictiterators \
qbitarray \
qcache \
qcommandlineparser \
@@ -12,17 +11,14 @@ SUBDIRS=\
qcryptographichash \
qeasingcurve \
qexplicitlyshareddatapointer \
+ qflatmap \
qfreelist \
qhash \
- qhash_strictiterators \
qhashfunctions \
qline \
qlinkedlist \
- qlist \
- qlist_strictiterators \
qmakearray \
qmap \
- qmap_strictiterators \
qmargins \
qmessageauthenticationcode \
qoffsetstringarray \
@@ -43,7 +39,6 @@ SUBDIRS=\
qtimeline \
qvarlengtharray \
qvector \
- qvector_strictiterators \
qversionnumber
darwin: SUBDIRS += qmacautoreleasepool
diff --git a/tests/auto/dbus/qdbusinterface/tst_qdbusinterface.cpp b/tests/auto/dbus/qdbusinterface/tst_qdbusinterface.cpp
index 05480c6dd2..5453d9de61 100644
--- a/tests/auto/dbus/qdbusinterface/tst_qdbusinterface.cpp
+++ b/tests/auto/dbus/qdbusinterface/tst_qdbusinterface.cpp
@@ -31,6 +31,7 @@
#include <qcoreapplication.h>
#include <qmetatype.h>
#include <QtTest/QtTest>
+#include <QtCore/qregularexpression.h>
#include <QtCore/qvariant.h>
#include <QtDBus/QtDBus>
#include <QtDBus/private/qdbus_symbols_p.h>
@@ -451,14 +452,16 @@ void tst_QDBusInterface::introspectVirtualObject()
QDBusMessage message = QDBusMessage::createMethodCall(con.baseService(), path, "org.freedesktop.DBus.Introspectable", "Introspect");
QDBusMessage reply = con.call(message, QDBus::Block, 5000);
QVERIFY(reply.arguments().at(0).toString().contains(
- QRegExp("<node>.*zitroneneis.*<interface name=") ));
+ QRegularExpression("<node>.*zitroneneis.*<interface name=",
+ QRegularExpression::DotMatchesEverythingOption)));
QDBusMessage message2 = QDBusMessage::createMethodCall(con.baseService(), path + "/foo", "org.freedesktop.DBus.Introspectable", "Introspect");
QDBusMessage reply2 = con.call(message2, QDBus::Block, 5000);
QVERIFY(reply2.arguments().at(0).toString().contains(
- QRegExp("<node>.*<interface name=\"org.qtproject.QtDBus.VirtualObject\">"
- ".*<method name=\"klingeling\" />\n"
- ".*</interface>.*<interface name=") ));
+ QRegularExpression("<node>.*<interface name=\"org.qtproject.QtDBus.VirtualObject\">"
+ ".*<method name=\"klingeling\" />\n"
+ ".*</interface>.*<interface name=",
+ QRegularExpression::DotMatchesEverythingOption)));
}
void tst_QDBusInterface::callMethod()
diff --git a/tests/auto/dbus/qdbusmetatype/tst_qdbusmetatype.cpp b/tests/auto/dbus/qdbusmetatype/tst_qdbusmetatype.cpp
index 4b926dcd05..ec3e71ac8f 100644
--- a/tests/auto/dbus/qdbusmetatype/tst_qdbusmetatype.cpp
+++ b/tests/auto/dbus/qdbusmetatype/tst_qdbusmetatype.cpp
@@ -402,7 +402,7 @@ void tst_QDBusMetaType::invalidTypes()
else if (qstrcmp(QTest::currentDataTag(), "Invalid7") == 0)
QTest::ignoreMessage(QtWarningMsg, "QDBusMarshaller: type `Invalid7' produces invalid D-BUS signature `()' (Did you forget to call beginStructure() ?)");
else if (qstrcmp(QTest::currentDataTag(), "QList<Invalid0>") == 0)
- QTest::ignoreMessage(QtWarningMsg, "QDBusMarshaller: type `QList<Invalid0>' produces invalid D-BUS signature `a' (Did you forget to call beginStructure() ?)");
+ QTest::ignoreMessage(QtWarningMsg, "QDBusMarshaller: type `QVector<Invalid0>' produces invalid D-BUS signature `a' (Did you forget to call beginStructure() ?)");
staticTypes();
staticTypes(); // run twice: the error messages should be printed once only
diff --git a/tests/auto/gui/image/qpicture/tst_qpicture.cpp b/tests/auto/gui/image/qpicture/tst_qpicture.cpp
index ec6bb8dcee..6287960457 100644
--- a/tests/auto/gui/image/qpicture/tst_qpicture.cpp
+++ b/tests/auto/gui/image/qpicture/tst_qpicture.cpp
@@ -37,6 +37,8 @@
#include <qscreen.h>
#include <limits.h>
+#ifndef QT_NO_PICTURE
+
class tst_QPicture : public QObject
{
Q_OBJECT
@@ -45,7 +47,6 @@ public:
tst_QPicture();
private slots:
- void getSetCheck();
void devType();
void paintingActive();
void boundingRect();
@@ -56,31 +57,6 @@ private slots:
void boundaryValues();
};
-// Testing get/set functions
-void tst_QPicture::getSetCheck()
-{
- QPictureIO obj1;
- // const QPicture & QPictureIO::picture()
- // void QPictureIO::setPicture(const QPicture &)
- // const char * QPictureIO::format()
- // void QPictureIO::setFormat(const char *)
- const char var2[] = "PNG";
- obj1.setFormat(var2);
- QCOMPARE(var2, obj1.format());
- obj1.setFormat((char *)0);
- // The format is stored internally in a QString, so return is always a valid char *
- QVERIFY(QString(obj1.format()).isEmpty());
-
- // const char * QPictureIO::parameters()
- // void QPictureIO::setParameters(const char *)
- const char var3[] = "Bogus data";
- obj1.setParameters(var3);
- QCOMPARE(var3, obj1.parameters());
- obj1.setParameters((char *)0);
- // The format is stored internally in a QString, so return is always a valid char *
- QVERIFY(QString(obj1.parameters()).isEmpty());
-}
-
tst_QPicture::tst_QPicture()
{
}
@@ -316,6 +292,7 @@ void tst_QPicture::boundaryValues()
painter.end();
}
-
QTEST_MAIN(tst_QPicture)
#include "tst_qpicture.moc"
+
+#endif // QT_NO_PICTURE
diff --git a/tests/auto/gui/kernel/kernel.pro b/tests/auto/gui/kernel/kernel.pro
index 42135dae24..106e9050b8 100644
--- a/tests/auto/gui/kernel/kernel.pro
+++ b/tests/auto/gui/kernel/kernel.pro
@@ -4,11 +4,14 @@ SUBDIRS=\
qclipboard \
qcursor \
qdrag \
+ qguiaction \
+ qguiactiongroup \
qevent \
qfileopenevent \
qguieventdispatcher \
qguieventloop \
qguimetatype \
+ qguishortcut \
qguitimer \
qguivariant \
qhighdpiscaling \
@@ -29,6 +32,12 @@ SUBDIRS=\
win32:!winrt:qtHaveModule(network): SUBDIRS += noqteventloop
+!qtConfig(shortcut): SUBDIRS -= \
+ qkeysequence \
+ qguishortcut \
+ qguimetatype \
+ qguivariant
+
!qtHaveModule(widgets): SUBDIRS -= \
qmouseevent_modal \
qtouchevent
@@ -36,6 +45,10 @@ win32:!winrt:qtHaveModule(network): SUBDIRS += noqteventloop
!qtHaveModule(network): SUBDIRS -= \
qguieventloop
+!qtConfig(action): SUBDIRS -= \
+ qguiaction \
+ qguiactiongroup
+
!qtConfig(highdpiscaling): SUBDIRS -= qhighdpiscaling
!qtConfig(opengl): SUBDIRS -= qopenglwindow
diff --git a/tests/auto/widgets/kernel/qaction/.gitignore b/tests/auto/gui/kernel/qguiaction/.gitignore
index bf81f5bf2c..bf81f5bf2c 100644
--- a/tests/auto/widgets/kernel/qaction/.gitignore
+++ b/tests/auto/gui/kernel/qguiaction/.gitignore
diff --git a/tests/auto/gui/kernel/qguiaction/qguiaction.pro b/tests/auto/gui/kernel/qguiaction/qguiaction.pro
new file mode 100644
index 0000000000..2a39636119
--- /dev/null
+++ b/tests/auto/gui/kernel/qguiaction/qguiaction.pro
@@ -0,0 +1,4 @@
+CONFIG += testcase
+TARGET = tst_qguiaction
+QT += gui-private core-private testlib
+SOURCES += tst_qguiaction.cpp
diff --git a/tests/auto/gui/kernel/qguiaction/tst_qguiaction.cpp b/tests/auto/gui/kernel/qguiaction/tst_qguiaction.cpp
new file mode 100644
index 0000000000..9d45d4ae14
--- /dev/null
+++ b/tests/auto/gui/kernel/qguiaction/tst_qguiaction.cpp
@@ -0,0 +1,210 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:GPL-EXCEPT$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3 as published by the Free Software
+** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtTest/QtTest>
+
+#include <qguiapplication.h>
+#include <qevent.h>
+#include <qguiaction.h>
+#include <qguiactiongroup.h>
+#include <qpa/qplatformtheme.h>
+
+#include <private/qguiapplication_p.h>
+
+class tst_QGuiAction : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_QGuiAction();
+
+private slots:
+ void cleanup();
+ void getSetCheck();
+ void setText_data();
+ void setText();
+ void setIconText_data() { setText_data(); }
+ void setIconText();
+#if QT_CONFIG(shortcut)
+ void setStandardKeys();
+ void task200823_tooltip();
+#endif
+ void task229128TriggeredSignalWithoutActiongroup();
+ void setData();
+
+private:
+ const int m_keyboardScheme;
+};
+
+tst_QGuiAction::tst_QGuiAction()
+ : m_keyboardScheme(QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::KeyboardScheme).toInt())
+{
+}
+
+void tst_QGuiAction::cleanup()
+{
+ QVERIFY(QGuiApplication::topLevelWindows().isEmpty());
+}
+
+// Testing get/set functions
+void tst_QGuiAction::getSetCheck()
+{
+ QGuiAction obj1(nullptr);
+ // QActionGroup * QAction::actionGroup()
+ // void QAction::setActionGroup(QActionGroup *)
+ auto var1 = new QGuiActionGroup(nullptr);
+ obj1.setActionGroup(var1);
+ QCOMPARE(var1, obj1.guiActionGroup());
+ obj1.setActionGroup(nullptr);
+ QCOMPARE(obj1.guiActionGroup(), nullptr);
+ delete var1;
+
+ QCOMPARE(obj1.priority(), QGuiAction::NormalPriority);
+ obj1.setPriority(QGuiAction::LowPriority);
+ QCOMPARE(obj1.priority(), QGuiAction::LowPriority);
+}
+
+void tst_QGuiAction::setText_data()
+{
+ QTest::addColumn<QString>("text");
+ QTest::addColumn<QString>("iconText");
+ QTest::addColumn<QString>("textFromIconText");
+
+ //next we fill it with data
+ QTest::newRow("Normal") << "Action" << "Action" << "Action";
+ QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
+ QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
+}
+
+void tst_QGuiAction::setText()
+{
+ QFETCH(QString, text);
+
+ QGuiAction action(nullptr);
+ action.setText(text);
+
+ QCOMPARE(action.text(), text);
+
+ QFETCH(QString, iconText);
+ QCOMPARE(action.iconText(), iconText);
+}
+
+void tst_QGuiAction::setIconText()
+{
+ QFETCH(QString, iconText);
+
+ QGuiAction action(nullptr);
+ action.setIconText(iconText);
+ QCOMPARE(action.iconText(), iconText);
+
+ QFETCH(QString, textFromIconText);
+ QCOMPARE(action.text(), textFromIconText);
+}
+
+#if QT_CONFIG(shortcut)
+
+//basic testing of standard keys
+void tst_QGuiAction::setStandardKeys()
+{
+ QGuiAction act(nullptr);
+ act.setShortcut(QKeySequence("CTRL+L"));
+ QList<QKeySequence> list;
+ act.setShortcuts(list);
+ act.setShortcuts(QKeySequence::Copy);
+ QCOMPARE(act.shortcut(), act.shortcuts().constFirst());
+
+ QList<QKeySequence> expected;
+ const QKeySequence ctrlC = QKeySequence(QStringLiteral("CTRL+C"));
+ const QKeySequence ctrlInsert = QKeySequence(QStringLiteral("CTRL+INSERT"));
+ switch (m_keyboardScheme) {
+ case QPlatformTheme::MacKeyboardScheme:
+ expected << ctrlC;
+ break;
+ case QPlatformTheme::WindowsKeyboardScheme:
+ expected << ctrlC << ctrlInsert;
+ break;
+ default: // X11
+ expected << ctrlC << ctrlInsert << QKeySequence(QStringLiteral("F16"));
+ break;
+ }
+
+ QCOMPARE(act.shortcuts(), expected);
+}
+
+void tst_QGuiAction::task200823_tooltip()
+{
+ const QScopedPointer<QGuiAction> action(new QGuiAction("foo", nullptr));
+ QString shortcut("ctrl+o");
+ action->setShortcut(shortcut);
+
+ // we want a non-standard tooltip that shows the shortcut
+ action->setToolTip(action->text() + QLatin1String(" (") + action->shortcut().toString() + QLatin1Char(')'));
+
+ QString ref = QLatin1String("foo (") + QKeySequence(shortcut).toString() + QLatin1Char(')');
+ QCOMPARE(action->toolTip(), ref);
+}
+
+#endif // QT_CONFIG(shortcut)
+
+void tst_QGuiAction::task229128TriggeredSignalWithoutActiongroup()
+{
+ // test without a group
+ const QScopedPointer<QGuiAction> actionWithoutGroup(new QGuiAction("Test", nullptr));
+ QSignalSpy spyWithoutGroup(actionWithoutGroup.data(), QOverload<bool>::of(&QGuiAction::triggered));
+ QCOMPARE(spyWithoutGroup.count(), 0);
+ actionWithoutGroup->trigger();
+ // signal should be emitted
+ QCOMPARE(spyWithoutGroup.count(), 1);
+
+ // it is now a checkable checked action
+ actionWithoutGroup->setCheckable(true);
+ actionWithoutGroup->setChecked(true);
+ spyWithoutGroup.clear();
+ QCOMPARE(spyWithoutGroup.count(), 0);
+ actionWithoutGroup->trigger();
+ // signal should be emitted
+ QCOMPARE(spyWithoutGroup.count(), 1);
+}
+
+void tst_QGuiAction::setData() // QTBUG-62006
+{
+ QGuiAction act(nullptr);
+ QSignalSpy spy(&act, &QGuiAction::changed);
+ QCOMPARE(act.data(), QVariant());
+ QCOMPARE(spy.count(), 0);
+ act.setData(QVariant());
+ QCOMPARE(spy.count(), 0);
+
+ act.setData(-1);
+ QCOMPARE(spy.count(), 1);
+ act.setData(-1);
+ QCOMPARE(spy.count(), 1);
+}
+
+QTEST_MAIN(tst_QGuiAction)
+#include "tst_qguiaction.moc"
diff --git a/tests/auto/gui/kernel/qguiactiongroup/.gitignore b/tests/auto/gui/kernel/qguiactiongroup/.gitignore
new file mode 100644
index 0000000000..daba003e96
--- /dev/null
+++ b/tests/auto/gui/kernel/qguiactiongroup/.gitignore
@@ -0,0 +1 @@
+tst_qactiongroup
diff --git a/tests/auto/gui/kernel/qguiactiongroup/qguiactiongroup.pro b/tests/auto/gui/kernel/qguiactiongroup/qguiactiongroup.pro
new file mode 100644
index 0000000000..7fd64e70f1
--- /dev/null
+++ b/tests/auto/gui/kernel/qguiactiongroup/qguiactiongroup.pro
@@ -0,0 +1,4 @@
+CONFIG += testcase
+TARGET = tst_qactiongroup
+QT += testlib
+SOURCES += tst_qguiactiongroup.cpp
diff --git a/tests/auto/gui/kernel/qguiactiongroup/tst_qguiactiongroup.cpp b/tests/auto/gui/kernel/qguiactiongroup/tst_qguiactiongroup.cpp
new file mode 100644
index 0000000000..1ac14280fb
--- /dev/null
+++ b/tests/auto/gui/kernel/qguiactiongroup/tst_qguiactiongroup.cpp
@@ -0,0 +1,235 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:GPL-EXCEPT$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3 as published by the Free Software
+** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtTest/QtTest>
+
+#include <qguiaction.h>
+#include <qguiactiongroup.h>
+
+class tst_QGuiActionGroup : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void cleanup() { QVERIFY(QGuiApplication::topLevelWindows().isEmpty()); }
+ void enabledPropagation();
+ void visiblePropagation();
+ void exclusive();
+ void exclusiveOptional();
+ void testActionInTwoQActionGroup();
+ void unCheckCurrentAction();
+};
+
+void tst_QGuiActionGroup::enabledPropagation()
+{
+ QGuiActionGroup testActionGroup(nullptr);
+
+ auto childAction = new QGuiAction( &testActionGroup );
+ auto anotherChildAction = new QGuiAction( &testActionGroup );
+ auto freeAction = new QGuiAction(nullptr);
+
+ QVERIFY( testActionGroup.isEnabled() );
+ QVERIFY( childAction->isEnabled() );
+
+ testActionGroup.setEnabled( false );
+ QVERIFY( !testActionGroup.isEnabled() );
+ QVERIFY( !childAction->isEnabled() );
+ QVERIFY( !anotherChildAction->isEnabled() );
+
+ childAction->setEnabled(true);
+ QVERIFY( !childAction->isEnabled());
+
+ anotherChildAction->setEnabled( false );
+
+ testActionGroup.setEnabled( true );
+ QVERIFY( testActionGroup.isEnabled() );
+ QVERIFY( childAction->isEnabled() );
+ QVERIFY( !anotherChildAction->isEnabled() );
+
+ testActionGroup.setEnabled( false );
+ auto lastChildAction = new QGuiAction(&testActionGroup);
+
+ QVERIFY(!lastChildAction->isEnabled());
+ testActionGroup.setEnabled( true );
+ QVERIFY(lastChildAction->isEnabled());
+
+ freeAction->setEnabled(false);
+ testActionGroup.addAction(freeAction);
+ QVERIFY(!freeAction->isEnabled());
+ delete freeAction;
+}
+
+void tst_QGuiActionGroup::visiblePropagation()
+{
+ QGuiActionGroup testActionGroup(nullptr);
+
+ auto childAction = new QGuiAction( &testActionGroup );
+ auto anotherChildAction = new QGuiAction( &testActionGroup );
+ auto freeAction = new QGuiAction(nullptr);
+
+ QVERIFY( testActionGroup.isVisible() );
+ QVERIFY( childAction->isVisible() );
+
+ testActionGroup.setVisible( false );
+ QVERIFY( !testActionGroup.isVisible() );
+ QVERIFY( !childAction->isVisible() );
+ QVERIFY( !anotherChildAction->isVisible() );
+
+ anotherChildAction->setVisible(false);
+
+ testActionGroup.setVisible( true );
+ QVERIFY( testActionGroup.isVisible() );
+ QVERIFY( childAction->isVisible() );
+
+ QVERIFY( !anotherChildAction->isVisible() );
+
+ testActionGroup.setVisible( false );
+ auto lastChildAction = new QGuiAction(&testActionGroup);
+
+ QVERIFY(!lastChildAction->isVisible());
+ testActionGroup.setVisible( true );
+ QVERIFY(lastChildAction->isVisible());
+
+ freeAction->setVisible(false);
+ testActionGroup.addAction(freeAction);
+ QVERIFY(!freeAction->isVisible());
+ delete freeAction;
+}
+
+void tst_QGuiActionGroup::exclusive()
+{
+ QGuiActionGroup group(nullptr);
+ group.setExclusive(false);
+ QVERIFY( !group.isExclusive() );
+
+ auto actOne = new QGuiAction(&group);
+ actOne->setCheckable( true );
+ auto actTwo = new QGuiAction(&group);
+ actTwo->setCheckable( true );
+ auto actThree = new QGuiAction(&group);
+ actThree->setCheckable( true );
+
+ group.setExclusive( true );
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actOne->setChecked( true );
+ QVERIFY( actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actTwo->setChecked( true );
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+}
+
+void tst_QGuiActionGroup::exclusiveOptional()
+{
+ QGuiActionGroup group(0);
+ group.setExclusive(true);
+ QVERIFY( group.isExclusive() );
+
+ auto actOne = new QGuiAction(&group);
+ actOne->setCheckable( true );
+ auto actTwo = new QGuiAction(&group);
+ actTwo->setCheckable( true );
+ auto actThree = new QGuiAction(&group);
+ actThree->setCheckable( true );
+
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actOne->trigger();
+ QVERIFY( actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actOne->trigger();
+ QVERIFY( actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ group.setExclusionPolicy(QGuiActionGroup::ExclusionPolicy::ExclusiveOptional);
+ QVERIFY( group.isExclusive() );
+
+ actOne->trigger();
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actTwo->trigger();
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+
+ actTwo->trigger();
+ QVERIFY( !actOne->isChecked() );
+ QVERIFY( !actTwo->isChecked() );
+ QVERIFY( !actThree->isChecked() );
+}
+
+void tst_QGuiActionGroup::testActionInTwoQActionGroup()
+{
+ QGuiAction action1("Action 1", this);
+
+ QGuiActionGroup group1(this);
+ QGuiActionGroup group2(this);
+
+ group1.addAction(&action1);
+ group2.addAction(&action1);
+
+ QCOMPARE(action1.guiActionGroup(), &group2);
+ QCOMPARE(group2.guiActions().constFirst(), &action1);
+ QCOMPARE(group1.guiActions().isEmpty(), true);
+}
+
+void tst_QGuiActionGroup::unCheckCurrentAction()
+{
+ QGuiActionGroup group(nullptr);
+ QGuiAction action1(&group) ,action2(&group);
+ action1.setCheckable(true);
+ action2.setCheckable(true);
+ QVERIFY(!action1.isChecked());
+ QVERIFY(!action2.isChecked());
+ action1.setChecked(true);
+ QVERIFY(action1.isChecked());
+ QVERIFY(!action2.isChecked());
+ auto current = group.checkedGuiAction();
+ QCOMPARE(current, &action1);
+ current->setChecked(false);
+ QVERIFY(!action1.isChecked());
+ QVERIFY(!action2.isChecked());
+ QVERIFY(!group.checkedGuiAction());
+}
+
+
+QTEST_MAIN(tst_QGuiActionGroup)
+#include "tst_qguiactiongroup.moc"
diff --git a/tests/auto/gui/kernel/qguimetatype/tst_qguimetatype.cpp b/tests/auto/gui/kernel/qguimetatype/tst_qguimetatype.cpp
index 3ce65a6785..2645bb111e 100644
--- a/tests/auto/gui/kernel/qguimetatype/tst_qguimetatype.cpp
+++ b/tests/auto/gui/kernel/qguimetatype/tst_qguimetatype.cpp
@@ -181,9 +181,13 @@ template<> struct TestValueFactory<QMetaType::QCursor> {
static QCursor *create() { return new QCursor(Qt::WaitCursor); }
};
#endif
+
+#if QT_CONFIG(shortcut)
template<> struct TestValueFactory<QMetaType::QKeySequence> {
static QKeySequence *create() { return new QKeySequence(QKeySequence::Close); }
};
+#endif
+
template<> struct TestValueFactory<QMetaType::QPen> {
static QPen *create() { return new QPen(Qt::DashDotDotLine); }
};
@@ -312,30 +316,10 @@ void tst_QGuiMetaType::sizeOf()
QCOMPARE(QMetaType::sizeOf(type), size);
}
-#ifndef Q_ALIGNOF
-template<uint N>
-struct RoundToNextHighestPowerOfTwo
-{
-private:
- enum { V1 = N-1 };
- enum { V2 = V1 | (V1 >> 1) };
- enum { V3 = V2 | (V2 >> 2) };
- enum { V4 = V3 | (V3 >> 4) };
- enum { V5 = V4 | (V4 >> 8) };
- enum { V6 = V5 | (V5 >> 16) };
-public:
- enum { Value = V6 + 1 };
-};
-#endif
-
template<class T>
struct TypeAlignment
{
-#ifdef Q_ALIGNOF
- enum { Value = Q_ALIGNOF(T) };
-#else
- enum { Value = RoundToNextHighestPowerOfTwo<sizeof(T)>::Value };
-#endif
+ enum { Value = alignof(T) };
};
void tst_QGuiMetaType::flags_data()
diff --git a/tests/auto/gui/kernel/qguishortcut/qguishortcut.pro b/tests/auto/gui/kernel/qguishortcut/qguishortcut.pro
new file mode 100644
index 0000000000..1417dee213
--- /dev/null
+++ b/tests/auto/gui/kernel/qguishortcut/qguishortcut.pro
@@ -0,0 +1,4 @@
+CONFIG += testcase
+TARGET = tst_qguishortcut
+QT += testlib
+SOURCES += tst_qguishortcut.cpp
diff --git a/tests/auto/gui/kernel/qguishortcut/tst_qguishortcut.cpp b/tests/auto/gui/kernel/qguishortcut/tst_qguishortcut.cpp
new file mode 100644
index 0000000000..bc3fb9862d
--- /dev/null
+++ b/tests/auto/gui/kernel/qguishortcut/tst_qguishortcut.cpp
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:GPL-EXCEPT$
+** 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 https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3 as published by the Free Software
+** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtTest/QtTest>
+#include <QtGui/qguiapplication.h>
+#include <QtGui/qguishortcut.h>
+#include <QtGui/qpainter.h>
+#include <QtGui/qrasterwindow.h>
+#include <QtGui/qscreen.h>
+#include <QtGui/qwindow.h>
+
+class tst_QGuiShortcut : public QObject
+{
+ Q_OBJECT
+public:
+
+private slots:
+ void trigger();
+};
+
+class ColoredWindow : public QRasterWindow {
+public:
+ ColoredWindow(QColor c) : m_color(c) {}
+
+protected:
+ void paintEvent(QPaintEvent *event) override;
+
+private:
+ const QColor m_color;
+};
+
+void ColoredWindow::paintEvent(QPaintEvent *)
+{
+ QPainter p(this);
+ p.fillRect(QRect(QPoint(), size()), m_color);
+}
+
+static void sendKey(QWindow *target, Qt::Key k, char c, Qt::KeyboardModifiers modifiers)
+{
+ QTest::sendKeyEvent(QTest::Press, target, k, c, modifiers);
+ QTest::sendKeyEvent(QTest::Release, target, k, c, modifiers);
+}
+
+void tst_QGuiShortcut::trigger()
+{
+ ColoredWindow w(Qt::yellow);
+ w.setTitle(QTest::currentTestFunction());
+ w.resize(QGuiApplication::primaryScreen()->size() / 4);
+ new QGuiShortcut(Qt::CTRL + Qt::Key_Q, &w, SLOT(close()));
+ w.show();
+ QVERIFY(QTest::qWaitForWindowExposed(&w));
+ sendKey(&w, Qt::Key_Q, 'q', Qt::ControlModifier);
+ QTRY_VERIFY(!w.isVisible());
+}
+
+QTEST_MAIN(tst_QGuiShortcut)
+#include "tst_qguishortcut.moc"
diff --git a/tests/auto/gui/kernel/qkeyevent/tst_qkeyevent.cpp b/tests/auto/gui/kernel/qkeyevent/tst_qkeyevent.cpp
index 87a47bd93b..6a928cac7a 100644
--- a/tests/auto/gui/kernel/qkeyevent/tst_qkeyevent.cpp
+++ b/tests/auto/gui/kernel/qkeyevent/tst_qkeyevent.cpp
@@ -64,8 +64,10 @@ public:
private slots:
void basicEventDelivery();
+#if QT_CONFIG(shortcut)
void modifiers_data();
void modifiers();
+#endif
};
tst_QKeyEvent::tst_QKeyEvent()
@@ -128,6 +130,8 @@ static QByteArray modifiersTestRowName(const QString &keySequence)
return result;
}
+#if QT_CONFIG(shortcut)
+
void tst_QKeyEvent::modifiers_data()
{
struct Modifier
@@ -198,5 +202,7 @@ void tst_QKeyEvent::modifiers()
}
}
+#endif // QT_CONFIG(shortcut)
+
QTEST_MAIN(tst_QKeyEvent)
#include "tst_qkeyevent.moc"
diff --git a/tests/auto/gui/kernel/qpalette/tst_qpalette.cpp b/tests/auto/gui/kernel/qpalette/tst_qpalette.cpp
index 6ce6422f48..a4764a47c0 100644
--- a/tests/auto/gui/kernel/qpalette/tst_qpalette.cpp
+++ b/tests/auto/gui/kernel/qpalette/tst_qpalette.cpp
@@ -41,6 +41,12 @@ private Q_SLOTS:
void copySemantics();
void moveSemantics();
void setBrush();
+
+ void isBrushSet();
+ void setAllPossibleBrushes();
+ void noBrushesSetForDefaultPalette();
+ void cannotCheckIfInvalidBrushSet();
+ void checkIfBrushForCurrentGroupSet();
};
void tst_QPalette::roleValues_data()
@@ -194,5 +200,62 @@ void tst_QPalette::setBrush()
QVERIFY(pp.isCopyOf(p));
}
+void tst_QPalette::isBrushSet()
+{
+ QPalette p;
+
+ // Set only one color group
+ p.setBrush(QPalette::Active, QPalette::Mid, QBrush(Qt::red));
+ QVERIFY(p.isBrushSet(QPalette::Active, QPalette::Mid));
+ QVERIFY(!p.isBrushSet(QPalette::Inactive, QPalette::Mid));
+ QVERIFY(!p.isBrushSet(QPalette::Disabled, QPalette::Mid));
+
+ // Set all color groups
+ p.setBrush(QPalette::LinkVisited, QBrush(Qt::green));
+ QVERIFY(p.isBrushSet(QPalette::Active, QPalette::LinkVisited));
+ QVERIFY(p.isBrushSet(QPalette::Inactive, QPalette::LinkVisited));
+ QVERIFY(p.isBrushSet(QPalette::Disabled, QPalette::LinkVisited));
+}
+
+void tst_QPalette::setAllPossibleBrushes()
+{
+ QPalette p;
+
+ QCOMPARE(p.resolve(), QPalette::ResolveMask(0));
+
+ for (int r = 0; r < QPalette::NColorRoles; ++r) {
+ p.setBrush(QPalette::All, QPalette::ColorRole(r), Qt::red);
+ }
+
+ for (int r = 0; r < QPalette::NColorRoles; ++r) {
+ for (int g = 0; g < QPalette::NColorGroups; ++g) {
+ QVERIFY(p.isBrushSet(QPalette::ColorGroup(g), QPalette::ColorRole(r)));
+ }
+ }
+}
+
+void tst_QPalette::noBrushesSetForDefaultPalette()
+{
+ QCOMPARE(QPalette().resolve(), QPalette::ResolveMask(0));
+}
+
+void tst_QPalette::cannotCheckIfInvalidBrushSet()
+{
+ QPalette p(Qt::red);
+
+ QVERIFY(!p.isBrushSet(QPalette::All, QPalette::LinkVisited));
+ QVERIFY(!p.isBrushSet(QPalette::Active, QPalette::NColorRoles));
+}
+
+void tst_QPalette::checkIfBrushForCurrentGroupSet()
+{
+ QPalette p;
+
+ p.setCurrentColorGroup(QPalette::Disabled);
+ p.setBrush(QPalette::Current, QPalette::Link, QBrush(Qt::yellow));
+
+ QVERIFY(p.isBrushSet(QPalette::Current, QPalette::Link));
+}
+
QTEST_MAIN(tst_QPalette)
#include "tst_qpalette.moc"
diff --git a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
index 07c820dc86..f8502c1e2f 100644
--- a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
+++ b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
@@ -1032,6 +1032,15 @@ void tst_QColor::setRgbF()
QCOMPARE(qfloat16(b2), qfloat16(b));
}
}
+ QVERIFY(color.isValid());
+ QColor invalidRgb = color;
+ QColor invalidRgbF = color;
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setRgb: RGB parameters out of range");
+ invalidRgb.setRgb(-1, -1, -1);
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setRgb: RGB parameters out of range");
+ invalidRgbF.setRgb(-1, -1, -1, -1);
+ QVERIFY(!invalidRgb.isValid());
+ QVERIFY(!invalidRgbF.isValid());
}
void tst_QColor::setRgba()
@@ -1146,6 +1155,16 @@ void tst_QColor::setHsv()
QCOMPARE(v2, v);
}
}
+ QVERIFY(color.isValid());
+ QVERIFY(color.isValid());
+ QColor invalidHsv = color;
+ QColor invalidHsvF = color;
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setHsv: HSV parameters out of range");
+ invalidHsv.setHsv(-1, -1, -1);
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setHsvF: HSV parameters out of range");
+ invalidHsvF.setHsvF(-1, -1, -1);
+ QVERIFY(!invalidHsv.isValid());
+ QVERIFY(!invalidHsvF.isValid());
}
void tst_QColor::setCmyk()
@@ -1271,6 +1290,15 @@ void tst_QColor::setCmyk()
QCOMPARE(k2, k);
}
}
+ QVERIFY(color.isValid());
+ QColor invalidCmyk = color;
+ QColor invalidCmykF = color;
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setCmyk: CMYK parameters out of range");
+ invalidCmyk.setCmyk(-1, -1, -1, -1, -1);
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setCmykF: CMYK parameters out of range");
+ invalidCmykF.setCmykF(-1, -1, -1, -1, -1);
+ QVERIFY(!invalidCmyk.isValid());
+ QVERIFY(!invalidCmykF.isValid());
}
void tst_QColor::setHsl()
@@ -1372,6 +1400,15 @@ void tst_QColor::setHsl()
QCOMPARE(l2, l);
}
}
+ QVERIFY(color.isValid());
+ QColor invalidHsl = color;
+ QColor invalidHslF = color;
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setHsl: HSL parameters out of range");
+ invalidHsl.setHsl(-1, -1, -1, -1);
+ QTest::ignoreMessage(QtWarningMsg, "QColor::setHslF: HSL parameters out of range");
+ invalidHslF.setHslF(-1, -1, -1, -1);
+ QVERIFY(!invalidHsl.isValid());
+ QVERIFY(!invalidHslF.isValid());
}
void tst_QColor::toRgb_data()
diff --git a/tests/auto/network/access/access.pro b/tests/auto/network/access/access.pro
index b140b5e9f2..d2b4d97b21 100644
--- a/tests/auto/network/access/access.pro
+++ b/tests/auto/network/access/access.pro
@@ -7,7 +7,6 @@ SUBDIRS=\
qnetworkrequest \
qhttpnetworkconnection \
qnetworkreply \
- spdy \
qnetworkcachemetadata \
qftp \
qhttpnetworkreply \
diff --git a/tests/auto/network/access/http2/tst_http2.cpp b/tests/auto/network/access/http2/tst_http2.cpp
index 6f94692cb1..904cfd52b0 100644
--- a/tests/auto/network/access/http2/tst_http2.cpp
+++ b/tests/auto/network/access/http2/tst_http2.cpp
@@ -939,13 +939,6 @@ void tst_Http2::replyFinished()
QVERIFY(http2Used.isValid());
QVERIFY(http2Used.toBool());
- const QVariant spdyUsed(reply->attribute(QNetworkRequest::SpdyWasUsedAttribute));
- if (!spdyUsed.isValid() || spdyUsed.toBool())
- stopEventLoop();
-
- QVERIFY(spdyUsed.isValid());
- QVERIFY(!spdyUsed.toBool());
-
const QVariant code(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute));
if (!code.isValid() || !code.canConvert<int>() || code.value<int>() != 200)
stopEventLoop();
diff --git a/tests/auto/network/access/qnetworkreply/BLACKLIST b/tests/auto/network/access/qnetworkreply/BLACKLIST
index 2a0651f96f..18450f1853 100644
--- a/tests/auto/network/access/qnetworkreply/BLACKLIST
+++ b/tests/auto/network/access/qnetworkreply/BLACKLIST
@@ -15,8 +15,6 @@ linux
# QTBUG-71953
[getFromHttp]
* !android !winrt
-[getFromHttp:success-external]
-*
[getFromHttpIntoBuffer]
osx
[getFromHttpIntoBuffer2]
diff --git a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
index 36f19c1582..b0b9560d5a 100644
--- a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
+++ b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
@@ -1914,10 +1914,6 @@ void tst_QNetworkReply::getFromHttp_data()
<< testDataDir + "/rfc3252.txt"
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt";
- QTest::newRow("success-external")
- << testDataDir + "/rfc3252.txt"
- << "http://www.ietf.org/rfc/rfc3252.txt";
-
QTest::newRow("bigfile-internal")
<< testDataDir + "/bigfile"
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile";
diff --git a/tests/auto/network/access/spdy/BLACKLIST b/tests/auto/network/access/spdy/BLACKLIST
deleted file mode 100644
index 5cf79327be..0000000000
--- a/tests/auto/network/access/spdy/BLACKLIST
+++ /dev/null
@@ -1,7 +0,0 @@
-[download]
-opensuse-leap
-[upload]
-opensuse-leap
-ubuntu-18.04
-b2qt
-
diff --git a/tests/auto/network/access/spdy/spdy.pro b/tests/auto/network/access/spdy/spdy.pro
deleted file mode 100644
index cdbe60a19b..0000000000
--- a/tests/auto/network/access/spdy/spdy.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-CONFIG += testcase
-TARGET = tst_spdy
-SOURCES += tst_spdy.cpp
-
-QT = core core-private network network-private testlib
-
-win32:CONFIG += insignificant_test # QTBUG-47128
diff --git a/tests/auto/network/access/spdy/tst_spdy.cpp b/tests/auto/network/access/spdy/tst_spdy.cpp
deleted file mode 100644
index f4a5976558..0000000000
--- a/tests/auto/network/access/spdy/tst_spdy.cpp
+++ /dev/null
@@ -1,693 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
-#include <QtNetwork/QNetworkAccessManager>
-#include <QtNetwork/QNetworkReply>
-#include <QtNetwork/QHttpPart>
-#include <QtNetwork/QHttpMultiPart>
-#include <QtNetwork/QNetworkProxy>
-#include <QtNetwork/QAuthenticator>
-#if defined(QT_BUILD_INTERNAL) && !defined(QT_NO_OPENSSL)
-#include <QtNetwork/private/qsslsocket_openssl_p.h>
-#endif // QT_BUILD_INTERNAL && !QT_NO_OPENSSL
-
-#include "../../../network-settings.h"
-
-Q_DECLARE_METATYPE(QAuthenticator*)
-
-class tst_Spdy: public QObject
-{
- Q_OBJECT
-
-public:
- tst_Spdy();
- ~tst_Spdy();
-
-private Q_SLOTS:
- void initTestCase();
- void settingsAndNegotiation_data();
- void settingsAndNegotiation();
-#ifndef QT_NO_NETWORKPROXY
- void download_data();
- void download();
-#endif // !QT_NO_NETWORKPROXY
- void headerFields();
-#ifndef QT_NO_NETWORKPROXY
- void upload_data();
- void upload();
- void errors_data();
- void errors();
-#endif // !QT_NO_NETWORKPROXY
- void multipleRequests_data();
- void multipleRequests();
-
-private:
- QNetworkAccessManager m_manager;
- int m_multipleRequestsCount;
- int m_multipleRepliesFinishedCount;
- const QString m_rfc3252FilePath;
-
-protected Q_SLOTS:
- void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *authenticator);
- void multipleRequestsFinishedSlot();
-};
-
-tst_Spdy::tst_Spdy()
- : m_rfc3252FilePath(QFINDTESTDATA("../qnetworkreply/rfc3252.txt"))
-{
-#if defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) && OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
- qRegisterMetaType<QNetworkReply *>(); // for QSignalSpy
- qRegisterMetaType<QAuthenticator *>();
-
- connect(&m_manager, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)),
- this, SLOT(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
-#else
- QSKIP("Qt built withouth OpenSSL, or the OpenSSL version is too old");
-#endif // defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) ...
-}
-
-tst_Spdy::~tst_Spdy()
-{
-}
-
-void tst_Spdy::initTestCase()
-{
- QVERIFY(!m_rfc3252FilePath.isEmpty());
- QVERIFY(QtNetworkSettings::verifyTestNetworkSettings());
-}
-
-void tst_Spdy::settingsAndNegotiation_data()
-{
- QTest::addColumn<QUrl>("url");
- QTest::addColumn<bool>("setAttribute");
- QTest::addColumn<bool>("enabled");
- QTest::addColumn<QByteArray>("expectedProtocol");
- QTest::addColumn<QByteArray>("expectedContent");
-
- QTest::newRow("default-settings") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/cgi-bin/echo.cgi?1")
- << false << false << QByteArray()
- << QByteArray("1");
-
- QTest::newRow("http-url") << QUrl("http://" + QtNetworkSettings::serverName()
- + "/qtest/cgi-bin/echo.cgi?1")
- << true << true << QByteArray()
- << QByteArray("1");
-
- QTest::newRow("spdy-disabled") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/cgi-bin/echo.cgi?1")
- << true << false << QByteArray()
- << QByteArray("1");
-
-#ifndef QT_NO_OPENSSL
- QTest::newRow("spdy-enabled") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/cgi-bin/echo.cgi?1")
- << true << true << QByteArray(QSslConfiguration::NextProtocolSpdy3_0)
- << QByteArray("1");
-#endif // QT_NO_OPENSSL
-}
-
-void tst_Spdy::settingsAndNegotiation()
-{
- QFETCH(QUrl, url);
- QFETCH(bool, setAttribute);
- QFETCH(bool, enabled);
-
- QNetworkRequest request(url);
-
- if (setAttribute) {
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, QVariant(enabled));
- }
-
- QNetworkReply *reply = m_manager.get(request);
- reply->ignoreSslErrors();
- QSignalSpy metaDataChangedSpy(reply, SIGNAL(metaDataChanged()));
- QSignalSpy readyReadSpy(reply, SIGNAL(readyRead()));
- QSignalSpy finishedSpy(reply, SIGNAL(finished()));
-
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QFETCH(QByteArray, expectedProtocol);
-
-#ifndef QT_NO_OPENSSL
- bool expectedSpdyUsed = (expectedProtocol == QSslConfiguration::NextProtocolSpdy3_0);
- QCOMPARE(reply->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), expectedSpdyUsed);
-#endif // QT_NO_OPENSSL
-
- QCOMPARE(metaDataChangedSpy.count(), 1);
- QCOMPARE(finishedSpy.count(), 1);
-
- int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- QCOMPARE(statusCode, 200);
-
- QByteArray content = reply->readAll();
-
- QFETCH(QByteArray, expectedContent);
- QCOMPARE(expectedContent, content);
-
-#ifndef QT_NO_OPENSSL
- QSslConfiguration::NextProtocolNegotiationStatus expectedStatus =
- (expectedProtocol.isEmpty())
- ? QSslConfiguration::NextProtocolNegotiationNone
- : QSslConfiguration::NextProtocolNegotiationNegotiated;
- QCOMPARE(reply->sslConfiguration().nextProtocolNegotiationStatus(),
- expectedStatus);
-
- QCOMPARE(reply->sslConfiguration().nextNegotiatedProtocol(), expectedProtocol);
-#endif // QT_NO_OPENSSL
-}
-
-void tst_Spdy::proxyAuthenticationRequired(const QNetworkProxy &/*proxy*/,
- QAuthenticator *authenticator)
-{
- authenticator->setUser("qsockstest");
- authenticator->setPassword("password");
-}
-
-#ifndef QT_NO_NETWORKPROXY
-void tst_Spdy::download_data()
-{
- QTest::addColumn<QUrl>("url");
- QTest::addColumn<QString>("fileName");
- QTest::addColumn<QNetworkProxy>("proxy");
-
- QTest::newRow("mediumfile") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/rfc3252.txt")
- << m_rfc3252FilePath
- << QNetworkProxy();
-
- QHostInfo hostInfo = QHostInfo::fromName(QtNetworkSettings::serverName());
- QString proxyserver = hostInfo.addresses().first().toString();
-
- QTest::newRow("mediumfile-http-proxy") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/rfc3252.txt")
- << m_rfc3252FilePath
- << QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3128);
-
- QTest::newRow("mediumfile-http-proxy-auth") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/rfc3252.txt")
- << m_rfc3252FilePath
- << QNetworkProxy(QNetworkProxy::HttpProxy,
- proxyserver, 3129);
-
- QTest::newRow("mediumfile-socks-proxy") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/rfc3252.txt")
- << m_rfc3252FilePath
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, proxyserver, 1080);
-
- QTest::newRow("mediumfile-socks-proxy-auth") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/rfc3252.txt")
- << m_rfc3252FilePath
- << QNetworkProxy(QNetworkProxy::Socks5Proxy,
- proxyserver, 1081);
-
- QTest::newRow("bigfile") << QUrl("https://" + QtNetworkSettings::serverName()
- + "/qtest/bigfile")
- << QFINDTESTDATA("../qnetworkreply/bigfile")
- << QNetworkProxy();
-}
-
-void tst_Spdy::download()
-{
- QFETCH(QUrl, url);
- QFETCH(QString, fileName);
- QFETCH(QNetworkProxy, proxy);
-
- QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
-
- if (proxy.type() != QNetworkProxy::DefaultProxy) {
- m_manager.setProxy(proxy);
- }
- QNetworkReply *reply = m_manager.get(request);
- reply->ignoreSslErrors();
- QSignalSpy metaDataChangedSpy(reply, SIGNAL(metaDataChanged()));
- QSignalSpy downloadProgressSpy(reply, SIGNAL(downloadProgress(qint64, qint64)));
- QSignalSpy readyReadSpy(reply, SIGNAL(readyRead()));
- QSignalSpy finishedSpy(reply, SIGNAL(finished()));
-
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
- QSignalSpy proxyAuthRequiredSpy(&m_manager, SIGNAL(
- proxyAuthenticationRequired(const QNetworkProxy &,
- QAuthenticator *)));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(finishedManagerSpy.count(), 1);
- QCOMPARE(metaDataChangedSpy.count(), 1);
- QCOMPARE(finishedSpy.count(), 1);
- QVERIFY(downloadProgressSpy.count() > 0);
- QVERIFY(readyReadSpy.count() > 0);
-
- QVERIFY(proxyAuthRequiredSpy.count() <= 1);
-
- QCOMPARE(reply->error(), QNetworkReply::NoError);
- QCOMPARE(reply->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), true);
- QCOMPARE(reply->attribute(QNetworkRequest::ConnectionEncryptedAttribute).toBool(), true);
- QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
-
- QFile file(fileName);
- QVERIFY(file.open(QIODevice::ReadOnly));
-
- qint64 contentLength = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong();
- qint64 expectedContentLength = file.bytesAvailable();
- QCOMPARE(contentLength, expectedContentLength);
-
- QByteArray expectedContent = file.readAll();
- QByteArray content = reply->readAll();
- QCOMPARE(content, expectedContent);
-
- reply->deleteLater();
- m_manager.setProxy(QNetworkProxy()); // reset
-}
-#endif // !QT_NO_NETWORKPROXY
-
-void tst_Spdy::headerFields()
-{
- QUrl url(QUrl("https://" + QtNetworkSettings::serverName()));
- QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
-
- QNetworkReply *reply = m_manager.get(request);
- reply->ignoreSslErrors();
-
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(reply->rawHeader("Content-Type"), QByteArray("text/html"));
- QVERIFY(reply->rawHeader("Content-Length").toInt() > 0);
- QVERIFY(reply->rawHeader("server").contains("Apache"));
-
- QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toByteArray(), QByteArray("text/html"));
- QVERIFY(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong() > 0);
- QVERIFY(reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().isValid());
- QVERIFY(reply->header(QNetworkRequest::ServerHeader).toByteArray().contains("Apache"));
-}
-
-static inline QByteArray md5sum(const QByteArray &data)
-{
- return QCryptographicHash::hash(data, QCryptographicHash::Md5).toHex().append('\n');
-}
-
-#ifndef QT_NO_NETWORKPROXY
-void tst_Spdy::upload_data()
-{
- QTest::addColumn<QUrl>("url");
- QTest::addColumn<QByteArray>("data");
- QTest::addColumn<QByteArray>("uploadMethod");
- QTest::addColumn<QObject *>("uploadObject");
- QTest::addColumn<QByteArray>("md5sum");
- QTest::addColumn<QNetworkProxy>("proxy");
-
-
- // 1. test uploading of byte arrays
-
- QUrl md5Url("https://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi");
-
- QByteArray data;
- data = "";
- QObject *dummyObject = 0;
- QTest::newRow("empty") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = "This is a normal message.";
- QTest::newRow("generic") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = "This is a message to show that Qt rocks!\r\n\n";
- QTest::newRow("small") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = QByteArray("abcd\0\1\2\abcd",12);
- QTest::newRow("with-nul") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = QByteArray(4097, '\4');
- QTest::newRow("4k+1") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data)<< QNetworkProxy();
-
- QHostInfo hostInfo = QHostInfo::fromName(QtNetworkSettings::serverName());
- QString proxyserver = hostInfo.addresses().first().toString();
-
- QTest::newRow("4k+1-with-http-proxy") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data)
- << QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3128);
-
- QTest::newRow("4k+1-with-http-proxy-auth") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data)
- << QNetworkProxy(QNetworkProxy::HttpProxy,
- proxyserver, 3129);
-
- QTest::newRow("4k+1-with-socks-proxy") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, proxyserver, 1080);
-
- QTest::newRow("4k+1-with-socks-proxy-auth") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy,
- proxyserver, 1081);
-
- data = QByteArray(128*1024+1, '\177');
- QTest::newRow("128k+1") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = QByteArray(128*1024+1, '\177');
- QTest::newRow("128k+1-put") << md5Url << data << QByteArray("PUT") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
- data = QByteArray(2*1024*1024+1, '\177');
- QTest::newRow("2MB+1") << md5Url << data << QByteArray("POST") << dummyObject
- << md5sum(data) << QNetworkProxy();
-
-
- // 2. test uploading of files
-
- QFile *file = new QFile(m_rfc3252FilePath);
- file->open(QIODevice::ReadOnly);
- QTest::newRow("file-26K") << md5Url << QByteArray() << QByteArray("POST")
- << static_cast<QObject *>(file)
- << QByteArray("b3e32ac459b99d3f59318f3ac31e4bee\n") << QNetworkProxy();
-
- QFile *file2 = new QFile(QFINDTESTDATA("../qnetworkreply/image1.jpg"));
- file2->open(QIODevice::ReadOnly);
- QTest::newRow("file-1MB") << md5Url << QByteArray() << QByteArray("POST")
- << static_cast<QObject *>(file2)
- << QByteArray("87ef3bb319b004ba9e5e9c9fa713776e\n") << QNetworkProxy();
-
-
- // 3. test uploading of multipart
-
- QUrl multiPartUrl("https://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/multipart.cgi");
-
- QHttpPart imagePart31;
- imagePart31.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
- imagePart31.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage1\""));
- imagePart31.setRawHeader("Content-Location", "http://my.test.location.tld");
- imagePart31.setRawHeader("Content-ID", "my@id.tld");
- QFile *file31 = new QFile(QFINDTESTDATA("../qnetworkreply/image1.jpg"));
- file31->open(QIODevice::ReadOnly);
- imagePart31.setBodyDevice(file31);
- QHttpMultiPart *imageMultiPart3 = new QHttpMultiPart(QHttpMultiPart::FormDataType);
- imageMultiPart3->append(imagePart31);
- file31->setParent(imageMultiPart3);
- QHttpPart imagePart32;
- imagePart32.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
- imagePart32.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage2\""));
- QFile *file32 = new QFile(QFINDTESTDATA("../qnetworkreply/image2.jpg"));
- file32->open(QIODevice::ReadOnly);
- imagePart32.setBodyDevice(file31); // check that resetting works
- imagePart32.setBodyDevice(file32);
- imageMultiPart3->append(imagePart32);
- file32->setParent(imageMultiPart3);
- QHttpPart imagePart33;
- imagePart33.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
- imagePart33.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage3\""));
- QFile *file33 = new QFile(QFINDTESTDATA("../qnetworkreply/image3.jpg"));
- file33->open(QIODevice::ReadOnly);
- imagePart33.setBodyDevice(file33);
- imageMultiPart3->append(imagePart33);
- file33->setParent(imageMultiPart3);
- QByteArray expectedData = "content type: multipart/form-data; boundary=\""
- + imageMultiPart3->boundary();
- expectedData.append("\"\nkey: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n"
- "key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n"
- "key: testImage3, value: ab0eb6fd4fcf8b4436254870b4513033\n");
-
- QTest::newRow("multipart-3images") << multiPartUrl << QByteArray() << QByteArray("POST")
- << static_cast<QObject *>(imageMultiPart3) << expectedData
- << QNetworkProxy();
-}
-
-void tst_Spdy::upload()
-{
- QFETCH(QUrl, url);
- QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
-
- QFETCH(QByteArray, data);
- QFETCH(QByteArray, uploadMethod);
- QFETCH(QObject *, uploadObject);
- QFETCH(QNetworkProxy, proxy);
-
- if (proxy.type() != QNetworkProxy::DefaultProxy) {
- m_manager.setProxy(proxy);
- }
-
- QNetworkReply *reply;
- QHttpMultiPart *multiPart = 0;
-
- if (uploadObject) {
- // upload via device
- if (QIODevice *device = qobject_cast<QIODevice *>(uploadObject)) {
- reply = m_manager.post(request, device);
- } else if ((multiPart = qobject_cast<QHttpMultiPart *>(uploadObject))) {
- reply = m_manager.post(request, multiPart);
- } else {
- QFAIL("got unknown upload device");
- }
- } else {
- // upload via byte array
- if (uploadMethod == "PUT") {
- reply = m_manager.put(request, data);
- } else {
- reply = m_manager.post(request, data);
- }
- }
-
- reply->ignoreSslErrors();
- QSignalSpy metaDataChangedSpy(reply, SIGNAL(metaDataChanged()));
- QSignalSpy uploadProgressSpy(reply, SIGNAL(uploadProgress(qint64, qint64)));
- QSignalSpy readyReadSpy(reply, SIGNAL(readyRead()));
- QSignalSpy finishedSpy(reply, SIGNAL(finished()));
-
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
-
- QTestEventLoop::instance().enterLoop(20);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(finishedManagerSpy.count(), 1);
- QCOMPARE(metaDataChangedSpy.count(), 1);
- QCOMPARE(finishedSpy.count(), 1);
- QVERIFY(uploadProgressSpy.count() > 0);
- QVERIFY(readyReadSpy.count() > 0);
-
- QCOMPARE(reply->error(), QNetworkReply::NoError);
- QCOMPARE(reply->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), true);
- QCOMPARE(reply->attribute(QNetworkRequest::ConnectionEncryptedAttribute).toBool(), true);
- QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
-
- qint64 contentLength = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong();
- if (!multiPart) // script to test multiparts does not return a content length
- QCOMPARE(contentLength, 33); // 33 bytes for md5 sums (including new line)
-
- QFETCH(QByteArray, md5sum);
- QByteArray content = reply->readAll();
- QCOMPARE(content, md5sum);
-
- reply->deleteLater();
- if (uploadObject)
- uploadObject->deleteLater();
-
- m_manager.setProxy(QNetworkProxy()); // reset
-}
-
-void tst_Spdy::errors_data()
-{
- QTest::addColumn<QUrl>("url");
- QTest::addColumn<QNetworkProxy>("proxy");
- QTest::addColumn<bool>("ignoreSslErrors");
- QTest::addColumn<int>("expectedReplyError");
-
- QTest::newRow("http-404") << QUrl("https://" + QtNetworkSettings::serverName() + "/non-existent-url")
- << QNetworkProxy() << true << int(QNetworkReply::ContentNotFoundError);
-
- QTest::newRow("ssl-errors") << QUrl("https://" + QtNetworkSettings::serverName())
- << QNetworkProxy() << false << int(QNetworkReply::SslHandshakeFailedError);
-
- QTest::newRow("host-not-found") << QUrl("https://this-host-does-not.exist")
- << QNetworkProxy()
- << true << int(QNetworkReply::HostNotFoundError);
-
- QTest::newRow("proxy-not-found") << QUrl("https://" + QtNetworkSettings::serverName())
- << QNetworkProxy(QNetworkProxy::HttpProxy,
- "https://this-host-does-not.exist", 3128)
- << true << int(QNetworkReply::HostNotFoundError);
-
- QHostInfo hostInfo = QHostInfo::fromName(QtNetworkSettings::serverName());
- QString proxyserver = hostInfo.addresses().first().toString();
-
- QTest::newRow("proxy-unavailable") << QUrl("https://" + QtNetworkSettings::serverName())
- << QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 10)
- << true << int(QNetworkReply::UnknownNetworkError);
-
- QTest::newRow("no-proxy-credentials") << QUrl("https://" + QtNetworkSettings::serverName())
- << QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3129)
- << true << int(QNetworkReply::ProxyAuthenticationRequiredError);
-}
-
-void tst_Spdy::errors()
-{
- QFETCH(QUrl, url);
- QFETCH(QNetworkProxy, proxy);
- QFETCH(bool, ignoreSslErrors);
- QFETCH(int, expectedReplyError);
-
- QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
-
- disconnect(&m_manager, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)),
- 0, 0);
- if (proxy.type() != QNetworkProxy::DefaultProxy) {
- m_manager.setProxy(proxy);
- }
- QNetworkReply *reply = m_manager.get(request);
- if (ignoreSslErrors)
- reply->ignoreSslErrors();
- QSignalSpy finishedSpy(reply, SIGNAL(finished()));
- QSignalSpy errorSpy(reply, SIGNAL(error(QNetworkReply::NetworkError)));
-
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(finishedSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 1);
-
- QCOMPARE(reply->error(), static_cast<QNetworkReply::NetworkError>(expectedReplyError));
-
- m_manager.setProxy(QNetworkProxy()); // reset
- m_manager.clearAccessCache(); // e.g. to get an SSL error we need a new connection
- connect(&m_manager, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)),
- this, SLOT(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)),
- Qt::UniqueConnection); // reset
-}
-#endif // !QT_NO_NETWORKPROXY
-
-void tst_Spdy::multipleRequests_data()
-{
- QTest::addColumn<QList<QUrl> >("urls");
-
- QString baseUrl = "https://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/echo.cgi?";
- QList<QUrl> urls;
- for (int a = 1; a <= 50; ++a)
- urls.append(QUrl(baseUrl + QLatin1String(QByteArray::number(a))));
-
- QTest::newRow("one-request") << urls.mid(0, 1);
- QTest::newRow("two-requests") << urls.mid(0, 2);
- QTest::newRow("ten-requests") << urls.mid(0, 10);
- QTest::newRow("twenty-requests") << urls.mid(0, 20);
- QTest::newRow("fifty-requests") << urls;
-}
-
-void tst_Spdy::multipleRequestsFinishedSlot()
-{
- m_multipleRepliesFinishedCount++;
- if (m_multipleRepliesFinishedCount == m_multipleRequestsCount)
- QTestEventLoop::instance().exitLoop();
-}
-
-void tst_Spdy::multipleRequests()
-{
- QFETCH(QList<QUrl>, urls);
- m_multipleRequestsCount = urls.count();
- m_multipleRepliesFinishedCount = 0;
-
- QList<QNetworkReply *> replies;
- QList<QSignalSpy *> metaDataChangedSpies;
- QList<QSignalSpy *> readyReadSpies;
- QList<QSignalSpy *> finishedSpies;
-
- foreach (const QUrl &url, urls) {
- QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
- QNetworkReply *reply = m_manager.get(request);
- replies.append(reply);
- reply->ignoreSslErrors();
- QObject::connect(reply, SIGNAL(finished()), this, SLOT(multipleRequestsFinishedSlot()));
- QSignalSpy *metaDataChangedSpy = new QSignalSpy(reply, SIGNAL(metaDataChanged()));
- metaDataChangedSpies << metaDataChangedSpy;
- QSignalSpy *readyReadSpy = new QSignalSpy(reply, SIGNAL(readyRead()));
- readyReadSpies << readyReadSpy;
- QSignalSpy *finishedSpy = new QSignalSpy(reply, SIGNAL(finished()));
- finishedSpies << finishedSpy;
- }
-
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(finishedManagerSpy.count(), m_multipleRequestsCount);
-
- for (int a = 0; a < replies.count(); ++a) {
-
-#ifndef QT_NO_OPENSSL
- QCOMPARE(replies.at(a)->sslConfiguration().nextProtocolNegotiationStatus(),
- QSslConfiguration::NextProtocolNegotiationNegotiated);
- QCOMPARE(replies.at(a)->sslConfiguration().nextNegotiatedProtocol(),
- QByteArray(QSslConfiguration::NextProtocolSpdy3_0));
-#endif // QT_NO_OPENSSL
-
- QCOMPARE(replies.at(a)->error(), QNetworkReply::NoError);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), true);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::ConnectionEncryptedAttribute).toBool(), true);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
-
- // using the echo script, a request to "echo.cgi?1" will return a body of "1"
- QByteArray expectedContent = replies.at(a)->url().query().toUtf8();
- QByteArray content = replies.at(a)->readAll();
- QCOMPARE(expectedContent, content);
-
- QCOMPARE(metaDataChangedSpies.at(a)->count(), 1);
- metaDataChangedSpies.at(a)->deleteLater();
-
- QCOMPARE(finishedSpies.at(a)->count(), 1);
- finishedSpies.at(a)->deleteLater();
-
- QVERIFY(readyReadSpies.at(a)->count() > 0);
- readyReadSpies.at(a)->deleteLater();
-
- replies.at(a)->deleteLater();
- }
-}
-
-QTEST_MAIN(tst_Spdy)
-
-#include "tst_spdy.moc"
diff --git a/tests/auto/network/ssl/qdtls/tst_qdtls.cpp b/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
index 5d79b0f26b..3bbde484ce 100644
--- a/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
+++ b/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
@@ -162,7 +162,6 @@ Q_DECLARE_METATYPE(QSslSocket::SslMode)
Q_DECLARE_METATYPE(QSslSocket::PeerVerifyMode)
Q_DECLARE_METATYPE(QList<QSslCertificate>)
Q_DECLARE_METATYPE(QSslKey)
-Q_DECLARE_METATYPE(QVector<QSslError>)
QT_BEGIN_NAMESPACE
diff --git a/tests/auto/network/ssl/qocsp/tst_qocsp.cpp b/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
index 94d206ac83..8e579f7b5e 100644
--- a/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
+++ b/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
@@ -60,7 +60,6 @@ using VectorOfErrors = QT_PREPEND_NAMESPACE(QVector<SslError>);
using Latin1String = QT_PREPEND_NAMESPACE(QLatin1String);
Q_DECLARE_METATYPE(SslError)
-Q_DECLARE_METATYPE(VectorOfErrors)
Q_DECLARE_METATYPE(Latin1String)
QT_BEGIN_NAMESPACE
diff --git a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
index a98790843a..bc289101bb 100644
--- a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
+++ b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
@@ -73,7 +73,7 @@ typedef QSharedPointer<QSslSocket> QSslSocketPtr;
#else
#define FLUKE_CERTIFICATE_ERROR QSslError::CertificateUntrusted
#endif
-#endif // QT_NO_SSL
+#endif // QT_NO_OPENSSL
// Detect ALPN (Application-Layer Protocol Negotiation) support
#undef ALPN_SUPPORTED // Undef the variable first to be safe
@@ -259,10 +259,14 @@ private slots:
void signatureAlgorithm();
#endif
- void disabledProtocols_data();
- void disabledProtocols();
+ void unsupportedProtocols_data();
+ void unsupportedProtocols();
void oldErrorsOnSocketReuse();
+#if QT_CONFIG(openssl)
+ void alertMissingCertificate();
+ void alertInvalidCertificate();
+#endif // openssl
void setEmptyDefaultConfiguration(); // this test should be last
@@ -337,6 +341,8 @@ tst_QSslSocket::tst_QSslSocket()
qRegisterMetaType<QSslError>("QSslError");
qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
+ qRegisterMetaType<QAlertLevel>("QAlertLevel");
+ qRegisterMetaType<QAlertType>("QAlertType");
#ifndef QT_NO_OPENSSL
qRegisterMetaType<QSslPreSharedKeyAuthenticator *>();
@@ -1179,25 +1185,6 @@ void tst_QSslSocket::protocol()
QCOMPARE(socket->protocol(), QSsl::AnyProtocol);
socket->abort();
}
- {
- // qt-test-server allows TlsV1, so it allows TlsV1SslV3
- socket->setProtocol(QSsl::TlsV1SslV3);
- QCOMPARE(socket->protocol(), QSsl::TlsV1SslV3);
- socket->connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
- if (setProxy && !socket->waitForEncrypted())
- QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1SslV3);
- socket->abort();
- QCOMPARE(socket->protocol(), QSsl::TlsV1SslV3);
- socket->connectToHost(QtNetworkSettings::httpServerName(), 443);
- if (setProxy && !socket->waitForConnected())
- QSKIP("Skipping flaky test - See QTBUG-29941");
- socket->startClientEncryption();
- if (setProxy && !socket->waitForEncrypted())
- QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1SslV3);
- socket->abort();
- }
}
class SslServer : public QTcpServer
@@ -1229,6 +1216,8 @@ public:
signals:
void socketError(QAbstractSocket::SocketError);
+ void gotAlert(QAlertLevel level, QAlertType type, const QString &message);
+ void alertSent(QAlertLevel level, QAlertType type, const QString &message);
protected:
void incomingConnection(qintptr socketDescriptor)
@@ -1240,6 +1229,8 @@ protected:
if (ignoreSslErrors)
connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(ignoreErrorSlot()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(socketError(QAbstractSocket::SocketError)));
+ connect(socket, &QSslSocket::alertReceived, this, &SslServer::gotAlert);
+ connect(socket, &QSslSocket::alertSent, this, &SslServer::alertSent);
QFile file(m_keyFile);
QVERIFY(file.open(QIODevice::ReadOnly));
@@ -1303,20 +1294,13 @@ void tst_QSslSocket::protocolServerSide_data()
QTest::addColumn<bool>("works");
QTest::newRow("tls1.0-tls1.0") << QSsl::TlsV1_0 << QSsl::TlsV1_0 << true;
- QTest::newRow("tls1ssl3-tls1ssl3") << QSsl::TlsV1SslV3 << QSsl::TlsV1SslV3 << true;
QTest::newRow("any-any") << QSsl::AnyProtocol << QSsl::AnyProtocol << true;
QTest::newRow("secure-secure") << QSsl::SecureProtocols << QSsl::SecureProtocols << true;
- QTest::newRow("tls1-tls1ssl3") << QSsl::TlsV1_0 << QSsl::TlsV1SslV3 << true;
QTest::newRow("tls1.0-secure") << QSsl::TlsV1_0 << QSsl::SecureProtocols << true;
QTest::newRow("tls1.0-any") << QSsl::TlsV1_0 << QSsl::AnyProtocol << true;
- QTest::newRow("tls1ssl3-tls1.0") << QSsl::TlsV1SslV3 << QSsl::TlsV1_0 << true;
- QTest::newRow("tls1ssl3-secure") << QSsl::TlsV1SslV3 << QSsl::SecureProtocols << true;
- QTest::newRow("tls1ssl3-any") << QSsl::TlsV1SslV3 << QSsl::AnyProtocol << true;
-
QTest::newRow("secure-tls1.0") << QSsl::SecureProtocols << QSsl::TlsV1_0 << true;
- QTest::newRow("secure-tls1ssl3") << QSsl::SecureProtocols << QSsl::TlsV1SslV3 << true;
QTest::newRow("secure-any") << QSsl::SecureProtocols << QSsl::AnyProtocol << true;
QTest::newRow("tls1.0orlater-tls1.0") << QSsl::TlsV1_0OrLater << QSsl::TlsV1_0 << true;
@@ -1348,7 +1332,6 @@ void tst_QSslSocket::protocolServerSide_data()
#endif // TLS1_3_VERSION
QTest::newRow("any-tls1.0") << QSsl::AnyProtocol << QSsl::TlsV1_0 << true;
- QTest::newRow("any-tls1ssl3") << QSsl::AnyProtocol << QSsl::TlsV1SslV3 << true;
QTest::newRow("any-secure") << QSsl::AnyProtocol << QSsl::SecureProtocols << true;
}
@@ -4325,27 +4308,30 @@ void tst_QSslSocket::forwardReadChannelFinished()
#endif // QT_NO_OPENSSL
-void tst_QSslSocket::disabledProtocols_data()
+void tst_QSslSocket::unsupportedProtocols_data()
{
- QTest::addColumn<QSsl::SslProtocol>("disabledProtocol");
- QTest::newRow("SslV2") << QSsl::SslV2;
- QTest::newRow("SslV3") << QSsl::SslV3;
+ QTest::addColumn<QSsl::SslProtocol>("unsupportedProtocol");
+ QTest::newRow("DtlsV1_0") << QSsl::DtlsV1_0;
+ QTest::newRow("DtlsV1_2") << QSsl::DtlsV1_2;
+ QTest::newRow("DtlsV1_0OrLater") << QSsl::DtlsV1_0OrLater;
+ QTest::newRow("DtlsV1_2OrLater") << QSsl::DtlsV1_2OrLater;
+ QTest::newRow("UnknownProtocol") << QSsl::UnknownProtocol;
}
-void tst_QSslSocket::disabledProtocols()
+void tst_QSslSocket::unsupportedProtocols()
{
QFETCH_GLOBAL(const bool, setProxy);
if (setProxy)
return;
- QFETCH(const QSsl::SslProtocol, disabledProtocol);
+ QFETCH(const QSsl::SslProtocol, unsupportedProtocol);
const int timeoutMS = 500;
// Test a client socket.
{
// 0. connectToHostEncrypted: client-side, non-blocking API, error is discovered
// early, preventing any real connection from ever starting.
QSslSocket socket;
- socket.setProtocol(disabledProtocol);
+ socket.setProtocol(unsupportedProtocol);
QCOMPARE(socket.socketError(), QAbstractSocket::UnknownSocketError);
socket.connectToHostEncrypted(QStringLiteral("doesnotmatter.org"), 1010);
QCOMPARE(socket.socketError(), QAbstractSocket::SslInvalidUserDataError);
@@ -4363,7 +4349,7 @@ void tst_QSslSocket::disabledProtocols()
socket.connectToHost(QHostAddress::LocalHost, server.serverPort());
QVERIFY(socket.waitForConnected(timeoutMS));
- socket.setProtocol(disabledProtocol);
+ socket.setProtocol(unsupportedProtocol);
socket.startClientEncryption();
QCOMPARE(socket.socketError(), QAbstractSocket::SslInvalidUserDataError);
}
@@ -4377,7 +4363,7 @@ void tst_QSslSocket::disabledProtocols()
// and then calls startServerEncryption() (which must fall).
{
SslServer server;
- server.protocol = disabledProtocol;
+ server.protocol = unsupportedProtocol;
QVERIFY(server.listen());
QTestEventLoop loop;
@@ -4442,6 +4428,119 @@ void tst_QSslSocket::oldErrorsOnSocketReuse()
#endif // QT_NO_SSL
+#if QT_CONFIG(openssl)
+
+void (QSslSocket::*const tlsErrorSignal)(const QList<QSslError> &) = &QSslSocket::sslErrors;
+void (QAbstractSocket::*const socketErrorSignal)(QAbstractSocket::SocketError) = &QAbstractSocket::error;
+
+void tst_QSslSocket::alertMissingCertificate()
+{
+ // In this test we want a server to abort the connection due to the failing
+ // client authentication. The server expected to send an alert before closing
+ // the connection, and the client expected to receive this alert and report it.
+
+ QFETCH_GLOBAL(const bool, setProxy);
+ if (setProxy) // Not what we test here, bail out.
+ return;
+
+ SslServer server;
+ if (!server.listen(QHostAddress::LocalHost))
+ QSKIP("SslServer::listen() returned false");
+
+ // We want a certificate request to be sent to the client:
+ server.peerVerifyMode = QSslSocket::VerifyPeer;
+ // The only way we can force OpenSSL to send an alert - is to use
+ // a special option (so we fail before handshake is finished):
+ server.config.setMissingCertificateIsFatal(true);
+
+ QSslSocket clientSocket;
+ connect(&clientSocket, tlsErrorSignal, [&clientSocket](const QList<QSslError> &errors){
+ qDebug() << "ERR";
+ clientSocket.ignoreSslErrors(errors);
+ });
+
+ QSignalSpy serverSpy(&server, &SslServer::alertSent);
+ QSignalSpy clientSpy(&clientSocket, &QSslSocket::alertReceived);
+
+ clientSocket.connectToHostEncrypted(server.serverAddress().toString(), server.serverPort());
+
+ QTestEventLoop runner;
+ QTimer::singleShot(500, [&runner](){
+ runner.exitLoop();
+ });
+
+ int waitFor = 2;
+ auto earlyQuitter = [&runner, &waitFor](QAbstractSocket::SocketError) {
+ if (!--waitFor)
+ runner.exitLoop();
+ };
+
+ // Presumably, RemoteHostClosedError for the client and SslHandshakeError
+ // for the server:
+ connect(&clientSocket, socketErrorSignal, earlyQuitter);
+ connect(&server, &SslServer::socketError, earlyQuitter);
+
+ runner.enterLoopMSecs(1000);
+
+ QVERIFY(serverSpy.count() > 0);
+ QVERIFY(clientSpy.count() > 0);
+ QVERIFY(server.socket && !server.socket->isEncrypted());
+ QVERIFY(!clientSocket.isEncrypted());
+}
+
+void tst_QSslSocket::alertInvalidCertificate()
+{
+ // In this test a client will not ignore verification errors,
+ // it also will do 'early' checks, meaning the reported and
+ // not ignored _during_ the hanshake, not after. This ensures
+ // OpenSSL sends an alert.
+ QFETCH_GLOBAL(const bool, setProxy);
+ if (setProxy) // Not what we test here, bail out.
+ return;
+
+ SslServer server;
+ if (!server.listen(QHostAddress::LocalHost))
+ QSKIP("SslServer::listen() returned false");
+
+ QSslSocket clientSocket;
+ auto configuration = QSslConfiguration::defaultConfiguration();
+ configuration.setHandshakeMustInterruptOnError(true);
+ QVERIFY(configuration.handshakeMustInterruptOnError());
+ clientSocket.setSslConfiguration(configuration);
+
+ QSignalSpy serverSpy(&server, &SslServer::gotAlert);
+ QSignalSpy clientSpy(&clientSocket, &QSslSocket::alertSent);
+ QSignalSpy interruptedSpy(&clientSocket, &QSslSocket::handshakeInterruptedOnError);
+
+ clientSocket.connectToHostEncrypted(server.serverAddress().toString(), server.serverPort());
+
+ QTestEventLoop runner;
+ QTimer::singleShot(500, [&runner](){
+ runner.exitLoop();
+ });
+
+ int waitFor = 2;
+ auto earlyQuitter = [&runner, &waitFor](QAbstractSocket::SocketError) {
+ if (!--waitFor)
+ runner.exitLoop();
+ };
+
+ // Presumably, RemoteHostClosedError for the server and SslHandshakeError
+ // for the client:
+ connect(&clientSocket, socketErrorSignal, earlyQuitter);
+ connect(&server, &SslServer::socketError, earlyQuitter);
+
+ runner.enterLoopMSecs(1000);
+
+ QVERIFY(serverSpy.count() > 0);
+ QVERIFY(clientSpy.count() > 0);
+ QVERIFY(interruptedSpy.count() > 0);
+ QVERIFY(server.socket && !server.socket->isEncrypted());
+ QVERIFY(!clientSocket.isEncrypted());
+}
+
+#endif // openssl
+
QTEST_MAIN(tst_QSslSocket)
#include "tst_qsslsocket.moc"
diff --git a/tests/auto/opengl/opengl.pro b/tests/auto/opengl/opengl.pro
index 963cda170d..a220deae24 100644
--- a/tests/auto/opengl/opengl.pro
+++ b/tests/auto/opengl/opengl.pro
@@ -1,6 +1,2 @@
-TEMPLATE=subdirs
-SUBDIRS=\
- qgl \
- qglbuffer \
- qglfunctions \
- qglthreads \
+TEMPLATE = subdirs
+#SUBDIRS =
diff --git a/tests/auto/opengl/qgl/.gitignore b/tests/auto/opengl/qgl/.gitignore
deleted file mode 100644
index bb6e921035..0000000000
--- a/tests/auto/opengl/qgl/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-tst_qgl
diff --git a/tests/auto/opengl/qgl/BLACKLIST b/tests/auto/opengl/qgl/BLACKLIST
deleted file mode 100644
index ec75ea16eb..0000000000
--- a/tests/auto/opengl/qgl/BLACKLIST
+++ /dev/null
@@ -1,8 +0,0 @@
-[graphicsViewClipping]
-ubuntu-16.04
-rhel-7.6
-opensuse-leap
-ubuntu-18.04
-rhel-7.4
-opensuse-42.3
-
diff --git a/tests/auto/opengl/qgl/qgl.pro b/tests/auto/opengl/qgl/qgl.pro
deleted file mode 100644
index af930c5be7..0000000000
--- a/tests/auto/opengl/qgl/qgl.pro
+++ /dev/null
@@ -1,11 +0,0 @@
-############################################################
-# Project file for autotest for file qgl.h
-############################################################
-
-CONFIG += testcase
-TARGET = tst_qgl
-requires(qtHaveModule(opengl))
-QT += widgets widgets-private opengl-private gui-private core-private testlib
-
-SOURCES += tst_qgl.cpp
-RESOURCES = qgl.qrc
diff --git a/tests/auto/opengl/qgl/qgl.qrc b/tests/auto/opengl/qgl/qgl.qrc
deleted file mode 100644
index 70f425c1b9..0000000000
--- a/tests/auto/opengl/qgl/qgl.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource>
- <file alias="designer.png">../../gui/image/qpixmap/images/designer.png</file>
-</qresource>
-</RCC>
diff --git a/tests/auto/opengl/qgl/tst_qgl.cpp b/tests/auto/opengl/qgl/tst_qgl.cpp
deleted file mode 100644
index 3cc9592fb1..0000000000
--- a/tests/auto/opengl/qgl/tst_qgl.cpp
+++ /dev/null
@@ -1,2524 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
-
-#include <qcoreapplication.h>
-#include <qdebug.h>
-#include <qgl.h>
-#include <qglpixelbuffer.h>
-#include <qglframebufferobject.h>
-#include <qglcolormap.h>
-#include <qpaintengine.h>
-#include <qopenglfunctions.h>
-#include <qopenglframebufferobject.h>
-#include <qopenglpaintdevice.h>
-
-#include <QGraphicsView>
-#include <QGraphicsProxyWidget>
-#include <QVBoxLayout>
-
-#ifdef QT_BUILD_INTERNAL
-#include <qpa/qplatformpixmap.h>
-#include <QtOpenGL/private/qgl_p.h>
-#include <QtGui/private/qimage_p.h>
-#include <QtGui/private/qimagepixmapcleanuphooks_p.h>
-#include <QtGui/private/qopenglextensions_p.h>
-#endif
-
-class tst_QGL : public QObject
-{
-Q_OBJECT
-
-public:
- tst_QGL();
- virtual ~tst_QGL();
-
- static void initMain();
-
-private slots:
- void initTestCase();
- void getSetCheck();
-#ifdef QT_BUILD_INTERNAL
- void qglContextDefaultBindTexture();
- void openGLVersionCheck();
- void shareRegister();
- void textureCleanup();
-#endif
- void partialGLWidgetUpdates_data();
- void partialGLWidgetUpdates();
- void glWidgetWithAlpha();
- void glWidgetRendering();
- void glFBOSimpleRendering();
- void glFBORendering();
- void currentFboSync();
- void multipleFBOInterleavedRendering();
- void glFBOUseInGLWidget();
- void glPBufferRendering();
- void glWidgetReparent();
- void glWidgetRenderPixmap();
- void colormap();
- void fboFormat();
- void testDontCrashOnDanglingResources();
- void replaceClipping();
- void clipTest();
- void destroyFBOAfterContext();
- void threadImages();
- void nullRectCrash();
- void graphicsViewClipping();
- void extensions();
-};
-
-tst_QGL::tst_QGL()
-{
-}
-
-tst_QGL::~tst_QGL()
-{
-}
-
-void tst_QGL::initMain()
-{
- QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
-}
-
-void tst_QGL::initTestCase()
-{
- QGLWidget glWidget;
- if (!glWidget.isValid())
- QSKIP("QGL is not supported on the test system");
-}
-
-class MyGLContext : public QGLContext
-{
-public:
- MyGLContext(const QGLFormat& format) : QGLContext(format) {}
- bool windowCreated() const { return QGLContext::windowCreated(); }
- void setWindowCreated(bool on) { QGLContext::setWindowCreated(on); }
- bool initialized() const { return QGLContext::initialized(); }
- void setInitialized(bool on) { QGLContext::setInitialized(on); }
-};
-
-class MyGLWidget : public QGLWidget
-{
-public:
- MyGLWidget() : QGLWidget() {}
- bool autoBufferSwap() const { return QGLWidget::autoBufferSwap(); }
- void setAutoBufferSwap(bool on) { QGLWidget::setAutoBufferSwap(on); }
-};
-
-static int appDefaultDepth()
-{
- static int depth = 0;
- if (depth == 0) {
- QPixmap pm(1, 1);
- depth = pm.depth();
- }
- return depth;
-}
-
-// Using INT_MIN and INT_MAX will cause failures on systems
-// where "int" is 64-bit, so use the explicit values instead.
-#define TEST_INT_MIN (-2147483647 - 1)
-#define TEST_INT_MAX 2147483647
-
-// Testing get/set functions
-void tst_QGL::getSetCheck()
-{
- QGLFormat obj1;
- // int QGLFormat::depthBufferSize()
- // void QGLFormat::setDepthBufferSize(int)
- QCOMPARE(-1, obj1.depthBufferSize());
- obj1.setDepthBufferSize(0);
- QCOMPARE(0, obj1.depthBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setDepthBufferSize: Cannot set negative depth buffer size -2147483648");
- obj1.setDepthBufferSize(TEST_INT_MIN);
- QCOMPARE(0, obj1.depthBufferSize()); // Makes no sense with a negative buffer size
- obj1.setDepthBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setDepthBufferSize: Cannot set negative depth buffer size -1");
- obj1.setDepthBufferSize(-1);
- QCOMPARE(3, obj1.depthBufferSize());
- obj1.setDepthBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.depthBufferSize());
-
- // int QGLFormat::accumBufferSize()
- // void QGLFormat::setAccumBufferSize(int)
- QCOMPARE(-1, obj1.accumBufferSize());
- obj1.setAccumBufferSize(0);
- QCOMPARE(0, obj1.accumBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setAccumBufferSize: Cannot set negative accumulate buffer size -2147483648");
- obj1.setAccumBufferSize(TEST_INT_MIN);
- QCOMPARE(0, obj1.accumBufferSize()); // Makes no sense with a negative buffer size
- obj1.setAccumBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setAccumBufferSize: Cannot set negative accumulate buffer size -1");
- obj1.setAccumBufferSize(-1);
- QCOMPARE(3, obj1.accumBufferSize());
- obj1.setAccumBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.accumBufferSize());
-
- // int QGLFormat::redBufferSize()
- // void QGLFormat::setRedBufferSize(int)
- QCOMPARE(-1, obj1.redBufferSize());
- obj1.setRedBufferSize(0);
- QCOMPARE(0, obj1.redBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setRedBufferSize: Cannot set negative red buffer size -2147483648");
- obj1.setRedBufferSize(TEST_INT_MIN);
- QCOMPARE(0, obj1.redBufferSize()); // Makes no sense with a negative buffer size
- obj1.setRedBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setRedBufferSize: Cannot set negative red buffer size -1");
- obj1.setRedBufferSize(-1);
- QCOMPARE(3, obj1.redBufferSize());
- obj1.setRedBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.redBufferSize());
-
- // int QGLFormat::greenBufferSize()
- // void QGLFormat::setGreenBufferSize(int)
- QCOMPARE(-1, obj1.greenBufferSize());
- obj1.setGreenBufferSize(0);
- QCOMPARE(0, obj1.greenBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setGreenBufferSize: Cannot set negative green buffer size -2147483648");
- obj1.setGreenBufferSize(TEST_INT_MIN);
- QCOMPARE(0, obj1.greenBufferSize()); // Makes no sense with a negative buffer size
- obj1.setGreenBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setGreenBufferSize: Cannot set negative green buffer size -1");
- obj1.setGreenBufferSize(-1);
- QCOMPARE(3, obj1.greenBufferSize());
- obj1.setGreenBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.greenBufferSize());
-
- // int QGLFormat::blueBufferSize()
- // void QGLFormat::setBlueBufferSize(int)
- QCOMPARE(-1, obj1.blueBufferSize());
- obj1.setBlueBufferSize(0);
- QCOMPARE(0, obj1.blueBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setBlueBufferSize: Cannot set negative blue buffer size -2147483648");
- obj1.setBlueBufferSize(TEST_INT_MIN);
- QCOMPARE(0, obj1.blueBufferSize()); // Makes no sense with a negative buffer size
- obj1.setBlueBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setBlueBufferSize: Cannot set negative blue buffer size -1");
- obj1.setBlueBufferSize(-1);
- QCOMPARE(3, obj1.blueBufferSize());
- obj1.setBlueBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.blueBufferSize());
-
- // int QGLFormat::alphaBufferSize()
- // void QGLFormat::setAlphaBufferSize(int)
- QCOMPARE(-1, obj1.alphaBufferSize());
- QCOMPARE(false, obj1.alpha());
- QVERIFY(!obj1.testOption(QGL::AlphaChannel));
- QVERIFY(obj1.testOption(QGL::NoAlphaChannel));
- obj1.setAlphaBufferSize(1);
- QCOMPARE(true, obj1.alpha()); // setAlphaBufferSize() enables alpha.
- QCOMPARE(1, obj1.alphaBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setAlphaBufferSize: Cannot set negative alpha buffer size -2147483648");
- obj1.setAlphaBufferSize(TEST_INT_MIN);
- QCOMPARE(1, obj1.alphaBufferSize()); // Makes no sense with a negative buffer size
- obj1.setAlphaBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setAlphaBufferSize: Cannot set negative alpha buffer size -1");
- obj1.setAlphaBufferSize(-1);
- QCOMPARE(3, obj1.alphaBufferSize());
- obj1.setAlphaBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.alphaBufferSize());
-
- // int QGLFormat::stencilBufferSize()
- // void QGLFormat::setStencilBufferSize(int)
- QCOMPARE(-1, obj1.stencilBufferSize());
- obj1.setStencilBufferSize(1);
- QCOMPARE(1, obj1.stencilBufferSize());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setStencilBufferSize: Cannot set negative stencil buffer size -2147483648");
- obj1.setStencilBufferSize(TEST_INT_MIN);
- QCOMPARE(1, obj1.stencilBufferSize()); // Makes no sense with a negative buffer size
- obj1.setStencilBufferSize(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setStencilBufferSize: Cannot set negative stencil buffer size -1");
- obj1.setStencilBufferSize(-1);
- QCOMPARE(3, obj1.stencilBufferSize());
- obj1.setStencilBufferSize(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.stencilBufferSize());
-
- // bool QGLFormat::sampleBuffers()
- // void QGLFormat::setSampleBuffers(bool)
- QCOMPARE(false, obj1.sampleBuffers());
- QVERIFY(!obj1.testOption(QGL::SampleBuffers));
- QVERIFY(obj1.testOption(QGL::NoSampleBuffers));
-
- obj1.setSampleBuffers(false);
- QCOMPARE(false, obj1.sampleBuffers());
- QVERIFY(obj1.testOption(QGL::NoSampleBuffers));
- obj1.setSampleBuffers(true);
- QCOMPARE(true, obj1.sampleBuffers());
- QVERIFY(obj1.testOption(QGL::SampleBuffers));
-
- // int QGLFormat::samples()
- // void QGLFormat::setSamples(int)
- QCOMPARE(-1, obj1.samples());
- obj1.setSamples(0);
- QCOMPARE(0, obj1.samples());
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setSamples: Cannot have negative number of samples per pixel -2147483648");
- obj1.setSamples(TEST_INT_MIN);
- QCOMPARE(0, obj1.samples()); // Makes no sense with a negative sample size
- obj1.setSamples(3);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setSamples: Cannot have negative number of samples per pixel -1");
- obj1.setSamples(-1);
- QCOMPARE(3, obj1.samples());
- obj1.setSamples(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.samples());
-
- // int QGLFormat::swapInterval()
- // void QGLFormat::setSwapInterval(int)
- QCOMPARE(-1, obj1.swapInterval());
- obj1.setSwapInterval(0);
- QCOMPARE(0, obj1.swapInterval());
- obj1.setSwapInterval(TEST_INT_MIN);
- QCOMPARE(TEST_INT_MIN, obj1.swapInterval());
- obj1.setSwapInterval(-1);
- QCOMPARE(-1, obj1.swapInterval());
- obj1.setSwapInterval(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.swapInterval());
-
- // bool QGLFormat::doubleBuffer()
- // void QGLFormat::setDoubleBuffer(bool)
- QCOMPARE(true, obj1.doubleBuffer());
- QVERIFY(obj1.testOption(QGL::DoubleBuffer));
- QVERIFY(!obj1.testOption(QGL::SingleBuffer));
- obj1.setDoubleBuffer(false);
- QCOMPARE(false, obj1.doubleBuffer());
- QVERIFY(!obj1.testOption(QGL::DoubleBuffer));
- QVERIFY(obj1.testOption(QGL::SingleBuffer));
- obj1.setDoubleBuffer(true);
- QCOMPARE(true, obj1.doubleBuffer());
- QVERIFY(obj1.testOption(QGL::DoubleBuffer));
- QVERIFY(!obj1.testOption(QGL::SingleBuffer));
-
- // bool QGLFormat::depth()
- // void QGLFormat::setDepth(bool)
- QCOMPARE(true, obj1.depth());
- QVERIFY(obj1.testOption(QGL::DepthBuffer));
- QVERIFY(!obj1.testOption(QGL::NoDepthBuffer));
- obj1.setDepth(false);
- QCOMPARE(false, obj1.depth());
- QVERIFY(!obj1.testOption(QGL::DepthBuffer));
- QVERIFY(obj1.testOption(QGL::NoDepthBuffer));
- obj1.setDepth(true);
- QCOMPARE(true, obj1.depth());
- QVERIFY(obj1.testOption(QGL::DepthBuffer));
- QVERIFY(!obj1.testOption(QGL::NoDepthBuffer));
-
- // bool QGLFormat::rgba()
- // void QGLFormat::setRgba(bool)
- QCOMPARE(true, obj1.rgba());
- QVERIFY(obj1.testOption(QGL::Rgba));
- QVERIFY(!obj1.testOption(QGL::ColorIndex));
- obj1.setRgba(false);
- QCOMPARE(false, obj1.rgba());
- QVERIFY(!obj1.testOption(QGL::Rgba));
- QVERIFY(obj1.testOption(QGL::ColorIndex));
- obj1.setRgba(true);
- QCOMPARE(true, obj1.rgba());
- QVERIFY(obj1.testOption(QGL::Rgba));
- QVERIFY(!obj1.testOption(QGL::ColorIndex));
-
- // bool QGLFormat::alpha()
- // void QGLFormat::setAlpha(bool)
- QVERIFY(obj1.testOption(QGL::AlphaChannel));
- QVERIFY(!obj1.testOption(QGL::NoAlphaChannel));
- obj1.setAlpha(false);
- QCOMPARE(false, obj1.alpha());
- QVERIFY(!obj1.testOption(QGL::AlphaChannel));
- QVERIFY(obj1.testOption(QGL::NoAlphaChannel));
- obj1.setAlpha(true);
- QCOMPARE(true, obj1.alpha());
- QVERIFY(obj1.testOption(QGL::AlphaChannel));
- QVERIFY(!obj1.testOption(QGL::NoAlphaChannel));
-
- // bool QGLFormat::accum()
- // void QGLFormat::setAccum(bool)
- obj1.setAccumBufferSize(0);
- QCOMPARE(false, obj1.accum());
- QVERIFY(!obj1.testOption(QGL::AccumBuffer));
- QVERIFY(obj1.testOption(QGL::NoAccumBuffer));
- obj1.setAccum(false);
- QCOMPARE(false, obj1.accum());
- QVERIFY(!obj1.testOption(QGL::AccumBuffer));
- QVERIFY(obj1.testOption(QGL::NoAccumBuffer));
- obj1.setAccum(true);
- QCOMPARE(true, obj1.accum());
- QVERIFY(obj1.testOption(QGL::AccumBuffer));
- QVERIFY(!obj1.testOption(QGL::NoAccumBuffer));
-
- // bool QGLFormat::stencil()
- // void QGLFormat::setStencil(bool)
- QCOMPARE(true, obj1.stencil());
- QVERIFY(obj1.testOption(QGL::StencilBuffer));
- QVERIFY(!obj1.testOption(QGL::NoStencilBuffer));
- obj1.setStencil(false);
- QCOMPARE(false, obj1.stencil());
- QVERIFY(!obj1.testOption(QGL::StencilBuffer));
- QVERIFY(obj1.testOption(QGL::NoStencilBuffer));
- obj1.setStencil(true);
- QCOMPARE(true, obj1.stencil());
- QVERIFY(obj1.testOption(QGL::StencilBuffer));
- QVERIFY(!obj1.testOption(QGL::NoStencilBuffer));
-
- // bool QGLFormat::stereo()
- // void QGLFormat::setStereo(bool)
- QCOMPARE(false, obj1.stereo());
- QVERIFY(!obj1.testOption(QGL::StereoBuffers));
- QVERIFY(obj1.testOption(QGL::NoStereoBuffers));
- obj1.setStereo(false);
- QCOMPARE(false, obj1.stereo());
- QVERIFY(!obj1.testOption(QGL::StereoBuffers));
- QVERIFY(obj1.testOption(QGL::NoStereoBuffers));
- obj1.setStereo(true);
- QCOMPARE(true, obj1.stereo());
- QVERIFY(obj1.testOption(QGL::StereoBuffers));
- QVERIFY(!obj1.testOption(QGL::NoStereoBuffers));
-
- // bool QGLFormat::directRendering()
- // void QGLFormat::setDirectRendering(bool)
- QCOMPARE(true, obj1.directRendering());
- QVERIFY(obj1.testOption(QGL::DirectRendering));
- QVERIFY(!obj1.testOption(QGL::IndirectRendering));
- obj1.setDirectRendering(false);
- QCOMPARE(false, obj1.directRendering());
- QVERIFY(!obj1.testOption(QGL::DirectRendering));
- QVERIFY(obj1.testOption(QGL::IndirectRendering));
- obj1.setDirectRendering(true);
- QCOMPARE(true, obj1.directRendering());
- QVERIFY(obj1.testOption(QGL::DirectRendering));
- QVERIFY(!obj1.testOption(QGL::IndirectRendering));
-
- // bool QGLFormat::overlay()
- // void QGLFormat::setOverlay(bool)
- QCOMPARE(false, obj1.hasOverlay());
- QVERIFY(!obj1.testOption(QGL::HasOverlay));
- QVERIFY(obj1.testOption(QGL::NoOverlay));
- obj1.setOverlay(false);
- QCOMPARE(false, obj1.hasOverlay());
- QVERIFY(!obj1.testOption(QGL::HasOverlay));
- QVERIFY(obj1.testOption(QGL::NoOverlay));
- obj1.setOverlay(true);
- QCOMPARE(true, obj1.hasOverlay());
- QVERIFY(obj1.testOption(QGL::HasOverlay));
- QVERIFY(!obj1.testOption(QGL::NoOverlay));
-
- // int QGLFormat::plane()
- // void QGLFormat::setPlane(int)
- QCOMPARE(0, obj1.plane());
- obj1.setPlane(0);
- QCOMPARE(0, obj1.plane());
- obj1.setPlane(TEST_INT_MIN);
- QCOMPARE(TEST_INT_MIN, obj1.plane());
- obj1.setPlane(TEST_INT_MAX);
- QCOMPARE(TEST_INT_MAX, obj1.plane());
-
- // int QGLFormat::major/minorVersion()
- // void QGLFormat::setVersion(int, int)
- QCOMPARE(obj1.majorVersion(), 2);
- QCOMPARE(obj1.minorVersion(), 0);
- obj1.setVersion(3, 2);
- QCOMPARE(obj1.majorVersion(), 3);
- QCOMPARE(obj1.minorVersion(), 2);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setVersion: Cannot set zero or negative version number 0.1");
- obj1.setVersion(0, 1);
- QCOMPARE(obj1.majorVersion(), 3);
- QCOMPARE(obj1.minorVersion(), 2);
- QTest::ignoreMessage(QtWarningMsg, "QGLFormat::setVersion: Cannot set zero or negative version number 3.-1");
- obj1.setVersion(3, -1);
- QCOMPARE(obj1.majorVersion(), 3);
- QCOMPARE(obj1.minorVersion(), 2);
- obj1.setVersion(TEST_INT_MAX, TEST_INT_MAX - 1);
- QCOMPARE(obj1.majorVersion(), TEST_INT_MAX);
- QCOMPARE(obj1.minorVersion(), TEST_INT_MAX - 1);
-
-
- // operator== and operator!= for QGLFormat
- QGLFormat format1;
- QGLFormat format2;
-
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
- format1.setDoubleBuffer(false);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setDoubleBuffer(false);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setDepthBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setDepthBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setAccumBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setAccumBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setRedBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setRedBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setGreenBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setGreenBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setBlueBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setBlueBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setAlphaBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setAlphaBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setStencilBufferSize(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setStencilBufferSize(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setSamples(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setSamples(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setSwapInterval(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setSwapInterval(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setPlane(8);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setPlane(8);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setVersion(3, 2);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setVersion(3, 2);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setProfile(QGLFormat::CoreProfile);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setProfile(QGLFormat::CoreProfile);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- format1.setOption(QGL::NoDeprecatedFunctions);
- QVERIFY(!(format1 == format2));
- QVERIFY(format1 != format2);
- format2.setOption(QGL::NoDeprecatedFunctions);
- QCOMPARE(format1, format2);
- QVERIFY(!(format1 != format2));
-
- // Copy constructor and assignment for QGLFormat.
- QGLFormat format3(format1);
- QGLFormat format4;
- QCOMPARE(format1, format3);
- QVERIFY(format1 != format4);
- format4 = format1;
- QCOMPARE(format1, format4);
-
- // Check that modifying a copy doesn't affect the original.
- format3.setRedBufferSize(16);
- format4.setPlane(16);
- QCOMPARE(format1.redBufferSize(), 8);
- QCOMPARE(format1.plane(), 8);
-
- // Check the QGLFormat constructor that takes an option list.
- QGLFormat format5
- (QGL::DepthBuffer | QGL::StereoBuffers | QGL::ColorIndex, 3);
- QVERIFY(format5.depth());
- QVERIFY(format5.stereo());
- QVERIFY(format5.doubleBuffer()); // From defaultFormat()
- QVERIFY(!format5.hasOverlay()); // From defaultFormat()
- QVERIFY(!format5.rgba());
- QCOMPARE(format5.plane(), 3);
-
- // The default format should be the same as QGLFormat().
- QCOMPARE(QGLFormat::defaultFormat(), QGLFormat());
-
- // Modify the default format and check that it was changed.
- QGLFormat::setDefaultFormat(format1);
- QCOMPARE(QGLFormat::defaultFormat(), format1);
-
- // Restore the default format.
- QGLFormat::setDefaultFormat(QGLFormat());
- QCOMPARE(QGLFormat::defaultFormat(), QGLFormat());
-
- // Check the default overlay format's expected values.
- QGLFormat overlay(QGLFormat::defaultOverlayFormat());
- QCOMPARE(overlay.depthBufferSize(), -1);
- QCOMPARE(overlay.accumBufferSize(), -1);
- QCOMPARE(overlay.redBufferSize(), -1);
- QCOMPARE(overlay.greenBufferSize(), -1);
- QCOMPARE(overlay.blueBufferSize(), -1);
- QCOMPARE(overlay.alphaBufferSize(), -1);
- QCOMPARE(overlay.samples(), -1);
- QCOMPARE(overlay.swapInterval(), -1);
- QCOMPARE(overlay.plane(), 1);
- QVERIFY(!overlay.sampleBuffers());
- QVERIFY(!overlay.doubleBuffer());
- QVERIFY(!overlay.depth());
- QVERIFY(!overlay.rgba());
- QVERIFY(!overlay.alpha());
- QVERIFY(!overlay.accum());
- QVERIFY(!overlay.stencil());
- QVERIFY(!overlay.stereo());
- QVERIFY(overlay.directRendering()); // Only option that should be on.
- QVERIFY(!overlay.hasOverlay()); // Overlay doesn't need an overlay!
-
- // Modify the default overlay format and check that it was changed.
- QGLFormat::setDefaultOverlayFormat(format1);
- QCOMPARE(QGLFormat::defaultOverlayFormat(), format1);
-
- // Restore the default overlay format.
- QGLFormat::setDefaultOverlayFormat(overlay);
- QCOMPARE(QGLFormat::defaultOverlayFormat(), overlay);
-
- MyGLContext obj2(obj1);
- // bool QGLContext::windowCreated()
- // void QGLContext::setWindowCreated(bool)
- obj2.setWindowCreated(false);
- QCOMPARE(false, obj2.windowCreated());
- obj2.setWindowCreated(true);
- QCOMPARE(true, obj2.windowCreated());
-
- // bool QGLContext::initialized()
- // void QGLContext::setInitialized(bool)
- obj2.setInitialized(false);
- QCOMPARE(false, obj2.initialized());
- obj2.setInitialized(true);
- QCOMPARE(true, obj2.initialized());
-
- MyGLWidget obj3;
- // bool QGLWidget::autoBufferSwap()
- // void QGLWidget::setAutoBufferSwap(bool)
- obj3.setAutoBufferSwap(false);
- QCOMPARE(false, obj3.autoBufferSwap());
- obj3.setAutoBufferSwap(true);
- QCOMPARE(true, obj3.autoBufferSwap());
-}
-
-#ifdef QT_BUILD_INTERNAL
-QT_BEGIN_NAMESPACE
-extern QGLFormat::OpenGLVersionFlags qOpenGLVersionFlagsFromString(const QString &versionString);
-QT_END_NAMESPACE
-#endif
-
-#ifdef QT_BUILD_INTERNAL
-void tst_QGL::openGLVersionCheck()
-{
- QString versionString;
- QGLFormat::OpenGLVersionFlags expectedFlag;
- QGLFormat::OpenGLVersionFlags versionFlag;
-
- versionString = "1.1 Irix 6.5";
- expectedFlag = QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "1.2 Microsoft";
- expectedFlag = QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "1.2.1";
- expectedFlag = QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "1.3 NVIDIA";
- expectedFlag = QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "1.4";
- expectedFlag = QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "1.5 NVIDIA";
- expectedFlag = QGLFormat::OpenGL_Version_1_5 | QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "2.0.2 NVIDIA 87.62";
- expectedFlag = QGLFormat::OpenGL_Version_2_0 | QGLFormat::OpenGL_Version_1_5 | QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "2.1 NVIDIA";
- expectedFlag = QGLFormat::OpenGL_Version_2_1 | QGLFormat::OpenGL_Version_2_0 | QGLFormat::OpenGL_Version_1_5 | QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "2.1";
- expectedFlag = QGLFormat::OpenGL_Version_2_1 | QGLFormat::OpenGL_Version_2_0 | QGLFormat::OpenGL_Version_1_5 | QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "OpenGL ES-CM 1.0 ATI";
- expectedFlag = QGLFormat::OpenGL_ES_Common_Version_1_0 | QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "OpenGL ES-CL 1.0 ATI";
- expectedFlag = QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "OpenGL ES-CM 1.1 ATI";
- expectedFlag = QGLFormat::OpenGL_ES_Common_Version_1_1 | QGLFormat::OpenGL_ES_CommonLite_Version_1_1 | QGLFormat::OpenGL_ES_Common_Version_1_0 | QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "OpenGL ES-CL 1.1 ATI";
- expectedFlag = QGLFormat::OpenGL_ES_CommonLite_Version_1_1 | QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "OpenGL ES 2.0 ATI";
- expectedFlag = QGLFormat::OpenGL_ES_Version_2_0;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- versionString = "3.0";
- expectedFlag = QGLFormat::OpenGL_Version_3_0 | QGLFormat::OpenGL_Version_2_1 | QGLFormat::OpenGL_Version_2_0 | QGLFormat::OpenGL_Version_1_5 | QGLFormat::OpenGL_Version_1_4 | QGLFormat::OpenGL_Version_1_3 | QGLFormat::OpenGL_Version_1_2 | QGLFormat::OpenGL_Version_1_1;
- versionFlag = qOpenGLVersionFlagsFromString(versionString);
- QCOMPARE(versionFlag, expectedFlag);
-
- QGLWidget glWidget;
- glWidget.show();
- glWidget.makeCurrent();
-
- // This is unfortunately the only test we can make on the actual openGLVersionFlags()
- // However, the complicated parts are in openGLVersionFlags(const QString &versionString)
- // tested above
-
-#if defined(QT_OPENGL_ES_2)
- QVERIFY(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0);
-#else
- if (QOpenGLContext::currentContext()->isOpenGLES())
- QVERIFY(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0);
- else
- QVERIFY(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_1);
-#endif //defined(QT_OPENGL_ES_2)
-}
-#endif //QT_BUILD_INTERNAL
-
-static bool fuzzyComparePixels(const QRgb testPixel, const QRgb refPixel, const char* file, int line, int x = -1, int y = -1)
-{
- static int maxFuzz = 1;
- static bool maxFuzzSet = false;
-
- // On 16 bpp systems, we need to allow for more fuzz:
- if (!maxFuzzSet) {
- maxFuzzSet = true;
- if (appDefaultDepth() < 24)
- maxFuzz = 32;
- }
-
- int redFuzz = qAbs(qRed(testPixel) - qRed(refPixel));
- int greenFuzz = qAbs(qGreen(testPixel) - qGreen(refPixel));
- int blueFuzz = qAbs(qBlue(testPixel) - qBlue(refPixel));
- int alphaFuzz = qAbs(qAlpha(testPixel) - qAlpha(refPixel));
-
- if (refPixel != 0 && testPixel == 0) {
- QString msg;
- if (x >= 0) {
- msg = QString("Test pixel [%1, %2] is null (black) when it should be (%3,%4,%5,%6)")
- .arg(x).arg(y)
- .arg(qRed(refPixel)).arg(qGreen(refPixel)).arg(qBlue(refPixel)).arg(qAlpha(refPixel));
- } else {
- msg = QString("Test pixel is null (black) when it should be (%2,%3,%4,%5)")
- .arg(qRed(refPixel)).arg(qGreen(refPixel)).arg(qBlue(refPixel)).arg(qAlpha(refPixel));
- }
-
- QTest::qFail(msg.toLatin1(), file, line);
- return false;
- }
-
- if (redFuzz > maxFuzz || greenFuzz > maxFuzz || blueFuzz > maxFuzz || alphaFuzz > maxFuzz) {
- QString msg;
-
- if (x >= 0)
- msg = QString("Pixel [%1,%2]: ").arg(x).arg(y);
- else
- msg = QString("Pixel ");
-
- msg += QString("Max fuzz (%1) exceeded: (%2,%3,%4,%5) vs (%6,%7,%8,%9)")
- .arg(maxFuzz)
- .arg(qRed(testPixel)).arg(qGreen(testPixel)).arg(qBlue(testPixel)).arg(qAlpha(testPixel))
- .arg(qRed(refPixel)).arg(qGreen(refPixel)).arg(qBlue(refPixel)).arg(qAlpha(refPixel));
- QTest::qFail(msg.toLatin1(), file, line);
- return false;
- }
- return true;
-}
-
-static void fuzzyCompareImages(const QImage &testImage, const QImage &referenceImage, const char* file, int line)
-{
- QCOMPARE(testImage.width(), referenceImage.width());
- QCOMPARE(testImage.height(), referenceImage.height());
-
- for (int y = 0; y < testImage.height(); y++) {
- for (int x = 0; x < testImage.width(); x++) {
- if (!fuzzyComparePixels(testImage.pixel(x, y), referenceImage.pixel(x, y), file, line, x, y)) {
- // Might as well save the images for easier debugging:
- referenceImage.save("referenceImage.png");
- testImage.save("testImage.png");
- return;
- }
- }
- }
-}
-
-#define QFUZZY_COMPARE_IMAGES(A,B) \
- fuzzyCompareImages(A, B, __FILE__, __LINE__)
-
-#define QFUZZY_COMPARE_PIXELS(A,B) \
- fuzzyComparePixels(A, B, __FILE__, __LINE__)
-
-class UnclippedWidget : public QWidget
-{
-public:
- bool painted;
-
- UnclippedWidget()
- : painted(false)
- {
- }
-
- void paintEvent(QPaintEvent *)
- {
- QPainter p(this);
- p.fillRect(rect().adjusted(-1000, -1000, 1000, 1000), Qt::black);
-
- painted = true;
- }
-};
-
-void tst_QGL::graphicsViewClipping()
-{
- const int size = 64;
- UnclippedWidget *widget = new UnclippedWidget;
- widget->setFixedSize(size, size);
-
- QGraphicsScene scene;
-
- scene.addWidget(widget)->setPos(0, 0);
-
- QGraphicsView view(&scene);
- // Use Qt::Tool as fully decorated windows have a minimum width of 160 on Windows.
- view.setWindowFlags(view.windowFlags() | Qt::Tool);
- view.setBackgroundBrush(Qt::white);
- view.resize(2*size, 2*size);
-
- QGLWidget *viewport = new QGLWidget;
- view.setViewport(viewport);
- view.show();
- qApp->setActiveWindow(&view);
-
- if (!viewport->isValid())
- return;
-
- scene.setSceneRect(view.viewport()->rect());
-
- QVERIFY(QTest::qWaitForWindowExposed(view.viewport()->windowHandle()));
- #ifdef Q_OS_MAC
- // The black rectangle jumps from the center to the upper left for some reason.
- QTest::qWait(100);
- #endif
-
- QTRY_VERIFY(widget->painted);
-
- QImage image = viewport->grabFrameBuffer();
- QImage expected = image;
-
- QPainter p(&expected);
- p.fillRect(expected.rect(), Qt::white);
- p.fillRect(QRect(0, 0, size, size), Qt::black);
- p.end();
-
- QFUZZY_COMPARE_IMAGES(image, expected);
-}
-
-void tst_QGL::partialGLWidgetUpdates_data()
-{
- QTest::addColumn<bool>("doubleBufferedContext");
- QTest::addColumn<bool>("autoFillBackground");
- QTest::addColumn<bool>("supportsPartialUpdates");
-
- QTest::newRow("Double buffered context") << true << true << false;
- QTest::newRow("Double buffered context without auto-fill background") << true << false << false;
- QTest::newRow("Single buffered context") << false << true << false;
- QTest::newRow("Single buffered context without auto-fill background") << false << false << true;
-}
-
-void tst_QGL::partialGLWidgetUpdates()
-{
- QFETCH(bool, doubleBufferedContext);
- QFETCH(bool, autoFillBackground);
- QFETCH(bool, supportsPartialUpdates);
-
- class MyGLWidget : public QGLWidget
- {
- public:
- QRegion paintEventRegion;
- void paintEvent(QPaintEvent *e)
- {
- paintEventRegion = e->region();
- }
- };
-
- QGLFormat format = QGLFormat::defaultFormat();
- format.setDoubleBuffer(doubleBufferedContext);
- QGLFormat::setDefaultFormat(format);
-
- MyGLWidget widget;
- widget.setFixedSize(150, 150);
- widget.setAutoFillBackground(autoFillBackground);
- widget.show();
- QVERIFY(QTest::qWaitForWindowExposed(&widget));
- QCoreApplication::processEvents(); // Process all queued paint events
-
- if (widget.format().doubleBuffer() != doubleBufferedContext)
- QSKIP("Platform does not support requested format");
-
- widget.paintEventRegion = QRegion();
- widget.repaint(50, 50, 50, 50);
-
- if (supportsPartialUpdates)
- QCOMPARE(widget.paintEventRegion, QRegion(50, 50, 50, 50));
- else
- QCOMPARE(widget.paintEventRegion, QRegion(widget.rect()));
-}
-
-
-// This tests that rendering to a QGLPBuffer using QPainter works.
-void tst_QGL::glPBufferRendering()
-{
- if (!QGLPixelBuffer::hasOpenGLPbuffers())
- QSKIP("QGLPixelBuffer not supported on this platform");
-
- QGLPixelBuffer* pbuf = new QGLPixelBuffer(128, 128);
-
- QPainter p;
- bool begun = p.begin(pbuf);
- QVERIFY(begun);
-
- QPaintEngine::Type engineType = p.paintEngine()->type();
- QVERIFY(engineType == QPaintEngine::OpenGL || engineType == QPaintEngine::OpenGL2);
-
- p.fillRect(0, 0, 128, 128, Qt::red);
- p.fillRect(32, 32, 64, 64, Qt::blue);
- p.end();
-
- QImage fb = pbuf->toImage();
- delete pbuf;
-
- QImage reference(128, 128, fb.format());
- p.begin(&reference);
- p.fillRect(0, 0, 128, 128, Qt::red);
- p.fillRect(32, 32, 64, 64, Qt::blue);
- p.end();
-
- QFUZZY_COMPARE_IMAGES(fb, reference);
-}
-
-void tst_QGL::glWidgetWithAlpha()
-{
- QGLWidget* w = new QGLWidget(QGLFormat(QGL::AlphaChannel));
- w->show();
- QVERIFY(QTest::qWaitForWindowExposed(w));
-
- delete w;
-}
-
-
-void qt_opengl_draw_test_pattern(QPainter* painter, int width, int height)
-{
- QPainterPath intersectingPath;
- intersectingPath.moveTo(0, 0);
- intersectingPath.lineTo(100, 0);
- intersectingPath.lineTo(0, 100);
- intersectingPath.lineTo(100, 100);
- intersectingPath.closeSubpath();
-
- QPainterPath trianglePath;
- trianglePath.moveTo(50, 0);
- trianglePath.lineTo(100, 100);
- trianglePath.lineTo(0, 100);
- trianglePath.closeSubpath();
-
- painter->setTransform(QTransform()); // reset xform
- painter->fillRect(-1, -1, width+2, height+2, Qt::red); // Background
- painter->translate(14, 14);
- painter->fillPath(intersectingPath, Qt::blue); // Test stencil buffer works
- painter->translate(128, 0);
- painter->setClipPath(trianglePath); // Test depth buffer works
- painter->setTransform(QTransform()); // reset xform ready for fill
- painter->fillRect(-1, -1, width+2, height+2, Qt::green);
-}
-
-void qt_opengl_check_test_pattern(const QImage& img)
-{
- // As we're doing more than trivial painting, we can't just compare to
- // an image rendered with raster. Instead, we sample at well-defined
- // test-points:
- QFUZZY_COMPARE_PIXELS(img.pixel(39, 64), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(img.pixel(89, 64), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(img.pixel(64, 39), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(img.pixel(64, 89), QColor(Qt::blue).rgb());
-
- QFUZZY_COMPARE_PIXELS(img.pixel(167, 39), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(img.pixel(217, 39), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(img.pixel(192, 64), QColor(Qt::green).rgb());
-}
-
-class GLWidget : public QGLWidget
-{
-public:
- GLWidget(QWidget* p = 0)
- : QGLWidget(p), beginOk(false), engineType(QPaintEngine::MaxUser) {}
- bool beginOk;
- QPaintEngine::Type engineType;
- void paintGL()
- {
- QPainter p;
- beginOk = p.begin(this);
- QPaintEngine* pe = p.paintEngine();
- engineType = pe->type();
-
- qt_opengl_draw_test_pattern(&p, width(), height());
-
- // No p.end() or swap buffers, should be done automatically
- }
-
-};
-
-void tst_QGL::glWidgetRendering()
-{
- GLWidget w;
- w.resize(256, 128);
- w.show();
-
- QVERIFY(QTest::qWaitForWindowExposed(&w));
-
- QVERIFY(w.beginOk);
- QVERIFY(w.engineType == QPaintEngine::OpenGL || w.engineType == QPaintEngine::OpenGL2);
-
-#if defined(Q_OS_QNX)
- // glReadPixels reads from the back buffer. On QNX the buffer is not preserved
- // after a buffer swap. This is why we have to swap the buffer explicitly before calling
- // grabFrameBuffer to retrieve the content of the front buffer.
- w.swapBuffers();
-#endif
- QImage fb = w.grabFrameBuffer(false);
- qt_opengl_check_test_pattern(fb);
-}
-
-void tst_QGL::glFBOSimpleRendering()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- QGLWidget glw;
- glw.makeCurrent();
-
- // No multisample with combined depth/stencil attachment:
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::NoAttachment);
-
- QGLFramebufferObject *fbo = new QGLFramebufferObject(200, 100, fboFormat);
-
- fbo->bind();
-
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- funcs->glClearColor(1.0, 0.0, 0.0, 1.0);
- funcs->glClear(GL_COLOR_BUFFER_BIT);
- funcs->glFinish();
-
- QImage fb = fbo->toImage().convertToFormat(QImage::Format_RGB32);
- QImage reference(fb.size(), QImage::Format_RGB32);
- reference.fill(0xffff0000);
-
- QFUZZY_COMPARE_IMAGES(fb, reference);
-
- delete fbo;
-}
-
-// NOTE: This tests that CombinedDepthStencil attachment works by assuming the
-// GL2 engine is being used and is implemented the same way as it was when
-// this autotest was written. If this is not the case, there may be some
-// false-positives: I.e. The test passes when either the depth or stencil
-// buffer is actually missing. But that's probably ok anyway.
-void tst_QGL::glFBORendering()
-{
-#if defined(Q_OS_QNX)
- QSKIP("Reading the QGLFramebufferObject is unsupported on this platform");
-#endif
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- QGLWidget glw;
- glw.makeCurrent();
-
- // No multisample with combined depth/stencil attachment:
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
-
- // Don't complicate things by using NPOT:
- QGLFramebufferObject *fbo = new QGLFramebufferObject(256, 128, fboFormat);
-
- if (fbo->attachment() != QGLFramebufferObject::CombinedDepthStencil) {
- delete fbo;
- QSKIP("FBOs missing combined depth~stencil support");
- }
-
- QPainter fboPainter;
- bool painterBegun = fboPainter.begin(fbo);
- QVERIFY(painterBegun);
-
- qt_opengl_draw_test_pattern(&fboPainter, fbo->width(), fbo->height());
-
- fboPainter.end();
-
- QImage fb = fbo->toImage().convertToFormat(QImage::Format_RGB32);
- delete fbo;
-
- qt_opengl_check_test_pattern(fb);
-}
-
-class QOpenGLFramebufferObjectPaintDevice : public QOpenGLPaintDevice
-{
-public:
- QOpenGLFramebufferObjectPaintDevice(int width, int height)
- : QOpenGLPaintDevice(width, height)
- , m_fbo(width, height, QOpenGLFramebufferObject::CombinedDepthStencil)
- {
- }
-
- void ensureActiveTarget()
- {
- m_fbo.bind();
- }
-
- QImage toImage() const
- {
- return m_fbo.toImage();
- }
-
-private:
- QOpenGLFramebufferObject m_fbo;
-};
-
-void tst_QGL::currentFboSync()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
-#if defined(Q_OS_QNX)
- QSKIP("Reading the QGLFramebufferObject is unsupported on this platform");
-#endif
-
- QGLWidget glw;
- glw.makeCurrent();
-
- // For some reason we offer inter-operatibility between QGL and QOpenGL
- // paint engines. (?!) Let's check if the two engines can be used to perform
- // drawing in turns on different targets within the same context.
-
- {
- QGLFramebufferObject fbo1(256, 256, QGLFramebufferObject::CombinedDepthStencil);
-
- QOpenGLFramebufferObjectPaintDevice fbo2(256, 256);
-
- QImage sourceImage(256, 256, QImage::Format_ARGB32_Premultiplied);
- QPainter sourcePainter(&sourceImage);
- qt_opengl_draw_test_pattern(&sourcePainter, 256, 256);
-
- QPainter fbo1Painter(&fbo1);
-
- QPainter fbo2Painter(&fbo2);
- fbo2Painter.drawImage(0, 0, sourceImage);
- fbo2Painter.end();
-
- QImage fbo2Image = fbo2.toImage();
-
- fbo1Painter.drawImage(0, 0, sourceImage);
- fbo1Painter.end();
-
- QGLFramebufferObject::bindDefault();
-
- // Convert the QGLFBO's result since QOpenGLFBO uses a wider
- // variety of possible return formats.
- QCOMPARE(fbo1.toImage().convertToFormat(fbo2Image.format()), fbo2Image);
- }
-
- {
- QGLFramebufferObject fbo1(512, 512, QGLFramebufferObject::CombinedDepthStencil);
-
- QOpenGLFramebufferObjectPaintDevice fbo2(256, 256);
-
- QImage sourceImage(256, 256, QImage::Format_ARGB32_Premultiplied);
- QPainter sourcePainter(&sourceImage);
- qt_opengl_draw_test_pattern(&sourcePainter, 256, 256);
-
- QPainter fbo2Painter(&fbo2);
- fbo2Painter.drawImage(0, 0, sourceImage);
- QImage fbo2Image1 = fbo2.toImage();
- fbo2Painter.fillRect(0, 0, 256, 256, Qt::white);
-
- QPainter fbo1Painter(&fbo1);
- fbo1Painter.drawImage(0, 0, sourceImage);
- fbo1Painter.end();
-
- // check that the OpenGL paint engine now knows it needs to sync
- fbo2Painter.drawImage(0, 0, sourceImage);
- QImage fbo2Image2 = fbo2.toImage();
-
- fbo2Painter.end();
-
- QCOMPARE(fbo2Image1, fbo2Image2);
- }
-}
-
-// Tests multiple QPainters active on different FBOs at the same time, with
-// interleaving painting. Performance-wise, this is sub-optimal, but it still
-// has to work flawlessly
-void tst_QGL::multipleFBOInterleavedRendering()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- QGLWidget glw;
- glw.makeCurrent();
-
- // No multisample with combined depth/stencil attachment:
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
-
- QGLFramebufferObject *fbo1 = new QGLFramebufferObject(256, 128, fboFormat);
- QGLFramebufferObject *fbo2 = new QGLFramebufferObject(256, 128, fboFormat);
- QGLFramebufferObject *fbo3 = new QGLFramebufferObject(256, 128, fboFormat);
-
- if ( (fbo1->attachment() != QGLFramebufferObject::CombinedDepthStencil) ||
- (fbo2->attachment() != QGLFramebufferObject::CombinedDepthStencil) ||
- (fbo3->attachment() != QGLFramebufferObject::CombinedDepthStencil) )
- {
- delete fbo1;
- delete fbo2;
- delete fbo3;
- QSKIP("FBOs missing combined depth~stencil support");
- }
-
- QPainter fbo1Painter;
- QPainter fbo2Painter;
- QPainter fbo3Painter;
-
- QVERIFY(fbo1Painter.begin(fbo1));
- QVERIFY(fbo2Painter.begin(fbo2));
- QVERIFY(fbo3Painter.begin(fbo3));
-
- // Confirm we're using the GL2 engine, as interleaved rendering isn't supported
- // on the GL1 engine:
- if (fbo1Painter.paintEngine()->type() != QPaintEngine::OpenGL2)
- QSKIP("Interleaved GL rendering requires OpenGL 2.0 or higher");
-
- QPainterPath intersectingPath;
- intersectingPath.moveTo(0, 0);
- intersectingPath.lineTo(100, 0);
- intersectingPath.lineTo(0, 100);
- intersectingPath.lineTo(100, 100);
- intersectingPath.closeSubpath();
-
- QPainterPath trianglePath;
- trianglePath.moveTo(50, 0);
- trianglePath.lineTo(100, 100);
- trianglePath.lineTo(0, 100);
- trianglePath.closeSubpath();
-
- fbo1Painter.fillRect(0, 0, fbo1->width(), fbo1->height(), Qt::red); // Background
- fbo2Painter.fillRect(0, 0, fbo2->width(), fbo2->height(), Qt::green); // Background
- fbo3Painter.fillRect(0, 0, fbo3->width(), fbo3->height(), Qt::blue); // Background
-
- fbo1Painter.translate(14, 14);
- fbo2Painter.translate(14, 14);
- fbo3Painter.translate(14, 14);
-
- fbo1Painter.fillPath(intersectingPath, Qt::blue); // Test stencil buffer works
- fbo2Painter.fillPath(intersectingPath, Qt::red); // Test stencil buffer works
- fbo3Painter.fillPath(intersectingPath, Qt::green); // Test stencil buffer works
-
- fbo1Painter.translate(128, 0);
- fbo2Painter.translate(128, 0);
- fbo3Painter.translate(128, 0);
-
- fbo1Painter.setClipPath(trianglePath);
- fbo2Painter.setClipPath(trianglePath);
- fbo3Painter.setClipPath(trianglePath);
-
- fbo1Painter.setTransform(QTransform()); // reset xform
- fbo2Painter.setTransform(QTransform()); // reset xform
- fbo3Painter.setTransform(QTransform()); // reset xform
-
- fbo1Painter.fillRect(0, 0, fbo1->width(), fbo1->height(), Qt::green);
- fbo2Painter.fillRect(0, 0, fbo2->width(), fbo2->height(), Qt::blue);
- fbo3Painter.fillRect(0, 0, fbo3->width(), fbo3->height(), Qt::red);
-
- fbo1Painter.end();
- fbo2Painter.end();
- fbo3Painter.end();
-
- QImage fb1 = fbo1->toImage().convertToFormat(QImage::Format_RGB32);
- QImage fb2 = fbo2->toImage().convertToFormat(QImage::Format_RGB32);
- QImage fb3 = fbo3->toImage().convertToFormat(QImage::Format_RGB32);
- delete fbo1;
- delete fbo2;
- delete fbo3;
-
- // As we're doing more than trivial painting, we can't just compare to
- // an image rendered with raster. Instead, we sample at well-defined
- // test-points:
- QFUZZY_COMPARE_PIXELS(fb1.pixel(39, 64), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(89, 64), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(64, 39), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(64, 89), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(167, 39), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(217, 39), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb1.pixel(192, 64), QColor(Qt::green).rgb());
-
- QFUZZY_COMPARE_PIXELS(fb2.pixel(39, 64), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(89, 64), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(64, 39), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(64, 89), QColor(Qt::red).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(167, 39), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(217, 39), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb2.pixel(192, 64), QColor(Qt::blue).rgb());
-
- QFUZZY_COMPARE_PIXELS(fb3.pixel(39, 64), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(89, 64), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(64, 39), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(64, 89), QColor(Qt::green).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(167, 39), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(217, 39), QColor(Qt::blue).rgb());
- QFUZZY_COMPARE_PIXELS(fb3.pixel(192, 64), QColor(Qt::red).rgb());
-}
-
-class FBOUseInGLWidget : public QGLWidget
-{
-public:
- bool widgetPainterBeginOk;
- bool fboPainterBeginOk;
- QImage fboImage;
-protected:
- void paintEvent(QPaintEvent*)
- {
- QPainter widgetPainter;
- widgetPainterBeginOk = widgetPainter.begin(this);
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::NoAttachment);
- QGLFramebufferObject *fbo = new QGLFramebufferObject(100, 100, fboFormat);
-
- QPainter fboPainter;
- fboPainterBeginOk = fboPainter.begin(fbo);
- fboPainter.fillRect(-1, -1, 130, 130, Qt::red);
- fboPainter.end();
- fboImage = fbo->toImage();
-
- widgetPainter.fillRect(-1, -1, width()+2, height()+2, Qt::blue);
-
- delete fbo;
- }
-
-};
-
-void tst_QGL::glFBOUseInGLWidget()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- FBOUseInGLWidget w;
- w.resize(100, 100);
- w.showNormal();
-
- QVERIFY(QTest::qWaitForWindowExposed(&w));
-
- QVERIFY(w.widgetPainterBeginOk);
- QVERIFY(w.fboPainterBeginOk);
-
-#if defined(Q_OS_QNX)
- // glReadPixels reads from the back buffer. On QNX the buffer is not preserved
- // after a buffer swap. This is why we have to swap the buffer explicitly before calling
- // grabFrameBuffer to retrieve the content of the front buffer
- w.swapBuffers();
-#endif
-
- QImage widgetFB = w.grabFrameBuffer(false);
- QImage widgetReference(widgetFB.size(), widgetFB.format());
- widgetReference.fill(0xff0000ff);
- QFUZZY_COMPARE_IMAGES(widgetFB, widgetReference);
-
- QImage fboReference(w.fboImage.size(), w.fboImage.format());
- fboReference.fill(0xffff0000);
- QFUZZY_COMPARE_IMAGES(w.fboImage, fboReference);
-}
-
-void tst_QGL::glWidgetReparent()
-{
- // Try it as a top-level first:
- GLWidget *widget = new GLWidget;
- widget->setObjectName(QStringLiteral("glWidget1"));
- widget->setGeometry(0, 0, 200, 30);
- widget->show();
-
- QWidget grandParentWidget;
- grandParentWidget.setObjectName(QStringLiteral("grandParentWidget"));
- grandParentWidget.setPalette(Qt::blue);
- QVBoxLayout grandParentLayout(&grandParentWidget);
-
- QWidget parentWidget(&grandParentWidget);
- parentWidget.setObjectName(QStringLiteral("parentWidget"));
- grandParentLayout.addWidget(&parentWidget);
- parentWidget.setPalette(Qt::green);
- parentWidget.setAutoFillBackground(true);
- QVBoxLayout parentLayout(&parentWidget);
-
- grandParentWidget.setGeometry(0, 100, 200, 200);
- grandParentWidget.show();
-
- QVERIFY(QTest::qWaitForWindowExposed(widget));
- QVERIFY(QTest::qWaitForWindowExposed(&grandParentWidget));
-
- QVERIFY(parentWidget.children().count() == 1); // The layout
-
- // Now both widgets should be created & shown, time to re-parent:
- parentLayout.addWidget(widget);
-
- QVERIFY(QTest::qWaitForWindowExposed(&grandParentWidget));
-
- QVERIFY(parentWidget.children().count() == 2); // Layout & glwidget
- QVERIFY(parentWidget.children().contains(widget));
- QTRY_VERIFY(widget->height() > 30);
-
- delete widget;
-
- QVERIFY(QTest::qWaitForWindowExposed(&grandParentWidget));
-
- QVERIFY(parentWidget.children().count() == 1); // The layout
-
- // Now do pretty much the same thing, but don't show the
- // widget first:
- widget = new GLWidget;
- widget->setObjectName(QStringLiteral("glWidget2"));
- parentLayout.addWidget(widget);
-
- QVERIFY(QTest::qWaitForWindowExposed(&grandParentWidget));
-
- QVERIFY(parentWidget.children().count() == 2); // Layout & glwidget
- QVERIFY(parentWidget.children().contains(widget));
- QVERIFY(widget->height() > 30);
-
- delete widget;
-}
-
-class RenderPixmapWidget : public QGLWidget
-{
-protected:
- void initializeGL() {
- // Set some gl state:
- QOpenGLContext::currentContext()->functions()->glClearColor(1.0, 0.0, 0.0, 1.0);
- }
-
- void paintGL() {
- QOpenGLContext::currentContext()->functions()->glClear(GL_COLOR_BUFFER_BIT);
- }
-};
-
-void tst_QGL::glWidgetRenderPixmap()
-{
- RenderPixmapWidget *w = new RenderPixmapWidget;
-
- QSize pmSize = QSize(100, 100);
- QPixmap pm = w->renderPixmap(pmSize.width(), pmSize.height(), false);
-
- delete w;
-
- QImage fb = pm.toImage().convertToFormat(QImage::Format_RGB32);
- QImage reference(pmSize, QImage::Format_RGB32);
- reference.fill(0xffff0000);
-
- QFUZZY_COMPARE_IMAGES(fb, reference);
-}
-
-class ColormapExtended : public QGLColormap
-{
-public:
- ColormapExtended() {}
-
- Qt::HANDLE handle() { return QGLColormap::handle(); }
- void setHandle(Qt::HANDLE handle) { QGLColormap::setHandle(handle); }
-};
-
-void tst_QGL::colormap()
-{
- // Check the properties of the default empty colormap.
- QGLColormap cmap1;
- QVERIFY(cmap1.isEmpty());
- QCOMPARE(cmap1.size(), 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());
- QCOMPARE(cmap1.find(qRgb(255, 0, 0)), -1);
- QCOMPARE(cmap1.findNearest(qRgb(255, 0, 0)), -1);
-
- // Set an entry and re-test.
- cmap1.setEntry(56, qRgb(255, 0, 0));
- // The colormap is still considered "empty" even though it
- // has entries in it now. The isEmpty() method is used to
- // detect when the colormap is in use by a GL widget,
- // not to detect when it is empty!
- QVERIFY(cmap1.isEmpty());
- QCOMPARE(cmap1.size(), 256);
- 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));
- QCOMPARE(cmap1.find(qRgb(255, 0, 0)), 56);
- QCOMPARE(cmap1.findNearest(qRgb(255, 0, 0)), 56);
-
- // Set some more entries.
- static QRgb const colors[] = {
- qRgb(255, 0, 0),
- qRgb(0, 255, 0),
- qRgb(255, 255, 255),
- qRgb(0, 0, 255),
- qRgb(0, 0, 0)
- };
- cmap1.setEntry(57, QColor(0, 255, 0));
- cmap1.setEntries(3, colors + 2, 58);
- cmap1.setEntries(5, colors, 251);
- int idx;
- for (idx = 0; idx < 5; ++idx) {
- QVERIFY(cmap1.entryRgb(56 + idx) == colors[idx]);
- QVERIFY(cmap1.entryColor(56 + idx) == QColor(colors[idx]));
- QVERIFY(cmap1.entryRgb(251 + idx) == colors[idx]);
- QVERIFY(cmap1.entryColor(251 + idx) == QColor(colors[idx]));
- }
- QCOMPARE(cmap1.size(), 256);
-
- // Perform color lookups.
- QCOMPARE(cmap1.find(qRgb(255, 0, 0)), 56);
- QCOMPARE(cmap1.find(qRgb(0, 0, 0)), 60); // Actually finds 0, 0, 0, 255.
- QCOMPARE(cmap1.find(qRgba(0, 0, 0, 0)), 0);
- QCOMPARE(cmap1.find(qRgb(0, 255, 0)), 57);
- QCOMPARE(cmap1.find(qRgb(255, 255, 255)), 58);
- QCOMPARE(cmap1.find(qRgb(0, 0, 255)), 59);
- QCOMPARE(cmap1.find(qRgb(140, 0, 0)), -1);
- QCOMPARE(cmap1.find(qRgb(0, 140, 0)), -1);
- QCOMPARE(cmap1.find(qRgb(0, 0, 140)), -1);
- QCOMPARE(cmap1.find(qRgb(64, 0, 0)), -1);
- QCOMPARE(cmap1.find(qRgb(0, 64, 0)), -1);
- QCOMPARE(cmap1.find(qRgb(0, 0, 64)), -1);
- QCOMPARE(cmap1.findNearest(qRgb(255, 0, 0)), 56);
- QCOMPARE(cmap1.findNearest(qRgb(0, 0, 0)), 60);
- QCOMPARE(cmap1.findNearest(qRgba(0, 0, 0, 0)), 0);
- QCOMPARE(cmap1.findNearest(qRgb(0, 255, 0)), 57);
- QCOMPARE(cmap1.findNearest(qRgb(255, 255, 255)), 58);
- QCOMPARE(cmap1.findNearest(qRgb(0, 0, 255)), 59);
- QCOMPARE(cmap1.findNearest(qRgb(140, 0, 0)), 56);
- QCOMPARE(cmap1.findNearest(qRgb(0, 140, 0)), 57);
- QCOMPARE(cmap1.findNearest(qRgb(0, 0, 140)), 59);
- QCOMPARE(cmap1.findNearest(qRgb(64, 0, 0)), 0);
- QCOMPARE(cmap1.findNearest(qRgb(0, 64, 0)), 0);
- QCOMPARE(cmap1.findNearest(qRgb(0, 0, 64)), 0);
-
- // Make some copies of the colormap and check that they are the same.
- QGLColormap cmap2(cmap1);
- QGLColormap cmap3;
- cmap3 = cmap1;
- QVERIFY(cmap2.isEmpty());
- QVERIFY(cmap3.isEmpty());
- QCOMPARE(cmap2.size(), 256);
- QCOMPARE(cmap3.size(), 256);
- for (idx = 0; idx < 256; ++idx) {
- QCOMPARE(cmap1.entryRgb(idx), cmap2.entryRgb(idx));
- QCOMPARE(cmap1.entryRgb(idx), cmap3.entryRgb(idx));
- }
-
- // Modify an entry in one of the copies and recheck the original.
- cmap2.setEntry(45, qRgb(255, 0, 0));
- for (idx = 0; idx < 256; ++idx) {
- if (idx != 45)
- QCOMPARE(cmap1.entryRgb(idx), cmap2.entryRgb(idx));
- else
- QCOMPARE(cmap2.entryRgb(45), qRgb(255, 0, 0));
- QCOMPARE(cmap1.entryRgb(idx), cmap3.entryRgb(idx));
- }
-
- // Check that setting the handle will cause isEmpty() to work right.
- ColormapExtended cmap4;
- cmap4.setEntry(56, qRgb(255, 0, 0));
- QVERIFY(cmap4.isEmpty());
- QCOMPARE(cmap4.size(), 256);
- cmap4.setHandle(Qt::HANDLE(42));
- QCOMPARE(cmap4.handle(), Qt::HANDLE(42));
- QVERIFY(!cmap4.isEmpty());
- QCOMPARE(cmap4.size(), 256);
-}
-
-#ifndef GL_TEXTURE_3D
-#define GL_TEXTURE_3D 0x806F
-#endif
-
-#ifndef GL_RGB16
-#define GL_RGB16 0x8054
-#endif
-
-void tst_QGL::fboFormat()
-{
- // Check the initial conditions.
- QGLFramebufferObjectFormat format1;
- QCOMPARE(format1.samples(), 0);
- QCOMPARE(format1.attachment(), QGLFramebufferObject::NoAttachment);
- QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_2D));
- int expectedFormat =
-#ifdef QT_OPENGL_ES_2
- GL_RGBA;
-#else
- QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL ? GL_RGBA : GL_RGBA8;
-#endif
- QCOMPARE(int(format1.internalTextureFormat()), expectedFormat);
-
- // Modify the values and re-check.
- format1.setSamples(8);
- format1.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
- format1.setTextureTarget(GL_TEXTURE_3D);
- format1.setInternalTextureFormat(GL_RGB16);
- QCOMPARE(format1.samples(), 8);
- QCOMPARE(format1.attachment(), QGLFramebufferObject::CombinedDepthStencil);
- QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_3D));
- QCOMPARE(int(format1.internalTextureFormat()), int(GL_RGB16));
-
- // Make copies and check that they are the same.
- QGLFramebufferObjectFormat format2(format1);
- QGLFramebufferObjectFormat format3;
- QCOMPARE(format2.samples(), 8);
- 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);
- QCOMPARE(format3.attachment(), QGLFramebufferObject::CombinedDepthStencil);
- QCOMPARE(int(format3.textureTarget()), int(GL_TEXTURE_3D));
- QCOMPARE(int(format3.internalTextureFormat()), int(GL_RGB16));
-
- // Modify the copies and check that the original is unchanged.
- format2.setSamples(9);
- format3.setTextureTarget(GL_TEXTURE_2D);
- QCOMPARE(format1.samples(), 8);
- QCOMPARE(format1.attachment(), QGLFramebufferObject::CombinedDepthStencil);
- QCOMPARE(int(format1.textureTarget()), int(GL_TEXTURE_3D));
- QCOMPARE(int(format1.internalTextureFormat()), int(GL_RGB16));
-
- // operator== and operator!= for QGLFramebufferObjectFormat.
- QGLFramebufferObjectFormat format1c;
- QGLFramebufferObjectFormat format2c;
-
- QCOMPARE(format1c, format2c);
- QVERIFY(!(format1c != format2c));
- format1c.setSamples(8);
- QVERIFY(!(format1c == format2c));
- QVERIFY(format1c != format2c);
- format2c.setSamples(8);
- QCOMPARE(format1c, format2c);
- QVERIFY(!(format1c != format2c));
-
- format1c.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
- QVERIFY(!(format1c == format2c));
- QVERIFY(format1c != format2c);
- format2c.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
- QCOMPARE(format1c, format2c);
- QVERIFY(!(format1c != format2c));
-
- format1c.setTextureTarget(GL_TEXTURE_3D);
- QVERIFY(!(format1c == format2c));
- QVERIFY(format1c != format2c);
- format2c.setTextureTarget(GL_TEXTURE_3D);
- QCOMPARE(format1c, format2c);
- QVERIFY(!(format1c != format2c));
-
- format1c.setInternalTextureFormat(GL_RGB16);
- QVERIFY(!(format1c == format2c));
- QVERIFY(format1c != format2c);
- format2c.setInternalTextureFormat(GL_RGB16);
- QCOMPARE(format1c, format2c);
- QVERIFY(!(format1c != format2c));
-
- QGLFramebufferObjectFormat format3c(format1c);
- QGLFramebufferObjectFormat format4c;
- QCOMPARE(format1c, format3c);
- QVERIFY(!(format1c != format3c));
- format3c.setInternalTextureFormat(
-#ifdef QT_OPENGL_ES_2
- GL_RGBA
-#else
- QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL ? GL_RGBA : GL_RGBA8
-#endif
- );
- QVERIFY(!(format1c == format3c));
- QVERIFY(format1c != format3c);
-
- format4c = format1c;
- QCOMPARE(format1c, format4c);
- QVERIFY(!(format1c != format4c));
- format4c.setInternalTextureFormat(
-#ifdef QT_OPENGL_ES_2
- GL_RGBA
-#else
- QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL ? GL_RGBA : GL_RGBA8
-#endif
- );
- QVERIFY(!(format1c == format4c));
- QVERIFY(format1c != format4c);
-}
-
-void tst_QGL::testDontCrashOnDanglingResources()
-{
- // We have a number of Q_GLOBAL_STATICS inside the Qt OpenGL
- // module. This test is verify that we don't crash as a result of
- // them calling into libgl on application shutdown.
- QWidget *widget = new UnclippedWidget();
- widget->show();
- qApp->processEvents();
- widget->hide();
-}
-
-class ReplaceClippingGLWidget : public QGLWidget
-{
-public:
- void paint(QPainter *painter)
- {
- painter->fillRect(rect(), Qt::white);
-
- QPainterPath path;
- path.addRect(0, 0, 100, 100);
- path.addRect(50, 50, 100, 100);
-
- painter->setClipRect(0, 0, 150, 150);
- painter->fillPath(path, Qt::red);
-
- painter->translate(150, 150);
- painter->setClipRect(0, 0, 150, 150);
- painter->fillPath(path, Qt::red);
- }
-
-protected:
- void paintEvent(QPaintEvent*)
- {
- // clear the stencil with junk
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- funcs->glStencilMask(0xFFFF);
- funcs->glClearStencil(0xFFFF);
- funcs->glDisable(GL_STENCIL_TEST);
- funcs->glDisable(GL_SCISSOR_TEST);
- funcs->glClear(GL_STENCIL_BUFFER_BIT);
-
- QPainter painter(this);
- paint(&painter);
- }
-};
-
-void tst_QGL::replaceClipping()
-{
- ReplaceClippingGLWidget glw;
- glw.resize(300, 300);
- glw.show();
-
- QVERIFY(QTest::qWaitForWindowExposed(&glw));
-
- QImage reference(300, 300, QImage::Format_RGB32);
- QPainter referencePainter(&reference);
- glw.paint(&referencePainter);
- referencePainter.end();
-
-#if defined(Q_OS_QNX)
- // glReadPixels reads from the back buffer. On QNX the buffer is not preserved
- // after a buffer swap. This is why we have to swap the buffer explicitly before calling
- // grabFrameBuffer to retrieve the content of the front buffer
- glw.swapBuffers();
-#endif
- const QImage widgetFB = glw.grabFrameBuffer(false).convertToFormat(QImage::Format_RGB32);
-
- // Sample pixels in a grid pattern which avoids false failures due to
- // off-by-one pixel errors on some buggy GL implementations
- for (int x = 25; x < reference.width(); x += 50) {
- for (int y = 25; y < reference.width(); y += 50) {
- QFUZZY_COMPARE_PIXELS(widgetFB.pixel(x, y), reference.pixel(x, y));
- }
- }
-}
-
-class ClipTestGLWidget : public QGLWidget
-{
-public:
- void paint(QPainter *painter)
- {
- painter->fillRect(-1, -1, width()+2, height()+2, Qt::white);
- painter->setClipRect(10, 10, width()-20, height()-20);
- painter->fillRect(rect(), Qt::cyan);
-
- painter->save();
- painter->setClipRect(10, 10, 100, 100, Qt::IntersectClip);
-
- painter->fillRect(rect(), Qt::blue);
-
- painter->save();
- painter->setClipRect(10, 10, 50, 50, Qt::IntersectClip);
- painter->fillRect(rect(), Qt::red);
- painter->restore();
- painter->fillRect(0, 0, 40, 40, Qt::white);
- painter->save();
-
- painter->setClipRect(0, 0, 35, 35, Qt::IntersectClip);
- painter->fillRect(rect(), Qt::black);
- painter->restore();
-
- painter->fillRect(0, 0, 30, 30, Qt::magenta);
-
- painter->save();
- painter->setClipRect(60, 10, 50, 50, Qt::ReplaceClip);
- painter->fillRect(rect(), Qt::green);
- painter->restore();
-
- painter->restore();
-
- painter->translate(100, 100);
-
- {
- QPainterPath path;
- path.addRect(10, 10, 100, 100);
- path.addRect(10, 10, 10, 10);
- painter->setClipPath(path, Qt::IntersectClip);
- }
-
- painter->fillRect(rect(), Qt::blue);
-
- painter->save();
- {
- QPainterPath path;
- path.addRect(10, 10, 50, 50);
- path.addRect(10, 10, 10, 10);
- painter->setClipPath(path, Qt::IntersectClip);
- }
- painter->fillRect(rect(), Qt::red);
- painter->restore();
- painter->fillRect(0, 0, 40, 40, Qt::white);
- painter->save();
-
- {
- QPainterPath path;
- path.addRect(0, 0, 35, 35);
- path.addRect(10, 10, 10, 10);
- painter->setClipPath(path, Qt::IntersectClip);
- }
- painter->fillRect(rect(), Qt::black);
- painter->restore();
-
- painter->fillRect(0, 0, 30, 30, Qt::magenta);
-
- painter->save();
- {
- QPainterPath path;
- path.addRect(60, 10, 50, 50);
- path.addRect(10, 10, 10, 10);
- painter->setClipPath(path, Qt::ReplaceClip);
- }
- painter->fillRect(rect(), Qt::green);
- painter->restore();
- }
-
-protected:
- void paintEvent(QPaintEvent*)
- {
- QPainter painter(this);
- paint(&painter);
- }
-};
-
-void tst_QGL::clipTest()
-{
- ClipTestGLWidget glw;
- glw.resize(220, 220);
- glw.showNormal();
-
- QVERIFY(QTest::qWaitForWindowExposed(&glw));
-
- QImage reference(glw.size(), QImage::Format_RGB32);
- QPainter referencePainter(&reference);
- glw.paint(&referencePainter);
- referencePainter.end();
-
-#if defined(Q_OS_QNX)
- // glReadPixels reads from the back buffer. On QNX the buffer is not preserved
- // after a buffer swap. This is why we have to swap the buffer explicitly before calling
- // grabFrameBuffer to retrieve the content of the front buffer
- glw.swapBuffers();
-#endif
- const QImage widgetFB = glw.grabFrameBuffer(false).convertToFormat(QImage::Format_RGB32);
-
- // Sample pixels in a grid pattern which avoids false failures due to
- // off-by-one pixel errors on some buggy GL implementations
- for (int x = 2; x < reference.width(); x += 5) {
- for (int y = 2; y < reference.height(); y += 5) {
- QFUZZY_COMPARE_PIXELS(widgetFB.pixel(x, y), reference.pixel(x, y));
- }
- }
-}
-
-void tst_QGL::destroyFBOAfterContext()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- QGLWidget *glw = new QGLWidget();
- glw->makeCurrent();
-
- // No multisample with combined depth/stencil attachment:
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
-
- // Don't complicate things by using NPOT:
- QGLFramebufferObject *fbo = new QGLFramebufferObject(256, 128, fboFormat);
-
- // The handle should be valid until the context is destroyed.
- QVERIFY(fbo->handle() != 0);
- QVERIFY(fbo->isValid());
-
- delete glw;
-
- // The handle should now be zero.
- QVERIFY(!fbo->handle());
- QVERIFY(!fbo->isValid());
-
- delete fbo;
-}
-
-#ifdef QT_BUILD_INTERNAL
-
-class tst_QGLResource
-{
-public:
- tst_QGLResource(const QGLContext * = 0) {}
- ~tst_QGLResource() { ++deletions; }
-
- static int deletions;
-};
-
-int tst_QGLResource::deletions = 0;
-
-#ifdef TODO
-Q_GLOBAL_STATIC(QOpenGLContextGroupResource<tst_QGLResource>, qt_shared_test)
-#endif //TODO
-#endif // QT_BUILD_INTERNAL
-
-#ifdef QT_BUILD_INTERNAL
-void tst_QGL::shareRegister()
-{
-#ifdef TODO
- // Create a context.
- QGLWidget *glw1 = new QGLWidget();
- glw1->makeCurrent();
-
- // Nothing should be sharing with glw1's context yet.
- QVERIFY(!glw1->isSharing());
-
- // Create a guard for the first context.
- QOpenGLSharedResourceGuard guard(glw1->context()->contextHandle());
- QCOMPARE(guard.id(), 0);
- guard.setId(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);
- QCOMPARE(qt_shared_test()->value(glw1->context()->contextHandle()), res1);
-
- // Create another context that shares with the first.
- QVERIFY(!glw1->isSharing());
- QGLWidget *glw2 = new QGLWidget(0, glw1);
- if (!glw2->isSharing()) {
- delete glw2;
- delete glw1;
- QSKIP("Context sharing is not supported");
- }
- QVERIFY(glw1->isSharing());
- QVERIFY(glw1->context() != glw2->context());
-
- // Check that the first context's resource is also on the second.
- QCOMPARE(qt_shared_test()->value(glw1->context()), res1);
- QCOMPARE(qt_shared_test()->value(glw2->context()), res1);
-
- // Guard should still be the same.
- QCOMPARE(guard.context(), glw1->context());
- QCOMPARE(guard.id(), 3);
-
- // Check the sharing relationships.
- QVERIFY(QGLContext::areSharing(glw1->context(), glw1->context()));
- QVERIFY(QGLContext::areSharing(glw2->context(), glw2->context()));
- QVERIFY(QGLContext::areSharing(glw1->context(), glw2->context()));
- QVERIFY(QGLContext::areSharing(glw2->context(), glw1->context()));
- QVERIFY(!QGLContext::areSharing(0, glw2->context()));
- QVERIFY(!QGLContext::areSharing(glw1->context(), 0));
- QVERIFY(!QGLContext::areSharing(0, 0));
-
- // Create a third context, not sharing with the others.
- QGLWidget *glw3 = new QGLWidget();
- QVERIFY(!glw3->isSharing());
-
- // Create a guard on the standalone context.
- QGLSharedResourceGuard guard3(glw3->context());
- guard3.setId(5);
-
- // Request a resource to the third context.
- tst_QGLResource *res3 = qt_shared_test()->value(glw3->context());
- QVERIFY(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()));
- QVERIFY(QGLContext::areSharing(glw2->context(), glw2->context()));
- QVERIFY(QGLContext::areSharing(glw1->context(), glw2->context()));
- QVERIFY(QGLContext::areSharing(glw2->context(), glw1->context()));
- QVERIFY(!QGLContext::areSharing(glw1->context(), glw3->context()));
- QVERIFY(!QGLContext::areSharing(glw2->context(), glw3->context()));
- QVERIFY(!QGLContext::areSharing(glw3->context(), glw1->context()));
- QVERIFY(!QGLContext::areSharing(glw3->context(), glw2->context()));
- QVERIFY(QGLContext::areSharing(glw3->context(), glw3->context()));
- QVERIFY(!QGLContext::areSharing(0, glw2->context()));
- QVERIFY(!QGLContext::areSharing(glw1->context(), 0));
- QVERIFY(!QGLContext::areSharing(0, glw3->context()));
- QVERIFY(!QGLContext::areSharing(glw3->context(), 0));
- QVERIFY(!QGLContext::areSharing(0, 0));
-
- // Shared guard should still be the same.
- QCOMPARE(guard.context(), glw1->context());
- QCOMPARE(guard.id(), 3);
-
- // Delete the first context.
- delete glw1;
-
- // The second context should no longer register as sharing.
- QVERIFY(!glw2->isSharing());
-
- // The first context's resource should transfer to the second context.
- QCOMPARE(tst_QGLResource::deletions, 0);
- 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.
- 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;
- QCOMPARE(tst_QGLResource::deletions, 1);
- delete glw3;
- QCOMPARE(tst_QGLResource::deletions, 2);
-
- // Guards should now be null and the id zero.
- QVERIFY(guard.context() == 0);
- QVERIFY(guard.id() == 0);
- QVERIFY(guard3.context() == 0);
- QVERIFY(guard3.id() == 0);
-#endif //TODO
-}
-#endif
-
-// Tests QGLContext::bindTexture with default options
-#ifdef QT_BUILD_INTERNAL
-void tst_QGL::qglContextDefaultBindTexture()
-{
- QGLWidget w;
- w.makeCurrent();
- QGLContext *ctx = const_cast<QGLContext*>(w.context());
-
- QImage *boundImage = new QImage(256, 256, QImage::Format_RGB32);
- boundImage->fill(0xFFFFFFFF);
- QPixmap *boundPixmap = new QPixmap(256, 256);
- boundPixmap->fill(Qt::red);
-
- int startCacheItemCount = QGLTextureCache::instance()->size();
-
- GLuint boundImageTextureId = ctx->bindTexture(*boundImage);
- GLuint boundPixmapTextureId = ctx->bindTexture(*boundPixmap);
-
- // Make sure the image & pixmap have been added to the cache:
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- // Make sure the image & pixmap have the is_cached flag set:
- QVERIFY(QImagePixmapCleanupHooks::isImageCached(*boundImage));
- QVERIFY(QImagePixmapCleanupHooks::isPixmapCached(*boundPixmap));
-
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- // Make sure the texture IDs returned are valid:
- 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(funcs->glIsTexture(boundImageTextureId), GLboolean(GL_TRUE));
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
- delete boundPixmap;
- boundPixmap = 0;
- 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(funcs->glIsTexture(boundImageTextureId), GLboolean(GL_FALSE));
- QCOMPARE(funcs->glIsTexture(boundPixmapTextureId), GLboolean(GL_FALSE));
-}
-#endif
-
-#ifdef QT_BUILD_INTERNAL
-void tst_QGL::textureCleanup()
-{
- QGLWidget w;
- w.resize(200,200);
- w.show();
- QVERIFY(QTest::qWaitForWindowExposed(&w));
- w.makeCurrent();
-
- // Test pixmaps which have been loaded via QPixmapCache are removed from the texture cache
- // when the pixmap cache is cleared
- {
- int startCacheItemCount = QGLTextureCache::instance()->size();
- QPainter p(&w);
-
- QPixmap boundPixmap(":designer.png");
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawPixmap(0, 0, boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- // Check that the texture doesn't get removed from the cache when the pixmap is cleared
- // as it should still be in the cache:
- boundPixmap = QPixmap();
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- QPixmapCache::clear();
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
- }
-
- // Test pixmaps which have been loaded via QPixmapCache are removed from the texture cache
- // when they are explicitly removed from the pixmap cache
- {
- int startCacheItemCount = QGLTextureCache::instance()->size();
- QPainter p(&w);
-
- QPixmap boundPixmap(128, 128);
- QString cacheKey = QString::fromLatin1("myPixmap");
- QPixmapCache::insert(cacheKey, boundPixmap);
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawPixmap(0, 0, boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- // Check that the texture doesn't get removed from the cache when the pixmap is cleared
- // as it should still be in the cache:
- boundPixmap = QPixmap();
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- // Finally, we check that the texture cache entry is removed when we remove the
- // pixmap cache entry, which should hold the last reference:
- QPixmapCache::remove(cacheKey);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
- }
-
- // Check images & pixmaps are removed from the cache when they are deleted
- {
- int startCacheItemCount = QGLTextureCache::instance()->size();
- QPainter p(&w);
-
- QImage *boundImage = new QImage(256, 256, QImage::Format_RGB32);
- boundImage->fill(0xFFFFFFFF);
- QPixmap *boundPixmap = new QPixmap(256, 256);
- boundPixmap->fill(Qt::red);
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawImage(0, 0, *boundImage);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- p.drawPixmap(0, 0, *boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- delete boundImage;
- boundImage = 0;
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- delete boundPixmap;
- boundPixmap = 0;
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
- }
-
- // Check images & pixmaps are removed from the cache when they are assigned to
- {
- int startCacheItemCount = QGLTextureCache::instance()->size();
- QPainter p(&w);
-
- QImage boundImage(256, 256, QImage::Format_RGB32);
- boundImage.fill(0xFFFFFFFF);
- QPixmap boundPixmap(256, 256);
- boundPixmap.fill(Qt::red);
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawImage(0, 0, boundImage);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- p.drawPixmap(0, 0, boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- boundImage = QImage(64, 64, QImage::Format_RGB32);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- boundPixmap = QPixmap(64, 64);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
- }
-
- // Check images & pixmaps are removed from the cache when they are modified (detached)
- {
- int startCacheItemCount = QGLTextureCache::instance()->size();
- QPainter p(&w);
-
- QImage boundImage(256, 256, QImage::Format_RGB32);
- boundImage.fill(0xFFFFFFFF);
- QPixmap boundPixmap(256, 256);
- boundPixmap.fill(Qt::red);
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawImage(0, 0, boundImage);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- p.drawPixmap(0, 0, boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- boundImage.fill(0x00000000);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- boundPixmap.fill(Qt::blue);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
- }
-
- // Check that images/pixmaps aren't removed from the cache if a shallow copy has been made
- QImage copyOfImage;
- QPixmap copyOfPixmap;
- int startCacheItemCount = QGLTextureCache::instance()->size();
- {
- QPainter p(&w);
-
- QImage boundImage(256, 256, QImage::Format_RGB32);
- boundImage.fill(0xFFFFFFFF);
- QPixmap boundPixmap(256, 256);
- boundPixmap.fill(Qt::red);
-
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-
- p.drawImage(0, 0, boundImage);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- p.drawPixmap(0, 0, boundPixmap);
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- // Need to call end for the GL2 paint engine to release references to pixmap if using tfp
- p.end();
-
- copyOfImage = boundImage;
- copyOfPixmap = boundPixmap;
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
- } // boundImage & boundPixmap would have been deleted when they went out of scope
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+2);
-
- copyOfImage = QImage();
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount+1);
-
- copyOfPixmap = QPixmap();
- QCOMPARE(QGLTextureCache::instance()->size(), startCacheItemCount);
-}
-#endif
-
-namespace ThreadImages {
-
-class Producer : public QObject
-{
- Q_OBJECT
-public:
- Producer()
- {
- startTimer(20);
-
- QThread *thread = new QThread;
- thread->start();
-
- connect(this, SIGNAL(destroyed()), thread, SLOT(quit()));
-
- moveToThread(thread);
- connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
- }
-
-signals:
- void imageReady(const QImage &image);
-
-protected:
- void timerEvent(QTimerEvent *)
- {
- QImage image(256, 256, QImage::Format_RGB32);
- QLinearGradient g(0, 0, 0, 256);
- g.setColorAt(0, QColor(255, 180, 180));
- g.setColorAt(1, Qt::white);
- g.setSpread(QGradient::ReflectSpread);
-
- QBrush brush(g);
- brush.setTransform(QTransform::fromTranslate(0, delta));
- delta += 10;
-
- QPainter p(&image);
- p.fillRect(image.rect(), brush);
-
- if (images.size() > 10)
- images.removeFirst();
-
- images.append(image);
-
- emit imageReady(image);
- }
-
-private:
- QList<QImage> images;
- int delta;
-};
-
-
-class DisplayWidget : public QGLWidget
-{
- Q_OBJECT
-public:
- DisplayWidget(QWidget *parent) : QGLWidget(parent) {}
- void paintEvent(QPaintEvent *)
- {
- QPainter p(this);
- p.drawImage(rect(), m_image);
- }
-
-public slots:
- void setImage(const QImage &image)
- {
- m_image = image;
- update();
- }
-
-private:
- QImage m_image;
-};
-
-class Widget : public QWidget
-{
- Q_OBJECT
-public:
- Widget()
- : iterations(0)
- , display(0)
- , producer(new Producer)
- {
- startTimer(400);
- connect(this, SIGNAL(destroyed()), producer, SLOT(deleteLater()));
- }
-
- int iterations;
-
-protected:
- void timerEvent(QTimerEvent *)
- {
- ++iterations;
-
- delete display;
- display = new DisplayWidget(this);
- connect(producer, SIGNAL(imageReady(QImage)), display, SLOT(setImage(QImage)));
-
- display->setGeometry(rect());
- display->show();
- }
-
-private:
- DisplayWidget *display;
- Producer *producer;
-};
-
-}
-
-void tst_QGL::threadImages()
-{
- ThreadImages::Widget *widget = new ThreadImages::Widget;
- widget->show();
-
- while (widget->iterations <= 5) {
- qApp->processEvents();
- }
-
- delete widget;
-}
-
-void tst_QGL::nullRectCrash()
-{
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects())
- QSKIP("QGLFramebufferObject not supported on this platform");
-
- QGLWidget glw;
- glw.makeCurrent();
-
- QGLFramebufferObjectFormat fboFormat;
- fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
-
- QGLFramebufferObject *fbo = new QGLFramebufferObject(128, 128, fboFormat);
-
- QPainter fboPainter(fbo);
-
- fboPainter.setPen(QPen(QColor(255, 127, 127, 127), 2));
- fboPainter.setBrush(QColor(127, 255, 127, 127));
- fboPainter.drawRect(QRectF());
-
- fboPainter.end();
-}
-
-void tst_QGL::extensions()
-{
- QGLWidget glw;
- glw.makeCurrent();
-
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- QVERIFY(ctx);
- QOpenGLFunctions *funcs = ctx->functions();
- QVERIFY(funcs);
- QSurfaceFormat format = ctx->format();
-
-#ifdef QT_BUILD_INTERNAL
- QOpenGLExtensions *exts = static_cast<QOpenGLExtensions *>(funcs);
- QOpenGLExtensions::OpenGLExtensions allExts = exts->openGLExtensions();
- // Mipmapping is always available in GL2/GLES2+. Verify this.
- if (format.majorVersion() >= 2)
- QVERIFY(allExts.testFlag(QOpenGLExtensions::GenerateMipmap));
-#endif
-
- // Now look for some features should always be available in a given version.
- QOpenGLFunctions::OpenGLFeatures allFeatures = funcs->openGLFeatures();
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Multitexture));
- if (format.majorVersion() >= 2) {
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Shaders));
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Buffers));
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Multisample));
- QVERIFY(!ctx->isOpenGLES() || allFeatures.testFlag(QOpenGLFunctions::Framebuffers));
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::NPOTTextures)
- && allFeatures.testFlag(QOpenGLFunctions::NPOTTextureRepeat));
- if (ctx->isOpenGLES()) {
- QVERIFY(!allFeatures.testFlag(QOpenGLFunctions::FixedFunctionPipeline));
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Framebuffers));
- }
- }
- if (format.majorVersion() >= 3)
- QVERIFY(allFeatures.testFlag(QOpenGLFunctions::Framebuffers));
-}
-
-QTEST_MAIN(tst_QGL)
-#include "tst_qgl.moc"
diff --git a/tests/auto/opengl/qglbuffer/qglbuffer.pro b/tests/auto/opengl/qglbuffer/qglbuffer.pro
deleted file mode 100644
index f12a191f79..0000000000
--- a/tests/auto/opengl/qglbuffer/qglbuffer.pro
+++ /dev/null
@@ -1,10 +0,0 @@
-############################################################
-# Project file for autotest for file qglbuffer.h
-############################################################
-
-CONFIG += testcase
-TARGET = tst_qglbuffer
-requires(qtHaveModule(opengl))
-QT += opengl widgets testlib
-
-SOURCES += tst_qglbuffer.cpp
diff --git a/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp b/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp
deleted file mode 100644
index c7d26e757f..0000000000
--- a/tests/auto/opengl/qglbuffer/tst_qglbuffer.cpp
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
-#include <QtOpenGL/qgl.h>
-#include <QtOpenGL/qglbuffer.h>
-
-class tst_QGLBuffer : public QObject
-{
- Q_OBJECT
-public:
- tst_QGLBuffer() {}
- ~tst_QGLBuffer() {}
-
-private slots:
- void vertexBuffer_data();
- void vertexBuffer();
- void indexBuffer_data();
- void indexBuffer();
- void bufferSharing();
-
-private:
- void testBuffer(QGLBuffer::Type type);
-};
-
-void tst_QGLBuffer::vertexBuffer_data()
-{
- QTest::addColumn<int>("usagePattern");
-
- QTest::newRow("StreamDraw") << int(QGLBuffer::StreamDraw);
- QTest::newRow("StaticDraw") << int(QGLBuffer::StaticDraw);
- QTest::newRow("DynamicDraw") << int(QGLBuffer::DynamicDraw);
-}
-
-void tst_QGLBuffer::vertexBuffer()
-{
- testBuffer(QGLBuffer::VertexBuffer);
-}
-
-void tst_QGLBuffer::indexBuffer_data()
-{
- vertexBuffer_data();
-}
-
-void tst_QGLBuffer::indexBuffer()
-{
- testBuffer(QGLBuffer::IndexBuffer);
-}
-
-void tst_QGLBuffer::testBuffer(QGLBuffer::Type type)
-{
- QFETCH(int, usagePattern);
-
- QGLWidget w;
- w.makeCurrent();
-
- // Create the local object, but not the buffer in the server.
- QGLBuffer buffer(type);
- QCOMPARE(buffer.usagePattern(), QGLBuffer::StaticDraw);
- buffer.setUsagePattern(QGLBuffer::UsagePattern(usagePattern));
-
- // Check the initial state.
- QCOMPARE(buffer.type(), type);
- QVERIFY(!buffer.isCreated());
- 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.
- QVERIFY(!buffer.bind());
-
- // Create the buffer - if this fails, then assume that the
- // GL implementation does not support buffers at all.
- if (!buffer.create())
- QSKIP("Buffers are not supported on this platform");
-
- // Should now have a buffer id.
- QVERIFY(buffer.bufferId() != 0);
-
- // Bind the buffer and upload some data.
- QVERIFY(buffer.bind());
- static GLfloat const data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
- buffer.allocate(data, sizeof(data));
-
- // Check the buffer size.
- QCOMPARE(buffer.size(), int(sizeof(data)));
-
- // Map the buffer and read back its contents.
- bool haveMap = false;
- GLfloat *mapped = reinterpret_cast<GLfloat *>
- (buffer.map(QGLBuffer::ReadOnly));
- if (mapped) {
- for (int index = 0; index < 9; ++index)
- QCOMPARE(mapped[index], data[index]);
- buffer.unmap();
- haveMap = true;
- } else {
- qWarning("QGLBuffer::map() is not supported on this platform");
- }
-
- // Read back the buffer contents using read().
- bool haveRead = false;
- GLfloat readdata[9];
- if (buffer.read(0, readdata, sizeof(readdata))) {
- for (int index = 0; index < 9; ++index)
- QCOMPARE(readdata[index], data[index]);
- haveRead = true;
- } else {
- qWarning("QGLBuffer::read() is not supported on this platform");
- }
-
- // Write some different data to a specific location and check it.
- static GLfloat const diffdata[] = {11, 12, 13};
- buffer.write(sizeof(GLfloat) * 3, diffdata, sizeof(diffdata));
- if (haveMap) {
- mapped = reinterpret_cast<GLfloat *>(buffer.map(QGLBuffer::ReadOnly));
- QVERIFY(mapped != 0);
- for (int index = 0; index < 9; ++index) {
- if (index >= 3 && index <= 5)
- QCOMPARE(mapped[index], diffdata[index - 3]);
- else
- QCOMPARE(mapped[index], data[index]);
- }
- buffer.unmap();
- }
- if (haveRead) {
- QVERIFY(buffer.read(0, readdata, sizeof(readdata)));
- for (int index = 0; index < 9; ++index) {
- if (index >= 3 && index <= 5)
- QCOMPARE(readdata[index], diffdata[index - 3]);
- else
- QCOMPARE(readdata[index], data[index]);
- }
- }
-
- // Write to the buffer using the return value from map.
- if (haveMap) {
- mapped = reinterpret_cast<GLfloat *>(buffer.map(QGLBuffer::WriteOnly));
- QVERIFY(mapped != 0);
- mapped[6] = 14;
- buffer.unmap();
-
- mapped = reinterpret_cast<GLfloat *>(buffer.map(QGLBuffer::ReadOnly));
- QVERIFY(mapped != 0);
- static GLfloat const diff2data[] = {11, 12, 13, 14};
- for (int index = 0; index < 9; ++index) {
- if (index >= 3 && index <= 6)
- QCOMPARE(mapped[index], diff2data[index - 3]);
- else
- QCOMPARE(mapped[index], data[index]);
- }
- buffer.unmap();
- }
-
- // Resize the buffer.
- buffer.allocate(sizeof(GLfloat) * 20);
- QCOMPARE(buffer.size(), int(sizeof(GLfloat) * 20));
- buffer.allocate(0, sizeof(GLfloat) * 32);
- QCOMPARE(buffer.size(), int(sizeof(GLfloat) * 32));
-
- // Release the buffer.
- buffer.release();
-}
-
-void tst_QGLBuffer::bufferSharing()
-{
-#if defined(Q_OS_WIN)
- // Needs investigation on Windows: QTBUG-29692
- QSKIP("Unreproducible timeout on Windows (MSVC/MinGW) CI bots");
-#endif
-
-#if defined(Q_OS_QNX)
- QSKIP("Crashes on QNX when destroying the second QGLWidget (see QTBUG-38275)");
-#endif
-
- QGLWidget *w1 = new QGLWidget();
- w1->makeCurrent();
-
- QGLWidget *w2 = new QGLWidget(0, w1);
- if (!w2->isSharing()) {
- delete w2;
- delete w1;
- QSKIP("Context sharing is not supported on this platform");
- }
-
- // Bind the buffer in the first context and write some data to it.
- QGLBuffer buffer(QGLBuffer::VertexBuffer);
- if (!buffer.create())
- QSKIP("Buffers are not supported on this platform");
- QVERIFY(buffer.isCreated());
- QVERIFY(buffer.bind());
- static GLfloat const data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
- buffer.allocate(data, sizeof(data));
- QCOMPARE(buffer.size(), int(sizeof(data)));
- buffer.release();
-
- // Bind the buffer in the second context and read back the data.
- w2->makeCurrent();
- QVERIFY(buffer.bind());
- QCOMPARE(buffer.size(), int(sizeof(data)));
- GLfloat readdata[9];
- if (buffer.read(0, readdata, sizeof(readdata))) {
- for (int index = 0; index < 9; ++index)
- QCOMPARE(readdata[index], data[index]);
- }
- buffer.release();
-
- // Delete the first context.
- delete w1;
-
- // Make the second context current again because deleting the first
- // one will call doneCurrent() even though it wasn't current!
- w2->makeCurrent();
-
- // The buffer should still be valid in the second context.
- QVERIFY(buffer.bufferId() != 0);
- QVERIFY(buffer.isCreated());
- QVERIFY(buffer.bind());
- QCOMPARE(buffer.size(), int(sizeof(data)));
- buffer.release();
-
- // Delete the second context.
- delete w2;
-
- // The buffer should now be invalid.
- QCOMPARE(buffer.bufferId(), GLuint(0));
- QVERIFY(!buffer.isCreated());
-}
-
-QTEST_MAIN(tst_QGLBuffer)
-
-#include "tst_qglbuffer.moc"
diff --git a/tests/auto/opengl/qglfunctions/qglfunctions.pro b/tests/auto/opengl/qglfunctions/qglfunctions.pro
deleted file mode 100644
index 9b349eaf34..0000000000
--- a/tests/auto/opengl/qglfunctions/qglfunctions.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qglfunctions
-requires(qtHaveModule(opengl))
-QT += opengl widgets testlib
-
-SOURCES += tst_qglfunctions.cpp
diff --git a/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp b/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp
deleted file mode 100644
index 93d06659c9..0000000000
--- a/tests/auto/opengl/qglfunctions/tst_qglfunctions.cpp
+++ /dev/null
@@ -1,233 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
-#include <QtOpenGL/qglfunctions.h>
-
-class tst_QGLFunctions : public QObject
-{
- Q_OBJECT
-public:
- tst_QGLFunctions() {}
- ~tst_QGLFunctions() {}
-
-private slots:
- void features();
- void multitexture();
- void blendColor();
-
-private:
- static bool hasExtension(const char *name);
-};
-
-bool tst_QGLFunctions::hasExtension(const char *name)
-{
- QString extensions =
- QString::fromLatin1
- (reinterpret_cast<const char *>(QOpenGLContext::currentContext()->functions()->glGetString(GL_EXTENSIONS)));
- return extensions.split(QLatin1Char(' ')).contains
- (QString::fromLatin1(name));
-}
-
-// Check that the reported features are consistent with the platform.
-void tst_QGLFunctions::features()
-{
- // Before being associated with a context, there should be
- // no features enabled.
- QGLFunctions funcs;
- QVERIFY(!funcs.openGLFeatures());
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Multitexture));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Shaders));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Buffers));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Framebuffers));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendColor));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendEquation));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendEquationSeparate));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendFuncSeparate));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendSubtract));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::CompressedTextures));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Multisample));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::StencilSeparate));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures));
-
- // Make a context current.
- QGLWidget glw;
- if (!glw.isValid())
- QSKIP("Could not create a GL context");
- glw.makeCurrent();
- funcs.initializeGLFunctions();
-
- // Validate the features against what we expect for this platform.
- if (QOpenGLContext::currentContext()->isOpenGLES()) {
-#if !defined(QT_OPENGL_ES) || defined(QT_OPENGL_ES_2)
- QGLFunctions::OpenGLFeatures allFeatures =
- (QGLFunctions::Multitexture |
- QGLFunctions::Shaders |
- QGLFunctions::Buffers |
- QGLFunctions::Framebuffers |
- QGLFunctions::BlendColor |
- QGLFunctions::BlendEquation |
- QGLFunctions::BlendEquationSeparate |
- QGLFunctions::BlendFuncSeparate |
- QGLFunctions::BlendSubtract |
- QGLFunctions::CompressedTextures |
- QGLFunctions::Multisample |
- QGLFunctions::StencilSeparate |
- QGLFunctions::NPOTTextures);
- QVERIFY((funcs.openGLFeatures() & allFeatures) == allFeatures);
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Multitexture));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Shaders));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Buffers));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Framebuffers));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::BlendColor));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::BlendEquation));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::BlendEquationSeparate));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::BlendFuncSeparate));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::BlendSubtract));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::CompressedTextures));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Multisample));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::StencilSeparate));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures));
-#elif defined(QT_OPENGL_ES) && !defined(QT_OPENGL_ES_2)
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Multitexture));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Buffers));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::CompressedTextures));
- QVERIFY(funcs.hasOpenGLFeature(QGLFunctions::Multisample));
-
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::Shaders));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::BlendColor));
- QVERIFY(!funcs.hasOpenGLFeature(QGLFunctions::StencilSeparate));
-
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Framebuffers),
- hasExtension("GL_OES_framebuffer_object"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendEquationSeparate),
- hasExtension("GL_OES_blend_equation_separate"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendFuncSeparate),
- hasExtension("GL_OES_blend_func_separate"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendSubtract),
- hasExtension("GL_OES_blend_subtract"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures),
- hasExtension("GL_OES_texture_npot"));
-#endif
- } else {
- // We check for both the extension name and the minimum OpenGL version
- // for the feature. This will help us catch situations where a platform
- // doesn't list an extension by name but does have the feature by virtue
- // of its version number.
- QGLFormat::OpenGLVersionFlags versions = QGLFormat::openGLVersionFlags();
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Multitexture),
- hasExtension("GL_ARB_multitexture") ||
- (versions & QGLFormat::OpenGL_Version_1_3) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Shaders),
- hasExtension("GL_ARB_shader_objects") ||
- (versions & QGLFormat::OpenGL_Version_2_0) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Buffers),
- (versions & QGLFormat::OpenGL_Version_1_5) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Framebuffers),
- hasExtension("GL_EXT_framebuffer_object") ||
- hasExtension("GL_ARB_framebuffer_object"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendColor),
- hasExtension("GL_EXT_blend_color") ||
- (versions & QGLFormat::OpenGL_Version_1_2) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendEquation),
- (versions & QGLFormat::OpenGL_Version_1_2) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendEquationSeparate),
- hasExtension("GL_EXT_blend_equation_separate") ||
- (versions & QGLFormat::OpenGL_Version_2_0) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendFuncSeparate),
- hasExtension("GL_EXT_blend_func_separate") ||
- (versions & QGLFormat::OpenGL_Version_1_4) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::BlendSubtract),
- hasExtension("GL_EXT_blend_subtract"));
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::CompressedTextures),
- hasExtension("GL_ARB_texture_compression") ||
- (versions & QGLFormat::OpenGL_Version_1_3) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::Multisample),
- hasExtension("GL_ARB_multisample") ||
- (versions & QGLFormat::OpenGL_Version_1_3) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::StencilSeparate),
- (versions & QGLFormat::OpenGL_Version_2_0) != 0);
- QCOMPARE(funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures),
- hasExtension("GL_ARB_texture_non_power_of_two") ||
- (versions & QGLFormat::OpenGL_Version_2_0) != 0);
- }
-}
-
-// Verify that the multitexture functions appear to resolve and work.
-void tst_QGLFunctions::multitexture()
-{
- QOpenGLFunctions funcs;
- QGLWidget glw;
- if (!glw.isValid())
- QSKIP("Could not create a GL context");
- glw.makeCurrent();
- funcs.initializeOpenGLFunctions();
-
- if (!funcs.hasOpenGLFeature(QOpenGLFunctions::Multitexture))
- QSKIP("Multitexture functions are not supported");
-
- funcs.glActiveTexture(GL_TEXTURE1);
-
- GLint active = 0;
- funcs.glGetIntegerv(GL_ACTIVE_TEXTURE, &active);
- QCOMPARE(active, GL_TEXTURE1);
-
- funcs.glActiveTexture(GL_TEXTURE0);
-
- active = 0;
- funcs.glGetIntegerv(GL_ACTIVE_TEXTURE, &active);
- QCOMPARE(active, GL_TEXTURE0);
-}
-
-// Verify that the glBlendColor() function appears to resolve and work.
-void tst_QGLFunctions::blendColor()
-{
- QOpenGLFunctions funcs;
- QGLWidget glw;
- if (!glw.isValid())
- QSKIP("Could not create a GL context");
- glw.makeCurrent();
- funcs.initializeOpenGLFunctions();
-
- if (!funcs.hasOpenGLFeature(QOpenGLFunctions::BlendColor))
- QSKIP("glBlendColor() is not supported");
-
- funcs.glBlendColor(0.0f, 1.0f, 0.0f, 1.0f);
-
- GLfloat colors[4] = {0.5f, 0.5f, 0.5f, 0.5f};
- funcs.glGetFloatv(GL_BLEND_COLOR, colors);
-
- QCOMPARE(colors[0], 0.0f);
- QCOMPARE(colors[1], 1.0f);
- QCOMPARE(colors[2], 0.0f);
- QCOMPARE(colors[3], 1.0f);
-}
-
-QTEST_MAIN(tst_QGLFunctions)
-
-#include "tst_qglfunctions.moc"
diff --git a/tests/auto/opengl/qglthreads/qglthreads.pro b/tests/auto/opengl/qglthreads/qglthreads.pro
deleted file mode 100644
index 9aa21fb3a2..0000000000
--- a/tests/auto/opengl/qglthreads/qglthreads.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qglthreads
-requires(qtHaveModule(opengl))
-QT += opengl widgets testlib gui-private core-private
-
-HEADERS += tst_qglthreads.h
-SOURCES += tst_qglthreads.cpp
diff --git a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp b/tests/auto/opengl/qglthreads/tst_qglthreads.cpp
deleted file mode 100644
index e12f6d9c18..0000000000
--- a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp
+++ /dev/null
@@ -1,687 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
-#include <QtCore/QtCore>
-#include <QtGui/QtGui>
-#include <private/qguiapplication_p.h>
-#include <qpa/qplatformintegration.h>
-#include <QtWidgets/QApplication>
-#include <QtOpenGL/QtOpenGL>
-#include <qelapsedtimer.h>
-#include "tst_qglthreads.h"
-
-#ifndef QT_OPENGL_ES_2
-#include <QtGui/QOpenGLFunctions_1_0>
-#endif
-
-#define RUNNING_TIME 5000
-
-tst_QGLThreads::tst_QGLThreads(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*
-
- swapInThread
-
- The purpose of this testcase is to verify that it is possible to do rendering into
- a GL context from the GUI thread, then swap the contents in from a background thread.
-
- The usecase for this is to have the background thread do the waiting for vertical
- sync while the GUI thread is idle.
-
- Currently the locking is handled directly in the paintEvent(). For the actual usecase
- in Qt, the locking is done in the windowsurface before starting any drawing while
- unlocking is done after all drawing has been done.
- */
-
-
-class SwapThread : public QThread
-{
- Q_OBJECT
-public:
- SwapThread(QGLWidget *widget)
- : m_context(widget->context())
- , m_swapTriggered(false)
- {
- moveToThread(this);
- }
-
- void run() {
- QElapsedTimer timer;
- timer.start();
- while (timer.elapsed() < RUNNING_TIME) {
- lock();
- waitForReadyToSwap();
-
- m_context->makeCurrent();
- m_context->swapBuffers();
- m_context->doneCurrent();
-
- m_context->moveToThread(qApp->thread());
-
- signalSwapDone();
- unlock();
- }
-
- m_swapTriggered = false;
- }
-
- void lock() { m_mutex.lock(); }
- void unlock() { m_mutex.unlock(); }
-
- void waitForSwapDone() { if (m_swapTriggered) m_swapDone.wait(&m_mutex); }
- void waitForReadyToSwap() { if (!m_swapTriggered) m_readyToSwap.wait(&m_mutex); }
-
- void signalReadyToSwap()
- {
- if (!isRunning())
- return;
- m_readyToSwap.wakeAll();
- m_swapTriggered = true;
- }
-
- void signalSwapDone()
- {
- m_swapTriggered = false;
- m_swapDone.wakeAll();
- }
-
-private:
- QGLContext *m_context;
- QMutex m_mutex;
- QWaitCondition m_readyToSwap;
- QWaitCondition m_swapDone;
-
- bool m_swapTriggered;
-};
-
-class ForegroundWidget : public QGLWidget
-{
-public:
- ForegroundWidget(const QGLFormat &format)
- : QGLWidget(format), m_thread(0)
- {
- setAutoBufferSwap(false);
- }
-
- void resizeEvent(QResizeEvent *e)
- {
- m_thread->lock();
- QGLWidget::resizeEvent(e);
- m_thread->unlock();
- }
-
- void paintEvent(QPaintEvent *)
- {
- m_thread->lock();
- m_thread->waitForSwapDone();
-
- makeCurrent();
- QPainter p(this);
- p.fillRect(rect(), QColor(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)));
- p.setPen(Qt::red);
- p.setFont(QFont("SansSerif", 24));
- p.drawText(rect(), Qt::AlignCenter, "This is an autotest");
- p.end();
- doneCurrent();
-
- if (m_thread->isRunning()) {
- context()->moveToThread(m_thread);
- m_thread->signalReadyToSwap();
- }
-
- m_thread->unlock();
-
- update();
- }
-
- void setThread(SwapThread *thread) {
- m_thread = thread;
- }
-
- SwapThread *m_thread;
-};
-
-void tst_QGLThreads::swapInThread()
-{
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
- QSKIP("No platformsupport for ThreadedOpenGL");
- QGLFormat format;
- format.setSwapInterval(1);
- ForegroundWidget widget(format);
- SwapThread thread(&widget);
- widget.setThread(&thread);
- widget.show();
-
- QVERIFY(QTest::qWaitForWindowExposed(&widget));
- thread.start();
-
- while (thread.isRunning()) {
- qApp->processEvents();
- }
-
- widget.hide();
-
- QVERIFY(true);
-}
-
-/*
- renderInThread
-
- This test sets up a scene and renders it in a different thread.
- For simplicity, the scene is simply a bunch of rectangles, but
- if that works, we're in good shape..
- */
-
-static inline float qrandom() { return (QRandomGenerator::global()->bounded(100)) / 100.f; }
-
-void renderAScene(int w, int h)
-{
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
-
- if (QOpenGLContext::currentContext()->isOpenGLES()) {
- Q_UNUSED(w);
- Q_UNUSED(h);
- QGLShaderProgram program;
- program.addShaderFromSourceCode(QGLShader::Vertex, "attribute highp vec2 pos; void main() { gl_Position = vec4(pos.xy, 1.0, 1.0); }");
- program.addShaderFromSourceCode(QGLShader::Fragment, "uniform lowp vec4 color; void main() { gl_FragColor = color; }");
- program.bindAttributeLocation("pos", 0);
- program.bind();
-
- funcs->glEnableVertexAttribArray(0);
-
- for (int i=0; i<1000; ++i) {
- GLfloat pos[] = {
- (QRandomGenerator::global()->bounded(100)) / 100.f,
- (QRandomGenerator::global()->bounded(100)) / 100.f,
- (QRandomGenerator::global()->bounded(100)) / 100.f,
- (QRandomGenerator::global()->bounded(100)) / 100.f,
- (QRandomGenerator::global()->bounded(100)) / 100.f,
- (QRandomGenerator::global()->bounded(100)) / 100.f
- };
-
- funcs->glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, pos);
- funcs->glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
- }
- } else {
-#ifndef QT_OPENGL_ES_2
- QOpenGLFunctions_1_0 *gl1funcs = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_1_0>();
- gl1funcs->initializeOpenGLFunctions();
-
- gl1funcs->glViewport(0, 0, w, h);
-
- gl1funcs->glMatrixMode(GL_PROJECTION);
- gl1funcs->glLoadIdentity();
- gl1funcs->glFrustum(0, w, h, 0, 1, 100);
- gl1funcs->glTranslated(0, 0, -1);
-
- gl1funcs->glMatrixMode(GL_MODELVIEW);
- gl1funcs->glLoadIdentity();
-
- for (int i=0;i<1000; ++i) {
- gl1funcs->glBegin(GL_TRIANGLES);
- gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
- gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
- gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
- gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
- gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
- gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
- gl1funcs->glEnd();
- }
-#endif
- }
-}
-
-class ThreadSafeGLWidget : public QGLWidget
-{
-public:
- ThreadSafeGLWidget(QWidget *parent = 0) : QGLWidget(parent) {}
- void paintEvent(QPaintEvent *)
- {
- // ignored as we're anyway swapping as fast as we can
- };
-
- void resizeEvent(QResizeEvent *e)
- {
- mutex.lock();
- newSize = e->size();
- mutex.unlock();
- };
-
- QMutex mutex;
- QSize newSize;
-};
-
-class SceneRenderingThread : public QThread
-{
- Q_OBJECT
-public:
- SceneRenderingThread(ThreadSafeGLWidget *widget)
- : m_widget(widget)
- {
- moveToThread(this);
- m_size = widget->size();
- }
-
- void run() {
- QElapsedTimer timer;
- timer.start();
- failure = false;
-
- while (timer.elapsed() < RUNNING_TIME && !failure) {
-
- m_widget->makeCurrent();
-
- m_widget->mutex.lock();
- QSize s = m_widget->newSize;
- m_widget->mutex.unlock();
-
- QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
- if (s != m_size) {
- funcs->glViewport(0, 0, s.width(), s.height());
- }
-
- if (QGLContext::currentContext() != m_widget->context()) {
- failure = true;
- break;
- }
-
- funcs->glClear(GL_COLOR_BUFFER_BIT);
-
- int w = m_widget->width();
- int h = m_widget->height();
-
- renderAScene(w, h);
-
- int color;
- funcs->glReadPixels(w / 2, h / 2, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &color);
-
- m_widget->swapBuffers();
- }
-
- m_widget->doneCurrent();
- }
-
- bool failure;
-
-private:
- ThreadSafeGLWidget *m_widget;
- QSize m_size;
-};
-
-void tst_QGLThreads::renderInThread_data()
-{
- QTest::addColumn<bool>("resize");
- QTest::addColumn<bool>("update");
-
- QTest::newRow("basic") << false << false;
- QTest::newRow("with-resize") << true << false;
- QTest::newRow("with-update") << false << true;
- QTest::newRow("with-resize-and-update") << true << true;
-}
-
-void tst_QGLThreads::renderInThread()
-{
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
- QSKIP("No platformsupport for ThreadedOpenGL");
-
- QFETCH(bool, resize);
- QFETCH(bool, update);
-
-#if defined(Q_OS_MACOS)
- if (resize)
- QSKIP("gldSetZero crashes in render thread, QTBUG-68524");
-#endif
-
- ThreadSafeGLWidget widget;
- widget.resize(200, 200);
- SceneRenderingThread thread(&widget);
-
- widget.show();
- QVERIFY(QTest::qWaitForWindowExposed(&widget));
- widget.doneCurrent();
-
- widget.context()->moveToThread(&thread);
-
- thread.start();
-
- int value = 10;
- while (thread.isRunning()) {
- if (resize)
- widget.resize(200 + value, 200 + value);
- if (update)
- widget.update(100 + value, 100 + value, 20, 20);
- qApp->processEvents();
- value = -value;
-
- QThread::msleep(100);
- }
-
- QVERIFY(!thread.failure);
-}
-
-class Device
-{
-public:
- virtual ~Device() {}
- virtual QPaintDevice *realPaintDevice() = 0;
- virtual void prepareDevice() {}
- virtual void moveToThread(QThread *) {}
-};
-
-class GLWidgetWrapper : public Device
-{
-public:
- GLWidgetWrapper() {
- widget.resize(150, 150);
- widget.show();
- QVERIFY(QTest::qWaitForWindowExposed(&widget));
- widget.doneCurrent();
- }
- QPaintDevice *realPaintDevice() { return &widget; }
- void moveToThread(QThread *thread) { widget.context()->moveToThread(thread); }
-
- ThreadSafeGLWidget widget;
-};
-
-class PixmapWrapper : public Device
-{
-public:
- PixmapWrapper() { pixmap = new QPixmap(512, 512); }
- ~PixmapWrapper() { delete pixmap; }
- QPaintDevice *realPaintDevice() { return pixmap; }
-
- QPixmap *pixmap;
-};
-
-class PixelBufferWrapper : public Device
-{
-public:
- PixelBufferWrapper() { pbuffer = new QGLPixelBuffer(512, 512); }
- ~PixelBufferWrapper() { delete pbuffer; }
- QPaintDevice *realPaintDevice() { return pbuffer; }
- void moveToThread(QThread *thread) { pbuffer->context()->moveToThread(thread); }
-
- QGLPixelBuffer *pbuffer;
-};
-
-
-class FrameBufferObjectWrapper : public Device
-{
-public:
- FrameBufferObjectWrapper() {
- widget.makeCurrent();
- fbo = new QGLFramebufferObject(512, 512);
- widget.doneCurrent();
- }
- ~FrameBufferObjectWrapper() { delete fbo; }
- QPaintDevice *realPaintDevice() { return fbo; }
- void prepareDevice() { widget.makeCurrent(); }
- void moveToThread(QThread *thread) { widget.context()->moveToThread(thread); }
-
- ThreadSafeGLWidget widget;
- QGLFramebufferObject *fbo;
-};
-
-
-class ThreadPainter : public QObject
-{
- Q_OBJECT
-public:
- ThreadPainter(Device *pd) : device(pd), fail(true) {
- pixmap = QPixmap(40, 40);
- pixmap.fill(Qt::green);
- QPainter p(&pixmap);
- p.drawLine(0, 0, 40, 40);
- p.drawLine(0, 40, 40, 0);
- }
-
-public slots:
- void draw() {
- bool beginFailed = false;
- QElapsedTimer timer;
- timer.start();
- int rotAngle = 10;
- device->prepareDevice();
- QPaintDevice *paintDevice = device->realPaintDevice();
- QSize s(paintDevice->width(), paintDevice->height());
- while (timer.elapsed() < RUNNING_TIME) {
- QPainter p;
- if (!p.begin(paintDevice)) {
- beginFailed = true;
- break;
- }
- p.translate(s.width()/2, s.height()/2);
- p.rotate(rotAngle);
- p.translate(-s.width()/2, -s.height()/2);
- p.fillRect(0, 0, s.width(), s.height(), Qt::red);
- QRect rect(QPoint(0, 0), s);
- p.drawPixmap(10, 10, pixmap);
- p.drawTiledPixmap(50, 50, 100, 100, pixmap);
- p.drawText(rect.center(), "This is a piece of text");
- p.end();
- rotAngle += 2;
- QThread::msleep(20);
- }
-
- device->moveToThread(qApp->thread());
-
- fail = beginFailed;
- QThread::currentThread()->quit();
- }
-
- bool failed() { return fail; }
-
-private:
- QPixmap pixmap;
- Device *device;
- bool fail;
-};
-
-template <class T>
-class PaintThreadManager
-{
-public:
- PaintThreadManager(int count) : numThreads(count)
- {
- for (int i=0; i<numThreads; ++i)
- devices.append(new T);
- // Wait until resize events are processed on the internal
- // QGLWidgets of the buffers to suppress errors
- // about makeCurrent() from the wrong thread.
- QCoreApplication::processEvents();
- for (int i=0; i<numThreads; ++i) {
- devices.append(new T);
- threads.append(new QThread);
- painters.append(new ThreadPainter(devices.at(i)));
- painters.at(i)->moveToThread(threads.at(i));
- painters.at(i)->connect(threads.at(i), SIGNAL(started()), painters.at(i), SLOT(draw()));
- devices.at(i)->moveToThread(threads.at(i));
- }
- }
-
- ~PaintThreadManager() {
- qDeleteAll(threads);
- qDeleteAll(painters);
- qDeleteAll(devices);
- }
-
-
- void start() {
- for (int i=0; i<numThreads; ++i)
- threads.at(i)->start();
- }
-
- bool areRunning() {
- bool running = false;
- for (int i=0; i<numThreads; ++i){
- if (threads.at(i)->isRunning())
- running = true;
- }
-
- return running;
- }
-
- bool failed() {
- for (int i=0; i<numThreads; ++i) {
- if (painters.at(i)->failed())
- return true;
- }
-
- return false;
- }
-
-private:
- QList<QThread *> threads;
- QList<Device *> devices;
- QList<ThreadPainter *> painters;
- int numThreads;
-};
-
-/*
- This test uses QPainter to draw onto different QGLWidgets in
- different threads at the same time. The ThreadSafeGLWidget is
- necessary to handle paint and resize events that might come from
- the main thread at any time while the test is running. The resize
- and paint events would cause makeCurrent() calls to be issued from
- within the QGLWidget while the widget's context was current in
- another thread, which would cause errors.
-*/
-void tst_QGLThreads::painterOnGLWidgetInThread()
-{
- //QTBUG-46446 tst_qglthreads is unstable on windows 7
- if (QGuiApplication::platformName().compare("windows 7", Qt::CaseInsensitive))
- QSKIP("Doesn't work on this platform. QTBUG-46446");
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
- QSKIP("No platformsupport for ThreadedOpenGL");
- if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
- (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
- QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
- }
-
- PaintThreadManager<GLWidgetWrapper> painterThreads(5);
- painterThreads.start();
-
- while (painterThreads.areRunning()) {
- qApp->processEvents();
- QThread::msleep(100);
- }
- QVERIFY(!painterThreads.failed());
-}
-
-/*
- This test uses QPainter to draw onto different QPixmaps in
- different threads at the same time.
-*/
-void tst_QGLThreads::painterOnPixmapInThread()
-{
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL)
- || !QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps))
- QSKIP("No platformsupport for ThreadedOpenGL or ThreadedPixmaps");
- PaintThreadManager<PixmapWrapper> painterThreads(5);
- painterThreads.start();
-
- while (painterThreads.areRunning()) {
- qApp->processEvents();
- QThread::msleep(100);
- }
- QVERIFY(!painterThreads.failed());
-}
-
-/* This test uses QPainter to draw onto different QGLPixelBuffer
- objects in different threads at the same time.
-*/
-void tst_QGLThreads::painterOnPboInThread()
-{
- //QTBUG-46446 tst_qglthreads is unstable on windows 7
- if (QGuiApplication::platformName().compare("windows 7", Qt::CaseInsensitive))
- QSKIP("Doesn't work on this platform. QTBUG-46446");
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
- QSKIP("No platformsupport for ThreadedOpenGL");
- if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
- (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
- QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
- }
-
- if (!QGLPixelBuffer::hasOpenGLPbuffers()) {
- QSKIP("This system doesn't support pbuffers.");
- }
-
- PaintThreadManager<PixelBufferWrapper> painterThreads(5);
- painterThreads.start();
-
- while (painterThreads.areRunning()) {
- qApp->processEvents();
- QThread::msleep(100);
- }
- QVERIFY(!painterThreads.failed());
-}
-
-/* This test uses QPainter to draw onto different
- QGLFramebufferObjects (bound in a QGLWidget's context) in different
- threads at the same time.
-*/
-void tst_QGLThreads::painterOnFboInThread()
-{
- //QTBUG-46446 tst_qglthreads is unstable on windows 7
- if (QGuiApplication::platformName().compare("windows 7", Qt::CaseInsensitive))
- QSKIP("Doesn't work on this platform. QTBUG-46446");
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
- QSKIP("No platformsupport for ThreadedOpenGL");
- if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
- (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
- QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
- }
-
- if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()) {
- QSKIP("This system doesn't support framebuffer objects.");
- }
-
- PaintThreadManager<FrameBufferObjectWrapper> painterThreads(5);
- painterThreads.start();
-
- while (painterThreads.areRunning()) {
- qApp->processEvents();
- QThread::msleep(100);
- }
- QVERIFY(!painterThreads.failed());
-}
-
-int main(int argc, char **argv)
-{
- QApplication app(argc, argv);
- QTEST_DISABLE_KEYPAD_NAVIGATION \
-
- tst_QGLThreads tc;
- return QTest::qExec(&tc, argc, argv);
-}
-
-#include "tst_qglthreads.moc"
diff --git a/tests/auto/opengl/qglthreads/tst_qglthreads.h b/tests/auto/opengl/qglthreads/tst_qglthreads.h
deleted file mode 100644
index e4b496c163..0000000000
--- a/tests/auto/opengl/qglthreads/tst_qglthreads.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TST_QGLTHREADS_H
-#define TST_QGLTHREADS_H
-
-#include <QObject>
-
-class tst_QGLThreads : public QObject
-{
-Q_OBJECT
-public:
- explicit tst_QGLThreads(QObject *parent = 0);
-
-private slots:
- void swapInThread();
-
- void renderInThread_data();
- void renderInThread();
- void painterOnGLWidgetInThread();
- void painterOnPixmapInThread();
- void painterOnPboInThread();
- void painterOnFboInThread();
-};
-
-#endif // TST_QGLTHREADS_H
diff --git a/tests/auto/other/compiler/tst_compiler.cpp b/tests/auto/other/compiler/tst_compiler.cpp
index de15f4c62d..78026665be 100644
--- a/tests/auto/other/compiler/tst_compiler.cpp
+++ b/tests/auto/other/compiler/tst_compiler.cpp
@@ -634,7 +634,7 @@ void tst_Compiler::cxx11_alignas()
struct S {
alignas(double) char c;
};
- QCOMPARE(Q_ALIGNOF(S), Q_ALIGNOF(double));
+ QCOMPARE(alignof(S), alignof(double));
#endif
}
@@ -1396,7 +1396,7 @@ void tst_Compiler::cxx11_unrestricted_unions()
~U() {}
};
U u;
- std::aligned_storage<sizeof(QString), Q_ALIGNOF(QString)> as;
+ std::aligned_storage<sizeof(QString), alignof(QString)> as;
Q_UNUSED(u);
Q_UNUSED(as);
diff --git a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
index 0e61647e76..ed38976d94 100644
--- a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
+++ b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp
@@ -203,11 +203,15 @@ private slots:
void applicationTest();
void mainWindowTest();
void subWindowTest();
+#if QT_CONFIG(shortcut)
void buttonTest();
+#endif
void scrollBarTest();
void tabTest();
void tabWidgetTest();
+#if QT_CONFIG(shortcut)
void menuTest();
+#endif
void spinBoxTest();
void doubleSpinBoxTest();
void textEditTest();
@@ -234,8 +238,10 @@ private slots:
void dockWidgetTest();
void comboBoxTest();
void accessibleName();
+#if QT_CONFIG(shortcut)
void labelTest();
void accelerators();
+#endif
void bridgeTest();
void focusChild();
@@ -1027,6 +1033,8 @@ public Q_SLOTS:
}
};
+#if QT_CONFIG(shortcut)
+
void tst_QAccessibility::buttonTest()
{
QWidget window;
@@ -1199,6 +1207,8 @@ void tst_QAccessibility::buttonTest()
// test->release();
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QAccessibility::scrollBarTest()
{
QScrollBar *scrollBar = new QScrollBar(Qt::Horizontal);
@@ -1408,6 +1418,8 @@ void tst_QAccessibility::tabWidgetTest()
QTestAccessibility::clearEvents();
}
+#if QT_CONFIG(shortcut)
+
void tst_QAccessibility::menuTest()
{
{
@@ -1618,6 +1630,8 @@ void tst_QAccessibility::menuTest()
QTestAccessibility::clearEvents();
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QAccessibility::spinBoxTest()
{
QSpinBox * const spinBox = new QSpinBox();
@@ -3630,6 +3644,8 @@ void tst_QAccessibility::comboBoxTest()
QTestAccessibility::clearEvents();
}
+#if QT_CONFIG(shortcut)
+
void tst_QAccessibility::labelTest()
{
QWidget *window = new QWidget;
@@ -3730,6 +3746,8 @@ void tst_QAccessibility::accelerators()
QTestAccessibility::clearEvents();
}
+#endif // QT_CONFIG(shortcut)
+
#ifdef QT_SUPPORTS_IACCESSIBLE2
static IUnknown *queryIA2(IAccessible *acc, const IID &iid)
{
diff --git a/tests/auto/other/qfocusevent/tst_qfocusevent.cpp b/tests/auto/other/qfocusevent/tst_qfocusevent.cpp
index 260ba12a97..9285d5b5da 100644
--- a/tests/auto/other/qfocusevent/tst_qfocusevent.cpp
+++ b/tests/auto/other/qfocusevent/tst_qfocusevent.cpp
@@ -91,7 +91,9 @@ private slots:
void checkReason_BackTab();
void checkReason_Popup();
void checkReason_focusWidget();
+#if QT_CONFIG(shortcut)
void checkReason_Shortcut();
+#endif
void checkReason_ActiveWindow();
private:
@@ -250,6 +252,8 @@ QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
#endif
+#if QT_CONFIG(shortcut)
+
void tst_QFocusEvent::checkReason_Shortcut()
{
initWidget();
@@ -288,6 +292,8 @@ void tst_QFocusEvent::checkReason_Shortcut()
#endif
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QFocusEvent::checkReason_focusWidget()
{
// This test checks that a widget doesn't loose
diff --git a/tests/auto/other/toolsupport/tst_toolsupport.cpp b/tests/auto/other/toolsupport/tst_toolsupport.cpp
index ab7bca8322..9591eca16a 100644
--- a/tests/auto/other/toolsupport/tst_toolsupport.cpp
+++ b/tests/auto/other/toolsupport/tst_toolsupport.cpp
@@ -97,14 +97,14 @@ void tst_toolsupport::offsets_data()
{
QTestData &data = QTest::newRow("sizeof(QObjectData)")
<< sizeof(QObjectData);
- data << 28 << 48; // vptr + 3 ptr + 2 int + ptr
+ data << 36 << 64; // vptr + 2 ptr + (2*ptr + int) + 2 int + ptr
}
#if RUN_MEMBER_OFFSET_TEST
{
QTestData &data = QTest::newRow("QObjectPrivate::extraData")
<< pmm_to_offsetof(&QObjectPrivate::extraData);
- data << 28 << 48; // sizeof(QObjectData)
+ data << 36 << 64; // sizeof(QObjectData)
}
{
@@ -126,9 +126,9 @@ void tst_toolsupport::offsets_data()
#ifdef Q_PROCESSOR_X86
// x86 32-bit has weird alignment rules. Refer to QtPrivate::AlignOf in
// qglobal.h for more details.
- data << 152 << 224;
+ data << 184 << 288;
#else
- data << 156 << 224;
+ data << 188 << 288;
#endif
}
#endif
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.lightxml b/tests/auto/testlib/selftests/expected_signaldumper.lightxml
index 443f649bb6..8ce57e4b84 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.lightxml
+++ b/tests/auto/testlib/selftests/expected_signaldumper.lightxml
@@ -542,7 +542,7 @@
<Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))]]></Description>
</Message>
<Message type="info" file="" line="0">
- <Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())]]></Description>
+ <Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())]]></Description>
</Message>
<Message type="info" file="" line="0">
<Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())]]></Description>
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.tap b/tests/auto/testlib/selftests/expected_signaldumper.tap
index e2d664f4f1..39419280d4 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.tap
+++ b/tests/auto/testlib/selftests/expected_signaldumper.tap
@@ -134,7 +134,7 @@ ok 18 - slotEmittingSignalOldSyntax(queued)
# Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&)@_POINTER_)
# Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))
# Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))
-# Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())
+# Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())
# Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())
# Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector<int>&)@_POINTER_)
# Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector<int>())
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.teamcity b/tests/auto/testlib/selftests/expected_signaldumper.teamcity
index 0fc568e086..15bb4ddfe1 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.teamcity
+++ b/tests/auto/testlib/selftests/expected_signaldumper.teamcity
@@ -54,7 +54,7 @@
##teamcity[testStdOut name='slotEmittingSignalOldSyntax(queued)' out='INFO: Signal: SignalSlotClass(_POINTER_) signalWithoutParameters ()|nINFO: Signal: QEventDispatcherPlatform(_POINTER_) awake ()|nINFO: Signal: SignalSlotClass(_POINTER_) nestedSignal ()' flowId='tst_Signaldumper']
##teamcity[testFinished name='slotEmittingSignalOldSyntax(queued)' flowId='tst_Signaldumper']
##teamcity[testStarted name='variousTypes()' flowId='tst_Signaldumper']
-##teamcity[testStdOut name='variousTypes()' out='INFO: Signal: SignalSlotClass(_POINTER_) qStringSignal (QString(Test string))|nINFO: Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&)@_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))|nINFO: Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))|nINFO: Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector<int>&)@_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorConstPointerSignal ((const QVector<int>*)_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorPointerConstSignal ()|nINFO: Signal: SignalSlotClass(_POINTER_) qVariantSignal (QVariant())|nINFO: Signal: SignalSlotClass(_POINTER_) qVariantSignal (QVariant())' flowId='tst_Signaldumper']
+##teamcity[testStdOut name='variousTypes()' out='INFO: Signal: SignalSlotClass(_POINTER_) qStringSignal (QString(Test string))|nINFO: Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&)@_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))|nINFO: Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))|nINFO: Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector<int>&)@_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector<int>())|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorConstPointerSignal ((const QVector<int>*)_POINTER_)|nINFO: Signal: SignalSlotClass(_POINTER_) qVectorPointerConstSignal ()|nINFO: Signal: SignalSlotClass(_POINTER_) qVariantSignal (QVariant())|nINFO: Signal: SignalSlotClass(_POINTER_) qVariantSignal (QVariant())' flowId='tst_Signaldumper']
##teamcity[testFinished name='variousTypes()' flowId='tst_Signaldumper']
##teamcity[testStarted name='deletingSender()' flowId='tst_Signaldumper']
##teamcity[testStdOut name='deletingSender()' out='INFO: Signal: SignalSlotClass(_POINTER_) signalWithoutParameters ()' flowId='tst_Signaldumper']
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.txt b/tests/auto/testlib/selftests/expected_signaldumper.txt
index 0ee8cd38a2..92d609d14c 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.txt
+++ b/tests/auto/testlib/selftests/expected_signaldumper.txt
@@ -134,7 +134,7 @@ INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qSt
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&)@_POINTER_)
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))
-INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())
+INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector<int>&)@_POINTER_)
INFO : tst_Signaldumper::variousTypes() Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector<int>())
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.xml b/tests/auto/testlib/selftests/expected_signaldumper.xml
index f11a0c3ce6..01b0471268 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.xml
+++ b/tests/auto/testlib/selftests/expected_signaldumper.xml
@@ -544,7 +544,7 @@
<Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))]]></Description>
</Message>
<Message type="info" file="" line="0">
- <Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())]]></Description>
+ <Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())]]></Description>
</Message>
<Message type="info" file="" line="0">
<Description><![CDATA[Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())]]></Description>
diff --git a/tests/auto/testlib/selftests/expected_signaldumper.xunitxml b/tests/auto/testlib/selftests/expected_signaldumper.xunitxml
index cbf7075ba1..6609f518a2 100644
--- a/tests/auto/testlib/selftests/expected_signaldumper.xunitxml
+++ b/tests/auto/testlib/selftests/expected_signaldumper.xunitxml
@@ -142,7 +142,7 @@
<!-- message="Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&amp;)@_POINTER_)" type="info" -->
<!-- message="Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))" type="info" -->
<!-- message="Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))" type="info" -->
- <!-- message="Signal: SignalSlotClass(_POINTER_) qListSignal (QList&lt;int&gt;())" type="info" -->
+ <!-- message="Signal: SignalSlotClass(_POINTER_) qListSignal (QVector&lt;int&gt;())" type="info" -->
<!-- message="Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector&lt;int&gt;())" type="info" -->
<!-- message="Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector&lt;int&gt;&amp;)@_POINTER_)" type="info" -->
<!-- message="Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector&lt;int&gt;())" type="info" -->
@@ -274,7 +274,7 @@
<![CDATA[Signal: SignalSlotClass(_POINTER_) qStringRefSignal ((QString&)@_POINTER_)]]>
<![CDATA[Signal: SignalSlotClass(_POINTER_) qStringConstRefSignal (QString(Test string))]]>
<![CDATA[Signal: SignalSlotClass(_POINTER_) qByteArraySignal (QByteArray(Test bytearray))]]>
-<![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QList<int>())]]>
+<![CDATA[Signal: SignalSlotClass(_POINTER_) qListSignal (QVector<int>())]]>
<![CDATA[Signal: SignalSlotClass(_POINTER_) qVectorSignal (QVector<int>())]]>
<![CDATA[Signal: SignalSlotClass(_POINTER_) qVectorRefSignal ((QVector<int>&)@_POINTER_)]]>
<![CDATA[Signal: SignalSlotClass(_POINTER_) qVectorConstRefSignal (QVector<int>())]]>
diff --git a/tests/auto/tools/moc/allmocs_baseline_in.json b/tests/auto/tools/moc/allmocs_baseline_in.json
index 8cb397190c..c8abba6a8f 100644
--- a/tests/auto/tools/moc/allmocs_baseline_in.json
+++ b/tests/auto/tools/moc/allmocs_baseline_in.json
@@ -2,68 +2,6 @@
{
"classes": [
{
- "className": "MyBooooooostishClass",
- "qualifiedClassName": "MyBooooooostishClass",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- }
- ],
- "slots": [
- {
- "access": "public",
- "name": "mySlot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "no-keywords.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "Task87883",
- "qualifiedClassName": "Task87883",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "task87883.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "IfdefedClass",
- "qualifiedClassName": "IfdefedClass",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "c-comments.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
"className": "BackslashNewlines",
"qualifiedClassName": "BackslashNewlines",
"slots": [
@@ -87,340 +25,8 @@
{
"classes": [
{
- "className": "OldStyleCast",
- "qualifiedClassName": "OldStyleCast",
- "slots": [
- {
- "access": "public",
- "name": "foo",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "int"
- },
- {
- "type": "int*"
- },
- {
- "type": "const int*"
- },
- {
- "type": "volatile int*"
- },
- {
- "type": "const int*volatile*"
- }
- ],
- "name": "bar",
- "returnType": "int"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "int"
- },
- {
- "type": "QObject*const"
- }
- ],
- "name": "slot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "oldstyle-casts.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "SlotsWithVoidTemplateTest",
- "qualifiedClassName": "SlotsWithVoidTemplateTest",
- "signals": [
- {
- "access": "public",
- "arguments": [
- {
- "type": "TestTemplate<void>"
- }
- ],
- "name": "mySignal",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "myVoidSignal",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "myVoidSignal2",
- "returnType": "void"
- }
- ],
- "slots": [
- {
- "access": "public",
- "name": "dummySlot",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "dummySlot2",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "TestTemplate<void>"
- }
- ],
- "name": "anotherSlot",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "mySlot",
- "returnType": "TestTemplate<void>"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "slots-with-void-template.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "InvokableBeforeReturnType",
- "methods": [
- {
- "access": "public",
- "name": "foo",
- "returnType": "const char*"
- }
- ],
- "qualifiedClassName": "InvokableBeforeReturnType",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "InvokableBeforeInline",
- "methods": [
- {
- "access": "public",
- "name": "foo",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "bar",
- "returnType": "void"
- }
- ],
- "qualifiedClassName": "InvokableBeforeInline",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "qinvokable.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "Bar",
- "enums": [
- {
- "alias": "Flag",
- "isClass": false,
- "isFlag": true,
- "name": "Flags",
- "values": [
- "Read",
- "Write"
- ]
- }
- ],
- "properties": [
- {
- "constant": false,
- "designable": true,
- "final": false,
- "name": "flags",
- "read": "flags",
- "scriptable": true,
- "stored": true,
- "type": "Flags",
- "user": false,
- "write": "setFlags"
- }
- ],
- "qualifiedClassName": "Foo::Bar",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "Baz",
- "properties": [
- {
- "constant": false,
- "designable": true,
- "final": false,
- "name": "flags",
- "read": "flags",
- "scriptable": true,
- "stored": true,
- "type": "Foo::Bar::Flags",
- "user": false,
- "write": "setFlags"
- },
- {
- "constant": false,
- "designable": true,
- "final": false,
- "name": "flagsList",
- "read": "flagsList",
- "scriptable": true,
- "stored": true,
- "type": "QList<Foo::Bar::Flags>",
- "user": false,
- "write": "setFlagsList"
- }
- ],
- "qualifiedClassName": "Foo::Baz",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "namespaced-flags.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "Foo",
- "qualifiedClassName": "BBB::Foo",
- "signals": [
- {
- "access": "public",
- "arguments": [
- {
- "type": "QList<QList<int> >"
- }
- ],
- "name": "foo",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "QList<QList<int> >"
- }
- ],
- "name": "foo2",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "QList< ::AAA::BaseA*>"
- }
- ],
- "name": "bar",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "QList< ::AAA::BaseA*>"
- }
- ],
- "name": "bar2",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "QList<const ::AAA::BaseA*>"
- }
- ],
- "name": "bar3",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- },
- {
- "access": "public",
- "name": "::AAA::BaseA"
- }
- ]
- }
- ],
- "inputFile": "trigraphs.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "classInfos": [
- {
- "name": "Test",
- "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\x53"
- },
- {
- "name": "Test2",
- "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\123"
- },
- {
- "name": "Test3",
- "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\nb"
- }
- ],
- "className": "StringLiterals",
- "qualifiedClassName": "StringLiterals",
+ "className": "IfdefedClass",
+ "qualifiedClassName": "IfdefedClass",
"superClasses": [
{
"access": "public",
@@ -429,7 +35,7 @@
]
}
],
- "inputFile": "escapes-in-string-literals.h",
+ "inputFile": "c-comments.h",
"outputRevision": 67
},
{
@@ -466,475 +72,6 @@
{
"classes": [
{
- "className": "TestQPrivateSlots",
- "methods": [
- {
- "access": "private",
- "name": "method1",
- "returnType": "void"
- }
- ],
- "qualifiedClassName": "TestQPrivateSlots",
- "slots": [
- {
- "access": "private",
- "name": "_q_privateslot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "qprivateslots.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "GadgetWithNoEnums",
- "gadget": true,
- "qualifiedClassName": "GadgetWithNoEnums"
- },
- {
- "className": "DerivedGadgetWithEnums",
- "enums": [
- {
- "isClass": false,
- "isFlag": false,
- "name": "FooEnum",
- "values": [
- "FooValue"
- ]
- }
- ],
- "gadget": true,
- "qualifiedClassName": "DerivedGadgetWithEnums",
- "superClasses": [
- {
- "access": "public",
- "name": "GadgetWithNoEnums"
- }
- ]
- }
- ],
- "inputFile": "gadgetwithnoenums.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "DirInIncludePath",
- "interfaces": [
- [
- {
- "className": "MyInterface",
- "id": "\"MyInterface\""
- }
- ]
- ],
- "qualifiedClassName": "DirInIncludePath",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- },
- {
- "access": "public",
- "name": "MyInterface"
- }
- ]
- }
- ],
- "inputFile": "dir-in-include-path.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "SingleFunctionKeywordBeforeReturnType",
- "qualifiedClassName": "SingleFunctionKeywordBeforeReturnType",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- }
- ],
- "slots": [
- {
- "access": "public",
- "name": "mySlot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "SingleFunctionKeywordBeforeInline",
- "qualifiedClassName": "SingleFunctionKeywordBeforeInline",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- }
- ],
- "slots": [
- {
- "access": "public",
- "name": "mySlot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "SingleFunctionKeywordAfterInline",
- "qualifiedClassName": "SingleFunctionKeywordAfterInline",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- }
- ],
- "slots": [
- {
- "access": "public",
- "name": "mySlot",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "single_function_keyword.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "Task192552",
- "qualifiedClassName": "Task192552",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "task192552.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "InlineSlotsWithThrowDeclaration",
- "qualifiedClassName": "InlineSlotsWithThrowDeclaration",
- "slots": [
- {
- "access": "public",
- "name": "a",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "b",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "c",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "d",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "e",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "task189996.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "TestObject",
- "qualifiedClassName": "NS_A::NS_B::TestObject",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "TestMain",
- "qualifiedClassName": "NS_A::NS_Main::TestMain",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "task234909.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "TypenameWithUnsigned",
- "qualifiedClassName": "TypenameWithUnsigned",
- "slots": [
- {
- "access": "public",
- "arguments": [
- {
- "type": "uint"
- }
- ],
- "name": "a",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "u",
- "type": "uint"
- }
- ],
- "name": "b",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "uint*"
- }
- ],
- "name": "c",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "p",
- "type": "uint*"
- }
- ],
- "name": "d",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "uint&"
- }
- ],
- "name": "e",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "r",
- "type": "uint&"
- }
- ],
- "name": "f",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "unsigned1"
- }
- ],
- "name": "g",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "u1",
- "type": "unsigned1"
- }
- ],
- "name": "h",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "uint"
- },
- {
- "type": "unsigned1"
- }
- ],
- "name": "i",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "unsigned1"
- },
- {
- "type": "uint"
- }
- ],
- "name": "j",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "type": "unsignedQImage"
- }
- ],
- "name": "k",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "uqi",
- "type": "unsignedQImage"
- }
- ],
- "name": "l",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "task240368.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "PureVirtualSignalsTest",
- "qualifiedClassName": "PureVirtualSignalsTest",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- },
- {
- "access": "public",
- "name": "myOtherSignal",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "foo",
- "type": "int"
- }
- ],
- "name": "mySignal2",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "PureVirtualSignalsImpl",
- "qualifiedClassName": "PureVirtualSignalsImpl",
- "signals": [
- {
- "access": "public",
- "name": "mySignal",
- "returnType": "void"
- },
- {
- "access": "public",
- "arguments": [
- {
- "name": "foo",
- "type": "int"
- }
- ],
- "name": "mySignal2",
- "returnType": "void"
- }
- ],
- "superClasses": [
- {
- "access": "public",
- "name": "PureVirtualSignalsTest"
- }
- ]
- }
- ],
- "inputFile": "pure-virtual-signals.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
"className": "CXX11Enums",
"enums": [
{
@@ -1101,102 +238,6 @@
{
"classes": [
{
- "className": "FinalTestClassQt",
- "qualifiedClassName": "FinalTestClassQt",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedFinalTestClassQt",
- "qualifiedClassName": "ExportedFinalTestClassQt",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedFinalTestClassQtX",
- "qualifiedClassName": "ExportedFinalTestClassQtX",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "FinalTestClassCpp11",
- "qualifiedClassName": "FinalTestClassCpp11",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedFinalTestClassCpp11",
- "qualifiedClassName": "ExportedFinalTestClassCpp11",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedFinalTestClassCpp11X",
- "qualifiedClassName": "ExportedFinalTestClassCpp11X",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "SealedTestClass",
- "qualifiedClassName": "SealedTestClass",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedSealedTestClass",
- "qualifiedClassName": "ExportedSealedTestClass",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
- {
- "className": "ExportedSealedTestClassX",
- "qualifiedClassName": "ExportedSealedTestClassX",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- }
- ],
- "inputFile": "cxx11-final-classes.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
"className": "ExplicitOverrideControlBase",
"qualifiedClassName": "ExplicitOverrideControlBase",
"slots": [
@@ -1491,6 +532,196 @@
{
"classes": [
{
+ "className": "FinalTestClassQt",
+ "qualifiedClassName": "FinalTestClassQt",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedFinalTestClassQt",
+ "qualifiedClassName": "ExportedFinalTestClassQt",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedFinalTestClassQtX",
+ "qualifiedClassName": "ExportedFinalTestClassQtX",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "FinalTestClassCpp11",
+ "qualifiedClassName": "FinalTestClassCpp11",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedFinalTestClassCpp11",
+ "qualifiedClassName": "ExportedFinalTestClassCpp11",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedFinalTestClassCpp11X",
+ "qualifiedClassName": "ExportedFinalTestClassCpp11X",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "SealedTestClass",
+ "qualifiedClassName": "SealedTestClass",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedSealedTestClass",
+ "qualifiedClassName": "ExportedSealedTestClass",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "ExportedSealedTestClassX",
+ "qualifiedClassName": "ExportedSealedTestClassX",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "cxx11-final-classes.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "ClassInNamespace",
+ "enums": [
+ {
+ "isClass": false,
+ "isFlag": false,
+ "name": "GadEn",
+ "values": [
+ "Value"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "CXX17Namespace::A::B::C::D::ClassInNamespace"
+ },
+ {
+ "className": "D",
+ "enums": [
+ {
+ "isClass": false,
+ "isFlag": false,
+ "name": "NamEn",
+ "values": [
+ "Value"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "CXX17Namespace::A::B::C::D"
+ }
+ ],
+ "inputFile": "cxx17-namespaces.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "DirInIncludePath",
+ "interfaces": [
+ [
+ {
+ "className": "MyInterface",
+ "id": "\"MyInterface\""
+ }
+ ]
+ ],
+ "qualifiedClassName": "DirInIncludePath",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ },
+ {
+ "access": "public",
+ "name": "MyInterface"
+ }
+ ]
+ }
+ ],
+ "inputFile": "dir-in-include-path.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "classInfos": [
+ {
+ "name": "Test",
+ "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\x53"
+ },
+ {
+ "name": "Test2",
+ "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\123"
+ },
+ {
+ "name": "Test3",
+ "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\nb"
+ }
+ ],
+ "className": "StringLiterals",
+ "qualifiedClassName": "StringLiterals",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "escapes-in-string-literals.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
"className": "ForwardDeclaredParamClass",
"qualifiedClassName": "ForwardDeclaredParamClass",
"signals": [
@@ -1691,6 +922,345 @@
{
"classes": [
{
+ "className": "FunctionWithAttributes",
+ "qualifiedClassName": "FunctionWithAttributes",
+ "slots": [
+ {
+ "access": "public",
+ "name": "test1",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "test2",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "function-with-attributes.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "GadgetWithNoEnums",
+ "gadget": true,
+ "qualifiedClassName": "GadgetWithNoEnums"
+ },
+ {
+ "className": "DerivedGadgetWithEnums",
+ "enums": [
+ {
+ "isClass": false,
+ "isFlag": false,
+ "name": "FooEnum",
+ "values": [
+ "FooValue"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "DerivedGadgetWithEnums",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "GadgetWithNoEnums"
+ }
+ ]
+ }
+ ],
+ "inputFile": "gadgetwithnoenums.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "BaseGadget",
+ "gadget": true,
+ "qualifiedClassName": "GrandParentGadget::BaseGadget"
+ },
+ {
+ "className": "DerivedGadget",
+ "gadget": true,
+ "qualifiedClassName": "GrandParentGadget::DerivedGadget",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "Derived"
+ }
+ ]
+ },
+ {
+ "className": "CRTPDerivedGadget",
+ "gadget": true,
+ "qualifiedClassName": "GrandParentGadget::CRTPDerivedGadget",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "CRTP<CRTPDerivedGadget>"
+ }
+ ]
+ }
+ ],
+ "inputFile": "grand-parent-gadget-class.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "FooNamespace",
+ "enums": [
+ {
+ "isClass": true,
+ "isFlag": false,
+ "name": "Enum1",
+ "values": [
+ "Key1",
+ "Key2"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "FooNamespace"
+ },
+ {
+ "className": "FooNestedNamespace",
+ "enums": [
+ {
+ "isClass": true,
+ "isFlag": false,
+ "name": "Enum2",
+ "values": [
+ "Key3",
+ "Key4"
+ ]
+ },
+ {
+ "isClass": true,
+ "isFlag": false,
+ "name": "Enum3",
+ "values": [
+ "Key5",
+ "Key6"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "FooNamespace::FooNestedNamespace"
+ },
+ {
+ "className": "FooMoreNestedNamespace",
+ "enums": [
+ {
+ "isClass": true,
+ "isFlag": false,
+ "name": "Enum4",
+ "values": [
+ "Key7",
+ "Key8"
+ ]
+ }
+ ],
+ "gadget": true,
+ "qualifiedClassName": "FooNamespace::FooNestedNamespace::FooMoreNestedNamespace"
+ }
+ ],
+ "inputFile": "namespace.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "Bar",
+ "enums": [
+ {
+ "alias": "Flag",
+ "isClass": false,
+ "isFlag": true,
+ "name": "Flags",
+ "values": [
+ "Read",
+ "Write"
+ ]
+ }
+ ],
+ "properties": [
+ {
+ "constant": false,
+ "designable": true,
+ "final": false,
+ "name": "flags",
+ "read": "flags",
+ "scriptable": true,
+ "stored": true,
+ "type": "Flags",
+ "user": false,
+ "write": "setFlags"
+ }
+ ],
+ "qualifiedClassName": "Foo::Bar",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "Baz",
+ "properties": [
+ {
+ "constant": false,
+ "designable": true,
+ "final": false,
+ "name": "flags",
+ "read": "flags",
+ "scriptable": true,
+ "stored": true,
+ "type": "Foo::Bar::Flags",
+ "user": false,
+ "write": "setFlags"
+ },
+ {
+ "constant": false,
+ "designable": true,
+ "final": false,
+ "name": "flagsList",
+ "read": "flagsList",
+ "scriptable": true,
+ "stored": true,
+ "type": "QVector<Foo::Bar::Flags>",
+ "user": false,
+ "write": "setFlagsList"
+ }
+ ],
+ "qualifiedClassName": "Foo::Baz",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "namespaced-flags.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "MyBooooooostishClass",
+ "qualifiedClassName": "MyBooooooostishClass",
+ "signals": [
+ {
+ "access": "public",
+ "name": "mySignal",
+ "returnType": "void"
+ }
+ ],
+ "slots": [
+ {
+ "access": "public",
+ "name": "mySlot",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "no-keywords.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "Derived",
+ "gadget": true,
+ "qualifiedClassName": "NonGadgetParent::Derived",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "Base"
+ }
+ ]
+ }
+ ],
+ "inputFile": "non-gadget-parent-class.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "OldStyleCast",
+ "qualifiedClassName": "OldStyleCast",
+ "slots": [
+ {
+ "access": "public",
+ "name": "foo",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "int"
+ },
+ {
+ "type": "int*"
+ },
+ {
+ "type": "const int*"
+ },
+ {
+ "type": "volatile int*"
+ },
+ {
+ "type": "const int*volatile*"
+ }
+ ],
+ "name": "bar",
+ "returnType": "int"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "int"
+ },
+ {
+ "type": "QObject*const"
+ }
+ ],
+ "name": "slot",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "oldstyle-casts.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
"classInfos": [
{
"name": "TestString",
@@ -1890,17 +1460,44 @@
{
"classes": [
{
- "className": "FunctionWithAttributes",
- "qualifiedClassName": "FunctionWithAttributes",
- "slots": [
+ "className": "TestPluginMetaData",
+ "qualifiedClassName": "TestPluginMetaData",
+ "superClasses": [
{
"access": "public",
- "name": "test1",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "plugin_metadata.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "PureVirtualSignalsTest",
+ "qualifiedClassName": "PureVirtualSignalsTest",
+ "signals": [
+ {
+ "access": "public",
+ "name": "mySignal",
"returnType": "void"
},
{
"access": "public",
- "name": "test2",
+ "name": "myOtherSignal",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "foo",
+ "type": "int"
+ }
+ ],
+ "name": "mySignal2",
"returnType": "void"
}
],
@@ -1910,16 +1507,73 @@
"name": "QObject"
}
]
+ },
+ {
+ "className": "PureVirtualSignalsImpl",
+ "qualifiedClassName": "PureVirtualSignalsImpl",
+ "signals": [
+ {
+ "access": "public",
+ "name": "mySignal",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "foo",
+ "type": "int"
+ }
+ ],
+ "name": "mySignal2",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "PureVirtualSignalsTest"
+ }
+ ]
}
],
- "inputFile": "function-with-attributes.h",
+ "inputFile": "pure-virtual-signals.h",
"outputRevision": 67
},
{
"classes": [
{
- "className": "TestPluginMetaData",
- "qualifiedClassName": "TestPluginMetaData",
+ "className": "InvokableBeforeReturnType",
+ "methods": [
+ {
+ "access": "public",
+ "name": "foo",
+ "returnType": "const char*"
+ }
+ ],
+ "qualifiedClassName": "InvokableBeforeReturnType",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ },
+ {
+ "className": "InvokableBeforeInline",
+ "methods": [
+ {
+ "access": "public",
+ "name": "foo",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "bar",
+ "returnType": "void"
+ }
+ ],
+ "qualifiedClassName": "InvokableBeforeInline",
"superClasses": [
{
"access": "public",
@@ -1928,24 +1582,28 @@
]
}
],
- "inputFile": "plugin_metadata.h",
+ "inputFile": "qinvokable.h",
"outputRevision": 67
},
{
"classes": [
{
- "className": "KDAB",
- "enums": [
+ "className": "TestQPrivateSlots",
+ "methods": [
{
- "isClass": false,
- "isFlag": false,
- "name": "Salaries",
- "values": [
- "Steve"
- ]
+ "access": "private",
+ "name": "method1",
+ "returnType": "void"
+ }
+ ],
+ "qualifiedClassName": "TestQPrivateSlots",
+ "slots": [
+ {
+ "access": "private",
+ "name": "_q_privateslot",
+ "returnType": "void"
}
],
- "qualifiedClassName": "KDAB",
"superClasses": [
{
"access": "public",
@@ -1954,7 +1612,7 @@
]
}
],
- "inputFile": "single-quote-digit-separator-n3781.h",
+ "inputFile": "qprivateslots.h",
"outputRevision": 67
},
{
@@ -1971,14 +1629,15 @@
]
}
],
- "qualifiedClassName": "QTBUG_2151::A",
- "superClasses": [
- {
- "access": "public",
- "name": "QObject"
- }
- ]
- },
+ "gadget": true,
+ "qualifiedClassName": "QTBUG_35657::A"
+ }
+ ],
+ "inputFile": "qtbug-35657-gadget.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
{
"className": "B",
"properties": [
@@ -1994,7 +1653,7 @@
"user": false
}
],
- "qualifiedClassName": "QTBUG_2151::B",
+ "qualifiedClassName": "QTBUG_35657::B",
"superClasses": [
{
"access": "public",
@@ -2003,7 +1662,7 @@
]
}
],
- "inputFile": "related-metaobjects-in-namespaces.h",
+ "inputFile": "related-metaobjects-in-gadget.h",
"outputRevision": 67
},
{
@@ -2020,66 +1679,15 @@
]
}
],
- "gadget": true,
- "qualifiedClassName": "QTBUG_35657::A"
- }
- ],
- "inputFile": "qtbug-35657-gadget.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "Derived",
- "gadget": true,
- "qualifiedClassName": "NonGadgetParent::Derived",
- "superClasses": [
- {
- "access": "public",
- "name": "Base"
- }
- ]
- }
- ],
- "inputFile": "non-gadget-parent-class.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
- "className": "BaseGadget",
- "gadget": true,
- "qualifiedClassName": "GrandParentGadget::BaseGadget"
- },
- {
- "className": "DerivedGadget",
- "gadget": true,
- "qualifiedClassName": "GrandParentGadget::DerivedGadget",
+ "qualifiedClassName": "QTBUG_2151::A",
"superClasses": [
{
"access": "public",
- "name": "Derived"
+ "name": "QObject"
}
]
},
{
- "className": "CRTPDerivedGadget",
- "gadget": true,
- "qualifiedClassName": "GrandParentGadget::CRTPDerivedGadget",
- "superClasses": [
- {
- "access": "public",
- "name": "CRTP<CRTPDerivedGadget>"
- }
- ]
- }
- ],
- "inputFile": "grand-parent-gadget-class.h",
- "outputRevision": 67
- },
- {
- "classes": [
- {
"className": "B",
"properties": [
{
@@ -2094,7 +1702,7 @@
"user": false
}
],
- "qualifiedClassName": "QTBUG_35657::B",
+ "qualifiedClassName": "QTBUG_2151::B",
"superClasses": [
{
"access": "public",
@@ -2103,7 +1711,7 @@
]
}
],
- "inputFile": "related-metaobjects-in-gadget.h",
+ "inputFile": "related-metaobjects-in-namespaces.h",
"outputRevision": 67
},
{
@@ -2520,100 +2128,449 @@
{
"classes": [
{
- "className": "FooNamespace",
+ "className": "KDAB",
"enums": [
{
- "isClass": true,
+ "isClass": false,
"isFlag": false,
- "name": "Enum1",
+ "name": "Salaries",
"values": [
- "Key1",
- "Key2"
+ "Steve"
]
}
],
- "gadget": true,
- "qualifiedClassName": "FooNamespace"
+ "qualifiedClassName": "KDAB",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "single-quote-digit-separator-n3781.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "SingleFunctionKeywordBeforeReturnType",
+ "qualifiedClassName": "SingleFunctionKeywordBeforeReturnType",
+ "signals": [
+ {
+ "access": "public",
+ "name": "mySignal",
+ "returnType": "void"
+ }
+ ],
+ "slots": [
+ {
+ "access": "public",
+ "name": "mySlot",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
},
{
- "className": "FooNestedNamespace",
- "enums": [
+ "className": "SingleFunctionKeywordBeforeInline",
+ "qualifiedClassName": "SingleFunctionKeywordBeforeInline",
+ "signals": [
{
- "isClass": true,
- "isFlag": false,
- "name": "Enum2",
- "values": [
- "Key3",
- "Key4"
- ]
- },
+ "access": "public",
+ "name": "mySignal",
+ "returnType": "void"
+ }
+ ],
+ "slots": [
{
- "isClass": true,
- "isFlag": false,
- "name": "Enum3",
- "values": [
- "Key5",
- "Key6"
- ]
+ "access": "public",
+ "name": "mySlot",
+ "returnType": "void"
}
],
- "gadget": true,
- "qualifiedClassName": "FooNamespace::FooNestedNamespace"
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
},
{
- "className": "FooMoreNestedNamespace",
- "enums": [
+ "className": "SingleFunctionKeywordAfterInline",
+ "qualifiedClassName": "SingleFunctionKeywordAfterInline",
+ "signals": [
{
- "isClass": true,
- "isFlag": false,
- "name": "Enum4",
- "values": [
- "Key7",
- "Key8"
- ]
+ "access": "public",
+ "name": "mySignal",
+ "returnType": "void"
}
],
- "gadget": true,
- "qualifiedClassName": "FooNamespace::FooNestedNamespace::FooMoreNestedNamespace"
+ "slots": [
+ {
+ "access": "public",
+ "name": "mySlot",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
}
],
- "inputFile": "namespace.h",
+ "inputFile": "single_function_keyword.h",
"outputRevision": 67
},
{
"classes": [
{
- "className": "ClassInNamespace",
- "enums": [
+ "className": "SlotsWithVoidTemplateTest",
+ "qualifiedClassName": "SlotsWithVoidTemplateTest",
+ "signals": [
{
- "isClass": false,
- "isFlag": false,
- "name": "GadEn",
- "values": [
- "Value"
- ]
+ "access": "public",
+ "arguments": [
+ {
+ "type": "TestTemplate<void>"
+ }
+ ],
+ "name": "mySignal",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "myVoidSignal",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "myVoidSignal2",
+ "returnType": "void"
}
],
- "gadget": true,
- "qualifiedClassName": "CXX17Namespace::A::B::C::D::ClassInNamespace"
+ "slots": [
+ {
+ "access": "public",
+ "name": "dummySlot",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "dummySlot2",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "TestTemplate<void>"
+ }
+ ],
+ "name": "anotherSlot",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "name": "mySlot",
+ "returnType": "TestTemplate<void>"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "slots-with-void-template.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "Task192552",
+ "qualifiedClassName": "Task192552",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "task192552.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "TestObject",
+ "qualifiedClassName": "NS_A::NS_B::TestObject",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
},
{
- "className": "D",
- "enums": [
+ "className": "TestMain",
+ "qualifiedClassName": "NS_A::NS_Main::TestMain",
+ "superClasses": [
{
- "isClass": false,
- "isFlag": false,
- "name": "NamEn",
- "values": [
- "Value"
- ]
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "task234909.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "TypenameWithUnsigned",
+ "qualifiedClassName": "TypenameWithUnsigned",
+ "slots": [
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "uint"
+ }
+ ],
+ "name": "a",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "u",
+ "type": "uint"
+ }
+ ],
+ "name": "b",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "uint*"
+ }
+ ],
+ "name": "c",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "p",
+ "type": "uint*"
+ }
+ ],
+ "name": "d",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "uint&"
+ }
+ ],
+ "name": "e",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "r",
+ "type": "uint&"
+ }
+ ],
+ "name": "f",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "unsigned1"
+ }
+ ],
+ "name": "g",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "u1",
+ "type": "unsigned1"
+ }
+ ],
+ "name": "h",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "uint"
+ },
+ {
+ "type": "unsigned1"
+ }
+ ],
+ "name": "i",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "unsigned1"
+ },
+ {
+ "type": "uint"
+ }
+ ],
+ "name": "j",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "unsignedQImage"
+ }
+ ],
+ "name": "k",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "name": "uqi",
+ "type": "unsignedQImage"
+ }
+ ],
+ "name": "l",
+ "returnType": "void"
}
],
- "gadget": true,
- "qualifiedClassName": "CXX17Namespace::A::B::C::D"
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
}
],
- "inputFile": "cxx17-namespaces.h",
+ "inputFile": "task240368.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "Task87883",
+ "qualifiedClassName": "Task87883",
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ }
+ ]
+ }
+ ],
+ "inputFile": "task87883.h",
+ "outputRevision": 67
+ },
+ {
+ "classes": [
+ {
+ "className": "Foo",
+ "qualifiedClassName": "BBB::Foo",
+ "signals": [
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "QVector<QVector<int> >"
+ }
+ ],
+ "name": "foo",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "QVector<QVector<int> >"
+ }
+ ],
+ "name": "foo2",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "QVector< ::AAA::BaseA*>"
+ }
+ ],
+ "name": "bar",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "QVector< ::AAA::BaseA*>"
+ }
+ ],
+ "name": "bar2",
+ "returnType": "void"
+ },
+ {
+ "access": "public",
+ "arguments": [
+ {
+ "type": "QVector<const ::AAA::BaseA*>"
+ }
+ ],
+ "name": "bar3",
+ "returnType": "void"
+ }
+ ],
+ "superClasses": [
+ {
+ "access": "public",
+ "name": "QObject"
+ },
+ {
+ "access": "public",
+ "name": "::AAA::BaseA"
+ }
+ ]
+ }
+ ],
+ "inputFile": "trigraphs.h",
"outputRevision": 67
}
]
diff --git a/tests/auto/tools/moc/moc.pro b/tests/auto/tools/moc/moc.pro
index 1794bafd2c..93ca330126 100644
--- a/tests/auto/tools/moc/moc.pro
+++ b/tests/auto/tools/moc/moc.pro
@@ -15,7 +15,7 @@ cross_compile: DEFINES += MOC_CROSS_COMPILED
HEADERS += using-namespaces.h no-keywords.h task87883.h c-comments.h backslash-newlines.h oldstyle-casts.h \
slots-with-void-template.h qinvokable.h namespaced-flags.h trigraphs.h \
escapes-in-string-literals.h cstyle-enums.h qprivateslots.h gadgetwithnoenums.h \
- dir-in-include-path.h single_function_keyword.h task192552.h task189996.h \
+ dir-in-include-path.h single_function_keyword.h task192552.h \
task234909.h task240368.h pure-virtual-signals.h cxx11-enums.h \
cxx11-final-classes.h \
cxx11-explicit-override-control.h \
diff --git a/tests/auto/tools/moc/task189996.h b/tests/auto/tools/moc/task189996.h
deleted file mode 100644
index f94a051b3a..0000000000
--- a/tests/auto/tools/moc/task189996.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-// inline functions can have throw declarations
-
-#ifndef TASK189996_H
-#define TASK189996_H
-
-#include <QObject>
-
-class InlineSlotsWithThrowDeclaration : public QObject
-{
- Q_OBJECT
-
-public slots:
- void a() throw() { }
- void b() const throw() { }
- void c() throw();
- void d() throw(int) { }
- void e() const throw(int,double) { }
-};
-
-#endif
diff --git a/tests/auto/tools/moc/tst_moc.cpp b/tests/auto/tools/moc/tst_moc.cpp
index 6b202f79a6..e5de647930 100644
--- a/tests/auto/tools/moc/tst_moc.cpp
+++ b/tests/auto/tools/moc/tst_moc.cpp
@@ -630,7 +630,6 @@ public:
private slots:
void initTestCase();
- void slotWithException() throw(MyStruct);
void dontStripNamespaces();
void oldStyleCasts();
void warnOnExtraSignalSlotQualifiaction();
@@ -672,7 +671,6 @@ private slots:
void templateGtGt();
void qprivateslots();
void qprivateproperties();
- void inlineSlotsWithThrowDeclaration();
void warnOnPropertyWithoutREAD();
void constructors();
void typenameWithUnsigned();
@@ -781,12 +779,6 @@ void tst_Moc::initTestCase()
#endif
}
-void tst_Moc::slotWithException() throw(MyStruct)
-{
- // be happy
- QVERIFY(true);
-}
-
void tst_Moc::dontStripNamespaces()
{
Sender sender;
@@ -821,7 +813,7 @@ void tst_Moc::oldStyleCasts()
QStringList args;
args << "-c" << "-x" << "c++" << "-Wold-style-cast" << "-I" << "."
- << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++11" << "-";
+ << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++1z" << "-";
proc.start("gcc", args);
QVERIFY(proc.waitForStarted());
proc.write(mocOut);
@@ -891,7 +883,7 @@ void tst_Moc::inputFileNameWithDotsButNoExtension()
QStringList args;
args << "-c" << "-x" << "c++" << "-I" << ".."
- << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++11" << "-";
+ << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++1z" << "-";
proc.start("gcc", args);
QVERIFY(proc.waitForStarted());
proc.write(mocOut);
@@ -1171,7 +1163,7 @@ void tst_Moc::ignoreOptionClashes()
QStringList gccArgs;
gccArgs << "-c" << "-x" << "c++" << "-I" << ".."
<< "-I" << qtIncludePath << "-I" << includeDir << "-o" << "/dev/null"
- << "-fPIC" << "-std=c++11" << "-";
+ << "-fPIC" << "-std=c++1z" << "-";
proc.start("gcc", gccArgs);
QVERIFY(proc.waitForStarted());
proc.write(mocOut);
@@ -1590,21 +1582,6 @@ void tst_Moc::qprivateproperties()
}
-#include "task189996.h"
-
-void InlineSlotsWithThrowDeclaration::c() throw() {}
-
-void tst_Moc::inlineSlotsWithThrowDeclaration()
-{
- InlineSlotsWithThrowDeclaration tst;
- const QMetaObject *mobj = tst.metaObject();
- QVERIFY(mobj->indexOfSlot("a()") != -1);
- QVERIFY(mobj->indexOfSlot("b()") != -1);
- QVERIFY(mobj->indexOfSlot("c()") != -1);
- QVERIFY(mobj->indexOfSlot("d()") != -1);
- QVERIFY(mobj->indexOfSlot("e()") != -1);
-}
-
void tst_Moc::warnOnPropertyWithoutREAD()
{
#ifdef MOC_CROSS_COMPILED
@@ -1866,7 +1843,7 @@ void tst_Moc::notifyError()
QStringList args;
args << "-c" << "-x" << "c++" << "-I" << "."
- << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++11" << "-";
+ << "-I" << qtIncludePath << "-o" << "/dev/null" << "-fPIC" << "-std=c++1z" << "-";
proc.start("gcc", args);
QVERIFY(proc.waitForStarted());
proc.write(mocOut);
diff --git a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
index 9ae4508bc1..dae274a8b6 100644
--- a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
+++ b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp
@@ -96,8 +96,9 @@ private slots:
void task248107_backButton();
void task255350_fieldObjectDestroyed();
void taskQTBUG_25691_fieldObjectDestroyed2();
+#if QT_CONFIG(shortcut)
void taskQTBUG_46894_nextButtonShortcut();
-
+#endif
/*
Things that could be added:
@@ -2703,6 +2704,8 @@ void tst_QWizard::taskQTBUG_25691_fieldObjectDestroyed2()
::taskQTBUG_25691_fieldObjectDestroyed2();
}
+#if QT_CONFIG(shortcut)
+
void tst_QWizard::taskQTBUG_46894_nextButtonShortcut()
{
for (int i = 0; i < QWizard::NStyles; ++i) {
@@ -2717,5 +2720,7 @@ void tst_QWizard::taskQTBUG_46894_nextButtonShortcut()
}
}
+#endif // QT_CONFIG(shortcut)
+
QTEST_MAIN(tst_QWizard)
#include "tst_qwizard.moc"
diff --git a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
index 262e1772a0..0010718d3e 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp
@@ -450,7 +450,9 @@ private slots:
void modality_keyEvents();
void itemIsInFront();
void scenePosChange();
+#if QT_CONFIG(shortcut)
void textItem_shortcuts();
+#endif
void scroll();
void focusHandling_data();
void focusHandling();
@@ -10801,6 +10803,8 @@ void tst_QGraphicsItem::scenePosChange()
QCOMPARE(child2->changes.count(QGraphicsItem::ItemScenePositionHasChanged), 0);
}
+#if QT_CONFIG(shortcut)
+
void tst_QGraphicsItem::textItem_shortcuts()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::WindowActivation))
@@ -10840,6 +10844,8 @@ void tst_QGraphicsItem::textItem_shortcuts()
QTRY_COMPARE(item->textCursor().selectedText(), item->toPlainText());
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QGraphicsItem::scroll()
{
// Create two overlapping rectangles in the scene:
diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/qgraphicsview.pro b/tests/auto/widgets/graphicsview/qgraphicsview/qgraphicsview.pro
index 8ed19697a4..e95cdcf7d8 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsview/qgraphicsview.pro
+++ b/tests/auto/widgets/graphicsview/qgraphicsview/qgraphicsview.pro
@@ -4,6 +4,7 @@ TARGET = tst_qgraphicsview
QT += widgets widgets-private testlib
QT += core-private gui-private testlib-private
+qtConfig(opengl): QT += opengl
SOURCES += tst_qgraphicsview.cpp tst_qgraphicsview_2.cpp
HEADERS += tst_qgraphicsview.h
diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
index ea89e2422b..d521c6f11c 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
@@ -48,8 +48,8 @@
#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QStyle>
#include <QtWidgets/QPushButton>
-#ifndef QT_NO_OPENGL
-#include <QtWidgets/QOpenGLWidget>
+#if QT_CONFIG(opengl)
+#include <QtOpenGL/QOpenGLWidget>
#endif
#include <private/qgraphicsscene_p.h>
#include <private/qgraphicsview_p.h>
@@ -154,7 +154,7 @@ private slots:
void sceneRect_growing();
void setSceneRect();
void viewport();
-#ifndef QT_NO_OPENGL
+#if QT_CONFIG(opengl)
void openGLViewport();
#endif
void dragMode_scrollHand();
@@ -659,7 +659,7 @@ void tst_QGraphicsView::viewport()
QVERIFY(QTest::qWaitForWindowExposed(&view));
}
-#ifndef QT_NO_OPENGL
+#if QT_CONFIG(opengl)
void tst_QGraphicsView::openGLViewport()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL))
diff --git a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
index d5813d64ff..bb098f32c2 100644
--- a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
+++ b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
@@ -1744,7 +1744,7 @@ void tst_QHeaderView::restoreQt4State()
QCOMPARE(h2.length(), old_length);
QCOMPARE(h2.saveState(), old_state);
#else
- QSKIP("Qt4 compatibility no longer needed in Qt6")
+ QSKIP("Qt4 compatibility no longer needed in Qt6");
#endif
}
diff --git a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
index ea3eb5fd0c..544069243f 100644
--- a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
+++ b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp
@@ -331,8 +331,10 @@ private slots:
void selectColumn_data();
void selectColumn();
+#if QT_CONFIG(shortcut)
void selectall_data();
void selectall();
+#endif
void visualRect_data();
void visualRect();
@@ -1843,6 +1845,8 @@ void tst_QTableView::selectColumn()
QCOMPARE(view.selectionModel()->selectedIndexes().at(i).column(), column);
}
+#if QT_CONFIG(shortcut)
+
void tst_QTableView::selectall_data()
{
QTest::addColumn<int>("rowCount");
@@ -1999,6 +2003,8 @@ void tst_QTableView::selectall()
QCOMPARE(view.selectedIndexes().count(), 0);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QTableView::visualRect_data()
{
QTest::addColumn<int>("rowCount");
diff --git a/tests/auto/widgets/kernel/kernel.pro b/tests/auto/widgets/kernel/kernel.pro
index af85a2bd13..9d0bf58b03 100644
--- a/tests/auto/widgets/kernel/kernel.pro
+++ b/tests/auto/widgets/kernel/kernel.pro
@@ -1,7 +1,5 @@
TEMPLATE=subdirs
SUBDIRS=\
- qaction \
- qactiongroup \
qapplication \
qboxlayout \
qdesktopwidget \
@@ -13,7 +11,6 @@ SUBDIRS=\
qtooltip \
qwidget \
qwidget_window \
- qwidgetaction \
qwidgetmetatype \
qwidgetsvariant \
qwindowcontainer \
@@ -22,3 +19,11 @@ SUBDIRS=\
darwin:SUBDIRS -= \ # Uses native recognizers
qgesturerecognizer \
+
+!qtConfig(action):SUBDIRS -= \
+ qaction \
+ qactiongroup \
+ qwidgetaction
+
+!qtConfig(shortcut): SUBDIRS -= \
+ qshortcut
diff --git a/tests/auto/widgets/kernel/qaction/tst_qaction.cpp b/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
index 1247f48dd0..cf8539da68 100644
--- a/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
+++ b/tests/auto/widgets/kernel/qaction/tst_qaction.cpp
@@ -50,30 +50,25 @@ public:
private slots:
void init();
void cleanup();
- void getSetCheck();
- void setText_data();
- void setText();
- void setIconText_data() { setText_data(); }
- void setIconText();
void setUnknownFont();
void actionEvent();
- void setStandardKeys();
+#if QT_CONFIG(shortcut)
void alternateShortcuts();
void enabledVisibleInteraction();
- void task200823_tooltip();
- void task229128TriggeredSignalWithoutActiongroup();
+#endif
void task229128TriggeredSignalWhenInActiongroup();
+#if QT_CONFIG(shortcut)
void repeat();
- void setData();
void keysequence(); // QTBUG-53381
void disableShortcutsWithBlockedWidgets_data();
void disableShortcutsWithBlockedWidgets();
void shortcutFromKeyEvent(); // QTBUG-48325
+#endif
private:
QEvent::Type m_lastEventType;
const int m_keyboardScheme;
- QAction *m_lastAction;
+ QGuiAction *m_lastAction;
};
tst_QAction::tst_QAction()
@@ -92,33 +87,6 @@ void tst_QAction::cleanup()
QVERIFY(QApplication::topLevelWidgets().isEmpty());
}
-// Testing get/set functions
-void tst_QAction::getSetCheck()
-{
- QAction obj1(nullptr);
- // QActionGroup * QAction::actionGroup()
- // void QAction::setActionGroup(QActionGroup *)
- QActionGroup *var1 = new QActionGroup(nullptr);
- obj1.setActionGroup(var1);
- QCOMPARE(var1, obj1.actionGroup());
- obj1.setActionGroup(nullptr);
- QCOMPARE(obj1.actionGroup(), nullptr);
- delete var1;
-
- // QMenu * QAction::menu()
- // void QAction::setMenu(QMenu *)
- QMenu *var2 = new QMenu(nullptr);
- obj1.setMenu(var2);
- QCOMPARE(var2, obj1.menu());
- obj1.setMenu(nullptr);
- QCOMPARE(obj1.menu(), nullptr);
- delete var2;
-
- QCOMPARE(obj1.priority(), QAction::NormalPriority);
- obj1.setPriority(QAction::LowPriority);
- QCOMPARE(obj1.priority(), QAction::LowPriority);
-}
-
class MyWidget : public QWidget
{
Q_OBJECT
@@ -133,43 +101,6 @@ private:
tst_QAction *m_test;
};
-void tst_QAction::setText_data()
-{
- QTest::addColumn<QString>("text");
- QTest::addColumn<QString>("iconText");
- QTest::addColumn<QString>("textFromIconText");
-
- //next we fill it with data
- QTest::newRow("Normal") << "Action" << "Action" << "Action";
- QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
- QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
-}
-
-void tst_QAction::setText()
-{
- QFETCH(QString, text);
-
- QAction action(nullptr);
- action.setText(text);
-
- QCOMPARE(action.text(), text);
-
- QFETCH(QString, iconText);
- QCOMPARE(action.iconText(), iconText);
-}
-
-void tst_QAction::setIconText()
-{
- QFETCH(QString, iconText);
-
- QAction action(nullptr);
- action.setIconText(iconText);
- QCOMPARE(action.iconText(), iconText);
-
- QFETCH(QString, textFromIconText);
- QCOMPARE(action.text(), textFromIconText);
-}
-
void tst_QAction::setUnknownFont() // QTBUG-42728
{
QAction action(nullptr);
@@ -221,34 +152,7 @@ void tst_QAction::actionEvent()
QCOMPARE(m_lastAction, &a);
}
-//basic testing of standard keys
-void tst_QAction::setStandardKeys()
-{
- QAction act(nullptr);
- act.setShortcut(QKeySequence("CTRL+L"));
- QList<QKeySequence> list;
- act.setShortcuts(list);
- act.setShortcuts(QKeySequence::Copy);
- QCOMPARE(act.shortcut(), act.shortcuts().constFirst());
-
- QList<QKeySequence> expected;
- const QKeySequence ctrlC = QKeySequence(QStringLiteral("CTRL+C"));
- const QKeySequence ctrlInsert = QKeySequence(QStringLiteral("CTRL+INSERT"));
- switch (m_keyboardScheme) {
- case QPlatformTheme::MacKeyboardScheme:
- expected << ctrlC;
- break;
- case QPlatformTheme::WindowsKeyboardScheme:
- expected << ctrlC << ctrlInsert;
- break;
- default: // X11
- expected << ctrlC << ctrlInsert << QKeySequence(QStringLiteral("F16"));
- break;
- }
-
- QCOMPARE(act.shortcuts(), expected);
-}
-
+#if QT_CONFIG(shortcut)
void tst_QAction::alternateShortcuts()
{
@@ -354,38 +258,7 @@ void tst_QAction::enabledVisibleInteraction()
QCOMPARE(spy.count(), 1); //act is visible and enabled, so trigger
}
-void tst_QAction::task200823_tooltip()
-{
- const QScopedPointer<QAction> action(new QAction("foo", nullptr));
- QString shortcut("ctrl+o");
- action->setShortcut(shortcut);
-
- // we want a non-standard tooltip that shows the shortcut
- action->setToolTip(action->text() + QLatin1String(" (") + action->shortcut().toString() + QLatin1Char(')'));
-
- QString ref = QLatin1String("foo (") + QKeySequence(shortcut).toString() + QLatin1Char(')');
- QCOMPARE(action->toolTip(), ref);
-}
-
-void tst_QAction::task229128TriggeredSignalWithoutActiongroup()
-{
- // test without a group
- const QScopedPointer<QAction> actionWithoutGroup(new QAction("Test", nullptr));
- QSignalSpy spyWithoutGroup(actionWithoutGroup.data(), QOverload<bool>::of(&QAction::triggered));
- QCOMPARE(spyWithoutGroup.count(), 0);
- actionWithoutGroup->trigger();
- // signal should be emitted
- QCOMPARE(spyWithoutGroup.count(), 1);
-
- // it is now a checkable checked action
- actionWithoutGroup->setCheckable(true);
- actionWithoutGroup->setChecked(true);
- spyWithoutGroup.clear();
- QCOMPARE(spyWithoutGroup.count(), 0);
- actionWithoutGroup->trigger();
- // signal should be emitted
- QCOMPARE(spyWithoutGroup.count(), 1);
-}
+#endif // QT_CONFIG(shortcut)
void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
{
@@ -408,6 +281,8 @@ void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
QCOMPARE(actionSpy.count(), 1);
}
+#if QT_CONFIG(shortcut)
+
void tst_QAction::repeat()
{
if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive))
@@ -452,21 +327,6 @@ void tst_QAction::repeat()
QCOMPARE(spy.count(), 2);
}
-void tst_QAction::setData() // QTBUG-62006
-{
- QAction act(nullptr);
- QSignalSpy spy(&act, &QAction::changed);
- QCOMPARE(act.data(), QVariant());
- QCOMPARE(spy.count(), 0);
- act.setData(QVariant());
- QCOMPARE(spy.count(), 0);
-
- act.setData(-1);
- QCOMPARE(spy.count(), 1);
- act.setData(-1);
- QCOMPARE(spy.count(), 1);
-}
-
void tst_QAction::disableShortcutsWithBlockedWidgets_data()
{
QTest::addColumn<Qt::ShortcutContext>("shortcutContext");
@@ -556,5 +416,7 @@ void tst_QAction::shortcutFromKeyEvent()
QCOMPARE(testWidget.shortcutOverrideCount, 1);
}
+#endif // QT_CONFIG(shortcut)
+
QTEST_MAIN(tst_QAction)
#include "tst_qaction.moc"
diff --git a/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp b/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
index 524040d003..d3b07ba26a 100644
--- a/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
+++ b/tests/auto/widgets/kernel/qactiongroup/tst_qactiongroup.cpp
@@ -38,166 +38,9 @@ class tst_QActionGroup : public QObject
private slots:
void cleanup() { QVERIFY(QApplication::topLevelWidgets().isEmpty()); }
- void enabledPropagation();
- void visiblePropagation();
- void exclusive();
- void exclusiveOptional();
void separators();
- void testActionInTwoQActionGroup();
- void unCheckCurrentAction();
};
-void tst_QActionGroup::enabledPropagation()
-{
- QActionGroup testActionGroup(nullptr);
-
- QAction* childAction = new QAction( &testActionGroup );
- QAction* anotherChildAction = new QAction( &testActionGroup );
- QAction* freeAction = new QAction(nullptr);
-
- QVERIFY( testActionGroup.isEnabled() );
- QVERIFY( childAction->isEnabled() );
-
- testActionGroup.setEnabled( false );
- QVERIFY( !testActionGroup.isEnabled() );
- QVERIFY( !childAction->isEnabled() );
- QVERIFY( !anotherChildAction->isEnabled() );
-
- childAction->setEnabled(true);
- QVERIFY( !childAction->isEnabled());
-
- anotherChildAction->setEnabled( false );
-
- testActionGroup.setEnabled( true );
- QVERIFY( testActionGroup.isEnabled() );
- QVERIFY( childAction->isEnabled() );
- QVERIFY( !anotherChildAction->isEnabled() );
-
- testActionGroup.setEnabled( false );
- QAction *lastChildAction = new QAction(&testActionGroup);
-
- QVERIFY(!lastChildAction->isEnabled());
- testActionGroup.setEnabled( true );
- QVERIFY(lastChildAction->isEnabled());
-
- freeAction->setEnabled(false);
- testActionGroup.addAction(freeAction);
- QVERIFY(!freeAction->isEnabled());
- delete freeAction;
-}
-
-void tst_QActionGroup::visiblePropagation()
-{
- QActionGroup testActionGroup(nullptr);
-
- QAction* childAction = new QAction( &testActionGroup );
- QAction* anotherChildAction = new QAction( &testActionGroup );
- QAction* freeAction = new QAction(nullptr);
-
- QVERIFY( testActionGroup.isVisible() );
- QVERIFY( childAction->isVisible() );
-
- testActionGroup.setVisible( false );
- QVERIFY( !testActionGroup.isVisible() );
- QVERIFY( !childAction->isVisible() );
- QVERIFY( !anotherChildAction->isVisible() );
-
- anotherChildAction->setVisible(false);
-
- testActionGroup.setVisible( true );
- QVERIFY( testActionGroup.isVisible() );
- QVERIFY( childAction->isVisible() );
-
- QVERIFY( !anotherChildAction->isVisible() );
-
- testActionGroup.setVisible( false );
- QAction *lastChildAction = new QAction(&testActionGroup);
-
- QVERIFY(!lastChildAction->isVisible());
- testActionGroup.setVisible( true );
- QVERIFY(lastChildAction->isVisible());
-
- freeAction->setVisible(false);
- testActionGroup.addAction(freeAction);
- QVERIFY(!freeAction->isVisible());
- delete freeAction;
-}
-
-void tst_QActionGroup::exclusive()
-{
- QActionGroup group(nullptr);
- group.setExclusive(false);
- QVERIFY( !group.isExclusive() );
-
- QAction* actOne = new QAction( &group );
- actOne->setCheckable( true );
- QAction* actTwo = new QAction( &group );
- actTwo->setCheckable( true );
- QAction* actThree = new QAction( &group );
- actThree->setCheckable( true );
-
- group.setExclusive( true );
- QVERIFY( !actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actOne->setChecked( true );
- QVERIFY( actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actTwo->setChecked( true );
- QVERIFY( !actOne->isChecked() );
- QVERIFY( actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-}
-
-void tst_QActionGroup::exclusiveOptional()
-{
- QActionGroup group(0);
- group.setExclusive(true);
- QVERIFY( group.isExclusive() );
-
- QAction* actOne = new QAction( &group );
- actOne->setCheckable( true );
- QAction* actTwo = new QAction( &group );
- actTwo->setCheckable( true );
- QAction* actThree = new QAction( &group );
- actThree->setCheckable( true );
-
- QVERIFY( !actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actOne->trigger();
- QVERIFY( actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actOne->trigger();
- QVERIFY( actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- group.setExclusionPolicy( QActionGroup::ExclusionPolicy::ExclusiveOptional );
- QVERIFY( group.isExclusive() );
-
- actOne->trigger();
- QVERIFY( !actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actTwo->trigger();
- QVERIFY( !actOne->isChecked() );
- QVERIFY( actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-
- actTwo->trigger();
- QVERIFY( !actOne->isChecked() );
- QVERIFY( !actTwo->isChecked() );
- QVERIFY( !actThree->isChecked() );
-}
-
void tst_QActionGroup::separators()
{
QMainWindow mw;
@@ -233,40 +76,5 @@ void tst_QActionGroup::separators()
QCOMPARE(menu.actions().size(), 3);
}
-void tst_QActionGroup::testActionInTwoQActionGroup()
-{
- QAction action1("Action 1", this);
-
- QActionGroup group1(this);
- QActionGroup group2(this);
-
- group1.addAction(&action1);
- group2.addAction(&action1);
-
- QCOMPARE(action1.actionGroup(), &group2);
- QCOMPARE(group2.actions().first(), &action1);
- QCOMPARE(group1.actions().isEmpty(), true);
-}
-
-void tst_QActionGroup::unCheckCurrentAction()
-{
- QActionGroup group(nullptr);
- QAction action1(&group) ,action2(&group);
- action1.setCheckable(true);
- action2.setCheckable(true);
- QVERIFY(!action1.isChecked());
- QVERIFY(!action2.isChecked());
- action1.setChecked(true);
- QVERIFY(action1.isChecked());
- QVERIFY(!action2.isChecked());
- QAction *current = group.checkedAction();
- QCOMPARE(current, &action1);
- current->setChecked(false);
- QVERIFY(!action1.isChecked());
- QVERIFY(!action2.isChecked());
- QVERIFY(!group.checkedAction());
-}
-
-
QTEST_MAIN(tst_QActionGroup)
#include "tst_qactiongroup.moc"
diff --git a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
index c6760000f4..45a35fe4f1 100644
--- a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
+++ b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp
@@ -99,7 +99,9 @@ class tst_QFormLayout : public QObject
private slots:
void cleanup();
void rowCount();
+#if QT_CONFIG(shortcut)
void buddies();
+#endif
void getItemPosition();
void wrapping();
void spacing();
@@ -190,6 +192,8 @@ void tst_QFormLayout::rowCount()
//TODO: remove items
}
+#if QT_CONFIG(shortcut)
+
void tst_QFormLayout::buddies()
{
QWidget w;
@@ -218,6 +222,8 @@ void tst_QFormLayout::buddies()
//TODO: empty label?
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QFormLayout::getItemPosition()
{
QWidget w;
@@ -687,17 +693,21 @@ void tst_QFormLayout::insertRow_QString_QWidget()
layout->insertRow(-5, "&Name:", fld1);
QLabel *label1 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label1 != 0);
+#if QT_CONFIG(shortcut)
QCOMPARE(label1->buddy(), fld1);
-
+#endif
layout->insertRow(0, "&Email:", fld2);
QLabel *label2 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label2 != 0);
+#if QT_CONFIG(shortcut)
QCOMPARE(label2->buddy(), fld2);
-
+#endif
layout->insertRow(5, "&Age:", fld3);
QLabel *label3 = qobject_cast<QLabel *>(layout->itemAt(2, QFormLayout::LabelRole)->widget());
QVERIFY(label3 != 0);
+#if QT_CONFIG(shortcut)
QCOMPARE(label3->buddy(), fld3);
+#endif
}
void tst_QFormLayout::insertRow_QString_QLayout()
@@ -711,21 +721,27 @@ void tst_QFormLayout::insertRow_QString_QLayout()
layout->insertRow(-5, "&Name:", fld1);
QLabel *label1 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label1 != 0);
+#if QT_CONFIG(shortcut)
QVERIFY(!label1->buddy());
+#endif
QCOMPARE(layout->rowCount(), 1);
layout->insertRow(0, "&Email:", fld2);
QLabel *label2 = qobject_cast<QLabel *>(layout->itemAt(0, QFormLayout::LabelRole)->widget());
QVERIFY(label2 != 0);
+#if QT_CONFIG(shortcut)
QVERIFY(!label2->buddy());
+#endif
QCOMPARE(layout->rowCount(), 2);
layout->insertRow(5, "&Age:", fld3);
QLabel *label3 = qobject_cast<QLabel *>(layout->itemAt(2, QFormLayout::LabelRole)->widget());
QVERIFY(label3 != 0);
+#if QT_CONFIG(shortcut)
QVERIFY(!label3->buddy());
+#endif
QCOMPARE(layout->rowCount(), 3);
}
diff --git a/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp b/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
index eb108a40de..e5a891912f 100644
--- a/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
+++ b/tests/auto/widgets/widgets/qabstractbutton/tst_qabstractbutton.cpp
@@ -34,7 +34,9 @@
#include <qapplication.h>
#include <qpainter.h>
#include <qstyleoption.h>
-#include <qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <qkeysequence.h>
+#endif
#include <qevent.h>
#include <qgridlayout.h>
#include <qabstractbutton.h>
@@ -59,7 +61,9 @@ private slots:
void setText();
void setIcon();
+#if QT_CONFIG(shortcut)
void setShortcut();
+#endif
void animateClick();
@@ -68,7 +72,9 @@ private slots:
void isChecked();
void toggled();
void setEnabled();
+#if QT_CONFIG(shortcut)
void shortcutEvents();
+#endif
void stopRepeatTimer();
void mouseReleased(); // QTBUG-53244
@@ -164,8 +170,10 @@ void tst_QAbstractButton::init()
testWidget->setEnabled( true );
testWidget->setDown( false );
testWidget->setAutoRepeat( false );
+#if QT_CONFIG(shortcut)
QKeySequence seq;
testWidget->setShortcut( seq );
+#endif
toggle_count = 0;
press_count = 0;
@@ -336,17 +344,17 @@ void tst_QAbstractButton::setText()
QCOMPARE( testWidget->text(), QString("simple") );
testWidget->setText("&ampersand");
QCOMPARE( testWidget->text(), QString("&ampersand") );
-#ifndef Q_OS_MAC // no mneonics on Mac.
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN) // no mnemonics on Mac.
QCOMPARE( testWidget->shortcut(), QKeySequence("ALT+A"));
#endif
testWidget->setText("te&st");
QCOMPARE( testWidget->text(), QString("te&st") );
-#ifndef Q_OS_MAC // no mneonics on Mac.
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN) // no mnemonics on Mac.
QCOMPARE( testWidget->shortcut(), QKeySequence("ALT+S"));
#endif
testWidget->setText("foo");
QCOMPARE( testWidget->text(), QString("foo") );
-#ifndef Q_OS_MAC // no mneonics on Mac.
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN) // no mnemonics on Mac.
QCOMPARE( testWidget->shortcut(), QKeySequence());
#endif
}
@@ -471,6 +479,7 @@ void tst_QAbstractButton::toggled()
testWidget->setCheckable(false);
}
+#if QT_CONFIG(shortcut)
void tst_QAbstractButton::setShortcut()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::WindowActivation))
@@ -502,6 +511,7 @@ void tst_QAbstractButton::setShortcut()
// qDebug() << click_count;
}
+#endif // QT_CONFIG(shortcut)
void tst_QAbstractButton::animateClick()
{
@@ -512,6 +522,8 @@ void tst_QAbstractButton::animateClick()
QTRY_VERIFY( !testWidget->isDown() );
}
+#if QT_CONFIG(shortcut)
+
void tst_QAbstractButton::shortcutEvents()
{
MyButton button;
@@ -535,6 +547,8 @@ void tst_QAbstractButton::shortcutEvents()
QCOMPARE(clickedSpy.count(), 3);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QAbstractButton::stopRepeatTimer()
{
MyButton button;
diff --git a/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp b/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
index 0044d33c66..45a23984e0 100644
--- a/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
+++ b/tests/auto/widgets/widgets/qcommandlinkbutton/tst_qcommandlinkbutton.cpp
@@ -51,7 +51,9 @@ private slots:
void getSetCheck();
void pressed();
+#if QT_CONFIG(shortcut)
void setAccel();
+#endif
void isCheckable();
void setDown();
void popupCrash();
@@ -133,8 +135,10 @@ void tst_QCommandLinkButton::init()
testWidget->setText("Test");
testWidget->setDescription("Description text.");
testWidget->setEnabled( true );
+#if QT_CONFIG(shortcut)
QKeySequence seq;
testWidget->setShortcut( seq );
+#endif
resetCounters();
}
@@ -327,6 +331,8 @@ void tst_QCommandLinkButton::toggled()
QVERIFY( click_count == 1 );
}
+#if QT_CONFIG(shortcut)
+
/*
If we press an accelerator key we ONLY get a pressed signal and
NOT a released or clicked signal.
@@ -355,6 +361,8 @@ void tst_QCommandLinkButton::setAccel()
QTest::qWait(200);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QCommandLinkButton::animateClick()
{
QVERIFY( !testWidget->isDown() );
diff --git a/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp b/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
index 264625777f..9eae1f10ea 100644
--- a/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
+++ b/tests/auto/widgets/widgets/qdatetimeedit/tst_qdatetimeedit.cpp
@@ -262,6 +262,8 @@ private slots:
void timeSpec();
void timeSpecBug();
void timeSpecInit();
+ void setDateTime_data();
+ void setDateTime();
void monthEdgeCase();
void setLocale();
@@ -3476,6 +3478,54 @@ void tst_QDateTimeEdit::timeSpecInit()
QCOMPARE(widget.dateTime(), utc);
}
+void tst_QDateTimeEdit::setDateTime_data()
+{
+ QTest::addColumn<Qt::TimeSpec>("spec");
+ QDateTime localNoon(QDate(2019, 12, 24), QTime(12, 0), Qt::LocalTime);
+#if 0 // Not yet supported
+ QTest::addColumn<int>("offset");
+ QTest::addColumn<QByteArray>("zoneName");
+
+ QTest::newRow("OffsetFromUTC/LocalTime")
+ << Qt::OffsetFromUTC << 7200 << ""
+ << localNoon << localNoon.toOffsetFromUtc(7200);
+#if QT_CONFIG(timezone)
+ QTest::newRow("TimeZone/LocalTime")
+ << Qt::TimeZone << 0 << "Europe/Berlin"
+ << localNoon << localNoon.toTimeZone(QTimeZone("Europe/Berlin"));
+#endif
+#endif // unsupported
+ QTest::addColumn<QDateTime>("store");
+ QTest::addColumn<QDateTime>("expect");
+ QTest::newRow("LocalTime/LocalTime")
+ << Qt::LocalTime // << 0 << ""
+ << localNoon << localNoon;
+ QTest::newRow("LocalTime/UTC")
+ << Qt::LocalTime // << 0 << ""
+ << localNoon.toUTC() << localNoon;
+ QTest::newRow("UTC/LocalTime")
+ << Qt::UTC // << 0 << ""
+ << localNoon << localNoon.toUTC();
+ QTest::newRow("UTC/UTC")
+ << Qt::UTC // << 0 << ""
+ << localNoon.toUTC() << localNoon.toUTC();
+}
+
+void tst_QDateTimeEdit::setDateTime()
+{
+ QFETCH(const Qt::TimeSpec, spec);
+#if 0 // Not yet supported
+ QFETCH(const int, offset);
+ QFETCH(const QByteArray, zoneName);
+#endif // configuring the spec, when OffsetFromUTC or TimeZone
+ QFETCH(const QDateTime, store);
+ QFETCH(const QDateTime, expect);
+ QDateTimeEdit editor;
+ editor.setTimeSpec(spec);
+ editor.setDateTime(store);
+ QCOMPARE(editor.dateTime(), expect);
+}
+
void tst_QDateTimeEdit::cachedDayTest()
{
testWidget->setDisplayFormat("MM/dd");
diff --git a/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp b/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp
index c293a4bdd2..c6de750482 100644
--- a/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp
+++ b/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp
@@ -166,7 +166,9 @@ private slots:
void doubleDot();
+#if QT_CONFIG(shortcut)
void undoRedo();
+#endif
void valueFromTextAndValidate_data();
void valueFromTextAndValidate();
@@ -1025,6 +1027,8 @@ void tst_QDoubleSpinBox::doubleDot()
QCOMPARE(spin.lineEdit()->cursorPosition(), 2);
}
+#if QT_CONFIG(shortcut)
+
void tst_QDoubleSpinBox::undoRedo()
{
//test undo/redo feature (in conjunction with the "undoRedoEnabled" property)
@@ -1073,6 +1077,8 @@ void tst_QDoubleSpinBox::undoRedo()
QVERIFY(!spin.lineEdit()->isRedoAvailable());
}
+#endif // QT_CONFIG(shortcut)
+
struct task199226_DoubleSpinBox : public QDoubleSpinBox
{
task199226_DoubleSpinBox(QWidget *parent = 0) : QDoubleSpinBox(parent) {}
diff --git a/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp b/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
index f599ac73c6..7760e12cca 100644
--- a/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
+++ b/tests/auto/widgets/widgets/qlabel/tst_qlabel.cpp
@@ -68,7 +68,7 @@ private Q_SLOTS:
void setText_data();
void setText();
void setTextFormat();
-#ifndef Q_OS_MAC
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN)
void setBuddy();
#endif
void setNum();
@@ -88,8 +88,10 @@ private Q_SLOTS:
void unicodeText_data();
void unicodeText();
+#if QT_CONFIG(shortcut)
void mnemonic_data();
void mnemonic();
+#endif
void selection();
#ifndef QT_NO_CONTEXTMENU
@@ -116,6 +118,7 @@ void tst_QLabel::getSetCheck()
obj1.setWordWrap(true);
QCOMPARE(true, obj1.wordWrap());
+#if QT_CONFIG(shortcut)
// QWidget * QLabel::buddy()
// void QLabel::setBuddy(QWidget *)
QWidget *var2 = new QWidget();
@@ -124,6 +127,7 @@ void tst_QLabel::getSetCheck()
obj1.setBuddy((QWidget *)0);
QCOMPARE((QWidget *)0, obj1.buddy());
delete var2;
+#endif // QT_CONFIG(shortcut)
// QMovie * QLabel::movie()
// void QLabel::setMovie(QMovie *)
@@ -153,7 +157,9 @@ void tst_QLabel::cleanupTestCase()
void tst_QLabel::init()
{
testWidget->setTextFormat( Qt::AutoText );
+# if QT_CONFIG(shortcut)
testWidget->setBuddy( 0 );
+#endif
testWidget->setIndent( 0 );
testWidget->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
testWidget->setScaledContents( false );
@@ -169,7 +175,7 @@ void tst_QLabel::cleanup()
}
// Set buddy doesn't make much sense on OS X
-#ifndef Q_OS_MAC
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN)
void tst_QLabel::setBuddy()
{
testWidget->hide();
@@ -204,7 +210,7 @@ void tst_QLabel::setBuddy()
delete test_box;
}
-#endif
+#endif // QT_CONFIG(shortcut) && !Q_OS_DARWIN
void tst_QLabel::setText_data()
{
@@ -469,6 +475,8 @@ void tst_QLabel::unicodeText()
testWidget->show();
}
+#if QT_CONFIG(shortcut)
+
void tst_QLabel::mnemonic_data()
{
QTest::addColumn<QString>("text");
@@ -513,6 +521,8 @@ void tst_QLabel::mnemonic()
QCOMPARE(d->shortcutCursor.selectedText(), expectedShortcutCursor);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QLabel::selection()
{
QLabel label;
diff --git a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
index 6408df3f11..bf31f12958 100644
--- a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
+++ b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
@@ -56,7 +56,9 @@
#include <qsortfilterproxymodel.h>
#include <qdebug.h>
#include <qscreen.h>
-#include <qshortcut.h>
+#if QT_CONFIG(shortcut)
+# include <qshortcut.h>
+#endif
#include "qcommonstyle.h"
#include "qstyleoption.h"
@@ -133,9 +135,11 @@ private slots:
void clearInputMask();
+#if QT_CONFIG(shortcut)
void keypress_inputMask_data();
void keypress_inputMask();
void keypress_inputMethod_inputMask();
+#endif
void inputMaskAndValidator_data();
void inputMaskAndValidator();
@@ -217,7 +221,7 @@ private slots:
void setSelection_data();
void setSelection();
-#ifndef QT_NO_CLIPBOARD
+#if QT_CONFIG(clipboard) && QT_CONFIG(shortcut)
void cut();
void cutWithoutSelection();
#endif
@@ -297,8 +301,10 @@ private slots:
void shouldShowPlaceholderText();
void QTBUG1266_setInputMaskEmittingTextEdited();
+#if QT_CONFIG(shortcut)
void shortcutOverrideOnReadonlyLineEdit_data();
void shortcutOverrideOnReadonlyLineEdit();
+#endif
void QTBUG59957_clearButtonLeftmostAction();
void QTBUG_60319_setInputMaskCheckImSurroundingText();
void testQuickSelectionWithMouse();
@@ -317,7 +323,9 @@ private:
void psKeyClick(QWidget *target, Qt::Key key, Qt::KeyboardModifiers pressState = {});
void psKeyClick(QTestEventList &keys, Qt::Key key, Qt::KeyboardModifiers pressState = {});
bool unselectingWithLeftOrRightChangesCursorPosition();
+#if QT_CONFIG(shortcut)
void addKeySequenceStandardKey(QTestEventList &keys, QKeySequence::StandardKey);
+#endif
QLineEdit *ensureTestWidget();
bool validInput;
@@ -713,6 +721,8 @@ void tst_QLineEdit::clearInputMask()
QCOMPARE(testWidget->inputMask(), QString());
}
+#if QT_CONFIG(shortcut)
+
void tst_QLineEdit::keypress_inputMask_data()
{
QTest::addColumn<QString>("mask");
@@ -838,6 +848,8 @@ void tst_QLineEdit::keypress_inputMethod_inputMask()
QCOMPARE(testWidget->text(), QStringLiteral("EE.EE.EE"));
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QLineEdit::hasAcceptableInputMask_data()
{
QTest::addColumn<QString>("optionalMask");
@@ -1989,6 +2001,8 @@ void tst_QLineEdit::psKeyClick(QTestEventList &keys, Qt::Key key, Qt::KeyboardMo
keys.addKeyClick(key, pressState);
}
+#if QT_CONFIG(shortcut)
+
void tst_QLineEdit::addKeySequenceStandardKey(QTestEventList &keys, QKeySequence::StandardKey key)
{
QKeySequence keyseq = QKeySequence(key);
@@ -1996,6 +2010,8 @@ void tst_QLineEdit::addKeySequenceStandardKey(QTestEventList &keys, QKeySequence
keys.addKeyClick( Qt::Key( keyseq[i] & ~Qt::KeyboardModifierMask), Qt::KeyboardModifier(keyseq[i] & Qt::KeyboardModifierMask) );
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QLineEdit::cursorPosition()
{
QLineEdit *testWidget = ensureTestWidget();
@@ -3026,7 +3042,7 @@ void tst_QLineEdit::setSelection()
QCOMPARE(testWidget->cursorPosition(), expectedCursor);
}
-#ifndef QT_NO_CLIPBOARD
+#if QT_CONFIG(clipboard) && QT_CONFIG(shortcut)
void tst_QLineEdit::cut()
{
if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive))
@@ -3127,7 +3143,7 @@ void tst_QLineEdit::cutWithoutSelection()
QCOMPARE(clipboard->text(), origText.left(selectionLength));
}
-#endif // !QT_NO_CLIPBOARD
+#endif // QT_CONFIG(clipboard) && QT_CONFIG(shortcut)
class InputMaskValidator : public QValidator
{
@@ -3975,7 +3991,9 @@ void tst_QLineEdit::taskQTBUG_7395_readOnlyShortcut()
le.setReadOnly(true);
QAction action(QString::fromLatin1("hello"), &le);
+#if QT_CONFIG(shortcut)
action.setShortcut(QString::fromLatin1("p"));
+#endif
QSignalSpy spy(&action, SIGNAL(triggered()));
le.addAction(&action);
@@ -4710,6 +4728,8 @@ void tst_QLineEdit::QTBUG1266_setInputMaskEmittingTextEdited()
QCOMPARE(spy.count(), 0);
}
+#if QT_CONFIG(shortcut)
+
void tst_QLineEdit::shortcutOverrideOnReadonlyLineEdit_data()
{
QTest::addColumn<QKeySequence>("keySequence");
@@ -4769,6 +4789,8 @@ void tst_QLineEdit::shortcutOverrideOnReadonlyLineEdit()
QCOMPARE(spy.count(), activationCount);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QLineEdit::QTBUG59957_clearButtonLeftmostAction()
{
#ifndef QT_BUILD_INTERNAL
diff --git a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
index e3b046e448..352a6314f3 100644
--- a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
+++ b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
@@ -2694,30 +2694,6 @@ void tst_QMdiArea::nativeSubWindows()
foreach (QMdiSubWindow *subWindow, mdiArea.subWindowList())
QVERIFY(subWindow->internalWinId());
}
-
-#ifndef QT_NO_OPENGL
- {
- if (!QGLFormat::hasOpenGL())
- QSKIP("QGL not supported on this platform");
-
- QMdiArea mdiArea;
- QGLWidget *glViewport = new QGLWidget;
- mdiArea.setViewport(glViewport);
- mdiArea.addSubWindow(new QWidget);
- mdiArea.addSubWindow(new QWidget);
- mdiArea.show();
- QVERIFY(QTest::qWaitForWindowExposed(&mdiArea));
-
- const QGLContext *context = glViewport->context();
- if (!context || !context->isValid())
- QSKIP("QGL is broken, cannot continue test");
-
- // The viewport and all the sub-windows must be native.
- QVERIFY(mdiArea.viewport()->internalWinId());
- foreach (QMdiSubWindow *subWindow, mdiArea.subWindowList())
- QVERIFY(subWindow->internalWinId());
- }
-#endif
}
void tst_QMdiArea::task_209615()
diff --git a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
index 1e20b7598f..2d74c20469 100644
--- a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
+++ b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp
@@ -481,7 +481,7 @@ void tst_QMenu::overrideMenuAction()
// On Mac and Windows CE, we need to create native key events to test menu
// action activation, so skip this part of the test.
-#if !defined(Q_OS_DARWIN)
+#if QT_CONFIG(shortcut) && !defined(Q_OS_DARWIN)
QAction *aQuit = new QAction("Quit", &w);
aQuit->setShortcut(QKeySequence("Ctrl+X"));
m->addAction(aQuit);
@@ -499,7 +499,7 @@ void tst_QMenu::overrideMenuAction()
//test if the menu still pops out
QTest::keyClick(&w, Qt::Key_F, Qt::AltModifier);
QTRY_VERIFY(m->isVisible());
-#endif
+#endif // QT_CONFIG(shortcut) && !Q_OS_DARWIN
delete aFileMenu;
@@ -1706,10 +1706,13 @@ void tst_QMenu::QTBUG_61039_menu_shortcuts()
QSKIP("Window activation is not supported");
QAction *actionKamen = new QAction("Action Kamen");
+#if QT_CONFIG(shortcut)
actionKamen->setShortcut(QKeySequence(QLatin1String("K")));
-
+#endif
QAction *actionJoe = new QAction("Action Joe");
+#if QT_CONFIG(shortcut)
actionJoe->setShortcut(QKeySequence(QLatin1String("Ctrl+J")));
+#endif
QMenu menu;
menu.addAction(actionKamen);
diff --git a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
index b255930138..8cbe821a68 100644
--- a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
+++ b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp
@@ -232,19 +232,25 @@ TestMenu tst_QMenuBar::initSimpleMenuBar(QMenuBar *mb, bool forceNonNative) {
connect(mb, SIGNAL(triggered(QAction*)), this, SLOT(onSimpleActivated(QAction*)));
QMenu *menu = mb->addMenu(QStringLiteral("&accel"));
QAction *action = menu->addAction(QStringLiteral("menu1") );
+#if QT_CONFIG(shortcut)
action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_A));
action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_A));
+#endif
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onSimpleActivated(QAction*)));
result.menus << menu;
result.actions << action;
menu = mb->addMenu(QStringLiteral("accel1"));
action = menu->addAction(QStringLiteral("&Open...") );
+#if QT_CONFIG(shortcut)
action->setShortcut(Qt::Key_O);
+#endif
result.actions << action;
action = menu->addAction(QStringLiteral("action"));
+#if QT_CONFIG(shortcut)
action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Z));
+#endif
result.actions << action;
result.menus << menu;
@@ -283,7 +289,9 @@ QAction *tst_QMenuBar::createCharacterAction(QMenu *menu, char lowerAscii)
QAction *action = menu->addAction(text);
action->setObjectName(text);
action->setData(QVariant(int(lowerAscii)));
+#if QT_CONFIG(shortcut)
action->setShortcut(Qt::CTRL + (lowerAscii - 'a' + Qt::Key_A));
+#endif
connect(action, SIGNAL(triggered()), this, SLOT(onComplexActionTriggered()));
return action;
}
@@ -318,7 +326,9 @@ TestMenu tst_QMenuBar::initComplexMenuBar(QMenuBar *mb)
QAction *action = mb->addAction(QStringLiteral("M&enu 3"));
action->setData(QVariant(3));
+#if QT_CONFIG(shortcut)
action->setShortcut(Qt::ALT + Qt::Key_J);
+#endif
connect(action, SIGNAL(triggered()), this, SLOT(onComplexActionTriggered()));
result.actions << action;
@@ -1422,7 +1432,9 @@ void tst_QMenuBar::taskQTBUG4965_escapeEaten()
menubar.setNativeMenuBar(false);
QMenu menu("menu1");
QAction *first = menubar.addMenu(&menu);
+#if QT_CONFIG(shortcut)
menu.addAction("quit", &menubar, SLOT(close()), QKeySequence("ESC"));
+#endif
centerOnScreen(&menubar);
menubar.show();
QApplication::setActiveWindow(&menubar);
diff --git a/tests/auto/widgets/widgets/qopenglwidget/qopenglwidget.pro b/tests/auto/widgets/widgets/qopenglwidget/qopenglwidget.pro
index 2d4cff9e10..039f5a71b8 100644
--- a/tests/auto/widgets/widgets/qopenglwidget/qopenglwidget.pro
+++ b/tests/auto/widgets/widgets/qopenglwidget/qopenglwidget.pro
@@ -1,5 +1,5 @@
CONFIG += testcase
TARGET = tst_qopenglwidget
-QT += gui-private core-private testlib widgets
+QT += opengl gui-private core-private testlib widgets
SOURCES += tst_qopenglwidget.cpp
diff --git a/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp b/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
index 17a5fe2cd9..e96e292525 100644
--- a/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
+++ b/tests/auto/widgets/widgets/qopenglwidget/tst_qopenglwidget.cpp
@@ -26,7 +26,7 @@
**
****************************************************************************/
-#include <QtWidgets/QOpenGLWidget>
+#include <QtOpenGL/QOpenGLWidget>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QPainter>
#include <QtGui/QScreen>
diff --git a/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp b/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
index 6f4838be7a..d0ed68c0c8 100644
--- a/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
+++ b/tests/auto/widgets/widgets/qpushbutton/tst_qpushbutton.cpp
@@ -53,7 +53,9 @@ private slots:
void getSetCheck();
void autoRepeat();
void pressed();
+#if QT_CONFIG(shortcut)
void setAccel();
+#endif
void isCheckable();
void setDown();
void popupCrash();
@@ -65,7 +67,9 @@ private slots:
void defaultAndAutoDefault();
void sizeHint_data();
void sizeHint();
+#if QT_CONFIG(shortcut)
void taskQTBUG_20191_shortcutWithKeypadModifer();
+#endif
void emitReleasedAfterChange();
protected slots:
@@ -125,8 +129,10 @@ void tst_QPushButton::init()
testWidget->setDown( false );
testWidget->setText("Test");
testWidget->setEnabled( true );
+#if QT_CONFIG(shortcut)
QKeySequence seq;
testWidget->setShortcut( seq );
+#endif
resetCounters();
}
@@ -318,6 +324,8 @@ void tst_QPushButton::toggled()
QVERIFY( click_count == 1 );
}
+#if QT_CONFIG(shortcut)
+
/*
If we press an accelerator key we ONLY get a pressed signal and
NOT a released or clicked signal.
@@ -349,6 +357,8 @@ void tst_QPushButton::setAccel()
QTRY_VERIFY( !testWidget->isDown() );
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QPushButton::animateClick()
{
QVERIFY( !testWidget->isDown() );
@@ -571,6 +581,8 @@ void tst_QPushButton::sizeHint()
}
}
+#if QT_CONFIG(shortcut)
+
void tst_QPushButton::taskQTBUG_20191_shortcutWithKeypadModifer()
{
// setup a dialog with two buttons
@@ -617,6 +629,8 @@ void tst_QPushButton::taskQTBUG_20191_shortcutWithKeypadModifer()
QCOMPARE(spy2.count(), 1);
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QPushButton::emitReleasedAfterChange()
{
QPushButton *button1 = new QPushButton("A");
diff --git a/tests/auto/widgets/widgets/qradiobutton/tst_qradiobutton.cpp b/tests/auto/widgets/widgets/qradiobutton/tst_qradiobutton.cpp
index 7123acfdc3..5c7d3bf1e9 100644
--- a/tests/auto/widgets/widgets/qradiobutton/tst_qradiobutton.cpp
+++ b/tests/auto/widgets/widgets/qradiobutton/tst_qradiobutton.cpp
@@ -44,12 +44,16 @@ public:
virtual ~tst_QRadioButton(){};
private slots:
+#if QT_CONFIG(shortcut)
void task190739_focus();
+#endif
void minimumSizeHint();
private:
};
+#if QT_CONFIG(shortcut)
+
void tst_QRadioButton::task190739_focus()
{
if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive))
@@ -84,6 +88,7 @@ void tst_QRadioButton::task190739_focus()
QVERIFY(!radio1.hasFocus());
}
+#endif // QT_CONFIG(shortcut)
void tst_QRadioButton::minimumSizeHint()
{
diff --git a/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp b/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp
index f8022559b2..5b49e3484c 100644
--- a/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp
+++ b/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp
@@ -47,7 +47,9 @@
#include <QLocale>
#include <QDoubleSpinBox>
#include <QVBoxLayout>
-#include <QKeySequence>
+#if QT_CONFIG(shortcut)
+# include <QKeySequence>
+#endif
#include <QStackedWidget>
#include <QDebug>
#include <QStyleOptionSpinBox>
@@ -173,7 +175,10 @@ private slots:
void removeAll();
void startWithDash();
+
+#if QT_CONFIG(shortcut)
void undoRedo();
+#endif
void specialValue();
void textFromValue();
@@ -1025,6 +1030,8 @@ void tst_QSpinBox::startWithDash()
QCOMPARE(spin.text(), QString("0"));
}
+#if QT_CONFIG(shortcut)
+
void tst_QSpinBox::undoRedo()
{
//test undo/redo feature (in conjunction with the "undoRedoEnabled" property)
@@ -1077,6 +1084,8 @@ void tst_QSpinBox::undoRedo()
QVERIFY(!spin.lineEdit()->isRedoAvailable());
}
+#endif // QT_CONFIG(shortcut)
+
void tst_QSpinBox::specialValue()
{
if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive))
diff --git a/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp b/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
index 61252831ed..1d5ac7c819 100644
--- a/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
+++ b/tests/auto/widgets/widgets/qtoolbar/tst_qtoolbar.cpp
@@ -40,7 +40,9 @@
#include <qwidgetaction.h>
#include <qtoolbutton.h>
#include <qlineedit.h>
-#include <qkeysequence.h>
+#if QT_CONFIG(shortcut)
+# include <qkeysequence.h>
+#endif
#include <qmenu.h>
#include <qlabel.h>
#include <private/qtoolbarextension_p.h>
diff --git a/tests/auto/widgets/widgets/widgets.pro b/tests/auto/widgets/widgets/widgets.pro
index c6325aac15..66950fa85a 100644
--- a/tests/auto/widgets/widgets/widgets.pro
+++ b/tests/auto/widgets/widgets/widgets.pro
@@ -47,6 +47,9 @@ SUBDIRS=\
qtoolbox \
qtoolbutton \
+!qtConfig(shortcut): SUBDIRS -= \
+ qkeysequenceedit
+
# The following tests depend on private API:
!qtConfig(private_tests): SUBDIRS -= \
qabstractspinbox \
diff --git a/tests/auto/xml/dom/qdom/tst_qdom.cpp b/tests/auto/xml/dom/qdom/tst_qdom.cpp
index a2a5b22cad..9cb06f5185 100644
--- a/tests/auto/xml/dom/qdom/tst_qdom.cpp
+++ b/tests/auto/xml/dom/qdom/tst_qdom.cpp
@@ -33,7 +33,7 @@
#include <QDebug>
#include <QFile>
#include <QList>
-#include <QRegExp>
+#include <QRegularExpression>
#include <QTextStream>
#include <QtTest/QtTest>
#include <QtXml>
@@ -517,10 +517,10 @@ void tst_QDom::save_data()
QTest::addColumn<int>("indent");
QTest::addColumn<QString>("res");
- QTest::newRow( "01" ) << doc01 << 0 << QString(doc01).replace( QRegExp(" "), "" );
+ QTest::newRow( "01" ) << doc01 << 0 << QString(doc01).replace( QRegularExpression(" "), "" );
QTest::newRow( "02" ) << doc01 << 1 << doc01;
- QTest::newRow( "03" ) << doc01 << 2 << QString(doc01).replace( QRegExp(" "), " " );
- QTest::newRow( "04" ) << doc01 << 10 << QString(doc01).replace( QRegExp(" "), " " );
+ QTest::newRow( "03" ) << doc01 << 2 << QString(doc01).replace( QRegularExpression(" "), " " );
+ QTest::newRow( "04" ) << doc01 << 10 << QString(doc01).replace( QRegularExpression(" "), " " );
}
void tst_QDom::save()
diff --git a/tests/benchmarks/corelib/io/qdiriterator/main.cpp b/tests/benchmarks/corelib/io/qdiriterator/main.cpp
index eae752d99a..60c75ead4d 100644
--- a/tests/benchmarks/corelib/io/qdiriterator/main.cpp
+++ b/tests/benchmarks/corelib/io/qdiriterator/main.cpp
@@ -44,9 +44,19 @@
#include "qfilesystemiterator.h"
+#if QT_HAS_INCLUDE(<filesystem>) && defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L
+#define HAS_STD_FILESYSTEM
+#endif
+
+#ifdef HAS_STD_FILESYSTEM
+#include <filesystem>
+#endif
+
class tst_qdiriterator : public QObject
{
Q_OBJECT
+
+ void data();
private slots:
void posix();
void posix_data() { data(); }
@@ -54,7 +64,8 @@ private slots:
void diriterator_data() { data(); }
void fsiterator();
void fsiterator_data() { data(); }
- void data();
+ void stdRecursiveDirectoryIterator();
+ void stdRecursiveDirectoryIterator_data() { data(); }
};
@@ -235,6 +246,28 @@ void tst_qdiriterator::fsiterator()
qDebug() << count;
}
+void tst_qdiriterator::stdRecursiveDirectoryIterator()
+{
+#ifdef HAS_STD_FILESYSTEM
+ QFETCH(QByteArray, dirpath);
+
+ int count = 0;
+
+ QBENCHMARK {
+ int c = 0;
+ for (auto obj : std::filesystem::recursive_directory_iterator(dirpath.data())) {
+ if (obj.is_directory())
+ continue;
+ c++;
+ }
+ count = c;
+ }
+ qDebug() << count;
+#else
+ QSKIP("Not supported.");
+#endif
+}
+
QTEST_MAIN(tst_qdiriterator)
#include "main.moc"
diff --git a/tests/benchmarks/corelib/io/qdiriterator/qdiriterator.pro b/tests/benchmarks/corelib/io/qdiriterator/qdiriterator.pro
index 061b22a5d1..4b28946f18 100644
--- a/tests/benchmarks/corelib/io/qdiriterator/qdiriterator.pro
+++ b/tests/benchmarks/corelib/io/qdiriterator/qdiriterator.pro
@@ -3,6 +3,8 @@ TARGET = tst_bench_qdiriterator
QT = core testlib
CONFIG += release
+# Enable c++17 support for std::filesystem
+qtConfig(c++1z): CONFIG += c++17
SOURCES += main.cpp qfilesystemiterator.cpp
HEADERS += qfilesystemiterator.h
diff --git a/tests/benchmarks/corelib/kernel/qobject/main.cpp b/tests/benchmarks/corelib/kernel/qobject/main.cpp
index 04ca69ad3b..918227f74e 100644
--- a/tests/benchmarks/corelib/kernel/qobject/main.cpp
+++ b/tests/benchmarks/corelib/kernel/qobject/main.cpp
@@ -51,8 +51,55 @@ private slots:
void connect_disconnect_benchmark_data();
void connect_disconnect_benchmark();
void receiver_destroyed_benchmark();
+
+ void stdAllocator();
};
+class QObjectUsingStandardAllocator : public QObject
+{
+ Q_OBJECT
+public:
+ QObjectUsingStandardAllocator()
+ {
+ }
+};
+
+template<class T>
+inline void allocator()
+{
+ // We need to allocate certain amount of objects otherwise the new implementation
+ // may re-use the previous allocation, hiding the somehow high cost of allocation. It
+ // also helps us to reduce the noise ratio, which is high for memory allocation.
+ //
+ // The check depends on memory allocation performance, which is quite non-deterministic.
+ // When a new memory is requested, the new operator, depending on implementation, is trying
+ // to re-use existing, already allocated for the process memory. If there is not enough, it
+ // asks OS to give more. Of course the first case is faster then the second. In the same
+ // time, from an application perspective the first is also more likely.
+ //
+ // As a result, depending on which use-case one wants to test, it may be recommended to run this
+ // test in separation from others, to "force" expensive code path in the memory allocation.
+ //
+ // The time based results are heavily affected by background noise. One really needs to
+ // prepare OS (no other tasks, CPU and RAM reservations) to run this test, or use
+ // instruction counting which seems to be less fragile.
+
+ const int count = 256 * 1024;
+
+ QScopedPointer<T> objects[count];
+ QBENCHMARK_ONCE {
+ for (int i = 0; i < count; ++i)
+ objects[i].reset(new T);
+ for (int i = 0; i < count; ++i)
+ objects[i].reset();
+ }
+}
+
+void QObjectBenchmark::stdAllocator()
+{
+ allocator<QObjectUsingStandardAllocator>();
+}
+
struct Functor {
void operator()(){}
};
diff --git a/tests/benchmarks/corelib/tools/qvector/outofline.cpp b/tests/benchmarks/corelib/tools/qvector/outofline.cpp
index 76a4edaa10..7182a43008 100644
--- a/tests/benchmarks/corelib/tools/qvector/outofline.cpp
+++ b/tests/benchmarks/corelib/tools/qvector/outofline.cpp
@@ -54,7 +54,7 @@ QVector<double> mixedvector_fill_and_return_helper()
std::vector<double> v(N);
for (int i = 0; i != N; ++i)
v[i] = i;
- return QVector<double>::fromStdVector(v);
+ return QVector<double>(v.begin(), v.end());
}
diff --git a/tests/benchmarks/corelib/tools/qvector/qrawvector.h b/tests/benchmarks/corelib/tools/qvector/qrawvector.h
index 16a911c63a..9ad5f771bd 100644
--- a/tests/benchmarks/corelib/tools/qvector/qrawvector.h
+++ b/tests/benchmarks/corelib/tools/qvector/qrawvector.h
@@ -130,78 +130,9 @@ public:
bool contains(const T &t) const;
int count(const T &t) const;
-#ifdef QT_STRICT_ITERATORS
- class iterator {
- public:
- T *i;
- typedef std::random_access_iterator_tag iterator_category;
- typedef ptrdiff_t difference_type;
- typedef T value_type;
- typedef T *pointer;
- typedef T &reference;
-
- inline iterator() : i(0) {}
- inline iterator(T *n) : i(n) {}
- inline iterator(const iterator &o): i(o.i){}
- inline T &operator*() const { return *i; }
- inline T *operator->() const { return i; }
- inline T &operator[](int j) const { return *(i + j); }
- 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 iterator &operator++() { ++i; return *this; }
- inline iterator operator++(int) { T *n = i; ++i; return n; }
- inline iterator &operator--() { i--; return *this; }
- inline iterator operator--(int) { T *n = i; i--; return n; }
- inline iterator &operator+=(int j) { i+=j; return *this; }
- inline iterator &operator-=(int j) { i-=j; return *this; }
- inline iterator operator+(int j) const { return iterator(i+j); }
- inline iterator operator-(int j) const { return iterator(i-j); }
- inline int operator-(iterator j) const { return i - j.i; }
- };
- friend class iterator;
-
- class const_iterator {
- public:
- T *i;
- typedef std::random_access_iterator_tag iterator_category;
- typedef ptrdiff_t difference_type;
- typedef T value_type;
- typedef const T *pointer;
- typedef const T &reference;
-
- inline const_iterator() : i(0) {}
- inline const_iterator(T *n) : i(n) {}
- inline const_iterator(const const_iterator &o): i(o.i) {}
- inline explicit const_iterator(const iterator &o): i(o.i) {}
- inline const T &operator*() const { return *i; }
- inline const T *operator->() const { return i; }
- inline const T &operator[](int j) const { return *(i + j); }
- 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 const_iterator &operator++() { ++i; return *this; }
- inline const_iterator operator++(int) { T *n = i; ++i; return n; }
- inline const_iterator &operator--() { i--; return *this; }
- inline const_iterator operator--(int) { T *n = i; i--; return n; }
- inline const_iterator &operator+=(int j) { i+=j; return *this; }
- inline const_iterator &operator-=(int j) { i+=j; return *this; }
- inline const_iterator operator+(int j) const { return const_iterator(i+j); }
- inline const_iterator operator-(int j) const { return const_iterator(i-j); }
- inline int operator-(const_iterator j) const { return i - j.i; }
- };
- friend class const_iterator;
-#else
// STL-style
typedef T *iterator;
typedef const T *const_iterator;
-#endif
inline iterator begin() { return m_begin; }
inline const_iterator begin() const { return m_begin; }
inline const_iterator constBegin() const { return m_begin; }
@@ -280,11 +211,7 @@ private:
}
static Q_DECL_CONSTEXPR int alignOfTypedData()
{
-#ifdef Q_ALIGNOF
- return Q_ALIGNOF(AlignmentDummy);
-#else
- return sizeof(void *);
-#endif
+ return alignof(AlignmentDummy);
}
public:
diff --git a/tests/benchmarks/network/access/qfile_vs_qnetworkaccessmanager/main.cpp b/tests/benchmarks/network/access/qfile_vs_qnetworkaccessmanager/main.cpp
index 46bb1791b4..1f3f38eaaf 100644
--- a/tests/benchmarks/network/access/qfile_vs_qnetworkaccessmanager/main.cpp
+++ b/tests/benchmarks/network/access/qfile_vs_qnetworkaccessmanager/main.cpp
@@ -105,7 +105,7 @@ void qfile_vs_qnetworkaccessmanager::qnamFileRead()
}
qint64 elapsed = t.elapsed();
- qDebug() << endl << "Finished!";
+ qDebug() << Qt::endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
@@ -138,7 +138,7 @@ void qfile_vs_qnetworkaccessmanager::qnamImmediateFileRead()
}
qint64 elapsed = t.elapsed();
- qDebug() << endl << "Finished!";
+ qDebug() << Qt::endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
@@ -167,7 +167,7 @@ void qfile_vs_qnetworkaccessmanager::qfileFileRead()
}
qint64 elapsed = t.elapsed();
- qDebug() << endl << "Finished!";
+ qDebug() << Qt::endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
diff --git a/tests/benchmarks/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/benchmarks/network/access/qnetworkreply/tst_qnetworkreply.cpp
index c182ef7ebf..6dd7eaee6b 100644
--- a/tests/benchmarks/network/access/qnetworkreply/tst_qnetworkreply.cpp
+++ b/tests/benchmarks/network/access/qnetworkreply/tst_qnetworkreply.cpp
@@ -544,15 +544,10 @@ void tst_qnetworkreply::echoPerformance()
void tst_qnetworkreply::preConnectEncrypted()
{
QFETCH(int, sleepTime);
- QFETCH(QSslConfiguration, sslConfiguration);
- bool spdyEnabled = !sslConfiguration.isNull();
-
QString hostName = QLatin1String("www.google.com");
QNetworkAccessManager manager;
QNetworkRequest request(QUrl("https://" + hostName));
- if (spdyEnabled)
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
// make sure we have a full request including
// DNS lookup, TCP and SSL handshakes
@@ -578,12 +573,7 @@ void tst_qnetworkreply::preConnectEncrypted()
manager.clearAccessCache();
// now try to make the connection beforehand
- if (spdyEnabled) {
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
- manager.connectToHostEncrypted(hostName, 443, sslConfiguration);
- } else {
- manager.connectToHostEncrypted(hostName);
- }
+ manager.connectToHostEncrypted(hostName);
QTestEventLoop::instance().enterLoopMSecs(sleepTime);
// now make another request and hopefully use the existing connection
@@ -591,8 +581,6 @@ void tst_qnetworkreply::preConnectEncrypted()
QNetworkReply *preConnectReply = normalResult.first;
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(preConnectReply->error() == QNetworkReply::NoError);
- bool spdyWasUsed = preConnectReply->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool();
- QCOMPARE(spdyEnabled, spdyWasUsed);
qint64 preConnectElapsed = preConnectResult.second;
qDebug() << request.url().toString() << "full request:" << normalElapsed
<< "ms, pre-connect request:" << preConnectElapsed << "ms, difference:"
@@ -605,27 +593,11 @@ void tst_qnetworkreply::preConnectEncrypted_data()
{
#ifndef QT_NO_OPENSSL
QTest::addColumn<int>("sleepTime");
- QTest::addColumn<QSslConfiguration>("sslConfiguration");
-
// start a new normal request after preconnecting is done
- QTest::newRow("HTTPS-2secs") << 2000 << QSslConfiguration();
+ QTest::newRow("HTTPS-2secs") << 2000;
// start a new normal request while preconnecting is in-flight
- QTest::newRow("HTTPS-100ms") << 100 << QSslConfiguration();
-
- QSslConfiguration spdySslConf = QSslConfiguration::defaultConfiguration();
- QList<QByteArray> nextProtocols = QList<QByteArray>()
- << QSslConfiguration::NextProtocolSpdy3_0
- << QSslConfiguration::NextProtocolHttp1_1;
- spdySslConf.setAllowedNextProtocols(nextProtocols);
-
-#if defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) && OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
- // start a new SPDY request while preconnecting is done
- QTest::newRow("SPDY-2secs") << 2000 << spdySslConf;
-
- // start a new SPDY request while preconnecting is in-flight
- QTest::newRow("SPDY-100ms") << 100 << spdySslConf;
-#endif // defined (QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) ...
+ QTest::newRow("HTTPS-100ms") << 100;
#endif // QT_NO_OPENSSL
}
diff --git a/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.cpp b/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.cpp
index dfa08b6869..1eaa5f6578 100644
--- a/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.cpp
+++ b/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.cpp
@@ -56,13 +56,6 @@ void ChipTester::setAntialias(bool enabled)
setRenderHint(QPainter::Antialiasing, enabled);
}
-void ChipTester::setOpenGL(bool enabled)
-{
-#ifndef QT_NO_OPENGL
- setViewport(enabled ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : 0);
-#endif
-}
-
void ChipTester::setOperation(Operation operation)
{
this->operation = operation;
diff --git a/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.h b/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.h
index d85686c94e..e4c9197142 100644
--- a/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.h
+++ b/tests/benchmarks/widgets/graphicsview/qgraphicsview/chiptester/chiptester.h
@@ -51,7 +51,6 @@ public:
ChipTester(QWidget *parent = 0);
void setAntialias(bool enabled);
- void setOpenGL(bool enabled);
void runBenchmark();
void setOperation(Operation operation);
diff --git a/tests/benchmarks/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp b/tests/benchmarks/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
index 9bb5231528..25fc439883 100644
--- a/tests/benchmarks/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
+++ b/tests/benchmarks/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp
@@ -382,31 +382,22 @@ void tst_QGraphicsView::mapRectFromScene()
void tst_QGraphicsView::chipTester_data()
{
QTest::addColumn<bool>("antialias");
- QTest::addColumn<bool>("opengl");
QTest::addColumn<int>("operation");
- QTest::newRow("rotate, normal") << false << false << 0;
- QTest::newRow("rotate, normal, antialias") << true << false << 0;
- QTest::newRow("rotate, opengl") << false << true << 0;
- QTest::newRow("rotate, opengl, antialias") << true << true << 0;
- QTest::newRow("zoom, normal") << false << false << 1;
- QTest::newRow("zoom, normal, antialias") << true << false << 1;
- QTest::newRow("zoom, opengl") << false << true << 1;
- QTest::newRow("zoom, opengl, antialias") << true << true << 1;
- QTest::newRow("translate, normal") << false << false << 2;
- QTest::newRow("translate, normal, antialias") << true << false << 2;
- QTest::newRow("translate, opengl") << false << true << 2;
- QTest::newRow("translate, opengl, antialias") << true << true << 2;
+ QTest::newRow("rotate") << false << 0;
+ QTest::newRow("rotate, antialias") << true << 0;
+ QTest::newRow("zoom") << false << 1;
+ QTest::newRow("zoom, antialias") << true << 1;
+ QTest::newRow("translate") << false << 2;
+ QTest::newRow("translate, antialias") << true << 2;
}
void tst_QGraphicsView::chipTester()
{
QFETCH(bool, antialias);
- QFETCH(bool, opengl);
QFETCH(int, operation);
ChipTester tester;
tester.setAntialias(antialias);
- tester.setOpenGL(opengl);
tester.setOperation(ChipTester::Operation(operation));
tester.show();
QVERIFY(QTest::qWaitForWindowExposed(&tester));
diff --git a/tests/manual/cocoa/menurama/menurama.pro b/tests/manual/cocoa/menurama/menurama.pro
index da6f224e0d..f0928be31d 100644
--- a/tests/manual/cocoa/menurama/menurama.pro
+++ b/tests/manual/cocoa/menurama/menurama.pro
@@ -4,9 +4,7 @@
#
#-------------------------------------------------
-QT += core gui
-
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += core gui widgets
TARGET = Menurama
TEMPLATE = app
diff --git a/tests/manual/corelib/tools/qhash/main.cpp b/tests/manual/corelib/tools/qhash/main.cpp
index b2c40f2183..298d1777ea 100644
--- a/tests/manual/corelib/tools/qhash/main.cpp
+++ b/tests/manual/corelib/tools/qhash/main.cpp
@@ -27,7 +27,6 @@
****************************************************************************/
#include <QDebug>
-//#define QT_STRICT_ITERATORS
#include <QHash>
void testEraseNoError()
diff --git a/tests/manual/corelib/tools/qlist/main.cpp b/tests/manual/corelib/tools/qlist/main.cpp
index 3f8ade5778..0b54105f5e 100644
--- a/tests/manual/corelib/tools/qlist/main.cpp
+++ b/tests/manual/corelib/tools/qlist/main.cpp
@@ -26,7 +26,6 @@
**
****************************************************************************/
#include <QDebug>
-//#define QT_STRICT_ITERATORS
#include <QVector>
void testErase()
{
@@ -55,4 +54,4 @@ int main()
// testErase();
testInsert();
return 0;
-} \ No newline at end of file
+}
diff --git a/tests/manual/corelib/tools/qset/main.cpp b/tests/manual/corelib/tools/qset/main.cpp
index 1066e53e7d..701c8889db 100644
--- a/tests/manual/corelib/tools/qset/main.cpp
+++ b/tests/manual/corelib/tools/qset/main.cpp
@@ -27,7 +27,6 @@
****************************************************************************/
#include <QDebug>
-//#define QT_STRICT_ITERATORS
#include <QSet>
void testErase()
diff --git a/tests/manual/corelib/tools/qvarlengtharray/main.cpp b/tests/manual/corelib/tools/qvarlengtharray/main.cpp
index 8580d97a36..0544bb0c4b 100644
--- a/tests/manual/corelib/tools/qvarlengtharray/main.cpp
+++ b/tests/manual/corelib/tools/qvarlengtharray/main.cpp
@@ -27,7 +27,6 @@
****************************************************************************/
#include <QDebug>
-//#define QT_STRICT_ITERATORS
#include <QVarLengthArray>
void testErase()
diff --git a/tests/manual/corelib/tools/qvector/main.cpp b/tests/manual/corelib/tools/qvector/main.cpp
index e3dc89b149..1b35123f15 100644
--- a/tests/manual/corelib/tools/qvector/main.cpp
+++ b/tests/manual/corelib/tools/qvector/main.cpp
@@ -27,7 +27,6 @@
****************************************************************************/
#include <QDebug>
-//#define QT_STRICT_ITERATORS
#include <QVector>
void testErase()
diff --git a/tests/manual/diaglib/debugproxystyle.cpp b/tests/manual/diaglib/debugproxystyle.cpp
index ed35af5962..809613cd1d 100644
--- a/tests/manual/diaglib/debugproxystyle.cpp
+++ b/tests/manual/diaglib/debugproxystyle.cpp
@@ -68,8 +68,8 @@ QDebug operator<<(QDebug debug, const QStyleOption *option)
} else {
debug << "QStyleOption(";
}
- debug << "rect=" << option->rect.width() << 'x' << option->rect.height()
- << forcesign << option->rect.x() << option->rect.y() << noforcesign;
+ debug << "rect=" << option->rect.width() << 'x' << option->rect.height() << Qt::forcesign
+ << option->rect.x() << option->rect.y() << Qt::noforcesign;
if (option->state != QStyle::State_None)
debug << ", state=" << option->state;
#if QT_VERSION >= 0x050000
diff --git a/tests/manual/diaglib/diaglib.pri b/tests/manual/diaglib/diaglib.pri
index b57ee75841..ace9caecc6 100644
--- a/tests/manual/diaglib/diaglib.pri
+++ b/tests/manual/diaglib/diaglib.pri
@@ -17,20 +17,8 @@ win32:!winrt: {
SOURCES += $$PWD/nativewindowdump.cpp
}
-greaterThan(QT_MAJOR_VERSION, 4) {
- QT += gui-private core-private
- contains(QT, widgets) {
- HEADERS += \
- $$PWD/qwidgetdump.h \
- $$PWD/debugproxystyle.h \
- $$PWD/logwidget.h
-
- SOURCES += \
- $$PWD/qwidgetdump.cpp \
- $$PWD/debugproxystyle.cpp \
- $$PWD/logwidget.cpp
- }
-} else {
+QT += gui-private core-private
+contains(QT, widgets) {
HEADERS += \
$$PWD/qwidgetdump.h \
$$PWD/debugproxystyle.h \
@@ -40,14 +28,17 @@ greaterThan(QT_MAJOR_VERSION, 4) {
$$PWD/qwidgetdump.cpp \
$$PWD/debugproxystyle.cpp \
$$PWD/logwidget.cpp
+ QT += widgets-private
}
contains(QT, opengl) {
-HEADERS += \
- $$PWD/glinfo.h
+ HEADERS += \
+ $$PWD/glinfo.h
-SOURCES += \
- $$PWD/glinfo.cpp
+ SOURCES += \
+ $$PWD/glinfo.cpp
+
+ QT += opengl
}
DEFINES += QT_DIAG_LIB
diff --git a/tests/manual/diaglib/qwidgetdump.cpp b/tests/manual/diaglib/qwidgetdump.cpp
index 5a2966021b..926d2aaf35 100644
--- a/tests/manual/diaglib/qwidgetdump.cpp
+++ b/tests/manual/diaglib/qwidgetdump.cpp
@@ -86,14 +86,16 @@ static void dumpWidgetRecursion(QTextStream &str, const QWidget *w,
formatWidgetClass(str, w);
str << ' ' << (w->isVisible() ? "[visible] " : "[hidden] ");
if (const WId nativeWinId = w->internalWinId())
- str << "[native: " << hex << showbase << nativeWinId << dec << noshowbase << "] ";
+ str << "[native: " << Qt::hex << Qt::showbase << nativeWinId << Qt::dec << Qt::noshowbase
+ << "] ";
if (w->isWindow())
str << "[top] ";
str << (w->testAttribute(Qt::WA_Mapped) ? "[mapped] " : "[not mapped] ");
if (w->testAttribute(Qt::WA_DontCreateNativeAncestors))
str << "[NoNativeAncestors] ";
if (const int states = w->windowState())
- str << "windowState=" << hex << showbase << states << dec << noshowbase << ' ';
+ str << "windowState=" << Qt::hex << Qt::showbase << states << Qt::dec << Qt::noshowbase
+ << ' ';
formatRect(str, w->geometry());
if (w->isWindow()) {
str << ' ' << w->logicalDpiX() << "DPI";
diff --git a/tests/manual/diaglib/qwindowdump.cpp b/tests/manual/diaglib/qwindowdump.cpp
index 381b683359..2be26ff142 100644
--- a/tests/manual/diaglib/qwindowdump.cpp
+++ b/tests/manual/diaglib/qwindowdump.cpp
@@ -61,8 +61,8 @@ void formatObject(QTextStream &str, const QObject *o)
void formatRect(QTextStream &str, const QRect &geom)
{
- str << geom.width() << 'x' << geom.height()
- << forcesign << geom.x() << geom.y() << noforcesign;
+ str << geom.width() << 'x' << geom.height() << Qt::forcesign << geom.x() << geom.y()
+ << Qt::noforcesign;
}
#define debugType(s, type, typeConstant) \
@@ -75,7 +75,7 @@ if (flags & flagConstant) \
void formatWindowFlags(QTextStream &str, Qt::WindowFlags flags)
{
- str << showbase << hex << unsigned(flags) << dec << noshowbase;
+ str << Qt::showbase << Qt::hex << unsigned(flags) << Qt::dec << Qt::noshowbase;
const Qt::WindowFlags windowType = flags & Qt::WindowType_Mask;
debugFlag(str, flags, Qt::Window)
debugType(str, windowType, Qt::Dialog)
@@ -123,7 +123,8 @@ void formatWindow(QTextStream &str, const QWindow *w, FormatWindowOptions option
formatObject(str, w);
str << ' ' << (w->isVisible() ? "[visible] " : "[hidden] ");
if (const WId nativeWinId = pw ? pw->winId() : WId(0))
- str << "[native: " << hex << showbase << nativeWinId << dec << noshowbase << "] ";
+ str << "[native: " << Qt::hex << Qt::showbase << nativeWinId << Qt::dec << Qt::noshowbase
+ << "] ";
if (w->isTopLevel())
str << "[top] ";
if (w->isExposed())
diff --git a/tests/manual/diaglib/textdump.cpp b/tests/manual/diaglib/textdump.cpp
index 383ec4edb0..33455a2a56 100644
--- a/tests/manual/diaglib/textdump.cpp
+++ b/tests/manual/diaglib/textdump.cpp
@@ -408,8 +408,8 @@ struct FormattingContext
static void formatCharacter(QTextStream &str, const QChar &qc, FormattingContext &context)
{
const ushort unicode = qc.unicode();
- str << "U+" << qSetFieldWidth(4) << qSetPadChar('0') << uppercasedigits << hex << unicode
- << dec << qSetFieldWidth(0) << ' ';
+ str << "U+" << qSetFieldWidth(4) << qSetPadChar('0') << Qt::uppercasedigits << Qt::hex
+ << unicode << Qt::dec << qSetFieldWidth(0) << ' ';
const EnumLookup *specialChar = enumLookup(unicode, specialCharactersEnumLookup, sizeof(specialCharactersEnumLookup) / sizeof(EnumLookup));
if (specialChar)
@@ -477,7 +477,7 @@ QString dumpTextAsCode(const QString &text)
{
QString result;
QTextStream str(&result);
- str << " QString result;\n" << hex << showbase;
+ str << " QString result;\n" << Qt::hex << Qt::showbase;
for (QChar c : text)
str << " result += QChar(" << c.unicode() << ");\n";
str << '\n';
diff --git a/tests/manual/dialogs/dialogs.pro b/tests/manual/dialogs/dialogs.pro
index d765b8cf05..1beedc251e 100644
--- a/tests/manual/dialogs/dialogs.pro
+++ b/tests/manual/dialogs/dialogs.pro
@@ -1,9 +1,5 @@
-QT += core gui
-
-greaterThan(QT_MAJOR_VERSION, 4) {
- QT += widgets
- qtHaveModule(printsupport): QT += printsupport
-}
+QT += core gui widgets
+qtHaveModule(printsupport): QT += printsupport
TARGET = dialogs
TEMPLATE = app
diff --git a/tests/manual/dialogs/messageboxpanel.cpp b/tests/manual/dialogs/messageboxpanel.cpp
index 07b387f988..6a305523ea 100644
--- a/tests/manual/dialogs/messageboxpanel.cpp
+++ b/tests/manual/dialogs/messageboxpanel.cpp
@@ -39,6 +39,8 @@
#include <QLineEdit>
#include <QLabel>
#include <QCheckBox>
+#include <QRegularExpressionValidator>
+#include <QRegularExpression>
MessageBoxPanel::MessageBoxPanel(QWidget *parent) : QWidget(parent)
,m_iconComboBox(new QComboBox)
@@ -80,7 +82,7 @@ MessageBoxPanel::MessageBoxPanel(QWidget *parent) : QWidget(parent)
// buttons mask
optionsLayout->addWidget(new QLabel(QString::fromLatin1("Message box button mask (in hex)")));
- m_validator = new QRegExpValidator(QRegExp("0[xX]?[0-9a-fA-F]+"), this);
+ m_validator = new QRegularExpressionValidator(QRegularExpression("0[xX]?[0-9a-fA-F]+"), this);
m_buttonsMask->setMaxLength(10);
m_buttonsMask->setValidator(m_validator);
m_buttonsMask->setText(QString::fromLatin1("0x00300400"));
diff --git a/tests/manual/dialogs/printdialogpanel.cpp b/tests/manual/dialogs/printdialogpanel.cpp
index b7447e3d64..dcd8b43bf3 100644
--- a/tests/manual/dialogs/printdialogpanel.cpp
+++ b/tests/manual/dialogs/printdialogpanel.cpp
@@ -190,7 +190,8 @@ QTextStream &operator<<(QTextStream &s, const QSizeF &size)
QTextStream &operator<<(QTextStream &s, const QRectF &rect)
{
- s << rect.width() << 'x' << rect.height() << forcesign << rect.x() << rect.y() << noforcesign;
+ s << rect.width() << 'x' << rect.height() << Qt::forcesign << rect.x() << rect.y()
+ << Qt::noforcesign;
return s;
}
diff --git a/tests/manual/gestures/graphicsview/graphicsview.pro b/tests/manual/gestures/graphicsview/graphicsview.pro
index 9ecd0b372f..a20c4b3948 100644
--- a/tests/manual/gestures/graphicsview/graphicsview.pro
+++ b/tests/manual/gestures/graphicsview/graphicsview.pro
@@ -1,5 +1,7 @@
QT += widgets
+TARGET = tst_manual_graphicsview
+
SOURCES += main.cpp \
imageitem.cpp \
gestures.cpp \
diff --git a/tests/manual/highdpi/main.cpp b/tests/manual/highdpi/main.cpp
index 0c4b5c88ae..2a9fb6aa0c 100644
--- a/tests/manual/highdpi/main.cpp
+++ b/tests/manual/highdpi/main.cpp
@@ -75,7 +75,7 @@ static QTextStream &operator<<(QTextStream &str, const QSizeF &s)
static QTextStream &operator<<(QTextStream &str, const QRect &r)
{
- str << r.width() << 'x' << r.height() << forcesign << r.x() << r.y() << noforcesign;
+ str << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
return str;
}
diff --git a/tests/manual/manual.pro b/tests/manual/manual.pro
index 42f9878e44..de13bc799e 100644
--- a/tests/manual/manual.pro
+++ b/tests/manual/manual.pro
@@ -67,8 +67,4 @@ qtConfig(opengl) {
win32: SUBDIRS -= network_remote_stresstest network_stresstest
-lessThan(QT_MAJOR_VERSION, 5): SUBDIRS -= bearerex lance qnetworkaccessmanager/qget qmimedatabase qnetworkreply \
-qpainfo qscreen socketengine xembed-raster xembed-widgets windowtransparency \
-embeddedintoforeignwindow foreignwindows
-
qtConfig(vulkan): SUBDIRS += qvulkaninstance
diff --git a/tests/manual/qcursor/childwidget/childwidget.pro b/tests/manual/qcursor/childwidget/childwidget.pro
index 9ca41c5b4f..9492ec2280 100644
--- a/tests/manual/qcursor/childwidget/childwidget.pro
+++ b/tests/manual/qcursor/childwidget/childwidget.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET = childwidget
+TARGET = tst_manual_childwidget
INCLUDEPATH += .
QT += widgets
diff --git a/tests/manual/qcursor/qcursorhighdpi/qcursorhighdpi.pro b/tests/manual/qcursor/qcursorhighdpi/qcursorhighdpi.pro
index 3a8fc25b33..b0a5a75a67 100644
--- a/tests/manual/qcursor/qcursorhighdpi/qcursorhighdpi.pro
+++ b/tests/manual/qcursor/qcursorhighdpi/qcursorhighdpi.pro
@@ -1,6 +1,5 @@
TEMPLATE = app
-QT = core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += gui-private core-private widgets
+QT = core gui gui-private core-private widgets
CONFIG -= app_bundle
SOURCES += main.cpp
win32: LIBS += -lUser32
diff --git a/tests/manual/qdesktopservices/qdesktopservices.pro b/tests/manual/qdesktopservices/qdesktopservices.pro
index baa3c325ff..d2c5703870 100644
--- a/tests/manual/qdesktopservices/qdesktopservices.pro
+++ b/tests/manual/qdesktopservices/qdesktopservices.pro
@@ -1,6 +1,6 @@
QT += testlib
-TARGET = tst_qdesktopservices
+TARGET = tst_manual_qdesktopservices
CONFIG += cmdline
TEMPLATE = app
diff --git a/tests/manual/qhttpnetworkconnection/main.cpp b/tests/manual/qhttpnetworkconnection/main.cpp
index 5b670a51e2..d67d76699c 100644
--- a/tests/manual/qhttpnetworkconnection/main.cpp
+++ b/tests/manual/qhttpnetworkconnection/main.cpp
@@ -58,7 +58,7 @@ void tst_qhttpnetworkconnection::bigRemoteFile()
QVERIFY(!QTestEventLoop::instance().timeout());
size = reply->size();
delete reply;
- qDebug() << "Finished!" << endl;
+ qDebug() << "Finished!" << Qt::endl;
qDebug() << "Time:" << t.elapsed() << "msec";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (size / qreal(1024)) / (t.elapsed() / qreal(1000)) << "KB/sec";
diff --git a/tests/manual/qhttpnetworkconnection/qhttpnetworkconnection.pro b/tests/manual/qhttpnetworkconnection/qhttpnetworkconnection.pro
index 62838785d6..f6763e434d 100644
--- a/tests/manual/qhttpnetworkconnection/qhttpnetworkconnection.pro
+++ b/tests/manual/qhttpnetworkconnection/qhttpnetworkconnection.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET = tst_qhttpnetworkconnection
+TARGET = tst_manual_qhttpnetworkconnection
QT -= gui
QT += network testlib
diff --git a/tests/manual/qnetworkaccessmanager/qget/qget.cpp b/tests/manual/qnetworkaccessmanager/qget/qget.cpp
index 639506af63..14bdb589ff 100644
--- a/tests/manual/qnetworkaccessmanager/qget/qget.cpp
+++ b/tests/manual/qnetworkaccessmanager/qget/qget.cpp
@@ -39,33 +39,41 @@
void printShortUsage()
{
- qDebug() << QCoreApplication::applicationName() << " [options] [list of urls]" << endl
- << "Get one or more urls using QNetworkAccessManager" << endl
- << "--help to display detailed usage" << endl;
+ qDebug() << QCoreApplication::applicationName() << " [options] [list of urls]" << Qt::endl
+ << "Get one or more urls using QNetworkAccessManager" << Qt::endl
+ << "--help to display detailed usage" << Qt::endl;
}
void printUsage()
{
- qDebug() << QCoreApplication::applicationName() << " [options] [list of urls]" << endl
- << "Get one or more urls using QNetworkAccessManager" << endl
+ qDebug() << QCoreApplication::applicationName() << " [options] [list of urls]" << Qt::endl
+ << "Get one or more urls using QNetworkAccessManager" << Qt::endl
<< "Options:"
- << "--help This message" << endl
- << "--user=<username> Set username to use for authentication" << endl
- << "--password=<password> Set password to use for authentication" << endl
- << "--proxy-user=<username> Set username to use for proxy authentication" << endl
- << "--proxy-password=<password> Set password to use for proxy authentication" << endl
- << "--proxy=on Use system proxy (default)" << endl
- << "--proxy=off Don't use system proxy" << endl
- << "--proxy=<host:port>[,type] Use specified proxy" << endl
- << " ,http HTTP proxy (default)" << endl
- << " ,socks SOCKS5 proxy" << endl
- << " ,ftp FTP proxy" << endl
- << " ,httpcaching HTTP caching proxy (no CONNECT method)" << endl
- << "--headers=filename Set request headers from file contents" << endl
- << "--post=filename upload the file to the next url using HTTP POST" << endl
- << "--put=filename upload the file to the next url using HTTP PUT" << endl
- << "--content-type=<MIME> set content-type header for upload" << endl
- << "--serial don't run requests in parallel" << endl;
+ << "--help This message" << Qt::endl
+ << "--user=<username> Set username to use for authentication"
+ << Qt::endl
+ << "--password=<password> Set password to use for authentication"
+ << Qt::endl
+ << "--proxy-user=<username> Set username to use for proxy authentication"
+ << Qt::endl
+ << "--proxy-password=<password> Set password to use for proxy authentication"
+ << Qt::endl
+ << "--proxy=on Use system proxy (default)" << Qt::endl
+ << "--proxy=off Don't use system proxy" << Qt::endl
+ << "--proxy=<host:port>[,type] Use specified proxy" << Qt::endl
+ << " ,http HTTP proxy (default)" << Qt::endl
+ << " ,socks SOCKS5 proxy" << Qt::endl
+ << " ,ftp FTP proxy" << Qt::endl
+ << " ,httpcaching HTTP caching proxy (no CONNECT method)"
+ << Qt::endl
+ << "--headers=filename Set request headers from file contents"
+ << Qt::endl
+ << "--post=filename upload the file to the next url using HTTP POST"
+ << Qt::endl
+ << "--put=filename upload the file to the next url using HTTP PUT"
+ << Qt::endl
+ << "--content-type=<MIME> set content-type header for upload" << Qt::endl
+ << "--serial don't run requests in parallel" << Qt::endl;
}
int main(int argc, char *argv[])
diff --git a/tests/manual/qnetworkconfiguration/qnetworkconfiguration.pro b/tests/manual/qnetworkconfiguration/qnetworkconfiguration.pro
index 25ef41b92a..13c229e885 100644
--- a/tests/manual/qnetworkconfiguration/qnetworkconfiguration.pro
+++ b/tests/manual/qnetworkconfiguration/qnetworkconfiguration.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET = tst_qnetworkconfiguration
+TARGET = tst_manual_qnetworkconfiguration
QT -= gui
QT += network testlib
diff --git a/tests/manual/qnetworkconfigurationmanager/qnetworkconfigurationmanager.pro b/tests/manual/qnetworkconfigurationmanager/qnetworkconfigurationmanager.pro
index 8f9314cc96..072b330894 100644
--- a/tests/manual/qnetworkconfigurationmanager/qnetworkconfigurationmanager.pro
+++ b/tests/manual/qnetworkconfigurationmanager/qnetworkconfigurationmanager.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET = tst_qnetworkconfigurationmanager
+TARGET = tst_manual_qnetworkconfigurationmanager
QT -= gui
QT += network testlib
diff --git a/tests/manual/qnetworkreply/main.cpp b/tests/manual/qnetworkreply/main.cpp
index afac7a7095..01bd30a854 100644
--- a/tests/manual/qnetworkreply/main.cpp
+++ b/tests/manual/qnetworkreply/main.cpp
@@ -58,9 +58,6 @@ private slots:
void setSslConfiguration_data();
void setSslConfiguration();
void uploadToFacebook();
- void spdy_data();
- void spdy();
- void spdyMultipleRequestsPerHost();
void proxyAuthentication_data();
void proxyAuthentication();
void authentication();
@@ -290,126 +287,6 @@ void tst_qnetworkreply::uploadToFacebook()
}
}
-void tst_qnetworkreply::spdy_data()
-{
- QTest::addColumn<QString>("host");
- QTest::addColumn<bool>("setAttribute");
- QTest::addColumn<bool>("enabled");
- QTest::addColumn<QByteArray>("expectedProtocol");
-
- QList<QString> hosts = QList<QString>()
- << QStringLiteral("www.google.com") // sends SPDY and 30x redirect
- << QStringLiteral("www.google.de") // sends SPDY and 200 OK
- << QStringLiteral("mail.google.com") // sends SPDY and 200 OK
- << QStringLiteral("www.youtube.com") // sends SPDY and 200 OK
- << QStringLiteral("www.dropbox.com") // no SPDY, but NPN which selects HTTP
- << QStringLiteral("www.facebook.com") // sends SPDY and 200 OK
- << QStringLiteral("graph.facebook.com") // sends SPDY and 200 OK
- << QStringLiteral("www.twitter.com") // sends SPDY and 30x redirect
- << QStringLiteral("twitter.com") // sends SPDY and 200 OK
- << QStringLiteral("api.twitter.com"); // sends SPDY and 200 OK
-
- foreach (const QString &host, hosts) {
- QByteArray tag = host.toLocal8Bit();
- tag.append("-not-used");
- QTest::newRow(tag)
- << QStringLiteral("https://") + host
- << false
- << false
- << QByteArray();
-
- tag = host.toLocal8Bit();
- tag.append("-disabled");
- QTest::newRow(tag)
- << QStringLiteral("https://") + host
- << true
- << false
- << QByteArray();
-
- if (host != QStringLiteral("api.twitter.com")) { // they don't offer an API over HTTP
- tag = host.toLocal8Bit();
- tag.append("-no-https-url");
- QTest::newRow(tag)
- << QStringLiteral("http://") + host
- << true
- << true
- << QByteArray();
- }
-
-#ifndef QT_NO_OPENSSL
- tag = host.toLocal8Bit();
- tag.append("-enabled");
- QTest::newRow(tag)
- << QStringLiteral("https://") + host
- << true
- << true
- << (host == QStringLiteral("www.dropbox.com")
- ? QByteArray(QSslConfiguration::NextProtocolHttp1_1)
- : QByteArray(QSslConfiguration::NextProtocolSpdy3_0));
-#endif // QT_NO_OPENSSL
- }
-}
-
-void tst_qnetworkreply::spdy()
-{
-#if defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) && OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
-
- m_manager.clearAccessCache();
-
- QFETCH(QString, host);
- QUrl url(host);
- QNetworkRequest request(url);
-
- QFETCH(bool, setAttribute);
- QFETCH(bool, enabled);
- if (setAttribute) {
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, QVariant(enabled));
- }
-
- QNetworkReply *reply = m_manager.get(request);
- QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
-
- QSignalSpy metaDataChangedSpy(reply, SIGNAL(metaDataChanged()));
- QSignalSpy readyReadSpy(reply, SIGNAL(readyRead()));
- QSignalSpy finishedSpy(reply, SIGNAL(finished()));
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QFETCH(QByteArray, expectedProtocol);
-
- bool expectedSpdyUsed = (expectedProtocol == QSslConfiguration::NextProtocolSpdy3_0);
- QCOMPARE(reply->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), expectedSpdyUsed);
-
- QCOMPARE(metaDataChangedSpy.count(), 1);
- QCOMPARE(finishedSpy.count(), 1);
- QCOMPARE(finishedManagerSpy.count(), 1);
-
- QUrl redirectUrl = reply->header(QNetworkRequest::LocationHeader).toUrl();
- QByteArray content = reply->readAll();
-
- int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- QVERIFY(statusCode >= 200 && statusCode < 500);
- if (statusCode == 200 || statusCode >= 400) {
- QVERIFY(readyReadSpy.count() > 0);
- QVERIFY(!content.isEmpty());
- } else if (statusCode >= 300 && statusCode < 400) {
- QVERIFY(!redirectUrl.isEmpty());
- }
-
- QSslConfiguration::NextProtocolNegotiationStatus expectedStatus =
- expectedProtocol.isNull() ? QSslConfiguration::NextProtocolNegotiationNone
- : QSslConfiguration::NextProtocolNegotiationNegotiated;
- QCOMPARE(reply->sslConfiguration().nextProtocolNegotiationStatus(),
- expectedStatus);
-
- QCOMPARE(reply->sslConfiguration().nextNegotiatedProtocol(), expectedProtocol);
-#else
- QSKIP("Qt built withouth OpenSSL, or the OpenSSL version is too old");
-#endif // defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) ...
-}
-
void tst_qnetworkreply::spdyReplyFinished()
{
static int finishedCount = 0;
@@ -419,85 +296,6 @@ void tst_qnetworkreply::spdyReplyFinished()
QTestEventLoop::instance().exitLoop();
}
-void tst_qnetworkreply::spdyMultipleRequestsPerHost()
-{
-#if defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) && OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
-
- QList<QNetworkRequest> requests;
- requests
- << QNetworkRequest(QUrl("https://www.facebook.com"))
- << QNetworkRequest(QUrl("https://www.facebook.com/images/fb_icon_325x325.png"))
-
- << QNetworkRequest(QUrl("https://www.google.de"))
- << QNetworkRequest(QUrl("https://www.google.de/preferences?hl=de"))
- << QNetworkRequest(QUrl("https://www.google.de/intl/de/policies/?fg=1"))
- << QNetworkRequest(QUrl("https://www.google.de/intl/de/about.html?fg=1"))
- << QNetworkRequest(QUrl("https://www.google.de/services/?fg=1"))
- << QNetworkRequest(QUrl("https://www.google.de/intl/de/ads/?fg=1"))
-
- << QNetworkRequest(QUrl("https://i1.ytimg.com/li/tnHdj3df7iM/default.jpg"))
- << QNetworkRequest(QUrl("https://i1.ytimg.com/li/7Dr1BKwqctY/default.jpg"))
- << QNetworkRequest(QUrl("https://i1.ytimg.com/li/hfZhJdhTqX8/default.jpg"))
- << QNetworkRequest(QUrl("https://i1.ytimg.com/vi/14Nprh8163I/hqdefault.jpg"))
- ;
- QList<QNetworkReply *> replies;
- QList<QSignalSpy *> metaDataChangedSpies;
- QList<QSignalSpy *> readyReadSpies;
- QList<QSignalSpy *> finishedSpies;
-
- QSignalSpy finishedManagerSpy(&m_manager, SIGNAL(finished(QNetworkReply*)));
-
- foreach (QNetworkRequest request, requests) {
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true);
- QNetworkReply *reply = m_manager.get(request);
- QObject::connect(reply, SIGNAL(finished()), this, SLOT(spdyReplyFinished()));
- replies << reply;
- QSignalSpy *metaDataChangedSpy = new QSignalSpy(reply, SIGNAL(metaDataChanged()));
- metaDataChangedSpies << metaDataChangedSpy;
- QSignalSpy *readyReadSpy = new QSignalSpy(reply, SIGNAL(readyRead()));
- readyReadSpies << readyReadSpy;
- QSignalSpy *finishedSpy = new QSignalSpy(reply, SIGNAL(finished()));
- finishedSpies << finishedSpy;
- }
-
- QCOMPARE(requests.count(), replies.count());
-
- QTestEventLoop::instance().enterLoop(15);
- QVERIFY(!QTestEventLoop::instance().timeout());
-
- QCOMPARE(finishedManagerSpy.count(), requests.count());
-
- for (int a = 0; a < replies.count(); ++a) {
-
- QCOMPARE(replies.at(a)->sslConfiguration().nextProtocolNegotiationStatus(),
- QSslConfiguration::NextProtocolNegotiationNegotiated);
- QCOMPARE(replies.at(a)->sslConfiguration().nextNegotiatedProtocol(),
- QByteArray(QSslConfiguration::NextProtocolSpdy3_0));
-
- QCOMPARE(replies.at(a)->error(), QNetworkReply::NoError);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::SpdyWasUsedAttribute).toBool(), true);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::ConnectionEncryptedAttribute).toBool(), true);
- QCOMPARE(replies.at(a)->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
-
- QByteArray content = replies.at(a)->readAll();
- QVERIFY(content.count() > 0);
-
- QCOMPARE(metaDataChangedSpies.at(a)->count(), 1);
- metaDataChangedSpies.at(a)->deleteLater();
-
- QCOMPARE(finishedSpies.at(a)->count(), 1);
- finishedSpies.at(a)->deleteLater();
-
- QVERIFY(readyReadSpies.at(a)->count() > 0);
- readyReadSpies.at(a)->deleteLater();
-
- replies.at(a)->deleteLater();
- }
-#else
- QSKIP("Qt built withouth OpenSSL, or the OpenSSL version is too old");
-#endif // defined(QT_BUILD_INTERNAL) && !defined(QT_NO_SSL) ...
-}
-
void tst_qnetworkreply::proxyAuthentication_data()
{
QTest::addColumn<QUrl>("url");
@@ -586,7 +384,7 @@ void tst_qnetworkreply::npnWithEmptyList() // QTBUG-40714
QUrl url(QStringLiteral("https://www.ossifrage.net/"));
QNetworkRequest request(url);
- request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, QVariant(true));
+ request.setAttribute(QNetworkRequest::Http2AllowedAttribute, QVariant(true));
QNetworkReply *reply = m_manager.get(request);
QObject::connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
diff --git a/tests/manual/qnetworkreply/qnetworkreply.pro b/tests/manual/qnetworkreply/qnetworkreply.pro
index eddcbdff1d..2457acd749 100644
--- a/tests/manual/qnetworkreply/qnetworkreply.pro
+++ b/tests/manual/qnetworkreply/qnetworkreply.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET = tst_qnetworkreply
+TARGET = tst_manual_qnetworkreply
QT -= gui
QT += core-private network network-private testlib
diff --git a/tests/manual/qscreen/main.cpp b/tests/manual/qscreen/main.cpp
index 0728d66bf9..ab92216d22 100644
--- a/tests/manual/qscreen/main.cpp
+++ b/tests/manual/qscreen/main.cpp
@@ -192,15 +192,15 @@ static inline QString msgScreenChange(const QWidget *w, const QScreen *oldScreen
if (!newScreen) {
result = QLatin1String("Screen changed --> null");
} else if (!oldScreen) {
- QTextStream(&result) << "Screen changed null --> \""
- << newScreen->name() << "\" at " << pos.x() << ',' << pos.y() << " geometry: "
- << geometry.width() << 'x' << geometry.height() << forcesign << geometry.x()
- << geometry.y() << '.';
+ QTextStream(&result) << "Screen changed null --> \"" << newScreen->name() << "\" at "
+ << pos.x() << ',' << pos.y() << " geometry: " << geometry.width()
+ << 'x' << geometry.height() << Qt::forcesign << geometry.x()
+ << geometry.y() << '.';
} else {
QTextStream(&result) << "Screen changed \"" << oldScreen->name() << "\" --> \""
- << newScreen->name() << "\" at " << pos.x() << ',' << pos.y() << " geometry: "
- << geometry.width() << 'x' << geometry.height() << forcesign << geometry.x()
- << geometry.y() << '.';
+ << newScreen->name() << "\" at " << pos.x() << ',' << pos.y()
+ << " geometry: " << geometry.width() << 'x' << geometry.height()
+ << Qt::forcesign << geometry.x() << geometry.y() << '.';
}
return result;
}
diff --git a/tests/manual/qssloptions/main.cpp b/tests/manual/qssloptions/main.cpp
index 0f06071b41..cc65c57f33 100644
--- a/tests/manual/qssloptions/main.cpp
+++ b/tests/manual/qssloptions/main.cpp
@@ -37,13 +37,13 @@ int main(int argc, char **argv)
if (argc < 3) {
QTextStream out(stdout);
- out << "Usage: " << argv[0] << " host port [options]" << endl;
- out << "The options can be one or more of the following:" << endl;
- out << "enable_empty_fragments" << endl;
- out << "disable_session_tickets" << endl;
- out << "disable_compression" << endl;
- out << "disable_sni" << endl;
- out << "enable_unsafe_reneg" << endl;
+ out << "Usage: " << argv[0] << " host port [options]" << Qt::endl;
+ out << "The options can be one or more of the following:" << Qt::endl;
+ out << "enable_empty_fragments" << Qt::endl;
+ out << "disable_session_tickets" << Qt::endl;
+ out << "disable_compression" << Qt::endl;
+ out << "disable_sni" << Qt::endl;
+ out << "enable_unsafe_reneg" << Qt::endl;
return 1;
}
diff --git a/tests/manual/qsslsocket/qsslsocket.pro b/tests/manual/qsslsocket/qsslsocket.pro
index c297d887ba..511d31898f 100644
--- a/tests/manual/qsslsocket/qsslsocket.pro
+++ b/tests/manual/qsslsocket/qsslsocket.pro
@@ -3,4 +3,4 @@ CONFIG += testcase
SOURCES += main.cpp
QT = core network testlib
-TARGET = tst_qsslsocket
+TARGET = tst_manual_qsslsocket
diff --git a/tests/manual/qtexteditlist/qtexteditlist.pro b/tests/manual/qtexteditlist/qtexteditlist.pro
index 953333f3ee..972e054445 100644
--- a/tests/manual/qtexteditlist/qtexteditlist.pro
+++ b/tests/manual/qtexteditlist/qtexteditlist.pro
@@ -1,6 +1,6 @@
#This project can be used to verify QTBUG-5111 case.
QT += core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += widgets
TARGET = qtexteditlist
TEMPLATE = app
SOURCES += main.cpp widget.cpp
diff --git a/tests/manual/qtexttableborders/qtexttableborders.pro b/tests/manual/qtexttableborders/qtexttableborders.pro
index 7e454f978d..3805ac6ed0 100644
--- a/tests/manual/qtexttableborders/qtexttableborders.pro
+++ b/tests/manual/qtexttableborders/qtexttableborders.pro
@@ -1,7 +1,6 @@
#This project can be used to verify QTBUG-36152 case.
-QT += core gui printsupport
+QT += core gui printsupport widgets
CONFIG += c++11
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = qtexttableborders
TEMPLATE = app
SOURCES += main.cpp widget.cpp
diff --git a/tests/manual/qtouchevent/qtouchevent.pro b/tests/manual/qtouchevent/qtouchevent.pro
index 81384eaf24..4ba921d301 100644
--- a/tests/manual/qtouchevent/qtouchevent.pro
+++ b/tests/manual/qtouchevent/qtouchevent.pro
@@ -1,5 +1,4 @@
-QT += testlib
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += testlib widgets
SOURCES = main.cpp \
touchwidget.cpp
FORMS += form.ui
diff --git a/tests/manual/repaint/mainwindow/mainwindow.pro b/tests/manual/repaint/mainwindow/mainwindow.pro
index f20e5fe402..419436032c 100644
--- a/tests/manual/repaint/mainwindow/mainwindow.pro
+++ b/tests/manual/repaint/mainwindow/mainwindow.pro
@@ -1,3 +1,4 @@
+TARGET = tst_manual_mainwindow
QT += widgets
HEADERS += ../shared/shared.h
SOURCES += main.cpp
diff --git a/tests/manual/repaint/scrollarea/scrollarea.pro b/tests/manual/repaint/scrollarea/scrollarea.pro
index f20e5fe402..deff158cce 100644
--- a/tests/manual/repaint/scrollarea/scrollarea.pro
+++ b/tests/manual/repaint/scrollarea/scrollarea.pro
@@ -1,3 +1,4 @@
QT += widgets
+TARGET = tst_manual_scrollarea
HEADERS += ../shared/shared.h
SOURCES += main.cpp
diff --git a/tests/manual/repaint/toplevel/toplevel.pro b/tests/manual/repaint/toplevel/toplevel.pro
index a881c24f56..d142fd19bb 100644
--- a/tests/manual/repaint/toplevel/toplevel.pro
+++ b/tests/manual/repaint/toplevel/toplevel.pro
@@ -1,5 +1,6 @@
CONFIG += console
QT += widgets
+TARGET = tst_manual_toplevel
HEADERS += ../shared/shared.h
SOURCES += main.cpp
diff --git a/tests/manual/touch/main.cpp b/tests/manual/touch/main.cpp
index a244230a22..8572e18955 100644
--- a/tests/manual/touch/main.cpp
+++ b/tests/manual/touch/main.cpp
@@ -526,7 +526,7 @@ void MainWindow::updateScreenLabel()
const QRect geometry = screen->geometry();
const qreal dpr = screen->devicePixelRatio();
str << '"' << screen->name() << "\" " << geometry.width() << 'x' << geometry.height()
- << forcesign << geometry.x() << geometry.y() << noforcesign;
+ << Qt::forcesign << geometry.x() << geometry.y() << Qt::noforcesign;
if (!qFuzzyCompare(dpr, qreal(1)))
str << ", dpr=" << dpr;
m_screenLabel->setText(text);
diff --git a/tests/manual/touch/touch.pro b/tests/manual/touch/touch.pro
index fcb3c47f43..08e3fdcd71 100644
--- a/tests/manual/touch/touch.pro
+++ b/tests/manual/touch/touch.pro
@@ -1,5 +1,4 @@
TEMPLATE = app
-QT = core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT = core gui widgets
CONFIG -= app_bundle
SOURCES += main.cpp
diff --git a/tests/manual/unc/unc.pro b/tests/manual/unc/unc.pro
index 977bd0c177..a1536a03db 100644
--- a/tests/manual/unc/unc.pro
+++ b/tests/manual/unc/unc.pro
@@ -1,5 +1,4 @@
-QT += core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += core gui widgets
TEMPLATE = app
diff --git a/tests/manual/widgetgrab/widgetgrab.pro b/tests/manual/widgetgrab/widgetgrab.pro
index d206fb1df1..c354711197 100644
--- a/tests/manual/widgetgrab/widgetgrab.pro
+++ b/tests/manual/widgetgrab/widgetgrab.pro
@@ -1,9 +1,5 @@
-QT += core gui
+QT += core gui widgets
TARGET = widgetgrab
TEMPLATE = app
SOURCES += main.cpp
-
-greaterThan(QT_MAJOR_VERSION, 4) {
- QT += widgets
-}
diff --git a/tests/manual/widgets/styles/styles.pro b/tests/manual/widgets/styles/styles.pro
index d302ae0691..1830e21705 100644
--- a/tests/manual/widgets/styles/styles.pro
+++ b/tests/manual/widgets/styles/styles.pro
@@ -1,5 +1,6 @@
TEMPLATE = app
QT = widgets
+TARGET = tst_manual_styles
CONFIG += cmdline
CONFIG += c++11
diff --git a/tests/manual/widgets/widgets.pro b/tests/manual/widgets/widgets.pro
index e3942a49e9..03aaa880b8 100644
--- a/tests/manual/widgets/widgets.pro
+++ b/tests/manual/widgets/widgets.pro
@@ -1,3 +1,2 @@
TEMPLATE = subdirs
-SUBDIRS = itemviews qgraphicsview kernel widgets
-greaterThan(QT_MAJOR_VERSION, 4): SUBDIRS += styles
+SUBDIRS = itemviews qgraphicsview kernel widgets styles
diff --git a/tests/manual/widgets/widgets/bigmenucreator/bigmenucreator.pro b/tests/manual/widgets/widgets/bigmenucreator/bigmenucreator.pro
index 69fbea3834..408dab6482 100644
--- a/tests/manual/widgets/widgets/bigmenucreator/bigmenucreator.pro
+++ b/tests/manual/widgets/widgets/bigmenucreator/bigmenucreator.pro
@@ -4,9 +4,7 @@
#
#-------------------------------------------------
-QT += core gui
-
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += core gui widgets
TARGET = BigMenuCreator
TEMPLATE = app
diff --git a/tests/manual/windowchildgeometry/windowchildgeometry.pro b/tests/manual/windowchildgeometry/windowchildgeometry.pro
index 921acd8a4e..7722547ce7 100644
--- a/tests/manual/windowchildgeometry/windowchildgeometry.pro
+++ b/tests/manual/windowchildgeometry/windowchildgeometry.pro
@@ -1,5 +1,4 @@
-QT += core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += core gui widgets
TARGET = windowchildgeometry
TEMPLATE = app
diff --git a/tests/manual/windowflags/previewwindow.cpp b/tests/manual/windowflags/previewwindow.cpp
index ef3966830b..893dbc9a41 100644
--- a/tests/manual/windowflags/previewwindow.cpp
+++ b/tests/manual/windowflags/previewwindow.cpp
@@ -48,7 +48,8 @@ void PreviewWindow::paintEvent(QPaintEvent *event)
static void formatWindowFlags(QTextStream &str, Qt::WindowFlags flags)
{
- str << "Window flags: " << hex << showbase << unsigned(flags) << noshowbase << dec << ' ';
+ str << "Window flags: " << Qt::hex << Qt::showbase << unsigned(flags) << Qt::noshowbase
+ << Qt::dec << ' ';
switch (flags & Qt::WindowType_Mask) {
case Qt::Window:
str << "Qt::Window";
@@ -125,7 +126,8 @@ static void formatWindowFlags(QTextStream &str, Qt::WindowFlags flags)
static void formatWindowStates(QTextStream &str, Qt::WindowStates states)
{
- str << "Window states: " << hex << showbase << unsigned(states) << noshowbase << dec << ' ';
+ str << "Window states: " << Qt::hex << Qt::showbase << unsigned(states) << Qt::noshowbase
+ << Qt::dec << ' ';
if (states & Qt::WindowActive) {
str << "Qt::WindowActive ";
states &= ~Qt::WindowActive;
@@ -150,7 +152,7 @@ static void formatWindowStates(QTextStream &str, Qt::WindowStates states)
QTextStream &operator<<(QTextStream &str, const QRect &r)
{
- str << r.width() << 'x' << r.height() << forcesign << r.x() << r.y() << noforcesign;
+ str << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
return str;
}
diff --git a/tests/manual/windowflags/windowflags.pro b/tests/manual/windowflags/windowflags.pro
index ba0f75b65c..4cd60ae6cf 100644
--- a/tests/manual/windowflags/windowflags.pro
+++ b/tests/manual/windowflags/windowflags.pro
@@ -1,3 +1,5 @@
+TARGET = tst_manual_windowflags
+
HEADERS = controllerwindow.h \
previewwindow.h \
controls.h
@@ -7,4 +9,4 @@ SOURCES = controllerwindow.cpp \
main.cpp \
controls.cpp
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += widgets
diff --git a/tests/manual/windowgeometry/windowgeometry.pro b/tests/manual/windowgeometry/windowgeometry.pro
index e717799649..ee99f1950c 100644
--- a/tests/manual/windowgeometry/windowgeometry.pro
+++ b/tests/manual/windowgeometry/windowgeometry.pro
@@ -1,5 +1,4 @@
-QT += core gui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+QT += core gui widgets
TARGET = windowgeometry
TEMPLATE = app
diff --git a/tests/manual/windowmodality/windowmodality.pro b/tests/manual/windowmodality/windowmodality.pro
index b29e939d27..973579c508 100644
--- a/tests/manual/windowmodality/windowmodality.pro
+++ b/tests/manual/windowmodality/windowmodality.pro
@@ -1,3 +1,3 @@
SOURCES = main.cpp
FORMS = widget.ui dialog.ui
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport
+QT += widgets printsupport
diff --git a/tests/manual/xembed-raster/xembed-raster.pro b/tests/manual/xembed-raster/xembed-raster.pro
index adaf9c4d25..4c9fee07b8 100644
--- a/tests/manual/xembed-raster/xembed-raster.pro
+++ b/tests/manual/xembed-raster/xembed-raster.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET= rasterwindow
+TARGET= tst_manual_rasterwindow
QT += gui
SOURCES += \
diff --git a/tests/manual/xembed-widgets/xembed-widgets.pro b/tests/manual/xembed-widgets/xembed-widgets.pro
index e406ee47fd..28d13d5b61 100644
--- a/tests/manual/xembed-widgets/xembed-widgets.pro
+++ b/tests/manual/xembed-widgets/xembed-widgets.pro
@@ -1,5 +1,5 @@
TEMPLATE = app
-TARGET= lineedits
+TARGET= tst_manual_lineedits
QT += widgets
SOURCES += \