From 17032c4d64cc4cf32580ff994e443f16126ad7a3 Mon Sep 17 00:00:00 2001 From: Assam Boudjelthia Date: Mon, 9 Sep 2019 10:20:51 +0300 Subject: [PATCH 01/41] Re-add tst_selftests "crashes old stdout txt" on QEMU The test is not failing anymore on QEMU targets. This partially reverts commit 71bd06d516a2410ae0ea698e79dcb94aba9bc5b4. Fixes: QTBUG-71915 Change-Id: I68593edf0ec245e14879833c8aa90661a3c2e227 Reviewed-by: Liang Qi --- tests/auto/testlib/selftests/tst_selftests.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/auto/testlib/selftests/tst_selftests.cpp b/tests/auto/testlib/selftests/tst_selftests.cpp index 3ef15b92618..e8d6fe228b5 100644 --- a/tests/auto/testlib/selftests/tst_selftests.cpp +++ b/tests/auto/testlib/selftests/tst_selftests.cpp @@ -682,9 +682,6 @@ static inline QByteArray msgProcessError(const QString &binary, const QStringLis void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& loggers, QStringList const& arguments, bool crashes) { - if (EmulationDetector::isRunningArmOnX86() && (subdir == "crashes")) - QSKIP("Skipping \"crashes\" due to QTBUG-71915"); - #if defined(__GNUC__) && defined(__i386) && defined(Q_OS_LINUX) if (arguments.contains("-callgrind")) { QProcess checkProcess; From 97b9af1519ad3809a7900f0ac1f5710a439c87c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Fri, 6 Sep 2019 13:51:37 +0200 Subject: [PATCH 02/41] Schannel: unbreak renegotiation (and likely gracious shutdown) The reason it wasn't working before was a couple of things: 1. Due to an extra 'else' it would not process the SEC_I_RENEGOTIATE or SEC_I_CONTEXT_EXPIRED branch. 2. The peerCertVerified boolean was not only wrong, but also broke renegotiation even if the 'else' wasn't there. My previous attempt to fix it ended up being a noop, so: Reverts e21fa577dde32849fdaa744f30ad3b23d63b7214 Change-Id: Ifbad55d4bb066b7566bb88cead48e329cbd574f9 Reviewed-by: Timur Pocheptsov --- src/network/ssl/qsslsocket_schannel.cpp | 19 ++++--------------- src/network/ssl/qsslsocket_schannel_p.h | 1 - 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/src/network/ssl/qsslsocket_schannel.cpp b/src/network/ssl/qsslsocket_schannel.cpp index 88f66ac4ead..37705b03a1d 100644 --- a/src/network/ssl/qsslsocket_schannel.cpp +++ b/src/network/ssl/qsslsocket_schannel.cpp @@ -1069,7 +1069,6 @@ bool QSslSocketBackendPrivate::verifyHandshake() } schannelState = SchannelState::Done; - peerCertVerified = true; return true; } @@ -1152,7 +1151,6 @@ void QSslSocketBackendPrivate::reset() connectionEncrypted = false; shutdown = false; - peerCertVerified = false; renegotiating = false; } @@ -1315,7 +1313,9 @@ void QSslSocketBackendPrivate::transmit() #endif intermediateBuffer = ciphertext.right(int(dataBuffer[3].cbBuffer)); } - } else if (status == SEC_E_INCOMPLETE_MESSAGE) { + } + + if (status == SEC_E_INCOMPLETE_MESSAGE) { // Need more data before we can decrypt.. to the buffer it goes! #ifdef QSSLSOCKET_DEBUG qCDebug(lcSsl, "We didn't have enough data to decrypt anything, will try again!"); @@ -1361,17 +1361,6 @@ void QSslSocketBackendPrivate::transmit() schannelState = SchannelState::Renegotiate; renegotiating = true; - if (dataBuffer[3].BufferType == SECBUFFER_EXTRA) { - // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel - // dataBuffer[3].cbBuffer indicates the amount of bytes _NOT_ processed, - // the rest need to be stored. -#ifdef QSSLSOCKET_DEBUG - qCDebug(lcSsl) << "We've got excess data, moving it to the intermediate buffer:" - << dataBuffer[3].cbBuffer << "bytes"; -#endif - intermediateBuffer = ciphertext.right(int(dataBuffer[3].cbBuffer)); - } - // We need to call 'continueHandshake' or else there's no guarantee it ever gets called continueHandshake(); break; @@ -1537,7 +1526,7 @@ void QSslSocketBackendPrivate::continueHandshake() case SchannelState::VerifyHandshake: // if we're in shutdown or renegotiating then we might not need to verify // (since we already did) - if (!peerCertVerified && !verifyHandshake()) { + if (!verifyHandshake()) { shutdown = true; // Skip sending shutdown alert q->abort(); // We don't want to send buffered data disconnectFromHost(); diff --git a/src/network/ssl/qsslsocket_schannel_p.h b/src/network/ssl/qsslsocket_schannel_p.h index 9879e2fc607..6ab200e1f94 100644 --- a/src/network/ssl/qsslsocket_schannel_p.h +++ b/src/network/ssl/qsslsocket_schannel_p.h @@ -147,7 +147,6 @@ private: ULONG contextAttributes = 0; bool renegotiating = false; - bool peerCertVerified = false; }; QT_END_NAMESPACE From e5e8f1d67ce5f74ccb345086667933266543fd51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Fri, 6 Sep 2019 13:01:43 +0200 Subject: [PATCH 03/41] Schannel: handle SEC_E_INCOMPLETE_DATA in acceptContext It's not a failure state, we just need more data. It is handled properly in other functions. Change-Id: I9450a78c71a3f4fe9506a7a79de6efa2db08697c Reviewed-by: Timur Pocheptsov --- src/network/ssl/qsslsocket_schannel.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/network/ssl/qsslsocket_schannel.cpp b/src/network/ssl/qsslsocket_schannel.cpp index 37705b03a1d..339ecf4da22 100644 --- a/src/network/ssl/qsslsocket_schannel.cpp +++ b/src/network/ssl/qsslsocket_schannel.cpp @@ -828,12 +828,17 @@ bool QSslSocketBackendPrivate::acceptContext() &expiry // ptsTimeStamp ); + if (status == SEC_E_INCOMPLETE_MESSAGE) { + // Need more data + return true; + } + if (inBuffers[1].BufferType == SECBUFFER_EXTRA) { // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel // inBuffers[1].cbBuffer indicates the amount of bytes _NOT_ processed, the rest need to // be stored. intermediateBuffer = intermediateBuffer.right(int(inBuffers[1].cbBuffer)); - } else if (status != SEC_E_INCOMPLETE_MESSAGE) { + } else { /* No 'extra' data, message not incomplete */ intermediateBuffer.clear(); } From be21ff11b7c25e3f6682c7987052557eca48e907 Mon Sep 17 00:00:00 2001 From: Alexandru Croitor Date: Tue, 10 Sep 2019 16:37:45 +0200 Subject: [PATCH 04/41] CMake: Fix usage of debug frameworks on macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If an app wants use a debug framework of Qt, it is still expected that the app should link against the release version, and just set DYLD_IMAGE_SUFFIX=_debug when running the app. This was not the case before, where the CMake Config files told CMake to link explicitly against the debug libraries. This caused crashes due to the Qt plugin loader mechanism still trying to find a release platform plugin, which in turn would load release libraries, and thus the application would end up loading both debug and release plugins. Make sure the Config files in a framework case always reference the release libraries (even though this might be counter intuitive). Otherwise users of the Debug Config files would always get crashes. Fixes: QTBUG-78131 Change-Id: I88b1dc421477ad186012ca67b328a891128eb568 Reviewed-by: Cristian Adam Reviewed-by: Tor Arne Vestbø --- mkspecs/features/create_cmake.prf | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mkspecs/features/create_cmake.prf b/mkspecs/features/create_cmake.prf index 376a7ded5d8..314cd5cc67a 100644 --- a/mkspecs/features/create_cmake.prf +++ b/mkspecs/features/create_cmake.prf @@ -254,7 +254,8 @@ mac { CMAKE_PRL_FILE_LOCATION_RELEASE = lib$${CMAKE_QT_STEM}.prl } else { qt_framework { - CMAKE_LIB_FILE_LOCATION_DEBUG = $${CMAKE_QT_STEM}.framework/$${CMAKE_QT_STEM}_debug + # Intentionally there is no '_debug' infix for framework builds. + CMAKE_LIB_FILE_LOCATION_DEBUG = $${CMAKE_QT_STEM}.framework/$${CMAKE_QT_STEM} CMAKE_LIB_FILE_LOCATION_RELEASE = $${CMAKE_QT_STEM}.framework/$${CMAKE_QT_STEM} CMAKE_BUILD_IS_FRAMEWORK = "true" } else { From 0fd6595d5e63fe1db429a0f242c7e98c6d2855f7 Mon Sep 17 00:00:00 2001 From: Timur Pocheptsov Date: Tue, 10 Sep 2019 09:39:59 +0200 Subject: [PATCH 05/41] Add a missing ConnectionTypeHttp2Direct in several if statements MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while preparing SPDY retirement. Change-Id: I30f923fdeb0f6f0b5e808a3e7b7d81ddb9c4ef12 Reviewed-by: Mårten Nordheim Reviewed-by: Edward Welbourne --- src/network/access/qhttpnetworkconnection.cpp | 3 ++- src/network/access/qhttpnetworkconnectionchannel.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp index 9b1e63520d5..294273d751c 100644 --- a/src/network/access/qhttpnetworkconnection.cpp +++ b/src/network/access/qhttpnetworkconnection.cpp @@ -1232,7 +1232,8 @@ void QHttpNetworkConnectionPrivate::_q_hostLookupFinished(const QHostInfo &info) emitReplyError(channels[0].socket, channels[0].reply, QNetworkReply::HostNotFoundError); networkLayerState = QHttpNetworkConnectionPrivate::Unknown; } else if (connectionType == QHttpNetworkConnection::ConnectionTypeSPDY - || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2) { + || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2 + || connectionType == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) { for (const HttpMessagePair &spdyPair : qAsConst(channels[0].spdyRequestsToSend)) { // emit error for all replies QHttpNetworkReply *currentReply = spdyPair.second; diff --git a/src/network/access/qhttpnetworkconnectionchannel.cpp b/src/network/access/qhttpnetworkconnectionchannel.cpp index d91fd8d2e6f..8f94cef32b4 100644 --- a/src/network/access/qhttpnetworkconnectionchannel.cpp +++ b/src/network/access/qhttpnetworkconnectionchannel.cpp @@ -1096,6 +1096,7 @@ 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 From 78437ef0d2d662663bbc827befc849cad5886b63 Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Wed, 11 Sep 2019 09:29:40 +0200 Subject: [PATCH 06/41] Add qt.core.filesystemwatcher logging category QFileSystemWatcher has open bugs, so users should be able to help troubleshoot. Change-Id: I6b703e25f294944469d20fd36012b6a55133732a Reviewed-by: Friedemann Kleint --- src/corelib/io/qfilesystemwatcher.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/corelib/io/qfilesystemwatcher.cpp b/src/corelib/io/qfilesystemwatcher.cpp index 64c422c55aa..a4705136a2a 100644 --- a/src/corelib/io/qfilesystemwatcher.cpp +++ b/src/corelib/io/qfilesystemwatcher.cpp @@ -41,9 +41,9 @@ #include "qfilesystemwatcher_p.h" #include -#include #include #include +#include #include #include @@ -67,6 +67,8 @@ QT_BEGIN_NAMESPACE +Q_LOGGING_CATEGORY(lcWatcher, "qt.core.filesystemwatcher") + QFileSystemWatcherEngine *QFileSystemWatcherPrivate::createNativeEngine(QObject *parent) { #if defined(Q_OS_WIN) @@ -137,6 +139,7 @@ void QFileSystemWatcherPrivate::initPollerEngine() void QFileSystemWatcherPrivate::_q_fileChanged(const QString &path, bool removed) { Q_Q(QFileSystemWatcher); + qCDebug(lcWatcher) << "file changed" << path << "removed?" << removed << "watching?" << files.contains(path); if (!files.contains(path)) { // the path was removed after a change was detected, but before we delivered the signal return; @@ -149,6 +152,7 @@ void QFileSystemWatcherPrivate::_q_fileChanged(const QString &path, bool removed void QFileSystemWatcherPrivate::_q_directoryChanged(const QString &path, bool removed) { Q_Q(QFileSystemWatcher); + qCDebug(lcWatcher) << "directory changed" << path << "removed?" << removed << "watching?" << directories.contains(path); if (!directories.contains(path)) { // perhaps the path was removed after a change was detected, but before we delivered the signal return; @@ -355,7 +359,7 @@ QStringList QFileSystemWatcher::addPaths(const QStringList &paths) qWarning("QFileSystemWatcher::addPaths: list is empty"); return p; } - + qCDebug(lcWatcher) << "adding" << paths; const auto selectEngine = [this, d]() -> QFileSystemWatcherEngine* { #ifdef QT_BUILD_INTERNAL const QString on = objectName(); @@ -364,11 +368,11 @@ QStringList QFileSystemWatcher::addPaths(const QStringList &paths) // Autotest override case - use the explicitly selected engine only const QStringRef forceName = on.midRef(26); if (forceName == QLatin1String("poller")) { - qDebug("QFileSystemWatcher: skipping native engine, using only polling engine"); + qCDebug(lcWatcher, "QFileSystemWatcher: skipping native engine, using only polling engine"); d_func()->initPollerEngine(); return d->poller; } else if (forceName == QLatin1String("native")) { - qDebug("QFileSystemWatcher: skipping polling engine, using only native engine"); + qCDebug(lcWatcher, "QFileSystemWatcher: skipping polling engine, using only native engine"); return d->native; } return nullptr; @@ -431,6 +435,7 @@ QStringList QFileSystemWatcher::removePaths(const QStringList &paths) qWarning("QFileSystemWatcher::removePaths: list is empty"); return p; } + qCDebug(lcWatcher) << "removing" << paths; if (d->native) p = d->native->removePaths(p, &d->files, &d->directories); From bc34784d053ebf9b0d167e9398052fcc80d8af87 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Sun, 8 Sep 2019 10:27:47 +0200 Subject: [PATCH 07/41] Handle robustness with OpenGL < 4.0 We need to have the right idea of robustness, so check for extension. Fixes: QTBUG-78107 Change-Id: I26987269e5c50bee20e2e3cc6d75f91a6c9af25e Reviewed-by: Laszlo Agocs --- .../xcb_glx/qglxintegration.cpp | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp index 5e5fefca90b..2b77062b163 100644 --- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp +++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp @@ -63,6 +63,7 @@ QT_BEGIN_NAMESPACE typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); +typedef const GLubyte *(*glGetStringiProc)(GLenum, GLuint); #ifndef GLX_CONTEXT_CORE_PROFILE_BIT_ARB #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 @@ -145,6 +146,27 @@ static inline QByteArray getGlString(GLenum param) return QByteArray(); } +static bool hasGlExtension(const QSurfaceFormat &format, const char *ext) +{ + if (format.majorVersion() < 3) { + auto exts = reinterpret_cast(glGetString(GL_EXTENSIONS)); + return exts && strstr(exts, ext); + } else { + auto glGetStringi = reinterpret_cast( + glXGetProcAddress(reinterpret_cast("glGetStringi"))); + if (glGetStringi) { + GLint n = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &n); + for (GLint i = 0; i < n; ++i) { + const char *p = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); + if (p && !strcmp(p, ext)) + return true; + } + } + return false; + } +} + static void updateFormatFromContext(QSurfaceFormat &format) { // Update the version, profile, and context bit of the format @@ -163,7 +185,7 @@ static void updateFormatFromContext(QSurfaceFormat &format) format.setOption(QSurfaceFormat::StereoBuffers); if (format.renderableType() == QSurfaceFormat::OpenGL) { - if (format.version() >= qMakePair(4, 0)) { + if (hasGlExtension(format, "GL_ARB_robustness")) { GLint value = 0; glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &value); if (value == GL_LOSE_CONTEXT_ON_RESET_ARB) From 3fede6cb547b783377e833c9b269d4cecfe47e61 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 6 Sep 2019 20:27:33 +0200 Subject: [PATCH 08/41] Cleanup QtWidgets (tools) examples Cleanup QtWidgets tools examples: - use member-init (clang-tidy) - fix includes/don't include QtWidgets globally - include own header first - use nullptr (clang-tidy) - avoid c-style casts - use QVector instead QList - use QItemDelegate instead QStyledItemDelegate Change-Id: Ibe9440cdf711e5cc2138c054864edebe1fc95731 Reviewed-by: Paul Wicking --- examples/widgets/tools/codecs/mainwindow.cpp | 20 +++++-- examples/widgets/tools/codecs/mainwindow.h | 6 +-- examples/widgets/tools/codecs/previewform.cpp | 22 +++++--- examples/widgets/tools/codecs/previewform.h | 4 +- examples/widgets/tools/completer/fsmodel.h | 2 +- .../widgets/tools/completer/mainwindow.cpp | 41 +++++++++----- examples/widgets/tools/completer/mainwindow.h | 21 ++++---- .../tools/customcompleter/mainwindow.cpp | 17 ++++-- .../tools/customcompleter/mainwindow.h | 8 +-- .../tools/customcompleter/textedit.cpp | 13 ++--- .../widgets/tools/customcompleter/textedit.h | 4 +- .../echoplugin/echowindow/echointerface.h | 3 +- .../echoplugin/echowindow/echowindow.cpp | 14 +++-- .../tools/echoplugin/echowindow/main.cpp | 2 +- .../tools/echoplugin/plugin/echoplugin.cpp | 2 - .../widgets/tools/i18n/languagechooser.cpp | 41 +++++++------- examples/widgets/tools/i18n/languagechooser.h | 16 +++--- examples/widgets/tools/i18n/mainwindow.cpp | 22 +++++--- examples/widgets/tools/i18n/mainwindow.h | 2 +- .../tools/plugandpaint/app/mainwindow.cpp | 21 ++++++-- .../tools/plugandpaint/app/paintarea.cpp | 5 +- .../tools/plugandpaint/app/plugindialog.cpp | 2 +- .../plugins/basictools/basictoolsplugin.cpp | 6 +-- .../plugins/basictools/basictoolsplugin.h | 10 ++-- .../extrafilters/extrafiltersplugin.cpp | 5 +- examples/widgets/tools/regexp/regexpdialog.h | 2 +- .../regularexpressiondialog.h | 2 +- .../tools/settingseditor/locationdialog.cpp | 17 ++++-- .../tools/settingseditor/locationdialog.h | 2 +- .../tools/settingseditor/mainwindow.cpp | 18 +++++-- .../widgets/tools/settingseditor/mainwindow.h | 12 ++--- .../tools/settingseditor/settingstree.cpp | 36 +++++-------- .../tools/settingseditor/settingstree.h | 13 +++-- .../tools/settingseditor/variantdelegate.cpp | 18 ++++--- .../tools/settingseditor/variantdelegate.h | 6 +-- .../tools/styleplugin/plugin/simplestyle.cpp | 2 - .../tools/styleplugin/plugin/simplestyle.h | 6 +-- .../styleplugin/plugin/simplestyleplugin.cpp | 6 +-- .../styleplugin/plugin/simplestyleplugin.h | 7 +-- .../tools/styleplugin/stylewindow/main.cpp | 3 +- .../styleplugin/stylewindow/stylewindow.cpp | 4 +- .../tools/treemodelcompleter/mainwindow.cpp | 53 +++++++++++-------- .../tools/treemodelcompleter/mainwindow.h | 22 ++++---- .../treemodelcompleter/treemodelcompleter.cpp | 12 ++--- .../treemodelcompleter/treemodelcompleter.h | 4 +- examples/widgets/tools/undo/commands.cpp | 36 +++++-------- examples/widgets/tools/undo/commands.h | 14 ++--- examples/widgets/tools/undo/document.cpp | 32 +++++------ examples/widgets/tools/undo/document.h | 15 +++--- examples/widgets/tools/undo/mainwindow.cpp | 51 +++++++++--------- examples/widgets/tools/undo/mainwindow.h | 2 +- .../widgets/tools/undoframework/commands.cpp | 20 +++---- .../widgets/tools/undoframework/commands.h | 6 +-- .../tools/undoframework/diagramitem.cpp | 9 ++-- .../widgets/tools/undoframework/diagramitem.h | 5 +- .../tools/undoframework/diagramscene.cpp | 17 +++--- .../tools/undoframework/diagramscene.h | 4 +- examples/widgets/tools/undoframework/main.cpp | 2 +- .../tools/undoframework/mainwindow.cpp | 9 +++- .../widgets/tools/undoframework/mainwindow.h | 28 +++++----- 60 files changed, 427 insertions(+), 377 deletions(-) diff --git a/examples/widgets/tools/codecs/mainwindow.cpp b/examples/widgets/tools/codecs/mainwindow.cpp index 53db9fe61ff..6b601062b68 100644 --- a/examples/widgets/tools/codecs/mainwindow.cpp +++ b/examples/widgets/tools/codecs/mainwindow.cpp @@ -48,12 +48,21 @@ ** ****************************************************************************/ -#include - #include "mainwindow.h" #include "encodingdialog.h" #include "previewform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + MainWindow::MainWindow() { textEdit = new QPlainTextEdit; @@ -146,14 +155,14 @@ void MainWindow::findCodecs() QTextCodec *codec = QTextCodec::codecForMib(mib); QString sortKey = codec->name().toUpper(); - int rank; + char rank; if (sortKey.startsWith(QLatin1String("UTF-8"))) { rank = 1; } else if (sortKey.startsWith(QLatin1String("UTF-16"))) { rank = 2; } else if ((match = iso8859RegExp.match(sortKey)).hasMatch()) { - if (match.captured(1).size() == 1) + if (match.capturedRef(1).size() == 1) rank = 3; else rank = 4; @@ -164,7 +173,8 @@ void MainWindow::findCodecs() codecMap.insert(sortKey, codec); } - codecs = codecMap.values(); + for (const auto &codec : qAsConst(codecMap)) + codecs += codec; } void MainWindow::createMenus() diff --git a/examples/widgets/tools/codecs/mainwindow.h b/examples/widgets/tools/codecs/mainwindow.h index 64494d1960f..cf182225207 100644 --- a/examples/widgets/tools/codecs/mainwindow.h +++ b/examples/widgets/tools/codecs/mainwindow.h @@ -51,7 +51,7 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include +#include #include QT_BEGIN_NAMESPACE @@ -81,10 +81,10 @@ private: void findCodecs(); void createMenus(); - QList saveAsActs; + QVector saveAsActs; QPlainTextEdit *textEdit; PreviewForm *previewForm; - QList codecs; + QVector codecs; EncodingDialog *m_encodingDialog = nullptr; }; diff --git a/examples/widgets/tools/codecs/previewform.cpp b/examples/widgets/tools/codecs/previewform.cpp index 206b5757cdd..ec75ebb9faf 100644 --- a/examples/widgets/tools/codecs/previewform.cpp +++ b/examples/widgets/tools/codecs/previewform.cpp @@ -48,10 +48,19 @@ ** ****************************************************************************/ -#include - #include "previewform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + // Helpers for creating hex dumps static void indent(QTextStream &str, int indent) { @@ -83,8 +92,7 @@ static void formatHex(QTextStream &str, const QByteArray &data) static void formatPrintableCharacters(QTextStream &str, const QByteArray &data) { - for (int i = 0, size = data.size(); i < size; ++i) { - const char c = data.at(i); + for (const char c : data) { switch (c) { case '\0': str << "\\0"; @@ -179,7 +187,7 @@ PreviewForm::PreviewForm(QWidget *parent) resize(screenGeometry.width() * 2 / 5, screenGeometry.height() / 2); } -void PreviewForm::setCodecList(const QList &list) +void PreviewForm::setCodecList(const QVector &list) { encodingComboBox->clear(); for (const QTextCodec *codec : list) { @@ -226,10 +234,10 @@ void PreviewForm::updateTextEdit() statusLabel->setText(message); statusLabel->setStyleSheet(QStringLiteral("background-color: \"red\";")); } else if (state.invalidChars) { - statusLabel->setText(tr("%1: %n invalid characters", 0, state.invalidChars).arg(name)); + statusLabel->setText(tr("%1: %n invalid characters", nullptr, state.invalidChars).arg(name)); statusLabel->setStyleSheet(QStringLiteral("background-color: \"yellow\";")); } else { - statusLabel->setText(tr("%1: %n bytes converted", 0, encodedData.size()).arg(name)); + statusLabel->setText(tr("%1: %n bytes converted", nullptr, encodedData.size()).arg(name)); statusLabel->setStyleSheet(QString()); } if (success) diff --git a/examples/widgets/tools/codecs/previewform.h b/examples/widgets/tools/codecs/previewform.h index 6335b6539f2..02eb3533f32 100644 --- a/examples/widgets/tools/codecs/previewform.h +++ b/examples/widgets/tools/codecs/previewform.h @@ -52,7 +52,7 @@ #define PREVIEWFORM_H #include -#include +#include QT_BEGIN_NAMESPACE class QComboBox; @@ -71,7 +71,7 @@ class PreviewForm : public QDialog public: explicit PreviewForm(QWidget *parent = nullptr); - void setCodecList(const QList &list); + void setCodecList(const QVector &list); void setEncodedData(const QByteArray &data); QString decodedString() const { return decodedStr; } diff --git a/examples/widgets/tools/completer/fsmodel.h b/examples/widgets/tools/completer/fsmodel.h index 7b2e7b7dab3..587e08b1922 100644 --- a/examples/widgets/tools/completer/fsmodel.h +++ b/examples/widgets/tools/completer/fsmodel.h @@ -62,7 +62,7 @@ class FileSystemModel : public QFileSystemModel { public: - FileSystemModel(QObject *parent = 0); + FileSystemModel(QObject *parent = nullptr); QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; }; //! [0] diff --git a/examples/widgets/tools/completer/mainwindow.cpp b/examples/widgets/tools/completer/mainwindow.cpp index 114ff0fd7c6..b50e0a54564 100644 --- a/examples/widgets/tools/completer/mainwindow.cpp +++ b/examples/widgets/tools/completer/mainwindow.cpp @@ -48,13 +48,28 @@ ** ****************************************************************************/ -#include -#include "fsmodel.h" #include "mainwindow.h" +#include "fsmodel.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include //! [0] MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), completer(0), lineEdit(0) + : QMainWindow(parent) { createMenu(); @@ -64,8 +79,8 @@ MainWindow::MainWindow(QWidget *parent) modelLabel->setText(tr("Model")); modelCombo = new QComboBox; - modelCombo->addItem(tr("QFileSytemModel")); - modelCombo->addItem(tr("QFileSytemModel that shows full path")); + modelCombo->addItem(tr("QFileSystemModel")); + modelCombo->addItem(tr("QFileSystemModel that shows full path")); modelCombo->addItem(tr("Country list")); modelCombo->addItem(tr("Word list")); modelCombo->setCurrentIndex(0); @@ -144,17 +159,17 @@ void MainWindow::createMenu() connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); - QMenu* fileMenu = menuBar()->addMenu(tr("File")); + QMenu *fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); - QMenu* helpMenu = menuBar()->addMenu(tr("About")); + QMenu *helpMenu = menuBar()->addMenu(tr("About")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } //! [4] //! [5] -QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) +QAbstractItemModel *MainWindow::modelFromFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) @@ -170,7 +185,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) while (!file.atEnd()) { QByteArray line = file.readLine(); if (!line.isEmpty()) - words << line.trimmed(); + words << QString::fromUtf8(line.trimmed()); } #ifndef QT_NO_CURSOR @@ -191,8 +206,8 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) for (int i = 0; i < words.count(); ++i) { QModelIndex countryIdx = m->index(i, 0); QModelIndex symbolIdx = m->index(i, 1); - QString country = words[i].mid(0, words[i].length() - 2).trimmed(); - QString symbol = words[i].right(2); + QString country = words.at(i).mid(0, words[i].length() - 2).trimmed(); + QString symbol = words.at(i).right(2); m->setData(countryIdx, country); m->setData(symbolIdx, symbol); } @@ -233,7 +248,7 @@ void MainWindow::changeModel() case 0: { // Unsorted QFileSystemModel QFileSystemModel *fsModel = new QFileSystemModel(completer); - fsModel->setRootPath(""); + fsModel->setRootPath(QString()); completer->setModel(fsModel); contentsLabel->setText(tr("Enter file path")); } @@ -243,7 +258,7 @@ void MainWindow::changeModel() { // FileSystemModel that shows full paths FileSystemModel *fsModel = new FileSystemModel(completer); completer->setModel(fsModel); - fsModel->setRootPath(""); + fsModel->setRootPath(QString()); contentsLabel->setText(tr("Enter file path")); } break; diff --git a/examples/widgets/tools/completer/mainwindow.h b/examples/widgets/tools/completer/mainwindow.h index 2bb351ec47b..6e6238bf32c 100644 --- a/examples/widgets/tools/completer/mainwindow.h +++ b/examples/widgets/tools/completer/mainwindow.h @@ -59,7 +59,6 @@ class QComboBox; class QCompleter; class QLabel; class QLineEdit; -class QProgressBar; class QCheckBox; class QSpinBox; QT_END_NAMESPACE @@ -70,7 +69,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); private slots: void about(); @@ -83,16 +82,16 @@ private slots: //! [1] private: void createMenu(); - QAbstractItemModel *modelFromFile(const QString& fileName); + QAbstractItemModel *modelFromFile(const QString &fileName); - QComboBox *caseCombo; - QComboBox *modeCombo; - QComboBox *modelCombo; - QSpinBox *maxVisibleSpinBox; - QCheckBox *wrapCheckBox; - QCompleter *completer; - QLabel *contentsLabel; - QLineEdit *lineEdit; + QComboBox *caseCombo = nullptr; + QComboBox *modeCombo = nullptr; + QComboBox *modelCombo = nullptr; + QSpinBox *maxVisibleSpinBox = nullptr; + QCheckBox *wrapCheckBox = nullptr; + QCompleter *completer = nullptr; + QLabel *contentsLabel = nullptr; + QLineEdit *lineEdit = nullptr; }; //! [1] diff --git a/examples/widgets/tools/customcompleter/mainwindow.cpp b/examples/widgets/tools/customcompleter/mainwindow.cpp index 39f5f396179..b8072b505cf 100644 --- a/examples/widgets/tools/customcompleter/mainwindow.cpp +++ b/examples/widgets/tools/customcompleter/mainwindow.cpp @@ -48,13 +48,20 @@ ** ****************************************************************************/ -#include #include "mainwindow.h" #include "textedit.h" +#include +#include +#include +#include +#include +#include +#include + //! [0] MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), completer(0) + : QMainWindow(parent) { createMenu(); @@ -83,10 +90,10 @@ void MainWindow::createMenu() connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); - QMenu* fileMenu = menuBar()->addMenu(tr("File")); + QMenu *fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); - QMenu* helpMenu = menuBar()->addMenu(tr("About")); + QMenu *helpMenu = menuBar()->addMenu(tr("About")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } @@ -107,7 +114,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) while (!file.atEnd()) { QByteArray line = file.readLine(); if (!line.isEmpty()) - words << line.trimmed(); + words << QString::fromUtf8(line.trimmed()); } #ifndef QT_NO_CURSOR diff --git a/examples/widgets/tools/customcompleter/mainwindow.h b/examples/widgets/tools/customcompleter/mainwindow.h index 436377cce7c..cde553e291e 100644 --- a/examples/widgets/tools/customcompleter/mainwindow.h +++ b/examples/widgets/tools/customcompleter/mainwindow.h @@ -55,11 +55,7 @@ QT_BEGIN_NAMESPACE class QAbstractItemModel; -class QComboBox; class QCompleter; -class QLabel; -class QLineEdit; -class QProgressBar; QT_END_NAMESPACE class TextEdit; @@ -69,7 +65,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); private slots: void about(); @@ -78,7 +74,7 @@ private: void createMenu(); QAbstractItemModel *modelFromFile(const QString& fileName); - QCompleter *completer; + QCompleter *completer = nullptr; TextEdit *completingTextEdit; }; //! [0] diff --git a/examples/widgets/tools/customcompleter/textedit.cpp b/examples/widgets/tools/customcompleter/textedit.cpp index d42f7b38bb1..0d536fea3cb 100644 --- a/examples/widgets/tools/customcompleter/textedit.cpp +++ b/examples/widgets/tools/customcompleter/textedit.cpp @@ -60,7 +60,7 @@ //! [0] TextEdit::TextEdit(QWidget *parent) -: QTextEdit(parent), c(0) + : QTextEdit(parent) { setPlainText(tr("This TextEdit provides autocompletions for words that have more than" " 3 characters. You can trigger autocompletion using ") + @@ -78,7 +78,7 @@ TextEdit::~TextEdit() void TextEdit::setCompleter(QCompleter *completer) { if (c) - QObject::disconnect(c, 0, this, 0); + c->disconnect(this); c = completer; @@ -101,7 +101,7 @@ QCompleter *TextEdit::completer() const //! [3] //! [4] -void TextEdit::insertCompletion(const QString& completion) +void TextEdit::insertCompletion(const QString &completion) { if (c->widget() != this) return; @@ -150,18 +150,19 @@ void TextEdit::keyPressEvent(QKeyEvent *e) } } - bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E + const bool isShortcut = (e->modifiers().testFlag(Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!c || !isShortcut) // do not process the shortcut when we have a completer QTextEdit::keyPressEvent(e); //! [7] //! [8] - const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); + const bool ctrlOrShift = e->modifiers().testFlag(Qt::ControlModifier) || + e->modifiers().testFlag(Qt::ShiftModifier); if (!c || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word - bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; + const bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 diff --git a/examples/widgets/tools/customcompleter/textedit.h b/examples/widgets/tools/customcompleter/textedit.h index d0636ab6706..788cb74ae15 100644 --- a/examples/widgets/tools/customcompleter/textedit.h +++ b/examples/widgets/tools/customcompleter/textedit.h @@ -63,7 +63,7 @@ class TextEdit : public QTextEdit Q_OBJECT public: - TextEdit(QWidget *parent = 0); + TextEdit(QWidget *parent = nullptr); ~TextEdit(); void setCompleter(QCompleter *c); @@ -80,7 +80,7 @@ private: QString textUnderCursor() const; private: - QCompleter *c; + QCompleter *c = nullptr; }; //! [0] diff --git a/examples/widgets/tools/echoplugin/echowindow/echointerface.h b/examples/widgets/tools/echoplugin/echowindow/echointerface.h index 1915330e219..fb07f7fb79e 100644 --- a/examples/widgets/tools/echoplugin/echowindow/echointerface.h +++ b/examples/widgets/tools/echoplugin/echowindow/echointerface.h @@ -51,13 +51,14 @@ #ifndef ECHOINTERFACE_H #define ECHOINTERFACE_H +#include #include //! [0] class EchoInterface { public: - virtual ~EchoInterface() {} + virtual ~EchoInterface() = default; virtual QString echo(const QString &message) = 0; }; diff --git a/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp b/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp index 6886a4cd88b..dce6bdedc3e 100644 --- a/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp +++ b/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp @@ -48,10 +48,17 @@ ** ****************************************************************************/ -#include - #include "echowindow.h" +#include +#include +#include +#include +#include +#include +#include +#include + //! [0] EchoWindow::EchoWindow() { @@ -101,7 +108,7 @@ void EchoWindow::createGUI() //! [3] bool EchoWindow::loadPlugin() { - QDir pluginsDir(qApp->applicationDirPath()); + QDir pluginsDir(QCoreApplication::applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); @@ -121,6 +128,7 @@ bool EchoWindow::loadPlugin() echoInterface = qobject_cast(plugin); if (echoInterface) return true; + pluginLoader.unload(); } } diff --git a/examples/widgets/tools/echoplugin/echowindow/main.cpp b/examples/widgets/tools/echoplugin/echowindow/main.cpp index 50e3c2763be..d3cf45fcdeb 100644 --- a/examples/widgets/tools/echoplugin/echowindow/main.cpp +++ b/examples/widgets/tools/echoplugin/echowindow/main.cpp @@ -48,7 +48,7 @@ ** ****************************************************************************/ -#include +#include #include "echowindow.h" #include "echointerface.h" diff --git a/examples/widgets/tools/echoplugin/plugin/echoplugin.cpp b/examples/widgets/tools/echoplugin/plugin/echoplugin.cpp index de6b6a44629..c9dd93aab83 100644 --- a/examples/widgets/tools/echoplugin/plugin/echoplugin.cpp +++ b/examples/widgets/tools/echoplugin/plugin/echoplugin.cpp @@ -48,8 +48,6 @@ ** ****************************************************************************/ -#include - #include "echoplugin.h" //! [0] diff --git a/examples/widgets/tools/i18n/languagechooser.cpp b/examples/widgets/tools/i18n/languagechooser.cpp index e61e4432e4d..2ce3471873b 100644 --- a/examples/widgets/tools/i18n/languagechooser.cpp +++ b/examples/widgets/tools/i18n/languagechooser.cpp @@ -48,34 +48,39 @@ ** ****************************************************************************/ -#include - #include "languagechooser.h" #include "mainwindow.h" -LanguageChooser::LanguageChooser(const QString& defaultLang, QWidget *parent) +#include +#include +#include +#include +#include +#include +#include +#include + +LanguageChooser::LanguageChooser(const QString &defaultLang, QWidget *parent) : QDialog(parent, Qt::WindowStaysOnTopHint) { groupBox = new QGroupBox("Languages"); QGridLayout *groupBoxLayout = new QGridLayout; - QStringList qmFiles = findQmFiles(); + const QStringList qmFiles = findQmFiles(); for (int i = 0; i < qmFiles.size(); ++i) { - QCheckBox *checkBox = new QCheckBox(languageName(qmFiles[i])); - qmFileForCheckBoxMap.insert(checkBox, qmFiles[i]); - connect(checkBox, - QOverload::of(&QCheckBox::toggled), - this, - &LanguageChooser::checkBoxToggled); - if (languageMatch(defaultLang, qmFiles[i])) - checkBox->setCheckState(Qt::Checked); + const QString &qmlFile = qmFiles.at(i); + QCheckBox *checkBox = new QCheckBox(languageName(qmlFile)); + qmFileForCheckBoxMap.insert(checkBox, qmlFile); + connect(checkBox, &QCheckBox::toggled, + this, &LanguageChooser::checkBoxToggled); + if (languageMatch(defaultLang, qmlFile)) + checkBox->setCheckState(Qt::Checked); groupBoxLayout->addWidget(checkBox, i / 2, i % 2); } groupBox->setLayout(groupBoxLayout); buttonBox = new QDialogButtonBox; - showAllButton = buttonBox->addButton("Show All", QDialogButtonBox::ActionRole); hideAllButton = buttonBox->addButton("Hide All", @@ -92,7 +97,7 @@ LanguageChooser::LanguageChooser(const QString& defaultLang, QWidget *parent) setWindowTitle("I18N"); } -bool LanguageChooser::languageMatch(const QString& lang, const QString& qmFile) +bool LanguageChooser::languageMatch(const QString &lang, const QString &qmFile) { //qmFile: i18n_xx.qm const QString prefix = "i18n_"; @@ -110,21 +115,21 @@ bool LanguageChooser::eventFilter(QObject *object, QEvent *event) checkBox->setChecked(false); } } - return QWidget::eventFilter(object, event); + return QDialog::eventFilter(object, event); } void LanguageChooser::closeEvent(QCloseEvent * /* event */) { - qApp->quit(); + QCoreApplication::quit(); } void LanguageChooser::checkBoxToggled() { QCheckBox *checkBox = qobject_cast(sender()); - MainWindow *window = mainWindowForCheckBoxMap[checkBox]; + MainWindow *window = mainWindowForCheckBoxMap.value(checkBox); if (!window) { QTranslator translator; - translator.load(qmFileForCheckBoxMap[checkBox]); + translator.load(qmFileForCheckBoxMap.value(checkBox)); qApp->installTranslator(&translator); window = new MainWindow; diff --git a/examples/widgets/tools/i18n/languagechooser.h b/examples/widgets/tools/i18n/languagechooser.h index 13363c71112..733cc50fd3f 100644 --- a/examples/widgets/tools/i18n/languagechooser.h +++ b/examples/widgets/tools/i18n/languagechooser.h @@ -52,7 +52,7 @@ #define LANGUAGECHOOSER_H #include -#include +#include #include QT_BEGIN_NAMESPACE @@ -68,7 +68,7 @@ class LanguageChooser : public QDialog Q_OBJECT public: - explicit LanguageChooser(const QString& defaultLang = QString(), QWidget *parent = 0); + explicit LanguageChooser(const QString &defaultLang = QString(), QWidget *parent = nullptr); protected: bool eventFilter(QObject *object, QEvent *event) override; @@ -80,17 +80,17 @@ private slots: void hideAll(); private: - QStringList findQmFiles(); - QString languageName(const QString &qmFile); - QColor colorForLanguage(const QString &language); - static bool languageMatch(const QString& lang, const QString& qmFile); + static QStringList findQmFiles(); + static QString languageName(const QString &qmFile); + static QColor colorForLanguage(const QString &language); + static bool languageMatch(const QString &lang, const QString &qmFile); QGroupBox *groupBox; QDialogButtonBox *buttonBox; QAbstractButton *showAllButton; QAbstractButton *hideAllButton; - QMap qmFileForCheckBoxMap; - QMap mainWindowForCheckBoxMap; + QHash qmFileForCheckBoxMap; + QHash mainWindowForCheckBoxMap; }; #endif diff --git a/examples/widgets/tools/i18n/mainwindow.cpp b/examples/widgets/tools/i18n/mainwindow.cpp index 6ebfddfa98b..a107a819cab 100644 --- a/examples/widgets/tools/i18n/mainwindow.cpp +++ b/examples/widgets/tools/i18n/mainwindow.cpp @@ -48,18 +48,26 @@ ** ****************************************************************************/ -#include - #include "mainwindow.h" +#include +#include +#include +#include +#include +#include +#include +#include + static const char * const listEntries[] = { QT_TRANSLATE_NOOP("MainWindow", "First"), QT_TRANSLATE_NOOP("MainWindow", "Second"), QT_TRANSLATE_NOOP("MainWindow", "Third"), - 0 + nullptr }; -MainWindow::MainWindow() +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { centralWidget = new QWidget; setCentralWidget(centralWidget); @@ -67,8 +75,8 @@ MainWindow::MainWindow() createGroupBox(); listWidget = new QListWidget; - for (int i = 0; listEntries[i]; ++i) - listWidget->addItem(tr(listEntries[i])); + for (const char *entry : listEntries) + listWidget->addItem(tr(entry)); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(groupBox); @@ -76,7 +84,7 @@ MainWindow::MainWindow() centralWidget->setLayout(mainLayout); exitAction = new QAction(tr("E&xit"), this); - connect(exitAction, &QAction::triggered, qApp, QApplication::quit); + connect(exitAction, &QAction::triggered, qApp, QCoreApplication::quit); fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->setPalette(QPalette(Qt::red)); diff --git a/examples/widgets/tools/i18n/mainwindow.h b/examples/widgets/tools/i18n/mainwindow.h index e0111518941..105472d60c0 100644 --- a/examples/widgets/tools/i18n/mainwindow.h +++ b/examples/widgets/tools/i18n/mainwindow.h @@ -67,7 +67,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); private: void createGroupBox(); diff --git a/examples/widgets/tools/plugandpaint/app/mainwindow.cpp b/examples/widgets/tools/plugandpaint/app/mainwindow.cpp index ebe1150eeaa..ff3b3614af5 100644 --- a/examples/widgets/tools/plugandpaint/app/mainwindow.cpp +++ b/examples/widgets/tools/plugandpaint/app/mainwindow.cpp @@ -49,8 +49,8 @@ ****************************************************************************/ -#include "interfaces.h" #include "mainwindow.h" +#include "interfaces.h" #include "paintarea.h" #include "plugindialog.h" @@ -67,9 +67,8 @@ #include #include -MainWindow::MainWindow() : - paintArea(new PaintArea), - scrollArea(new QScrollArea) +MainWindow::MainWindow() : paintArea(new PaintArea) + , scrollArea(new QScrollArea) { scrollArea->setBackgroundRole(QPalette::Dark); scrollArea->setWidget(paintArea); @@ -136,7 +135,11 @@ void MainWindow::brushWidth() void MainWindow::changeBrush() { auto action = qobject_cast(sender()); + if (!action) + return; auto iBrush = qobject_cast(action->parent()); + if (!iBrush) + return; const QString brush = action->text(); paintArea->setBrush(iBrush, brush); @@ -147,7 +150,11 @@ void MainWindow::changeBrush() void MainWindow::insertShape() { auto action = qobject_cast(sender()); + if (!action) + return; auto iShape = qobject_cast(action->parent()); + if (!iShape) + return; const QPainterPath path = iShape->generateShape(action->text(), this); if (!path.isEmpty()) @@ -159,7 +166,11 @@ void MainWindow::insertShape() void MainWindow::applyFilter() { auto action = qobject_cast(sender()); + if (!action) + return; auto iFilter = qobject_cast(action->parent()); + if (!iFilter) + return; const QImage image = iFilter->filterImage(action->text(), paintArea->image(), this); @@ -247,7 +258,7 @@ void MainWindow::loadPlugins() populateMenus(plugin); //! [4] //! [5] - pluginsDir = QDir(qApp->applicationDirPath()); + pluginsDir = QDir(QCoreApplication::applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") diff --git a/examples/widgets/tools/plugandpaint/app/paintarea.cpp b/examples/widgets/tools/plugandpaint/app/paintarea.cpp index e225d783987..92b8ea4777f 100644 --- a/examples/widgets/tools/plugandpaint/app/paintarea.cpp +++ b/examples/widgets/tools/plugandpaint/app/paintarea.cpp @@ -49,14 +49,13 @@ ****************************************************************************/ -#include "interfaces.h" #include "paintarea.h" +#include "interfaces.h" #include #include -PaintArea::PaintArea(QWidget *parent) : - QWidget(parent) +PaintArea::PaintArea(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); setAttribute(Qt::WA_OpaquePaintEvent); diff --git a/examples/widgets/tools/plugandpaint/app/plugindialog.cpp b/examples/widgets/tools/plugandpaint/app/plugindialog.cpp index 84bd364b418..204d6ffec41 100644 --- a/examples/widgets/tools/plugandpaint/app/plugindialog.cpp +++ b/examples/widgets/tools/plugandpaint/app/plugindialog.cpp @@ -49,8 +49,8 @@ ****************************************************************************/ -#include "interfaces.h" #include "plugindialog.h" +#include "interfaces.h" #include #include diff --git a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp index 3b465565ba7..64f9f7a0d9d 100644 --- a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp +++ b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp @@ -50,10 +50,10 @@ #include "basictoolsplugin.h" +#include +#include +#include #include -#include - -#include //! [0] QStringList BasicToolsPlugin::brushes() const diff --git a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.h b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.h index fd9bb9e5f31..1d9d170daad 100644 --- a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.h +++ b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.h @@ -54,12 +54,12 @@ //! [0] #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include //! [1] class BasicToolsPlugin : public QObject, diff --git a/examples/widgets/tools/plugandpaint/plugins/extrafilters/extrafiltersplugin.cpp b/examples/widgets/tools/plugandpaint/plugins/extrafilters/extrafiltersplugin.cpp index 48717e34f65..30c616a830b 100644 --- a/examples/widgets/tools/plugandpaint/plugins/extrafilters/extrafiltersplugin.cpp +++ b/examples/widgets/tools/plugandpaint/plugins/extrafilters/extrafiltersplugin.cpp @@ -50,10 +50,7 @@ #include "extrafiltersplugin.h" -#include - -#include -#include +#include QStringList ExtraFiltersPlugin::filters() const { diff --git a/examples/widgets/tools/regexp/regexpdialog.h b/examples/widgets/tools/regexp/regexpdialog.h index 4bdc18da15c..2f701a72289 100644 --- a/examples/widgets/tools/regexp/regexpdialog.h +++ b/examples/widgets/tools/regexp/regexpdialog.h @@ -65,7 +65,7 @@ class RegExpDialog : public QDialog Q_OBJECT public: - RegExpDialog(QWidget *parent = 0); + RegExpDialog(QWidget *parent = nullptr); private slots: void refresh(); diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.h b/examples/widgets/tools/regularexpression/regularexpressiondialog.h index ba5b38b5e3d..8fe85afe56b 100644 --- a/examples/widgets/tools/regularexpression/regularexpressiondialog.h +++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.h @@ -70,7 +70,7 @@ class RegularExpressionDialog : public QDialog Q_OBJECT public: - RegularExpressionDialog(QWidget *parent = 0); + RegularExpressionDialog(QWidget *parent = nullptr); private: void refresh(); diff --git a/examples/widgets/tools/settingseditor/locationdialog.cpp b/examples/widgets/tools/settingseditor/locationdialog.cpp index 5b6e2652bbb..99c9834a63e 100644 --- a/examples/widgets/tools/settingseditor/locationdialog.cpp +++ b/examples/widgets/tools/settingseditor/locationdialog.cpp @@ -48,10 +48,20 @@ ** ****************************************************************************/ -#include - #include "locationdialog.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + LocationDialog::LocationDialog(QWidget *parent) : QDialog(parent) { @@ -91,8 +101,7 @@ LocationDialog::LocationDialog(QWidget *parent) locationsGroupBox = new QGroupBox(tr("Setting Locations")); - QStringList labels; - labels << tr("Location") << tr("Access"); + const QStringList labels{tr("Location"), tr("Access")}; locationsTable = new QTableWidget; locationsTable->setSelectionMode(QAbstractItemView::SingleSelection); diff --git a/examples/widgets/tools/settingseditor/locationdialog.h b/examples/widgets/tools/settingseditor/locationdialog.h index c25b01effdc..cd2efecb0b0 100644 --- a/examples/widgets/tools/settingseditor/locationdialog.h +++ b/examples/widgets/tools/settingseditor/locationdialog.h @@ -68,7 +68,7 @@ class LocationDialog : public QDialog Q_OBJECT public: - LocationDialog(QWidget *parent = 0); + LocationDialog(QWidget *parent = nullptr); QSettings::Format format() const; QSettings::Scope scope() const; diff --git a/examples/widgets/tools/settingseditor/mainwindow.cpp b/examples/widgets/tools/settingseditor/mainwindow.cpp index a7a1e9b415f..b9c2193ccb6 100644 --- a/examples/widgets/tools/settingseditor/mainwindow.cpp +++ b/examples/widgets/tools/settingseditor/mainwindow.cpp @@ -48,15 +48,23 @@ ** ****************************************************************************/ -#include - #include "locationdialog.h" #include "mainwindow.h" #include "settingstree.h" -MainWindow::MainWindow() - : settingsTree(new SettingsTree) - , locationDialog(nullptr) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) + , settingsTree(new SettingsTree) { setCentralWidget(settingsTree); diff --git a/examples/widgets/tools/settingseditor/mainwindow.h b/examples/widgets/tools/settingseditor/mainwindow.h index 373c982afe4..b1115005a98 100644 --- a/examples/widgets/tools/settingseditor/mainwindow.h +++ b/examples/widgets/tools/settingseditor/mainwindow.h @@ -68,7 +68,7 @@ class MainWindow : public QMainWindow public: typedef QSharedPointer SettingsPtr; - MainWindow(); + MainWindow(QWidget *parent = nullptr); private slots: void openSettings(); @@ -81,11 +81,11 @@ private: void createActions(); void setSettingsObject(const SettingsPtr &settings); - SettingsTree *settingsTree; - LocationDialog *locationDialog; - QAction *refreshAct; - QAction *autoRefreshAct; - QAction *fallbacksAct; + SettingsTree *settingsTree = nullptr; + LocationDialog *locationDialog = nullptr; + QAction *refreshAct = nullptr; + QAction *autoRefreshAct = nullptr; + QAction *fallbacksAct = nullptr; }; #endif diff --git a/examples/widgets/tools/settingseditor/settingstree.cpp b/examples/widgets/tools/settingseditor/settingstree.cpp index 85857927879..b263746847f 100644 --- a/examples/widgets/tools/settingseditor/settingstree.cpp +++ b/examples/widgets/tools/settingseditor/settingstree.cpp @@ -48,20 +48,20 @@ ** ****************************************************************************/ -#include - #include "settingstree.h" #include "variantdelegate.h" +#include +#include +#include +#include + SettingsTree::SettingsTree(QWidget *parent) : QTreeWidget(parent) - , autoRefresh(false) { setItemDelegate(new VariantDelegate(this)); - QStringList labels; - labels << tr("Setting") << tr("Type") << tr("Value"); - setHeaderLabels(labels); + setHeaderLabels({tr("Setting"), tr("Type"), tr("Value")}); header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); header()->setSectionResizeMode(2, QHeaderView::Stretch); @@ -77,10 +77,6 @@ SettingsTree::SettingsTree(QWidget *parent) connect(&refreshTimer, &QTimer::timeout, this, &SettingsTree::maybeRefresh); } -SettingsTree::~SettingsTree() -{ -} - void SettingsTree::setSettingsObject(const SettingsPtr &newSettings) { settings = newSettings; @@ -137,7 +133,7 @@ void SettingsTree::refresh() this, &SettingsTree::updateSetting); settings->sync(); - updateChildItems(0); + updateChildItems(nullptr); connect(this, &QTreeWidget::itemChanged, this, &SettingsTree::updateSetting); @@ -228,7 +224,7 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent) QTreeWidgetItem *SettingsTree::createItem(const QString &text, QTreeWidgetItem *parent, int index) { - QTreeWidgetItem *after = 0; + QTreeWidgetItem *after = nullptr; if (index != 0) after = childAt(parent, index - 1); @@ -243,24 +239,18 @@ QTreeWidgetItem *SettingsTree::createItem(const QString &text, return item; } -QTreeWidgetItem *SettingsTree::childAt(QTreeWidgetItem *parent, int index) +QTreeWidgetItem *SettingsTree::childAt(QTreeWidgetItem *parent, int index) const { - if (parent) - return parent->child(index); - else - return topLevelItem(index); + return (parent ? parent->child(index) : topLevelItem(index)); } -int SettingsTree::childCount(QTreeWidgetItem *parent) +int SettingsTree::childCount(QTreeWidgetItem *parent) const { - if (parent) - return parent->childCount(); - else - return topLevelItemCount(); + return (parent ? parent->childCount() : topLevelItemCount()); } int SettingsTree::findChild(QTreeWidgetItem *parent, const QString &text, - int startIndex) + int startIndex) const { for (int i = startIndex; i < childCount(parent); ++i) { if (childAt(parent, i)->text(0) == text) diff --git a/examples/widgets/tools/settingseditor/settingstree.h b/examples/widgets/tools/settingseditor/settingstree.h index 15efa0e6aa6..3e9e9658ce1 100644 --- a/examples/widgets/tools/settingseditor/settingstree.h +++ b/examples/widgets/tools/settingseditor/settingstree.h @@ -65,10 +65,9 @@ class SettingsTree : public QTreeWidget Q_OBJECT public: - typedef QSharedPointer SettingsPtr; + using SettingsPtr = QSharedPointer; - SettingsTree(QWidget *parent = 0); - ~SettingsTree(); + SettingsTree(QWidget *parent = nullptr); void setSettingsObject(const SettingsPtr &settings); QSize sizeHint() const override; @@ -89,16 +88,16 @@ private: void updateChildItems(QTreeWidgetItem *parent); QTreeWidgetItem *createItem(const QString &text, QTreeWidgetItem *parent, int index); - QTreeWidgetItem *childAt(QTreeWidgetItem *parent, int index); - int childCount(QTreeWidgetItem *parent); - int findChild(QTreeWidgetItem *parent, const QString &text, int startIndex); + QTreeWidgetItem *childAt(QTreeWidgetItem *parent, int index) const; + int childCount(QTreeWidgetItem *parent) const; + int findChild(QTreeWidgetItem *parent, const QString &text, int startIndex) const; void moveItemForward(QTreeWidgetItem *parent, int oldIndex, int newIndex); SettingsPtr settings; QTimer refreshTimer; - bool autoRefresh; QIcon groupIcon; QIcon keyIcon; + bool autoRefresh = false; }; #endif diff --git a/examples/widgets/tools/settingseditor/variantdelegate.cpp b/examples/widgets/tools/settingseditor/variantdelegate.cpp index 266754ca4d3..9772fe8a41d 100644 --- a/examples/widgets/tools/settingseditor/variantdelegate.cpp +++ b/examples/widgets/tools/settingseditor/variantdelegate.cpp @@ -48,12 +48,14 @@ ** ****************************************************************************/ -#include - #include "variantdelegate.h" +#include +#include +#include + VariantDelegate::VariantDelegate(QObject *parent) - : QItemDelegate(parent) + : QStyledItemDelegate(parent) { boolExp.setPattern("true|false"); boolExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption); @@ -82,12 +84,12 @@ void VariantDelegate::paint(QPainter *painter, if (!isSupportedType(value.type())) { QStyleOptionViewItem myOption = option; myOption.state &= ~QStyle::State_Enabled; - QItemDelegate::paint(painter, myOption, index); + QStyledItemDelegate::paint(painter, myOption, index); return; } } - QItemDelegate::paint(painter, option, index); + QStyledItemDelegate::paint(painter, option, index); } QWidget *VariantDelegate::createEditor(QWidget *parent, @@ -95,11 +97,11 @@ QWidget *VariantDelegate::createEditor(QWidget *parent, const QModelIndex &index) const { if (index.column() != 2) - return 0; + return nullptr; QVariant originalValue = index.model()->data(index, Qt::UserRole); if (!isSupportedType(originalValue.type())) - return 0; + return nullptr; QLineEdit *lineEdit = new QLineEdit(parent); lineEdit->setFrame(false); @@ -149,7 +151,7 @@ QWidget *VariantDelegate::createEditor(QWidget *parent, regExp = unsignedIntegerExp; break; default: - ; + break; } if (regExp.isValid()) { diff --git a/examples/widgets/tools/settingseditor/variantdelegate.h b/examples/widgets/tools/settingseditor/variantdelegate.h index 7cd9fa9ee89..68f21fa3f6c 100644 --- a/examples/widgets/tools/settingseditor/variantdelegate.h +++ b/examples/widgets/tools/settingseditor/variantdelegate.h @@ -51,15 +51,15 @@ #ifndef VARIANTDELEGATE_H #define VARIANTDELEGATE_H -#include +#include #include -class VariantDelegate : public QItemDelegate +class VariantDelegate : public QStyledItemDelegate { Q_OBJECT public: - VariantDelegate(QObject *parent = 0); + VariantDelegate(QObject *parent = nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; diff --git a/examples/widgets/tools/styleplugin/plugin/simplestyle.cpp b/examples/widgets/tools/styleplugin/plugin/simplestyle.cpp index 59da6a86721..765c9c2745a 100644 --- a/examples/widgets/tools/styleplugin/plugin/simplestyle.cpp +++ b/examples/widgets/tools/styleplugin/plugin/simplestyle.cpp @@ -48,8 +48,6 @@ ** ****************************************************************************/ -#include - #include "simplestyle.h" void SimpleStyle::polish(QPalette &palette) diff --git a/examples/widgets/tools/styleplugin/plugin/simplestyle.h b/examples/widgets/tools/styleplugin/plugin/simplestyle.h index 51d6d5b77e4..4f49de8cbcb 100644 --- a/examples/widgets/tools/styleplugin/plugin/simplestyle.h +++ b/examples/widgets/tools/styleplugin/plugin/simplestyle.h @@ -53,16 +53,12 @@ #include -QT_BEGIN_NAMESPACE -class QPalette; -QT_END_NAMESPACE - class SimpleStyle : public QProxyStyle { Q_OBJECT public: - SimpleStyle() {}; + SimpleStyle() = default; void polish(QPalette &palette) override; }; diff --git a/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.cpp b/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.cpp index 344e46061c4..cbe7c15cc0d 100644 --- a/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.cpp +++ b/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.cpp @@ -48,15 +48,13 @@ ** ****************************************************************************/ -#include - #include "simplestyleplugin.h" #include "simplestyle.h" //! [0] QStringList SimpleStylePlugin::keys() const { - return QStringList() << "SimpleStyle"; + return {"SimpleStyle"}; } //! [0] @@ -65,6 +63,6 @@ QStyle *SimpleStylePlugin::create(const QString &key) { if (key.toLower() == "simplestyle") return new SimpleStyle; - return 0; + return nullptr; } //! [1] diff --git a/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.h b/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.h index 88805d48873..3ce37410eb2 100644 --- a/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.h +++ b/examples/widgets/tools/styleplugin/plugin/simplestyleplugin.h @@ -53,11 +53,6 @@ #include -QT_BEGIN_NAMESPACE -class QStringList; -class QStyle; -QT_END_NAMESPACE - //! [0] class SimpleStylePlugin : public QStylePlugin { @@ -65,7 +60,7 @@ class SimpleStylePlugin : public QStylePlugin Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "simplestyle.json") public: - SimpleStylePlugin() {} + SimpleStylePlugin() = default; QStringList keys() const; QStyle *create(const QString &key) override; diff --git a/examples/widgets/tools/styleplugin/stylewindow/main.cpp b/examples/widgets/tools/styleplugin/stylewindow/main.cpp index 93816d393dd..ff29eb119e3 100644 --- a/examples/widgets/tools/styleplugin/stylewindow/main.cpp +++ b/examples/widgets/tools/styleplugin/stylewindow/main.cpp @@ -48,7 +48,8 @@ ** ****************************************************************************/ -#include +#include +#include #include "stylewindow.h" diff --git a/examples/widgets/tools/styleplugin/stylewindow/stylewindow.cpp b/examples/widgets/tools/styleplugin/stylewindow/stylewindow.cpp index 7a05a3ae921..90413ed12ef 100644 --- a/examples/widgets/tools/styleplugin/stylewindow/stylewindow.cpp +++ b/examples/widgets/tools/styleplugin/stylewindow/stylewindow.cpp @@ -48,7 +48,9 @@ ** ****************************************************************************/ -#include +#include +#include +#include #include "stylewindow.h" diff --git a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp index dec3cb04966..302ccc436c2 100644 --- a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp +++ b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp @@ -48,13 +48,28 @@ ** ****************************************************************************/ -#include -#include "treemodelcompleter.h" #include "mainwindow.h" +#include "treemodelcompleter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include //! [0] MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), completer(0), lineEdit(0) + : QMainWindow(parent) { createMenu(); @@ -151,10 +166,10 @@ void MainWindow::createMenu() connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); - QMenu* fileMenu = menuBar()->addMenu(tr("File")); + QMenu *fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); - QMenu* helpMenu = menuBar()->addMenu(tr("About")); + QMenu *helpMenu = menuBar()->addMenu(tr("About")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } @@ -175,7 +190,7 @@ void MainWindow::changeMode(int index) } //! [5] -QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) +QAbstractItemModel *MainWindow::modelFromFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) @@ -184,39 +199,35 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) #ifndef QT_NO_CURSOR QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif - QStringList words; QStandardItemModel *model = new QStandardItemModel(completer); QVector parents(10); parents[0] = model->invisibleRootItem(); + QRegularExpression re("^\\s+"); while (!file.atEnd()) { - QString line = file.readLine(); - QString trimmedLine = line.trimmed(); - if (line.isEmpty() || trimmedLine.isEmpty()) + const QString line = QString::fromUtf8(file.readLine()).trimmed(); + const QString trimmedLine = line.trimmed(); + if (trimmedLine.isEmpty()) continue; - QRegularExpression re("^\\s+"); - QRegularExpressionMatch match = re.match(line); + const QRegularExpressionMatch match = re.match(line); int nonws = match.capturedStart(); int level = 0; if (nonws == -1) { level = 0; } else { - if (line.startsWith("\t")) { - level = match.capturedLength(); - } else { - level = match.capturedLength()/4; - } + const int capLen = match.capturedLength(); + level = line.startsWith(QLatin1Char('\t')) ? capLen / 4 : capLen; } - if (level+1 >= parents.size()) - parents.resize(parents.size()*2); + if (level + 1 >= parents.size()) + parents.resize(parents.size() * 2); QStandardItem *item = new QStandardItem; item->setText(trimmedLine); parents[level]->appendRow(item); - parents[level+1] = item; + parents[level + 1] = item; } #ifndef QT_NO_CURSOR @@ -252,7 +263,7 @@ void MainWindow::changeCase(int cs) } //! [7] -void MainWindow::updateContentsLabel(const QString& sep) +void MainWindow::updateContentsLabel(const QString &sep) { contentsLabel->setText(tr("Type path from model above with items at each level separated by a '%1'").arg(sep)); } diff --git a/examples/widgets/tools/treemodelcompleter/mainwindow.h b/examples/widgets/tools/treemodelcompleter/mainwindow.h index 2edcd5aab03..87f492c4ac3 100644 --- a/examples/widgets/tools/treemodelcompleter/mainwindow.h +++ b/examples/widgets/tools/treemodelcompleter/mainwindow.h @@ -60,8 +60,6 @@ class QAbstractItemModel; class QComboBox; class QLabel; class QLineEdit; -class QProgressBar; -class QCheckBox; class QTreeView; QT_END_NAMESPACE @@ -71,27 +69,27 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); private slots: void about(); void changeCase(int); void changeMode(int); - void highlight(const QModelIndex&); - void updateContentsLabel(const QString&); + void highlight(const QModelIndex &index); + void updateContentsLabel(const QString &sep); //! [0] //! [1] private: void createMenu(); - QAbstractItemModel *modelFromFile(const QString& fileName); + QAbstractItemModel *modelFromFile(const QString &fileName); - QTreeView *treeView; - QComboBox *caseCombo; - QComboBox *modeCombo; - QLabel *contentsLabel; - TreeModelCompleter *completer; - QLineEdit *lineEdit; + QTreeView *treeView = nullptr; + QComboBox *caseCombo = nullptr; + QComboBox *modeCombo = nullptr; + QLabel *contentsLabel = nullptr; + TreeModelCompleter *completer = nullptr; + QLineEdit *lineEdit = nullptr; }; //! [1] diff --git a/examples/widgets/tools/treemodelcompleter/treemodelcompleter.cpp b/examples/widgets/tools/treemodelcompleter/treemodelcompleter.cpp index cab0476e3ca..8930c815d5e 100644 --- a/examples/widgets/tools/treemodelcompleter/treemodelcompleter.cpp +++ b/examples/widgets/tools/treemodelcompleter/treemodelcompleter.cpp @@ -80,26 +80,20 @@ QString TreeModelCompleter::separator() const //! [3] QStringList TreeModelCompleter::splitPath(const QString &path) const { - if (sep.isNull()) { - return QCompleter::splitPath(path); - } - - return path.split(sep); + return (sep.isNull() ? QCompleter::splitPath(path) : path.split(sep)); } //! [3] //! [4] QString TreeModelCompleter::pathFromIndex(const QModelIndex &index) const { - if (sep.isNull()) { + if (sep.isNull()) return QCompleter::pathFromIndex(index); - } // navigate up and accumulate data QStringList dataList; - for (QModelIndex i = index; i.isValid(); i = i.parent()) { + for (QModelIndex i = index; i.isValid(); i = i.parent()) dataList.prepend(model()->data(i, completionRole()).toString()); - } return dataList.join(sep); } diff --git a/examples/widgets/tools/treemodelcompleter/treemodelcompleter.h b/examples/widgets/tools/treemodelcompleter/treemodelcompleter.h index 1d28fddee08..d7d1852cc7c 100644 --- a/examples/widgets/tools/treemodelcompleter/treemodelcompleter.h +++ b/examples/widgets/tools/treemodelcompleter/treemodelcompleter.h @@ -60,8 +60,8 @@ class TreeModelCompleter : public QCompleter Q_PROPERTY(QString separator READ separator WRITE setSeparator) public: - explicit TreeModelCompleter(QObject *parent = 0); - explicit TreeModelCompleter(QAbstractItemModel *model, QObject *parent = 0); + explicit TreeModelCompleter(QObject *parent = nullptr); + explicit TreeModelCompleter(QAbstractItemModel *model, QObject *parent = nullptr); QString separator() const; public slots: diff --git a/examples/widgets/tools/undo/commands.cpp b/examples/widgets/tools/undo/commands.cpp index 81561d24212..97204f9d2f4 100644 --- a/examples/widgets/tools/undo/commands.cpp +++ b/examples/widgets/tools/undo/commands.cpp @@ -50,18 +50,16 @@ #include "commands.h" -static const int setShapeRectCommandId = 1; -static const int setShapeColorCommandId = 2; +static constexpr int setShapeRectCommandId = 1; +static constexpr int setShapeColorCommandId = 2; /****************************************************************************** ** AddShapeCommand */ AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent) - : QUndoCommand(parent) + : QUndoCommand(parent), m_doc(doc), m_shape(shape) { - m_doc = doc; - m_shape = shape; } void AddShapeCommand::undo() @@ -81,13 +79,11 @@ void AddShapeCommand::redo() */ RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName, - QUndoCommand *parent) - : QUndoCommand(parent) + QUndoCommand *parent) + : QUndoCommand(parent), m_doc(doc), m_shape(doc->shape(shapeName)) + , m_shapeName(shapeName) { setText(QObject::tr("Remove %1").arg(shapeName)); - m_doc = doc; - m_shape = doc->shape(shapeName); - m_shapeName = shapeName; } void RemoveShapeCommand::undo() @@ -105,15 +101,11 @@ void RemoveShapeCommand::redo() */ SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName, - const QColor &color, QUndoCommand *parent) - : QUndoCommand(parent) + const QColor &color, QUndoCommand *parent) + : QUndoCommand(parent), m_doc(doc), m_shapeName(shapeName) + , m_oldColor(doc->shape(shapeName).color()), m_newColor(color) { setText(QObject::tr("Set %1's color").arg(shapeName)); - - m_doc = doc; - m_shapeName = shapeName; - m_oldColor = doc->shape(shapeName).color(); - m_newColor = color; } void SetShapeColorCommand::undo() @@ -149,15 +141,11 @@ int SetShapeColorCommand::id() const */ SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName, - const QRect &rect, QUndoCommand *parent) - : QUndoCommand(parent) + const QRect &rect, QUndoCommand *parent) + : QUndoCommand(parent), m_doc(doc), m_shapeName(shapeName) + , m_oldRect(doc->shape(shapeName).rect()), m_newRect(rect) { setText(QObject::tr("Change %1's geometry").arg(shapeName)); - - m_doc = doc; - m_shapeName = shapeName; - m_oldRect = doc->shape(shapeName).rect(); - m_newRect = rect; } void SetShapeRectCommand::undo() diff --git a/examples/widgets/tools/undo/commands.h b/examples/widgets/tools/undo/commands.h index de3bebd7404..ccb550fdd4e 100644 --- a/examples/widgets/tools/undo/commands.h +++ b/examples/widgets/tools/undo/commands.h @@ -57,7 +57,8 @@ class AddShapeCommand : public QUndoCommand { public: - AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent = 0); + AddShapeCommand(Document *doc, const Shape &shape, + QUndoCommand *parent = nullptr); void undo() override; void redo() override; @@ -70,7 +71,8 @@ private: class RemoveShapeCommand : public QUndoCommand { public: - RemoveShapeCommand(Document *doc, const QString &shapeName, QUndoCommand *parent = 0); + RemoveShapeCommand(Document *doc, const QString &shapeName, + QUndoCommand *parent = nullptr); void undo() override; void redo() override; @@ -83,8 +85,8 @@ private: class SetShapeColorCommand : public QUndoCommand { public: - SetShapeColorCommand(Document *doc, const QString &shapeName, const QColor &color, - QUndoCommand *parent = 0); + SetShapeColorCommand(Document *doc, const QString &shapeName, + const QColor &color, QUndoCommand *parent = nullptr); void undo() override; void redo() override; @@ -102,8 +104,8 @@ private: class SetShapeRectCommand : public QUndoCommand { public: - SetShapeRectCommand(Document *doc, const QString &shapeName, const QRect &rect, - QUndoCommand *parent = 0); + SetShapeRectCommand(Document *doc, const QString &shapeName, + const QRect &rect, QUndoCommand *parent = nullptr); void undo() override; void redo() override; diff --git a/examples/widgets/tools/undo/document.cpp b/examples/widgets/tools/undo/document.cpp index 8935f98a7a2..2deed83a99a 100644 --- a/examples/widgets/tools/undo/document.cpp +++ b/examples/widgets/tools/undo/document.cpp @@ -48,14 +48,15 @@ ** ****************************************************************************/ -#include -#include -#include -#include #include "document.h" #include "commands.h" -static const int resizeHandleWidth = 6; +#include +#include +#include +#include + +static constexpr int resizeHandleWidth = 6; /****************************************************************************** ** Shape @@ -96,26 +97,21 @@ QRect Shape::resizeHandle() const QString Shape::typeToString(Type type) { - QString result; - switch (type) { case Rectangle: - result = QLatin1String("Rectangle"); - break; + return QLatin1String("Rectangle"); case Circle: - result = QLatin1String("Circle"); - break; + return QLatin1String("Circle"); case Triangle: - result = QLatin1String("Triangle"); - break; + return QLatin1String("Triangle"); } - return result; + return QString(); } Shape::Type Shape::stringToType(const QString &s, bool *ok) { - if (ok != 0) + if (ok != nullptr) *ok = true; if (s == QLatin1String("Rectangle")) @@ -125,7 +121,7 @@ Shape::Type Shape::stringToType(const QString &s, bool *ok) if (s == QLatin1String("Triangle")) return Triangle; - if (ok != 0) + if (ok != nullptr) *ok = false; return Rectangle; } @@ -135,10 +131,8 @@ Shape::Type Shape::stringToType(const QString &s, bool *ok) */ Document::Document(QWidget *parent) - : QWidget(parent), m_currentIndex(-1), m_mousePressIndex(-1), m_resizeHandlePressed(false) + : QWidget(parent), m_undoStack(new QUndoStack(this)) { - m_undoStack = new QUndoStack(this); - setAutoFillBackground(true); setBackgroundRole(QPalette::Base); diff --git a/examples/widgets/tools/undo/document.h b/examples/widgets/tools/undo/document.h index 8076d7185c7..01447ef5415 100644 --- a/examples/widgets/tools/undo/document.h +++ b/examples/widgets/tools/undo/document.h @@ -70,7 +70,7 @@ public: QColor color() const; static QString typeToString(Type type); - static Type stringToType(const QString &s, bool *ok = 0); + static Type stringToType(const QString &s, bool *ok = nullptr); static const QSize minSize; @@ -88,7 +88,7 @@ class Document : public QWidget Q_OBJECT public: - Document(QWidget *parent = 0); + Document(QWidget *parent = nullptr); QString addShape(const Shape &shape); void deleteShape(const QString &shapeName); @@ -121,14 +121,13 @@ private: int indexAt(const QPoint &pos) const; QString uniqueName(const QString &name) const; - QList m_shapeList; - int m_currentIndex; - int m_mousePressIndex; + QVector m_shapeList; QPoint m_mousePressOffset; - bool m_resizeHandlePressed; QString m_fileName; - - QUndoStack *m_undoStack; + QUndoStack *m_undoStack = nullptr; + int m_currentIndex = -1; + int m_mousePressIndex = -1; + bool m_resizeHandlePressed = false; }; #endif // DOCUMENT_H diff --git a/examples/widgets/tools/undo/mainwindow.cpp b/examples/widgets/tools/undo/mainwindow.cpp index 118d604742e..9d83e3067a7 100644 --- a/examples/widgets/tools/undo/mainwindow.cpp +++ b/examples/widgets/tools/undo/mainwindow.cpp @@ -48,6 +48,10 @@ ** ****************************************************************************/ +#include "mainwindow.h" +#include "document.h" +#include "commands.h" + #include #include #include @@ -55,9 +59,6 @@ #include #include #include -#include "document.h" -#include "mainwindow.h" -#include "commands.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) @@ -122,17 +123,17 @@ MainWindow::MainWindow(QWidget *parent) void MainWindow::updateActions() { Document *doc = currentDocument(); - m_undoGroup->setActiveStack(doc == 0 ? 0 : doc->undoStack()); - QString shapeName = doc == 0 ? QString() : doc->currentShapeName(); + m_undoGroup->setActiveStack(doc == nullptr ? nullptr : doc->undoStack()); + QString shapeName = doc == nullptr ? QString() : doc->currentShapeName(); - actionAddRobot->setEnabled(doc != 0); - actionAddSnowman->setEnabled(doc != 0); - actionAddCircle->setEnabled(doc != 0); - actionAddRectangle->setEnabled(doc != 0); - actionAddTriangle->setEnabled(doc != 0); - actionClose->setEnabled(doc != 0); - actionSave->setEnabled(doc != 0 && !doc->undoStack()->isClean()); - undoLimit->setEnabled(doc != 0 && doc->undoStack()->count() == 0); + actionAddRobot->setEnabled(doc != nullptr); + actionAddSnowman->setEnabled(doc != nullptr); + actionAddCircle->setEnabled(doc != nullptr); + actionAddRectangle->setEnabled(doc != nullptr); + actionAddTriangle->setEnabled(doc != nullptr); + actionClose->setEnabled(doc != nullptr); + actionSave->setEnabled(doc != nullptr && !doc->undoStack()->isClean()); + undoLimit->setEnabled(doc != nullptr && doc->undoStack()->count() == 0); if (shapeName.isEmpty()) { actionRed->setEnabled(false); @@ -147,7 +148,7 @@ void MainWindow::updateActions() actionRemoveShape->setEnabled(true); } - if (doc != 0) { + if (doc != nullptr) { int index = documentTabs->indexOf(doc); Q_ASSERT(index != -1); static const QIcon unsavedIcon(":/icons/filesave.png"); @@ -264,7 +265,7 @@ void MainWindow::removeDocument(Document *doc) void MainWindow::saveDocument() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; for (;;) { @@ -298,7 +299,7 @@ void MainWindow::saveDocument() void MainWindow::closeDocument() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; if (!doc->undoStack()->isClean()) { @@ -338,10 +339,10 @@ static QRect randomRect(const QSize &s) { QSize min = Shape::minSize; - int left = (int) ((0.0 + s.width() - min.width())*(QRandomGenerator::global()->bounded(1.0))); - int top = (int) ((0.0 + s.height() - min.height())*(QRandomGenerator::global()->bounded(1.0))); - int width = (int) ((0.0 + s.width() - left - min.width())*(QRandomGenerator::global()->bounded(1.0))) + min.width(); - int height = (int) ((0.0 + s.height() - top - min.height())*(QRandomGenerator::global()->bounded(1.0))) + min.height(); + int left = qRound((s.width() - min.width()) * (QRandomGenerator::global()->bounded(1.0))); + int top = qRound((s.height() - min.height()) * (QRandomGenerator::global()->bounded(1.0))); + int width = qRound((s.width() - left - min.width()) * (QRandomGenerator::global()->bounded(1.0))) + min.width(); + int height = qRound((s.height() - top - min.height()) * (QRandomGenerator::global()->bounded(1.0))) + min.height(); return QRect(left, top, width, height); } @@ -349,7 +350,7 @@ static QRect randomRect(const QSize &s) void MainWindow::addShape() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; Shape::Type type; @@ -369,7 +370,7 @@ void MainWindow::addShape() void MainWindow::removeShape() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; QString shapeName = doc->currentShapeName(); @@ -382,7 +383,7 @@ void MainWindow::removeShape() void MainWindow::setShapeColor() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; QString shapeName = doc->currentShapeName(); @@ -409,7 +410,7 @@ void MainWindow::setShapeColor() void MainWindow::addSnowman() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; // Create a macro command using beginMacro() and endMacro() @@ -427,7 +428,7 @@ void MainWindow::addSnowman() void MainWindow::addRobot() { Document *doc = currentDocument(); - if (doc == 0) + if (doc == nullptr) return; // Compose a macro command by explicitly adding children to a parent command diff --git a/examples/widgets/tools/undo/mainwindow.h b/examples/widgets/tools/undo/mainwindow.h index 57c1f87ab20..87ee3084fbf 100644 --- a/examples/widgets/tools/undo/mainwindow.h +++ b/examples/widgets/tools/undo/mainwindow.h @@ -61,7 +61,7 @@ class MainWindow : public QMainWindow, public Ui::MainWindow Q_OBJECT public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); void addDocument(Document *doc); void removeDocument(Document *doc); diff --git a/examples/widgets/tools/undoframework/commands.cpp b/examples/widgets/tools/undoframework/commands.cpp index c3e7383de15..077d7eccaa5 100644 --- a/examples/widgets/tools/undoframework/commands.cpp +++ b/examples/widgets/tools/undoframework/commands.cpp @@ -48,19 +48,17 @@ ** ****************************************************************************/ -#include - #include "commands.h" #include "diagramitem.h" +#include + //! [0] MoveCommand::MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, - QUndoCommand *parent) - : QUndoCommand(parent) + QUndoCommand *parent) + : QUndoCommand(parent), myDiagramItem(diagramItem) + , myOldPos(oldPos), newPos(diagramItem->pos()) { - myDiagramItem = diagramItem; - newPos = diagramItem->pos(); - myOldPos = oldPos; } //! [0] @@ -71,7 +69,7 @@ bool MoveCommand::mergeWith(const QUndoCommand *command) DiagramItem *item = moveCommand->myDiagramItem; if (myDiagramItem != item) - return false; + return false; newPos = item->pos(); setText(QObject::tr("Move %1") @@ -102,9 +100,8 @@ void MoveCommand::redo() //! [4] DeleteCommand::DeleteCommand(QGraphicsScene *scene, QUndoCommand *parent) - : QUndoCommand(parent) + : QUndoCommand(parent), myGraphicsScene(scene) { - myGraphicsScene = scene; QList list = myGraphicsScene->selectedItems(); list.first()->setSelected(false); myDiagramItem = static_cast(list.first()); @@ -131,11 +128,10 @@ void DeleteCommand::redo() //! [7] AddCommand::AddCommand(DiagramItem::DiagramType addType, QGraphicsScene *scene, QUndoCommand *parent) - : QUndoCommand(parent) + : QUndoCommand(parent), myGraphicsScene(scene) { static int itemCount = 0; - myGraphicsScene = scene; myDiagramItem = new DiagramItem(addType); initialPosition = QPointF((itemCount * 15) % int(scene->width()), (itemCount * 15) % int(scene->height())); diff --git a/examples/widgets/tools/undoframework/commands.h b/examples/widgets/tools/undoframework/commands.h index dc53c145575..185d36d6683 100644 --- a/examples/widgets/tools/undoframework/commands.h +++ b/examples/widgets/tools/undoframework/commands.h @@ -62,7 +62,7 @@ public: enum { Id = 1234 }; MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, - QUndoCommand *parent = 0); + QUndoCommand *parent = nullptr); void undo() override; void redo() override; @@ -80,7 +80,7 @@ private: class DeleteCommand : public QUndoCommand { public: - explicit DeleteCommand(QGraphicsScene *graphicsScene, QUndoCommand *parent = 0); + explicit DeleteCommand(QGraphicsScene *graphicsScene, QUndoCommand *parent = nullptr); void undo() override; void redo() override; @@ -96,7 +96,7 @@ class AddCommand : public QUndoCommand { public: AddCommand(DiagramItem::DiagramType addType, QGraphicsScene *graphicsScene, - QUndoCommand *parent = 0); + QUndoCommand *parent = nullptr); ~AddCommand(); void undo() override; diff --git a/examples/widgets/tools/undoframework/diagramitem.cpp b/examples/widgets/tools/undoframework/diagramitem.cpp index 723645c9b24..91da6538cff 100644 --- a/examples/widgets/tools/undoframework/diagramitem.cpp +++ b/examples/widgets/tools/undoframework/diagramitem.cpp @@ -48,10 +48,11 @@ ** ****************************************************************************/ -#include - #include "diagramitem.h" +#include +#include + DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item) : QGraphicsPolygonItem(item) { @@ -65,7 +66,9 @@ DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item) setPolygon(trianglePolygon); } - QColor color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)); + QColor color(QRandomGenerator::global()->bounded(256), + QRandomGenerator::global()->bounded(256), + QRandomGenerator::global()->bounded(256)); QBrush brush(color); setBrush(brush); setFlag(QGraphicsItem::ItemIsSelectable); diff --git a/examples/widgets/tools/undoframework/diagramitem.h b/examples/widgets/tools/undoframework/diagramitem.h index 1638dcbea8b..13ff614427f 100644 --- a/examples/widgets/tools/undoframework/diagramitem.h +++ b/examples/widgets/tools/undoframework/diagramitem.h @@ -66,9 +66,10 @@ public: enum { Type = UserType + 1 }; enum DiagramType { Box, Triangle }; - explicit DiagramItem(DiagramType diagramType, QGraphicsItem *item = 0); + explicit DiagramItem(DiagramType diagramType, QGraphicsItem *item = nullptr); - DiagramType diagramType() const { + DiagramType diagramType() const + { return polygon() == boxPolygon ? Box : Triangle; } int type() const override { return Type; } diff --git a/examples/widgets/tools/undoframework/diagramscene.cpp b/examples/widgets/tools/undoframework/diagramscene.cpp index 63aad97cb1d..65909ab6cbc 100644 --- a/examples/widgets/tools/undoframework/diagramscene.cpp +++ b/examples/widgets/tools/undoframework/diagramscene.cpp @@ -48,27 +48,24 @@ ** ****************************************************************************/ -#include - #include "diagramscene.h" #include "diagramitem.h" +#include + DiagramScene::DiagramScene(QObject *parent) : QGraphicsScene(parent) -{ - movingItem = 0; -} +{} void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event) { QPointF mousePos(event->buttonDownScenePos(Qt::LeftButton).x(), event->buttonDownScenePos(Qt::LeftButton).y()); const QList itemList = items(mousePos); - movingItem = itemList.isEmpty() ? 0 : itemList.first(); + movingItem = itemList.isEmpty() ? nullptr : itemList.first(); - if (movingItem != 0 && event->button() == Qt::LeftButton) { + if (movingItem != nullptr && event->button() == Qt::LeftButton) oldPos = movingItem->pos(); - } clearSelection(); QGraphicsScene::mousePressEvent(event); @@ -76,11 +73,11 @@ void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event) void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (movingItem != 0 && event->button() == Qt::LeftButton) { + if (movingItem != nullptr && event->button() == Qt::LeftButton) { if (oldPos != movingItem->pos()) emit itemMoved(qgraphicsitem_cast(movingItem), oldPos); - movingItem = 0; + movingItem = nullptr; } QGraphicsScene::mouseReleaseEvent(event); } diff --git a/examples/widgets/tools/undoframework/diagramscene.h b/examples/widgets/tools/undoframework/diagramscene.h index b1e2804ba68..205d4162bb5 100644 --- a/examples/widgets/tools/undoframework/diagramscene.h +++ b/examples/widgets/tools/undoframework/diagramscene.h @@ -66,7 +66,7 @@ class DiagramScene : public QGraphicsScene Q_OBJECT public: - DiagramScene(QObject *parent = 0); + DiagramScene(QObject *parent = nullptr); signals: void itemMoved(DiagramItem *movedItem, const QPointF &movedFromPosition); @@ -76,7 +76,7 @@ protected: void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; private: - QGraphicsItem *movingItem; + QGraphicsItem *movingItem = nullptr; QPointF oldPos; }; //! [0] diff --git a/examples/widgets/tools/undoframework/main.cpp b/examples/widgets/tools/undoframework/main.cpp index 51fb5c53ebf..cf090f56eb5 100644 --- a/examples/widgets/tools/undoframework/main.cpp +++ b/examples/widgets/tools/undoframework/main.cpp @@ -48,7 +48,7 @@ ** ****************************************************************************/ -#include +#include #include "mainwindow.h" diff --git a/examples/widgets/tools/undoframework/mainwindow.cpp b/examples/widgets/tools/undoframework/mainwindow.cpp index e95d50d1646..583af11a2b4 100644 --- a/examples/widgets/tools/undoframework/mainwindow.cpp +++ b/examples/widgets/tools/undoframework/mainwindow.cpp @@ -48,13 +48,18 @@ ** ****************************************************************************/ -#include - #include "mainwindow.h" #include "diagramscene.h" #include "diagramitem.h" #include "commands.h" +#include +#include +#include +#include +#include +#include + //! [0] MainWindow::MainWindow() { diff --git a/examples/widgets/tools/undoframework/mainwindow.h b/examples/widgets/tools/undoframework/mainwindow.h index def2b7d7890..c1a56e07701 100644 --- a/examples/widgets/tools/undoframework/mainwindow.h +++ b/examples/widgets/tools/undoframework/mainwindow.h @@ -87,22 +87,22 @@ private: void createMenus(); void createUndoView(); - QAction *deleteAction; - QAction *addBoxAction; - QAction *addTriangleAction; - QAction *undoAction; - QAction *redoAction; - QAction *exitAction; - QAction *aboutAction; + QAction *deleteAction = nullptr; + QAction *addBoxAction = nullptr; + QAction *addTriangleAction = nullptr; + QAction *undoAction = nullptr; + QAction *redoAction = nullptr; + QAction *exitAction = nullptr; + QAction *aboutAction = nullptr; - QMenu *fileMenu; - QMenu *editMenu; - QMenu *itemMenu; - QMenu *helpMenu; + QMenu *fileMenu = nullptr; + QMenu *editMenu = nullptr; + QMenu *itemMenu = nullptr; + QMenu *helpMenu = nullptr; - DiagramScene *diagramScene; - QUndoStack *undoStack; - QUndoView *undoView; + DiagramScene *diagramScene = nullptr; + QUndoStack *undoStack = nullptr; + QUndoView *undoView = nullptr; }; //! [0] From 137cbd1c7200809cc3945c6d4b6deee560cdc9fc Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Thu, 29 Aug 2019 23:58:58 +0200 Subject: [PATCH 09/41] Cocoa: Set the accepted action to be the one from the response MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By setting the accepted action to be the one from the response it will enable the user to set the drop action in their code and this will be reflected at the platform level. Change-Id: I7b9459b228c00ef01d91649b3405316729713164 Fixes: QTBUG-77427 Reviewed-by: Morten Johan Sørvig --- src/plugins/platforms/cocoa/qnsview_dragging.mm | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/plugins/platforms/cocoa/qnsview_dragging.mm b/src/plugins/platforms/cocoa/qnsview_dragging.mm index 37e972dba9e..41b96b2df67 100644 --- a/src/plugins/platforms/cocoa/qnsview_dragging.mm +++ b/src/plugins/platforms/cocoa/qnsview_dragging.mm @@ -270,6 +270,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin // The drag was started from within the application response = QWindowSystemInterface::handleDrop(target, nativeDrag->dragMimeData(), point, qtAllowed, buttons, modifiers); + nativeDrag->setAcceptedAction(response.acceptedAction()); } else { QCocoaDropData mimeData(sender.draggingPasteboard); response = QWindowSystemInterface::handleDrop(target, &mimeData, @@ -282,6 +283,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin { Q_UNUSED(session); Q_UNUSED(screenPoint); + Q_UNUSED(operation); if (!m_platformWindow) return; @@ -290,8 +292,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin if (!target) return; - QCocoaDrag* nativeDrag = QCocoaIntegration::instance()->drag(); - nativeDrag->setAcceptedAction(qt_mac_mapNSDragOperation(operation)); + QCocoaIntegration::instance()->drag(); // Qt starts drag-and-drop on a mouse button press event. Cococa in // this case won't send the matching release event, so we have to From 72259e7186cdba25fa856bf379a35326f1cbad3d Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 9 Sep 2019 17:35:05 +0200 Subject: [PATCH 10/41] Brush up QReadWriteLock benchmark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add override - tests C++17 shared_mutex in addition to C++14 shared_timed_mutex - replace manual memory management with unique_ptr Change-Id: If52df2097a4b92c10df4a7cdbb1c506d64b673e3 Reviewed-by: Mårten Nordheim --- .../thread/qreadwritelock/qreadwritelock.pro | 3 +- .../qreadwritelock/tst_qreadwritelock.cpp | 28 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/tests/benchmarks/corelib/thread/qreadwritelock/qreadwritelock.pro b/tests/benchmarks/corelib/thread/qreadwritelock/qreadwritelock.pro index 86102adecdc..a1827d0276e 100644 --- a/tests/benchmarks/corelib/thread/qreadwritelock/qreadwritelock.pro +++ b/tests/benchmarks/corelib/thread/qreadwritelock/qreadwritelock.pro @@ -1,6 +1,7 @@ TEMPLATE = app TARGET = tst_bench_qreadwritelock -QT = core testlib +QT = core-private testlib SOURCES += tst_qreadwritelock.cpp CONFIG += c++14 # for std::shared_timed_mutex +CONFIG += c++1z # for std::shared_mutex diff --git a/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp b/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp index fcf600a059f..4093e976072 100644 --- a/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp +++ b/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp @@ -28,12 +28,14 @@ #include #include +#include #include #if QT_HAS_INCLUDE() #if __cplusplus > 201103L #include #endif #endif +#include // Wrapers that take pointers instead of reference to have the same interface as Qt template @@ -106,6 +108,14 @@ void tst_QReadWriteLock::uncontended_data() << FunctionPtrHolder(testUncontended); QTest::newRow("std::mutex") << FunctionPtrHolder( testUncontended>>); +#ifdef __cpp_lib_shared_mutex + QTest::newRow("std::shared_mutex, read") << FunctionPtrHolder( + testUncontended>>); + QTest::newRow("std::shared_mutex, write") << FunctionPtrHolder( + testUncontended>>); +#endif #if defined __cpp_lib_shared_timed_mutex QTest::newRow("std::shared_timed_mutex, read") << FunctionPtrHolder( testUncontended threads; + std::vector> threads; for (int i = 0; i < threadCount; ++i) { - auto t = new Thread; + auto t = qt_make_unique(); t->lock = &lock; - threads.append(t); + threads.push_back(std::move(t)); } QBENCHMARK { - for (auto t : threads) { + for (auto &t : threads) { t->start(); } - for (auto t : threads) { + for (auto &t : threads) { t->wait(); } } - qDeleteAll(threads); } void tst_QReadWriteLock::readOnly_data() @@ -166,6 +175,11 @@ void tst_QReadWriteLock::readOnly_data() QTest::newRow("QReadWriteLock") << FunctionPtrHolder(testReadOnly); QTest::newRow("std::mutex") << FunctionPtrHolder( testReadOnly>>); +#ifdef __cpp_lib_shared_mutex + QTest::newRow("std::shared_mutex") << FunctionPtrHolder( + testReadOnly>>); +#endif #if defined __cpp_lib_shared_timed_mutex QTest::newRow("std::shared_timed_mutex") << FunctionPtrHolder( testReadOnly Date: Mon, 9 Sep 2019 12:14:26 +0200 Subject: [PATCH 11/41] QtGui: replace some QMutexLockers with (new) qt_{scoped,unique}_lock() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In QImageReader, also replace a QMutex with a QBasicMutex, making the code similar to the corresponding code in QPicture. Change-Id: Ia1cd546eccd3662837762e506235e350b7a08647 Reviewed-by: Mårten Nordheim --- src/gui/image/qimagereader.cpp | 6 +++--- src/gui/image/qpicture.cpp | 3 ++- src/gui/kernel/qguiapplication.cpp | 7 ++++--- src/gui/kernel/qopenglcontext.cpp | 11 ++++++----- src/gui/kernel/qtouchdevice.cpp | 10 +++++----- 5 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/gui/image/qimagereader.cpp b/src/gui/image/qimagereader.cpp index 6a0763e6966..dff24b449a1 100644 --- a/src/gui/image/qimagereader.cpp +++ b/src/gui/image/qimagereader.cpp @@ -150,7 +150,7 @@ // factory loader #include #include -#include +#include // for qt_getImageText #include @@ -186,8 +186,8 @@ static QImageIOHandler *createReadHandlerHelper(QIODevice *device, QByteArray suffix; #ifndef QT_NO_IMAGEFORMATPLUGIN - static QMutex mutex; - QMutexLocker locker(&mutex); + static QBasicMutex mutex; + const auto locker = qt_scoped_lock(mutex); typedef QMultiMap PluginKeyMap; diff --git a/src/gui/image/qpicture.cpp b/src/gui/image/qpicture.cpp index 8548f1857ef..978a07b9f9d 100644 --- a/src/gui/image/qpicture.cpp +++ b/src/gui/image/qpicture.cpp @@ -57,6 +57,7 @@ #include "qregexp.h" #include "qregion.h" #include "qdebug.h" +#include #include @@ -1427,7 +1428,7 @@ void qt_init_picture_plugins() typedef PluginKeyMap::const_iterator PluginKeyMapConstIterator; static QBasicMutex mutex; - QMutexLocker locker(&mutex); + const auto locker = qt_scoped_lock(mutex); static QFactoryLoader loader(QPictureFormatInterface_iid, QStringLiteral("/pictureformats")); diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp index 47bd5727a9a..a3ef3b23144 100644 --- a/src/gui/kernel/qguiapplication.cpp +++ b/src/gui/kernel/qguiapplication.cpp @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -3305,7 +3306,7 @@ void QGuiApplicationPrivate::applyWindowGeometrySpecificationTo(QWindow *window) QFont QGuiApplication::font() { Q_ASSERT_X(QGuiApplicationPrivate::self, "QGuiApplication::font()", "no QGuiApplication instance"); - QMutexLocker locker(&applicationFontMutex); + const auto locker = qt_scoped_lock(applicationFontMutex); initFontUnlocked(); return *QGuiApplicationPrivate::app_font; } @@ -3317,7 +3318,7 @@ QFont QGuiApplication::font() */ void QGuiApplication::setFont(const QFont &font) { - QMutexLocker locker(&applicationFontMutex); + auto locker = qt_unique_lock(applicationFontMutex); const bool emitChange = !QGuiApplicationPrivate::app_font || (*QGuiApplicationPrivate::app_font != font); if (!QGuiApplicationPrivate::app_font) @@ -4081,7 +4082,7 @@ void QGuiApplicationPrivate::notifyThemeChanged() sendApplicationPaletteChange(); } if (!(applicationResourceFlags & ApplicationFontExplicitlySet)) { - QMutexLocker locker(&applicationFontMutex); + const auto locker = qt_scoped_lock(applicationFontMutex); clearFontUnlocked(); initFontUnlocked(); } diff --git a/src/gui/kernel/qopenglcontext.cpp b/src/gui/kernel/qopenglcontext.cpp index 6f51fe3095d..638eb1d12f4 100644 --- a/src/gui/kernel/qopenglcontext.cpp +++ b/src/gui/kernel/qopenglcontext.cpp @@ -45,6 +45,7 @@ #include #include +#include #include #include @@ -1442,7 +1443,7 @@ QOpenGLContextGroup *QOpenGLContextGroup::currentContextGroup() void QOpenGLContextGroupPrivate::addContext(QOpenGLContext *ctx) { - QMutexLocker locker(&m_mutex); + const auto locker = qt_scoped_lock(m_mutex); m_refs.ref(); m_shares << ctx; } @@ -1454,7 +1455,7 @@ void QOpenGLContextGroupPrivate::removeContext(QOpenGLContext *ctx) bool deleteObject = false; { - QMutexLocker locker(&m_mutex); + const auto locker = qt_scoped_lock(m_mutex); m_shares.removeOne(ctx); if (ctx == m_context && !m_shares.isEmpty()) @@ -1502,7 +1503,7 @@ void QOpenGLContextGroupPrivate::cleanup() void QOpenGLContextGroupPrivate::deletePendingResources(QOpenGLContext *ctx) { - QMutexLocker locker(&m_mutex); + const auto locker = qt_scoped_lock(m_mutex); const QList pending = m_pendingDeletion; m_pendingDeletion.clear(); @@ -1543,7 +1544,7 @@ void QOpenGLContextGroupPrivate::deletePendingResources(QOpenGLContext *ctx) QOpenGLSharedResource::QOpenGLSharedResource(QOpenGLContextGroup *group) : m_group(group) { - QMutexLocker locker(&m_group->d_func()->m_mutex); + const auto locker = qt_scoped_lock(m_group->d_func()->m_mutex); m_group->d_func()->m_sharedResources << this; } @@ -1559,7 +1560,7 @@ void QOpenGLSharedResource::free() return; } - QMutexLocker locker(&m_group->d_func()->m_mutex); + const auto locker = qt_scoped_lock(m_group->d_func()->m_mutex); m_group->d_func()->m_sharedResources.removeOne(this); m_group->d_func()->m_pendingDeletion << this; diff --git a/src/gui/kernel/qtouchdevice.cpp b/src/gui/kernel/qtouchdevice.cpp index ea187f54aab..8293fddc597 100644 --- a/src/gui/kernel/qtouchdevice.cpp +++ b/src/gui/kernel/qtouchdevice.cpp @@ -228,7 +228,7 @@ TouchDevices::TouchDevices() */ QList QTouchDevice::devices() { - QMutexLocker lock(&devicesMutex); + const auto locker = qt_scoped_lock(devicesMutex); return deviceList->list; } @@ -237,13 +237,13 @@ QList QTouchDevice::devices() */ bool QTouchDevicePrivate::isRegistered(const QTouchDevice *dev) { - QMutexLocker locker(&devicesMutex); + const auto locker = qt_scoped_lock(devicesMutex); return deviceList->list.contains(dev); } const QTouchDevice *QTouchDevicePrivate::deviceById(quint8 id) { - QMutexLocker locker(&devicesMutex); + const auto locker = qt_scoped_lock(devicesMutex); for (const QTouchDevice *dev : qAsConst(deviceList->list)) if (QTouchDevicePrivate::get(const_cast(dev))->id == id) return dev; @@ -255,7 +255,7 @@ const QTouchDevice *QTouchDevicePrivate::deviceById(quint8 id) */ void QTouchDevicePrivate::registerDevice(const QTouchDevice *dev) { - QMutexLocker lock(&devicesMutex); + const auto locker = qt_scoped_lock(devicesMutex); deviceList->list.append(dev); } @@ -264,7 +264,7 @@ void QTouchDevicePrivate::registerDevice(const QTouchDevice *dev) */ void QTouchDevicePrivate::unregisterDevice(const QTouchDevice *dev) { - QMutexLocker lock(&devicesMutex); + const auto locker = qt_scoped_lock(devicesMutex); deviceList->list.removeOne(dev); } From 0f219d20549030d56f1951a9bd72b25f7a64bbe7 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 9 Sep 2019 16:37:11 +0200 Subject: [PATCH 12/41] QReadWriteLock: use NSDMI to simplify the Private ctor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I7267dedb152186ad8c74cbf2eddd863c3bc0845f Reviewed-by: Olivier Goffart (Woboq GmbH) Reviewed-by: Mårten Nordheim --- src/corelib/thread/qreadwritelock_p.h | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/corelib/thread/qreadwritelock_p.h b/src/corelib/thread/qreadwritelock_p.h index 31da2401c0d..a4d002b7f2a 100644 --- a/src/corelib/thread/qreadwritelock_p.h +++ b/src/corelib/thread/qreadwritelock_p.h @@ -63,17 +63,16 @@ QT_BEGIN_NAMESPACE class QReadWriteLockPrivate { public: - QReadWriteLockPrivate(bool isRecursive = false) - : readerCount(0), writerCount(0), waitingReaders(0), waitingWriters(0), - recursive(isRecursive), id(0), currentWriter(nullptr) {} + explicit QReadWriteLockPrivate(bool isRecursive = false) + : recursive(isRecursive) {} QMutex mutex; QWaitCondition writerCond; QWaitCondition readerCond; - int readerCount; - int writerCount; - int waitingReaders; - int waitingWriters; + int readerCount = 0; + int writerCount = 0; + int waitingReaders = 0; + int waitingWriters = 0; const bool recursive; //Called with the mutex locked @@ -82,19 +81,18 @@ public: void unlock(); //memory management - int id; + int id = 0; void release(); static QReadWriteLockPrivate *allocate(); // Recusive mutex handling - Qt::HANDLE currentWriter; + Qt::HANDLE currentWriter = {}; QHash currentReaders; // called with the mutex unlocked bool recursiveLockForWrite(int timeout); bool recursiveLockForRead(int timeout); void recursiveUnlock(); - }; QT_END_NAMESPACE From 333b1e92297f6fe7de702fce6ef13aa2087d2c65 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 11 Sep 2019 10:39:14 +0200 Subject: [PATCH 13/41] QReadWriteLock: add a check for writeOnly, too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Results on my machine: PASS : tst_QReadWriteLock::writeOnly(QMutex) RESULT : tst_QReadWriteLock::writeOnly():QMutex: 3,607 msecs per iteration (total: 3,607, iterations: 1) PASS : tst_QReadWriteLock::writeOnly(QReadWriteLock) RESULT : tst_QReadWriteLock::writeOnly():QReadWriteLock: 39,703 msecs per iteration (total: 39,703, iterations: 1) PASS : tst_QReadWriteLock::writeOnly(std::mutex) RESULT : tst_QReadWriteLock::writeOnly():std::mutex: 3,697 msecs per iteration (total: 3,697, iterations: 1) PASS : tst_QReadWriteLock::writeOnly(std::shared_mutex) RESULT : tst_QReadWriteLock::writeOnly():std::shared_mutex: 5,727 msecs per iteration (total: 5,727, iterations: 1) PASS : tst_QReadWriteLock::writeOnly(std::shared_timed_mutex) RESULT : tst_QReadWriteLock::writeOnly():std::shared_timed_mutex: 5,921 msecs per iteration (total: 5,921, iterations: 1) (the 'nothing' test of course doesn't work with writing, as writing to the same QString from different threads is UB) Change-Id: Ia78b54963a51eaf6563ce0d243316a3337056a83 Reviewed-by: Olivier Goffart (Woboq GmbH) Reviewed-by: Mårten Nordheim --- .../qreadwritelock/tst_qreadwritelock.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp b/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp index 4093e976072..1d47d986575 100644 --- a/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp +++ b/tests/benchmarks/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp @@ -65,6 +65,8 @@ private slots: void uncontended(); void readOnly_data(); void readOnly(); + void writeOnly_data(); + void writeOnly(); // void readWrite(); }; @@ -193,5 +195,66 @@ void tst_QReadWriteLock::readOnly() holder.value(); } +static QString global_string; + +template +void testWriteOnly() +{ + struct Thread : QThread + { + Mutex *lock; + void run() override + { + for (int i = 0; i < Iterations; ++i) { + QString s = QString::number(i); // Do something outside the lock + Locker locker(lock); + global_string = s; + } + } + }; + Mutex lock; + std::vector> threads; + for (int i = 0; i < threadCount; ++i) { + auto t = qt_make_unique(); + t->lock = &lock; + threads.push_back(std::move(t)); + } + QBENCHMARK { + for (auto &t : threads) { + t->start(); + } + for (auto &t : threads) { + t->wait(); + } + } +} + +void tst_QReadWriteLock::writeOnly_data() +{ + QTest::addColumn("holder"); + + // QTest::newRow("nothing") << FunctionPtrHolder(testWriteOnly); + QTest::newRow("QMutex") << FunctionPtrHolder(testWriteOnly); + QTest::newRow("QReadWriteLock") << FunctionPtrHolder(testWriteOnly); + QTest::newRow("std::mutex") << FunctionPtrHolder( + testWriteOnly>>); +#ifdef __cpp_lib_shared_mutex + QTest::newRow("std::shared_mutex") << FunctionPtrHolder( + testWriteOnly>>); +#endif +#if defined __cpp_lib_shared_timed_mutex + QTest::newRow("std::shared_timed_mutex") << FunctionPtrHolder( + testWriteOnly>>); +#endif +} + +void tst_QReadWriteLock::writeOnly() +{ + QFETCH(FunctionPtrHolder, holder); + holder.value(); +} + QTEST_MAIN(tst_QReadWriteLock) #include "tst_qreadwritelock.moc" From 08ad96404b4c915eece1a547bf12e91664e7cdff Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 21 Aug 2019 22:14:16 +0200 Subject: [PATCH 14/41] QCoreApplication: work towards replacing a QRecursiveMutex with a QMutex At first glance, libraryPathMutex is only recursive because setLibraryPaths(), addLibraryPath() and removeLibraryPath(), all of which lock libraryPathMutex, may call libraryPaths(), which does, too. This is easily fixed by splitting libraryPaths() into public libraryPaths() and private libraryPathsLocked(), the latter expecting to be called with the libraryPathMutex already held. And this is what this patch does. However, on second glance, the building of the initial app_libpaths calls a monstrous amount of code, incl. QLibraryInfo, and some of that code probably re-enters one of the library-path functions. So while this patch is a step towards making libraryPathMutex non-recursive, it's probably not the end. Change-Id: I3ed83272ace6966980cf8e1db877f24c89789da3 Reviewed-by: Ulf Hermann Reviewed-by: Edward Welbourne Reviewed-by: Olivier Goffart (Woboq GmbH) --- src/corelib/kernel/qcoreapplication.cpp | 13 ++++++++++--- src/corelib/kernel/qcoreapplication.h | 3 +++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp index 6647ea99f5f..c537e8f51b4 100644 --- a/src/corelib/kernel/qcoreapplication.cpp +++ b/src/corelib/kernel/qcoreapplication.cpp @@ -2693,7 +2693,14 @@ Q_GLOBAL_STATIC(QRecursiveMutex, libraryPathMutex) QStringList QCoreApplication::libraryPaths() { QMutexLocker locker(libraryPathMutex()); + return libraryPathsLocked(); +} +/*! + \internal +*/ +QStringList QCoreApplication::libraryPathsLocked() +{ if (coreappdata()->manual_libpaths) return *(coreappdata()->manual_libpaths); @@ -2769,7 +2776,7 @@ void QCoreApplication::setLibraryPaths(const QStringList &paths) // When the application is constructed it should still amend the paths. So we keep the originals // around, and even create them if they don't exist, yet. if (!coreappdata()->app_libpaths) - libraryPaths(); + libraryPathsLocked(); if (coreappdata()->manual_libpaths) *(coreappdata()->manual_libpaths) = paths; @@ -2812,7 +2819,7 @@ void QCoreApplication::addLibraryPath(const QString &path) return; } else { // make sure that library paths are initialized - libraryPaths(); + libraryPathsLocked(); QStringList *app_libpaths = coreappdata()->app_libpaths.data(); if (app_libpaths->contains(canonicalPath)) return; @@ -2851,7 +2858,7 @@ void QCoreApplication::removeLibraryPath(const QString &path) return; } else { // make sure that library paths is initialized - libraryPaths(); + libraryPathsLocked(); QStringList *app_libpaths = coreappdata()->app_libpaths.data(); if (!app_libpaths->contains(canonicalPath)) return; diff --git a/src/corelib/kernel/qcoreapplication.h b/src/corelib/kernel/qcoreapplication.h index b7df004736d..71ea124fbe0 100644 --- a/src/corelib/kernel/qcoreapplication.h +++ b/src/corelib/kernel/qcoreapplication.h @@ -208,6 +208,9 @@ private: static bool notifyInternal2(QObject *receiver, QEvent *); static bool forwardEvent(QObject *receiver, QEvent *event, QEvent *originatingEvent = nullptr); #endif +#if QT_CONFIG(library) + static QStringList libraryPathsLocked(); +#endif static QCoreApplication *self; From 447ee95d5e050c5db1636c5d3bd0edbf59f26108 Mon Sep 17 00:00:00 2001 From: Timur Pocheptsov Date: Wed, 11 Sep 2019 09:25:51 +0200 Subject: [PATCH 15/41] QHttpThreadDelegate - remove unneeded code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while cleaning up SPDY remains: I've noticed that for H2 case I never check if incomingSslConfiguration is nullptr or not, but the code several lines below - does it, which looks kind of moronic. This configuration is initialized when the delegate is created, so no need to have this if-statement. Instead, assert, making this behavior a requirement. Change-Id: I90fb84337be925a3288252aa2491b4c23d6c6cbb Reviewed-by: Mårten Nordheim --- src/network/access/qhttpthreaddelegate.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/network/access/qhttpthreaddelegate.cpp b/src/network/access/qhttpthreaddelegate.cpp index 3d1849010bd..46a6615f4da 100644 --- a/src/network/access/qhttpthreaddelegate.cpp +++ b/src/network/access/qhttpthreaddelegate.cpp @@ -297,6 +297,11 @@ void QHttpThreadDelegate::startRequest() connectionType = QHttpNetworkConnection::ConnectionTypeHTTP2Direct; } +#if QT_CONFIG(ssl) + // See qnetworkreplyhttpimpl, delegate's initialization code. + Q_ASSERT(!ssl || incomingSslConfiguration.data()); +#endif // QT_CONFIG(ssl) + const bool isH2 = httpRequest.isHTTP2Allowed() || httpRequest.isHTTP2Direct(); if (isH2) { #if QT_CONFIG(ssl) @@ -316,9 +321,6 @@ void QHttpThreadDelegate::startRequest() } #ifndef QT_NO_SSL - if (ssl && !incomingSslConfiguration.data()) - incomingSslConfiguration.reset(new QSslConfiguration); - if (!isH2 && httpRequest.isSPDYAllowed() && ssl) { connectionType = QHttpNetworkConnection::ConnectionTypeSPDY; urlCopy.setScheme(QStringLiteral("spdy")); // to differentiate SPDY requests from HTTPS requests From f567129bb514b5856c7d1320cdc4dd5a84a5b6e3 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Sat, 7 Sep 2019 19:23:09 +0200 Subject: [PATCH 16/41] rhi: d3d11: Add the device lost testing machinery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The device can be lost when physically removing the graphics adapter, disabling the driver (Device Manager), upgrading/uninstalling the graphics driver, and when it is reset due to an error. Some of these can (and should) be tested manually, but the last one has a convenient, programmatic way of triggering: by triggering the timeout detection and recovery (TDR) of WDDM. A compute shader with an infinite loop should trigger this after 2 seconds by default. All tests in tests/manual/rhi can now be started with a --curse argument where specifies the number of frames to render before breaking the device. Qt Quick will get an environment variable with similar semantics in a separate patch. Change-Id: I4b6f8d977a15b5b89d686b3973965df6435810ae Reviewed-by: Christian Strømme --- src/gui/rhi/cs_tdr.h | 209 ++++++++++++++++++++++++++++ src/gui/rhi/qrhid3d11.cpp | 57 +++++++- src/gui/rhi/qrhid3d11_p.h | 3 + src/gui/rhi/qrhid3d11_p_p.h | 13 ++ src/gui/rhi/tdr.hlsl | 9 ++ tests/manual/rhi/shared/examplefw.h | 15 +- 6 files changed, 304 insertions(+), 2 deletions(-) create mode 100644 src/gui/rhi/cs_tdr.h create mode 100644 src/gui/rhi/tdr.hlsl diff --git a/src/gui/rhi/cs_tdr.h b/src/gui/rhi/cs_tdr.h new file mode 100644 index 00000000000..f80cb3a4985 --- /dev/null +++ b/src/gui/rhi/cs_tdr.h @@ -0,0 +1,209 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Gui module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#ifdef Q_OS_WIN + +#include + +#if 0 +// +// Generated by Microsoft (R) HLSL Shader Compiler 10.1 +// +// +// Buffer Definitions: +// +// cbuffer ConstantBuffer +// { +// +// uint zero; // Offset: 0 Size: 4 +// +// } +// +// +// Resource Bindings: +// +// Name Type Format Dim HLSL Bind Count +// ------------------------------ ---------- ------- ----------- -------------- ------ +// uav UAV uint buf u0 1 +// ConstantBuffer cbuffer NA NA cb0 1 +// +// +// +// Input signature: +// +// Name Index Mask Register SysValue Format Used +// -------------------- ----- ------ -------- -------- ------- ------ +// no Input +// +// Output signature: +// +// Name Index Mask Register SysValue Format Used +// -------------------- ----- ------ -------- -------- ------- ------ +// no Output +cs_5_0 +dcl_globalFlags refactoringAllowed +dcl_constantbuffer CB0[1], immediateIndexed +dcl_uav_typed_buffer (uint,uint,uint,uint) u0 +dcl_input vThreadID.x +dcl_thread_group 256, 1, 1 +loop + breakc_nz cb0[0].x + store_uav_typed u0.xyzw, vThreadID.xxxx, cb0[0].xxxx +endloop +ret +// Approximately 5 instruction slots used +#endif + +const BYTE g_killDeviceByTimingOut[] = +{ + 68, 88, 66, 67, 217, 62, + 220, 38, 136, 51, 86, 245, + 161, 96, 18, 35, 141, 17, + 26, 13, 1, 0, 0, 0, + 164, 2, 0, 0, 5, 0, + 0, 0, 52, 0, 0, 0, + 100, 1, 0, 0, 116, 1, + 0, 0, 132, 1, 0, 0, + 8, 2, 0, 0, 82, 68, + 69, 70, 40, 1, 0, 0, + 1, 0, 0, 0, 144, 0, + 0, 0, 2, 0, 0, 0, + 60, 0, 0, 0, 0, 5, + 83, 67, 0, 1, 0, 0, + 0, 1, 0, 0, 82, 68, + 49, 49, 60, 0, 0, 0, + 24, 0, 0, 0, 32, 0, + 0, 0, 40, 0, 0, 0, + 36, 0, 0, 0, 12, 0, + 0, 0, 0, 0, 0, 0, + 124, 0, 0, 0, 4, 0, + 0, 0, 4, 0, 0, 0, + 1, 0, 0, 0, 255, 255, + 255, 255, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, + 0, 0, 128, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, 117, 97, + 118, 0, 67, 111, 110, 115, + 116, 97, 110, 116, 66, 117, + 102, 102, 101, 114, 0, 171, + 128, 0, 0, 0, 1, 0, + 0, 0, 168, 0, 0, 0, + 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 208, 0, 0, 0, 0, 0, + 0, 0, 4, 0, 0, 0, + 2, 0, 0, 0, 220, 0, + 0, 0, 0, 0, 0, 0, + 255, 255, 255, 255, 0, 0, + 0, 0, 255, 255, 255, 255, + 0, 0, 0, 0, 122, 101, + 114, 111, 0, 100, 119, 111, + 114, 100, 0, 171, 0, 0, + 19, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 213, 0, 0, 0, 77, 105, + 99, 114, 111, 115, 111, 102, + 116, 32, 40, 82, 41, 32, + 72, 76, 83, 76, 32, 83, + 104, 97, 100, 101, 114, 32, + 67, 111, 109, 112, 105, 108, + 101, 114, 32, 49, 48, 46, + 49, 0, 73, 83, 71, 78, + 8, 0, 0, 0, 0, 0, + 0, 0, 8, 0, 0, 0, + 79, 83, 71, 78, 8, 0, + 0, 0, 0, 0, 0, 0, + 8, 0, 0, 0, 83, 72, + 69, 88, 124, 0, 0, 0, + 80, 0, 5, 0, 31, 0, + 0, 0, 106, 8, 0, 1, + 89, 0, 0, 4, 70, 142, + 32, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 156, 8, + 0, 4, 0, 224, 17, 0, + 0, 0, 0, 0, 68, 68, + 0, 0, 95, 0, 0, 2, + 18, 0, 2, 0, 155, 0, + 0, 4, 0, 1, 0, 0, + 1, 0, 0, 0, 1, 0, + 0, 0, 48, 0, 0, 1, + 3, 0, 4, 4, 10, 128, + 32, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 164, 0, + 0, 7, 242, 224, 17, 0, + 0, 0, 0, 0, 6, 0, + 2, 0, 6, 128, 32, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 22, 0, 0, 1, + 62, 0, 0, 1, 83, 84, + 65, 84, 148, 0, 0, 0, + 5, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 2, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0 +}; + +#endif // Q_OS_WIN diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index 93eadc047d5..f12e376b58f 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -36,6 +36,7 @@ #include "qrhid3d11_p_p.h" #include "qshader_p.h" +#include "cs_tdr.h" #include #include #include @@ -119,9 +120,14 @@ QT_BEGIN_NAMESPACE */ QRhiD3D11::QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importDevice) - : ofr(this) + : ofr(this), + deviceCurse(this) { debugLayer = params->enableDebugLayer; + + deviceCurse.framesToActivate = params->framesUntilKillingDeviceViaTdr; + deviceCurse.permanent = params->repeatDeviceKill; + importedDevice = importDevice != nullptr; if (importedDevice) { dev = reinterpret_cast(importDevice->dev); @@ -264,6 +270,9 @@ bool QRhiD3D11::create(QRhi::Flags flags) nativeHandlesStruct.dev = dev; nativeHandlesStruct.context = context; + if (deviceCurse.framesToActivate > 0) + deviceCurse.initResources(); + return true; } @@ -281,6 +290,8 @@ void QRhiD3D11::destroy() clearShaderCache(); + deviceCurse.releaseResources(); + if (annotations) { annotations->Release(); annotations = nullptr; @@ -1003,6 +1014,20 @@ QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrame swapChainD->frameCount += 1; contextState.currentSwapChain = nullptr; + + if (deviceCurse.framesToActivate > 0) { + deviceCurse.framesLeft -= 1; + if (deviceCurse.framesLeft == 0) { + deviceCurse.framesLeft = deviceCurse.framesToActivate; + if (!deviceCurse.permanent) + deviceCurse.framesToActivate = -1; + + deviceCurse.activate(); + } else if (deviceCurse.framesLeft % 100 == 0) { + qDebug("Impending doom: %d frames left", deviceCurse.framesLeft); + } + } + return QRhi::FrameOpSuccess; } @@ -3914,4 +3939,34 @@ bool QD3D11SwapChain::buildOrResize() return true; } +void QRhiD3D11::DeviceCurse::initResources() +{ + framesLeft = framesToActivate; + + HRESULT hr = q->dev->CreateComputeShader(g_killDeviceByTimingOut, sizeof(g_killDeviceByTimingOut), nullptr, &cs); + if (FAILED(hr)) { + qWarning("Failed to create compute shader: %s", qPrintable(comErrorMessage(hr))); + return; + } +} + +void QRhiD3D11::DeviceCurse::releaseResources() +{ + if (cs) { + cs->Release(); + cs = nullptr; + } +} + +void QRhiD3D11::DeviceCurse::activate() +{ + if (!cs) + return; + + qDebug("Activating Curse. Goodbye Cruel World."); + + q->context->CSSetShader(cs, nullptr, 0); + q->context->Dispatch(256, 1, 1); +} + QT_END_NAMESPACE diff --git a/src/gui/rhi/qrhid3d11_p.h b/src/gui/rhi/qrhid3d11_p.h index 3e2e492d9c5..5df1843b1ea 100644 --- a/src/gui/rhi/qrhid3d11_p.h +++ b/src/gui/rhi/qrhid3d11_p.h @@ -58,6 +58,9 @@ QT_BEGIN_NAMESPACE struct Q_GUI_EXPORT QRhiD3D11InitParams : public QRhiInitParams { bool enableDebugLayer = false; + + int framesUntilKillingDeviceViaTdr = -1; + bool repeatDeviceKill = false; }; struct Q_GUI_EXPORT QRhiD3D11NativeHandles : public QRhiNativeHandles diff --git a/src/gui/rhi/qrhid3d11_p_p.h b/src/gui/rhi/qrhid3d11_p_p.h index cd44519aaa6..cc4e095d10b 100644 --- a/src/gui/rhi/qrhid3d11_p_p.h +++ b/src/gui/rhi/qrhid3d11_p_p.h @@ -694,6 +694,19 @@ public: QByteArray bytecode; }; QHash m_shaderCache; + + struct DeviceCurse { + DeviceCurse(QRhiD3D11 *impl) : q(impl) { } + QRhiD3D11 *q; + int framesToActivate = -1; + bool permanent = false; + int framesLeft = 0; + ID3D11ComputeShader *cs = nullptr; + + void initResources(); + void releaseResources(); + void activate(); + } deviceCurse; }; Q_DECLARE_TYPEINFO(QRhiD3D11::ActiveReadback, Q_MOVABLE_TYPE); diff --git a/src/gui/rhi/tdr.hlsl b/src/gui/rhi/tdr.hlsl new file mode 100644 index 00000000000..f79de91c4a0 --- /dev/null +++ b/src/gui/rhi/tdr.hlsl @@ -0,0 +1,9 @@ +RWBuffer uav; +cbuffer ConstantBuffer { uint zero; } + +[numthreads(256, 1, 1)] +void killDeviceByTimingOut(uint3 id: SV_DispatchThreadID) +{ + while (zero == 0) + uav[id.x] = zero; +} diff --git a/tests/manual/rhi/shared/examplefw.h b/tests/manual/rhi/shared/examplefw.h index 1a29ef5f7ef..8afacc074a2 100644 --- a/tests/manual/rhi/shared/examplefw.h +++ b/tests/manual/rhi/shared/examplefw.h @@ -126,6 +126,7 @@ int sampleCount = 1; QRhiSwapChain::Flags scFlags = 0; QRhi::BeginFrameFlags beginFrameFlags = 0; QRhi::EndFrameFlags endFrameFlags = 0; +int framesUntilTdr = -1; class Window : public QWindow { @@ -278,6 +279,10 @@ void Window::init() if (graphicsApi == D3D11) { QRhiD3D11InitParams params; params.enableDebugLayer = true; + if (framesUntilTdr > 0) { + params.framesUntilKillingDeviceViaTdr = framesUntilTdr; + params.repeatDeviceKill = true; + } m_r = QRhi::create(QRhi::D3D11, ¶ms, rhiFlags); } #endif @@ -461,8 +466,13 @@ int main(int argc, char **argv) // Testing cleanup both with QWindow::close() (hitting X or Alt-F4) and // QCoreApplication::quit() (e.g. what a menu widget would do) is important. // Use this parameter for the latter. - QCommandLineOption sdOption({ "s", "self-destruct" }, QLatin1String("Self destruct after 5 seconds")); + QCommandLineOption sdOption({ "s", "self-destruct" }, QLatin1String("Self-destruct after 5 seconds.")); cmdLineParser.addOption(sdOption); + // Attempt testing device lost situations on D3D at least. + QCommandLineOption tdrOption(QLatin1String("curse"), QLatin1String("Curse the graphics device. " + "(generate a device reset every frames when on D3D11)"), + QLatin1String("count")); + cmdLineParser.addOption(tdrOption); cmdLineParser.process(app); if (cmdLineParser.isSet(nullOption)) @@ -521,6 +531,9 @@ int main(int argc, char **argv) } #endif + if (cmdLineParser.isSet(tdrOption)) + framesUntilTdr = cmdLineParser.value(tdrOption).toInt(); + // Create and show the window. Window w; #if QT_CONFIG(vulkan) From d1486e2982df9373a7e5816609eff066cac6eb52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Wed, 4 Sep 2019 12:50:37 +0200 Subject: [PATCH 17/41] Simplify QColorSpacePrivate initialization QColorVector and QColorMatrix are default-constructed following the Qt philosophy of types always being well-defined. The corner-case where we need uninitialized versions of these types for performance reasons is handled explicitly. Change-Id: I629334d1ffc63563ec9fd1298c623946e0799d1d Reviewed-by: Paul Olav Tvete Reviewed-by: Simon Hausmann --- src/gui/painting/qcolormatrix_p.h | 16 +++++----------- src/gui/painting/qcolorspace.cpp | 8 +------- src/gui/painting/qcolorspace_p.h | 6 +++--- src/gui/painting/qcolortransform.cpp | 12 +++++++++++- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src/gui/painting/qcolormatrix_p.h b/src/gui/painting/qcolormatrix_p.h index 70d2137119b..edb2d32258c 100644 --- a/src/gui/painting/qcolormatrix_p.h +++ b/src/gui/painting/qcolormatrix_p.h @@ -62,17 +62,16 @@ class QColorVector { public: QColorVector() = default; - Q_DECL_CONSTEXPR QColorVector(float x, float y, float z) : x(x), y(y), z(z), _unused(0.0f) { } + Q_DECL_CONSTEXPR QColorVector(float x, float y, float z) : x(x), y(y), z(z) { } explicit Q_DECL_CONSTEXPR QColorVector(const QPointF &chr) // from XY chromaticity : x(chr.x() / chr.y()) , y(1.0f) , z((1.0 - chr.x() - chr.y()) / chr.y()) - , _unused(0.0f) { } - float x; // X, x or red - float y; // Y, y or green - float z; // Z, Y or blue - float _unused; + float x = 0.0f; // X, x or red + float y = 0.0f; // Y, y or green + float z = 0.0f; // Z, Y or blue + float _unused = 0.0f; friend inline bool operator==(const QColorVector &v1, const QColorVector &v2); friend inline bool operator!=(const QColorVector &v1, const QColorVector &v2); @@ -81,7 +80,6 @@ public: return !x && !y && !z; } - static Q_DECL_CONSTEXPR QColorVector null() { return QColorVector(0.0f, 0.0f, 0.0f); } static bool isValidChromaticity(const QPointF &chr) { if (chr.x() < qreal(0.0) || chr.x() > qreal(1.0)) @@ -187,10 +185,6 @@ public: { r.z, g.z, b.z } }; } - static QColorMatrix null() - { - return { QColorVector::null(), QColorVector::null(), QColorVector::null() }; - } static QColorMatrix identity() { return { { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }; diff --git a/src/gui/painting/qcolorspace.cpp b/src/gui/painting/qcolorspace.cpp index 720c531e3f5..937bb505c96 100644 --- a/src/gui/painting/qcolorspace.cpp +++ b/src/gui/painting/qcolorspace.cpp @@ -146,17 +146,11 @@ QColorMatrix QColorSpacePrimaries::toXyzMatrix() const } QColorSpacePrivate::QColorSpacePrivate() - : primaries(QColorSpace::Primaries::Custom) - , transferFunction(QColorSpace::TransferFunction::Custom) - , gamma(0.0f) - , whitePoint(QColorVector::null()) - , toXyz(QColorMatrix::null()) { } QColorSpacePrivate::QColorSpacePrivate(QColorSpace::NamedColorSpace namedColorSpace) : namedColorSpace(namedColorSpace) - , gamma(0.0f) { switch (namedColorSpace) { case QColorSpace::SRgb: @@ -282,7 +276,7 @@ void QColorSpacePrivate::initialize() void QColorSpacePrivate::setToXyzMatrix() { if (primaries == QColorSpace::Primaries::Custom) { - toXyz = QColorMatrix::null(); + toXyz = QColorMatrix(); whitePoint = QColorVector::D50(); return; } diff --git a/src/gui/painting/qcolorspace_p.h b/src/gui/painting/qcolorspace_p.h index c06681df6b5..e7add19ed38 100644 --- a/src/gui/painting/qcolorspace_p.h +++ b/src/gui/painting/qcolorspace_p.h @@ -124,9 +124,9 @@ public: static constexpr QColorSpace::NamedColorSpace Unknown = QColorSpace::NamedColorSpace(0); QColorSpace::NamedColorSpace namedColorSpace = Unknown; - QColorSpace::Primaries primaries; - QColorSpace::TransferFunction transferFunction; - float gamma; + QColorSpace::Primaries primaries = QColorSpace::Primaries::Custom; + QColorSpace::TransferFunction transferFunction = QColorSpace::TransferFunction::Custom; + float gamma = 0.0f; QColorVector whitePoint; QColorTrc trc[3]; diff --git a/src/gui/painting/qcolortransform.cpp b/src/gui/painting/qcolortransform.cpp index 53fd1dfbaac..10ccefed742 100644 --- a/src/gui/painting/qcolortransform.cpp +++ b/src/gui/painting/qcolortransform.cpp @@ -612,6 +612,15 @@ static void storeOpaque(QRgba64 *dst, const QRgba64 *src, const QColorVector *bu static constexpr qsizetype WorkBlockSize = 256; +template +class QUninitialized +{ +public: + operator T*() { return reinterpret_cast(this); } +private: + alignas(T) char data[sizeof(T) * Count]; +}; + template void QColorTransformPrivate::apply(T *dst, const T *src, qsizetype count, TransformFlags flags) const { @@ -623,7 +632,8 @@ void QColorTransformPrivate::apply(T *dst, const T *src, qsizetype count, Transf bool doApplyMatrix = (colorMatrix != QColorMatrix::identity()); - QColorVector buffer[WorkBlockSize]; + QUninitialized buffer; + qsizetype i = 0; while (i < count) { const qsizetype len = qMin(count - i, WorkBlockSize); From 1c63605c102c52efbc3b620bb3221e167da39570 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Mon, 9 Sep 2019 17:00:27 +0200 Subject: [PATCH 18/41] rhi: Make the clang code model happy as much as we can MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When interfacing with reality (i.e. native platform APIs provided in C, ObjC, or COM), each of the APIs has its own idea of what types it likes to use for sizes, points, rects, etc. Out of the hundreds of warnings Qt Creator throws at us with the default clang check level when opening one of the rhi backends not a single one is useful. Regardless, let's try getting rid of what we can. This mostly involves throwing in int/uint conversions in order to get the signedness change warnings to shut up. The things that are either unacceptable to change or are beyond our control are left untouched. Change-Id: I6e4cb7cd373bf48dc990eaf83344242bbf30bd66 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhi.cpp | 25 +-- src/gui/rhi/qrhid3d11.cpp | 269 +++++++++++++++---------------- src/gui/rhi/qrhigles2.cpp | 121 +++++++------- src/gui/rhi/qrhimetal.mm | 214 +++++++++++++------------ src/gui/rhi/qrhiprofiler.cpp | 14 +- src/gui/rhi/qrhiprofiler_p_p.h | 6 +- src/gui/rhi/qrhivulkan.cpp | 285 +++++++++++++++++---------------- 7 files changed, 470 insertions(+), 464 deletions(-) diff --git a/src/gui/rhi/qrhi.cpp b/src/gui/rhi/qrhi.cpp index 88d2f73541a..65cfaf5123c 100644 --- a/src/gui/rhi/qrhi.cpp +++ b/src/gui/rhi/qrhi.cpp @@ -673,7 +673,7 @@ bool operator!=(const QRhiDepthStencilClearValue &a, const QRhiDepthStencilClear */ uint qHash(const QRhiDepthStencilClearValue &v, uint seed) Q_DECL_NOTHROW { - return seed * (qFloor(v.depthClearValue() * 100) + v.stencilClearValue()); + return seed * (uint(qFloor(qreal(v.depthClearValue()) * 100)) + v.stencilClearValue()); } #ifndef QT_NO_DEBUG_STREAM @@ -768,7 +768,8 @@ bool operator!=(const QRhiViewport &a, const QRhiViewport &b) Q_DECL_NOTHROW uint qHash(const QRhiViewport &v, uint seed) Q_DECL_NOTHROW { const std::array r = v.viewport(); - return seed + r[0] + r[1] + r[2] + r[3] + qFloor(v.minDepth() * 100) + qFloor(v.maxDepth() * 100); + return seed + uint(r[0]) + uint(r[1]) + uint(r[2]) + uint(r[3]) + + uint(qFloor(qreal(v.minDepth()) * 100)) + uint(qFloor(qreal(v.maxDepth()) * 100)); } #ifndef QT_NO_DEBUG_STREAM @@ -850,7 +851,7 @@ bool operator!=(const QRhiScissor &a, const QRhiScissor &b) Q_DECL_NOTHROW uint qHash(const QRhiScissor &v, uint seed) Q_DECL_NOTHROW { const std::array r = v.scissor(); - return seed + r[0] + r[1] + r[2] + r[3]; + return seed + uint(r[0]) + uint(r[1]) + uint(r[2]) + uint(r[3]); } #ifndef QT_NO_DEBUG_STREAM @@ -1136,7 +1137,7 @@ bool operator!=(const QRhiVertexInputAttribute &a, const QRhiVertexInputAttribut */ uint qHash(const QRhiVertexInputAttribute &v, uint seed) Q_DECL_NOTHROW { - return seed + v.binding() + v.location() + v.format() + v.offset(); + return seed + uint(v.binding()) + uint(v.location()) + uint(v.format()) + v.offset(); } #ifndef QT_NO_DEBUG_STREAM @@ -3001,7 +3002,7 @@ bool operator!=(const QRhiShaderResourceBinding &a, const QRhiShaderResourceBind uint qHash(const QRhiShaderResourceBinding &b, uint seed) Q_DECL_NOTHROW { const char *u = reinterpret_cast(&b.d->u); - return seed + b.d->binding + 10 * b.d->stage + 100 * b.d->type + return seed + uint(b.d->binding) + 10 * uint(b.d->stage) + 100 * uint(b.d->type) + qHash(QByteArray::fromRawData(u, sizeof(b.d->u)), seed); } @@ -3823,8 +3824,8 @@ void QRhiImplementation::compressedFormatInfo(QRhiTexture::Format format, const break; } - const quint32 wblocks = (size.width() + xdim - 1) / xdim; - const quint32 hblocks = (size.height() + ydim - 1) / ydim; + const quint32 wblocks = uint((size.width() + xdim - 1) / xdim); + const quint32 hblocks = uint((size.height() + ydim - 1) / ydim); if (bpl) *bpl = wblocks * blockSize; @@ -3880,9 +3881,9 @@ void QRhiImplementation::textureFormatInfo(QRhiTexture::Format format, const QSi } if (bpl) - *bpl = size.width() * bpc; + *bpl = uint(size.width()) * bpc; if (byteSize) - *byteSize = size.width() * size.height() * bpc; + *byteSize = uint(size.width() * size.height()) * bpc; } // Approximate because it excludes subresource alignment or multisampling. @@ -3892,12 +3893,12 @@ quint32 QRhiImplementation::approxByteSizeForTexture(QRhiTexture::Format format, quint32 approxSize = 0; for (int level = 0; level < mipCount; ++level) { quint32 byteSize = 0; - const QSize size(qFloor(float(qMax(1, baseSize.width() >> level))), - qFloor(float(qMax(1, baseSize.height() >> level)))); + const QSize size(qFloor(qreal(qMax(1, baseSize.width() >> level))), + qFloor(qreal(qMax(1, baseSize.height() >> level)))); textureFormatInfo(format, size, nullptr, &byteSize); approxSize += byteSize; } - approxSize *= layerCount; + approxSize *= uint(layerCount); return approxSize; } diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index f12e376b58f..2828256a90d 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -161,7 +161,7 @@ static QString comErrorMessage(HRESULT hr) } template -static inline Int aligned(Int v, Int byteAlign) +inline Int aligned(Int v, Int byteAlign) { return (v + byteAlign - 1) & ~(byteAlign - 1); } @@ -172,7 +172,7 @@ static IDXGIFactory1 *createDXGIFactory2() if (QOperatingSystemVersion::current() > QOperatingSystemVersion::Windows7) { using PtrCreateDXGIFactory2 = HRESULT (WINAPI *)(UINT, REFIID, void **); QSystemLibrary dxgilib(QStringLiteral("dxgi")); - if (auto createDXGIFactory2 = (PtrCreateDXGIFactory2)dxgilib.resolve("CreateDXGIFactory2")) { + if (auto createDXGIFactory2 = reinterpret_cast(dxgilib.resolve("CreateDXGIFactory2"))) { const HRESULT hr = createDXGIFactory2(0, IID_IDXGIFactory2, reinterpret_cast(&result)); if (FAILED(hr)) { qWarning("CreateDXGIFactory2() failed to create DXGI factory: %s", qPrintable(comErrorMessage(hr))); @@ -227,10 +227,10 @@ bool QRhiD3D11::create(QRhi::Flags flags) int requestedAdapterIndex = -1; if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX")) requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX"); - for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) { + for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) { DXGI_ADAPTER_DESC1 desc; adapter->GetDesc1(&desc); - const QString name = QString::fromUtf16((char16_t *) desc.Description); + const QString name = QString::fromUtf16(reinterpret_cast(desc.Description)); qCDebug(QRHI_LOG_INFO, "Adapter %d: '%s' (flags 0x%x)", adapterIndex, qPrintable(name), desc.Flags); if (!adapterToUse && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) { adapterToUse = adapter; @@ -343,9 +343,9 @@ DXGI_SAMPLE_DESC QRhiD3D11::effectiveSampleCount(int sampleCount) const return desc; } - desc.Count = s; + desc.Count = UINT(s); if (s > 1) - desc.Quality = D3D11_STANDARD_MULTISAMPLE_PATTERN; + desc.Quality = UINT(D3D11_STANDARD_MULTISAMPLE_PATTERN); else desc.Quality = 0; @@ -666,7 +666,7 @@ void QRhiD3D11::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBind uint *p = cmd.args.bindShaderResources.dynamicOffsetPairs; for (int i = 0; i < dynamicOffsetCount; ++i) { const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]); - const uint binding = dynOfs.first; + const uint binding = uint(dynOfs.first); Q_ASSERT(aligned(dynOfs.second, quint32(256)) == dynOfs.second); const uint offsetInConstants = dynOfs.second / 16; *p++ = binding; @@ -802,10 +802,10 @@ void QRhiD3D11::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) QD3D11CommandBuffer::Command cmd; cmd.cmd = QD3D11CommandBuffer::Command::BlendConstants; cmd.args.blendConstants.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline); - cmd.args.blendConstants.c[0] = c.redF(); - cmd.args.blendConstants.c[1] = c.greenF(); - cmd.args.blendConstants.c[2] = c.blueF(); - cmd.args.blendConstants.c[3] = c.alphaF(); + cmd.args.blendConstants.c[0] = float(c.redF()); + cmd.args.blendConstants.c[1] = float(c.greenF()); + cmd.args.blendConstants.c[2] = float(c.blueF()); + cmd.args.blendConstants.c[3] = float(c.alphaF()); cbD->commands.append(cmd); } @@ -1201,7 +1201,7 @@ QRhi::FrameOpResult QRhiD3D11::finish() void QRhiD3D11::enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cbD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc) { - UINT subres = D3D11CalcSubresource(level, layer, texD->mipLevelCount); + UINT subres = D3D11CalcSubresource(UINT(level), UINT(layer), texD->mipLevelCount); const QPoint dp = subresDesc.destinationTopLeft(); D3D11_BOX box; box.front = 0; @@ -1232,13 +1232,13 @@ void QRhiD3D11::enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cb } else { cmd.args.updateSubRes.src = cbD->retainImage(img); } - box.left = dp.x(); - box.top = dp.y(); - box.right = dp.x() + size.width(); - box.bottom = dp.y() + size.height(); + box.left = UINT(dp.x()); + box.top = UINT(dp.y()); + box.right = UINT(dp.x() + size.width()); + box.bottom = UINT(dp.y() + size.height()); cmd.args.updateSubRes.hasDstBox = true; cmd.args.updateSubRes.dstBox = box; - cmd.args.updateSubRes.srcRowPitch = bpl; + cmd.args.updateSubRes.srcRowPitch = UINT(bpl); } else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) { const QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize) : subresDesc.sourceSize(); @@ -1248,10 +1248,10 @@ void QRhiD3D11::enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cb // Everything must be a multiple of the block width and // height, so e.g. a mip level of size 2x2 will be 4x4 when it // comes to the actual data. - box.left = aligned(dp.x(), blockDim.width()); - box.top = aligned(dp.y(), blockDim.height()); - box.right = aligned(dp.x() + size.width(), blockDim.width()); - box.bottom = aligned(dp.y() + size.height(), blockDim.height()); + box.left = UINT(aligned(dp.x(), blockDim.width())); + box.top = UINT(aligned(dp.y(), blockDim.height())); + box.right = UINT(aligned(dp.x() + size.width(), blockDim.width())); + box.bottom = UINT(aligned(dp.y() + size.height(), blockDim.height())); cmd.args.updateSubRes.hasDstBox = true; cmd.args.updateSubRes.dstBox = box; cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data()); @@ -1261,10 +1261,10 @@ void QRhiD3D11::enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cb : subresDesc.sourceSize(); quint32 bpl = 0; textureFormatInfo(texD->m_format, size, &bpl, nullptr); - box.left = dp.x(); - box.top = dp.y(); - box.right = dp.x() + size.width(); - box.bottom = dp.y() + size.height(); + box.left = UINT(dp.x()); + box.top = UINT(dp.y()); + box.right = UINT(dp.x() + size.width()); + box.bottom = UINT(dp.y() + size.height()); cmd.args.updateSubRes.hasDstBox = true; cmd.args.updateSubRes.dstBox = box; cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data()); @@ -1286,7 +1286,7 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : ud->dynamicBufferUpdates) { QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf); Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic); - memcpy(bufD->dynBuf.data() + u.offset, u.data.constData(), u.data.size()); + memcpy(bufD->dynBuf.data() + u.offset, u.data.constData(), size_t(u.data.size())); bufD->hasPendingDynamicUpdates = true; } @@ -1304,10 +1304,10 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate // since the ID3D11Buffer's size is rounded up to be a multiple of 256 // while the data we have has the original size. D3D11_BOX box; - box.left = u.offset; + box.left = UINT(u.offset); box.top = box.front = 0; box.back = box.bottom = 1; - box.right = u.offset + u.data.size(); // no -1: right, bottom, back are exclusive, see D3D11_BOX doc + box.right = UINT(u.offset + u.data.size()); // no -1: right, bottom, back are exclusive, see D3D11_BOX doc cmd.args.updateSubRes.hasDstBox = true; cmd.args.updateSubRes.dstBox = box; cbD->commands.append(cmd); @@ -1326,25 +1326,25 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate Q_ASSERT(u.copy.src && u.copy.dst); QD3D11Texture *srcD = QRHI_RES(QD3D11Texture, u.copy.src); QD3D11Texture *dstD = QRHI_RES(QD3D11Texture, u.copy.dst); - UINT srcSubRes = D3D11CalcSubresource(u.copy.desc.sourceLevel(), u.copy.desc.sourceLayer(), srcD->mipLevelCount); - UINT dstSubRes = D3D11CalcSubresource(u.copy.desc.destinationLevel(), u.copy.desc.destinationLayer(), dstD->mipLevelCount); + UINT srcSubRes = D3D11CalcSubresource(UINT(u.copy.desc.sourceLevel()), UINT(u.copy.desc.sourceLayer()), srcD->mipLevelCount); + UINT dstSubRes = D3D11CalcSubresource(UINT(u.copy.desc.destinationLevel()), UINT(u.copy.desc.destinationLayer()), dstD->mipLevelCount); const QPoint dp = u.copy.desc.destinationTopLeft(); const QSize size = u.copy.desc.pixelSize().isEmpty() ? srcD->m_pixelSize : u.copy.desc.pixelSize(); const QPoint sp = u.copy.desc.sourceTopLeft(); D3D11_BOX srcBox; - srcBox.left = sp.x(); - srcBox.top = sp.y(); + srcBox.left = UINT(sp.x()); + srcBox.top = UINT(sp.y()); srcBox.front = 0; // back, right, bottom are exclusive - srcBox.right = srcBox.left + size.width(); - srcBox.bottom = srcBox.top + size.height(); + srcBox.right = srcBox.left + UINT(size.width()); + srcBox.bottom = srcBox.top + UINT(size.height()); srcBox.back = 1; QD3D11CommandBuffer::Command cmd; cmd.cmd = QD3D11CommandBuffer::Command::CopySubRes; cmd.args.copySubRes.dst = dstD->tex; cmd.args.copySubRes.dstSubRes = dstSubRes; - cmd.args.copySubRes.dstX = dp.x(); - cmd.args.copySubRes.dstY = dp.y(); + cmd.args.copySubRes.dstX = UINT(dp.x()); + cmd.args.copySubRes.dstY = UINT(dp.y()); cmd.args.copySubRes.src = srcD->tex; cmd.args.copySubRes.srcSubRes = srcSubRes; cmd.args.copySubRes.hasSrcBox = true; @@ -1372,7 +1372,7 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate dxgiFormat = texD->dxgiFormat; pixelSize = u.read.rb.level() > 0 ? q->sizeForMipLevel(u.read.rb.level(), texD->m_pixelSize) : texD->m_pixelSize; format = texD->m_format; - subres = D3D11CalcSubresource(u.read.rb.level(), u.read.rb.layer(), texD->mipLevelCount); + subres = D3D11CalcSubresource(UINT(u.read.rb.level()), UINT(u.read.rb.layer()), texD->mipLevelCount); } else { Q_ASSERT(contextState.currentSwapChain); swapChainD = QRHI_RES(QD3D11SwapChain, contextState.currentSwapChain); @@ -1401,8 +1401,8 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate D3D11_TEXTURE2D_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.Width = pixelSize.width(); - desc.Height = pixelSize.height(); + desc.Width = UINT(pixelSize.width()); + desc.Height = UINT(pixelSize.height()); desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = dxgiFormat; @@ -1415,7 +1415,7 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate qWarning("Failed to create readback staging texture: %s", qPrintable(comErrorMessage(hr))); return; } - QRHI_PROF_F(newReadbackBuffer(quint64(quintptr(stagingTex)), + QRHI_PROF_F(newReadbackBuffer(qint64(qintptr(stagingTex)), texD ? static_cast(texD) : static_cast(swapChainD), bufSize)); @@ -1458,7 +1458,7 @@ void QRhiD3D11::finishActiveReadbacks() const QRhiD3D11::ActiveReadback &aRb(activeReadbacks[i]); aRb.result->format = aRb.format; aRb.result->pixelSize = aRb.pixelSize; - aRb.result->data.resize(aRb.bufSize); + aRb.result->data.resize(int(aRb.bufSize)); D3D11_MAPPED_SUBRESOURCE mp; HRESULT hr = context->Map(aRb.stagingTex, 0, D3D11_MAP_READ, 0, &mp); @@ -1479,7 +1479,7 @@ void QRhiD3D11::finishActiveReadbacks() context->Unmap(aRb.stagingTex, 0); aRb.stagingTex->Release(); - QRHI_PROF_F(releaseReadbackBuffer(quint64(quintptr(aRb.stagingTex)))); + QRHI_PROF_F(releaseReadbackBuffer(qint64(qintptr(aRb.stagingTex)))); if (aRb.result->completed) completedCallbacks.append(aRb.result->completed); @@ -1548,10 +1548,10 @@ void QRhiD3D11::beginPass(QRhiCommandBuffer *cb, if (rtD->dsAttCount && wantsDsClear) clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Depth | QD3D11CommandBuffer::Command::Stencil; - clearCmd.args.clear.c[0] = colorClearValue.redF(); - clearCmd.args.clear.c[1] = colorClearValue.greenF(); - clearCmd.args.clear.c[2] = colorClearValue.blueF(); - clearCmd.args.clear.c[3] = colorClearValue.alphaF(); + clearCmd.args.clear.c[0] = float(colorClearValue.redF()); + clearCmd.args.clear.c[1] = float(colorClearValue.greenF()); + clearCmd.args.clear.c[2] = float(colorClearValue.blueF()); + clearCmd.args.clear.c[3] = float(colorClearValue.alphaF()); clearCmd.args.clear.d = depthStencilClearValue.depthClearValue(); clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue(); cbD->commands.append(clearCmd); @@ -1582,8 +1582,8 @@ void QRhiD3D11::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resource QD3D11CommandBuffer::Command cmd; cmd.cmd = QD3D11CommandBuffer::Command::ResolveSubRes; cmd.args.resolveSubRes.dst = dstTexD->tex; - cmd.args.resolveSubRes.dstSubRes = D3D11CalcSubresource(colorAtt.resolveLevel(), - colorAtt.resolveLayer(), + cmd.args.resolveSubRes.dstSubRes = D3D11CalcSubresource(UINT(colorAtt.resolveLevel()), + UINT(colorAtt.resolveLayer()), dstTexD->mipLevelCount); if (srcTexD) { cmd.args.resolveSubRes.src = srcTexD->tex; @@ -1610,7 +1610,7 @@ void QRhiD3D11::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resource continue; } } - cmd.args.resolveSubRes.srcSubRes = D3D11CalcSubresource(0, colorAtt.layer(), 1); + cmd.args.resolveSubRes.srcSubRes = D3D11CalcSubresource(0, UINT(colorAtt.layer()), 1); cmd.args.resolveSubRes.format = dstTexD->dxgiFormat; cbD->commands.append(cmd); } @@ -1677,9 +1677,9 @@ void QRhiD3D11::dispatch(QRhiCommandBuffer *cb, int x, int y, int z) QD3D11CommandBuffer::Command cmd; cmd.cmd = QD3D11CommandBuffer::Command::Dispatch; - cmd.args.dispatch.x = x; - cmd.args.dispatch.y = y; - cmd.args.dispatch.z = z; + cmd.args.dispatch.x = UINT(x); + cmd.args.dispatch.y = UINT(y); + cmd.args.dispatch.z = UINT(z); cbD->commands.append(cmd); } @@ -1721,11 +1721,11 @@ void QRhiD3D11::updateShaderResourceBindings(QD3D11ShaderResourceBindings *srbD) // dynamic ubuf offsets are not considered here, those are baked in // at a later stage, which is good as vsubufoffsets and friends are // per-srb, not per-setShaderResources call - const uint offsetInConstants = b->u.ubuf.offset / 16; + const uint offsetInConstants = uint(b->u.ubuf.offset) / 16; // size must be 16 mult. (in constants, i.e. multiple of 256 bytes). // We can round up if needed since the buffers's actual size // (ByteWidth) is always a multiple of 256. - const uint sizeInConstants = aligned(b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size, 256) / 16; + const uint sizeInConstants = uint(aligned(b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size, 256) / 16); if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) { srbD->vsubufs.feed(b->binding, bufD->buffer); srbD->vsubufoffsets.feed(b->binding, offsetInConstants); @@ -1843,7 +1843,7 @@ void QRhiD3D11::executeBufferHostWritesForCurrentFrame(QD3D11Buffer *bufD) D3D11_MAPPED_SUBRESOURCE mp; HRESULT hr = context->Map(bufD->buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp); if (SUCCEEDED(hr)) { - memcpy(mp.pData, bufD->dynBuf.constData(), bufD->dynBuf.size()); + memcpy(mp.pData, bufD->dynBuf.constData(), size_t(bufD->dynBuf.size())); context->Unmap(bufD->buffer, 0); } else { qWarning("Failed to map buffer: %s", qPrintable(comErrorMessage(hr))); @@ -1856,13 +1856,13 @@ static void applyDynamicOffsets(QVarLengthArray *offsets, QRhiBatchedBindings *ubufoffsets, const uint *dynOfsPairs, int dynOfsPairCount) { - const UINT count = ubufs->batches[batchIndex].resources.count(); + const int count = ubufs->batches[batchIndex].resources.count(); const UINT startBinding = ubufs->batches[batchIndex].startBinding; *offsets = ubufoffsets->batches[batchIndex].resources; - for (UINT b = 0; b < count; ++b) { + for (int b = 0; b < count; ++b) { for (int di = 0; di < dynOfsPairCount; ++di) { const uint binding = dynOfsPairs[2 * di]; - if (binding == startBinding + b) { + if (binding == startBinding + UINT(b)) { const uint offsetInConstants = dynOfsPairs[2 * di + 1]; (*offsets)[b] = offsetInConstants; break; @@ -1877,37 +1877,37 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, { if (!offsetOnlyChange) { for (const auto &batch : srbD->vssamplers.batches) - context->VSSetSamplers(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->VSSetSamplers(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); for (const auto &batch : srbD->vsshaderresources.batches) { - context->VSSetShaderResources(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->VSSetShaderResources(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); contextState.vsHighestActiveSrvBinding = qMax(contextState.vsHighestActiveSrvBinding, - batch.startBinding + batch.resources.count() - 1); + int(batch.startBinding) + batch.resources.count() - 1); } for (const auto &batch : srbD->fssamplers.batches) - context->PSSetSamplers(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->PSSetSamplers(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); for (const auto &batch : srbD->fsshaderresources.batches) { - context->PSSetShaderResources(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->PSSetShaderResources(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); contextState.fsHighestActiveSrvBinding = qMax(contextState.fsHighestActiveSrvBinding, - batch.startBinding + batch.resources.count() - 1); + int(batch.startBinding) + batch.resources.count() - 1); } for (const auto &batch : srbD->cssamplers.batches) - context->CSSetSamplers(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->CSSetSamplers(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); for (const auto &batch : srbD->csshaderresources.batches) { - context->CSSetShaderResources(batch.startBinding, batch.resources.count(), batch.resources.constData()); + context->CSSetShaderResources(batch.startBinding, UINT(batch.resources.count()), batch.resources.constData()); contextState.csHighestActiveSrvBinding = qMax(contextState.csHighestActiveSrvBinding, - batch.startBinding + batch.resources.count() - 1); + int(batch.startBinding) + batch.resources.count() - 1); } } for (int i = 0, ie = srbD->vsubufs.batches.count(); i != ie; ++i) { if (!dynOfsPairCount) { context->VSSetConstantBuffers1(srbD->vsubufs.batches[i].startBinding, - srbD->vsubufs.batches[i].resources.count(), + UINT(srbD->vsubufs.batches[i].resources.count()), srbD->vsubufs.batches[i].resources.constData(), srbD->vsubufoffsets.batches[i].resources.constData(), srbD->vsubufsizes.batches[i].resources.constData()); @@ -1915,7 +1915,7 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, QVarLengthArray offsets; applyDynamicOffsets(&offsets, i, &srbD->vsubufs, &srbD->vsubufoffsets, dynOfsPairs, dynOfsPairCount); context->VSSetConstantBuffers1(srbD->vsubufs.batches[i].startBinding, - srbD->vsubufs.batches[i].resources.count(), + UINT(srbD->vsubufs.batches[i].resources.count()), srbD->vsubufs.batches[i].resources.constData(), offsets.constData(), srbD->vsubufsizes.batches[i].resources.constData()); @@ -1925,7 +1925,7 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, for (int i = 0, ie = srbD->fsubufs.batches.count(); i != ie; ++i) { if (!dynOfsPairCount) { context->PSSetConstantBuffers1(srbD->fsubufs.batches[i].startBinding, - srbD->fsubufs.batches[i].resources.count(), + UINT(srbD->fsubufs.batches[i].resources.count()), srbD->fsubufs.batches[i].resources.constData(), srbD->fsubufoffsets.batches[i].resources.constData(), srbD->fsubufsizes.batches[i].resources.constData()); @@ -1933,7 +1933,7 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, QVarLengthArray offsets; applyDynamicOffsets(&offsets, i, &srbD->fsubufs, &srbD->fsubufoffsets, dynOfsPairs, dynOfsPairCount); context->PSSetConstantBuffers1(srbD->fsubufs.batches[i].startBinding, - srbD->fsubufs.batches[i].resources.count(), + UINT(srbD->fsubufs.batches[i].resources.count()), srbD->fsubufs.batches[i].resources.constData(), offsets.constData(), srbD->fsubufsizes.batches[i].resources.constData()); @@ -1943,7 +1943,7 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, for (int i = 0, ie = srbD->csubufs.batches.count(); i != ie; ++i) { if (!dynOfsPairCount) { context->CSSetConstantBuffers1(srbD->csubufs.batches[i].startBinding, - srbD->csubufs.batches[i].resources.count(), + UINT(srbD->csubufs.batches[i].resources.count()), srbD->csubufs.batches[i].resources.constData(), srbD->csubufoffsets.batches[i].resources.constData(), srbD->csubufsizes.batches[i].resources.constData()); @@ -1951,7 +1951,7 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, QVarLengthArray offsets; applyDynamicOffsets(&offsets, i, &srbD->csubufs, &srbD->csubufoffsets, dynOfsPairs, dynOfsPairCount); context->CSSetConstantBuffers1(srbD->csubufs.batches[i].startBinding, - srbD->csubufs.batches[i].resources.count(), + UINT(srbD->csubufs.batches[i].resources.count()), srbD->csubufs.batches[i].resources.constData(), offsets.constData(), srbD->csubufsizes.batches[i].resources.constData()); @@ -1960,13 +1960,13 @@ void QRhiD3D11::bindShaderResources(QD3D11ShaderResourceBindings *srbD, for (int i = 0, ie = srbD->csUAVs.batches.count(); i != ie; ++i) { const uint startBinding = srbD->csUAVs.batches[i].startBinding; - const uint count = srbD->csUAVs.batches[i].resources.count(); + const uint count = uint(srbD->csUAVs.batches[i].resources.count()); context->CSSetUnorderedAccessViews(startBinding, count, srbD->csUAVs.batches[i].resources.constData(), nullptr); contextState.csHighestActiveUavBinding = qMax(contextState.csHighestActiveUavBinding, - startBinding + count - 1); + int(startBinding + count - 1)); } } @@ -1990,7 +1990,7 @@ void QRhiD3D11::resetShaderResources() QVarLengthArray nulloffsets(count); for (int i = 0; i < count; ++i) nulloffsets[i] = 0; - context->IASetVertexBuffers(0, count, nullbufs.constData(), nullstrides.constData(), nulloffsets.constData()); + context->IASetVertexBuffers(0, UINT(count), nullbufs.constData(), nullstrides.constData(), nulloffsets.constData()); contextState.vsHighestActiveVertexBufferBinding = -1; } @@ -2003,15 +2003,15 @@ void QRhiD3D11::resetShaderResources() for (int i = 0; i < nullsrvs.count(); ++i) nullsrvs[i] = nullptr; if (contextState.vsHighestActiveSrvBinding >= 0) { - context->VSSetShaderResources(0, contextState.vsHighestActiveSrvBinding + 1, nullsrvs.constData()); + context->VSSetShaderResources(0, UINT(contextState.vsHighestActiveSrvBinding + 1), nullsrvs.constData()); contextState.vsHighestActiveSrvBinding = -1; } if (contextState.fsHighestActiveSrvBinding >= 0) { - context->PSSetShaderResources(0, contextState.fsHighestActiveSrvBinding + 1, nullsrvs.constData()); + context->PSSetShaderResources(0, UINT(contextState.fsHighestActiveSrvBinding + 1), nullsrvs.constData()); contextState.fsHighestActiveSrvBinding = -1; } if (contextState.csHighestActiveSrvBinding >= 0) { - context->CSSetShaderResources(0, contextState.csHighestActiveSrvBinding + 1, nullsrvs.constData()); + context->CSSetShaderResources(0, UINT(contextState.csHighestActiveSrvBinding + 1), nullsrvs.constData()); contextState.csHighestActiveSrvBinding = -1; } } @@ -2022,7 +2022,7 @@ void QRhiD3D11::resetShaderResources() D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nulluavs(nulluavCount); for (int i = 0; i < nulluavCount; ++i) nulluavs[i] = nullptr; - context->CSSetUnorderedAccessViews(0, nulluavCount, nulluavs.constData(), nullptr); + context->CSSetUnorderedAccessViews(0, UINT(nulluavCount), nulluavs.constData(), nullptr); contextState.csHighestActiveUavBinding = -1; } } @@ -2044,7 +2044,7 @@ void QRhiD3D11::executeCommandBuffer(QD3D11CommandBuffer *cbD, QD3D11SwapChain * // writing the first timestamp only afterwards. context->Begin(tsDisjoint); QD3D11RenderTargetData *rtD = rtData(×tampSwapChain->rt); - context->OMSetRenderTargets(rtD->colorAttCount, rtD->colorAttCount ? rtD->rtv : nullptr, rtD->dsv); + context->OMSetRenderTargets(UINT(rtD->colorAttCount), rtD->colorAttCount ? rtD->rtv : nullptr, rtD->dsv); context->End(tsStart); // just record a timestamp, no Begin needed } } @@ -2057,7 +2057,7 @@ void QRhiD3D11::executeCommandBuffer(QD3D11CommandBuffer *cbD, QD3D11SwapChain * case QD3D11CommandBuffer::Command::SetRenderTarget: { QD3D11RenderTargetData *rtD = rtData(cmd.args.setRenderTarget.rt); - context->OMSetRenderTargets(rtD->colorAttCount, rtD->colorAttCount ? rtD->rtv : nullptr, rtD->dsv); + context->OMSetRenderTargets(UINT(rtD->colorAttCount), rtD->colorAttCount ? rtD->rtv : nullptr, rtD->dsv); } break; case QD3D11CommandBuffer::Command::Clear: @@ -2073,7 +2073,7 @@ void QRhiD3D11::executeCommandBuffer(QD3D11CommandBuffer *cbD, QD3D11SwapChain * if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Stencil) ds |= D3D11_CLEAR_STENCIL; if (ds) - context->ClearDepthStencilView(rtD->dsv, ds, cmd.args.clear.d, cmd.args.clear.s); + context->ClearDepthStencilView(rtD->dsv, ds, cmd.args.clear.d, UINT8(cmd.args.clear.s)); } break; case QD3D11CommandBuffer::Command::Viewport: @@ -2103,8 +2103,8 @@ void QRhiD3D11::executeCommandBuffer(QD3D11CommandBuffer *cbD, QD3D11SwapChain * contextState.vsHighestActiveVertexBufferBinding = qMax( contextState.vsHighestActiveVertexBufferBinding, cmd.args.bindVertexBuffers.startSlot + cmd.args.bindVertexBuffers.slotCount - 1); - context->IASetVertexBuffers(cmd.args.bindVertexBuffers.startSlot, - cmd.args.bindVertexBuffers.slotCount, + context->IASetVertexBuffers(UINT(cmd.args.bindVertexBuffers.startSlot), + UINT(cmd.args.bindVertexBuffers.slotCount), cmd.args.bindVertexBuffers.buffers, cmd.args.bindVertexBuffers.strides, cmd.args.bindVertexBuffers.offsets); @@ -2247,7 +2247,7 @@ static inline uint toD3DBufferUsage(QRhiBuffer::UsageFlags usage) u |= D3D11_BIND_CONSTANT_BUFFER; if (usage.testFlag(QRhiBuffer::StorageBuffer)) u |= D3D11_BIND_UNORDERED_ACCESS; - return u; + return uint(u); } bool QD3D11Buffer::build() @@ -2270,7 +2270,7 @@ bool QD3D11Buffer::build() D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.ByteWidth = roundedSize; + desc.ByteWidth = UINT(roundedSize); desc.Usage = m_type == Dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; desc.BindFlags = toD3DBufferUsage(m_usage); desc.CPUAccessFlags = m_type == Dynamic ? D3D11_CPU_ACCESS_WRITE : 0; @@ -2289,10 +2289,10 @@ bool QD3D11Buffer::build() } if (!m_objectName.isEmpty()) - buffer->SetPrivateData(WKPDID_D3DDebugObjectName, m_objectName.size(), m_objectName.constData()); + buffer->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData()); QRHI_PROF; - QRHI_PROF_F(newBuffer(this, roundedSize, m_type == Dynamic ? 2 : 1, m_type == Dynamic ? 1 : 0)); + QRHI_PROF_F(newBuffer(this, quint32(roundedSize), m_type == Dynamic ? 2 : 1, m_type == Dynamic ? 1 : 0)); generation += 1; rhiD->registerResource(this); @@ -2310,7 +2310,7 @@ ID3D11UnorderedAccessView *QD3D11Buffer::unorderedAccessView() desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; desc.Buffer.FirstElement = 0; - desc.Buffer.NumElements = aligned(m_size, 4) / 4; + desc.Buffer.NumElements = UINT(aligned(m_size, 4) / 4); desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW; QRHI_RES_RHI(QRhiD3D11); @@ -2371,8 +2371,8 @@ bool QD3D11RenderBuffer::build() D3D11_TEXTURE2D_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.Width = m_pixelSize.width(); - desc.Height = m_pixelSize.height(); + desc.Width = UINT(m_pixelSize.width()); + desc.Height = UINT(m_pixelSize.height()); desc.MipLevels = 1; desc.ArraySize = 1; desc.SampleDesc = sampleDesc; @@ -2421,10 +2421,10 @@ bool QD3D11RenderBuffer::build() } if (!m_objectName.isEmpty()) - tex->SetPrivateData(WKPDID_D3DDebugObjectName, m_objectName.size(), m_objectName.constData()); + tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData()); QRHI_PROF; - QRHI_PROF_F(newRenderBuffer(this, false, false, sampleDesc.Count)); + QRHI_PROF_F(newRenderBuffer(this, false, false, int(sampleDesc.Count))); rhiD->registerResource(this); return true; @@ -2514,7 +2514,7 @@ bool QD3D11Texture::prepareBuild(QSize *adjustedSize) QRHI_RES_RHI(QRhiD3D11); dxgiFormat = toD3DTextureFormat(m_format, m_flags); - mipLevelCount = hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1; + mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1); sampleDesc = rhiD->effectiveSampleCount(m_sampleCount); if (sampleDesc.Count > 1) { if (isCube) { @@ -2600,8 +2600,8 @@ bool QD3D11Texture::build() D3D11_TEXTURE2D_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.Width = size.width(); - desc.Height = size.height(); + desc.Width = UINT(size.width()); + desc.Height = UINT(size.height()); desc.MipLevels = mipLevelCount; desc.ArraySize = isCube ? 6 : 1; desc.Format = dxgiFormat; @@ -2621,10 +2621,10 @@ bool QD3D11Texture::build() return false; if (!m_objectName.isEmpty()) - tex->SetPrivateData(WKPDID_D3DDebugObjectName, m_objectName.size(), m_objectName.constData()); + tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData()); QRHI_PROF; - QRHI_PROF_F(newTexture(this, true, mipLevelCount, isCube ? 6 : 1, sampleDesc.Count)); + QRHI_PROF_F(newTexture(this, true, int(mipLevelCount), isCube ? 6 : 1, int(sampleDesc.Count))); owns = true; rhiD->registerResource(this); @@ -2646,7 +2646,7 @@ bool QD3D11Texture::buildFrom(const QRhiNativeHandles *src) return false; QRHI_PROF; - QRHI_PROF_F(newTexture(this, false, mipLevelCount, m_flags.testFlag(CubeMap) ? 6 : 1, sampleDesc.Count)); + QRHI_PROF_F(newTexture(this, false, int(mipLevelCount), m_flags.testFlag(CubeMap) ? 6 : 1, int(sampleDesc.Count))); owns = false; QRHI_RES_RHI(QRhiD3D11); @@ -2670,12 +2670,12 @@ ID3D11UnorderedAccessView *QD3D11Texture::unorderedAccessViewForLevel(int level) desc.Format = dxgiFormat; if (isCube) { desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY; - desc.Texture2DArray.MipSlice = level; + desc.Texture2DArray.MipSlice = UINT(level); desc.Texture2DArray.FirstArraySlice = 0; desc.Texture2DArray.ArraySize = 6; } else { desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; - desc.Texture2D.MipSlice = level; + desc.Texture2D.MipSlice = UINT(level); } QRHI_RES_RHI(QRhiD3D11); @@ -2935,15 +2935,15 @@ bool QD3D11TextureRenderTarget::build() rtvDesc.Format = toD3DTextureFormat(texD->format(), texD->flags()); if (texD->flags().testFlag(QRhiTexture::CubeMap)) { rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; - rtvDesc.Texture2DArray.MipSlice = colorAttachments[i].level(); - rtvDesc.Texture2DArray.FirstArraySlice = colorAttachments[i].layer(); + rtvDesc.Texture2DArray.MipSlice = UINT(colorAttachments[i].level()); + rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAttachments[i].layer()); rtvDesc.Texture2DArray.ArraySize = 1; } else { if (texD->sampleDesc.Count > 1) { rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; } else { rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; - rtvDesc.Texture2D.MipSlice = colorAttachments[i].level(); + rtvDesc.Texture2D.MipSlice = UINT(colorAttachments[i].level()); } } HRESULT hr = rhiD->dev->CreateRenderTargetView(texD->tex, &rtvDesc, &rtv[i]); @@ -2954,7 +2954,7 @@ bool QD3D11TextureRenderTarget::build() ownsRtv[i] = true; if (i == 0) { d.pixelSize = texD->pixelSize(); - d.sampleCount = texD->sampleDesc.Count; + d.sampleCount = int(texD->sampleDesc.Count); } } else if (rb) { QD3D11RenderBuffer *rbD = QRHI_RES(QD3D11RenderBuffer, rb); @@ -2962,7 +2962,7 @@ bool QD3D11TextureRenderTarget::build() rtv[i] = rbD->rtv; if (i == 0) { d.pixelSize = rbD->pixelSize(); - d.sampleCount = rbD->sampleDesc.Count; + d.sampleCount = int(rbD->sampleDesc.Count); } } } @@ -2984,7 +2984,7 @@ bool QD3D11TextureRenderTarget::build() } if (d.colorAttCount == 0) { d.pixelSize = depthTexD->pixelSize(); - d.sampleCount = depthTexD->sampleDesc.Count; + d.sampleCount = int(depthTexD->sampleDesc.Count); } } else { ownsDsv = false; @@ -2992,7 +2992,7 @@ bool QD3D11TextureRenderTarget::build() dsv = depthRbD->dsv; if (d.colorAttCount == 0) { d.pixelSize = m_desc.depthStencilBuffer()->pixelSize(); - d.sampleCount = depthRbD->sampleDesc.Count; + d.sampleCount = int(depthRbD->sampleDesc.Count); } } d.dsAttCount = 1; @@ -3216,9 +3216,9 @@ static inline D3D11_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topol } } -static inline uint toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c) +static inline UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c) { - uint f = 0; + UINT8 f = 0; if (c.testFlag(QRhiGraphicsPipeline::R)) f |= D3D11_COLOR_WRITE_ENABLE_RED; if (c.testFlag(QRhiGraphicsPipeline::G)) @@ -3353,22 +3353,22 @@ static QByteArray compileHlslShaderSource(const QShader &shader, QShader::Varian ID3DBlob *bytecode = nullptr; ID3DBlob *errors = nullptr; - HRESULT hr = d3dCompile(hlslSource.shader().constData(), hlslSource.shader().size(), + HRESULT hr = d3dCompile(hlslSource.shader().constData(), SIZE_T(hlslSource.shader().size()), nullptr, nullptr, nullptr, hlslSource.entryPoint().constData(), target, 0, 0, &bytecode, &errors); if (FAILED(hr) || !bytecode) { qWarning("HLSL shader compilation failed: 0x%x", uint(hr)); if (errors) { *error = QString::fromUtf8(static_cast(errors->GetBufferPointer()), - errors->GetBufferSize()); + int(errors->GetBufferSize())); errors->Release(); } return QByteArray(); } QByteArray result; - result.resize(bytecode->GetBufferSize()); - memcpy(result.data(), bytecode->GetBufferPointer(), result.size()); + result.resize(int(bytecode->GetBufferSize())); + memcpy(result.data(), bytecode->GetBufferPointer(), size_t(result.size())); bytecode->Release(); return result; } @@ -3400,8 +3400,8 @@ bool QD3D11GraphicsPipeline::build() dsDesc.DepthFunc = toD3DCompareOp(m_depthOp); dsDesc.StencilEnable = m_stencilTest; if (m_stencilTest) { - dsDesc.StencilReadMask = m_stencilReadMask; - dsDesc.StencilWriteMask = m_stencilWriteMask; + dsDesc.StencilReadMask = UINT8(m_stencilReadMask); + dsDesc.StencilWriteMask = UINT8(m_stencilWriteMask); dsDesc.FrontFace.StencilFailOp = toD3DStencilOp(m_stencilFront.failOp); dsDesc.FrontFace.StencilDepthFailOp = toD3DStencilOp(m_stencilFront.depthFailOp); dsDesc.FrontFace.StencilPassOp = toD3DStencilOp(m_stencilFront.passOp); @@ -3478,7 +3478,7 @@ bool QD3D11GraphicsPipeline::build() switch (shaderStage.type()) { case QRhiShaderStage::Vertex: - hr = rhiD->dev->CreateVertexShader(bytecode.constData(), bytecode.size(), nullptr, &vs); + hr = rhiD->dev->CreateVertexShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &vs); if (FAILED(hr)) { qWarning("Failed to create vertex shader: %s", qPrintable(comErrorMessage(hr))); return false; @@ -3488,7 +3488,7 @@ bool QD3D11GraphicsPipeline::build() vs->AddRef(); break; case QRhiShaderStage::Fragment: - hr = rhiD->dev->CreatePixelShader(bytecode.constData(), bytecode.size(), nullptr, &fs); + hr = rhiD->dev->CreatePixelShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &fs); if (FAILED(hr)) { qWarning("Failed to create pixel shader: %s", qPrintable(comErrorMessage(hr))); return false; @@ -3513,20 +3513,21 @@ bool QD3D11GraphicsPipeline::build() memset(&desc, 0, sizeof(desc)); // the output from SPIRV-Cross uses TEXCOORD as the semantic desc.SemanticName = "TEXCOORD"; - desc.SemanticIndex = attribute.location(); + desc.SemanticIndex = UINT(attribute.location()); desc.Format = toD3DAttributeFormat(attribute.format()); - desc.InputSlot = attribute.binding(); + desc.InputSlot = UINT(attribute.binding()); desc.AlignedByteOffset = attribute.offset(); const QRhiVertexInputBinding &binding(bindings[attribute.binding()]); if (binding.classification() == QRhiVertexInputBinding::PerInstance) { desc.InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; - desc.InstanceDataStepRate = binding.instanceStepRate(); + desc.InstanceDataStepRate = UINT(binding.instanceStepRate()); } else { desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; } inputDescs.append(desc); } - hr = rhiD->dev->CreateInputLayout(inputDescs.constData(), inputDescs.count(), vsByteCode, vsByteCode.size(), &inputLayout); + hr = rhiD->dev->CreateInputLayout(inputDescs.constData(), UINT(inputDescs.count()), + vsByteCode, SIZE_T(vsByteCode.size()), &inputLayout); if (FAILED(hr)) { qWarning("Failed to create input layout: %s", qPrintable(comErrorMessage(hr))); return false; @@ -3579,7 +3580,7 @@ bool QD3D11ComputePipeline::build() return false; } - HRESULT hr = rhiD->dev->CreateComputeShader(bytecode.constData(), bytecode.size(), nullptr, &cs); + HRESULT hr = rhiD->dev->CreateComputeShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &cs); if (FAILED(hr)) { qWarning("Failed to create compute shader: %s", qPrintable(comErrorMessage(hr))); return false; @@ -3715,8 +3716,8 @@ bool QD3D11SwapChain::newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI { D3D11_TEXTURE2D_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.Width = size.width(); - desc.Height = size.height(); + desc.Width = UINT(size.width()); + desc.Height = UINT(size.height()); desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = format; @@ -3787,8 +3788,8 @@ bool QD3D11SwapChain::buildOrResize() DXGI_SWAP_CHAIN_DESC1 desc; memset(&desc, 0, sizeof(desc)); - desc.Width = pixelSize.width(); - desc.Height = pixelSize.height(); + desc.Width = UINT(pixelSize.width()); + desc.Height = UINT(pixelSize.height()); desc.Format = colorFormat; desc.SampleDesc.Count = 1; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; @@ -3813,8 +3814,8 @@ bool QD3D11SwapChain::buildOrResize() DXGI_SWAP_CHAIN_DESC desc; memset(&desc, 0, sizeof(desc)); - desc.BufferDesc.Width = pixelSize.width(); - desc.BufferDesc.Height = pixelSize.height(); + desc.BufferDesc.Width = UINT(pixelSize.width()); + desc.BufferDesc.Height = UINT(pixelSize.height()); desc.BufferDesc.RefreshRate.Numerator = 60; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferDesc.Format = colorFormat; @@ -3836,7 +3837,7 @@ bool QD3D11SwapChain::buildOrResize() } else { releaseBuffers(); const UINT count = useFlipDiscard ? BUFFER_COUNT : 1; - HRESULT hr = swapChain->ResizeBuffers(count, pixelSize.width(), pixelSize.height(), + HRESULT hr = swapChain->ResizeBuffers(count, UINT(pixelSize.width()), UINT(pixelSize.height()), colorFormat, swapChainFlags); if (FAILED(hr)) { qWarning("Failed to resize D3D11 swapchain: %s", qPrintable(comErrorMessage(hr))); @@ -3899,13 +3900,13 @@ bool QD3D11SwapChain::buildOrResize() QD3D11ReferenceRenderTarget *rtD = QRHI_RES(QD3D11ReferenceRenderTarget, &rt); rtD->d.rp = QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc); rtD->d.pixelSize = pixelSize; - rtD->d.dpr = window->devicePixelRatio(); - rtD->d.sampleCount = sampleDesc.Count; + rtD->d.dpr = float(window->devicePixelRatio()); + rtD->d.sampleCount = int(sampleDesc.Count); rtD->d.colorAttCount = 1; rtD->d.dsAttCount = m_depthStencil ? 1 : 0; QRHI_PROF; - QRHI_PROF_F(resizeSwapChain(this, BUFFER_COUNT, sampleDesc.Count > 1 ? BUFFER_COUNT : 0, sampleDesc.Count)); + QRHI_PROF_F(resizeSwapChain(this, BUFFER_COUNT, sampleDesc.Count > 1 ? BUFFER_COUNT : 0, int(sampleDesc.Count))); if (rhiP) { D3D11_QUERY_DESC queryDesc; memset(&queryDesc, 0, sizeof(queryDesc)); diff --git a/src/gui/rhi/qrhigles2.cpp b/src/gui/rhi/qrhigles2.cpp index 9ad591a17ad..0329acd350e 100644 --- a/src/gui/rhi/qrhigles2.cpp +++ b/src/gui/rhi/qrhigles2.cpp @@ -654,7 +654,7 @@ static inline GLenum toGlCompressedTextureFormat(QRhiTexture::Format format, QRh bool QRhiGles2::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const { if (isCompressedFormat(format)) - return supportedCompressedFormats.contains(toGlCompressedTextureFormat(format, flags)); + return supportedCompressedFormats.contains(GLint(toGlCompressedTextureFormat(format, flags))); switch (format) { case QRhiTexture::D16: @@ -930,7 +930,7 @@ void QRhiGles2::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBind uint *p = cmd.args.bindShaderResources.dynamicOffsetPairs; for (int i = 0; i < dynamicOffsetCount; ++i) { const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]); - *p++ = dynOfs.first; + *p++ = uint(dynOfs.first); *p++ = dynOfs.second; } } else { @@ -1023,10 +1023,10 @@ void QRhiGles2::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) QGles2CommandBuffer::Command cmd; cmd.cmd = QGles2CommandBuffer::Command::BlendConstants; - cmd.args.blendConstants.r = c.redF(); - cmd.args.blendConstants.g = c.greenF(); - cmd.args.blendConstants.b = c.blueF(); - cmd.args.blendConstants.a = c.alphaF(); + cmd.args.blendConstants.r = float(c.redF()); + cmd.args.blendConstants.g = float(c.greenF()); + cmd.args.blendConstants.b = float(c.blueF()); + cmd.args.blendConstants.a = float(c.alphaF()); cbD->commands.append(cmd); } @@ -1314,7 +1314,7 @@ void QRhiGles2::enqueueSubresUpload(QGles2Texture *texD, QGles2CommandBuffer *cb } cmd.args.subImage.target = texD->target; cmd.args.subImage.texture = texD->texture; - cmd.args.subImage.faceTarget = faceTargetBase + layer; + cmd.args.subImage.faceTarget = faceTargetBase + uint(layer); cmd.args.subImage.level = level; cmd.args.subImage.dx = dp.x(); cmd.args.subImage.dy = dp.y(); @@ -1333,7 +1333,7 @@ void QRhiGles2::enqueueSubresUpload(QGles2Texture *texD, QGles2CommandBuffer *cb cmd.cmd = QGles2CommandBuffer::Command::CompressedSubImage; cmd.args.compressedSubImage.target = texD->target; cmd.args.compressedSubImage.texture = texD->texture; - cmd.args.compressedSubImage.faceTarget = faceTargetBase + layer; + cmd.args.compressedSubImage.faceTarget = faceTargetBase + uint(layer); cmd.args.compressedSubImage.level = level; cmd.args.compressedSubImage.dx = dp.x(); cmd.args.compressedSubImage.dy = dp.y(); @@ -1348,7 +1348,7 @@ void QRhiGles2::enqueueSubresUpload(QGles2Texture *texD, QGles2CommandBuffer *cb cmd.cmd = QGles2CommandBuffer::Command::CompressedImage; cmd.args.compressedImage.target = texD->target; cmd.args.compressedImage.texture = texD->texture; - cmd.args.compressedImage.faceTarget = faceTargetBase + layer; + cmd.args.compressedImage.faceTarget = faceTargetBase + uint(layer); cmd.args.compressedImage.level = level; cmd.args.compressedImage.glintformat = texD->glintformat; cmd.args.compressedImage.w = size.width(); @@ -1366,7 +1366,7 @@ void QRhiGles2::enqueueSubresUpload(QGles2Texture *texD, QGles2CommandBuffer *cb cmd.cmd = QGles2CommandBuffer::Command::SubImage; cmd.args.subImage.target = texD->target; cmd.args.subImage.texture = texD->texture; - cmd.args.subImage.faceTarget = faceTargetBase + layer; + cmd.args.subImage.faceTarget = faceTargetBase + uint(layer); cmd.args.subImage.level = level; cmd.args.subImage.dx = dp.x(); cmd.args.subImage.dy = dp.y(); @@ -1394,7 +1394,7 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf); Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic); if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) { - memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size()); + memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), size_t(u.data.size())); } else { trackedBufferBarrier(cbD, bufD, QGles2Buffer::AccessUpdate); QGles2CommandBuffer::Command cmd; @@ -1413,7 +1413,7 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic); Q_ASSERT(u.offset + u.data.size() <= bufD->m_size); if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) { - memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size()); + memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), size_t(u.data.size())); } else { trackedBufferBarrier(cbD, bufD, QGles2Buffer::AccessUpdate); QGles2CommandBuffer::Command cmd; @@ -1458,7 +1458,7 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate QGles2CommandBuffer::Command cmd; cmd.cmd = QGles2CommandBuffer::Command::CopyTex; - cmd.args.copyTex.srcFaceTarget = srcFaceTargetBase + u.copy.desc.sourceLayer(); + cmd.args.copyTex.srcFaceTarget = srcFaceTargetBase + uint(u.copy.desc.sourceLayer()); cmd.args.copyTex.srcTexture = srcD->texture; cmd.args.copyTex.srcLevel = u.copy.desc.sourceLevel(); cmd.args.copyTex.srcX = sp.x(); @@ -1466,7 +1466,7 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate cmd.args.copyTex.dstTarget = dstD->target; cmd.args.copyTex.dstTexture = dstD->texture; - cmd.args.copyTex.dstFaceTarget = dstFaceTargetBase + u.copy.desc.destinationLayer(); + cmd.args.copyTex.dstFaceTarget = dstFaceTargetBase + uint(u.copy.desc.destinationLayer()); cmd.args.copyTex.dstLevel = u.copy.desc.destinationLevel(); cmd.args.copyTex.dstX = dp.x(); cmd.args.copyTex.dstY = dp.y(); @@ -1488,7 +1488,7 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate cmd.args.readPixels.format = texD->m_format; const GLenum faceTargetBase = texD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target; - cmd.args.readPixels.readTarget = faceTargetBase + u.read.rb.layer(); + cmd.args.readPixels.readTarget = faceTargetBase + uint(u.read.rb.layer()); cmd.args.readPixels.level = u.read.rb.level(); } cbD->commands.append(cmd); @@ -1848,7 +1848,7 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) f->glBindVertexArray(0); break; case QGles2CommandBuffer::Command::Viewport: - f->glViewport(cmd.args.viewport.x, cmd.args.viewport.y, cmd.args.viewport.w, cmd.args.viewport.h); + f->glViewport(GLint(cmd.args.viewport.x), GLint(cmd.args.viewport.y), GLsizei(cmd.args.viewport.w), GLsizei(cmd.args.viewport.h)); f->glDepthRangef(cmd.args.viewport.d0, cmd.args.viewport.d1); break; case QGles2CommandBuffer::Command::Scissor: @@ -1861,8 +1861,8 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) { QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.stencilRef.ps); if (psD) { - f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask); - f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask); + f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), GLint(cmd.args.stencilRef.ref), psD->m_stencilReadMask); + f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), GLint(cmd.args.stencilRef.ref), psD->m_stencilReadMask); } else { qWarning("No graphics pipeline active for setStencilRef; ignored"); } @@ -1882,7 +1882,7 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) // we do not support more than one vertex buffer f->glBindBuffer(GL_ARRAY_BUFFER, cmd.args.bindVertexBuffer.buffer); - const int stride = bindings[bindingIdx].stride(); + const int stride = int(bindings[bindingIdx].stride()); int size = 1; GLenum type = GL_FLOAT; bool normalize = false; @@ -1924,13 +1924,13 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) const int locationIdx = a.location(); quint32 ofs = a.offset() + cmd.args.bindVertexBuffer.offset; - f->glVertexAttribPointer(locationIdx, size, type, normalize, stride, + f->glVertexAttribPointer(GLuint(locationIdx), size, type, normalize, stride, reinterpret_cast(quintptr(ofs))); - f->glEnableVertexAttribArray(locationIdx); + f->glEnableVertexAttribArray(GLuint(locationIdx)); if (bindings[bindingIdx].classification() == QRhiVertexInputBinding::PerInstance && caps.instancing) { - f->glVertexAttribDivisor(locationIdx, bindings[bindingIdx].instanceStepRate()); + f->glVertexAttribDivisor(GLuint(locationIdx), GLuint(bindings[bindingIdx].instanceStepRate())); } } } else { @@ -1949,10 +1949,10 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.draw.ps); if (psD) { if (cmd.args.draw.instanceCount == 1 || !caps.instancing) { - f->glDrawArrays(psD->drawMode, cmd.args.draw.firstVertex, cmd.args.draw.vertexCount); + f->glDrawArrays(psD->drawMode, GLint(cmd.args.draw.firstVertex), GLsizei(cmd.args.draw.vertexCount)); } else { - f->glDrawArraysInstanced(psD->drawMode, cmd.args.draw.firstVertex, cmd.args.draw.vertexCount, - cmd.args.draw.instanceCount); + f->glDrawArraysInstanced(psD->drawMode, GLint(cmd.args.draw.firstVertex), GLsizei(cmd.args.draw.vertexCount), + GLsizei(cmd.args.draw.instanceCount)); } } else { qWarning("No graphics pipeline active for draw; ignored"); @@ -1968,30 +1968,30 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) if (cmd.args.drawIndexed.instanceCount == 1 || !caps.instancing) { if (cmd.args.drawIndexed.baseVertex != 0 && caps.baseVertex) { f->glDrawElementsBaseVertex(psD->drawMode, - cmd.args.drawIndexed.indexCount, + GLsizei(cmd.args.drawIndexed.indexCount), indexType, ofs, cmd.args.drawIndexed.baseVertex); } else { f->glDrawElements(psD->drawMode, - cmd.args.drawIndexed.indexCount, + GLsizei(cmd.args.drawIndexed.indexCount), indexType, ofs); } } else { if (cmd.args.drawIndexed.baseVertex != 0 && caps.baseVertex) { f->glDrawElementsInstancedBaseVertex(psD->drawMode, - cmd.args.drawIndexed.indexCount, + GLsizei(cmd.args.drawIndexed.indexCount), indexType, ofs, - cmd.args.drawIndexed.instanceCount, + GLsizei(cmd.args.drawIndexed.instanceCount), cmd.args.drawIndexed.baseVertex); } else { f->glDrawElementsInstanced(psD->drawMode, - cmd.args.drawIndexed.indexCount, + GLsizei(cmd.args.drawIndexed.indexCount), indexType, ofs, - cmd.args.drawIndexed.instanceCount); + GLsizei(cmd.args.drawIndexed.instanceCount)); } } } else { @@ -2016,7 +2016,7 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) const int colorAttCount = cmd.args.bindFramebuffer.colorAttCount; QVarLengthArray bufs; for (int i = 0; i < colorAttCount; ++i) - bufs.append(GL_COLOR_ATTACHMENT0 + i); + bufs.append(GL_COLOR_ATTACHMENT0 + uint(i)); f->glDrawBuffers(colorAttCount, bufs.constData()); } } else { @@ -2044,7 +2044,7 @@ void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb) f->glClearDepthf(cmd.args.clear.d); } if (cmd.args.clear.mask & GL_STENCIL_BUFFER_BIT) - f->glClearStencil(cmd.args.clear.s); + f->glClearStencil(GLint(cmd.args.clear.s)); f->glClear(cmd.args.clear.mask); break; case QGles2CommandBuffer::Command::BufferSubData: @@ -2288,7 +2288,7 @@ void QRhiGles2::bindShaderResources(QRhiGraphicsPipeline *maybeGraphicsPs, QRhiC if (dynOfsCount) { for (int j = 0; j < dynOfsCount; ++j) { if (dynOfsPairs[2 * j] == uint(b->binding)) { - viewOffset = dynOfsPairs[2 * j + 1]; + viewOffset = int(dynOfsPairs[2 * j + 1]); break; } } @@ -2379,20 +2379,20 @@ void QRhiGles2::bindShaderResources(QRhiGraphicsPipeline *maybeGraphicsPs, QRhiC for (QGles2SamplerDescription &sampler : samplers) { if (sampler.binding == b->binding) { - f->glActiveTexture(GL_TEXTURE0 + texUnit); + f->glActiveTexture(GL_TEXTURE0 + uint(texUnit)); f->glBindTexture(texD->target, texD->texture); if (texD->samplerState != samplerD->d) { - f->glTexParameteri(texD->target, GL_TEXTURE_MIN_FILTER, samplerD->d.glminfilter); - f->glTexParameteri(texD->target, GL_TEXTURE_MAG_FILTER, samplerD->d.glmagfilter); - f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_S, samplerD->d.glwraps); - f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_T, samplerD->d.glwrapt); + f->glTexParameteri(texD->target, GL_TEXTURE_MIN_FILTER, GLint(samplerD->d.glminfilter)); + f->glTexParameteri(texD->target, GL_TEXTURE_MAG_FILTER, GLint(samplerD->d.glmagfilter)); + f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_S, GLint(samplerD->d.glwraps)); + f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_T, GLint(samplerD->d.glwrapt)); // 3D textures not supported by GLES 2.0 or by us atm... //f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_R, samplerD->d.glwrapr); if (caps.textureCompareMode) { if (samplerD->d.gltexcomparefunc != GL_NEVER) { f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); - f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_FUNC, samplerD->d.gltexcomparefunc); + f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_FUNC, GLint(samplerD->d.gltexcomparefunc)); } else { f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_MODE, GL_NONE); } @@ -2419,7 +2419,7 @@ void QRhiGles2::bindShaderResources(QRhiGraphicsPipeline *maybeGraphicsPs, QRhiC access = GL_READ_ONLY; else if (b->type == QRhiShaderResourceBinding::ImageStore) access = GL_WRITE_ONLY; - f->glBindImageTexture(b->binding, texD->texture, + f->glBindImageTexture(GLuint(b->binding), texD->texture, b->u.simage.level, layered, 0, access, texD->glsizedintformat); } @@ -2432,9 +2432,9 @@ void QRhiGles2::bindShaderResources(QRhiGraphicsPipeline *maybeGraphicsPs, QRhiC { QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, b->u.sbuf.buf); if (b->u.sbuf.offset == 0 && b->u.sbuf.maybeSize == 0) - f->glBindBufferBase(GL_SHADER_STORAGE_BUFFER, b->binding, bufD->buffer); + f->glBindBufferBase(GL_SHADER_STORAGE_BUFFER, GLuint(b->binding), bufD->buffer); else - f->glBindBufferRange(GL_SHADER_STORAGE_BUFFER, b->binding, bufD->buffer, + f->glBindBufferRange(GL_SHADER_STORAGE_BUFFER, GLuint(b->binding), bufD->buffer, b->u.sbuf.offset, b->u.sbuf.maybeSize ? b->u.sbuf.maybeSize : bufD->m_size); } break; @@ -2556,10 +2556,10 @@ void QRhiGles2::beginPass(QRhiCommandBuffer *cb, clearCmd.args.clear.mask |= GL_COLOR_BUFFER_BIT; if (rtD->dsAttCount && wantsDsClear) clearCmd.args.clear.mask |= GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT; - clearCmd.args.clear.c[0] = colorClearValue.redF(); - clearCmd.args.clear.c[1] = colorClearValue.greenF(); - clearCmd.args.clear.c[2] = colorClearValue.blueF(); - clearCmd.args.clear.c[3] = colorClearValue.alphaF(); + clearCmd.args.clear.c[0] = float(colorClearValue.redF()); + clearCmd.args.clear.c[1] = float(colorClearValue.greenF()); + clearCmd.args.clear.c[2] = float(colorClearValue.blueF()); + clearCmd.args.clear.c[3] = float(colorClearValue.alphaF()); clearCmd.args.clear.d = depthStencilClearValue.depthClearValue(); clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue(); cbD->commands.append(clearCmd); @@ -2597,7 +2597,7 @@ void QRhiGles2::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resource QGles2Texture *colorTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture()); const GLenum faceTargetBase = colorTexD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : colorTexD->target; - cmd.args.blitFromRb.target = faceTargetBase + colorAtt.resolveLayer(); + cmd.args.blitFromRb.target = faceTargetBase + uint(colorAtt.resolveLayer()); cmd.args.blitFromRb.texture = colorTexD->texture; cmd.args.blitFromRb.dstLevel = colorAtt.resolveLevel(); cbD->commands.append(cmd); @@ -2664,9 +2664,9 @@ void QRhiGles2::dispatch(QRhiCommandBuffer *cb, int x, int y, int z) QGles2CommandBuffer::Command cmd; cmd.cmd = QGles2CommandBuffer::Command::Dispatch; - cmd.args.dispatch.x = x; - cmd.args.dispatch.y = y; - cmd.args.dispatch.z = z; + cmd.args.dispatch.x = GLuint(x); + cmd.args.dispatch.y = GLuint(y); + cmd.args.dispatch.z = GLuint(z); cbD->commands.append(cmd); } @@ -2818,7 +2818,7 @@ void QRhiGles2::gatherUniforms(GLuint program, const QShaderDescription::Uniform uniform.glslLocation = f->glGetUniformLocation(program, name.constData()); if (uniform.glslLocation >= 0) { uniform.binding = ub.binding; - uniform.offset = blockMember.offset; + uniform.offset = uint(blockMember.offset); uniform.size = blockMember.size; dst->append(uniform); } @@ -2882,7 +2882,7 @@ bool QGles2Buffer::build() return false; } ubuf.resize(nonZeroSize); - QRHI_PROF_F(newBuffer(this, nonZeroSize, 0, 1)); + QRHI_PROF_F(newBuffer(this, uint(nonZeroSize), 0, 1)); return true; } @@ -2901,7 +2901,7 @@ bool QGles2Buffer::build() usageState.access = AccessNone; - QRHI_PROF_F(newBuffer(this, nonZeroSize, 1, 0)); + QRHI_PROF_F(newBuffer(this, uint(nonZeroSize), 1, 0)); rhiD->registerResource(this); return true; } @@ -3172,13 +3172,13 @@ bool QGles2Texture::build() for (int layer = 0, layerCount = isCube ? 6 : 1; layer != layerCount; ++layer) { for (int level = 0; level != mipLevelCount; ++level) { const QSize mipSize = rhiD->q->sizeForMipLevel(level, size); - rhiD->f->glTexImage2D(faceTargetBase + layer, level, glintformat, + rhiD->f->glTexImage2D(faceTargetBase + uint(layer), level, GLint(glintformat), mipSize.width(), mipSize.height(), 0, glformat, gltype, nullptr); } } } else { - rhiD->f->glTexImage2D(target, 0, glintformat, size.width(), size.height(), + rhiD->f->glTexImage2D(target, 0, GLint(glintformat), size.width(), size.height(), 0, glformat, gltype, nullptr); } } else { @@ -3381,14 +3381,15 @@ bool QGles2TextureRenderTarget::build() QGles2Texture *texD = QRHI_RES(QGles2Texture, texture); Q_ASSERT(texD->texture && texD->specified); const GLenum faceTargetBase = texD->flags().testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target; - rhiD->f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, faceTargetBase + colorAtt.layer(), texD->texture, colorAtt.level()); + rhiD->f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(i), faceTargetBase + uint(colorAtt.layer()), + texD->texture, colorAtt.level()); if (i == 0) { d.pixelSize = texD->pixelSize(); d.sampleCount = 1; } } else if (renderBuffer) { QGles2RenderBuffer *rbD = QRHI_RES(QGles2RenderBuffer, renderBuffer); - rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, rbD->renderbuffer); + rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(i), GL_RENDERBUFFER, rbD->renderbuffer); if (i == 0) { d.pixelSize = rbD->pixelSize(); d.sampleCount = rbD->samples; @@ -3538,7 +3539,7 @@ bool QGles2GraphicsPipeline::build() for (auto inVar : vsDesc.inputVariables()) { const QByteArray name = inVar.name.toUtf8(); - rhiD->f->glBindAttribLocation(program, inVar.location, name.constData()); + rhiD->f->glBindAttribLocation(program, GLuint(inVar.location), name.constData()); } if (!rhiD->linkProgram(program)) @@ -3684,7 +3685,7 @@ bool QGles2SwapChain::buildOrResize() rt.d.rp = QRHI_RES(QGles2RenderPassDescriptor, m_renderPassDesc); rt.d.pixelSize = pixelSize; - rt.d.dpr = m_window->devicePixelRatio(); + rt.d.dpr = float(m_window->devicePixelRatio()); rt.d.sampleCount = qBound(1, m_sampleCount, 64); rt.d.colorAttCount = 1; rt.d.dsAttCount = m_depthStencil ? 1 : 0; diff --git a/src/gui/rhi/qrhimetal.mm b/src/gui/rhi/qrhimetal.mm index a14ffa71735..3bf95ad6766 100644 --- a/src/gui/rhi/qrhimetal.mm +++ b/src/gui/rhi/qrhimetal.mm @@ -352,7 +352,8 @@ QRhiMetal::~QRhiMetal() delete d; } -static inline uint aligned(uint v, uint byteAlign) +template +inline Int aligned(Int v, Int byteAlign) { return (v + byteAlign - 1) & ~(byteAlign - 1); } @@ -655,7 +656,7 @@ void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD { QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->u.ubuf.buf); id mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0]; - uint offset = b->u.ubuf.offset; + uint offset = uint(b->u.ubuf.offset); for (int i = 0; i < dynamicOffsetCount; ++i) { const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]); if (dynOfs.first == b->binding) { @@ -719,7 +720,7 @@ void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD { QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->u.sbuf.buf); id mtlbuf = bufD->d->buf[0]; - uint offset = b->u.sbuf.offset; + uint offset = uint(b->u.sbuf.offset); if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) { res[0].buffers.feed(b->binding, mtlbuf); res[0].bufferOffsets.feed(b->binding, offset); @@ -751,17 +752,17 @@ void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD case 0: [cbD->d->currentRenderPassEncoder setVertexBuffers: bufferBatch.resources.constData() offsets: offsetBatch.resources.constData() - withRange: NSMakeRange(bufferBatch.startBinding, bufferBatch.resources.count())]; + withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))]; break; case 1: [cbD->d->currentRenderPassEncoder setFragmentBuffers: bufferBatch.resources.constData() offsets: offsetBatch.resources.constData() - withRange: NSMakeRange(bufferBatch.startBinding, bufferBatch.resources.count())]; + withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))]; break; case 2: [cbD->d->currentComputePassEncoder setBuffers: bufferBatch.resources.constData() offsets: offsetBatch.resources.constData() - withRange: NSMakeRange(bufferBatch.startBinding, bufferBatch.resources.count())]; + withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))]; break; default: Q_UNREACHABLE(); @@ -780,15 +781,15 @@ void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD switch (idx) { case 0: [cbD->d->currentRenderPassEncoder setVertexTextures: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; case 1: [cbD->d->currentRenderPassEncoder setFragmentTextures: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; case 2: [cbD->d->currentComputePassEncoder setTextures: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; default: Q_UNREACHABLE(); @@ -800,15 +801,15 @@ void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD switch (idx) { case 0: [cbD->d->currentRenderPassEncoder setVertexSamplerStates: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; case 1: [cbD->d->currentRenderPassEncoder setFragmentSamplerStates: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; case 2: [cbD->d->currentComputePassEncoder setSamplerStates: batch.resources.constData() - withRange: NSMakeRange(batch.startBinding, batch.resources.count())]; + withRange: NSMakeRange(batch.startBinding, NSUInteger(batch.resources.count()))]; break; default: Q_UNREACHABLE(); @@ -1006,7 +1007,7 @@ void QRhiMetal::setVertexInput(QRhiCommandBuffer *cb, [cbD->d->currentRenderPassEncoder setVertexBuffers: bufferBatch.resources.constData() offsets: offsetBatch.resources.constData() - withRange: NSMakeRange(firstVertexBinding + bufferBatch.startBinding, bufferBatch.resources.count())]; + withRange: NSMakeRange(uint(firstVertexBinding) + bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))]; } } @@ -1067,21 +1068,21 @@ void QRhiMetal::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) return; MTLViewport vp; - vp.originX = x; - vp.originY = y; - vp.width = w; - vp.height = h; - vp.znear = viewport.minDepth(); - vp.zfar = viewport.maxDepth(); + vp.originX = double(x); + vp.originY = double(y); + vp.width = double(w); + vp.height = double(h); + vp.znear = double(viewport.minDepth()); + vp.zfar = double(viewport.maxDepth()); [cbD->d->currentRenderPassEncoder setViewport: vp]; if (!QRHI_RES(QMetalGraphicsPipeline, cbD->currentGraphicsPipeline)->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor)) { MTLScissorRect s; - s.x = x; - s.y = y; - s.width = w; - s.height = h; + s.x = NSUInteger(x); + s.y = NSUInteger(y); + s.width = NSUInteger(w); + s.height = NSUInteger(h); [cbD->d->currentRenderPassEncoder setScissorRect: s]; } } @@ -1099,10 +1100,10 @@ void QRhiMetal::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) return; MTLScissorRect s; - s.x = x; - s.y = y; - s.width = w; - s.height = h; + s.x = NSUInteger(x); + s.y = NSUInteger(y); + s.width = NSUInteger(w); + s.height = NSUInteger(h); [cbD->d->currentRenderPassEncoder setScissorRect: s]; } @@ -1112,7 +1113,8 @@ void QRhiMetal::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb); Q_ASSERT(cbD->recordingPass == QMetalCommandBuffer::RenderPass); - [cbD->d->currentRenderPassEncoder setBlendColorRed: c.redF() green: c.greenF() blue: c.blueF() alpha: c.alphaF()]; + [cbD->d->currentRenderPassEncoder setBlendColorRed: float(c.redF()) + green: float(c.greenF()) blue: float(c.blueF()) alpha: float(c.alphaF())]; } void QRhiMetal::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) @@ -1144,7 +1146,7 @@ void QRhiMetal::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, return; const quint32 indexOffset = cbD->currentIndexOffset + firstIndex * (cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4); - Q_ASSERT(indexOffset == aligned(indexOffset, 4)); + Q_ASSERT(indexOffset == aligned(indexOffset, 4)); QMetalBuffer *ibufD = QRHI_RES(QMetalBuffer, cbD->currentIndexBuffer); id mtlbuf = ibufD->d->buf[ibufD->d->slotted ? currentFrameSlot : 0]; @@ -1402,7 +1404,7 @@ MTLRenderPassDescriptor *QRhiMetalData::createDefaultRenderPass(bool hasDepthSte MTLClearColor c = MTLClearColorMake(colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(), colorClearValue.alphaF()); - for (int i = 0; i < colorAttCount; ++i) { + for (uint i = 0; i < uint(colorAttCount); ++i) { rp.colorAttachments[i].loadAction = MTLLoadActionClear; rp.colorAttachments[i].storeAction = MTLStoreActionStore; rp.colorAttachments[i].clearColor = c; @@ -1413,7 +1415,7 @@ MTLRenderPassDescriptor *QRhiMetalData::createDefaultRenderPass(bool hasDepthSte rp.depthAttachment.storeAction = MTLStoreActionDontCare; rp.stencilAttachment.loadAction = MTLLoadActionClear; rp.stencilAttachment.storeAction = MTLStoreActionDontCare; - rp.depthAttachment.clearDepth = depthStencilClearValue.depthClearValue(); + rp.depthAttachment.clearDepth = double(depthStencilClearValue.depthClearValue()); rp.stencilAttachment.clearStencil = depthStencilClearValue.stencilClearValue(); } @@ -1426,7 +1428,7 @@ qsizetype QRhiMetal::subresUploadByteSize(const QRhiTextureSubresourceUploadDesc const qsizetype imageSizeBytes = subresDesc.image().isNull() ? subresDesc.data().size() : subresDesc.image().sizeInBytes(); if (imageSizeBytes > 0) - size += aligned(imageSizeBytes, QRhiMetalData::TEXBUF_ALIGN); + size += aligned(imageSizeBytes, QRhiMetalData::TEXBUF_ALIGN); return size; } @@ -1454,31 +1456,31 @@ void QRhiMetal::enqueueSubresUpload(QMetalTexture *texD, void *mp, void *blitEnc h = subresDesc.sourceSize().height(); } if (img.depth() == 32) { - memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), fullImageSizeBytes); + memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), size_t(fullImageSizeBytes)); srcOffset = sy * bpl + sx * 4; // bpl remains set to the original image's row stride } else { img = img.copy(sx, sy, w, h); bpl = img.bytesPerLine(); Q_ASSERT(img.sizeInBytes() <= fullImageSizeBytes); - memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), img.sizeInBytes()); + memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), size_t(img.sizeInBytes())); } } else { - memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), fullImageSizeBytes); + memcpy(reinterpret_cast(mp) + *curOfs, img.constBits(), size_t(fullImageSizeBytes)); } [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot] - sourceOffset: *curOfs + srcOffset - sourceBytesPerRow: bpl + sourceOffset: NSUInteger(*curOfs + srcOffset) + sourceBytesPerRow: NSUInteger(bpl) sourceBytesPerImage: 0 - sourceSize: MTLSizeMake(w, h, 1) + sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1) toTexture: texD->d->tex - destinationSlice: layer - destinationLevel: level - destinationOrigin: MTLOriginMake(dp.x(), dp.y(), 0) + destinationSlice: NSUInteger(layer) + destinationLevel: NSUInteger(level) + destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), 0) options: MTLBlitOptionNone]; - *curOfs += aligned(fullImageSizeBytes, QRhiMetalData::TEXBUF_ALIGN); + *curOfs += aligned(fullImageSizeBytes, QRhiMetalData::TEXBUF_ALIGN); } else if (!rawData.isEmpty() && isCompressedFormat(texD->m_format)) { const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize); const int subresw = subresSize.width(); @@ -1503,17 +1505,17 @@ void QRhiMetal::enqueueSubresUpload(QMetalTexture *texD, void *mp, void *blitEnc if (dy + h != subresh) h = aligned(h, blockDim.height()); - memcpy(reinterpret_cast(mp) + *curOfs, rawData.constData(), rawData.size()); + memcpy(reinterpret_cast(mp) + *curOfs, rawData.constData(), size_t(rawData.size())); [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot] - sourceOffset: *curOfs + sourceOffset: NSUInteger(*curOfs) sourceBytesPerRow: bpl sourceBytesPerImage: 0 - sourceSize: MTLSizeMake(w, h, 1) + sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1) toTexture: texD->d->tex - destinationSlice: layer - destinationLevel: level - destinationOrigin: MTLOriginMake(dx, dy, 0) + destinationSlice: NSUInteger(layer) + destinationLevel: NSUInteger(level) + destinationOrigin: MTLOriginMake(NSUInteger(dx), NSUInteger(dy), 0) options: MTLBlitOptionNone]; *curOfs += aligned(rawData.size(), QRhiMetalData::TEXBUF_ALIGN); @@ -1532,17 +1534,17 @@ void QRhiMetal::enqueueSubresUpload(QMetalTexture *texD, void *mp, void *blitEnc quint32 bpl = 0; textureFormatInfo(texD->m_format, QSize(w, h), &bpl, nullptr); - memcpy(reinterpret_cast(mp) + *curOfs, rawData.constData(), rawData.size()); + memcpy(reinterpret_cast(mp) + *curOfs, rawData.constData(), size_t(rawData.size())); [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot] - sourceOffset: *curOfs + sourceOffset: NSUInteger(*curOfs) sourceBytesPerRow: bpl sourceBytesPerImage: 0 - sourceSize: MTLSizeMake(w, h, 1) + sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1) toTexture: texD->d->tex - destinationSlice: layer - destinationLevel: level - destinationOrigin: MTLOriginMake(dp.x(), dp.y(), 0) + destinationSlice: NSUInteger(layer) + destinationLevel: NSUInteger(level) + destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), 0) options: MTLBlitOptionNone]; *curOfs += aligned(rawData.size(), QRhiMetalData::TEXBUF_ALIGN); @@ -1596,9 +1598,9 @@ void QRhiMetal::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate ensureBlit(); Q_ASSERT(!utexD->d->stagingBuf[currentFrameSlot]); - utexD->d->stagingBuf[currentFrameSlot] = [d->dev newBufferWithLength: stagingSize + utexD->d->stagingBuf[currentFrameSlot] = [d->dev newBufferWithLength: NSUInteger(stagingSize) options: MTLResourceStorageModeShared]; - QRHI_PROF_F(newTextureStagingArea(utexD, currentFrameSlot, stagingSize)); + QRHI_PROF_F(newTextureStagingArea(utexD, currentFrameSlot, quint32(stagingSize))); void *mp = [utexD->d->stagingBuf[currentFrameSlot] contents]; qsizetype curOfs = 0; @@ -1628,14 +1630,14 @@ void QRhiMetal::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate ensureBlit(); [blitEnc copyFromTexture: srcD->d->tex - sourceSlice: u.copy.desc.sourceLayer() - sourceLevel: u.copy.desc.sourceLevel() - sourceOrigin: MTLOriginMake(sp.x(), sp.y(), 0) - sourceSize: MTLSizeMake(size.width(), size.height(), 1) + sourceSlice: NSUInteger(u.copy.desc.sourceLayer()) + sourceLevel: NSUInteger(u.copy.desc.sourceLevel()) + sourceOrigin: MTLOriginMake(NSUInteger(sp.x()), NSUInteger(sp.y()), 0) + sourceSize: MTLSizeMake(NSUInteger(size.width()), NSUInteger(size.height()), 1) toTexture: dstD->d->tex - destinationSlice: u.copy.desc.destinationLayer() - destinationLevel: u.copy.desc.destinationLevel() - destinationOrigin: MTLOriginMake(dp.x(), dp.y(), 0)]; + destinationSlice: NSUInteger(u.copy.desc.destinationLayer()) + destinationLevel: NSUInteger(u.copy.desc.destinationLevel()) + destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), 0)]; srcD->lastActiveFrameSlot = dstD->lastActiveFrameSlot = currentFrameSlot; } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Read) { @@ -1675,16 +1677,16 @@ void QRhiMetal::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate textureFormatInfo(aRb.format, aRb.pixelSize, &bpl, &aRb.bufSize); aRb.buf = [d->dev newBufferWithLength: aRb.bufSize options: MTLResourceStorageModeShared]; - QRHI_PROF_F(newReadbackBuffer(quint64(quintptr(aRb.buf)), + QRHI_PROF_F(newReadbackBuffer(qint64(qintptr(aRb.buf)), texD ? static_cast(texD) : static_cast(swapChainD), aRb.bufSize)); ensureBlit(); [blitEnc copyFromTexture: src - sourceSlice: u.read.rb.layer() - sourceLevel: u.read.rb.level() + sourceSlice: NSUInteger(u.read.rb.layer()) + sourceLevel: NSUInteger(u.read.rb.level()) sourceOrigin: MTLOriginMake(0, 0, 0) - sourceSize: MTLSizeMake(srcSize.width(), srcSize.height(), 1) + sourceSize: MTLSizeMake(NSUInteger(srcSize.width()), NSUInteger(srcSize.height()), 1) toBuffer: aRb.buf destinationOffset: 0 destinationBytesPerRow: bpl @@ -1722,14 +1724,14 @@ void QRhiMetal::executeBufferHostWritesForCurrentFrame(QMetalBuffer *bufD) int changeEnd = -1; for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : updates) { Q_ASSERT(bufD == QRHI_RES(QMetalBuffer, u.buf)); - memcpy(static_cast(p) + u.offset, u.data.constData(), u.data.size()); + memcpy(static_cast(p) + u.offset, u.data.constData(), size_t(u.data.size())); if (changeBegin == -1 || u.offset < changeBegin) changeBegin = u.offset; if (changeEnd == -1 || u.offset + u.data.size() > changeEnd) changeEnd = u.offset + u.data.size(); } if (changeBegin >= 0 && bufD->d->managed) - [bufD->d->buf[idx] didModifyRange: NSMakeRange(changeBegin, changeEnd - changeBegin)]; + [bufD->d->buf[idx] didModifyRange: NSMakeRange(NSUInteger(changeBegin), NSUInteger(changeEnd - changeBegin))]; updates.clear(); } @@ -1786,7 +1788,7 @@ void QRhiMetal::beginPass(QRhiCommandBuffer *cb, rtD = rtTex->d; cbD->d->currentPassRpDesc = d->createDefaultRenderPass(rtD->dsAttCount, colorClearValue, depthStencilClearValue, rtD->colorAttCount); if (rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents)) { - for (int i = 0; i < rtD->colorAttCount; ++i) + for (uint i = 0; i < uint(rtD->colorAttCount); ++i) cbD->d->currentPassRpDesc.colorAttachments[i].loadAction = MTLLoadActionLoad; } if (rtD->dsAttCount && rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents)) { @@ -1813,15 +1815,15 @@ void QRhiMetal::beginPass(QRhiCommandBuffer *cb, break; } - for (int i = 0; i < rtD->colorAttCount; ++i) { + for (uint i = 0; i < uint(rtD->colorAttCount); ++i) { cbD->d->currentPassRpDesc.colorAttachments[i].texture = rtD->fb.colorAtt[i].tex; - cbD->d->currentPassRpDesc.colorAttachments[i].slice = rtD->fb.colorAtt[i].layer; - cbD->d->currentPassRpDesc.colorAttachments[i].level = rtD->fb.colorAtt[i].level; + cbD->d->currentPassRpDesc.colorAttachments[i].slice = NSUInteger(rtD->fb.colorAtt[i].layer); + cbD->d->currentPassRpDesc.colorAttachments[i].level = NSUInteger(rtD->fb.colorAtt[i].level); if (rtD->fb.colorAtt[i].resolveTex) { cbD->d->currentPassRpDesc.colorAttachments[i].storeAction = MTLStoreActionMultisampleResolve; cbD->d->currentPassRpDesc.colorAttachments[i].resolveTexture = rtD->fb.colorAtt[i].resolveTex; - cbD->d->currentPassRpDesc.colorAttachments[i].resolveSlice = rtD->fb.colorAtt[i].resolveLayer; - cbD->d->currentPassRpDesc.colorAttachments[i].resolveLevel = rtD->fb.colorAtt[i].resolveLevel; + cbD->d->currentPassRpDesc.colorAttachments[i].resolveSlice = NSUInteger(rtD->fb.colorAtt[i].resolveLayer); + cbD->d->currentPassRpDesc.colorAttachments[i].resolveLevel = NSUInteger(rtD->fb.colorAtt[i].resolveLevel); } } @@ -1903,7 +1905,7 @@ void QRhiMetal::dispatch(QRhiCommandBuffer *cb, int x, int y, int z) Q_ASSERT(cbD->recordingPass == QMetalCommandBuffer::ComputePass); QMetalComputePipeline *psD = QRHI_RES(QMetalComputePipeline, cbD->currentComputePipeline); - [cbD->d->currentComputePassEncoder dispatchThreadgroups: MTLSizeMake(x, y, z) + [cbD->d->currentComputePassEncoder dispatchThreadgroups: MTLSizeMake(NSUInteger(x), NSUInteger(y), NSUInteger(z)) threadsPerThreadgroup: psD->d->localSize]; } @@ -1971,12 +1973,12 @@ void QRhiMetal::finishActiveReadbacks(bool forced) if (forced || currentFrameSlot == aRb.activeFrameSlot || aRb.activeFrameSlot < 0) { aRb.result->format = aRb.format; aRb.result->pixelSize = aRb.pixelSize; - aRb.result->data.resize(aRb.bufSize); + aRb.result->data.resize(int(aRb.bufSize)); void *p = [aRb.buf contents]; memcpy(aRb.result->data.data(), p, aRb.bufSize); [aRb.buf release]; - QRHI_PROF_F(releaseReadbackBuffer(quint64(quintptr(aRb.buf)))); + QRHI_PROF_F(releaseReadbackBuffer(qint64(qintptr(aRb.buf)))); if (aRb.result->completed) completedCallbacks.append(aRb.result->completed); @@ -2035,8 +2037,8 @@ bool QMetalBuffer::build() return false; } - const int nonZeroSize = m_size <= 0 ? 256 : m_size; - const int roundedSize = m_usage.testFlag(QRhiBuffer::UniformBuffer) ? aligned(nonZeroSize, 256) : nonZeroSize; + const uint nonZeroSize = m_size <= 0 ? 256 : uint(m_size); + const uint roundedSize = m_usage.testFlag(QRhiBuffer::UniformBuffer) ? aligned(nonZeroSize, 256) : nonZeroSize; d->managed = false; MTLResourceOptions opts = MTLResourceStorageModeShared; @@ -2123,10 +2125,10 @@ bool QMetalRenderBuffer::build() MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init]; desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D; - desc.width = m_pixelSize.width(); - desc.height = m_pixelSize.height(); + desc.width = NSUInteger(m_pixelSize.width()); + desc.height = NSUInteger(m_pixelSize.height()); if (samples > 1) - desc.sampleCount = samples; + desc.sampleCount = NSUInteger(samples); desc.resourceOptions = MTLResourceStorageModePrivate; desc.usage = MTLTextureUsageRenderTarget; @@ -2393,11 +2395,11 @@ bool QMetalTexture::build() else desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D; desc.pixelFormat = d->format; - desc.width = size.width(); - desc.height = size.height(); - desc.mipmapLevelCount = mipLevelCount; + desc.width = NSUInteger(size.width()); + desc.height = NSUInteger(size.height()); + desc.mipmapLevelCount = NSUInteger(mipLevelCount); if (samples > 1) - desc.sampleCount = samples; + desc.sampleCount = NSUInteger(samples); desc.resourceOptions = MTLResourceStorageModePrivate; desc.storageMode = MTLStorageModePrivate; desc.usage = MTLTextureUsageShaderRead; @@ -2463,7 +2465,7 @@ id QMetalTextureData::viewForLevel(int level) const MTLTextureType type = [tex textureType]; const bool isCube = q->m_flags.testFlag(QRhiTexture::CubeMap); id view = [tex newTextureViewWithPixelFormat: format textureType: type - levels: NSMakeRange(level, 1) slices: NSMakeRange(0, isCube ? 6 : 1)]; + levels: NSMakeRange(NSUInteger(level), 1) slices: NSMakeRange(0, isCube ? 6 : 1)]; perLevelViews[level] = view; return view; @@ -2673,13 +2675,13 @@ QRhiRenderPassDescriptor *QMetalTextureRenderTarget::newCompatibleRenderPassDesc for (int i = 0, ie = colorAttachments.count(); i != ie; ++i) { QMetalTexture *texD = QRHI_RES(QMetalTexture, colorAttachments[i].texture()); QMetalRenderBuffer *rbD = QRHI_RES(QMetalRenderBuffer, colorAttachments[i].renderBuffer()); - rpD->colorFormat[i] = texD ? texD->d->format : rbD->d->format; + rpD->colorFormat[i] = int(texD ? texD->d->format : rbD->d->format); } if (m_desc.depthTexture()) - rpD->dsFormat = QRHI_RES(QMetalTexture, m_desc.depthTexture())->d->format; + rpD->dsFormat = int(QRHI_RES(QMetalTexture, m_desc.depthTexture())->d->format); else if (m_desc.depthStencilBuffer()) - rpD->dsFormat = QRHI_RES(QMetalRenderBuffer, m_desc.depthStencilBuffer())->d->format; + rpD->dsFormat = int(QRHI_RES(QMetalRenderBuffer, m_desc.depthStencilBuffer())->d->format); return rpD; } @@ -3079,7 +3081,7 @@ id QRhiMetalData::createMetalLib(const QShader &shader, QShader::Var QShaderCode mtllib = shader.shader({ QShader::MetalLibShader, 12, shaderVariant }); if (!mtllib.shader().isEmpty()) { dispatch_data_t data = dispatch_data_create(mtllib.shader().constData(), - mtllib.shader().size(), + size_t(mtllib.shader().size()), dispatch_get_global_queue(0, 0), DISPATCH_DATA_DESTRUCTOR_DEFAULT); NSError *err = nil; @@ -3139,19 +3141,19 @@ bool QMetalGraphicsPipeline::build() MTLVertexDescriptor *inputLayout = [MTLVertexDescriptor vertexDescriptor]; const QVector attributes = m_vertexInputLayout.attributes(); for (const QRhiVertexInputAttribute &attribute : attributes) { - const int loc = attribute.location(); + const uint loc = uint(attribute.location()); inputLayout.attributes[loc].format = toMetalAttributeFormat(attribute.format()); - inputLayout.attributes[loc].offset = attribute.offset(); - inputLayout.attributes[loc].bufferIndex = firstVertexBinding + attribute.binding(); + inputLayout.attributes[loc].offset = NSUInteger(attribute.offset()); + inputLayout.attributes[loc].bufferIndex = NSUInteger(firstVertexBinding + attribute.binding()); } const QVector bindings = m_vertexInputLayout.bindings(); for (int i = 0, ie = bindings.count(); i != ie; ++i) { const QRhiVertexInputBinding &binding(bindings[i]); - const int layoutIdx = firstVertexBinding + i; + const uint layoutIdx = uint(firstVertexBinding + i); inputLayout.layouts[layoutIdx].stepFunction = binding.classification() == QRhiVertexInputBinding::PerInstance ? MTLVertexStepFunctionPerInstance : MTLVertexStepFunctionPerVertex; - inputLayout.layouts[layoutIdx].stepRate = binding.instanceStepRate(); + inputLayout.layouts[layoutIdx].stepRate = NSUInteger(binding.instanceStepRate()); inputLayout.layouts[layoutIdx].stride = binding.stride(); } @@ -3239,8 +3241,8 @@ bool QMetalGraphicsPipeline::build() Q_ASSERT(m_targetBlends.count() == rpD->colorAttachmentCount || (m_targetBlends.isEmpty() && rpD->colorAttachmentCount == 1)); - for (int i = 0, ie = m_targetBlends.count(); i != ie; ++i) { - const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[i]); + for (uint i = 0, ie = uint(m_targetBlends.count()); i != ie; ++i) { + const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[int(i)]); rpDesc.colorAttachments[i].pixelFormat = MTLPixelFormat(rpD->colorFormat[i]); rpDesc.colorAttachments[i].blendingEnabled = b.enable; rpDesc.colorAttachments[i].sourceRGBBlendFactor = toMetalBlendFactor(b.srcColor); @@ -3262,7 +3264,7 @@ bool QMetalGraphicsPipeline::build() rpDesc.stencilAttachmentPixelFormat = fmt; } - rpDesc.sampleCount = rhiD->effectiveSampleCount(m_sampleCount); + rpDesc.sampleCount = NSUInteger(rhiD->effectiveSampleCount(m_sampleCount)); NSError *err = nil; d->ps = [rhiD->d->dev newRenderPipelineStateWithDescriptor: rpDesc error: &err]; @@ -3517,7 +3519,7 @@ QSize QMetalSwapChain::surfacePixelSize() CAMetalLayer *layer = (CAMetalLayer *) [v layer]; if (layer) { CGSize size = [layer drawableSize]; - return QSize(size.width, size.height); + return QSize(int(size.width), int(size.height)); } } return QSize(); @@ -3532,7 +3534,7 @@ QRhiRenderPassDescriptor *QMetalSwapChain::newCompatibleRenderPassDescriptor() rpD->colorAttachmentCount = 1; rpD->hasDepthStencil = m_depthStencil != nullptr; - rpD->colorFormat[0] = d->colorFormat; + rpD->colorFormat[0] = int(d->colorFormat); // m_depthStencil may not be built yet so cannot rely on computed fields in it rpD->dsFormat = rhiD->d->dev.depth24Stencil8PixelFormatSupported @@ -3616,7 +3618,7 @@ bool QMetalSwapChain::buildOrResize() } rtWrapper.d->pixelSize = pixelSize; - rtWrapper.d->dpr = window->devicePixelRatio(); + rtWrapper.d->dpr = float(window->devicePixelRatio()); rtWrapper.d->sampleCount = samples; rtWrapper.d->colorAttCount = 1; rtWrapper.d->dsAttCount = ds ? 1 : 0; @@ -3627,9 +3629,9 @@ bool QMetalSwapChain::buildOrResize() MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init]; desc.textureType = MTLTextureType2DMultisample; desc.pixelFormat = d->colorFormat; - desc.width = pixelSize.width(); - desc.height = pixelSize.height(); - desc.sampleCount = samples; + desc.width = NSUInteger(pixelSize.width()); + desc.height = NSUInteger(pixelSize.height()); + desc.sampleCount = NSUInteger(samples); desc.resourceOptions = MTLResourceStorageModePrivate; desc.storageMode = MTLStorageModePrivate; desc.usage = MTLTextureUsageRenderTarget; diff --git a/src/gui/rhi/qrhiprofiler.cpp b/src/gui/rhi/qrhiprofiler.cpp index e74e446a1c0..1521c0f36e9 100644 --- a/src/gui/rhi/qrhiprofiler.cpp +++ b/src/gui/rhi/qrhiprofiler.cpp @@ -319,7 +319,7 @@ void QRhiProfilerPrivate::writeFloat(const char *key, float f) Q_ASSERT(key[0] == 'F'); buf.append(key); buf.append(','); - buf.append(QByteArray::number(f)); + buf.append(QByteArray::number(double(f))); buf.append(','); } @@ -385,7 +385,7 @@ void QRhiProfilerPrivate::newRenderBuffer(QRhiRenderBuffer *rb, bool transientBa const QRhiTexture::Format assumedFormat = type == QRhiRenderBuffer::DepthStencil ? QRhiTexture::D32F : QRhiTexture::RGBA8; quint32 byteSize = rhiDWhenEnabled->approxByteSizeForTexture(assumedFormat, sz, 1, 1); if (sampleCount > 1) - byteSize *= sampleCount; + byteSize *= uint(sampleCount); startEntry(QRhiProfiler::NewRenderBuffer, ts.elapsed(), rb); writeInt("type", type); @@ -416,7 +416,7 @@ void QRhiProfilerPrivate::newTexture(QRhiTexture *tex, bool owns, int mipCount, const QSize sz = tex->pixelSize(); quint32 byteSize = rhiDWhenEnabled->approxByteSizeForTexture(format, sz, mipCount, layerCount); if (sampleCount > 1) - byteSize *= sampleCount; + byteSize *= uint(sampleCount); startEntry(QRhiProfiler::NewTexture, ts.elapsed(), tex); writeInt("width", sz.width()); @@ -467,7 +467,7 @@ void QRhiProfilerPrivate::resizeSwapChain(QRhiSwapChain *sc, int bufferCount, in const QSize sz = sc->currentPixelSize(); quint32 byteSize = rhiDWhenEnabled->approxByteSizeForTexture(QRhiTexture::BGRA8, sz, 1, 1); - byteSize = byteSize * bufferCount + byteSize * msaaBufferCount * sampleCount; + byteSize = byteSize * uint(bufferCount) + byteSize * uint(msaaBufferCount) * uint(sampleCount); startEntry(QRhiProfiler::ResizeSwapChain, ts.elapsed(), sc); writeInt("width", sz.width()); @@ -569,7 +569,7 @@ void QRhiProfilerPrivate::swapChainFrameGpuTime(QRhiSwapChain *sc, float gpuTime } } -void QRhiProfilerPrivate::newReadbackBuffer(quint64 id, QRhiResource *src, quint32 size) +void QRhiProfilerPrivate::newReadbackBuffer(qint64 id, QRhiResource *src, quint32 size) { if (!outputDevice) return; @@ -580,7 +580,7 @@ void QRhiProfilerPrivate::newReadbackBuffer(quint64 id, QRhiResource *src, quint endEntry(); } -void QRhiProfilerPrivate::releaseReadbackBuffer(quint64 id) +void QRhiProfilerPrivate::releaseReadbackBuffer(qint64 id) { if (!outputDevice) return; @@ -590,7 +590,7 @@ void QRhiProfilerPrivate::releaseReadbackBuffer(quint64 id) endEntry(); } -void QRhiProfilerPrivate::vmemStat(int realAllocCount, int subAllocCount, quint32 totalSize, quint32 unusedSize) +void QRhiProfilerPrivate::vmemStat(uint realAllocCount, uint subAllocCount, quint32 totalSize, quint32 unusedSize) { if (!outputDevice) return; diff --git a/src/gui/rhi/qrhiprofiler_p_p.h b/src/gui/rhi/qrhiprofiler_p_p.h index 49c6bd78ede..7d0f183fb11 100644 --- a/src/gui/rhi/qrhiprofiler_p_p.h +++ b/src/gui/rhi/qrhiprofiler_p_p.h @@ -79,10 +79,10 @@ public: void endSwapChainFrame(QRhiSwapChain *sc, int frameCount); void swapChainFrameGpuTime(QRhiSwapChain *sc, float gpuTimeMs); - void newReadbackBuffer(quint64 id, QRhiResource *src, quint32 size); - void releaseReadbackBuffer(quint64 id); + void newReadbackBuffer(qint64 id, QRhiResource *src, quint32 size); + void releaseReadbackBuffer(qint64 id); - void vmemStat(int realAllocCount, int subAllocCount, quint32 totalSize, quint32 unusedSize); + void vmemStat(uint realAllocCount, uint subAllocCount, quint32 totalSize, quint32 unusedSize); void startEntry(QRhiProfiler::StreamOp op, qint64 timestamp, QRhiResource *res); void writeInt(const char *key, qint64 v); diff --git a/src/gui/rhi/qrhivulkan.cpp b/src/gui/rhi/qrhivulkan.cpp index 4f550c6a90a..c4f298dafb1 100644 --- a/src/gui/rhi/qrhivulkan.cpp +++ b/src/gui/rhi/qrhivulkan.cpp @@ -211,7 +211,8 @@ QT_BEGIN_NAMESPACE \brief Holds the Vulkan render pass object backing a QRhiRenderPassDescriptor. */ -static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +template +inline Int aligned(Int v, Int byteAlign) { return (v + byteAlign - 1) & ~(byteAlign - 1); } @@ -370,7 +371,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) auto queryQueueFamilyProps = [this, &queueFamilyProps] { uint32_t queueCount = 0; f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, nullptr); - queueFamilyProps.resize(queueCount); + queueFamilyProps.resize(int(queueCount)); f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, queueFamilyProps.data()); }; @@ -391,7 +392,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) int requestedPhysDevIndex = -1; if (qEnvironmentVariableIsSet("QT_VK_PHYSICAL_DEVICE_INDEX")) requestedPhysDevIndex = qEnvironmentVariableIntValue("QT_VK_PHYSICAL_DEVICE_INDEX"); - for (uint32_t i = 0; i < physDevCount; ++i) { + for (int i = 0; i < int(physDevCount); ++i) { f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties); qCDebug(QRHI_LOG_INFO, "Physical device %d: '%s' %d.%d.%d", i, physDevProperties.deviceName, @@ -423,7 +424,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) i, queueFamilyProps[i].queueFlags, queueFamilyProps[i].queueCount); if (gfxQueueFamilyIdx == -1 && (queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) - && (!maybeWindow || inst->supportsPresent(physDev, i, maybeWindow))) + && (!maybeWindow || inst->supportsPresent(physDev, uint32_t(i), maybeWindow))) { if (queueFamilyProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT) gfxQueueFamilyIdx = i; @@ -444,7 +445,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) const float prio[] = { 0 }; memset(queueInfo, 0, sizeof(queueInfo)); queueInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - queueInfo[0].queueFamilyIndex = gfxQueueFamilyIdx; + queueInfo[0].queueFamilyIndex = uint32_t(gfxQueueFamilyIdx); queueInfo[0].queueCount = 1; queueInfo[0].pQueuePriorities = prio; @@ -480,9 +481,9 @@ bool QRhiVulkan::create(QRhi::Flags flags) devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; devInfo.queueCreateInfoCount = 1; devInfo.pQueueCreateInfos = queueInfo; - devInfo.enabledLayerCount = devLayers.count(); + devInfo.enabledLayerCount = uint32_t(devLayers.count()); devInfo.ppEnabledLayerNames = devLayers.constData(); - devInfo.enabledExtensionCount = requestedDevExts.count(); + devInfo.enabledExtensionCount = uint32_t(requestedDevExts.count()); devInfo.ppEnabledExtensionNames = requestedDevExts.constData(); err = f->vkCreateDevice(physDev, &devInfo, nullptr, &dev); @@ -498,7 +499,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) VkCommandPoolCreateInfo poolInfo; memset(&poolInfo, 0, sizeof(poolInfo)); poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - poolInfo.queueFamilyIndex = gfxQueueFamilyIdx; + poolInfo.queueFamilyIndex = uint32_t(gfxQueueFamilyIdx); VkResult err = df->vkCreateCommandPool(dev, &poolInfo, nullptr, &cmdPool); if (err != VK_SUCCESS) { qWarning("Failed to create command pool: %d", err); @@ -508,7 +509,7 @@ bool QRhiVulkan::create(QRhi::Flags flags) if (gfxQueueFamilyIdx != -1) { if (!gfxQueue) - df->vkGetDeviceQueue(dev, gfxQueueFamilyIdx, 0, &gfxQueue); + df->vkGetDeviceQueue(dev, uint32_t(gfxQueueFamilyIdx), 0, &gfxQueue); if (queueFamilyProps.isEmpty()) queryQueueFamilyProps(); @@ -691,7 +692,7 @@ bool QRhiVulkan::allocateDescriptorSet(VkDescriptorSetAllocateInfo *allocInfo, V df->vkResetDescriptorPool(dev, descriptorPools[i].pool, 0); descriptorPools[i].allocedDescSets = 0; } - if (descriptorPools[i].allocedDescSets + allocInfo->descriptorSetCount <= QVK_DESC_SETS_PER_POOL) { + if (descriptorPools[i].allocedDescSets + int(allocInfo->descriptorSetCount) <= QVK_DESC_SETS_PER_POOL) { VkResult err = tryAllocate(i); if (err == VK_SUCCESS) { descriptorPools[i].allocedDescSets += allocInfo->descriptorSetCount; @@ -901,8 +902,8 @@ bool QRhiVulkan::createTransientImage(VkFormat format, imgInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imgInfo.imageType = VK_IMAGE_TYPE_2D; imgInfo.format = format; - imgInfo.extent.width = pixelSize.width(); - imgInfo.extent.height = pixelSize.height(); + imgInfo.extent.width = uint32_t(pixelSize.width()); + imgInfo.extent.height = uint32_t(pixelSize.height()); imgInfo.extent.depth = 1; imgInfo.mipLevels = imgInfo.arrayLayers = 1; imgInfo.samples = samples; @@ -925,7 +926,7 @@ bool QRhiVulkan::createTransientImage(VkFormat format, VkMemoryAllocateInfo memInfo; memset(&memInfo, 0, sizeof(memInfo)); memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memInfo.allocationSize = aligned(memReq.size, memReq.alignment) * count; + memInfo.allocationSize = aligned(memReq.size, memReq.alignment) * VkDeviceSize(count); uint32_t startIndex = 0; do { @@ -1175,7 +1176,7 @@ bool QRhiVulkan::createOffscreenRenderPass(VkRenderPass *rp, VkSubpassDescription subpassDesc; memset(&subpassDesc, 0, sizeof(subpassDesc)); subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpassDesc.colorAttachmentCount = colorRefs.count(); + subpassDesc.colorAttachmentCount = uint32_t(colorRefs.count()); Q_ASSERT(colorRefs.count() == resolveRefs.count()); subpassDesc.pColorAttachments = !colorRefs.isEmpty() ? colorRefs.constData() : nullptr; subpassDesc.pDepthStencilAttachment = hasDepthStencil ? &dsRef : nullptr; @@ -1184,7 +1185,7 @@ bool QRhiVulkan::createOffscreenRenderPass(VkRenderPass *rp, VkRenderPassCreateInfo rpInfo; memset(&rpInfo, 0, sizeof(rpInfo)); rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - rpInfo.attachmentCount = attDescs.count(); + rpInfo.attachmentCount = uint32_t(attDescs.count()); rpInfo.pAttachments = attDescs.constData(); rpInfo.subpassCount = 1; rpInfo.pSubpasses = &subpassDesc; @@ -1325,7 +1326,7 @@ bool QRhiVulkan::recreateSwapChain(QRhiSwapChain *swapChain) } if (actualSwapChainBufferCount != reqBufferCount) qCDebug(QRHI_LOG_INFO, "Actual swapchain buffer count is %u", actualSwapChainBufferCount); - swapChainD->bufferCount = actualSwapChainBufferCount; + swapChainD->bufferCount = int(actualSwapChainBufferCount); VkImage swapChainImages[QVkSwapChain::MAX_BUFFER_COUNT]; err = vkGetSwapchainImagesKHR(dev, swapChainD->sc, &actualSwapChainBufferCount, swapChainImages); @@ -1540,12 +1541,12 @@ QRhi::FrameOpResult QRhiVulkan::beginFrame(QRhiSwapChain *swapChain, QRhi::Begin // will make B wait for A's frame 0 commands, so if a resource is written // in B's frame or when B checks for pending resource releases, that won't // mess up A's in-flight commands (as they are not in flight anymore). - waitCommandCompletion(swapChainD->currentFrameSlot); + waitCommandCompletion(int(swapChainD->currentFrameSlot)); // Now is the time to read the timestamps for the previous frame for this slot. if (frame.timestampQueryIndex >= 0) { quint64 timestamp[2] = { 0, 0 }; - VkResult err = df->vkGetQueryPoolResults(dev, timestampQueryPool, frame.timestampQueryIndex, 2, + VkResult err = df->vkGetQueryPoolResults(dev, timestampQueryPool, uint32_t(frame.timestampQueryIndex), 2, 2 * sizeof(quint64), timestamp, sizeof(quint64), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); timestampQueryPoolMap.clearBit(frame.timestampQueryIndex / 2); @@ -1585,10 +1586,10 @@ QRhi::FrameOpResult QRhiVulkan::beginFrame(QRhiSwapChain *swapChain, QRhi::Begin } } if (timestampQueryIdx >= 0) { - df->vkCmdResetQueryPool(frame.cmdBuf, timestampQueryPool, timestampQueryIdx, 2); + df->vkCmdResetQueryPool(frame.cmdBuf, timestampQueryPool, uint32_t(timestampQueryIdx), 2); // record timestamp at the start of the command buffer df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - timestampQueryPool, timestampQueryIdx); + timestampQueryPool, uint32_t(timestampQueryIdx)); frame.timestampQueryIndex = timestampQueryIdx; } @@ -1598,7 +1599,7 @@ QRhi::FrameOpResult QRhiVulkan::beginFrame(QRhiSwapChain *swapChain, QRhi::Begin QVkSwapChain::ImageResources &image(swapChainD->imageRes[swapChainD->currentImageIndex]); swapChainD->rtWrapper.d.fb = image.fb; - currentFrameSlot = swapChainD->currentFrameSlot; + currentFrameSlot = int(swapChainD->currentFrameSlot); currentSwapChain = swapChainD; if (swapChainD->ds) swapChainD->ds->lastActiveFrameSlot = currentFrameSlot; @@ -1653,7 +1654,7 @@ QRhi::FrameOpResult QRhiVulkan::endFrame(QRhiSwapChain *swapChain, QRhi::EndFram // record another timestamp, when enabled if (frame.timestampQueryIndex >= 0) { df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - timestampQueryPool, frame.timestampQueryIndex + 1); + timestampQueryPool, uint32_t(frame.timestampQueryIndex + 1)); } // stop recording and submit to the queue @@ -1932,8 +1933,8 @@ static inline QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const { QRhiPassResourceTracker::UsageState u; u.layout = 0; // unused with buffers - u.access = bufUsage.access; - u.stage = bufUsage.stage; + u.access = int(bufUsage.access); + u.stage = int(bufUsage.stage); return u; } @@ -1941,8 +1942,8 @@ static inline QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const { QRhiPassResourceTracker::UsageState u; u.layout = texUsage.layout; - u.access = texUsage.access; - u.stage = texUsage.stage; + u.access = int(texUsage.access); + u.stage = int(texUsage.stage); return u; } @@ -2106,8 +2107,8 @@ void QRhiVulkan::beginPass(QRhiCommandBuffer *cb, rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rpBeginInfo.renderPass = rtD->rp->rp; rpBeginInfo.framebuffer = rtD->fb; - rpBeginInfo.renderArea.extent.width = rtD->pixelSize.width(); - rpBeginInfo.renderArea.extent.height = rtD->pixelSize.height(); + rpBeginInfo.renderArea.extent.width = uint32_t(rtD->pixelSize.width()); + rpBeginInfo.renderArea.extent.height = uint32_t(rtD->pixelSize.height()); QVarLengthArray cvs; for (int i = 0; i < rtD->colorAttCount; ++i) { @@ -2127,7 +2128,7 @@ void QRhiVulkan::beginPass(QRhiCommandBuffer *cb, float(colorClearValue.alphaF()) } }; cvs.append(cv); } - rpBeginInfo.clearValueCount = cvs.count(); + rpBeginInfo.clearValueCount = uint32_t(cvs.count()); QVkCommandBuffer::Command cmd; cmd.cmd = QVkCommandBuffer::Command::BeginRenderPass; @@ -2229,7 +2230,7 @@ void QRhiVulkan::dispatch(QRhiCommandBuffer *cb, int x, int y, int z) Q_ASSERT(cbD->recordingPass == QVkCommandBuffer::ComputePass); if (cbD->useSecondaryCb) { - df->vkCmdDispatch(cbD->secondaryCbs.last(), x, y, z); + df->vkCmdDispatch(cbD->secondaryCbs.last(), uint32_t(x), uint32_t(y), uint32_t(z)); } else { QVkCommandBuffer::Command cmd; cmd.cmd = QVkCommandBuffer::Command::Dispatch; @@ -2245,7 +2246,7 @@ VkShaderModule QRhiVulkan::createShader(const QByteArray &spirv) VkShaderModuleCreateInfo shaderInfo; memset(&shaderInfo, 0, sizeof(shaderInfo)); shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - shaderInfo.codeSize = spirv.size(); + shaderInfo.codeSize = size_t(spirv.size()); shaderInfo.pCode = reinterpret_cast(spirv.constData()); VkShaderModule shaderModule; VkResult err = df->vkCreateShaderModule(dev, &shaderInfo, nullptr, &shaderModule); @@ -2292,7 +2293,7 @@ void QRhiVulkan::updateShaderResourceBindings(QRhiShaderResourceBindings *srb, i memset(&writeInfo, 0, sizeof(writeInfo)); writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeInfo.dstSet = srbD->descSets[frameSlot]; - writeInfo.dstBinding = b->binding; + writeInfo.dstBinding = uint32_t(b->binding); writeInfo.descriptorCount = 1; switch (b->type) { @@ -2306,8 +2307,8 @@ void QRhiVulkan::updateShaderResourceBindings(QRhiShaderResourceBindings *srb, i bd.ubuf.generation = bufD->generation; VkDescriptorBufferInfo bufInfo; bufInfo.buffer = bufD->m_type == QRhiBuffer::Dynamic ? bufD->buffers[frameSlot] : bufD->buffers[0]; - bufInfo.offset = b->u.ubuf.offset; - bufInfo.range = b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size; + bufInfo.offset = VkDeviceSize(b->u.ubuf.offset); + bufInfo.range = VkDeviceSize(b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size); // be nice and assert when we know the vulkan device would die a horrible death due to non-aligned reads Q_ASSERT(aligned(bufInfo.offset, ubufAlign) == bufInfo.offset); bufferInfos.append(bufInfo); @@ -2364,8 +2365,8 @@ void QRhiVulkan::updateShaderResourceBindings(QRhiShaderResourceBindings *srb, i bd.sbuf.generation = bufD->generation; VkDescriptorBufferInfo bufInfo; bufInfo.buffer = bufD->m_type == QRhiBuffer::Dynamic ? bufD->buffers[frameSlot] : bufD->buffers[0]; - bufInfo.offset = b->u.ubuf.offset; - bufInfo.range = b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size; + bufInfo.offset = VkDeviceSize(b->u.ubuf.offset); + bufInfo.range = VkDeviceSize(b->u.ubuf.maybeSize ? b->u.ubuf.maybeSize : bufD->m_size); bufferInfos.append(bufInfo); writeInfo.pBufferInfo = &bufferInfos.last(); } @@ -2379,7 +2380,7 @@ void QRhiVulkan::updateShaderResourceBindings(QRhiShaderResourceBindings *srb, i ++frameSlot; } - df->vkUpdateDescriptorSets(dev, writeInfos.count(), writeInfos.constData(), 0, nullptr); + df->vkUpdateDescriptorSets(dev, uint32_t(writeInfos.count()), writeInfos.constData(), 0, nullptr); } static inline bool accessIsWrite(VkAccessFlags access) @@ -2487,10 +2488,10 @@ void QRhiVulkan::subresourceBarrier(QVkCommandBuffer *cbD, VkImage image, memset(&barrier, 0, sizeof(barrier)); barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - barrier.subresourceRange.baseMipLevel = startLevel; - barrier.subresourceRange.levelCount = levelCount; - barrier.subresourceRange.baseArrayLayer = startLayer; - barrier.subresourceRange.layerCount = layerCount; + barrier.subresourceRange.baseMipLevel = uint32_t(startLevel); + barrier.subresourceRange.levelCount = uint32_t(levelCount); + barrier.subresourceRange.baseArrayLayer = uint32_t(startLayer); + barrier.subresourceRange.layerCount = uint32_t(layerCount); barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcAccessMask = srcAccess; @@ -2511,7 +2512,7 @@ VkDeviceSize QRhiVulkan::subresUploadByteSize(const QRhiTextureSubresourceUpload const qsizetype imageSizeBytes = subresDesc.image().isNull() ? subresDesc.data().size() : subresDesc.image().sizeInBytes(); if (imageSizeBytes > 0) - size += aligned(imageSizeBytes, texbufAlign); + size += aligned(VkDeviceSize(imageSizeBytes), texbufAlign); return size; } @@ -2528,8 +2529,8 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, memset(©Info, 0, sizeof(copyInfo)); copyInfo.bufferOffset = *curOfs; copyInfo.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyInfo.imageSubresource.mipLevel = level; - copyInfo.imageSubresource.baseArrayLayer = layer; + copyInfo.imageSubresource.mipLevel = uint32_t(level); + copyInfo.imageSubresource.baseArrayLayer = uint32_t(layer); copyInfo.imageSubresource.layerCount = 1; copyInfo.imageExtent.depth = 1; @@ -2544,7 +2545,7 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, // be taken into account for bufferRowLength. int bpc = qMax(1, image.depth() / 8); // this is in pixels, not bytes, to make it more complicated... - copyInfo.bufferRowLength = image.bytesPerLine() / bpc; + copyInfo.bufferRowLength = uint32_t(image.bytesPerLine() / bpc); if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) { const int sx = subresDesc.sourceTopLeft().x(); const int sy = subresDesc.sourceTopLeft().y(); @@ -2554,7 +2555,7 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, // The staging buffer will get the full image // regardless, just adjust the vk // buffer-to-image copy start offset. - copyInfo.bufferOffset += sy * image.bytesPerLine() + sx * 4; + copyInfo.bufferOffset += VkDeviceSize(sy * image.bytesPerLine() + sx * 4); // bufferRowLength remains set to the original image's width } else { image = image.copy(sx, sy, size.width(), size.height()); @@ -2563,13 +2564,13 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, // space reserved for this mip will be unused. copySizeBytes = image.sizeInBytes(); bpc = qMax(1, image.depth() / 8); - copyInfo.bufferRowLength = image.bytesPerLine() / bpc; + copyInfo.bufferRowLength = uint32_t(image.bytesPerLine() / bpc); } } copyInfo.imageOffset.x = dp.x(); copyInfo.imageOffset.y = dp.y(); - copyInfo.imageExtent.width = size.width(); - copyInfo.imageExtent.height = size.height(); + copyInfo.imageExtent.width = uint32_t(size.width()); + copyInfo.imageExtent.height = uint32_t(size.height()); copyInfos->append(copyInfo); } else if (!rawData.isEmpty() && isCompressedFormat(texD->m_format)) { copySizeBytes = imageSizeBytes = rawData.size(); @@ -2588,8 +2589,8 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, copyInfo.imageOffset.y = aligned(dp.y(), blockDim.height()); // width and height must be multiples of the block width and height // or x + width and y + height must equal the subresource width and height - copyInfo.imageExtent.width = dp.x() + w == subresw ? w : aligned(w, blockDim.width()); - copyInfo.imageExtent.height = dp.y() + h == subresh ? h : aligned(h, blockDim.height()); + copyInfo.imageExtent.width = uint32_t(dp.x() + w == subresw ? w : aligned(w, blockDim.width())); + copyInfo.imageExtent.height = uint32_t(dp.y() + h == subresh ? h : aligned(h, blockDim.height())); copyInfos->append(copyInfo); } else if (!rawData.isEmpty()) { copySizeBytes = imageSizeBytes = rawData.size(); @@ -2599,15 +2600,15 @@ void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level, size = subresDesc.sourceSize(); copyInfo.imageOffset.x = dp.x(); copyInfo.imageOffset.y = dp.y(); - copyInfo.imageExtent.width = size.width(); - copyInfo.imageExtent.height = size.height(); + copyInfo.imageExtent.width = uint32_t(size.width()); + copyInfo.imageExtent.height = uint32_t(size.height()); copyInfos->append(copyInfo); } else { qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level); } - memcpy(reinterpret_cast(mp) + *curOfs, src, copySizeBytes); - *curOfs += aligned(imageSizeBytes, texbufAlign); + memcpy(reinterpret_cast(mp) + *curOfs, src, size_t(copySizeBytes)); + *curOfs += aligned(VkDeviceSize(imageSizeBytes), texbufAlign); } void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates) @@ -2633,7 +2634,7 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; // must cover the entire buffer - this way multiple, partial updates per frame // are supported even when the staging buffer is reused (Static) - bufferInfo.size = bufD->m_size; + bufferInfo.size = VkDeviceSize(bufD->m_size); bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VmaAllocationCreateInfo allocInfo; @@ -2645,7 +2646,7 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat &bufD->stagingBuffers[currentFrameSlot], &allocation, nullptr); if (err == VK_SUCCESS) { bufD->stagingAllocations[currentFrameSlot] = allocation; - QRHI_PROF_F(newBufferStagingArea(bufD, currentFrameSlot, bufD->m_size)); + QRHI_PROF_F(newBufferStagingArea(bufD, currentFrameSlot, quint32(bufD->m_size))); } else { qWarning("Failed to create staging buffer of size %d: %d", bufD->m_size, err); continue; @@ -2659,18 +2660,18 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat qWarning("Failed to map buffer: %d", err); continue; } - memcpy(static_cast(p) + u.offset, u.data.constData(), u.data.size()); + memcpy(static_cast(p) + u.offset, u.data.constData(), size_t(u.data.size())); vmaUnmapMemory(toVmaAllocator(allocator), a); - vmaFlushAllocation(toVmaAllocator(allocator), a, u.offset, u.data.size()); + vmaFlushAllocation(toVmaAllocator(allocator), a, VkDeviceSize(u.offset), VkDeviceSize(u.data.size())); trackedBufferBarrier(cbD, bufD, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); VkBufferCopy copyInfo; memset(©Info, 0, sizeof(copyInfo)); - copyInfo.srcOffset = u.offset; - copyInfo.dstOffset = u.offset; - copyInfo.size = u.data.size(); + copyInfo.srcOffset = VkDeviceSize(u.offset); + copyInfo.dstOffset = VkDeviceSize(u.offset); + copyInfo.size = VkDeviceSize(u.data.size()); QVkCommandBuffer::Command cmd; cmd.cmd = QVkCommandBuffer::Command::CopyBuffer; @@ -2732,7 +2733,7 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat continue; } utexD->stagingAllocations[currentFrameSlot] = allocation; - QRHI_PROF_F(newTextureStagingArea(utexD, currentFrameSlot, stagingSize)); + QRHI_PROF_F(newTextureStagingArea(utexD, currentFrameSlot, quint32(stagingSize))); BufferImageCopyList copyInfos; size_t curOfs = 0; @@ -2799,24 +2800,24 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat memset(®ion, 0, sizeof(region)); region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.srcSubresource.mipLevel = u.copy.desc.sourceLevel(); - region.srcSubresource.baseArrayLayer = u.copy.desc.sourceLayer(); + region.srcSubresource.mipLevel = uint32_t(u.copy.desc.sourceLevel()); + region.srcSubresource.baseArrayLayer = uint32_t(u.copy.desc.sourceLayer()); region.srcSubresource.layerCount = 1; region.srcOffset.x = u.copy.desc.sourceTopLeft().x(); region.srcOffset.y = u.copy.desc.sourceTopLeft().y(); region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.dstSubresource.mipLevel = u.copy.desc.destinationLevel(); - region.dstSubresource.baseArrayLayer = u.copy.desc.destinationLayer(); + region.dstSubresource.mipLevel = uint32_t(u.copy.desc.destinationLevel()); + region.dstSubresource.baseArrayLayer = uint32_t(u.copy.desc.destinationLayer()); region.dstSubresource.layerCount = 1; region.dstOffset.x = u.copy.desc.destinationTopLeft().x(); region.dstOffset.y = u.copy.desc.destinationTopLeft().y(); const QSize size = u.copy.desc.pixelSize().isEmpty() ? srcD->m_pixelSize : u.copy.desc.pixelSize(); - region.extent.width = size.width(); - region.extent.height = size.height(); + region.extent.width = uint32_t(size.width()); + region.extent.height = uint32_t(size.height()); region.extent.depth = 1; trackedImageBarrier(cbD, srcD, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, @@ -2883,7 +2884,7 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo, &aRb.buf, &allocation, nullptr); if (err == VK_SUCCESS) { aRb.bufAlloc = allocation; - QRHI_PROF_F(newReadbackBuffer(quint64(aRb.buf), + QRHI_PROF_F(newReadbackBuffer(qint64(aRb.buf), texD ? static_cast(texD) : static_cast(swapChainD), aRb.bufSize)); } else { @@ -2896,11 +2897,11 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat memset(©Desc, 0, sizeof(copyDesc)); copyDesc.bufferOffset = 0; copyDesc.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyDesc.imageSubresource.mipLevel = u.read.rb.level(); - copyDesc.imageSubresource.baseArrayLayer = u.read.rb.layer(); + copyDesc.imageSubresource.mipLevel = uint32_t(u.read.rb.level()); + copyDesc.imageSubresource.baseArrayLayer = uint32_t(u.read.rb.layer()); copyDesc.imageSubresource.layerCount = 1; - copyDesc.imageExtent.width = aRb.pixelSize.width(); - copyDesc.imageExtent.height = aRb.pixelSize.height(); + copyDesc.imageExtent.width = uint32_t(aRb.pixelSize.width()); + copyDesc.imageExtent.height = uint32_t(aRb.pixelSize.height()); copyDesc.imageExtent.depth = 1; if (texD) { @@ -2953,7 +2954,7 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat if (!origStage) origStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - for (uint level = 1; level < utexD->mipLevelCount; ++level) { + for (int level = 1; level < int(utexD->mipLevelCount); ++level) { if (level == 1) { subresourceBarrier(cbD, utexD->image, origLayout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, @@ -2981,8 +2982,8 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat memset(®ion, 0, sizeof(region)); region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.srcSubresource.mipLevel = level - 1; - region.srcSubresource.baseArrayLayer = u.mipgen.layer; + region.srcSubresource.mipLevel = uint32_t(level) - 1; + region.srcSubresource.baseArrayLayer = uint32_t(u.mipgen.layer); region.srcSubresource.layerCount = 1; region.srcOffsets[1].x = qMax(1, w); @@ -2990,8 +2991,8 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat region.srcOffsets[1].z = 1; region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.dstSubresource.mipLevel = level; - region.dstSubresource.baseArrayLayer = u.mipgen.layer; + region.dstSubresource.mipLevel = uint32_t(level); + region.dstSubresource.baseArrayLayer = uint32_t(u.mipgen.layer); region.dstSubresource.layerCount = 1; region.dstOffsets[1].x = qMax(1, w >> 1); @@ -3018,13 +3019,13 @@ void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdat VK_ACCESS_TRANSFER_READ_BIT, origAccess, VK_PIPELINE_STAGE_TRANSFER_BIT, origStage, u.mipgen.layer, 1, - 0, utexD->mipLevelCount - 1); + 0, int(utexD->mipLevelCount) - 1); subresourceBarrier(cbD, utexD->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, origLayout, VK_ACCESS_TRANSFER_WRITE_BIT, origAccess, VK_PIPELINE_STAGE_TRANSFER_BIT, origStage, u.mipgen.layer, 1, - utexD->mipLevelCount - 1, 1); + int(utexD->mipLevelCount) - 1, 1); } utexD->lastActiveFrameSlot = currentFrameSlot; @@ -3055,7 +3056,7 @@ void QRhiVulkan::executeBufferHostWritesForCurrentFrame(QVkBuffer *bufD) int changeEnd = -1; for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : updates) { Q_ASSERT(bufD == QRHI_RES(QVkBuffer, u.buf)); - memcpy(static_cast(p) + u.offset, u.data.constData(), u.data.size()); + memcpy(static_cast(p) + u.offset, u.data.constData(), size_t(u.data.size())); if (changeBegin == -1 || u.offset < changeBegin) changeBegin = u.offset; if (changeEnd == -1 || u.offset + u.data.size() > changeEnd) @@ -3063,7 +3064,7 @@ void QRhiVulkan::executeBufferHostWritesForCurrentFrame(QVkBuffer *bufD) } vmaUnmapMemory(toVmaAllocator(allocator), a); if (changeBegin >= 0) - vmaFlushAllocation(toVmaAllocator(allocator), a, changeBegin, changeEnd - changeBegin); + vmaFlushAllocation(toVmaAllocator(allocator), a, VkDeviceSize(changeBegin), VkDeviceSize(changeEnd - changeBegin)); updates.clear(); } @@ -3164,7 +3165,7 @@ void QRhiVulkan::finishActiveReadbacks(bool forced) if (forced || currentFrameSlot == aRb.activeFrameSlot || aRb.activeFrameSlot < 0) { aRb.result->format = aRb.format; aRb.result->pixelSize = aRb.pixelSize; - aRb.result->data.resize(aRb.bufSize); + aRb.result->data.resize(int(aRb.bufSize)); void *p = nullptr; VmaAllocation a = toVmaAllocation(aRb.bufAlloc); VkResult err = vmaMapMemory(toVmaAllocator(allocator), a, &p); @@ -3176,7 +3177,7 @@ void QRhiVulkan::finishActiveReadbacks(bool forced) vmaUnmapMemory(toVmaAllocator(allocator), a); vmaDestroyBuffer(toVmaAllocator(allocator), aRb.buf, a); - QRHI_PROF_F(releaseReadbackBuffer(quint64(aRb.buf))); + QRHI_PROF_F(releaseReadbackBuffer(qint64(aRb.buf))); if (aRb.result->completed) completedCallbacks.append(aRb.result->completed); @@ -3266,7 +3267,7 @@ void QRhiVulkan::recordPrimaryCommandBuffer(QVkCommandBuffer *cbD) case QVkCommandBuffer::Command::CopyBufferToImage: df->vkCmdCopyBufferToImage(cbD->cb, cmd.args.copyBufferToImage.src, cmd.args.copyBufferToImage.dst, cmd.args.copyBufferToImage.dstLayout, - cmd.args.copyBufferToImage.count, + uint32_t(cmd.args.copyBufferToImage.count), cbD->pools.bufferImageCopy.constData() + cmd.args.copyBufferToImage.bufferImageCopyIndex); break; case QVkCommandBuffer::Command::CopyImage: @@ -3315,13 +3316,13 @@ void QRhiVulkan::recordPrimaryCommandBuffer(QVkCommandBuffer *cbD) df->vkCmdBindDescriptorSets(cbD->cb, cmd.args.bindDescriptorSet.bindPoint, cmd.args.bindDescriptorSet.pipelineLayout, 0, 1, &cmd.args.bindDescriptorSet.descSet, - cmd.args.bindDescriptorSet.dynamicOffsetCount, + uint32_t(cmd.args.bindDescriptorSet.dynamicOffsetCount), offsets); } break; case QVkCommandBuffer::Command::BindVertexBuffer: - df->vkCmdBindVertexBuffers(cbD->cb, cmd.args.bindVertexBuffer.startBinding, - cmd.args.bindVertexBuffer.count, + df->vkCmdBindVertexBuffers(cbD->cb, uint32_t(cmd.args.bindVertexBuffer.startBinding), + uint32_t(cmd.args.bindVertexBuffer.count), cbD->pools.vertexBuffer.constData() + cmd.args.bindVertexBuffer.vertexBufferIndex, cbD->pools.vertexBufferOffset.constData() + cmd.args.bindVertexBuffer.vertexBufferOffsetIndex); break; @@ -3367,7 +3368,7 @@ void QRhiVulkan::recordPrimaryCommandBuffer(QVkCommandBuffer *cbD) recordTransitionPassResources(cbD, cbD->passResTrackers[cmd.args.transitionResources.trackerIndex]); break; case QVkCommandBuffer::Command::Dispatch: - df->vkCmdDispatch(cbD->cb, cmd.args.dispatch.x, cmd.args.dispatch.y, cmd.args.dispatch.z); + df->vkCmdDispatch(cbD->cb, uint32_t(cmd.args.dispatch.x), uint32_t(cmd.args.dispatch.y), uint32_t(cmd.args.dispatch.z)); break; case QVkCommandBuffer::Command::ExecuteSecondary: df->vkCmdExecuteCommands(cbD->cb, 1, &cmd.args.executeSecondary.cb); @@ -3421,8 +3422,8 @@ static inline VkPipelineStageFlags toVkPipelineStage(QRhiPassResourceTracker::Bu static inline QVkBuffer::UsageState toVkBufferUsageState(QRhiPassResourceTracker::UsageState usage) { QVkBuffer::UsageState u; - u.access = usage.access; - u.stage = usage.stage; + u.access = VkAccessFlags(usage.access); + u.stage = VkPipelineStageFlags(usage.stage); return u; } @@ -3494,8 +3495,8 @@ static inline QVkTexture::UsageState toVkTextureUsageState(QRhiPassResourceTrack { QVkTexture::UsageState u; u.layout = VkImageLayout(usage.layout); - u.access = usage.access; - u.stage = usage.stage; + u.access = VkAccessFlags(usage.access); + u.stage = VkPipelineStageFlags(usage.stage); return u; } @@ -3603,7 +3604,7 @@ QRhiBuffer *QRhiVulkan::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFla int QRhiVulkan::ubufAlignment() const { - return ubufAlign; // typically 256 (bytes) + return int(ubufAlign); // typically 256 (bytes) } bool QRhiVulkan::isYUpInFramebuffer() const @@ -3711,9 +3712,9 @@ int QRhiVulkan::resourceLimit(QRhi::ResourceLimit limit) const case QRhi::TextureSizeMin: return 1; case QRhi::TextureSizeMax: - return physDevProperties.limits.maxImageDimension2D; + return int(physDevProperties.limits.maxImageDimension2D); case QRhi::MaxColorAttachments: - return physDevProperties.limits.maxColorAttachments; + return int(physDevProperties.limits.maxColorAttachments); case QRhi::FramesInFlight: return QVK_FRAMES_IN_FLIGHT; default: @@ -3736,7 +3737,7 @@ void QRhiVulkan::sendVMemStatsToProfiler() VmaStats stats; vmaCalculateStats(toVmaAllocator(allocator), &stats); QRHI_PROF_F(vmemStat(stats.total.blockCount, stats.total.allocationCount, - stats.total.usedBytes, stats.total.unusedBytes)); + quint32(stats.total.usedBytes), quint32(stats.total.unusedBytes))); } void QRhiVulkan::makeThreadLocalNativeContextCurrent() @@ -4008,7 +4009,7 @@ void QRhiVulkan::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBin gfxPsD ? VK_PIPELINE_BIND_POINT_GRAPHICS : VK_PIPELINE_BIND_POINT_COMPUTE, gfxPsD ? gfxPsD->layout : compPsD->layout, 0, 1, &srbD->descSets[descSetIdx], - dynOfs.count(), + uint32_t(dynOfs.count()), dynOfs.count() ? dynOfs.constData() : nullptr); } else { QVkCommandBuffer::Command cmd; @@ -4078,8 +4079,8 @@ void QRhiVulkan::setVertexInput(QRhiCommandBuffer *cb, } if (cbD->useSecondaryCb) { - df->vkCmdBindVertexBuffers(cbD->secondaryCbs.last(), startBinding, - bufs.count(), bufs.constData(), ofs.constData()); + df->vkCmdBindVertexBuffers(cbD->secondaryCbs.last(), uint32_t(startBinding), + uint32_t(bufs.count()), bufs.constData(), ofs.constData()); } else { QVkCommandBuffer::Command cmd; cmd.cmd = QVkCommandBuffer::Command::BindVertexBuffer; @@ -4160,10 +4161,10 @@ void QRhiVulkan::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport if (!QRHI_RES(QVkGraphicsPipeline, cbD->currentGraphicsPipeline)->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor)) { VkRect2D *s = &cmd.args.setScissor.scissor; - s->offset.x = x; - s->offset.y = y; - s->extent.width = w; - s->extent.height = h; + s->offset.x = int32_t(x); + s->offset.y = int32_t(y); + s->extent.width = uint32_t(w); + s->extent.height = uint32_t(h); if (cbD->useSecondaryCb) { df->vkCmdSetScissor(cbD->secondaryCbs.last(), 0, 1, s); } else { @@ -4189,8 +4190,8 @@ void QRhiVulkan::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) VkRect2D *s = &cmd.args.setScissor.scissor; s->offset.x = x; s->offset.y = y; - s->extent.width = w; - s->extent.height = h; + s->extent.width = uint32_t(w); + s->extent.height = uint32_t(h); if (cbD->useSecondaryCb) { df->vkCmdSetScissor(cbD->secondaryCbs.last(), 0, 1, s); @@ -4211,10 +4212,10 @@ void QRhiVulkan::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) } else { QVkCommandBuffer::Command cmd; cmd.cmd = QVkCommandBuffer::Command::SetBlendConstants; - cmd.args.setBlendConstants.c[0] = c.redF(); - cmd.args.setBlendConstants.c[1] = c.greenF(); - cmd.args.setBlendConstants.c[2] = c.blueF(); - cmd.args.setBlendConstants.c[3] = c.alphaF(); + cmd.args.setBlendConstants.c[0] = float(c.redF()); + cmd.args.setBlendConstants.c[1] = float(c.greenF()); + cmd.args.setBlendConstants.c[2] = float(c.blueF()); + cmd.args.setBlendConstants.c[3] = float(c.alphaF()); cbD->commands.append(cmd); } } @@ -4843,7 +4844,7 @@ bool QVkBuffer::build() VkBufferCreateInfo bufferInfo; memset(&bufferInfo, 0, sizeof(bufferInfo)); bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.size = nonZeroSize; + bufferInfo.size = uint32_t(nonZeroSize); bufferInfo.usage = toVkBufferUsage(m_usage); VmaAllocationCreateInfo allocInfo; @@ -4890,7 +4891,7 @@ bool QVkBuffer::build() } QRHI_PROF; - QRHI_PROF_F(newBuffer(this, nonZeroSize, m_type != Dynamic ? 1 : QVK_FRAMES_IN_FLIGHT, 0)); + QRHI_PROF_F(newBuffer(this, uint(nonZeroSize), m_type != Dynamic ? 1 : QVK_FRAMES_IN_FLIGHT, 0)); lastActiveFrameSlot = -1; generation += 1; @@ -5081,7 +5082,7 @@ bool QVkTexture::prepareBuild(QSize *adjustedSize) const bool isCube = m_flags.testFlag(CubeMap); const bool hasMipMaps = m_flags.testFlag(MipMapped); - mipLevelCount = hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1; + mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1); const int maxLevels = QRhi::MAX_LEVELS; if (mipLevelCount > maxLevels) { qWarning("Too many mip levels (%d, max is %d), truncating mip chain", mipLevelCount, maxLevels); @@ -5160,8 +5161,8 @@ bool QVkTexture::build() imageInfo.flags = isCube ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0; imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.format = vkformat; - imageInfo.extent.width = size.width(); - imageInfo.extent.height = size.height(); + imageInfo.extent.width = uint32_t(size.width()); + imageInfo.extent.height = uint32_t(size.height()); imageInfo.extent.depth = 1; imageInfo.mipLevels = mipLevelCount; imageInfo.arrayLayers = isCube ? 6 : 1; @@ -5202,7 +5203,7 @@ bool QVkTexture::build() rhiD->setObjectName(uint64_t(image), VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, m_objectName); QRHI_PROF; - QRHI_PROF_F(newTexture(this, true, mipLevelCount, isCube ? 6 : 1, samples)); + QRHI_PROF_F(newTexture(this, true, int(mipLevelCount), isCube ? 6 : 1, samples)); owns = true; rhiD->registerResource(this); @@ -5224,7 +5225,7 @@ bool QVkTexture::buildFrom(const QRhiNativeHandles *src) return false; QRHI_PROF; - QRHI_PROF_F(newTexture(this, false, mipLevelCount, m_flags.testFlag(CubeMap) ? 6 : 1, samples)); + QRHI_PROF_F(newTexture(this, false, int(mipLevelCount), m_flags.testFlag(CubeMap) ? 6 : 1, samples)); usageState.layout = h->layout; @@ -5260,7 +5261,7 @@ VkImageView QVkTexture::imageViewForLevel(int level) viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; viewInfo.subresourceRange.aspectMask = isDepth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; - viewInfo.subresourceRange.baseMipLevel = level; + viewInfo.subresourceRange.baseMipLevel = uint32_t(level); viewInfo.subresourceRange.levelCount = 1; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = isCube ? 6 : 1; @@ -5501,9 +5502,9 @@ bool QVkTextureRenderTarget::build() viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - viewInfo.subresourceRange.baseMipLevel = colorAttachments[i].level(); + viewInfo.subresourceRange.baseMipLevel = uint32_t(colorAttachments[i].level()); viewInfo.subresourceRange.levelCount = 1; - viewInfo.subresourceRange.baseArrayLayer = colorAttachments[i].layer(); + viewInfo.subresourceRange.baseArrayLayer = uint32_t(colorAttachments[i].layer()); viewInfo.subresourceRange.layerCount = 1; VkResult err = rhiD->df->vkCreateImageView(rhiD->dev, &viewInfo, nullptr, &rtv[i]); if (err != VK_SUCCESS) { @@ -5565,9 +5566,9 @@ bool QVkTextureRenderTarget::build() viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - viewInfo.subresourceRange.baseMipLevel = colorAttachments[i].resolveLevel(); + viewInfo.subresourceRange.baseMipLevel = uint32_t(colorAttachments[i].resolveLevel()); viewInfo.subresourceRange.levelCount = 1; - viewInfo.subresourceRange.baseArrayLayer = colorAttachments[i].resolveLayer(); + viewInfo.subresourceRange.baseArrayLayer = uint32_t(colorAttachments[i].resolveLayer()); viewInfo.subresourceRange.layerCount = 1; VkResult err = rhiD->df->vkCreateImageView(rhiD->dev, &viewInfo, nullptr, &resrtv[i]); if (err != VK_SUCCESS) { @@ -5588,10 +5589,10 @@ bool QVkTextureRenderTarget::build() memset(&fbInfo, 0, sizeof(fbInfo)); fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fbInfo.renderPass = d.rp->rp; - fbInfo.attachmentCount = d.colorAttCount + d.dsAttCount + d.resolveAttCount; + fbInfo.attachmentCount = uint32_t(d.colorAttCount + d.dsAttCount + d.resolveAttCount); fbInfo.pAttachments = views.constData(); - fbInfo.width = d.pixelSize.width(); - fbInfo.height = d.pixelSize.height(); + fbInfo.width = uint32_t(d.pixelSize.width()); + fbInfo.height = uint32_t(d.pixelSize.height()); fbInfo.layers = 1; VkResult err = rhiD->df->vkCreateFramebuffer(rhiD->dev, &fbInfo, nullptr, &d.fb); @@ -5675,7 +5676,7 @@ bool QVkShaderResourceBindings::build() const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&binding); VkDescriptorSetLayoutBinding vkbinding; memset(&vkbinding, 0, sizeof(vkbinding)); - vkbinding.binding = b->binding; + vkbinding.binding = uint32_t(b->binding); vkbinding.descriptorType = toVkDescriptorType(b); vkbinding.descriptorCount = 1; // no array support yet vkbinding.stageFlags = toVkShaderStageFlags(b->stage); @@ -5792,7 +5793,7 @@ bool QVkGraphicsPipeline::build() shaderStageCreateInfos.append(shaderInfo); } } - pipelineInfo.stageCount = shaderStageCreateInfos.count(); + pipelineInfo.stageCount = uint32_t(shaderStageCreateInfos.count()); pipelineInfo.pStages = shaderStageCreateInfos.constData(); const QVector bindings = m_vertexInputLayout.bindings(); @@ -5833,15 +5834,15 @@ bool QVkGraphicsPipeline::build() VkPipelineVertexInputStateCreateInfo vertexInputInfo; memset(&vertexInputInfo, 0, sizeof(vertexInputInfo)); vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertexInputInfo.vertexBindingDescriptionCount = vertexBindings.count(); + vertexInputInfo.vertexBindingDescriptionCount = uint32_t(vertexBindings.count()); vertexInputInfo.pVertexBindingDescriptions = vertexBindings.constData(); - vertexInputInfo.vertexAttributeDescriptionCount = vertexAttributes.count(); + vertexInputInfo.vertexAttributeDescriptionCount = uint32_t(vertexAttributes.count()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributes.constData(); VkPipelineVertexInputDivisorStateCreateInfoEXT divisorInfo; if (!nonOneStepRates.isEmpty()) { memset(&divisorInfo, 0, sizeof(divisorInfo)); divisorInfo.sType = VkStructureType(1000190001); // VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT - divisorInfo.vertexBindingDivisorCount = nonOneStepRates.count(); + divisorInfo.vertexBindingDivisorCount = uint32_t(nonOneStepRates.count()); divisorInfo.pVertexBindingDivisors = nonOneStepRates.constData(); vertexInputInfo.pNext = &divisorInfo; } @@ -5858,7 +5859,7 @@ bool QVkGraphicsPipeline::build() VkPipelineDynamicStateCreateInfo dynamicInfo; memset(&dynamicInfo, 0, sizeof(dynamicInfo)); dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; - dynamicInfo.dynamicStateCount = dynEnable.count(); + dynamicInfo.dynamicStateCount = uint32_t(dynEnable.count()); dynamicInfo.pDynamicStates = dynEnable.constData(); pipelineInfo.pDynamicState = &dynamicInfo; @@ -5930,7 +5931,7 @@ bool QVkGraphicsPipeline::build() | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; vktargetBlends.append(blend); } - blendInfo.attachmentCount = vktargetBlends.count(); + blendInfo.attachmentCount = uint32_t(vktargetBlends.count()); blendInfo.pAttachments = vktargetBlends.constData(); pipelineInfo.pColorBlendState = &blendInfo; @@ -6131,11 +6132,11 @@ QSize QVkSwapChain::surfacePixelSize() QRHI_RES_RHI(QRhiVulkan); rhiD->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(rhiD->physDev, surface, &surfaceCaps); VkExtent2D bufferSize = surfaceCaps.currentExtent; - if (bufferSize.width == quint32(-1)) { - Q_ASSERT(bufferSize.height == quint32(-1)); + if (bufferSize.width == uint32_t(-1)) { + Q_ASSERT(bufferSize.height == uint32_t(-1)); return m_window->size() * m_window->devicePixelRatio(); } - return QSize(bufferSize.width, bufferSize.height); + return QSize(int(bufferSize.width), int(bufferSize.height)); } QRhiRenderPassDescriptor *QVkSwapChain::newCompatibleRenderPassDescriptor() @@ -6203,7 +6204,7 @@ bool QVkSwapChain::ensureSurface() QRHI_RES_RHI(QRhiVulkan); if (rhiD->gfxQueueFamilyIdx != -1) { - if (!rhiD->inst->supportsPresent(rhiD->physDev, rhiD->gfxQueueFamilyIdx, m_window)) { + if (!rhiD->inst->supportsPresent(rhiD->physDev, uint32_t(rhiD->gfxQueueFamilyIdx), m_window)) { qWarning("Presenting not supported on this window"); return false; } @@ -6232,7 +6233,7 @@ bool QVkSwapChain::ensureSurface() rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surface, &formatCount, formats.data()); const bool srgbRequested = m_flags.testFlag(sRGB); - for (quint32 i = 0; i < formatCount; ++i) { + for (int i = 0; i < int(formatCount); ++i) { if (formats[i].format != VK_FORMAT_UNDEFINED && srgbRequested == isSrgbFormat(formats[i].format)) { colorFormat = formats[i].format; colorSpace = formats[i].colorSpace; @@ -6293,7 +6294,7 @@ bool QVkSwapChain::buildOrResize() Q_ASSERT(rtWrapper.d.rp && rtWrapper.d.rp->rp); rtWrapper.d.pixelSize = pixelSize; - rtWrapper.d.dpr = window->devicePixelRatio(); + rtWrapper.d.dpr = float(window->devicePixelRatio()); rtWrapper.d.sampleCount = samples; rtWrapper.d.colorAttCount = 1; if (m_depthStencil) { @@ -6320,10 +6321,10 @@ bool QVkSwapChain::buildOrResize() memset(&fbInfo, 0, sizeof(fbInfo)); fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fbInfo.renderPass = rtWrapper.d.rp->rp; - fbInfo.attachmentCount = rtWrapper.d.colorAttCount + rtWrapper.d.dsAttCount + rtWrapper.d.resolveAttCount; + fbInfo.attachmentCount = uint32_t(rtWrapper.d.colorAttCount + rtWrapper.d.dsAttCount + rtWrapper.d.resolveAttCount); fbInfo.pAttachments = views; - fbInfo.width = pixelSize.width(); - fbInfo.height = pixelSize.height(); + fbInfo.width = uint32_t(pixelSize.width()); + fbInfo.height = uint32_t(pixelSize.height()); fbInfo.layers = 1; VkResult err = rhiD->df->vkCreateFramebuffer(rhiD->dev, &fbInfo, nullptr, &image.fb); From 1fbe3c23160120ab2d392ff841aa57d58a2e0063 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Mon, 9 Sep 2019 16:14:55 +0200 Subject: [PATCH 19/41] rhi: d3d11: Fix enabling alpha compositing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task-number: QTBUG-78089 Change-Id: I4e33665947debe007abcb976641e515224fa8451 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhid3d11.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index 2828256a90d..119234035a4 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -3773,11 +3773,23 @@ bool QD3D11SwapChain::buildOrResize() const UINT swapChainFlags = 0; QRHI_RES_RHI(QRhiD3D11); - const bool useFlipDiscard = rhiD->hasDxgi2 && rhiD->supportsFlipDiscardSwapchain; + bool useFlipDiscard = rhiD->hasDxgi2 && rhiD->supportsFlipDiscardSwapchain; if (!swapChain) { HWND hwnd = reinterpret_cast(window->winId()); sampleDesc = rhiD->effectiveSampleCount(m_sampleCount); + // Take a shortcut for alpha: our QWindow is OpenGLSurface so whatever + // the platform plugin does to enable transparency for OpenGL window + // will be sufficient for us too on the legacy (DISCARD) path. For + // FLIP_DISCARD we'd need to use DirectComposition (create a + // IDCompositionDevice/Target/Visual), avoid that for now. + if (m_flags.testFlag(SurfaceHasPreMulAlpha) || m_flags.testFlag(SurfaceHasNonPreMulAlpha)) { + useFlipDiscard = false; + if (window->requestedFormat().alphaBufferSize() <= 0) + qWarning("Swapchain says surface has alpha but the window has no alphaBufferSize set. " + "This may lead to problems."); + } + HRESULT hr; if (useFlipDiscard) { // We use FLIP_DISCARD which implies a buffer count of 2 (as opposed to the @@ -3796,10 +3808,9 @@ bool QD3D11SwapChain::buildOrResize() desc.BufferCount = BUFFER_COUNT; desc.Scaling = DXGI_SCALING_STRETCH; desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; - if (m_flags.testFlag(SurfaceHasPreMulAlpha)) - desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; - else if (m_flags.testFlag(SurfaceHasNonPreMulAlpha)) - desc.AlphaMode = DXGI_ALPHA_MODE_STRAIGHT; + // Do not bother with AlphaMode, if won't work unless we go through + // DirectComposition. Instead, we just take the other (DISCARD) + // path for now when alpha is requested. desc.Flags = swapChainFlags; IDXGISwapChain1 *sc1; From 6f592ea300dfc69343aef1e79c7df5579909d3e9 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Tue, 10 Sep 2019 16:22:15 +0200 Subject: [PATCH 20/41] rhi: gl: Avoid crash when reading back the swapchain backbuffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I9a632c06d8b9e666d99d0f135d3396d2de03f92a Reviewed-by: Christian Strømme --- src/gui/rhi/qrhigles2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gui/rhi/qrhigles2.cpp b/src/gui/rhi/qrhigles2.cpp index 0329acd350e..4d91ac45bdb 100644 --- a/src/gui/rhi/qrhigles2.cpp +++ b/src/gui/rhi/qrhigles2.cpp @@ -1480,7 +1480,8 @@ void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate cmd.cmd = QGles2CommandBuffer::Command::ReadPixels; cmd.args.readPixels.result = u.read.result; QGles2Texture *texD = QRHI_RES(QGles2Texture, u.read.rb.texture()); - trackedImageBarrier(cbD, texD, QGles2Texture::AccessRead); + if (texD) + trackedImageBarrier(cbD, texD, QGles2Texture::AccessRead); cmd.args.readPixels.texture = texD ? texD->texture : 0; if (texD) { cmd.args.readPixels.w = texD->m_pixelSize.width(); From d39d1a9e67affb3fd44fdd9ec71a50282a6fed1f Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Wed, 11 Sep 2019 09:50:57 +0200 Subject: [PATCH 21/41] rhi: Clarify the swapchain alpha flag docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: Iff0edf0ae40b830af0209403d899def922e6088c Reviewed-by: Christian Strømme --- src/gui/rhi/qrhi.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/gui/rhi/qrhi.cpp b/src/gui/rhi/qrhi.cpp index 65cfaf5123c..5ad433cf231 100644 --- a/src/gui/rhi/qrhi.cpp +++ b/src/gui/rhi/qrhi.cpp @@ -3458,10 +3458,18 @@ QRhiResource::Type QRhiGraphicsPipeline::resourceType() const Flag values to describe swapchain properties \value SurfaceHasPreMulAlpha Indicates that the target surface has - transparency with premultiplied alpha. + transparency with premultiplied alpha. For example, this is what Qt Quick + uses when the alpha channel is enabled on the target QWindow, because the + scenegraph rendrerer always outputs fragments with alpha multiplied into + the red, green, and blue values. To ensure identical behavior across + platforms, always set QSurfaceFormat::alphaBufferSize() to a non-zero value + on the target QWindow whenever this flag is set on the swapchain. \value SurfaceHasNonPreMulAlpha Indicates the target surface has - transparencyt with non-premultiplied alpha. + transparency with non-premultiplied alpha. Be aware that this may not be + supported on some systems, if the system compositor always expects content + with premultiplied alpha. In that case the behavior with this flag set is + expected to be equivalent to SurfaceHasPreMulAlpha. \value sRGB Requests to pick an sRGB format for the swapchain and/or its render target views, where applicable. Note that this implies that sRGB From 0616e14de0bf867bc2730b2b07005fbcbb234bb4 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Tue, 10 Sep 2019 14:09:41 +0200 Subject: [PATCH 22/41] rhi: Better handling of device loss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Starting with D3D11. The other backends will follow later. Change-Id: I4f165c9f1743df0fb00bdce1e898917575bf5f6e Reviewed-by: Christian Strømme --- src/gui/rhi/qrhi.cpp | 43 +++++++++++++++++++++++++++++++++++- src/gui/rhi/qrhi_p.h | 2 ++ src/gui/rhi/qrhi_p_p.h | 1 + src/gui/rhi/qrhid3d11.cpp | 21 ++++++++++++++++-- src/gui/rhi/qrhid3d11_p_p.h | 2 ++ src/gui/rhi/qrhigles2.cpp | 5 +++++ src/gui/rhi/qrhigles2_p_p.h | 1 + src/gui/rhi/qrhimetal.mm | 5 +++++ src/gui/rhi/qrhimetal_p_p.h | 1 + src/gui/rhi/qrhinull.cpp | 5 +++++ src/gui/rhi/qrhinull_p_p.h | 1 + src/gui/rhi/qrhivulkan.cpp | 5 +++++ src/gui/rhi/qrhivulkan_p_p.h | 1 + 13 files changed, 90 insertions(+), 3 deletions(-) diff --git a/src/gui/rhi/qrhi.cpp b/src/gui/rhi/qrhi.cpp index 5ad433cf231..fbdc90bd1b6 100644 --- a/src/gui/rhi/qrhi.cpp +++ b/src/gui/rhi/qrhi.cpp @@ -455,7 +455,7 @@ Q_LOGGING_CATEGORY(QRHI_LOG_INFO, "qt.rhi.general") \value FrameOpDeviceLost The graphics device was lost. This can be recoverable by attempting to repeat the operation (such as, beginFrame()) - and releasing and reinitializing all objects backed by native graphics + after releasing and reinitializing all objects backed by native graphics resources. */ @@ -5045,6 +5045,47 @@ void QRhi::releaseCachedResources() d->releaseCachedResources(); } +/*! + \return true if the graphics device was lost. + + The loss of the device is typically detected in beginFrame(), endFrame() or + QRhiSwapChain::buildOrResize(), depending on the backend and the underlying + native APIs. The most common is endFrame() because that is where presenting + happens. With some backends QRhiSwapChain::buildOrResize() can also fail + due to a device loss. Therefore this function is provided as a generic way + to check if a device loss was detected by a previous operation. + + When the device is lost, no further operations should be done via the QRhi. + Rather, all QRhi resources should be released, followed by destroying the + QRhi. A new QRhi can then be attempted to be created. If successful, all + graphics resources must be reinitialized. If not, try again later, + repeatedly. + + While simple applications may decide to not care about device loss, + on the commonly used desktop platforms a device loss can happen + due to a variety of reasons, including physically disconnecting the + graphics adapter, disabling the device or driver, uninstalling or upgrading + the graphics driver, or due to errors that lead to a graphics device reset. + Some of these can happen under perfectly normal circumstances as well, for + example the upgrade of the graphics driver to a newer version is a common + task that can happen at any time while a Qt application is running. Users + may very well expect applications to be able to survive this, even when the + application is actively using an API like OpenGL or Direct3D. + + Qt's own frameworks built on top of QRhi, such as, Qt Quick, can be + expected to handle and take appropriate measures when a device loss occurs. + If the data for graphics resources, such as textures and buffers, are still + available on the CPU side, such an event may not be noticeable on the + application level at all since graphics resources can seamlessly be + reinitialized then. However, applications and libraries working directly + with QRhi are expected to be prepared to check and handle device loss + situations themselves. + */ +bool QRhi::isDeviceLost() const +{ + return d->isDeviceLost(); +} + /*! \return a new graphics pipeline resource. diff --git a/src/gui/rhi/qrhi_p.h b/src/gui/rhi/qrhi_p.h index 928d1f8fa77..51e70af18ef 100644 --- a/src/gui/rhi/qrhi_p.h +++ b/src/gui/rhi/qrhi_p.h @@ -1422,6 +1422,8 @@ public: void releaseCachedResources(); + bool isDeviceLost() const; + protected: QRhi(); diff --git a/src/gui/rhi/qrhi_p_p.h b/src/gui/rhi/qrhi_p_p.h index b69757ae6d8..7c0b000c339 100644 --- a/src/gui/rhi/qrhi_p_p.h +++ b/src/gui/rhi/qrhi_p_p.h @@ -158,6 +158,7 @@ public: virtual void sendVMemStatsToProfiler() = 0; virtual void makeThreadLocalNativeContextCurrent() = 0; virtual void releaseCachedResources() = 0; + virtual bool isDeviceLost() const = 0; bool isCompressedFormat(QRhiTexture::Format format) const; void compressedFormatInfo(QRhiTexture::Format format, const QSize &size, diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index 119234035a4..2350691dc0d 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -267,6 +267,8 @@ bool QRhiD3D11::create(QRhi::Flags flags) if (FAILED(context->QueryInterface(IID_ID3DUserDefinedAnnotation, reinterpret_cast(&annotations)))) annotations = nullptr; + deviceLost = false; + nativeHandlesStruct.dev = dev; nativeHandlesStruct.context = context; @@ -487,6 +489,11 @@ void QRhiD3D11::releaseCachedResources() clearShaderCache(); } +bool QRhiD3D11::isDeviceLost() const +{ + return deviceLost; +} + QRhiRenderBuffer *QRhiD3D11::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags) { @@ -1003,8 +1010,14 @@ QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrame if (!flags.testFlag(QRhi::SkipPresent)) { const UINT presentFlags = 0; HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags); - if (FAILED(hr)) + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { + qWarning("Device loss detected in Present()"); + deviceLost = true; + return QRhi::FrameOpDeviceLost; + } else if (FAILED(hr)) { qWarning("Failed to present: %s", qPrintable(comErrorMessage(hr))); + return QRhi::FrameOpError; + } // move on to the next buffer swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QD3D11SwapChain::BUFFER_COUNT; @@ -3850,7 +3863,11 @@ bool QD3D11SwapChain::buildOrResize() const UINT count = useFlipDiscard ? BUFFER_COUNT : 1; HRESULT hr = swapChain->ResizeBuffers(count, UINT(pixelSize.width()), UINT(pixelSize.height()), colorFormat, swapChainFlags); - if (FAILED(hr)) { + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { + qWarning("Device loss detected in ResizeBuffers()"); + rhiD->deviceLost = true; + return false; + } else if (FAILED(hr)) { qWarning("Failed to resize D3D11 swapchain: %s", qPrintable(comErrorMessage(hr))); return false; } diff --git a/src/gui/rhi/qrhid3d11_p_p.h b/src/gui/rhi/qrhid3d11_p_p.h index cc4e095d10b..da7fe84b1a1 100644 --- a/src/gui/rhi/qrhid3d11_p_p.h +++ b/src/gui/rhi/qrhid3d11_p_p.h @@ -633,6 +633,7 @@ public: void sendVMemStatsToProfiler() override; void makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; + bool isDeviceLost() const override; void enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cbD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc); @@ -658,6 +659,7 @@ public: IDXGIFactory1 *dxgiFactory = nullptr; bool hasDxgi2 = false; bool supportsFlipDiscardSwapchain = false; + bool deviceLost = false; QRhiD3D11NativeHandles nativeHandlesStruct; struct { diff --git a/src/gui/rhi/qrhigles2.cpp b/src/gui/rhi/qrhigles2.cpp index 4d91ac45bdb..d408490b344 100644 --- a/src/gui/rhi/qrhigles2.cpp +++ b/src/gui/rhi/qrhigles2.cpp @@ -772,6 +772,11 @@ void QRhiGles2::releaseCachedResources() m_shaderCache.clear(); } +bool QRhiGles2::isDeviceLost() const +{ + return false; +} + QRhiRenderBuffer *QRhiGles2::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags) { diff --git a/src/gui/rhi/qrhigles2_p_p.h b/src/gui/rhi/qrhigles2_p_p.h index 877eb88d276..3664e7162b9 100644 --- a/src/gui/rhi/qrhigles2_p_p.h +++ b/src/gui/rhi/qrhigles2_p_p.h @@ -666,6 +666,7 @@ public: void sendVMemStatsToProfiler() override; void makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; + bool isDeviceLost() const override; bool ensureContext(QSurface *surface = nullptr) const; void executeDeferredReleases(); diff --git a/src/gui/rhi/qrhimetal.mm b/src/gui/rhi/qrhimetal.mm index 3bf95ad6766..770786db986 100644 --- a/src/gui/rhi/qrhimetal.mm +++ b/src/gui/rhi/qrhimetal.mm @@ -596,6 +596,11 @@ void QRhiMetal::releaseCachedResources() d->shaderCache.clear(); } +bool QRhiMetal::isDeviceLost() const +{ + return false; +} + QRhiRenderBuffer *QRhiMetal::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags) { diff --git a/src/gui/rhi/qrhimetal_p_p.h b/src/gui/rhi/qrhimetal_p_p.h index 01b0bf4f56e..633e9b8de42 100644 --- a/src/gui/rhi/qrhimetal_p_p.h +++ b/src/gui/rhi/qrhimetal_p_p.h @@ -418,6 +418,7 @@ public: void sendVMemStatsToProfiler() override; void makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; + bool isDeviceLost() const override; void executeDeferredReleases(bool forced = false); void finishActiveReadbacks(bool forced = false); diff --git a/src/gui/rhi/qrhinull.cpp b/src/gui/rhi/qrhinull.cpp index 29a3968bfc3..b58d9f5c560 100644 --- a/src/gui/rhi/qrhinull.cpp +++ b/src/gui/rhi/qrhinull.cpp @@ -179,6 +179,11 @@ void QRhiNull::releaseCachedResources() // nothing to do here } +bool QRhiNull::isDeviceLost() const +{ + return false; +} + QRhiRenderBuffer *QRhiNull::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags) { diff --git a/src/gui/rhi/qrhinull_p_p.h b/src/gui/rhi/qrhinull_p_p.h index b43f830d5e8..d6dbdbdc753 100644 --- a/src/gui/rhi/qrhinull_p_p.h +++ b/src/gui/rhi/qrhinull_p_p.h @@ -284,6 +284,7 @@ public: void sendVMemStatsToProfiler() override; void makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; + bool isDeviceLost() const override; QRhiNullNativeHandles nativeHandlesStruct; QRhiSwapChain *currentSwapChain = nullptr; diff --git a/src/gui/rhi/qrhivulkan.cpp b/src/gui/rhi/qrhivulkan.cpp index c4f298dafb1..5dd4b123293 100644 --- a/src/gui/rhi/qrhivulkan.cpp +++ b/src/gui/rhi/qrhivulkan.cpp @@ -3750,6 +3750,11 @@ void QRhiVulkan::releaseCachedResources() // nothing to do here } +bool QRhiVulkan::isDeviceLost() const +{ + return false; +} + QRhiRenderBuffer *QRhiVulkan::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags) { diff --git a/src/gui/rhi/qrhivulkan_p_p.h b/src/gui/rhi/qrhivulkan_p_p.h index 23cc80b8142..0f16c547795 100644 --- a/src/gui/rhi/qrhivulkan_p_p.h +++ b/src/gui/rhi/qrhivulkan_p_p.h @@ -713,6 +713,7 @@ public: void sendVMemStatsToProfiler() override; void makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; + bool isDeviceLost() const override; VkResult createDescriptorPool(VkDescriptorPool *pool); bool allocateDescriptorSet(VkDescriptorSetAllocateInfo *allocInfo, VkDescriptorSet *result, int *resultPoolIndex); From 8fef0ffc16ec9a88169349adfa8aafc9f375e94b Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Tue, 10 Sep 2019 16:49:58 +0200 Subject: [PATCH 23/41] rhi: vulkan: Report device lost MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typically caught in vkQueueSubmit(). The WaitIdles that can be hit upon cleanup must be guarded by !deviceLost because they inexplicably cause an infinite blocking wait when the device was already reported as lost. (with NVIDIA at least) Change-Id: I7142e2461e1aed9ee3068b2b963cdf2c678ca4e0 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhivulkan.cpp | 67 ++++++++++++++++++++---------------- src/gui/rhi/qrhivulkan_p_p.h | 1 + 2 files changed, 38 insertions(+), 30 deletions(-) diff --git a/src/gui/rhi/qrhivulkan.cpp b/src/gui/rhi/qrhivulkan.cpp index 5dd4b123293..1ed3ffc206a 100644 --- a/src/gui/rhi/qrhivulkan.cpp +++ b/src/gui/rhi/qrhivulkan.cpp @@ -589,6 +589,8 @@ bool QRhiVulkan::create(QRhi::Flags flags) vkDebugMarkerSetObjectName = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkDebugMarkerSetObjectNameEXT")); } + deviceLost = false; + nativeHandlesStruct.physDev = physDev; nativeHandlesStruct.dev = dev; nativeHandlesStruct.gfxQueueFamilyIdx = gfxQueueFamilyIdx; @@ -604,7 +606,8 @@ void QRhiVulkan::destroy() if (!df) return; - df->vkDeviceWaitIdle(dev); + if (!deviceLost) + df->vkDeviceWaitIdle(dev); executeDeferredReleases(true); finishActiveReadbacks(true); @@ -1425,7 +1428,8 @@ void QRhiVulkan::releaseSwapChainResources(QRhiSwapChain *swapChain) if (swapChainD->sc == VK_NULL_HANDLE) return; - df->vkDeviceWaitIdle(dev); + if (!deviceLost) + df->vkDeviceWaitIdle(dev); for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) { QVkSwapChain::FrameResources &frame(swapChainD->frameRes[i]); @@ -1488,15 +1492,6 @@ void QRhiVulkan::releaseSwapChainResources(QRhiSwapChain *swapChain) // NB! surface and similar must remain intact } -static inline bool checkDeviceLost(VkResult err) -{ - if (err == VK_ERROR_DEVICE_LOST) { - qWarning("Device lost"); - return true; - } - return false; -} - QRhi::FrameOpResult QRhiVulkan::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) { QVkSwapChain *swapChainD = QRHI_RES(QVkSwapChain, swapChain); @@ -1523,10 +1518,12 @@ QRhi::FrameOpResult QRhiVulkan::beginFrame(QRhiSwapChain *swapChain, QRhi::Begin } else if (err == VK_ERROR_OUT_OF_DATE_KHR) { return QRhi::FrameOpSwapChainOutOfDate; } else { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkAcquireNextImageKHR()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to acquire next swapchain image: %d", err); + } + qWarning("Failed to acquire next swapchain image: %d", err); return QRhi::FrameOpError; } } @@ -1690,10 +1687,12 @@ QRhi::FrameOpResult QRhiVulkan::endFrame(QRhiSwapChain *swapChain, QRhi::EndFram if (err == VK_ERROR_OUT_OF_DATE_KHR) { return QRhi::FrameOpSwapChainOutOfDate; } else if (err != VK_SUBOPTIMAL_KHR) { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkQueuePresentKHR()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to present: %d", err); + } + qWarning("Failed to present: %d", err); return QRhi::FrameOpError; } } @@ -1750,10 +1749,12 @@ QRhi::FrameOpResult QRhiVulkan::startPrimaryCommandBuffer(VkCommandBuffer *cb) VkResult err = df->vkAllocateCommandBuffers(dev, &cmdBufInfo, cb); if (err != VK_SUCCESS) { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkAllocateCommandBuffers()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to allocate frame command buffer: %d", err); + } + qWarning("Failed to allocate frame command buffer: %d", err); return QRhi::FrameOpError; } @@ -1763,10 +1764,12 @@ QRhi::FrameOpResult QRhiVulkan::startPrimaryCommandBuffer(VkCommandBuffer *cb) err = df->vkBeginCommandBuffer(*cb, &cmdBufBeginInfo); if (err != VK_SUCCESS) { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkBeginCommandBuffer()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to begin frame command buffer: %d", err); + } + qWarning("Failed to begin frame command buffer: %d", err); return QRhi::FrameOpError; } @@ -1778,10 +1781,12 @@ QRhi::FrameOpResult QRhiVulkan::endAndSubmitPrimaryCommandBuffer(VkCommandBuffer { VkResult err = df->vkEndCommandBuffer(cb); if (err != VK_SUCCESS) { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkEndCommandBuffer()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to end frame command buffer: %d", err); + } + qWarning("Failed to end frame command buffer: %d", err); return QRhi::FrameOpError; } @@ -1803,10 +1808,12 @@ QRhi::FrameOpResult QRhiVulkan::endAndSubmitPrimaryCommandBuffer(VkCommandBuffer err = df->vkQueueSubmit(gfxQueue, 1, &submitInfo, cmdFence); if (err != VK_SUCCESS) { - if (checkDeviceLost(err)) + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("Device loss detected in vkQueueSubmit()"); + deviceLost = true; return QRhi::FrameOpDeviceLost; - else - qWarning("Failed to submit to graphics queue: %d", err); + } + qWarning("Failed to submit to graphics queue: %d", err); return QRhi::FrameOpError; } @@ -3752,7 +3759,7 @@ void QRhiVulkan::releaseCachedResources() bool QRhiVulkan::isDeviceLost() const { - return false; + return deviceLost; } QRhiRenderBuffer *QRhiVulkan::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, diff --git a/src/gui/rhi/qrhivulkan_p_p.h b/src/gui/rhi/qrhivulkan_p_p.h index 0f16c547795..a53b3b88fba 100644 --- a/src/gui/rhi/qrhivulkan_p_p.h +++ b/src/gui/rhi/qrhivulkan_p_p.h @@ -805,6 +805,7 @@ public: VkDeviceSize ubufAlign; VkDeviceSize texbufAlign; bool hasWideLines = false; + bool deviceLost = false; bool debugMarkersAvailable = false; bool vertexAttribDivisorAvailable = false; From ef78a2e8f9bade867e43c75892353e38d48c595c Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Wed, 11 Sep 2019 11:09:05 +0200 Subject: [PATCH 24/41] rhi: Add a flag to indicate preferring a software adapter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ...if there is one and the concept is applicable in the first place. Change-Id: Iab202c1c1cdd229f4910159de4cae7ce30805ea9 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhi.cpp | 12 ++++++++++++ src/gui/rhi/qrhi_p.h | 3 ++- src/gui/rhi/qrhid3d11.cpp | 25 ++++++++++++++++++++++++- src/gui/rhi/qrhivulkan.cpp | 24 ++++++++++++++++++++++-- tests/manual/rhi/shared/examplefw.h | 7 +++++++ 5 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/gui/rhi/qrhi.cpp b/src/gui/rhi/qrhi.cpp index fbdc90bd1b6..585dc8a8fae 100644 --- a/src/gui/rhi/qrhi.cpp +++ b/src/gui/rhi/qrhi.cpp @@ -439,6 +439,18 @@ Q_LOGGING_CATEGORY(QRHI_LOG_INFO, "qt.rhi.general") visible in external GPU debugging tools will not be available and functions like QRhiCommandBuffer::debugMarkBegin() will become a no-op. Avoid enabling in production builds as it may involve a performance penalty. + + \value PreferSoftwareRenderer Indicates that backends should prefer + choosing an adapter or physical device that renders in software on the CPU. + For example, with Direct3D there is typically a "Basic Render Driver" + adapter available with \c{DXGI_ADAPTER_FLAG_SOFTWARE}. Setting this flag + requests the backend to choose that adapter over any other, as long as no + specific adapter was forced by other backend-specific means. With Vulkan + this maps to preferring physical devices with + \c{VK_PHYSICAL_DEVICE_TYPE_CPU}. When not available, or when it is not + possible to decide if an adapter/device is software-based, this flag is + ignored. It may also be ignored with graphics APIs that have no concept and + means of enumerating adapters/devices. */ /*! diff --git a/src/gui/rhi/qrhi_p.h b/src/gui/rhi/qrhi_p.h index 51e70af18ef..6f0b8e0b04b 100644 --- a/src/gui/rhi/qrhi_p.h +++ b/src/gui/rhi/qrhi_p.h @@ -1294,7 +1294,8 @@ public: enum Flag { EnableProfiling = 1 << 0, - EnableDebugMarkers = 1 << 1 + EnableDebugMarkers = 1 << 1, + PreferSoftwareRenderer = 1 << 2 }; Q_DECLARE_FLAGS(Flags, Flag) diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index 2350691dc0d..0977a3042de 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -119,6 +119,11 @@ QT_BEGIN_NAMESPACE \c{ID3D11Texture2D *}. */ +// help mingw with its ancient sdk headers +#ifndef DXGI_ADAPTER_FLAG_SOFTWARE +#define DXGI_ADAPTER_FLAG_SOFTWARE 2 +#endif + QRhiD3D11::QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importDevice) : ofr(this), deviceCurse(this) @@ -227,11 +232,29 @@ bool QRhiD3D11::create(QRhi::Flags flags) int requestedAdapterIndex = -1; if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX")) requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX"); + + if (requestedAdapterIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) { + for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) { + DXGI_ADAPTER_DESC1 desc; + adapter->GetDesc1(&desc); + adapter->Release(); + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { + requestedAdapterIndex = adapterIndex; + break; + } + } + } + for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) { DXGI_ADAPTER_DESC1 desc; adapter->GetDesc1(&desc); const QString name = QString::fromUtf16(reinterpret_cast(desc.Description)); - qCDebug(QRHI_LOG_INFO, "Adapter %d: '%s' (flags 0x%x)", adapterIndex, qPrintable(name), desc.Flags); + qCDebug(QRHI_LOG_INFO, "Adapter %d: '%s' (vendor 0x%X device 0x%X flags 0x%X)", + adapterIndex, + qPrintable(name), + desc.VendorId, + desc.DeviceId, + desc.Flags); if (!adapterToUse && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) { adapterToUse = adapter; qCDebug(QRHI_LOG_INFO, " using this adapter"); diff --git a/src/gui/rhi/qrhivulkan.cpp b/src/gui/rhi/qrhivulkan.cpp index 1ed3ffc206a..64fea37292e 100644 --- a/src/gui/rhi/qrhivulkan.cpp +++ b/src/gui/rhi/qrhivulkan.cpp @@ -388,22 +388,42 @@ bool QRhiVulkan::create(QRhi::Flags flags) qWarning("Failed to enumerate physical devices: %d", err); return false; } + int physDevIndex = -1; int requestedPhysDevIndex = -1; if (qEnvironmentVariableIsSet("QT_VK_PHYSICAL_DEVICE_INDEX")) requestedPhysDevIndex = qEnvironmentVariableIntValue("QT_VK_PHYSICAL_DEVICE_INDEX"); + + if (requestedPhysDevIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) { + for (int i = 0; i < int(physDevCount); ++i) { + f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties); + if (physDevProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { + requestedPhysDevIndex = i; + break; + } + } + } + for (int i = 0; i < int(physDevCount); ++i) { f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties); - qCDebug(QRHI_LOG_INFO, "Physical device %d: '%s' %d.%d.%d", i, + qCDebug(QRHI_LOG_INFO, "Physical device %d: '%s' %d.%d.%d (api %d.%d.%d vendor 0x%X device 0x%X type %d)", + i, physDevProperties.deviceName, VK_VERSION_MAJOR(physDevProperties.driverVersion), VK_VERSION_MINOR(physDevProperties.driverVersion), - VK_VERSION_PATCH(physDevProperties.driverVersion)); + VK_VERSION_PATCH(physDevProperties.driverVersion), + VK_VERSION_MAJOR(physDevProperties.apiVersion), + VK_VERSION_MINOR(physDevProperties.apiVersion), + VK_VERSION_PATCH(physDevProperties.apiVersion), + physDevProperties.vendorID, + physDevProperties.deviceID, + physDevProperties.deviceType); if (physDevIndex < 0 && (requestedPhysDevIndex < 0 || requestedPhysDevIndex == int(i))) { physDevIndex = i; qCDebug(QRHI_LOG_INFO, " using this physical device"); } } + if (physDevIndex < 0) { qWarning("No matching physical device"); return false; diff --git a/tests/manual/rhi/shared/examplefw.h b/tests/manual/rhi/shared/examplefw.h index 8afacc074a2..4bd087473bf 100644 --- a/tests/manual/rhi/shared/examplefw.h +++ b/tests/manual/rhi/shared/examplefw.h @@ -473,6 +473,10 @@ int main(int argc, char **argv) "(generate a device reset every frames when on D3D11)"), QLatin1String("count")); cmdLineParser.addOption(tdrOption); + // Allow testing preferring the software adapter (D3D). + QCommandLineOption swOption(QLatin1String("software"), QLatin1String("Prefer a software renderer when choosing the adapter. " + "Only applicable with some APIs and platforms.")); + cmdLineParser.addOption(swOption); cmdLineParser.process(app); if (cmdLineParser.isSet(nullOption)) @@ -534,6 +538,9 @@ int main(int argc, char **argv) if (cmdLineParser.isSet(tdrOption)) framesUntilTdr = cmdLineParser.value(tdrOption).toInt(); + if (cmdLineParser.isSet(swOption)) + rhiFlags |= QRhi::PreferSoftwareRenderer; + // Create and show the window. Window w; #if QT_CONFIG(vulkan) From 3d7207414b07104c1ea03ef341301a7390d7b0ad Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Mon, 9 Sep 2019 15:48:09 +0200 Subject: [PATCH 25/41] rhi: metal: Configure the layer's opaque property as appropriate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task-number: QTBUG-78089 Change-Id: I6cd95e24d38562cf1931c107bb6b719e340583a8 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhimetal.mm | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/gui/rhi/qrhimetal.mm b/src/gui/rhi/qrhimetal.mm index 770786db986..2d85c86bf00 100644 --- a/src/gui/rhi/qrhimetal.mm +++ b/src/gui/rhi/qrhimetal.mm @@ -3596,6 +3596,18 @@ bool QMetalSwapChain::buildOrResize() } #endif + if (m_flags.testFlag(SurfaceHasPreMulAlpha)) { + d->layer.opaque = NO; + } else if (m_flags.testFlag(SurfaceHasNonPreMulAlpha)) { + // The CoreAnimation compositor is said to expect premultiplied alpha, + // so this is then wrong when it comes to the blending operations but + // there's nothing we can do. Fortunately Qt Quick always outputs + // premultiplied alpha so it is not a problem there. + d->layer.opaque = NO; + } else { + d->layer.opaque = YES; + } + m_currentPixelSize = surfacePixelSize(); pixelSize = m_currentPixelSize; From 16da0b2cf8b6b344ae9dc37f46acec643c72fc28 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Wed, 11 Sep 2019 19:41:49 +0200 Subject: [PATCH 26/41] QTranslator doc: use QCoreApplication::installTranslator() The example snippet was using app.installTranslator() even installTranslator() is a static function. And since app is a QApplication instead a QCoreApplication this could lead to the assumption that a QTranslator can only be used for gui applications. Therefore use the correct static invocation QCoreApplication::installTranslator(). Change-Id: Ia3ce00f25230c2fe2bdc159ec14c88c961924651 Reviewed-by: Paul Wicking Reviewed-by: Friedemann Kleint --- src/corelib/doc/snippets/hellotrmain.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/doc/snippets/hellotrmain.cpp b/src/corelib/doc/snippets/hellotrmain.cpp index 2fab919a47a..721a83240b8 100644 --- a/src/corelib/doc/snippets/hellotrmain.cpp +++ b/src/corelib/doc/snippets/hellotrmain.cpp @@ -56,13 +56,13 @@ int main(int argc, char *argv[]) QTranslator translator; // look up e.g. :/translations/myapp_de.qm if (translator.load(QLocale(), QLatin1String("myapp"), QLatin1String("_"), QLatin1String(":/translations"))) - app.installTranslator(&translator); + QCoreApplication::installTranslator(&translator); QPushButton hello(QCoreApplication::translate("main", "Hello world!")); hello.resize(100, 30); hello.show(); - return app.exec(); + return QCoreApplication::exec(); } //! [0] From 117175a2f2ecab990f65eefd32b42be22f9aa3ce Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Wed, 11 Sep 2019 17:56:14 +0200 Subject: [PATCH 27/41] macOS dark mode: set the link color MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: QTBUG-71740 Change-Id: I49f49338c7f3a28845de63c2a6bf2dc8495dd108 Reviewed-by: Tor Arne Vestbø --- src/plugins/platforms/cocoa/qcocoasystemsettings.mm | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm index 9b6dc94d33d..cb25bd7d810 100644 --- a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm +++ b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2017 The Qt Company Ltd. +** Copyright (C) 2019 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. @@ -52,6 +52,8 @@ @property (class, strong, readonly) NSColor *unemphasizedSelectedTextColor NS_AVAILABLE_MAC(10_14); @property (class, strong, readonly) NSColor *unemphasizedSelectedContentBackgroundColor NS_AVAILABLE_MAC(10_14); @property (class, strong, readonly) NSArray *alternatingContentBackgroundColors NS_AVAILABLE_MAC(10_14); +// Missing from non-Mojave SDKs, even if introduced in 10.10 +@property (class, strong, readonly) NSColor *linkColor NS_AVAILABLE_MAC(10_10); @end #endif @@ -111,6 +113,8 @@ QPalette * qt_mac_createSystemPalette() palette->setBrush(QPalette::ToolTipBase, qt_mac_toQBrush([NSColor controlColor])); + palette->setColor(QPalette::Normal, QPalette::Link, qt_mac_toQColor([NSColor linkColor])); + return palette; } From 351c738fc4586bf354c9363fb78e190bdfca4617 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 12 Sep 2019 11:07:31 +0200 Subject: [PATCH 28/41] QPointer: some simplifications - don't write explicit meta functions, use std::conditional - = default the default ctor The class is already not trivially-copyable, so making the default ctor trivial doesn't change the ABI. Change-Id: I8e35bbbb35973c9ff8fc48dfbfc10061de4bfd30 Reviewed-by: Olivier Goffart (Woboq GmbH) --- src/corelib/kernel/qpointer.h | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/corelib/kernel/qpointer.h b/src/corelib/kernel/qpointer.h index 7052bcf0d44..5efdb0b395d 100644 --- a/src/corelib/kernel/qpointer.h +++ b/src/corelib/kernel/qpointer.h @@ -54,20 +54,11 @@ class QPointer { Q_STATIC_ASSERT_X(!std::is_pointer::value, "QPointer's template type must not be a pointer type"); - template - struct TypeSelector - { - typedef QObject Type; - }; - template - struct TypeSelector - { - typedef const QObject Type; - }; - typedef typename TypeSelector::Type QObjectType; + using QObjectType = + typename std::conditional::value, const QObject, QObject>::type; QWeakPointer wp; public: - inline QPointer() { } + QPointer() = default; inline QPointer(T *p) : wp(p, true) { } // compiler-generated copy/move ctor/assignment operators are fine! // compiler-generated dtor is fine! From 68b30a23a8ee66de4da62dcddfe2072c01945c24 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Tue, 10 Sep 2019 19:27:43 +0200 Subject: [PATCH 29/41] Port QReadWriteLock from QMutexLocker to qt_unique_lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Most of these are unique_locks because they call QWaitCondition::wait() and it doesn't feel right to use qt_scoped_lock if the lock is dropped within the scope. Change-Id: I506eede63008dad135c21112e578da4f7684e528 Reviewed-by: Mårten Nordheim --- src/corelib/thread/qreadwritelock.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/corelib/thread/qreadwritelock.cpp b/src/corelib/thread/qreadwritelock.cpp index 30e9b95a525..14654986a0c 100644 --- a/src/corelib/thread/qreadwritelock.cpp +++ b/src/corelib/thread/qreadwritelock.cpp @@ -48,6 +48,7 @@ #include "qreadwritelock_p.h" #include "qelapsedtimer.h" #include "private/qfreelist_p.h" +#include "private/qlocking_p.h" QT_BEGIN_NAMESPACE @@ -262,7 +263,7 @@ bool QReadWriteLock::tryLockForRead(int timeout) if (d->recursive) return d->recursiveLockForRead(timeout); - QMutexLocker lock(&d->mutex); + auto lock = qt_unique_lock(d->mutex); if (d != d_ptr.loadRelaxed()) { // d_ptr has changed: this QReadWriteLock was unlocked before we had // time to lock d->mutex. @@ -369,7 +370,7 @@ bool QReadWriteLock::tryLockForWrite(int timeout) if (d->recursive) return d->recursiveLockForWrite(timeout); - QMutexLocker lock(&d->mutex); + auto lock = qt_unique_lock(d->mutex); if (d != d_ptr.loadRelaxed()) { // The mutex was unlocked before we had time to lock the mutex. // We are holding to a mutex within a QReadWriteLockPrivate that is already released @@ -418,7 +419,7 @@ void QReadWriteLock::unlock() return; } - QMutexLocker locker(&d->mutex); + const auto lock = qt_scoped_lock(d->mutex); if (d->writerCount) { Q_ASSERT(d->writerCount == 1); Q_ASSERT(d->readerCount == 0); @@ -536,7 +537,7 @@ void QReadWriteLockPrivate::unlock() bool QReadWriteLockPrivate::recursiveLockForRead(int timeout) { Q_ASSERT(recursive); - QMutexLocker lock(&mutex); + auto lock = qt_unique_lock(mutex); Qt::HANDLE self = QThread::currentThreadId(); @@ -556,7 +557,7 @@ bool QReadWriteLockPrivate::recursiveLockForRead(int timeout) bool QReadWriteLockPrivate::recursiveLockForWrite(int timeout) { Q_ASSERT(recursive); - QMutexLocker lock(&mutex); + auto lock = qt_unique_lock(mutex); Qt::HANDLE self = QThread::currentThreadId(); if (currentWriter == self) { @@ -574,7 +575,7 @@ bool QReadWriteLockPrivate::recursiveLockForWrite(int timeout) void QReadWriteLockPrivate::recursiveUnlock() { Q_ASSERT(recursive); - QMutexLocker lock(&mutex); + auto lock = qt_unique_lock(mutex); Qt::HANDLE self = QThread::currentThreadId(); if (self == currentWriter) { From 319c4786036b5f45fc95c683cef5cf5ba2ce2a6d Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Fri, 23 Aug 2019 15:05:32 +0200 Subject: [PATCH 30/41] QReadWriteLock: replace (QWaitCondition, QMutex) with std::(condition_variable, mutex) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It turns out that QWaitCondition is a std::condition_variable_any. The _any variant works with any mutex type, but requires a native mutex for the native condition variable. So, QWaitCondition and std::condition_variable_any both require two different mutexes: the one the user passes in, and an internal one. std::condition_variable, however, only works with std::mutex, and since both are backed by the native API, condition_variable can use the mutex passed in by the user instead of having to use an internal one. So, port from 2 × QWaitCondition + QMutex (2 × native cond + 2 × native mutex + Qt mutex) to std::condition_variable + std::mutex (2 × native cond + native mutex), shaving the overhead of two additional mutexes (one Qt, one native) as well as the memory allocation performed by QWaitCondition (for its Private). Speeds up the writeOnly case by ~1/8th: PASS : tst_QReadWriteLock::writeOnly(QReadWriteLock) RESULT : tst_QReadWriteLock::writeOnly():"QReadWriteLock": - 39,703 msecs per iteration (total: 39,703, iterations: 1) + 34,950 msecs per iteration (total: 34,950, iterations: 1) Change-Id: I196cb13a27242fc1cb99723dfab5b2e5f8522143 Reviewed-by: Edward Welbourne Reviewed-by: Mårten Nordheim Reviewed-by: Olivier Goffart (Woboq GmbH) Reviewed-by: Volker Hilsheimer --- src/corelib/thread/qreadwritelock.cpp | 37 +++++++++++++++------------ src/corelib/thread/qreadwritelock_p.h | 14 +++++----- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/src/corelib/thread/qreadwritelock.cpp b/src/corelib/thread/qreadwritelock.cpp index 14654986a0c..5aba05c1b97 100644 --- a/src/corelib/thread/qreadwritelock.cpp +++ b/src/corelib/thread/qreadwritelock.cpp @@ -50,6 +50,8 @@ #include "private/qfreelist_p.h" #include "private/qlocking_p.h" +#include + QT_BEGIN_NAMESPACE /* @@ -65,6 +67,9 @@ QT_BEGIN_NAMESPACE */ namespace { + +using ms = std::chrono::milliseconds; + enum { StateMask = 0x3, StateLockedForRead = 0x1, @@ -274,7 +279,7 @@ bool QReadWriteLock::tryLockForRead(int timeout) d = d_ptr.loadAcquire(); continue; } - return d->lockForRead(timeout); + return d->lockForRead(lock, timeout); } } @@ -378,7 +383,7 @@ bool QReadWriteLock::tryLockForWrite(int timeout) d = d_ptr.loadAcquire(); continue; } - return d->lockForWrite(timeout); + return d->lockForWrite(lock, timeout); } } @@ -461,9 +466,9 @@ QReadWriteLock::StateForWaitCondition QReadWriteLock::stateForWaitCondition() co } -bool QReadWriteLockPrivate::lockForRead(int timeout) +bool QReadWriteLockPrivate::lockForRead(std::unique_lock &lock, int timeout) { - Q_ASSERT(!mutex.tryLock()); // mutex must be locked when entering this function + Q_ASSERT(!mutex.try_lock()); // mutex must be locked when entering this function QElapsedTimer t; if (timeout > 0) @@ -477,10 +482,10 @@ bool QReadWriteLockPrivate::lockForRead(int timeout) if (elapsed > timeout) return false; waitingReaders++; - readerCond.wait(&mutex, timeout - elapsed); + readerCond.wait_for(lock, ms{timeout - elapsed}); } else { waitingReaders++; - readerCond.wait(&mutex); + readerCond.wait(lock); } waitingReaders--; } @@ -489,9 +494,9 @@ bool QReadWriteLockPrivate::lockForRead(int timeout) return true; } -bool QReadWriteLockPrivate::lockForWrite(int timeout) +bool QReadWriteLockPrivate::lockForWrite(std::unique_lock &lock, int timeout) { - Q_ASSERT(!mutex.tryLock()); // mutex must be locked when entering this function + Q_ASSERT(!mutex.try_lock()); // mutex must be locked when entering this function QElapsedTimer t; if (timeout > 0) @@ -506,15 +511,15 @@ bool QReadWriteLockPrivate::lockForWrite(int timeout) if (waitingReaders && !waitingWriters && !writerCount) { // We timed out and now there is no more writers or waiting writers, but some // readers were queueud (probably because of us). Wake the waiting readers. - readerCond.wakeAll(); + readerCond.notify_all(); } return false; } waitingWriters++; - writerCond.wait(&mutex, timeout - elapsed); + writerCond.wait_for(lock, ms{timeout - elapsed}); } else { waitingWriters++; - writerCond.wait(&mutex); + writerCond.wait(lock); } waitingWriters--; } @@ -527,11 +532,11 @@ bool QReadWriteLockPrivate::lockForWrite(int timeout) void QReadWriteLockPrivate::unlock() { - Q_ASSERT(!mutex.tryLock()); // mutex must be locked when entering this function + Q_ASSERT(!mutex.try_lock()); // mutex must be locked when entering this function if (waitingWriters) - writerCond.wakeOne(); + writerCond.notify_one(); else if (waitingReaders) - readerCond.wakeAll(); + readerCond.notify_all(); } bool QReadWriteLockPrivate::recursiveLockForRead(int timeout) @@ -547,7 +552,7 @@ bool QReadWriteLockPrivate::recursiveLockForRead(int timeout) return true; } - if (!lockForRead(timeout)) + if (!lockForRead(lock, timeout)) return false; currentReaders.insert(self, 1); @@ -565,7 +570,7 @@ bool QReadWriteLockPrivate::recursiveLockForWrite(int timeout) return true; } - if (!lockForWrite(timeout)) + if (!lockForWrite(lock, timeout)) return false; currentWriter = self; diff --git a/src/corelib/thread/qreadwritelock_p.h b/src/corelib/thread/qreadwritelock_p.h index a4d002b7f2a..b2e782f9eeb 100644 --- a/src/corelib/thread/qreadwritelock_p.h +++ b/src/corelib/thread/qreadwritelock_p.h @@ -54,7 +54,9 @@ #include #include -#include + +#include +#include QT_REQUIRE_CONFIG(thread); @@ -66,9 +68,9 @@ public: explicit QReadWriteLockPrivate(bool isRecursive = false) : recursive(isRecursive) {} - QMutex mutex; - QWaitCondition writerCond; - QWaitCondition readerCond; + std::mutex mutex; + std::condition_variable writerCond; + std::condition_variable readerCond; int readerCount = 0; int writerCount = 0; int waitingReaders = 0; @@ -76,8 +78,8 @@ public: const bool recursive; //Called with the mutex locked - bool lockForWrite(int timeout); - bool lockForRead(int timeout); + bool lockForWrite(std::unique_lock &lock, int timeout); + bool lockForRead(std::unique_lock &lock, int timeout); void unlock(); //memory management From 6eaa1d07e1e86f1535b8294645f75972dc69184b Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 12 Sep 2019 09:24:29 +0200 Subject: [PATCH 31/41] Eliminate the last QList in QtBase production code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QList is horribly inefficient™ (on 32-bit platforms). Fix by using a QVector instead. Change-Id: Id85cb71404f329049c3e9997e51113035569e1b4 Reviewed-by: Friedemann Kleint --- src/plugins/platforms/eglfs/api/qeglfscursor_p.h | 4 +++- .../eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmcursor.h | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/plugins/platforms/eglfs/api/qeglfscursor_p.h b/src/plugins/platforms/eglfs/api/qeglfscursor_p.h index 89c2e89f584..8768f9dd8c2 100644 --- a/src/plugins/platforms/eglfs/api/qeglfscursor_p.h +++ b/src/plugins/platforms/eglfs/api/qeglfscursor_p.h @@ -59,6 +59,8 @@ #include #include +#include + QT_BEGIN_NAMESPACE class QOpenGLShaderProgram; @@ -143,7 +145,7 @@ private: int cursorsPerRow; int width, height; // width and height of the atlas int cursorWidth, cursorHeight; // width and height of cursors inside the atlas - QList hotSpots; + QVector hotSpots; QImage image; // valid until it's uploaded } m_cursorAtlas; diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmcursor.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmcursor.h index c96dd585d3f..d47b579238a 100644 --- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmcursor.h +++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmcursor.h @@ -41,7 +41,7 @@ #define QEGLFSKMSGBMCURSOR_H #include -#include +#include #include #include @@ -110,7 +110,7 @@ private: int cursorsPerRow; int width, height; // width and height of the atlas int cursorWidth, cursorHeight; // width and height of cursors inside the atlas - QList hotSpots; + QVector hotSpots; QImage image; } m_cursorAtlas; }; From 29e40c1f6f630803747ca615f99d2813df57fc52 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 4 Sep 2019 23:49:09 +0200 Subject: [PATCH 32/41] QWinRTUiaValueProvider: optimize SetValue() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The code followed a pattern used elsewhere whereby a return value is transmitted out of a task executed on a separate thread by way of shared ownership of the value using QSharedPointer. In the present case, however, the pattern was applied to an argument of the task, not its return value, so remove all the sharing machinery and just copy the argument (a QString) into the task (a lambda). Change-Id: Ib997322ed70201781b6012c7e4f945b124b05868 Reviewed-by: Edward Welbourne Reviewed-by: Mårten Nordheim --- .../winrt/uiautomation/qwinrtuiavalueprovider.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/plugins/platforms/winrt/uiautomation/qwinrtuiavalueprovider.cpp b/src/plugins/platforms/winrt/uiautomation/qwinrtuiavalueprovider.cpp index 21389b74d2f..255d8ee49ea 100644 --- a/src/plugins/platforms/winrt/uiautomation/qwinrtuiavalueprovider.cpp +++ b/src/plugins/platforms/winrt/uiautomation/qwinrtuiavalueprovider.cpp @@ -96,24 +96,22 @@ HRESULT STDMETHODCALLTYPE QWinRTUiaValueProvider::SetValue(HSTRING value) qCDebug(lcQpaUiAutomation) << __FUNCTION__; auto accid = id(); - auto tmpValue = QSharedPointer(new QString); - auto ptrValue = new QSharedPointer(tmpValue); - *tmpValue = hStrToQStr(value); + QString tmpValue = hStrToQStr(value); - QEventDispatcherWinRT::runOnMainThread([accid, ptrValue]() { + QEventDispatcherWinRT::runOnMainThread([accid, tmpValue]() { if (QAccessibleInterface *accessible = accessibleForId(accid)) { // First sets the value as a text. - accessible->setText(QAccessible::Value, **ptrValue); + accessible->setText(QAccessible::Value, tmpValue); // Then, if the control supports the value interface (range value) // and the supplied text can be converted to a number, and that number // lies within the min/max limits, sets it as the control's current (numeric) value. if (QAccessibleValueInterface *valueInterface = accessible->valueInterface()) { bool ok = false; - double numval = (*ptrValue)->toDouble(&ok); + double numval = tmpValue.toDouble(&ok); if (ok) { double minimum = valueInterface->minimumValue().toDouble(); double maximum = valueInterface->maximumValue().toDouble(); @@ -124,7 +122,6 @@ HRESULT STDMETHODCALLTYPE QWinRTUiaValueProvider::SetValue(HSTRING value) } } QWinRTUiaMetadataCache::instance()->load(accid); - delete ptrValue; return S_OK; }, 0); From af1c3bf884c896e42fd2a8b7847ae86743b2c4ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Thu, 5 Sep 2019 12:22:13 +0200 Subject: [PATCH 33/41] qnetconmonitor_win: Mark destructors virtual After these two classes were no longer marked final clang started complaining because their dtor is not marked virtual. Amends 9dc594b2bf3572aa5df3ec3ad2b9842c96e8290d Change-Id: I42b78c0b444935d3e0cb4d476d3881fd5fb5c3cb Reviewed-by: Timur Pocheptsov Reviewed-by: Friedemann Kleint --- src/network/kernel/qnetconmonitor_win.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/network/kernel/qnetconmonitor_win.cpp b/src/network/kernel/qnetconmonitor_win.cpp index a010df8e3ac..1566e7f914c 100644 --- a/src/network/kernel/qnetconmonitor_win.cpp +++ b/src/network/kernel/qnetconmonitor_win.cpp @@ -103,7 +103,7 @@ class QNetworkConnectionEvents : public INetworkConnectionEvents { public: QNetworkConnectionEvents(QNetworkConnectionMonitorPrivate *monitor); - ~QNetworkConnectionEvents(); + virtual ~QNetworkConnectionEvents(); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override; @@ -471,7 +471,7 @@ class QNetworkListManagerEvents : public INetworkListManagerEvents { public: QNetworkListManagerEvents(QNetworkStatusMonitorPrivate *monitor); - ~QNetworkListManagerEvents(); + virtual ~QNetworkListManagerEvents(); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override; From 39b0a6f152d70eff50fde978c074a6a0860e6394 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Thu, 12 Sep 2019 16:09:36 +0200 Subject: [PATCH 34/41] rhi: gl: Pick up context loss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ...and change the return value of makeThreadLocalNativeContextCurrent() to a bool since we expect this to mirror QOpenGLContext::makeCurrent(). Change-Id: I339507152e461fe28fcf7fe777165e6d0072f055 Reviewed-by: Christian Strømme --- src/gui/rhi/qrhi.cpp | 43 +++++++++++++++++++++++++++++++----- src/gui/rhi/qrhi_p.h | 2 +- src/gui/rhi/qrhi_p_p.h | 2 +- src/gui/rhi/qrhid3d11.cpp | 5 +++-- src/gui/rhi/qrhid3d11_p_p.h | 2 +- src/gui/rhi/qrhigles2.cpp | 29 +++++++++++++++--------- src/gui/rhi/qrhigles2_p_p.h | 3 ++- src/gui/rhi/qrhimetal.mm | 5 +++-- src/gui/rhi/qrhimetal_p_p.h | 2 +- src/gui/rhi/qrhinull.cpp | 5 +++-- src/gui/rhi/qrhinull_p_p.h | 2 +- src/gui/rhi/qrhivulkan.cpp | 5 +++-- src/gui/rhi/qrhivulkan_p_p.h | 2 +- 13 files changed, 76 insertions(+), 31 deletions(-) diff --git a/src/gui/rhi/qrhi.cpp b/src/gui/rhi/qrhi.cpp index 585dc8a8fae..858be0159b3 100644 --- a/src/gui/rhi/qrhi.cpp +++ b/src/gui/rhi/qrhi.cpp @@ -468,7 +468,7 @@ Q_LOGGING_CATEGORY(QRHI_LOG_INFO, "qt.rhi.general") \value FrameOpDeviceLost The graphics device was lost. This can be recoverable by attempting to repeat the operation (such as, beginFrame()) after releasing and reinitializing all objects backed by native graphics - resources. + resources. See isDeviceLost(). */ /*! @@ -5022,10 +5022,17 @@ const QRhiNativeHandles *QRhi::nativeHandles() has to ensure external OpenGL code provided by the application can still run like it did before with direct usage of OpenGL, as long as the QRhi is using the OpenGL backend. + + \return false when failed, similarly to QOpenGLContext::makeCurrent(). When + the operation failed, isDeviceLost() can be called to determine if there + was a loss of context situation. Such a check is equivalent to checking via + QOpenGLContext::isValid(). + + \sa QOpenGLContext::makeCurrent(), QOpenGLContext::isValid() */ -void QRhi::makeThreadLocalNativeContextCurrent() +bool QRhi::makeThreadLocalNativeContextCurrent() { - d->makeThreadLocalNativeContextCurrent(); + return d->makeThreadLocalNativeContextCurrent(); } /*! @@ -5092,6 +5099,12 @@ void QRhi::releaseCachedResources() reinitialized then. However, applications and libraries working directly with QRhi are expected to be prepared to check and handle device loss situations themselves. + + \note With OpenGL, applications may need to opt-in to context reset + notifications by setting QSurfaceFormat::ResetNotification on the + QOpenGLContext. This is typically done by enabling the flag in + QRhiGles2InitParams::format. Keep in mind however that some systems may + generate context resets situations even when this flag is not set. */ bool QRhi::isDeviceLost() const { @@ -5259,7 +5272,17 @@ QRhiSwapChain *QRhi::newSwapChain() \endlist - \sa endFrame(), beginOffscreenFrame() + \return QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult + value on failure. Some of these should be treated as soft, "try again + later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned, + the swapchain is to be resized or updated by calling + QRhiSwapChain::buildOrResize(). The application should then attempt to + generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is + lost but this may also be recoverable by releasing all resources, including + the QRhi itself, and then recreating all resources. See isDeviceLost() for + further discussion. + + \sa endFrame(), beginOffscreenFrame(), isDeviceLost() */ QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain, BeginFrameFlags flags) { @@ -5284,7 +5307,17 @@ QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain, BeginFrameFlags f Passing QRhi::SkipPresent skips queuing the Present command or calling swapBuffers. - \sa beginFrame() + \return QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult + value on failure. Some of these should be treated as soft, "try again + later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned, + the swapchain is to be resized or updated by calling + QRhiSwapChain::buildOrResize(). The application should then attempt to + generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is + lost but this may also be recoverable by releasing all resources, including + the QRhi itself, and then recreating all resources. See isDeviceLost() for + further discussion. + + \sa beginFrame(), isDeviceLost() */ QRhi::FrameOpResult QRhi::endFrame(QRhiSwapChain *swapChain, EndFrameFlags flags) { diff --git a/src/gui/rhi/qrhi_p.h b/src/gui/rhi/qrhi_p.h index 6f0b8e0b04b..c73f03cf72f 100644 --- a/src/gui/rhi/qrhi_p.h +++ b/src/gui/rhi/qrhi_p.h @@ -1414,7 +1414,7 @@ public: int resourceLimit(ResourceLimit limit) const; const QRhiNativeHandles *nativeHandles(); - void makeThreadLocalNativeContextCurrent(); + bool makeThreadLocalNativeContextCurrent(); QRhiProfiler *profiler(); diff --git a/src/gui/rhi/qrhi_p_p.h b/src/gui/rhi/qrhi_p_p.h index 7c0b000c339..63f27b6de42 100644 --- a/src/gui/rhi/qrhi_p_p.h +++ b/src/gui/rhi/qrhi_p_p.h @@ -156,7 +156,7 @@ public: virtual int resourceLimit(QRhi::ResourceLimit limit) const = 0; virtual const QRhiNativeHandles *nativeHandles() = 0; virtual void sendVMemStatsToProfiler() = 0; - virtual void makeThreadLocalNativeContextCurrent() = 0; + virtual bool makeThreadLocalNativeContextCurrent() = 0; virtual void releaseCachedResources() = 0; virtual bool isDeviceLost() const = 0; diff --git a/src/gui/rhi/qrhid3d11.cpp b/src/gui/rhi/qrhid3d11.cpp index 0977a3042de..1d2f3cfa806 100644 --- a/src/gui/rhi/qrhid3d11.cpp +++ b/src/gui/rhi/qrhid3d11.cpp @@ -502,9 +502,10 @@ void QRhiD3D11::sendVMemStatsToProfiler() // nothing to do here } -void QRhiD3D11::makeThreadLocalNativeContextCurrent() +bool QRhiD3D11::makeThreadLocalNativeContextCurrent() { - // nothing to do here + // not applicable + return false; } void QRhiD3D11::releaseCachedResources() diff --git a/src/gui/rhi/qrhid3d11_p_p.h b/src/gui/rhi/qrhid3d11_p_p.h index da7fe84b1a1..cf4808510ca 100644 --- a/src/gui/rhi/qrhid3d11_p_p.h +++ b/src/gui/rhi/qrhid3d11_p_p.h @@ -631,7 +631,7 @@ public: int resourceLimit(QRhi::ResourceLimit limit) const override; const QRhiNativeHandles *nativeHandles() override; void sendVMemStatsToProfiler() override; - void makeThreadLocalNativeContextCurrent() override; + bool makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; bool isDeviceLost() const override; diff --git a/src/gui/rhi/qrhigles2.cpp b/src/gui/rhi/qrhigles2.cpp index d408490b344..2d51d892e32 100644 --- a/src/gui/rhi/qrhigles2.cpp +++ b/src/gui/rhi/qrhigles2.cpp @@ -371,7 +371,12 @@ bool QRhiGles2::ensureContext(QSurface *surface) const return true; if (!ctx->makeCurrent(surface)) { - qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen."); + if (ctx->isValid()) { + qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen."); + } else { + qWarning("QRhiGles2: Context is lost."); + contextLost = true; + } return false; } @@ -491,6 +496,8 @@ bool QRhiGles2::create(QRhi::Flags flags) nativeHandlesStruct.context = ctx; + contextLost = false; + return true; } @@ -753,12 +760,12 @@ void QRhiGles2::sendVMemStatsToProfiler() // nothing to do here } -void QRhiGles2::makeThreadLocalNativeContextCurrent() +bool QRhiGles2::makeThreadLocalNativeContextCurrent() { if (inFrame && !ofr.active) - ensureContext(currentSwapChain->surface); + return ensureContext(currentSwapChain->surface); else - ensureContext(); + return ensureContext(); } void QRhiGles2::releaseCachedResources() @@ -774,7 +781,7 @@ void QRhiGles2::releaseCachedResources() bool QRhiGles2::isDeviceLost() const { - return false; + return contextLost; } QRhiRenderBuffer *QRhiGles2::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, @@ -1161,7 +1168,7 @@ QRhi::FrameOpResult QRhiGles2::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginF QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain); if (!ensureContext(swapChainD->surface)) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; currentSwapChain = swapChainD; @@ -1184,7 +1191,7 @@ QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrame addBoundaryCommand(&swapChainD->cb, QGles2CommandBuffer::Command::EndFrame); if (!ensureContext(swapChainD->surface)) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; executeCommandBuffer(&swapChainD->cb); @@ -1208,7 +1215,7 @@ QRhi::FrameOpResult QRhiGles2::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi: { Q_UNUSED(flags); if (!ensureContext()) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; ofr.active = true; @@ -1230,7 +1237,7 @@ QRhi::FrameOpResult QRhiGles2::endOffscreenFrame(QRhi::EndFrameFlags flags) addBoundaryCommand(&ofr.cbWrapper, QGles2CommandBuffer::Command::EndFrame); if (!ensureContext()) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; executeCommandBuffer(&ofr.cbWrapper); @@ -1244,14 +1251,14 @@ QRhi::FrameOpResult QRhiGles2::finish() Q_ASSERT(!currentSwapChain); Q_ASSERT(ofr.cbWrapper.recordingPass == QGles2CommandBuffer::NoPass); if (!ensureContext()) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; executeCommandBuffer(&ofr.cbWrapper); ofr.cbWrapper.resetCommands(); } else { Q_ASSERT(currentSwapChain); Q_ASSERT(currentSwapChain->cb.recordingPass == QGles2CommandBuffer::NoPass); if (!ensureContext(currentSwapChain->surface)) - return QRhi::FrameOpError; + return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError; executeCommandBuffer(¤tSwapChain->cb); currentSwapChain->cb.resetCommands(); } diff --git a/src/gui/rhi/qrhigles2_p_p.h b/src/gui/rhi/qrhigles2_p_p.h index 3664e7162b9..e7bcb626b6d 100644 --- a/src/gui/rhi/qrhigles2_p_p.h +++ b/src/gui/rhi/qrhigles2_p_p.h @@ -664,7 +664,7 @@ public: int resourceLimit(QRhi::ResourceLimit limit) const override; const QRhiNativeHandles *nativeHandles() override; void sendVMemStatsToProfiler() override; - void makeThreadLocalNativeContextCurrent() override; + bool makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; bool isDeviceLost() const override; @@ -770,6 +770,7 @@ public: QVector supportedCompressedFormats; mutable QVector supportedSampleCountList; QRhiGles2NativeHandles nativeHandlesStruct; + mutable bool contextLost = false; struct DeferredReleaseEntry { enum Type { diff --git a/src/gui/rhi/qrhimetal.mm b/src/gui/rhi/qrhimetal.mm index 2d85c86bf00..0b1ab72c2cc 100644 --- a/src/gui/rhi/qrhimetal.mm +++ b/src/gui/rhi/qrhimetal.mm @@ -583,9 +583,10 @@ void QRhiMetal::sendVMemStatsToProfiler() // nothing to do here } -void QRhiMetal::makeThreadLocalNativeContextCurrent() +bool QRhiMetal::makeThreadLocalNativeContextCurrent() { - // nothing to do here + // not applicable + return false; } void QRhiMetal::releaseCachedResources() diff --git a/src/gui/rhi/qrhimetal_p_p.h b/src/gui/rhi/qrhimetal_p_p.h index 633e9b8de42..a08f56072a0 100644 --- a/src/gui/rhi/qrhimetal_p_p.h +++ b/src/gui/rhi/qrhimetal_p_p.h @@ -416,7 +416,7 @@ public: int resourceLimit(QRhi::ResourceLimit limit) const override; const QRhiNativeHandles *nativeHandles() override; void sendVMemStatsToProfiler() override; - void makeThreadLocalNativeContextCurrent() override; + bool makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; bool isDeviceLost() const override; diff --git a/src/gui/rhi/qrhinull.cpp b/src/gui/rhi/qrhinull.cpp index b58d9f5c560..60d620813bb 100644 --- a/src/gui/rhi/qrhinull.cpp +++ b/src/gui/rhi/qrhinull.cpp @@ -169,9 +169,10 @@ void QRhiNull::sendVMemStatsToProfiler() // nothing to do here } -void QRhiNull::makeThreadLocalNativeContextCurrent() +bool QRhiNull::makeThreadLocalNativeContextCurrent() { - // nothing to do here + // not applicable + return false; } void QRhiNull::releaseCachedResources() diff --git a/src/gui/rhi/qrhinull_p_p.h b/src/gui/rhi/qrhinull_p_p.h index d6dbdbdc753..ee301d247bb 100644 --- a/src/gui/rhi/qrhinull_p_p.h +++ b/src/gui/rhi/qrhinull_p_p.h @@ -282,7 +282,7 @@ public: int resourceLimit(QRhi::ResourceLimit limit) const override; const QRhiNativeHandles *nativeHandles() override; void sendVMemStatsToProfiler() override; - void makeThreadLocalNativeContextCurrent() override; + bool makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; bool isDeviceLost() const override; diff --git a/src/gui/rhi/qrhivulkan.cpp b/src/gui/rhi/qrhivulkan.cpp index 64fea37292e..444c91dd751 100644 --- a/src/gui/rhi/qrhivulkan.cpp +++ b/src/gui/rhi/qrhivulkan.cpp @@ -3767,9 +3767,10 @@ void QRhiVulkan::sendVMemStatsToProfiler() quint32(stats.total.usedBytes), quint32(stats.total.unusedBytes))); } -void QRhiVulkan::makeThreadLocalNativeContextCurrent() +bool QRhiVulkan::makeThreadLocalNativeContextCurrent() { - // nothing to do here + // not applicable + return false; } void QRhiVulkan::releaseCachedResources() diff --git a/src/gui/rhi/qrhivulkan_p_p.h b/src/gui/rhi/qrhivulkan_p_p.h index a53b3b88fba..a390bc3707c 100644 --- a/src/gui/rhi/qrhivulkan_p_p.h +++ b/src/gui/rhi/qrhivulkan_p_p.h @@ -711,7 +711,7 @@ public: int resourceLimit(QRhi::ResourceLimit limit) const override; const QRhiNativeHandles *nativeHandles() override; void sendVMemStatsToProfiler() override; - void makeThreadLocalNativeContextCurrent() override; + bool makeThreadLocalNativeContextCurrent() override; void releaseCachedResources() override; bool isDeviceLost() const override; From 9864d2c6f3b628ca9f07a56b197e77bd43931cca Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 11 Sep 2019 13:18:28 +0200 Subject: [PATCH 35/41] Revert "configure: actually resolve libraries into full filepaths" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 521a85395da1a2728902816c072ec46bcb0ad380. Having libraries resolved to absolute file paths by configure has annoying consequences: 1. The Qt installer needs to unabsolutify paths in all kinds of files. This is error-prone and fragile. 2. It hurts Qt's relocatabilty. The absolute paths are unlikely to be right on different systems. 3. Qt's configure must imitate linker behavior correctly to do the resolution right on every platform, which is hard to get right. Consequently, the disadvantages of 521a8539 outweigh the advantages. Task-number: QTBUG-72903 Change-Id: I3e159c46a1348963615b95614e56f026ecb2aefd Reviewed-by: Tor Arne Vestbø Reviewed-by: Edward Welbourne --- mkspecs/common/mac.conf | 1 - mkspecs/features/qmake_use.prf | 2 + mkspecs/features/qt_configure.prf | 106 +++++------------------------- 3 files changed, 18 insertions(+), 91 deletions(-) diff --git a/mkspecs/common/mac.conf b/mkspecs/common/mac.conf index b77494ec9b2..61bea952b22 100644 --- a/mkspecs/common/mac.conf +++ b/mkspecs/common/mac.conf @@ -14,7 +14,6 @@ include(unix.conf) QMAKE_RESOURCE = /Developer/Tools/Rez QMAKE_EXTENSION_SHLIB = dylib -QMAKE_EXTENSIONS_AUX_SHLIB = tbd QMAKE_LIBDIR = # sdk.prf will prefix the proper SDK sysroot diff --git a/mkspecs/features/qmake_use.prf b/mkspecs/features/qmake_use.prf index ecb4f7ed41c..8475e4111a7 100644 --- a/mkspecs/features/qmake_use.prf +++ b/mkspecs/features/qmake_use.prf @@ -22,6 +22,8 @@ for(ever) { !defined(QMAKE_LIBS_$$nu, var): \ error("Library '$$lower($$replace(nu, _, -))' is not defined.") + QMAKE_LIBDIR += $$eval(QMAKE_LIBDIR_$$nu) + android { ABI_LIBS = $$eval(QMAKE_LIBS_$${nu}_$${QT_ARCH}) isEmpty(ABI_LIBS): ABI_LIBS = $$eval(QMAKE_LIBS_$${nu}) diff --git a/mkspecs/features/qt_configure.prf b/mkspecs/features/qt_configure.prf index 1219fe14431..52baca1fbbf 100644 --- a/mkspecs/features/qt_configure.prf +++ b/mkspecs/features/qt_configure.prf @@ -537,98 +537,23 @@ defineReplace(qtGccSysrootifiedPaths) { return($$sysrootified) } -# libs-var, libs, in-paths, out-paths-var +# libs-var, libs, in-paths defineTest(qtConfResolveLibs) { - ret = true - paths = $$3 - out = - copy = false - for (l, 2) { - $$copy { - copy = false - out += $$l - } else: equals(l, "-s") { - # em++ flag to link libraries from emscripten-ports; passed on literally. - copy = true - out += $$l - } else: contains(l, "^-L.*") { - lp = $$replace(l, "^-L", ) - gcc: lp = $$qtGccSysrootifiedPath($$lp) - !exists($$lp/.) { - qtLog("Library path $$val_escape(lp) is invalid.") - ret = false - } else { - paths += $$lp - } - } else: !android: contains(l, "^-l.*") { - lib = $$replace(l, "^-l", ) - lcan = - integrity:contains(lib, "^.*\\.a") { - # INTEGRITY compiler searches for exact filename - # if -l argument has .a suffix - lcan += $${lib} - } else: contains(lib, "^:.*") { - # Use exact filename when -l:filename syntax is used. - lib ~= s/^:// - lcan += $${lib} - } else: unix { - # Under UNIX, we look for actual shared libraries, in addition - # to static ones. - shexts = $$QMAKE_EXTENSION_SHLIB $$QMAKE_EXTENSIONS_AUX_SHLIB - for (ext, shexts) { - lcan += $${QMAKE_PREFIX_SHLIB}$${lib}.$${ext} - } - lcan += \ - $${QMAKE_PREFIX_STATICLIB}$${lib}.$${QMAKE_EXTENSION_STATICLIB} - } else { - # Under Windows, we look only for static libraries, as even for DLLs - # one actually links against a static import library. - mingw { - lcan += \ - # MinGW supports UNIX-style library naming in addition to - # the MSVC style. - lib$${lib}.dll.a lib$${lib}.a \ - # Fun fact: prefix-less libraries are also supported. - $${lib}.dll.a $${lib}.a - } - lcan += $${lib}.lib - } - l = $$qtConfFindInPathList($$lcan, $$paths $$EXTRA_LIBDIR $$QMAKE_DEFAULT_LIBDIRS) - isEmpty(l) { - qtLog("None of [$$val_escape(lcan)] found in [$$val_escape(paths)] and global paths.") - ret = false - } else { - out += $$l - } - } else { - out += $$l - } - } - $$1 = $$out + for (path, 3): \ + pre_lflags += -L$$path + $$1 = $$pre_lflags $$2 export($$1) - !isEmpty(4) { - $$4 = $$paths - export($$4) - } - return($$ret) -} - -# source-var -defineTest(qtConfResolveAllLibs) { - ret = true - !qtConfResolveLibs($${1}.libs, $$eval($${1}.libs), , $${1}.libdirs): \ - ret = false - for (b, $${1}.builds._KEYS_): \ - !qtConfResolveLibs($${1}.builds.$${b}, $$eval($${1}.builds.$${b}), $$eval($${1}.libdirs), ): \ - ret = false - return($$ret) + return(true) } # libs-var, in-paths, libs defineTest(qtConfResolvePathLibs) { ret = true - gcc: 2 = $$qtGccSysrootifiedPaths($$2) - for (libdir, 2) { + gcc: \ + local_paths = $$qtGccSysrootifiedPaths($$2) + else: \ + local_paths = $$2 + for (libdir, local_paths) { !exists($$libdir/.) { qtLog("Library path $$val_escape(libdir) is invalid.") ret = false @@ -678,8 +603,11 @@ defineReplace(qtConfGetTestIncludes) { # includes-var, in-paths, test-object-var defineTest(qtConfResolvePathIncs) { ret = true - gcc: 2 = $$qtGccSysrootifiedPaths($$2) - for (incdir, 2) { + gcc: \ + local_paths = $$qtGccSysrootifiedPaths($$2) + else: \ + local_paths = $$2 + for (incdir, local_paths) { !exists($$incdir/.) { qtLog("Include path $$val_escape(incdir) is invalid.") ret = false @@ -773,11 +701,9 @@ defineTest(qtConfLibrary_inline) { for (ld, libdir): \ libs += -L$$ld $${1}.libs = $$libs $$eval($${1}.libs) + export($${1}.libs) } - !qtConfResolveAllLibs($$1): \ - return(false) - !qtConfResolvePathIncs($${1}.includedir, $$includes, $$2): \ return(false) From 8286daba038d3c90d2bc06785ffcf9c0c603cb83 Mon Sep 17 00:00:00 2001 From: Edward Welbourne Date: Thu, 5 Sep 2019 17:18:56 +0200 Subject: [PATCH 36/41] MS TZ data: avoid calculating a date in year 0 There is no year 0 in the proleptic Gregorian calendar, so QDate() won't be happy if asked for a date in it. Tweak scanning of the data we get from MS-Win so as to avoid a date calculation that could otherwise happen in year 0 when constructing QDateTime(QDate(1, 1, 1), QTime(0, 0, 0), QTimeZone("Australia/Sydney")). Added a test for this case, which Oliver Wolff has kindly verified does reproduce the assertion failure. However, Coin is unable to reproduce, as all its MS builds are configured with -release, so Q_ASSERT() does nothing. (The relevant code then skips over year 0, albeit for the wrong reasons, and gets the right results, albeit inefficiently, leaving no other symptom by which to detect the problem.) Fixes: QTBUG-78051 Change-Id: Ife8a7470e5bd450bc421e89b3f1e1211756fc889 Reviewed-by: Qt CI Bot Reviewed-by: Oliver Wolff Reviewed-by: Volker Hilsheimer --- src/corelib/time/qtimezoneprivate_win.cpp | 42 +++++++++++++------ .../corelib/time/qdatetime/tst_qdatetime.cpp | 8 ++++ 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/corelib/time/qtimezoneprivate_win.cpp b/src/corelib/time/qtimezoneprivate_win.cpp index 1bf2366748d..5a480222e08 100644 --- a/src/corelib/time/qtimezoneprivate_win.cpp +++ b/src/corelib/time/qtimezoneprivate_win.cpp @@ -371,6 +371,7 @@ QDate calculateTransitionLocalDate(const SYSTEMTIME &rule, int year) // Otherwise, the rule date is annual and relative: const int dayOfWeek = rule.wDayOfWeek == 0 ? 7 : rule.wDayOfWeek; QDate date(year, rule.wMonth, 1); + Q_ASSERT(date.isValid()); // How many days before was last dayOfWeek before target month ? int adjust = dayOfWeek - date.dayOfWeek(); // -6 <= adjust < 7 if (adjust >= 0) // Ensure -7 <= adjust < 0: @@ -401,6 +402,7 @@ qint64 calculateTransitionForYear(const SYSTEMTIME &rule, int year, int bias) { // TODO Consider caching the calculated values - i.e. replace SYSTEMTIME in // WinTransitionRule; do this in init() once and store the results. + Q_ASSERT(year); const QDate date = calculateTransitionLocalDate(rule, year); const QTime time = QTime(rule.wHour, rule.wMinute, rule.wSecond); if (date.isValid() && time.isValid()) @@ -479,6 +481,7 @@ struct TransitionTimePair int yearEndOffset(const QWinTimeZonePrivate::QWinTransitionRule &rule, int year) { + Q_ASSERT(year); int offset = rule.standardTimeBias; // Only needed to help another TransitionTimePair work out year + 1's start // offset; and the oldYearOffset we use only affects an alleged transition @@ -743,11 +746,12 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::data(qint64 forMSecsSinceEpoch) cons const QWinTransitionRule &rule = m_tranRules.at(ruleIndex); // Does this rule's period include any transition at all ? if (rule.standardTimeRule.wMonth > 0 || rule.daylightTimeRule.wMonth > 0) { - const int endYear = qMax(rule.startYear, year - 1); + int prior = year == 1 ? -1 : year - 1; // No year 0. + const int endYear = qMax(rule.startYear, prior); while (year >= endYear) { const int newYearOffset = (year <= rule.startYear && ruleIndex > 0) - ? yearEndOffset(m_tranRules.at(ruleIndex - 1), year - 1) - : yearEndOffset(rule, year - 1); + ? yearEndOffset(m_tranRules.at(ruleIndex - 1), prior) + : yearEndOffset(rule, prior); const TransitionTimePair pair(rule, year, newYearOffset); bool isDst = false; if (pair.std != invalidMSecs() && pair.std <= forMSecsSinceEpoch) { @@ -755,7 +759,8 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::data(qint64 forMSecsSinceEpoch) cons } else if (pair.dst != invalidMSecs() && pair.dst <= forMSecsSinceEpoch) { isDst = true; } else { - --year; // Try an earlier year for this rule (once). + year = prior; // Try an earlier year for this rule (once). + prior = year == 1 ? -1 : year - 1; // No year 0. continue; } return ruleToData(rule, forMSecsSinceEpoch, @@ -767,8 +772,11 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::data(qint64 forMSecsSinceEpoch) cons // No transition, no DST, use the year's standard time. return ruleToData(rule, forMSecsSinceEpoch, QTimeZone::StandardTime); } - if (year >= rule.startYear) + if (year >= rule.startYear) { year = rule.startYear - 1; // Seek last transition in new rule. + if (!year) + --year; + } } // We don't have relevant data :-( return invalidData(); @@ -795,9 +803,10 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::nextTransition(qint64 afterMSecsSinc year = rule.startYear; // Seek first transition in this rule. const int endYear = ruleIndex + 1 < m_tranRules.count() ? qMin(m_tranRules.at(ruleIndex + 1).startYear, year + 2) : (year + 2); + int prior = year == 1 ? -1 : year - 1; // No year 0. int newYearOffset = (year <= rule.startYear && ruleIndex > 0) - ? yearEndOffset(m_tranRules.at(ruleIndex - 1), year - 1) - : yearEndOffset(rule, year - 1); + ? yearEndOffset(m_tranRules.at(ruleIndex - 1), prior) + : yearEndOffset(rule, prior); while (year < endYear) { const TransitionTimePair pair(rule, year, newYearOffset); bool isDst = false; @@ -810,7 +819,9 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::nextTransition(qint64 afterMSecsSinc newYearOffset = rule.standardTimeBias; if (pair.dst > pair.std) newYearOffset += rule.daylightTimeBias; - ++year; // Try a later year for this rule (once). + // Try a later year for this rule (once). + prior = year; + year = year == -1 ? 1 : year + 1; // No year 0 continue; } @@ -837,11 +848,12 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::previousTransition(qint64 beforeMSec const QWinTransitionRule &rule = m_tranRules.at(ruleIndex); // Does this rule's period include any transition at all ? if (rule.standardTimeRule.wMonth > 0 || rule.daylightTimeRule.wMonth > 0) { - const int endYear = qMax(rule.startYear, year - 1); + int prior = year == 1 ? -1 : year - 1; // No year 0. + const int endYear = qMax(rule.startYear, prior); while (year >= endYear) { const int newYearOffset = (year <= rule.startYear && ruleIndex > 0) - ? yearEndOffset(m_tranRules.at(ruleIndex - 1), year - 1) - : yearEndOffset(rule, year - 1); + ? yearEndOffset(m_tranRules.at(ruleIndex - 1), prior) + : yearEndOffset(rule, prior); const TransitionTimePair pair(rule, year, newYearOffset); bool isDst = false; if (pair.std != invalidMSecs() && pair.std < beforeMSecsSinceEpoch) { @@ -849,7 +861,8 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::previousTransition(qint64 beforeMSec } else if (pair.dst != invalidMSecs() && pair.dst < beforeMSecsSinceEpoch) { isDst = true; } else { - --year; // Try an earlier year for this rule (once). + year = prior; // Try an earlier year for this rule (once). + prior = year == 1 ? -1 : year - 1; // No year 0. continue; } if (isDst) @@ -863,8 +876,11 @@ QTimeZonePrivate::Data QWinTimeZonePrivate::previousTransition(qint64 beforeMSec // rule: return ruleToData(rule, startOfTime, QTimeZone::StandardTime, false); } // else: no transition during rule's period - if (year >= rule.startYear) + if (year >= rule.startYear) { year = rule.startYear - 1; // Seek last transition in new rule + if (!year) + --year; + } } // Apparently no transition before the given time: return invalidData(); diff --git a/tests/auto/corelib/time/qdatetime/tst_qdatetime.cpp b/tests/auto/corelib/time/qdatetime/tst_qdatetime.cpp index ac1b903aa19..531ac2995f3 100644 --- a/tests/auto/corelib/time/qdatetime/tst_qdatetime.cpp +++ b/tests/auto/corelib/time/qdatetime/tst_qdatetime.cpp @@ -3352,6 +3352,14 @@ void tst_QDateTime::timeZones() const QCOMPARE(dt3.timeSpec(), dt1.timeSpec()); QCOMPARE(dt3.timeZone(), dt1.timeZone()); + // The start of year 1 should be *describable* in any zone (QTBUG-78051) + dt3 = QDateTime(QDate(1, 1, 1), QTime(0, 0, 0), ausTz); + QVERIFY(dt3.isValid()); + // Likewise the end of year -1 (a.k.a. 1 BCE). + dt3 = dt3.addMSecs(-1); + QVERIFY(dt3.isValid()); + QCOMPARE(dt3, QDateTime(QDate(-1, 12, 31), QTime(23, 59, 59, 999), ausTz)); + // Check datastream serialises the time zone QByteArray tmp; { From c6bde29e143b1fadac97f656ba6c3059135d4a11 Mon Sep 17 00:00:00 2001 From: Edward Welbourne Date: Mon, 9 Sep 2019 16:20:47 +0200 Subject: [PATCH 37/41] Doc-fix: correct some misinformation about QDateTime's handling of DST Tidy up QDateTime::offsetFromUtc's doc, in the process. We don't take DST into account for dates before the epoch; that should be mentioned when saying we take DST into account. Also, referring to *this as the "current" time begs to be misunderstood. The \class comment also misleadingly claimed that we don't take into account any changes to time-zone before DST; where, in fact, we only ignore DST changes before 1970, not changes to standard offset. Change-Id: I090e668edf0338c825f5afcc67f894579a129c46 Reviewed-by: Paul Wicking --- src/corelib/time/qdatetime.cpp | 53 +++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/src/corelib/time/qdatetime.cpp b/src/corelib/time/qdatetime.cpp index 8b1665e7dd6..13a54c1210b 100644 --- a/src/corelib/time/qdatetime.cpp +++ b/src/corelib/time/qdatetime.cpp @@ -3432,15 +3432,15 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT datetime by adding a number of seconds, days, months, or years. QDateTime can describe datetimes with respect to \l{Qt::LocalTime}{local - time}, to \l{Qt::UTC}{UTC}, to a specified \l{Qt::OffsetFromUTC}{offset - from UTC} or to a specified \l{Qt::TimeZone}{time zone}, in conjunction - with the QTimeZone class. For example, a time zone of "Europe/Berlin" will - apply the daylight-saving rules as used in Germany since 1970. In contrast, - an offset from UTC of +3600 seconds is one hour ahead of UTC (usually - written in ISO standard notation as "UTC+01:00"), with no daylight-saving - offset or changes. When using either local time or a specified time zone, - time-zone transitions such as the starts and ends of daylight-saving time - (DST) are taken into account. The choice of system used to represent a + time}, to \l{Qt::UTC}{UTC}, to a specified \l{Qt::OffsetFromUTC}{offset from + UTC} or to a specified \l{Qt::TimeZone}{time zone}, in conjunction with the + QTimeZone class. For example, a time zone of "Europe/Berlin" will apply the + daylight-saving rules as used in Germany since 1970. In contrast, an offset + from UTC of +3600 seconds is one hour ahead of UTC (usually written in ISO + standard notation as "UTC+01:00"), with no daylight-saving offset or + changes. When using either local time or a specified time zone, time-zone + transitions such as the starts and ends of daylight-saving time (DST; but + see below) are taken into account. The choice of system used to represent a datetime is described as its "timespec". A QDateTime object is typically created either by giving a date and time @@ -3528,11 +3528,13 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT The range of valid dates taking DST into account is 1970-01-01 to the present, and rules are in place for handling DST correctly until 2037-12-31, - but these could change. For dates falling outside that range, QDateTime - makes a \e{best guess} using the rules for year 1970 or 2037, but we can't - guarantee accuracy. This means QDateTime doesn't take into account changes - in a time zone before 1970, even if the system's time zone database provides - that information. + but these could change. For dates after 2037, QDateTime makes a \e{best + guess} using the rules for year 2037, but we can't guarantee accuracy; + indeed, for \e{any} future date, the time-zone may change its rules before + that date comes around. For dates before 1970, QDateTime doesn't take DST + changes into account, even if the system's time zone database provides that + information, although it does take into account changes to the time-zone's + standard offset, where this information is available. \section2 Offsets From UTC @@ -3797,17 +3799,22 @@ QTimeZone QDateTime::timeZone() const /*! \since 5.2 - Returns the current Offset From UTC in seconds. + Returns this date-time's Offset From UTC in seconds. - If the timeSpec() is Qt::OffsetFromUTC this will be the value originally set. + The result depends on timeSpec(): + \list + \li \c Qt::UTC The offset is 0. + \li \c Qt::OffsetFromUTC The offset is the value originally set. + \li \c Qt::LocalTime The local time's offset from UTC is returned. + \li \c Qt::TimeZone The offset used by the time-zone is returned. + \endlist - If the timeSpec() is Qt::TimeZone this will be the offset effective in the - Time Zone including any Daylight-Saving Offset. - - If the timeSpec() is Qt::LocalTime this will be the difference between the - Local Time and UTC including any Daylight-Saving Offset. - - If the timeSpec() is Qt::UTC this will be 0. + For the last two, the offset at this date and time will be returned, taking + account of Daylight-Saving Offset unless the date precedes the start of + 1970. The offset is the difference between the local time or time in the + given time-zone and UTC time; it is positive in time-zones ahead of UTC + (East of The Prime Meridian), negative for those behind UTC (West of The + Prime Meridian). \sa setOffsetFromUtc() */ From 00d0a530358d40d577578cb1bcb75a978549bd8d Mon Sep 17 00:00:00 2001 From: David Faure Date: Sat, 7 Sep 2019 23:14:19 +0200 Subject: [PATCH 38/41] QDpi: divide the forced DPI by the scaling factor, as Qt 5.13 did MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When setting a DPI in xrdb, it should have the same effect on apps that enable scaling and apps that don't (including Qt4 and GTK applications). That's what happened in Qt 5.13, while the recent changes removed that division, and as a result the fonts were huge in Qt5 apps compared to Qt4/GTK/kwin/plasmashell/krunner (which don't scale, but do honor the font DPI). Change-Id: Icd7be2d15a9b50982ae624e41bd9e546f315d58b Reviewed-by: Friedemann Kleint Reviewed-by: Morten Johan Sørvig --- src/gui/kernel/qhighdpiscaling.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/gui/kernel/qhighdpiscaling.cpp b/src/gui/kernel/qhighdpiscaling.cpp index dcbae4f5c0a..ee54fd4fa19 100644 --- a/src/gui/kernel/qhighdpiscaling.cpp +++ b/src/gui/kernel/qhighdpiscaling.cpp @@ -680,8 +680,11 @@ QDpi QHighDpiScaling::logicalDpi(const QScreen *screen) if (!screen || !screen->handle()) return QDpi(96, 96); - if (!m_usePixelDensity) - return QPlatformScreen::overrideDpi(screen->handle()->logicalDpi()); + if (!m_usePixelDensity) { + const qreal screenScaleFactor = screenSubfactor(screen->handle()); + const QDpi dpi = QPlatformScreen::overrideDpi(screen->handle()->logicalDpi()); + return QDpi{ dpi.first / screenScaleFactor, dpi.second / screenScaleFactor }; + } const qreal scaleFactor = rawScaleFactor(screen->handle()); const qreal roundedScaleFactor = roundScaleFactor(scaleFactor); From 4534522ff0f189418d828fd29b9d417b5a1b5d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Fri, 13 Sep 2019 18:37:00 +0200 Subject: [PATCH 39/41] macOS: Keep default NSWindow background unless window is frameless The logic was changed in ee82f8661 to only draw a window background when the window was textured, and otherwise ask for a clear window background. This has an unfortunate side-effect on macOS 10.15 that the window's title bar will be partially transparent and reflect the content under the window, with a blur effect. It also inadvertently broke the use-case of setting the NSWindow background color explicitly. With this patch we're back to the behavior before ee82f8661, and users who still want to have a non-borderless window with a clear background can still do this by setting the background color to the clear color manually. Task-number: QTBUG-77637 Change-Id: I8a11bc46e6393b29a37f002ea123a987048106b9 Reviewed-by: Timur Pocheptsov --- src/plugins/platforms/cocoa/qnswindow.mm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/platforms/cocoa/qnswindow.mm b/src/plugins/platforms/cocoa/qnswindow.mm index 68cb2704575..6b4e110af27 100644 --- a/src/plugins/platforms/cocoa/qnswindow.mm +++ b/src/plugins/platforms/cocoa/qnswindow.mm @@ -255,8 +255,8 @@ static bool isMouseEvent(NSEvent *ev) - (NSColor *)backgroundColor { - return self.styleMask & NSWindowStyleMaskTexturedBackground ? - [super backgroundColor] : [NSColor clearColor]; + return self.styleMask == NSWindowStyleMaskBorderless ? + [NSColor clearColor] : [super backgroundColor]; } - (void)sendEvent:(NSEvent*)theEvent From 02e43e6fa6f47eaedc1dd72956569aa939d90981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Wed, 28 Aug 2019 16:56:18 +0200 Subject: [PATCH 40/41] widgets: Remove use of deprecated activated(const QString &) API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I71c6a10f6593ac28bf8f60d9db8d167cf88715cb Reviewed-by: Paul Olav Tvete Reviewed-by: Tor Arne Vestbø --- src/widgets/widgets/qcombobox.cpp | 15 --------------- src/widgets/widgets/qcombobox_p.h | 10 ++++++++++ 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp index a53c278aeae..9a0e969e1c5 100644 --- a/src/widgets/widgets/qcombobox.cpp +++ b/src/widgets/widgets/qcombobox.cpp @@ -2539,21 +2539,6 @@ QSize QComboBox::sizeHint() const } #ifdef Q_OS_MAC - -namespace { -struct IndexSetter { - int index; - QComboBox *cb; - - void operator()(void) - { - cb->setCurrentIndex(index); - emit cb->activated(index); - emit cb->activated(cb->itemText(index)); - } -}; -} - void QComboBoxPrivate::cleanupNativePopup() { if (!m_platformMenu) diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h index eadb21628f4..5967776a614 100644 --- a/src/widgets/widgets/qcombobox_p.h +++ b/src/widgets/widgets/qcombobox_p.h @@ -390,6 +390,16 @@ public: #ifdef Q_OS_MAC void cleanupNativePopup(); bool showNativePopup(); + struct IndexSetter { + int index; + QComboBox *cb; + + void operator()(void) + { + cb->setCurrentIndex(index); + cb->d_func()->emitActivated(cb->d_func()->currentIndex); + } + }; #endif QAbstractItemModel *model; From 6f8fc4217a722cf89cd3502156cc0586588fda1e Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Mon, 26 Aug 2019 20:53:53 +0200 Subject: [PATCH 41/41] tst_QTableView: cleanup Cleanup QTableView autotest: - use range-based for loops where possible - use nullptr - use member initialization - use new signal/slot syntax - remove a lot of c-style casts - use static invocations - use override - instantiate objects on stack instead heap to avoid memleaks Change-Id: I52fee26697b1732afa9f965e600d4c59551370ce Reviewed-by: Friedemann Kleint Reviewed-by: Edward Welbourne --- .../itemviews/qtableview/tst_qtableview.cpp | 1367 ++++++++--------- 1 file changed, 639 insertions(+), 728 deletions(-) diff --git a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp index 35c0c6c6060..09990ab70a2 100644 --- a/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp +++ b/tests/auto/widgets/itemviews/qtableview/tst_qtableview.cpp @@ -26,19 +26,24 @@ ** ****************************************************************************/ - -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include -#include -#include "private/qapplication_p.h" +#include #if QT_CONFIG(textmarkdownwriter) -#include "private/qtextmarkdownwriter_p.h" +#include #endif -#include - -#include using namespace QTestPrivate; @@ -49,14 +54,241 @@ using namespace QTestPrivate; #define VERIFY_SPANS_CONSISTENCY(TEST_VIEW_) (void)false #endif -typedef QList IntList; +Q_DECLARE_METATYPE(Qt::Key); +Q_DECLARE_METATYPE(Qt::KeyboardModifier); +Q_DECLARE_METATYPE(QItemSelectionModel::SelectionFlag); +using BoolList = QVector; +using IntList = QVector; +using KeyList = QVector; +using SpanList = QVector; -typedef QList BoolList; +class QtTestTableModel: public QAbstractTableModel +{ + Q_OBJECT + +signals: + void invalidIndexEncountered() const; + +public slots: + bool submit() override { ++submit_count; return QAbstractTableModel::submit(); } + +public: + QtTestTableModel(int rows = 0, int columns = 0, QObject *parent = nullptr) + : QAbstractTableModel(parent), row_count(rows), column_count(columns) + {} + + int rowCount(const QModelIndex& = QModelIndex()) const override + { + return row_count; + } + + int columnCount(const QModelIndex& = QModelIndex()) const override + { + return column_count; + } + + bool isEditable(const QModelIndex &) const { return true; } + + Qt::ItemFlags flags(const QModelIndex &index) const override + { + Qt::ItemFlags index_flags = QAbstractTableModel::flags(index); + if (disabled_rows.contains(index.row()) + || disabled_columns.contains(index.column())) + index_flags &= ~Qt::ItemIsEnabled; + return index_flags; + } + + void disableRow(int row) + { + disabled_rows.insert(row); + } + + void enableRow(int row) + { + disabled_rows.remove(row); + } + + void disableColumn(int column) + { + disabled_columns.insert(column); + } + + void enableColumn(int column) + { + disabled_columns.remove(column); + } + + QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override + { + if (!idx.isValid() || idx.row() >= row_count || idx.column() >= column_count) { + qWarning() << "Invalid modelIndex [%d,%d,%p]" << idx; + emit invalidIndexEncountered(); + return QVariant(); + } + + if (role == Qt::DisplayRole || role == Qt::EditRole) { + return QLatin1Char('[') + QString::number(idx.row()) + QLatin1Char(',') + + QString::number(idx.column()) + QLatin1String(",0]"); + } + + return QVariant(); + } + + bool insertRows(int start, int count, const QModelIndex &parent = QModelIndex()) override + { + if (start < 0 || start > row_count) + return false; + + beginInsertRows(parent, start, start + count - 1); + row_count += count; + endInsertRows(); + return true; + } + + bool removeRows(int start, int count, const QModelIndex &parent = QModelIndex()) override + { + if (start < 0 || start >= row_count || row_count < count) + return false; + + beginRemoveRows(parent, start, start + count - 1); + row_count -= count; + endRemoveRows(); + return true; + } + + void removeLastRow() + { + beginRemoveRows(QModelIndex(), row_count - 1, row_count - 1); + --row_count; + endRemoveRows(); + } + + void removeAllRows() + { + beginRemoveRows(QModelIndex(), 0, row_count - 1); + row_count = 0; + endRemoveRows(); + } + + bool insertColumns(int start, int count, const QModelIndex &parent = QModelIndex()) override + { + if (start < 0 || start > column_count) + return false; + + beginInsertColumns(parent, start, start + count - 1); + column_count += count; + endInsertColumns(); + return true; + } + + bool removeColumns(int start, int count, const QModelIndex &parent = QModelIndex()) override + { + if (start < 0 || start >= column_count || column_count < count) + return false; + + beginRemoveColumns(parent, start, start + count - 1); + column_count -= count; + endRemoveColumns(); + return true; + } + + void removeLastColumn() + { + beginRemoveColumns(QModelIndex(), column_count - 1, column_count - 1); + --column_count; + endRemoveColumns(); + } + + void removeAllColumns() + { + beginRemoveColumns(QModelIndex(), 0, column_count - 1); + column_count = 0; + endRemoveColumns(); + } + + bool canFetchMore(const QModelIndex &) const override + { + return can_fetch_more; + } + + void fetchMore(const QModelIndex &) override + { + ++fetch_more_count; + } + + QSet disabled_rows; + QSet disabled_columns; + int row_count; + int column_count; + int submit_count = 0; + int fetch_more_count = 0; + bool can_fetch_more = false; +}; + +class QtTestTableView : public QTableView +{ + Q_OBJECT +public: + using QTableView::QTableView; + + void setModel(QAbstractItemModel *model) override + { + QTableView::setModel(model); + connect(selectionModel(), &QItemSelectionModel::currentChanged, + this, &QtTestTableView::slotCurrentChanged); + connect(selectionModel(), &QItemSelectionModel::selectionChanged, + this, &QtTestTableView::itemSelectionChanged); + // Allow small sections in this test, since this test was made before we correctly enforced minimum sizes. + horizontalHeader()->setMinimumSectionSize(0); + verticalHeader()->setMinimumSectionSize(0); + } + + using QTableView::moveCursor; + using QTableView::isIndexHidden; + using QTableView::setSelection; + using QTableView::selectedIndexes; + using QTableView::sizeHintForRow; + using QTableView::viewOptions; + + bool checkSignalOrder = false; +public slots: + void slotCurrentChanged(QModelIndex, QModelIndex) { + hasCurrentChanged++; + if (checkSignalOrder) + QVERIFY(hasCurrentChanged > hasSelectionChanged); + } + + void itemSelectionChanged(QItemSelection , QItemSelection ) { + hasSelectionChanged++; + if (checkSignalOrder) + QVERIFY(hasCurrentChanged >= hasSelectionChanged); + } +private: + int hasCurrentChanged = 0; + int hasSelectionChanged = 0; + + friend class tst_QTableView; + friend struct QMetaTypeId; +}; +Q_DECLARE_METATYPE(QtTestTableView::CursorAction); + +class QtTestItemDelegate : public QStyledItemDelegate +{ +public: + QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override + { + return hint; + } + + QSize hint; +}; class tst_QTableView : public QObject { Q_OBJECT +private: + using CursorActionList = QVector; private slots: void getSetCheck(); @@ -236,14 +468,14 @@ void tst_QTableView::getSetCheck() QHeaderView *var1 = new QHeaderView(Qt::Horizontal); obj1.setHorizontalHeader(var1); QCOMPARE(var1, obj1.horizontalHeader()); - obj1.setHorizontalHeader((QHeaderView *)0); + obj1.setHorizontalHeader(nullptr); QCOMPARE(var1, obj1.horizontalHeader()); delete var1; QHeaderView *var2 = new QHeaderView(Qt::Vertical); obj1.setVerticalHeader(var2); QCOMPARE(var2, obj1.verticalHeader()); - obj1.setVerticalHeader((QHeaderView *)0); + obj1.setVerticalHeader(nullptr); QCOMPARE(var2, obj1.verticalHeader()); delete var2; @@ -251,283 +483,12 @@ void tst_QTableView::getSetCheck() obj1.setCornerButtonEnabled(false); QCOMPARE(obj1.isCornerButtonEnabled(), false); } - -class QtTestTableModel: public QAbstractTableModel -{ - Q_OBJECT - -signals: - void invalidIndexEncountered() const; - -public slots: - bool submit() { ++submit_count; return QAbstractTableModel::submit(); } - -public: - QtTestTableModel(int rows = 0, int columns = 0, QObject *parent = 0) - : QAbstractTableModel(parent), - row_count(rows), - column_count(columns), - submit_count(0), - can_fetch_more(false), - fetch_more_count(0), - disabled_rows(), - disabled_columns() {} - - int rowCount(const QModelIndex& = QModelIndex()) const { return row_count; } - int columnCount(const QModelIndex& = QModelIndex()) const { return column_count; } - bool isEditable(const QModelIndex &) const { return true; } - - Qt::ItemFlags flags(const QModelIndex &index) const - { - Qt::ItemFlags index_flags = QAbstractTableModel::flags(index); - if (disabled_rows.contains(index.row()) - || disabled_columns.contains(index.column())) - index_flags &= ~Qt::ItemIsEnabled; - return index_flags; - } - - void disableRow(int row) - { - disabled_rows.insert(row); - } - - void enableRow(int row) - { - disabled_rows.remove(row); - } - - void disableColumn(int column) - { - disabled_columns.insert(column); - } - - void enableColumn(int column) - { - disabled_columns.remove(column); - } - - QVariant data(const QModelIndex &idx, int role) const - { - if (!idx.isValid() || idx.row() >= row_count || idx.column() >= column_count) { - qWarning() << "Invalid modelIndex [%d,%d,%p]" << idx; - emit invalidIndexEncountered(); - return QVariant(); - } - - if (role == Qt::DisplayRole || role == Qt::EditRole) { - return QLatin1Char('[') + QString::number(idx.row()) + QLatin1Char(',') - + QString::number(idx.column()) + QLatin1String(",0]"); - } - - return QVariant(); - } - - bool insertRows(int start, int count, const QModelIndex &parent = QModelIndex()) - { - if (start < 0 || start > row_count) - return false; - - beginInsertRows(parent, start, start + count - 1); - row_count += count; - endInsertRows(); - return true; - } - - bool removeRows(int start, int count, const QModelIndex &parent = QModelIndex()) - { - if (start < 0 || start >= row_count || row_count < count) - return false; - - beginRemoveRows(parent, start, start + count - 1); - row_count -= count; - endRemoveRows(); - return true; - } - - void removeLastRow() - { - beginRemoveRows(QModelIndex(), row_count - 1, row_count - 1); - --row_count; - endRemoveRows(); - } - - void removeAllRows() - { - beginRemoveRows(QModelIndex(), 0, row_count - 1); - row_count = 0; - endRemoveRows(); - } - - bool insertColumns(int start, int count, const QModelIndex &parent = QModelIndex()) - { - if (start < 0 || start > column_count) - return false; - - beginInsertColumns(parent, start, start + count - 1); - column_count += count; - endInsertColumns(); - return true; - } - - bool removeColumns(int start, int count, const QModelIndex &parent = QModelIndex()) - { - if (start < 0 || start >= column_count || column_count < count) - return false; - - beginRemoveColumns(parent, start, start + count - 1); - column_count -= count; - endRemoveColumns(); - return true; - } - - void removeLastColumn() - { - beginRemoveColumns(QModelIndex(), column_count - 1, column_count - 1); - --column_count; - endRemoveColumns(); - } - - void removeAllColumns() - { - beginRemoveColumns(QModelIndex(), 0, column_count - 1); - column_count = 0; - endRemoveColumns(); - } - - bool canFetchMore(const QModelIndex &) const - { - return can_fetch_more; - } - - void fetchMore(const QModelIndex &) - { - ++fetch_more_count; - } - - void reset() - { - beginResetModel(); - endResetModel(); - } - - int row_count; - int column_count; - int submit_count; - bool can_fetch_more; - int fetch_more_count; - QSet disabled_rows; - QSet disabled_columns; -}; - -class QtTestTableView : public QTableView -{ -Q_OBJECT - -public: - QtTestTableView(QWidget *parent = 0) : QTableView(parent), checkSignalOrder(false), hasCurrentChanged(0), hasSelectionChanged(0) {} - - void setModel(QAbstractItemModel *model) - { - QTableView::setModel(model); - connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), - this, SLOT(slotCurrentChanged(QModelIndex,QModelIndex))); - connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(itemSelectionChanged(QItemSelection,QItemSelection))); - // Allow small sections in this test, since this test was made before we correctly enforced minimum sizes. - horizontalHeader()->setMinimumSectionSize(0); - verticalHeader()->setMinimumSectionSize(0); - } - - // enum CursorAction and moveCursor() are protected in QTableView. - enum CursorAction { - MoveUp = QAbstractItemView::MoveUp, - MoveDown = QAbstractItemView::MoveDown, - MoveLeft = QAbstractItemView::MoveLeft, - MoveRight = QAbstractItemView::MoveRight, - MoveHome = QAbstractItemView::MoveHome, - MoveEnd = QAbstractItemView::MoveEnd, - MovePageUp = QAbstractItemView::MovePageUp, - MovePageDown = QAbstractItemView::MovePageDown, - MoveNext = QAbstractItemView::MoveNext, - MovePrevious = QAbstractItemView::MovePrevious - }; - - QModelIndex doMoveCursor(QtTestTableView::CursorAction cursorAction, - Qt::KeyboardModifiers modifiers) - { - return QTableView::moveCursor((QAbstractItemView::CursorAction)cursorAction, modifiers); - } - - int columnWidthHint(int column) const - { - return sizeHintForColumn(column); - } - - int rowHeightHint(int row) const - { - return sizeHintForRow(row); - } - - bool isIndexHidden(const QModelIndex &index) const - { - return QTableView::isIndexHidden(index); - } - - void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) - { - QTableView::setSelection(rect, command); - } - - QModelIndexList selectedIndexes() const - { - return QTableView::selectedIndexes(); - } - - int sizeHintForRow(int row) const - { - return QTableView::sizeHintForRow(row); - } - - QStyleOptionViewItem viewOptions() const { - return QTableView::viewOptions(); - } - - bool checkSignalOrder; -public slots: - void slotCurrentChanged(QModelIndex, QModelIndex) { - hasCurrentChanged++; - if (checkSignalOrder) - QVERIFY(hasCurrentChanged > hasSelectionChanged); - } - - void itemSelectionChanged(QItemSelection , QItemSelection ) { - hasSelectionChanged++; - if (checkSignalOrder) - QVERIFY(hasCurrentChanged >= hasSelectionChanged); - } -private: - int hasCurrentChanged; - int hasSelectionChanged; - -}; - -class QtTestItemDelegate : public QItemDelegate -{ -public: - QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const - { - return hint; - } - - QSize hint; -}; - void tst_QTableView::noDelegate() { QtTestTableModel model(3, 3); QTableView view; view.setModel(&model); - view.setItemDelegate(0); + view.setItemDelegate(nullptr); view.show(); } @@ -541,7 +502,7 @@ void tst_QTableView::emptyModel() { QtTestTableModel model; QTableView view; - QSignalSpy spy(&model, SIGNAL(invalidIndexEncountered())); + QSignalSpy spy(&model, &QtTestTableModel::invalidIndexEncountered); view.setModel(&model); view.show(); QCOMPARE(spy.count(), 0); @@ -562,7 +523,7 @@ void tst_QTableView::removeRows() QFETCH(int, columnCount); QtTestTableModel model(rowCount, columnCount); - QSignalSpy spy(&model, SIGNAL(invalidIndexEncountered())); + QSignalSpy spy(&model, &QtTestTableModel::invalidIndexEncountered); QTableView view; view.setModel(&model); @@ -590,7 +551,7 @@ void tst_QTableView::removeColumns() QFETCH(int, columnCount); QtTestTableModel model(rowCount, columnCount); - QSignalSpy spy(&model, SIGNAL(invalidIndexEncountered())); + QSignalSpy spy(&model, &QtTestTableModel::invalidIndexEncountered); QTableView view; view.setModel(&model); @@ -608,58 +569,18 @@ void tst_QTableView::keyboardNavigation_data() QTest::addColumn("rowCount"); QTest::addColumn("columnCount"); QTest::addColumn("tabKeyNavigation"); - QTest::addColumn("keyPresses"); + QTest::addColumn("keyPresses"); - QTest::newRow("16x16 model") << 16 << 16 << true - << (IntList() - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Right - << Qt::Key_Right - << Qt::Key_Up - << Qt::Key_Left - << Qt::Key_Left - << Qt::Key_Up - << Qt::Key_Down - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Left - << Qt::Key_Left - << Qt::Key_Up - << Qt::Key_Down - << Qt::Key_Down - << Qt::Key_Tab - << Qt::Key_Backtab); + const KeyList keyList { + Qt::Key_Up, Qt::Key_Up, Qt::Key_Right, Qt::Key_Right, + Qt::Key_Up, Qt::Key_Left, Qt::Key_Left, Qt::Key_Up, + Qt::Key_Down, Qt::Key_Up, Qt::Key_Up, Qt::Key_Up, + Qt::Key_Up, Qt::Key_Up, Qt::Key_Up, Qt::Key_Left, + Qt::Key_Left, Qt::Key_Up, Qt::Key_Down, Qt::Key_Down, + Qt::Key_Tab, Qt::Key_Backtab}; - - QTest::newRow("no tab") << 8 << 8 << false - << (IntList() - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Right - << Qt::Key_Right - << Qt::Key_Up - << Qt::Key_Left - << Qt::Key_Left - << Qt::Key_Up - << Qt::Key_Down - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Up - << Qt::Key_Left - << Qt::Key_Left - << Qt::Key_Up - << Qt::Key_Down - << Qt::Key_Down - << Qt::Key_Tab - << Qt::Key_Backtab); + QTest::newRow("16x16 model") << 16 << 16 << true << keyList; + QTest::newRow("no tab") << 8 << 8 << false << keyList; } void tst_QTableView::keyboardNavigation() @@ -667,7 +588,7 @@ void tst_QTableView::keyboardNavigation() QFETCH(int, rowCount); QFETCH(int, columnCount); QFETCH(bool, tabKeyNavigation); - QFETCH(IntList, keyPresses); + QFETCH(const KeyList, keyPresses); QtTestTableModel model(rowCount, columnCount); QTableView view; @@ -678,14 +599,12 @@ void tst_QTableView::keyboardNavigation() view.setCurrentIndex(index); view.show(); - qApp->setActiveWindow(&view); + QApplication::setActiveWindow(&view); QVERIFY(QTest::qWaitForWindowActive(&view)); int row = rowCount - 1; int column = columnCount - 1; - for (int i = 0; i < keyPresses.count(); ++i) { - - Qt::Key key = (Qt::Key)keyPresses.at(i); + for (Qt::Key key : keyPresses) { switch (key) { case Qt::Key_Up: @@ -785,8 +704,8 @@ void tst_QTableView::moveCursor_data() QTest::addColumn("startRow"); QTest::addColumn("startColumn"); - QTest::addColumn("cursorMoveAction"); - QTest::addColumn("modifier"); + QTest::addColumn("cursorMoveAction"); + QTest::addColumn("modifier"); QTest::addColumn("expectedRow"); QTest::addColumn("expectedColumn"); @@ -797,346 +716,346 @@ void tst_QTableView::moveCursor_data() QTest::newRow("MoveRight (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveRight) << int(Qt::NoModifier) + << QtTestTableView::MoveRight << Qt::NoModifier << 0 << 1 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveRight (3,0)") << 4 << 4 << -1 << -1 << 3 << 0 - << int(QtTestTableView::MoveRight) << int(Qt::NoModifier) + << QtTestTableView::MoveRight << Qt::NoModifier << 3 << 1 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveRight (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveRight) << int(Qt::NoModifier) + << QtTestTableView::MoveRight << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); // ### QTest::newRow("MoveRight, hidden column 1 (0,0)") << 4 << 4 << -1 << 1 << 0 << 0 - << int(QtTestTableView::MoveRight) << int(Qt::NoModifier) + << QtTestTableView::MoveRight << Qt::NoModifier << 0 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveRight, hidden column 3 (0,2)") << 4 << 4 << -1 << 3 << 0 << 2 - << int(QtTestTableView::MoveRight) << int(Qt::NoModifier) + << QtTestTableView::MoveRight << Qt::NoModifier << 0 << 2 << IntPair(0,0) << IntPair(0,0); // ### // MoveNext should in addition wrap QTest::newRow("MoveNext (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 1 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext (0,2)") << 4 << 4 << -1 << -1 << 0 << 2 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrap (0,3)") << 4 << 4 << -1 << -1 << 0 << 3 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 1 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrap (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, hidden column 1 (0,0)") << 4 << 4 << -1 << 1 << 0 << 0 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrap, hidden column 3 (0,2)") << 4 << 4 << -1 << 3 << 0 << 2 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 1 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrap, hidden column 3 (3,2)") << 4 << 4 << -1 << 3 << 3 << 2 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrapy, wrapx, hidden column 3, hidden row 3 (2,2)") << 4 << 4 << 3 << 3 << 2 << 2 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveNext, wrap, hidden column 2, moved column from 3 to 0. (0,2)") << 4 << 4 << -1 << 2 << 0 << 2 - << int(QtTestTableView::MoveNext) << int(Qt::NoModifier) + << QtTestTableView::MoveNext << Qt::NoModifier << 1 << 3 << IntPair(0,0) << IntPair(3,0); // MoveLeft QTest::newRow("MoveLeft (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveLeft) << int(Qt::NoModifier) + << QtTestTableView::MoveLeft << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveLeft (0,3)") << 4 << 4 << -1 << -1 << 0 << 3 - << int(QtTestTableView::MoveLeft) << int(Qt::NoModifier) + << QtTestTableView::MoveLeft << Qt::NoModifier << 0 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveLeft (1,0)") << 4 << 4 << -1 << -1 << 1 << 0 - << int(QtTestTableView::MoveLeft) << int(Qt::NoModifier) + << QtTestTableView::MoveLeft << Qt::NoModifier << 1 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveLeft, hidden column 0 (0,2)") << 4 << 4 << -1 << 1 << 0 << 2 - << int(QtTestTableView::MoveLeft) << int(Qt::NoModifier) + << QtTestTableView::MoveLeft << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveLeft, hidden column 0 (0,1)") << 4 << 4 << -1 << 0 << 0 << 1 - << int(QtTestTableView::MoveLeft) << int(Qt::NoModifier) + << QtTestTableView::MoveLeft << Qt::NoModifier << 0 << 1 << IntPair(0,0) << IntPair(0,0); // MovePrevious should in addition wrap QTest::newRow("MovePrevious (0,3)") << 4 << 4 << -1 << -1 << 0 << 3 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious (0,1)") << 4 << 4 << -1 << -1 << 0 << 1 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrap (1,0)") << 4 << 4 << -1 << -1 << 1 << 0 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrap, (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, hidden column 1 (0,2)") << 4 << 4 << -1 << 1 << 0 << 2 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrap, hidden column 3 (0,2)") << 4 << 4 << -1 << 3 << 0 << 2 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 1 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrapy, hidden column 0 (0,1)") << 4 << 4 << -1 << 0 << 0 << 1 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrap, hidden column 0, hidden row 0 (1,1)") << 4 << 4 << 0 << 0 << 1 << 1 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePrevious, wrap, hidden column 1, moved column from 0 to 3. (1,2)") << 4 << 4 << -1 << 1 << 1 << 2 - << int(QtTestTableView::MovePrevious) << int(Qt::NoModifier) + << QtTestTableView::MovePrevious << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,3); // MoveDown QTest::newRow("MoveDown (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 1 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveDown (3,0)") << 4 << 4 << -1 << -1 << 3 << 0 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 3 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveDown (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveDown, hidden row 1 (0,0)") << 4 << 4 << 1 << -1 << 0 << 0 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 2 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveDown, hidden row 3 (2,0)") << 4 << 4 << 3 << -1 << 2 << 0 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 2 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveDown, hidden row 0 hidden column 0 (0,0)") << 4 << 4 << 0 << 0 << 0 << 0 - << int(QtTestTableView::MoveDown) << int(Qt::NoModifier) + << QtTestTableView::MoveDown << Qt::NoModifier << 1 << 1 << IntPair(0,0) << IntPair(0,0); // MoveUp QTest::newRow("MoveUp (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveUp) << int(Qt::NoModifier) + << QtTestTableView::MoveUp << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveUp (3, 0)") << 4 << 4 << -1 << -1 << 3 << 0 - << int(QtTestTableView::MoveUp) << int(Qt::NoModifier) + << QtTestTableView::MoveUp << Qt::NoModifier << 2 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveUp (0,1)") << 4 << 4 << -1 << -1 << 0 << 1 - << int(QtTestTableView::MoveUp) << int(Qt::NoModifier) + << QtTestTableView::MoveUp << Qt::NoModifier << 0 << 1 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveUp, hidden row 1 (2,0)") << 4 << 4 << 1 << -1 << 2 << 0 - << int(QtTestTableView::MoveUp) << int(Qt::NoModifier) + << QtTestTableView::MoveUp << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveUp, hidden row (1,0)") << 4 << 4 << 0 << -1 << 1 << 0 - << int(QtTestTableView::MoveUp) << int(Qt::NoModifier) + << QtTestTableView::MoveUp << Qt::NoModifier << 1 << 0 << IntPair(0,0) << IntPair(0,0); // MoveHome QTest::newRow("MoveHome (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveHome) << int(Qt::NoModifier) + << QtTestTableView::MoveHome << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveHome (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveHome) << int(Qt::NoModifier) + << QtTestTableView::MoveHome << Qt::NoModifier << 3 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveHome, hidden column 0 (3,3)") << 4 << 4 << -1 << 0 << 3 << 3 - << int(QtTestTableView::MoveHome) << int(Qt::NoModifier) + << QtTestTableView::MoveHome << Qt::NoModifier << 3 << 1 << IntPair(0,0) << IntPair(0,0); // Use Ctrl modifier QTest::newRow("MoveHome + Ctrl (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveHome) << int(Qt::ControlModifier) + << QtTestTableView::MoveHome << Qt::ControlModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveHome + Ctrl (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveHome) << int(Qt::ControlModifier) + << QtTestTableView::MoveHome << Qt::ControlModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveHome + Ctrl, hidden column 0, hidden row 0 (3,3)") << 4 << 4 << 0 << 0 << 3 << 3 - << int(QtTestTableView::MoveHome) << int(Qt::ControlModifier) + << QtTestTableView::MoveHome << Qt::ControlModifier << 1 << 1 << IntPair(0,0) << IntPair(0,0); // MoveEnd QTest::newRow("MoveEnd (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveEnd) << int(Qt::NoModifier) + << QtTestTableView::MoveEnd << Qt::NoModifier << 0 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveEnd (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveEnd) << int(Qt::NoModifier) + << QtTestTableView::MoveEnd << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveEnd, hidden column (0,0)") << 4 << 4 << -1 << 3 << 0 << 0 - << int(QtTestTableView::MoveEnd) << int(Qt::NoModifier) + << QtTestTableView::MoveEnd << Qt::NoModifier << 0<< 2 << IntPair(0,0) << IntPair(0,0); // Use Ctrl modifier QTest::newRow("MoveEnd + Ctrl (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MoveEnd) << int(Qt::ControlModifier) + << QtTestTableView::MoveEnd << Qt::ControlModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveEnd + Ctrl (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MoveEnd) << int(Qt::ControlModifier) + << QtTestTableView::MoveEnd << Qt::ControlModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveEnd + Ctrl, hidden column 3 (0,0)") << 4 << 4 << -1 << 3 << 0 << 0 - << int(QtTestTableView::MoveEnd) << int(Qt::ControlModifier) + << QtTestTableView::MoveEnd << Qt::ControlModifier << 3 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MoveEnd + Ctrl, hidden column 3, hidden row 3 (0,0)") << 4 << 4 << 3 << 3 << 0 << 0 - << int(QtTestTableView::MoveEnd) << int(Qt::ControlModifier) + << QtTestTableView::MoveEnd << Qt::ControlModifier << 2 << 2 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePageUp (0,0)") << 4 << 4 << -1 << -1 << 0 << 0 - << int(QtTestTableView::MovePageUp) << 0 + << QtTestTableView::MovePageUp << Qt::NoModifier << 0 << 0 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePageUp (3,3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MovePageUp) << 0 + << QtTestTableView::MovePageUp << Qt::NoModifier << 0 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePageDown (3, 3)") << 4 << 4 << -1 << -1 << 3 << 3 - << int(QtTestTableView::MovePageDown) << 0 + << QtTestTableView::MovePageDown << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); QTest::newRow("MovePageDown (0, 3)") << 4 << 4 << -1 << -1 << 0 << 3 - << int(QtTestTableView::MovePageDown) << 0 + << QtTestTableView::MovePageDown << Qt::NoModifier << 3 << 3 << IntPair(0,0) << IntPair(0,0); } @@ -1148,8 +1067,8 @@ void tst_QTableView::moveCursor() QFETCH(int, hideColumn); QFETCH(int, startRow); QFETCH(int, startColumn); - QFETCH(int, cursorMoveAction); - QFETCH(int, modifier); + QFETCH(QtTestTableView::CursorAction, cursorMoveAction); + QFETCH(Qt::KeyboardModifier, modifier); QFETCH(int, expectedRow); QFETCH(int, expectedColumn); QFETCH(IntPair, moveRow); @@ -1174,8 +1093,7 @@ void tst_QTableView::moveCursor() QModelIndex index = model.index(startRow, startColumn); view.setCurrentIndex(index); - QModelIndex newIndex = view.doMoveCursor((QtTestTableView::CursorAction)cursorMoveAction, - (Qt::KeyboardModifiers)modifier); + QModelIndex newIndex = view.moveCursor(cursorMoveAction, modifier); // expected fails, task 119433 if(newIndex.row() == -1) return; @@ -1193,7 +1111,7 @@ void tst_QTableView::moveCursorStrikesBack_data() QTest::addColumn("startRow"); QTest::addColumn("startColumn"); - QTest::addColumn("cursorMoveActions"); + QTest::addColumn("cursorMoveActions"); QTest::addColumn("expectedRow"); QTest::addColumn("expectedColumn"); @@ -1201,70 +1119,84 @@ void tst_QTableView::moveCursorStrikesBack_data() << IntList() << (IntList() << 6) << QRect() - << 0 << 5 << (IntList() << int(QtTestTableView::MoveNext)) + << 0 << 5 + << CursorActionList{QtTestTableView::MoveNext} << 1 << 0; QTest::newRow("Last column disabled 2. Task QTBUG-3878") << -1 << -1 << IntList() << (IntList() << 6) << QRect() - << 1 << 0 << (IntList() << int(QtTestTableView::MovePrevious)) + << 1 << 0 + << CursorActionList{QtTestTableView::MovePrevious} << 0 << 5; QTest::newRow("Span, anchor column hidden") << -1 << 1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 2 << 0 << (IntList() << int(QtTestTableView::MoveNext)) + << 2 << 0 + << CursorActionList{QtTestTableView::MoveNext} << 2 << 1; QTest::newRow("Span, anchor column disabled") << -1 << -1 << IntList() << (IntList() << 1) << QRect(1, 2, 2, 3) - << 2 << 0 << (IntList() << int(QtTestTableView::MoveNext)) + << 2 << 0 + << CursorActionList{QtTestTableView::MoveNext} << 2 << 1; QTest::newRow("Span, anchor row hidden") << 2 << -1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 1 << 2 << (IntList() << int(QtTestTableView::MoveDown)) + << 1 << 2 + << CursorActionList{QtTestTableView::MoveDown} << 2 << 1; QTest::newRow("Span, anchor row disabled") << -1 << -1 << (IntList() << 2) << IntList() << QRect(1, 2, 2, 3) - << 1 << 2 << (IntList() << int(QtTestTableView::MoveDown)) + << 1 << 2 + << CursorActionList{QtTestTableView::MoveDown} << 2 << 1; QTest::newRow("Move through span right") << -1 << -1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 3 << 0 << (IntList() << int(QtTestTableView::MoveRight) << int(QtTestTableView::MoveRight)) + << 3 << 0 + << CursorActionList{QtTestTableView::MoveRight, + QtTestTableView::MoveRight} << 3 << 3; QTest::newRow("Move through span left") << -1 << -1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 3 << 3 << (IntList() << int(QtTestTableView::MoveLeft) << int(QtTestTableView::MoveLeft)) + << 3 << 3 + << CursorActionList{QtTestTableView::MoveLeft, + QtTestTableView::MoveLeft} << 3 << 0; QTest::newRow("Move through span down") << -1 << -1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 1 << 2 << (IntList() << int(QtTestTableView::MoveDown) << int(QtTestTableView::MoveDown)) + << 1 << 2 + << CursorActionList{QtTestTableView::MoveDown, + QtTestTableView::MoveDown} << 5 << 2; QTest::newRow("Move through span up") << -1 << -1 << IntList() << IntList() << QRect(1, 2, 2, 3) - << 5 << 2 << (IntList() << int(QtTestTableView::MoveUp) << int(QtTestTableView::MoveUp)) + << 5 << 2 + << CursorActionList{QtTestTableView::MoveUp, + QtTestTableView::MoveUp} << 1 << 2; IntList fullList; @@ -1275,42 +1207,48 @@ void tst_QTableView::moveCursorStrikesBack_data() << fullList << fullList << QRect() - << 1 << 0 << (IntList() << int(QtTestTableView::MoveNext)) + << 1 << 0 + << CursorActionList{QtTestTableView::MoveNext} << -1 << -1; QTest::newRow("All disabled, wrap backwards. => invalid index") << -1 << -1 << fullList << fullList << QRect() - << 1 << 0 << (IntList() << int(QtTestTableView::MovePrevious)) + << 1 << 0 + << CursorActionList{QtTestTableView::MovePrevious} << -1 << -1; QTest::newRow("Last column disabled, MoveEnd. QTBUG-72400") << -1 << -1 << IntList() << (IntList() << 6) << QRect() - << 0 << 0 << (IntList() << int(QtTestTableView::MoveEnd)) + << 0 << 0 + << CursorActionList{QtTestTableView::MoveEnd} << 0 << 5; QTest::newRow("First column disabled, MoveHome. QTBUG-72400") << -1 << -1 << IntList() << (IntList() << 0) << QRect() - << 0 << 6 << (IntList() << int(QtTestTableView::MoveHome)) + << 0 << 6 + << CursorActionList{QtTestTableView::MoveHome} << 0 << 1; QTest::newRow("First row disabled, MovePageUp. QTBUG-72400") << -1 << -1 << (IntList() << 0) << IntList() << QRect() - << 2 << 0 << (IntList() << int(QtTestTableView::MovePageUp)) + << 2 << 0 + << CursorActionList{QtTestTableView::MovePageUp} << 1 << 0; QTest::newRow("Last row disabled, MovePageDown. QTBUG-72400") << -1 << -1 << (IntList() << 6) << IntList() << QRect() - << 4 << 0 << (IntList() << int(QtTestTableView::MovePageDown)) + << 4 << 0 + << CursorActionList{QtTestTableView::MovePageDown} << 5 << 0; } @@ -1318,13 +1256,13 @@ void tst_QTableView::moveCursorStrikesBack() { QFETCH(int, hideRow); QFETCH(int, hideColumn); - QFETCH(IntList, disableRows); - QFETCH(IntList, disableColumns); + QFETCH(const IntList, disableRows); + QFETCH(const IntList, disableColumns); QFETCH(QRect, span); QFETCH(int, startRow); QFETCH(int, startColumn); - QFETCH(IntList, cursorMoveActions); + QFETCH(const CursorActionList, cursorMoveActions); QFETCH(int, expectedRow); QFETCH(int, expectedColumn); @@ -1344,15 +1282,15 @@ void tst_QTableView::moveCursorStrikesBack() QModelIndex index = model.index(startRow, startColumn); view.setCurrentIndex(index); - foreach (int row, disableRows) + for (int row : disableRows) model.disableRow(row); - foreach (int column, disableColumns) + for (int column : disableColumns) model.disableColumn(column); int newRow = -1; int newColumn = -1; - foreach (int cursorMoveAction, cursorMoveActions) { - QModelIndex newIndex = view.doMoveCursor((QtTestTableView::CursorAction)cursorMoveAction, 0); + for (auto cursorMoveAction : cursorMoveActions) { + QModelIndex newIndex = view.moveCursor(cursorMoveAction, nullptr); view.setCurrentIndex(newIndex); newRow = newIndex.row(); newColumn = newIndex.column(); @@ -1523,7 +1461,7 @@ void tst_QTableView::selection_data() QTest::addColumn("y"); QTest::addColumn("width"); QTest::addColumn("height"); - QTest::addColumn("command"); + QTest::addColumn("command"); QTest::addColumn("selectedCount"); // ### make this more detailed QTest::newRow("no span, no hidden, no moved, 3x3 select") @@ -1535,7 +1473,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 9; // selected count QTest::newRow("row span, no hidden, no moved, 3x3 select") @@ -1547,7 +1485,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 8; // selected count QTest::newRow("col span, no hidden, no moved, 3x3 select") @@ -1559,7 +1497,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 8; // selected count QTest::newRow("no span, row hidden, no moved, 3x3 select") @@ -1571,7 +1509,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 9; // selected count QTest::newRow("no span, col hidden, no moved, 3x3 select") @@ -1583,7 +1521,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 9; // selected count QTest::newRow("no span, no hidden, row moved, 3x3 select") @@ -1595,7 +1533,7 @@ void tst_QTableView::selection_data() << -1 << -1 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 9; // selected count QTest::newRow("no span, no hidden, col moved, 3x3 select") @@ -1607,7 +1545,7 @@ void tst_QTableView::selection_data() << 1 << 3 // move col << 40 << 40 // cell size << 20 << 20 << 80 << 80 // rect - << int(QItemSelectionModel::Select) // command + << QItemSelectionModel::Select // command << 9; // selected count } @@ -1631,7 +1569,7 @@ void tst_QTableView::selection() QFETCH(int, y); QFETCH(int, width); QFETCH(int, height); - QFETCH(int, command); + QFETCH(QItemSelectionModel::SelectionFlag, command); QFETCH(int, selectedCount); QtTestTableModel model(rowCount, columnCount); @@ -1653,8 +1591,7 @@ void tst_QTableView::selection() for (int c = 0; c < columnCount; ++c) view.setColumnWidth(c, columnWidth); - view.setSelection(QRect(x, y, width, height), - QItemSelectionModel::SelectionFlags(command)); + view.setSelection(QRect(x, y, width, height), command); QCOMPARE(view.selectedIndexes().count(), selectedCount); } @@ -1664,92 +1601,92 @@ void tst_QTableView::selectRow_data() QTest::addColumn("rowCount"); QTest::addColumn("columnCount"); QTest::addColumn("row"); - QTest::addColumn("mode"); - QTest::addColumn("behavior"); + QTest::addColumn("mode"); + QTest::addColumn("behavior"); QTest::addColumn("selectedItems"); QTest::newRow("SingleSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectItems << 0; QTest::newRow("SingleSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectRows << 10; QTest::newRow("SingleSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectColumns << 0; QTest::newRow("MultiSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("MultiSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectRows << 10; QTest::newRow("MultiSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectColumns << 0; QTest::newRow("ExtendedSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("ExtendedSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectRows << 10; QTest::newRow("ExtendedSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectColumns << 0; QTest::newRow("ContiguousSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("ContiguousSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectRows << 10; QTest::newRow("ContiguousSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectColumns << 0; } @@ -1758,16 +1695,16 @@ void tst_QTableView::selectRow() QFETCH(int, rowCount); QFETCH(int, columnCount); QFETCH(int, row); - QFETCH(int, mode); - QFETCH(int, behavior); + QFETCH(QAbstractItemView::SelectionMode, mode); + QFETCH(QAbstractItemView::SelectionBehavior, behavior); QFETCH(int, selectedItems); QtTestTableModel model(rowCount, columnCount); QTableView view; view.setModel(&model); - view.setSelectionMode((QAbstractItemView::SelectionMode)mode); - view.setSelectionBehavior((QAbstractItemView::SelectionBehavior)behavior); + view.setSelectionMode(mode); + view.setSelectionBehavior(behavior); QCOMPARE(view.selectionModel()->selectedIndexes().count(), 0); @@ -1785,92 +1722,92 @@ void tst_QTableView::selectColumn_data() QTest::addColumn("rowCount"); QTest::addColumn("columnCount"); QTest::addColumn("column"); - QTest::addColumn("mode"); - QTest::addColumn("behavior"); + QTest::addColumn("mode"); + QTest::addColumn("behavior"); QTest::addColumn("selectedItems"); QTest::newRow("SingleSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectItems << 0; QTest::newRow("SingleSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectRows << 0; QTest::newRow("SingleSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::SingleSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::SingleSelection + << QAbstractItemView::SelectColumns << 10; QTest::newRow("MultiSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("MultiSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectRows << 0; QTest::newRow("MultiSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::MultiSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::MultiSelection + << QAbstractItemView::SelectColumns << 10; QTest::newRow("ExtendedSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("ExtendedSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectRows << 0; QTest::newRow("ExtendedSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::ExtendedSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::ExtendedSelection + << QAbstractItemView::SelectColumns << 10; QTest::newRow("ContiguousSelection and SelectItems") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectItems + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectItems << 10; QTest::newRow("ContiguousSelection and SelectRows") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectRows + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectRows << 0; QTest::newRow("ContiguousSelection and SelectColumns") << 10 << 10 << 0 - << (int)QAbstractItemView::ContiguousSelection - << (int)QAbstractItemView::SelectColumns + << QAbstractItemView::ContiguousSelection + << QAbstractItemView::SelectColumns << 10; } @@ -1879,16 +1816,16 @@ void tst_QTableView::selectColumn() QFETCH(int, rowCount); QFETCH(int, columnCount); QFETCH(int, column); - QFETCH(int, mode); - QFETCH(int, behavior); + QFETCH(QAbstractItemView::SelectionMode, mode); + QFETCH(QAbstractItemView::SelectionBehavior, behavior); QFETCH(int, selectedItems); QtTestTableModel model(rowCount, columnCount); QTableView view; view.setModel(&model); - view.setSelectionMode((QAbstractItemView::SelectionMode)mode); - view.setSelectionBehavior((QAbstractItemView::SelectionBehavior)behavior); + view.setSelectionMode(mode); + view.setSelectionBehavior(behavior); QCOMPARE(view.selectionModel()->selectedIndexes().count(), 0); @@ -1988,9 +1925,9 @@ void tst_QTableView::selectall_data() << 100; // selected count } -void QTest__keySequence(QWidget* widget, QKeySequence ks) +void QTest__keySequence(QWidget* widget, const QKeySequence &ks) { - for (int i=0; i("rowCount"); QTest::addColumn("rowHeight"); QTest::addColumn("row"); - QTest::addColumn("verticalScrollMode"); + QTest::addColumn("verticalScrollMode"); QTest::addColumn("verticalScrollValue"); QTest::addColumn("rowViewportPosition"); QTest::newRow("row 0, scroll per item 0") - << 10 << 40 << 0 << int(QAbstractItemView::ScrollPerItem) << 0 << 0; + << 10 << 40 << 0 << QAbstractItemView::ScrollPerItem << 0 << 0; QTest::newRow("row 1, scroll per item, 0") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerItem) << 0 << 1 * 40; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerItem << 0 << 1 * 40; QTest::newRow("row 1, scroll per item, 1") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerItem) << 1 << 0; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerItem << 1 << 0; QTest::newRow("row 5, scroll per item, 0") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerItem) << 0 << 5 * 40; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerItem << 0 << 5 * 40; QTest::newRow("row 5, scroll per item, 5") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerItem) << 5 << 0; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerItem << 5 << 0; QTest::newRow("row 9, scroll per item, 0") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerItem) << 0 << 9 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerItem << 0 << 9 * 40; QTest::newRow("row 9, scroll per item, 5") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerItem) << 5 << 4 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerItem << 5 << 4 * 40; QTest::newRow("row 0, scroll per pixel 0") - << 10 << 40 << 0 << int(QAbstractItemView::ScrollPerPixel) << 0 << 0; + << 10 << 40 << 0 << QAbstractItemView::ScrollPerPixel << 0 << 0; QTest::newRow("row 1, scroll per pixel, 0") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerPixel) << 0 << 1 * 40; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerPixel << 0 << 1 * 40; QTest::newRow("row 1, scroll per pixel, 1") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerPixel) << 1 * 40 << 0; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerPixel << 1 * 40 << 0; QTest::newRow("row 5, scroll per pixel, 0") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerPixel) << 0 << 5 * 40; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerPixel << 0 << 5 * 40; QTest::newRow("row 5, scroll per pixel, 5") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerPixel) << 5 * 40 << 0; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerPixel << 5 * 40 << 0; QTest::newRow("row 9, scroll per pixel, 0") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerPixel) << 0 << 9 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerPixel << 0 << 9 * 40; QTest::newRow("row 9, scroll per pixel, 5") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerPixel) << 5 * 40 << 4 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerPixel << 5 * 40 << 4 * 40; } void tst_QTableView::rowViewportPosition() @@ -2352,7 +2288,7 @@ void tst_QTableView::rowViewportPosition() QFETCH(int, rowCount); QFETCH(int, rowHeight); QFETCH(int, row); - QFETCH(int, verticalScrollMode); + QFETCH(QAbstractItemView::ScrollMode, verticalScrollMode); QFETCH(int, verticalScrollValue); QFETCH(int, rowViewportPosition); @@ -2366,7 +2302,7 @@ void tst_QTableView::rowViewportPosition() for (int r = 0; r < rowCount; ++r) view.setRowHeight(r, rowHeight); - view.setVerticalScrollMode((QAbstractItemView::ScrollMode)verticalScrollMode); + view.setVerticalScrollMode(verticalScrollMode); view.verticalScrollBar()->setValue(verticalScrollValue); #ifdef Q_OS_WINRT @@ -2471,51 +2407,51 @@ void tst_QTableView::columnViewportPosition_data() QTest::addColumn("columnCount"); QTest::addColumn("columnWidth"); QTest::addColumn("column"); - QTest::addColumn("horizontalScrollMode"); + QTest::addColumn("horizontalScrollMode"); QTest::addColumn("horizontalScrollValue"); QTest::addColumn("columnViewportPosition"); QTest::newRow("column 0, scroll per item 0") - << 10 << 40 << 0 << int(QAbstractItemView::ScrollPerItem) << 0 << 0; + << 10 << 40 << 0 << QAbstractItemView::ScrollPerItem << 0 << 0; QTest::newRow("column 1, scroll per item, 0") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerItem) << 0 << 1 * 40; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerItem << 0 << 1 * 40; QTest::newRow("column 1, scroll per item, 1") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerItem) << 1 << 0; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerItem << 1 << 0; QTest::newRow("column 5, scroll per item, 0") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerItem) << 0 << 5 * 40; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerItem << 0 << 5 * 40; QTest::newRow("column 5, scroll per item, 5") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerItem) << 5 << 0; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerItem << 5 << 0; QTest::newRow("column 9, scroll per item, 0") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerItem) << 0 << 9 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerItem << 0 << 9 * 40; QTest::newRow("column 9, scroll per item, 5") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerItem) << 5 << 4 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerItem << 5 << 4 * 40; QTest::newRow("column 0, scroll per pixel 0") - << 10 << 40 << 0 << int(QAbstractItemView::ScrollPerPixel) << 0 << 0; + << 10 << 40 << 0 << QAbstractItemView::ScrollPerPixel << 0 << 0; QTest::newRow("column 1, scroll per pixel 0") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerPixel) << 0 << 1 * 40; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerPixel << 0 << 1 * 40; QTest::newRow("column 1, scroll per pixel 1") - << 10 << 40 << 1 << int(QAbstractItemView::ScrollPerPixel) << 1 * 40 << 0; + << 10 << 40 << 1 << QAbstractItemView::ScrollPerPixel << 1 * 40 << 0; QTest::newRow("column 5, scroll per pixel 0") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerPixel) << 0 << 5 * 40; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerPixel << 0 << 5 * 40; QTest::newRow("column 5, scroll per pixel 5") - << 10 << 40 << 5 << int(QAbstractItemView::ScrollPerPixel) << 5 * 40 << 0; + << 10 << 40 << 5 << QAbstractItemView::ScrollPerPixel << 5 * 40 << 0; QTest::newRow("column 9, scroll per pixel 0") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerPixel) << 0 << 9 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerPixel << 0 << 9 * 40; QTest::newRow("column 9, scroll per pixel 5") - << 10 << 40 << 9 << int(QAbstractItemView::ScrollPerPixel) << 5 * 40 << 4 * 40; + << 10 << 40 << 9 << QAbstractItemView::ScrollPerPixel << 5 * 40 << 4 * 40; } void tst_QTableView::columnViewportPosition() @@ -2523,7 +2459,7 @@ void tst_QTableView::columnViewportPosition() QFETCH(int, columnCount); QFETCH(int, columnWidth); QFETCH(int, column); - QFETCH(int, horizontalScrollMode); + QFETCH(QAbstractItemView::ScrollMode, horizontalScrollMode); QFETCH(int, horizontalScrollValue); QFETCH(int, columnViewportPosition); @@ -2537,7 +2473,7 @@ void tst_QTableView::columnViewportPosition() for (int c = 0; c < columnCount; ++c) view.setColumnWidth(c, columnWidth); - view.setHorizontalScrollMode((QAbstractItemView::ScrollMode)horizontalScrollMode); + view.setHorizontalScrollMode(horizontalScrollMode); view.horizontalScrollBar()->setValue(horizontalScrollValue); #ifdef Q_OS_WINRT @@ -2737,8 +2673,8 @@ void tst_QTableView::sortingEnabled() void tst_QTableView::scrollTo_data() { - QTest::addColumn("verticalScrollMode"); - QTest::addColumn("horizontalScrollMode"); + QTest::addColumn("verticalScrollMode"); + QTest::addColumn("horizontalScrollMode"); QTest::addColumn("rowCount"); QTest::addColumn("columnCount"); QTest::addColumn("rowHeight"); @@ -2751,51 +2687,51 @@ void tst_QTableView::scrollTo_data() QTest::addColumn("columnSpan"); QTest::addColumn("horizontalScroll"); QTest::addColumn("verticalScroll"); - QTest::addColumn("scrollHint"); + QTest::addColumn("scrollHint"); QTest::addColumn("expectedHorizontalScroll"); QTest::addColumn("expectedVerticalScroll"); QTest::newRow("no hidden, no span, no scroll, per item") - << (int)QAbstractItemView::ScrollPerItem - << (int)QAbstractItemView::ScrollPerItem + << QAbstractItemView::ScrollPerItem + << QAbstractItemView::ScrollPerItem << 10 << 10 // table << 80 << 80 // size << -1 << -1 // hide << 0 << 0 // cell << 1 << 1 // span << 0 << 0 // scroll - << (int)QAbstractItemView::PositionAtTop + << QAbstractItemView::PositionAtTop << 0 << 0; // expected QTest::newRow("no hidden, no span, no scroll, per pixel") - << (int)QAbstractItemView::ScrollPerPixel - << (int)QAbstractItemView::ScrollPerPixel + << QAbstractItemView::ScrollPerPixel + << QAbstractItemView::ScrollPerPixel << 10 << 10 // table << 80 << 80 // size << -1 << -1 // hide << 0 << 0 // cell << 1 << 1 // span << 0 << 0 // scroll - << (int)QAbstractItemView::PositionAtTop + << QAbstractItemView::PositionAtTop << 0 << 0; // expected QTest::newRow("hidden, no span, no scroll, per item") - << (int)QAbstractItemView::ScrollPerItem - << (int)QAbstractItemView::ScrollPerItem + << QAbstractItemView::ScrollPerItem + << QAbstractItemView::ScrollPerItem << 10 << 10 // table << 80 << 80 // size << 3 << 3 // hide << 5 << 5 // cell << 1 << 1 // span << 0 << 0 // scroll - << (int)QAbstractItemView::PositionAtTop + << QAbstractItemView::PositionAtTop << 4 << 4; // expected } void tst_QTableView::scrollTo() { - QFETCH(int, horizontalScrollMode); - QFETCH(int, verticalScrollMode); + QFETCH(QAbstractItemView::ScrollMode, horizontalScrollMode); + QFETCH(QAbstractItemView::ScrollMode, verticalScrollMode); QFETCH(int, rowCount); QFETCH(int, columnCount); QFETCH(int, rowHeight); @@ -2808,7 +2744,7 @@ void tst_QTableView::scrollTo() QFETCH(int, columnSpan); QFETCH(int, horizontalScroll); QFETCH(int, verticalScroll); - QFETCH(int, scrollHint); + QFETCH(QAbstractItemView::ScrollHint, scrollHint); QFETCH(int, expectedHorizontalScroll); QFETCH(int, expectedVerticalScroll); @@ -2828,8 +2764,8 @@ void tst_QTableView::scrollTo() view.setSpan(row, column, rowSpan, columnSpan); view.hideRow(hiddenRow); view.hideColumn(hiddenColumn); - view.setHorizontalScrollMode((QAbstractItemView::ScrollMode)horizontalScrollMode); - view.setVerticalScrollMode((QAbstractItemView::ScrollMode)verticalScrollMode); + view.setHorizontalScrollMode(horizontalScrollMode); + view.setVerticalScrollMode(verticalScrollMode); for (int r = 0; r < rowCount; ++r) view.setRowHeight(r, rowHeight); @@ -2841,7 +2777,7 @@ void tst_QTableView::scrollTo() QModelIndex index = model.index(row, column); QVERIFY(index.isValid()); - view.scrollTo(index, (QAbstractItemView::ScrollHint)scrollHint); + view.scrollTo(index, scrollHint); QTRY_COMPARE(view.verticalScrollBar()->value(), expectedVerticalScroll); QTRY_COMPARE(view.horizontalScrollBar()->value(), expectedHorizontalScroll); } @@ -3146,8 +3082,6 @@ void tst_QTableView::span() VERIFY_SPANS_CONSISTENCY(&view); } -typedef QVector SpanList; - void tst_QTableView::spans_data() { QTest::addColumn("rows"); @@ -3275,7 +3209,7 @@ void tst_QTableView::spans() { QFETCH(int, rows); QFETCH(int, columns); - QFETCH(SpanList, spans); + QFETCH(const SpanList, spans); QFETCH(bool, hideRowLastRowOfFirstSpan); QFETCH(QPoint, pos); QFETCH(int, expectedRowSpan); @@ -3287,10 +3221,8 @@ void tst_QTableView::spans() view.setModel(&model); view.show(); - for (int i = 0; i < spans.count(); ++i) { - QRect sp = spans.at(i); + for (const auto &sp : spans) view.setSpan(sp.x(), sp.y(), sp.width(), sp.height()); - } if (hideRowLastRowOfFirstSpan) { view.setRowHidden(spans.at(0).bottom(), true); @@ -3384,32 +3316,34 @@ void tst_QTableView::spansAfterRowRemoval() QtTestTableView view; view.setModel(&model); - QList spans; - spans << QRect(0, 1, 1, 2) - << QRect(1, 2, 1, 2) - << QRect(2, 2, 1, 5) - << QRect(2, 8, 1, 2) - << QRect(3, 4, 1, 2) - << QRect(4, 4, 1, 4) - << QRect(5, 6, 1, 3) - << QRect(6, 7, 1, 3); - foreach (QRect span, spans) + static const QRect spans[] = { + {0, 1, 1, 2}, + {1, 2, 1, 2}, + {2, 2, 1, 5}, + {2, 8, 1, 2}, + {3, 4, 1, 2}, + {4, 4, 1, 4}, + {5, 6, 1, 3}, + {6, 7, 1, 3} + }; + for (const QRect &span : spans) view.setSpan(span.top(), span.left(), span.height(), span.width()); view.show(); QVERIFY(QTest::qWaitForWindowActive(&view)); view.model()->removeRows(3, 3); - QList expectedSpans; - expectedSpans << QRect(0, 1, 1, 2) - << QRect(1, 2, 1, 1) - << QRect(2, 2, 1, 2) - << QRect(2, 5, 1, 2) - << QRect(3, 4, 1, 1) - << QRect(4, 3, 1, 2) - << QRect(5, 3, 1, 3) - << QRect(6, 4, 1, 3); - foreach (QRect span, expectedSpans) { + static const QRect expectedSpans[] = { + {0, 1, 1, 2}, + {1, 2, 1, 1}, + {2, 2, 1, 2}, + {2, 5, 1, 2}, + {3, 4, 1, 1}, + {4, 3, 1, 2}, + {5, 3, 1, 3}, + {6, 4, 1, 3} + }; + for (const QRect &span : expectedSpans) { QCOMPARE(view.columnSpan(span.top(), span.left()), span.width()); QCOMPARE(view.rowSpan(span.top(), span.left()), span.height()); } @@ -3424,32 +3358,34 @@ void tst_QTableView::spansAfterColumnRemoval() view.setModel(&model); // Same set as above just swapping columns and rows. - QList spans; - spans << QRect(0, 1, 1, 2) - << QRect(1, 2, 1, 2) - << QRect(2, 2, 1, 5) - << QRect(2, 8, 1, 2) - << QRect(3, 4, 1, 2) - << QRect(4, 4, 1, 4) - << QRect(5, 6, 1, 3) - << QRect(6, 7, 1, 3); - foreach (QRect span, spans) - view.setSpan(span.left(), span.top(), span.width(), span.height()); + static const QRect spans[] = { + {0, 1, 1, 2}, + {1, 2, 1, 2}, + {2, 2, 1, 5}, + {2, 8, 1, 2}, + {3, 4, 1, 2}, + {4, 4, 1, 4}, + {5, 6, 1, 3}, + {6, 7, 1, 3} + }; + for (const QRect &span : spans) + view.setSpan(span.left(), span.top(), span.width(), span.height()); view.show(); QVERIFY(QTest::qWaitForWindowActive(&view)); view.model()->removeColumns(3, 3); - QList expectedSpans; - expectedSpans << QRect(0, 1, 1, 2) - << QRect(1, 2, 1, 1) - << QRect(2, 2, 1, 2) - << QRect(2, 5, 1, 2) - << QRect(3, 4, 1, 1) - << QRect(4, 3, 1, 2) - << QRect(5, 3, 1, 3) - << QRect(6, 4, 1, 3); - foreach (QRect span, expectedSpans) { + static const QRect expectedSpans[] = { + {0, 1, 1, 2}, + {1, 2, 1, 1}, + {2, 2, 1, 2}, + {2, 5, 1, 2}, + {3, 4, 1, 1}, + {4, 3, 1, 2}, + {5, 3, 1, 3}, + {6, 4, 1, 3} + }; + for (const QRect &span : expectedSpans) { QCOMPARE(view.columnSpan(span.left(), span.top()), span.height()); QCOMPARE(view.rowSpan(span.left(), span.top()), span.width()); } @@ -3457,12 +3393,10 @@ void tst_QTableView::spansAfterColumnRemoval() VERIFY_SPANS_CONSISTENCY(&view); } -Q_DECLARE_METATYPE(Qt::Key) - void tst_QTableView::editSpanFromDirections_data() { - QTest::addColumn >("keyPresses"); - QTest::addColumn >("model"); + QTest::addColumn("keyPresses"); + QTest::addColumn>("model"); QTest::addColumn("row"); QTest::addColumn("column"); QTest::addColumn("rowSpan"); @@ -3481,8 +3415,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+---+ | | ^ | +---+---+ */ - QList keyPresses; - keyPresses << Qt::Key_Right << Qt::Key_PageDown << Qt::Key_Up; + KeyList keyPresses {Qt::Key_Right, Qt::Key_PageDown, Qt::Key_Up}; QSharedPointer model(new QStandardItemModel(4, 2)); QTest::newRow("row span, bottom up") << keyPresses << model << 1 << 1 << 2 << 1 << model->index(2, 1) << model->index(1, 1); @@ -3496,8 +3429,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+---+ | | | +---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_Right << Qt::Key_Down; + keyPresses = {Qt::Key_Right, Qt::Key_Down}; model = QSharedPointer::create(4, 2); QTest::newRow("row span, top down") << keyPresses << model << 1 << 1 << 2 << 1 << model->index(1, 1) << model->index(1, 1); @@ -3509,8 +3441,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+ +---+ | | | | +---+---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_End << Qt::Key_Down << Qt::Key_Left; + keyPresses = {Qt::Key_End, Qt::Key_Down, Qt::Key_Left}; model = QSharedPointer::create(3, 3); QTest::newRow("row span, right to left") << keyPresses << model << 1 << 1 << 2 << 1 << model->index(1, 1) << model->index(1, 1); @@ -3522,8 +3453,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+ +---+ | > | c | | +---+---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_PageDown << Qt::Key_Right; + keyPresses = {Qt::Key_PageDown, Qt::Key_Right}; model = QSharedPointer::create(3, 3); QTest::newRow("row span, left to right") << keyPresses << model << 1 << 1 << 2 << 1 << model->index(2, 1) << model->index(1, 1); @@ -3535,8 +3465,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+---+---+ | ^ | | | +---+---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_PageDown << Qt::Key_Up; + keyPresses = {Qt::Key_PageDown, Qt::Key_Up}; model = QSharedPointer::create(3, 3); QTest::newRow("col span, bottom up") << keyPresses << model << 1 << 0 << 1 << 3 << model->index(1, 0) << model->index(1, 0); @@ -3548,8 +3477,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+---+---+ | | ^ | | +---+---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_PageDown << Qt::Key_Right << Qt::Key_Up; + keyPresses = {Qt::Key_PageDown, Qt::Key_Right, Qt::Key_Up}; model = QSharedPointer::create(3, 3); QTest::newRow("col span, bottom up #2") << keyPresses << model << 1 << 0 << 1 << 3 << model->index(1, 1) << model->index(1, 0); @@ -3561,8 +3489,7 @@ void tst_QTableView::editSpanFromDirections_data() +---+---+---+ | | | | +---+---+---+ */ - keyPresses.clear(); - keyPresses << Qt::Key_End << Qt::Key_Down; + keyPresses = {Qt::Key_End, Qt::Key_Down}; model = QSharedPointer::create(3, 3); QTest::newRow("col span, top down") << keyPresses << model << 1 << 0 << 1 << 3 << model->index(1, 2) << model->index(1, 0); @@ -3571,12 +3498,10 @@ void tst_QTableView::editSpanFromDirections_data() class TableViewWithCursorExposed : public QTableView { public: - TableViewWithCursorExposed() : - QTableView() { - } + using QTableView::QTableView; -public: - QModelIndex visualCursorIndex() { + QModelIndex visualCursorIndex() + { QTableViewPrivate *d = static_cast(qt_widget_private(this)); return d->model->index(d->visualCursor.y(), d->visualCursor.x()); } @@ -3584,7 +3509,7 @@ public: void tst_QTableView::editSpanFromDirections() { - QFETCH(QList, keyPresses); + QFETCH(const KeyList, keyPresses); QFETCH(QSharedPointer, model); QFETCH(int, row); QFETCH(int, column); @@ -3602,9 +3527,8 @@ void tst_QTableView::editSpanFromDirections() view.show(); QVERIFY(QTest::qWaitForWindowActive(&view)); - foreach (Qt::Key key, keyPresses) { + for (Qt::Key key : keyPresses) QTest::keyClick(&view, key); - } QCOMPARE(view.visualCursorIndex(), expectedVisualCursorIndex); QCOMPARE(view.selectionModel()->currentIndex(), expectedEditedIndex); @@ -3613,21 +3537,21 @@ void tst_QTableView::editSpanFromDirections() QTRY_COMPARE(view.model()->data(expectedEditedIndex).toString(), QLatin1String("x")); } -class Model : public QAbstractTableModel { - -Q_OBJECT - +class Model : public QAbstractTableModel +{ + Q_OBJECT public: - Model(QObject * parent = 0) : QAbstractTableModel(parent) { - } + using QAbstractTableModel::QAbstractTableModel; - int rowCount(const QModelIndex &) const { + int rowCount(const QModelIndex &) const override + { return rows; } - int columnCount(const QModelIndex &) const { + int columnCount(const QModelIndex &) const override + { return columns; } - QVariant data(const QModelIndex &, int) const + QVariant data(const QModelIndex &, int) const override { return QVariant(); } @@ -3637,8 +3561,8 @@ public: endResetModel(); } - int rows; - int columns; + int rows = 0; + int columns = 0; }; void tst_QTableView::checkHeaderReset() @@ -3662,7 +3586,7 @@ void tst_QTableView::checkHeaderMinSize() //viewport. QTableView view; QStringListModel m; - m.setStringList( QStringList() << QLatin1String("one cell is enough")); + m.setStringList({QLatin1String("one cell is enough")}); view.setModel(&m); //setting the minimum height on the horizontal header @@ -3693,31 +3617,29 @@ void tst_QTableView::resizeToContents() table2.verticalHeader()->setVisible(false); - for(int i = 0;ifocusWidget(), Qt::Key_Tab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Tab); QTRY_VERIFY(!window.hasFocus()); QVERIFY(view->hasFocus()); QVERIFY(!edit->hasFocus()); // tab to edit - QTest::keyPress(qApp->focusWidget(), Qt::Key_Tab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Tab); QTRY_VERIFY(edit->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!view->hasFocus()); } // backtab to view - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(view->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!edit->hasFocus()); // backtab to edit - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(edit->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!view->hasFocus()); - QStandardItemModel *model = new QStandardItemModel; - view->setModel(model); + QStandardItemModel model; + view->setModel(&model); // backtab to view - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(view->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!edit->hasFocus()); // backtab to edit - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(edit->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!view->hasFocus()); - model->insertRow(0, new QStandardItem("Hei")); - model->insertRow(0, new QStandardItem("Hei")); - model->insertRow(0, new QStandardItem("Hei")); + model.insertRow(0, new QStandardItem("Hei")); + model.insertRow(0, new QStandardItem("Hei")); + model.insertRow(0, new QStandardItem("Hei")); // backtab to view - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(view->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!edit->hasFocus()); // backtab to edit doesn't work - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QVERIFY(!window.hasFocus()); QVERIFY(view->hasFocus()); QVERIFY(!edit->hasFocus()); @@ -3805,41 +3727,38 @@ void tst_QTableView::tabFocus() view->setTabKeyNavigation(false); // backtab to edit - QTest::keyPress(qApp->focusWidget(), Qt::Key_Backtab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Backtab); QTRY_VERIFY(edit->hasFocus()); QVERIFY(!window.hasFocus()); QVERIFY(!view->hasFocus()); - QTest::keyPress(qApp->focusWidget(), Qt::Key_Tab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Tab); QTRY_VERIFY(view->hasFocus()); - QTest::keyPress(qApp->focusWidget(), Qt::Key_Tab); + QTest::keyPress(QApplication::focusWidget(), Qt::Key_Tab); QTRY_VERIFY(edit->hasFocus()); - - delete model; } class BigModel : public QAbstractTableModel { Q_OBJECT public: - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const + QVariant data(const QModelIndex &index, + int role = Qt::DisplayRole) const override { if (role == Qt::DisplayRole) return QString::number(index.column()) + QLatin1String(" - ") + QString::number(index.row()); return QVariant(); } - - int rowCount(const QModelIndex & parent = QModelIndex()) const + int rowCount(const QModelIndex &parent = QModelIndex()) const override { - Q_UNUSED(parent); + Q_UNUSED(parent) return 10000000; } - int columnCount(const QModelIndex & parent = QModelIndex()) const + int columnCount(const QModelIndex &parent = QModelIndex()) const override { - Q_UNUSED(parent); + Q_UNUSED(parent) return 20000000; } }; @@ -3868,7 +3787,7 @@ void tst_QTableView::selectionSignal() view.resize(200, 200); view.show(); QVERIFY(QTest::qWaitForWindowExposed(&view)); - QTest::mouseClick(view.viewport(), Qt::LeftButton, 0, view.visualRect(model.index(2, 0)).center()); + QTest::mouseClick(view.viewport(), Qt::LeftButton, {}, view.visualRect(model.index(2, 0)).center()); } void tst_QTableView::setCurrentIndex() @@ -3894,14 +3813,14 @@ void tst_QTableView::setCurrentIndex() class task173773_EventFilter : public QObject { - int paintEventCount_; + int paintEventCount_ = 0; public: - task173773_EventFilter() : paintEventCount_(0) {} + using QObject::QObject; int paintEventCount() const { return paintEventCount_; } private: - bool eventFilter(QObject *obj, QEvent *e) + bool eventFilter(QObject *obj, QEvent *e) override { - Q_UNUSED(obj); + Q_UNUSED(obj) if (e->type() == QEvent::Paint) ++paintEventCount_; return false; @@ -4030,25 +3949,25 @@ void tst_QTableView::task248688_autoScrollNavigation() #if QT_CONFIG(wheelevent) void tst_QTableView::mouseWheel_data() { - QTest::addColumn("scrollMode"); + QTest::addColumn("scrollMode"); QTest::addColumn("delta"); QTest::addColumn("horizontalPositon"); QTest::addColumn("verticalPosition"); QTest::newRow("scroll up per item") - << int(QAbstractItemView::ScrollPerItem) << 120 - << 10 - qApp->wheelScrollLines() << 10 - qApp->wheelScrollLines(); + << QAbstractItemView::ScrollPerItem << 120 + << 10 - QApplication::wheelScrollLines() << 10 - QApplication::wheelScrollLines(); QTest::newRow("scroll down per item") - << int(QAbstractItemView::ScrollPerItem) << -120 - << 10 + qApp->wheelScrollLines() << 10 + qApp->wheelScrollLines(); + << QAbstractItemView::ScrollPerItem << -120 + << 10 + QApplication::wheelScrollLines() << 10 + QApplication::wheelScrollLines(); QTest::newRow("scroll down per pixel") - << int(QAbstractItemView::ScrollPerPixel) << -120 - << 10 + qApp->wheelScrollLines() * 91 << 10 + qApp->wheelScrollLines() * 46; + << QAbstractItemView::ScrollPerPixel << -120 + << 10 + QApplication::wheelScrollLines() * 91 << 10 + QApplication::wheelScrollLines() * 46; } void tst_QTableView::mouseWheel() { - QFETCH(int, scrollMode); + QFETCH(QAbstractItemView::ScrollMode, scrollMode); QFETCH(int, delta); QFETCH(int, horizontalPositon); QFETCH(int, verticalPosition); @@ -4068,8 +3987,8 @@ void tst_QTableView::mouseWheel() for (int c = 0; c < 100; ++c) view.setColumnWidth(c, 100); - view.setHorizontalScrollMode((QAbstractItemView::ScrollMode)scrollMode); - view.setVerticalScrollMode((QAbstractItemView::ScrollMode)scrollMode); + view.setHorizontalScrollMode(scrollMode); + view.setVerticalScrollMode(scrollMode); view.horizontalScrollBar()->setValue(10); view.verticalScrollBar()->setValue(10); @@ -4168,15 +4087,15 @@ void tst_QTableView::task191545_dragSelectRows() QWidget *vHeaderVp = vHeader->viewport(); QPoint rowPos(cellRect.center()); QMouseEvent rowPressEvent(QEvent::MouseButtonPress, rowPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(vHeaderVp, &rowPressEvent); + QCoreApplication::sendEvent(vHeaderVp, &rowPressEvent); for (int i = 0; i < 4; ++i) { rowPos.setY(rowPos.y() + cellRect.height()); QMouseEvent moveEvent(QEvent::MouseMove, rowPos, Qt::NoButton, Qt::LeftButton, Qt::ControlModifier); - qApp->sendEvent(vHeaderVp, &moveEvent); + QCoreApplication::sendEvent(vHeaderVp, &moveEvent); } QMouseEvent rowReleaseEvent(QEvent::MouseButtonRelease, rowPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(vHeaderVp, &rowReleaseEvent); + QCoreApplication::sendEvent(vHeaderVp, &rowReleaseEvent); for (int i = 0; i < 4; ++i) { QModelIndex index = model.index(3 + i, 0, table.rootIndex()); @@ -4190,15 +4109,15 @@ void tst_QTableView::task191545_dragSelectRows() QWidget *hHeaderVp = hHeader->viewport(); QPoint colPos((cellRect.left() + cellRect.right()) / 2, 5); QMouseEvent colPressEvent(QEvent::MouseButtonPress, colPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(hHeaderVp, &colPressEvent); + QCoreApplication::sendEvent(hHeaderVp, &colPressEvent); for (int i = 0; i < 4; ++i) { colPos.setX(colPos.x() + cellRect.width()); QMouseEvent moveEvent(QEvent::MouseMove, colPos, Qt::NoButton, Qt::LeftButton, Qt::ControlModifier); - qApp->sendEvent(hHeaderVp, &moveEvent); + QCoreApplication::sendEvent(hHeaderVp, &moveEvent); } QMouseEvent colReleaseEvent(QEvent::MouseButtonRelease, colPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(hHeaderVp, &colReleaseEvent); + QCoreApplication::sendEvent(hHeaderVp, &colReleaseEvent); for (int i = 0; i < 4; ++i) { QModelIndex index = model.index(0, 3 + i, table.rootIndex()); @@ -4211,22 +4130,23 @@ void tst_QTableView::task191545_dragSelectRows() QWidget *tableVp = table.viewport(); QPoint cellPos = cellRect.center(); QMouseEvent cellPressEvent(QEvent::MouseButtonPress, cellPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &cellPressEvent); + QCoreApplication::sendEvent(tableVp, &cellPressEvent); for (int i = 0; i < 6; ++i) { cellPos.setX(cellPos.x() + cellRect.width()); cellPos.setY(cellPos.y() + cellRect.height()); QMouseEvent moveEvent(QEvent::MouseMove, cellPos, Qt::NoButton, Qt::LeftButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &moveEvent); + QCoreApplication::sendEvent(tableVp, &moveEvent); } QMouseEvent cellReleaseEvent(QEvent::MouseButtonRelease, cellPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &cellReleaseEvent); + QCoreApplication::sendEvent(tableVp, &cellReleaseEvent); - for (int i = 0; i < 6; ++i) + for (int i = 0; i < 6; ++i) { for (int j = 0; j < 6; ++j) { QModelIndex index = model.index(2 + i, 2 + j, table.rootIndex()); QVERIFY(table.selectionModel()->isSelected(index)); } + } } { @@ -4234,23 +4154,24 @@ void tst_QTableView::task191545_dragSelectRows() QWidget *tableVp = table.viewport(); QPoint cellPos = cellRect.center(); QMouseEvent cellPressEvent(QEvent::MouseButtonPress, cellPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &cellPressEvent); + QCoreApplication::sendEvent(tableVp, &cellPressEvent); for (int i = 0; i < 6; ++i) { cellPos.setX(cellPos.x() + cellRect.width()); cellPos.setY(cellPos.y() + cellRect.height()); QMouseEvent moveEvent(QEvent::MouseMove, cellPos, Qt::NoButton, Qt::LeftButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &moveEvent); + QCoreApplication::sendEvent(tableVp, &moveEvent); } QMouseEvent cellReleaseEvent(QEvent::MouseButtonRelease, cellPos, Qt::LeftButton, Qt::NoButton, Qt::ControlModifier); - qApp->sendEvent(tableVp, &cellReleaseEvent); + QCoreApplication::sendEvent(tableVp, &cellReleaseEvent); QTest::qWait(200); - for (int i = 0; i < 6; ++i) + for (int i = 0; i < 6; ++i) { for (int j = 0; j < 6; ++j) { QModelIndex index = model.index(3 + i, 3 + j, table.rootIndex()); QVERIFY(!table.selectionModel()->isSelected(index)); } + } } } @@ -4328,8 +4249,6 @@ void tst_QTableView::taskQTBUG_4516_clickOnRichTextLabel() QTest::mouseClick(&label, Qt::LeftButton); QCOMPARE(view.currentIndex(), model.index(1,1)); - - } @@ -4371,14 +4290,14 @@ void tst_QTableView::taskQTBUG_5237_wheelEventOnHeader() } #endif -class TestTableView : public QTableView { -Q_OBJECT +class TestTableView : public QTableView +{ + Q_OBJECT public: - TestTableView(QWidget *parent = 0) : QTableView(parent) + TestTableView(QWidget *parent = nullptr) : QTableView(parent) { - connect(this, SIGNAL(entered(QModelIndex)), this, SLOT(openEditor(QModelIndex))); + connect(this, &QTableView::entered, this, &TestTableView::openPersistentEditor); } - ~TestTableView(){} public slots: void onDataChanged() { @@ -4386,9 +4305,6 @@ public slots: setRowHidden(i, model()->data(model()->index(i, 0)).toBool()); } } - - void openEditor(const QModelIndex& index) - { openPersistentEditor(index); } }; @@ -4396,15 +4312,13 @@ void tst_QTableView::taskQTBUG_8585_crashForNoGoodReason() { QStandardItemModel model; model.insertColumn(0, QModelIndex()); - for(int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) model.insertRow(i); - } TestTableView w; w.setMouseTracking(true); w.setModel(&model); - connect(&model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), &w, SLOT(onDataChanged())); + connect(&model, &QStandardItemModel::dataChanged, &w, &TestTableView::onDataChanged); w.show(); QVERIFY(QTest::qWaitForWindowExposed(&w)); for (int i = 0; i < 10; i++) @@ -4418,10 +4332,7 @@ void tst_QTableView::taskQTBUG_8585_crashForNoGoodReason() class TableView7774 : public QTableView { public: - QRegion visualRegionForSelection(const QItemSelection &selection) const - { - return QTableView::visualRegionForSelection(selection); - } + using QTableView::visualRegionForSelection; }; void tst_QTableView::taskQTBUG_7774_RtoLVisualRegionForSelection()