diff options
Diffstat (limited to 'src/corelib/io')
65 files changed, 636 insertions, 650 deletions
diff --git a/src/corelib/io/forkfd_qt.cpp b/src/corelib/io/forkfd_qt.cpp index dce0ebb4da..80d1cd54d7 100644 --- a/src/corelib/io/forkfd_qt.cpp +++ b/src/corelib/io/forkfd_qt.cpp @@ -56,8 +56,6 @@ QT_BEGIN_NAMESPACE #define FFD_ATOMIC_RELAXED Relaxed #define FFD_ATOMIC_ACQUIRE Acquire #define FFD_ATOMIC_RELEASE Release -#define loadRelaxed load -#define storeRelaxed store #define FFD_CONCAT(x, y) x ## y diff --git a/src/corelib/io/io.pri b/src/corelib/io/io.pri index 9b6044752f..fe81689932 100644 --- a/src/corelib/io/io.pri +++ b/src/corelib/io/io.pri @@ -158,7 +158,8 @@ win32 { io/qwindowspipereader.cpp \ io/qwindowspipewriter.cpp - LIBS += -lmpr -lnetapi32 -luserenv + LIBS += -lmpr -luserenv + QMAKE_USE_PRIVATE += netapi32 } else { SOURCES += \ io/qstandardpaths_winrt.cpp \ @@ -171,7 +172,7 @@ win32 { io/qlockfile_unix.cpp \ io/qfilesystemiterator_unix.cpp - !integrity:!uikit { + !integrity:!uikit:!rtems { SOURCES += io/forkfd_qt.cpp HEADERS += \ ../3rdparty/forkfd/forkfd.h diff --git a/src/corelib/io/qabstractfileengine.cpp b/src/corelib/io/qabstractfileengine.cpp index f2a895bbb8..8a1679c5af 100644 --- a/src/corelib/io/qabstractfileengine.cpp +++ b/src/corelib/io/qabstractfileengine.cpp @@ -159,7 +159,7 @@ QAbstractFileEngineHandler::~QAbstractFileEngineHandler() */ QAbstractFileEngine *qt_custom_file_engine_handler_create(const QString &path) { - QAbstractFileEngine *engine = 0; + QAbstractFileEngine *engine = nullptr; if (qt_file_engine_handlers_in_use) { QReadLocker locker(fileEngineHandlerMutex()); @@ -658,7 +658,7 @@ QStringList QAbstractFileEngine::entryList(QDir::Filters filters, const QStringL QAbstractFileEngine::FileFlags QAbstractFileEngine::fileFlags(FileFlags type) const { Q_UNUSED(type); - return 0; + return nullptr; } /*! @@ -838,7 +838,7 @@ uchar *QAbstractFileEngine::map(qint64 offset, qint64 size, QFile::MemoryMapFlag option.flags = flags; MapExtensionReturn r; if (!extension(MapExtension, &option, &r)) - return 0; + return nullptr; return r.address; } @@ -1118,7 +1118,7 @@ QAbstractFileEngine::Iterator *QAbstractFileEngine::beginEntryList(QDir::Filters { Q_UNUSED(filters); Q_UNUSED(filterNames); - return 0; + return nullptr; } /*! @@ -1126,7 +1126,7 @@ QAbstractFileEngine::Iterator *QAbstractFileEngine::beginEntryList(QDir::Filters */ QAbstractFileEngine::Iterator *QAbstractFileEngine::endEntryList() { - return 0; + return nullptr; } /*! diff --git a/src/corelib/io/qabstractfileengine_p.h b/src/corelib/io/qabstractfileengine_p.h index 4a7fe7bff5..c88b66c7ce 100644 --- a/src/corelib/io/qabstractfileengine_p.h +++ b/src/corelib/io/qabstractfileengine_p.h @@ -193,7 +193,7 @@ public: uchar *address; }; - virtual bool extension(Extension extension, const ExtensionOption *option = 0, ExtensionReturn *output = 0); + virtual bool extension(Extension extension, const ExtensionOption *option = nullptr, ExtensionReturn *output = nullptr); virtual bool supportsExtension(Extension extension) const; // Factory diff --git a/src/corelib/io/qbuffer.cpp b/src/corelib/io/qbuffer.cpp index 7b3fa2ccad..8e980733de 100644 --- a/src/corelib/io/qbuffer.cpp +++ b/src/corelib/io/qbuffer.cpp @@ -50,7 +50,7 @@ class QBufferPrivate : public QIODevicePrivate public: QBufferPrivate() - : buf(0) + : buf(nullptr) #ifndef QT_NO_QOBJECT , writtenSinceLastEmit(0), signalConnectionCount(0), signalsEmitted(false) #endif diff --git a/src/corelib/io/qdebug.cpp b/src/corelib/io/qdebug.cpp index 15c5e0ce96..d13e94e096 100644 --- a/src/corelib/io/qdebug.cpp +++ b/src/corelib/io/qdebug.cpp @@ -147,7 +147,7 @@ using QtMiscUtils::fromHex; // Has been defined in the header / inlined before Qt 5.4 QDebug::~QDebug() { - if (!--stream->ref) { + if (stream && !--stream->ref) { if (stream->space && stream->buffer.endsWith(QLatin1Char(' '))) stream->buffer.chop(1); if (stream->message_output) { @@ -166,7 +166,7 @@ void QDebug::putUcs4(uint ucs4) { maybeQuote('\''); if (ucs4 < 0x20) { - stream->ts << "\\x" << hex << ucs4 << reset; + stream->ts << "\\x" << Qt::hex << ucs4 << Qt::reset; } else if (ucs4 < 0x80) { stream->ts << char(ucs4); } else { @@ -174,7 +174,7 @@ void QDebug::putUcs4(uint ucs4) stream->ts << "\\u" << qSetFieldWidth(4); else stream->ts << "\\U" << qSetFieldWidth(8); - stream->ts << hex << qSetPadChar(QLatin1Char('0')) << ucs4 << reset; + stream->ts << Qt::hex << qSetPadChar(QLatin1Char('0')) << ucs4 << Qt::reset; } maybeQuote('\''); } @@ -834,7 +834,7 @@ QDebug &QDebug::resetFormat() that QDebugStateSaver stores for the duration of the current block. The settings of the internal QTextStream are also saved and restored, - so that using << hex in a QDebug operator doesn't affect other QDebug + so that using << Qt::hex in a QDebug operator doesn't affect other QDebug operators. \since 5.1 @@ -843,36 +843,34 @@ QDebug &QDebug::resetFormat() class QDebugStateSaverPrivate { public: - QDebugStateSaverPrivate(QDebug &dbg) - : m_dbg(dbg), - m_spaces(dbg.autoInsertSpaces()), - m_flags(0), - m_streamParams(dbg.stream->ts.d_ptr->params) + QDebugStateSaverPrivate(QDebug::Stream *stream) + : m_stream(stream), + m_spaces(stream->space), + m_flags(stream->context.version > 1 ? stream->flags : 0), + m_streamParams(stream->ts.d_ptr->params) { - if (m_dbg.stream->context.version > 1) - m_flags = m_dbg.stream->flags; } void restoreState() { - const bool currentSpaces = m_dbg.autoInsertSpaces(); + const bool currentSpaces = m_stream->space; if (currentSpaces && !m_spaces) - if (m_dbg.stream->buffer.endsWith(QLatin1Char(' '))) - m_dbg.stream->buffer.chop(1); + if (m_stream->buffer.endsWith(QLatin1Char(' '))) + m_stream->buffer.chop(1); - m_dbg.setAutoInsertSpaces(m_spaces); - m_dbg.stream->ts.d_ptr->params = m_streamParams; - if (m_dbg.stream->context.version > 1) - m_dbg.stream->flags = m_flags; + m_stream->space = m_spaces; + m_stream->ts.d_ptr->params = m_streamParams; + if (m_stream->context.version > 1) + m_stream->flags = m_flags; if (!currentSpaces && m_spaces) - m_dbg.stream->ts << ' '; + m_stream->ts << ' '; } - QDebug &m_dbg; + QDebug::Stream *m_stream; // QDebug state const bool m_spaces; - int m_flags; + const int m_flags; // QTextStream state const QTextStreamPrivate::Params m_streamParams; @@ -886,7 +884,7 @@ public: \sa QDebug::setAutoInsertSpaces(), QDebug::autoInsertSpaces() */ QDebugStateSaver::QDebugStateSaver(QDebug &dbg) - : d(new QDebugStateSaverPrivate(dbg)) + : d(new QDebugStateSaverPrivate(dbg.stream)) { } diff --git a/src/corelib/io/qdebug.h b/src/corelib/io/qdebug.h index 91fde75fa5..421c5d933b 100644 --- a/src/corelib/io/qdebug.h +++ b/src/corelib/io/qdebug.h @@ -65,6 +65,7 @@ QT_BEGIN_NAMESPACE class Q_CORE_EXPORT QDebug { friend class QMessageLogger; + friend class QDebugStateSaver; friend class QDebugStateSaverPrivate; struct Stream { enum { VerbosityShift = 29, VerbosityMask = 0x7 }; @@ -114,9 +115,12 @@ public: inline QDebug(QString *string) : stream(new Stream(string)) {} inline QDebug(QtMsgType t) : stream(new Stream(t)) {} inline QDebug(const QDebug &o):stream(o.stream) { ++stream->ref; } + QDebug(QDebug &&other) noexcept : stream{qExchange(other.stream, nullptr)} {} inline QDebug &operator=(const QDebug &other); + QDebug &operator=(QDebug &&other) noexcept + { QDebug{std::move(other)}.swap(*this); return *this; } ~QDebug(); - inline void swap(QDebug &other) Q_DECL_NOTHROW { qSwap(stream, other.stream); } + inline void swap(QDebug &other) noexcept { qSwap(stream, other.stream); } QDebug &resetFormat(); @@ -161,9 +165,7 @@ public: inline QDebug &operator<<(QLatin1String t) { putByteArray(t.latin1(), t.size(), ContainsLatin1); return maybeSpace(); } inline QDebug &operator<<(const QByteArray & t) { putByteArray(t.constData(), t.size(), ContainsBinary); return maybeSpace(); } inline QDebug &operator<<(const void * t) { stream->ts << t; return maybeSpace(); } -#ifdef Q_COMPILER_NULLPTR inline QDebug &operator<<(std::nullptr_t) { stream->ts << "(nullptr)"; return maybeSpace(); } -#endif inline QDebug &operator<<(QTextStreamFunction f) { stream->ts << f; return *this; @@ -205,10 +207,7 @@ public: inline QDebug &QDebug::operator=(const QDebug &other) { - if (this != &other) { - QDebug copy(other); - qSwap(stream, copy.stream); - } + QDebug{other}.swap(*this); return *this; } @@ -352,7 +351,7 @@ void qt_QMetaEnum_flagDebugOperator(QDebug &debug, size_t sizeofT, Int value) { const QDebugStateSaver saver(debug); debug.resetFormat(); - debug.nospace() << "QFlags(" << hex << showbase; + debug.nospace() << "QFlags(" << Qt::hex << Qt::showbase; bool needSeparator = false; for (uint i = 0; i < sizeofT * 8; ++i) { if (value & (Int(1) << i)) { diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 671913e92f..fae935fc24 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -153,7 +153,7 @@ QDirPrivate::QDirPrivate(const QDirPrivate ©) bool QDirPrivate::exists() const { - if (fileEngine.isNull()) { + if (!fileEngine) { QFileSystemEngine::fillMetaData(dirEntry, metaData, QFileSystemMetaData::ExistsAttribute | QFileSystemMetaData::DirectoryType); // always stat return metaData.exists() && metaData.isDirectory(); @@ -226,7 +226,7 @@ inline void QDirPrivate::resolveAbsoluteEntry() const return; QString absoluteName; - if (fileEngine.isNull()) { + if (!fileEngine) { if (!dirEntry.isRelative() && dirEntry.isClean()) { absoluteDirEntry = dirEntry; return; @@ -693,7 +693,7 @@ QString QDir::absolutePath() const QString QDir::canonicalPath() const { const QDirPrivate* d = d_ptr.constData(); - if (d->fileEngine.isNull()) { + if (!d->fileEngine) { QFileSystemEntry answer = QFileSystemEngine::canonicalName(d->dirEntry, d->metaData); return answer.filePath(); } @@ -947,6 +947,12 @@ QString QDir::fromNativeSeparators(const QString &pathName) int i = pathName.indexOf(QLatin1Char('\\')); if (i != -1) { QString n(pathName); + if (n.startsWith(QLatin1String("\\\\?\\"))) { + n.remove(0, 4); + i = n.indexOf(QLatin1Char('\\')); + if (i == -1) + return n; + } QChar * const data = n.data(); data[i++] = QLatin1Char('/'); @@ -1431,7 +1437,7 @@ QStringList QDir::entryList(const QStringList &nameFilters, Filters filters, l.append(it.fileInfo()); } QStringList ret; - d->sortFileList(sort, l, &ret, 0); + d->sortFileList(sort, l, &ret, nullptr); return ret; } @@ -1473,7 +1479,7 @@ QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filter l.append(it.fileInfo()); } QFileInfoList ret; - d->sortFileList(sort, l, 0, &ret); + d->sortFileList(sort, l, nullptr, &ret); return ret; } @@ -1496,7 +1502,7 @@ bool QDir::mkdir(const QString &dirName) const } QString fn = filePath(dirName); - if (d->fileEngine.isNull()) + if (!d->fileEngine) return QFileSystemEngine::createDirectory(QFileSystemEntry(fn), false); return d->fileEngine->mkdir(fn, false); } @@ -1520,7 +1526,7 @@ bool QDir::rmdir(const QString &dirName) const } QString fn = filePath(dirName); - if (d->fileEngine.isNull()) + if (!d->fileEngine) return QFileSystemEngine::removeDirectory(QFileSystemEntry(fn), false); return d->fileEngine->rmdir(fn, false); @@ -1548,7 +1554,7 @@ bool QDir::mkpath(const QString &dirPath) const } QString fn = filePath(dirPath); - if (d->fileEngine.isNull()) + if (!d->fileEngine) return QFileSystemEngine::createDirectory(QFileSystemEntry(fn), true); return d->fileEngine->mkdir(fn, true); } @@ -1574,7 +1580,7 @@ bool QDir::rmpath(const QString &dirPath) const } QString fn = filePath(dirPath); - if (d->fileEngine.isNull()) + if (!d->fileEngine) return QFileSystemEngine::removeDirectory(QFileSystemEntry(fn), true); return d->fileEngine->rmdir(fn, true); } @@ -1647,7 +1653,7 @@ bool QDir::isReadable() const { const QDirPrivate* d = d_ptr.constData(); - if (d->fileEngine.isNull()) { + if (!d->fileEngine) { if (!d->metaData.hasFlags(QFileSystemMetaData::UserReadPermission)) QFileSystemEngine::fillMetaData(d->dirEntry, d->metaData, QFileSystemMetaData::UserReadPermission); @@ -1692,7 +1698,7 @@ bool QDir::exists() const */ bool QDir::isRoot() const { - if (d_ptr->fileEngine.isNull()) + if (!d_ptr->fileEngine) return d_ptr->dirEntry.isRoot(); return d_ptr->fileEngine->fileFlags(QAbstractFileEngine::FlagsMask) & QAbstractFileEngine::RootFlag; } @@ -1724,7 +1730,7 @@ bool QDir::isRoot() const */ bool QDir::isRelative() const { - if (d_ptr->fileEngine.isNull()) + if (!d_ptr->fileEngine) return d_ptr->dirEntry.isRelative(); return d_ptr->fileEngine->isRelativePath(); } @@ -1741,7 +1747,7 @@ bool QDir::makeAbsolute() { const QDirPrivate *d = d_ptr.constData(); QScopedPointer<QDirPrivate> dir; - if (!d->fileEngine.isNull()) { + if (!!d->fileEngine) { QString absolutePath = d->fileEngine->fileName(QAbstractFileEngine::AbsoluteName); if (QDir::isRelativePath(absolutePath)) return false; @@ -1774,8 +1780,8 @@ bool QDir::operator==(const QDir &dir) const if (d == other) return true; Qt::CaseSensitivity sensitive; - if (d->fileEngine.isNull() || other->fileEngine.isNull()) { - if (d->fileEngine.data() != other->fileEngine.data()) // one is native, the other is a custom file-engine + if (!d->fileEngine || !other->fileEngine) { + if (d->fileEngine.get() != other->fileEngine.get()) // one is native, the other is a custom file-engine return false; sensitive = QFileSystemEngine::isCaseSensitive() ? Qt::CaseSensitive : Qt::CaseInsensitive; @@ -2339,6 +2345,11 @@ static QString qt_cleanPath(const QString &path, bool *ok) if (path.isEmpty()) return path; QString name = path; +#if defined (Q_OS_WIN) + if (name.startsWith(QLatin1String("\\\\?\\"))) + name.remove(0, 4); +#endif + QChar dir_separator = QDir::separator(); if (dir_separator != QLatin1Char('/')) name.replace(dir_separator, QLatin1Char('/')); diff --git a/src/corelib/io/qdir.h b/src/corelib/io/qdir.h index 9abb833ab1..45a40995f8 100644 --- a/src/corelib/io/qdir.h +++ b/src/corelib/io/qdir.h @@ -109,11 +109,9 @@ public: QT_DEPRECATED_X("Use QDir::setPath() instead") QDir &operator=(const QString &path); #endif -#ifdef Q_COMPILER_RVALUE_REFS - QDir &operator=(QDir &&other) Q_DECL_NOTHROW { swap(other); return *this; } -#endif + QDir &operator=(QDir &&other) noexcept { swap(other); return *this; } - void swap(QDir &other) Q_DECL_NOTHROW + void swap(QDir &other) noexcept { qSwap(d_ptr, other.d_ptr); } void setPath(const QString &path); @@ -190,7 +188,7 @@ public: static QFileInfoList drives(); - Q_DECL_CONSTEXPR static inline QChar listSeparator() Q_DECL_NOTHROW + Q_DECL_CONSTEXPR static inline QChar listSeparator() noexcept { #if defined(Q_OS_WIN) return QLatin1Char(';'); diff --git a/src/corelib/io/qdir_p.h b/src/corelib/io/qdir_p.h index 0f3ab7f899..af105de8db 100644 --- a/src/corelib/io/qdir_p.h +++ b/src/corelib/io/qdir_p.h @@ -54,6 +54,8 @@ #include "qfilesystementry_p.h" #include "qfilesystemmetadata_p.h" +#include <memory> + QT_BEGIN_NAMESPACE class QDirPrivate : public QSharedData @@ -82,7 +84,7 @@ public: static inline QChar getFilterSepChar(const QString &nameFilter); - static inline QStringList splitFilters(const QString &nameFilter, QChar sep = 0); + static inline QStringList splitFilters(const QString &nameFilter, QChar sep = {}); void setPath(const QString &path); @@ -98,7 +100,7 @@ public: QDir::SortFlags sort; QDir::Filters filters; - QScopedPointer<QAbstractFileEngine> fileEngine; + std::unique_ptr<QAbstractFileEngine> fileEngine; QFileSystemEntry dirEntry; mutable QFileSystemEntry absoluteDirEntry; diff --git a/src/corelib/io/qdiriterator.cpp b/src/corelib/io/qdiriterator.cpp index ccde9745bf..ce436b06e3 100644 --- a/src/corelib/io/qdiriterator.cpp +++ b/src/corelib/io/qdiriterator.cpp @@ -93,9 +93,13 @@ #include "qdir_p.h" #include "qabstractfileengine_p.h" +#include <QtCore/qregexp.h> #include <QtCore/qset.h> #include <QtCore/qstack.h> #include <QtCore/qvariant.h> +#if QT_CONFIG(regularexpression) +#include <QtCore/qregularexpression.h> +#endif #include <QtCore/private/qfilesystemiterator_p.h> #include <QtCore/private/qfilesystementry_p.h> @@ -103,6 +107,8 @@ #include <QtCore/private/qfilesystemengine_p.h> #include <QtCore/private/qfileinfo_p.h> +#include <memory> + QT_BEGIN_NAMESPACE template <class Iterator> @@ -128,15 +134,18 @@ public: void checkAndPushDirectory(const QFileInfo &); bool matchesFilters(const QString &fileName, const QFileInfo &fi) const; - QScopedPointer<QAbstractFileEngine> engine; + std::unique_ptr<QAbstractFileEngine> engine; QFileSystemEntry dirEntry; const QStringList nameFilters; const QDir::Filters filters; const QDirIterator::IteratorFlags iteratorFlags; -#ifndef QT_NO_REGEXP +#if defined(QT_BOOTSTRAPPED) + // ### Qt6: Get rid of this once we don't bootstrap qmake anymore QVector<QRegExp> nameRegExps; +#elif QT_CONFIG(regularexpression) + QVector<QRegularExpression> nameRegExps; #endif QDirIteratorPrivateIteratorStack<QAbstractFileEngineIterator> fileEngineIterators; @@ -161,13 +170,21 @@ QDirIteratorPrivate::QDirIteratorPrivate(const QFileSystemEntry &entry, const QS , filters(QDir::NoFilter == filters ? QDir::AllEntries : filters) , iteratorFlags(flags) { -#ifndef QT_NO_REGEXP +#if defined(QT_BOOTSTRAPPED) nameRegExps.reserve(nameFilters.size()); - for (int i = 0; i < nameFilters.size(); ++i) + for (const auto &filter : nameFilters) { nameRegExps.append( - QRegExp(nameFilters.at(i), + QRegExp(filter, (filters & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::Wildcard)); + } +#elif QT_CONFIG(regularexpression) + nameRegExps.reserve(nameFilters.size()); + for (const auto &filter : nameFilters) { + QString re = QRegularExpression::anchoredPattern(QRegularExpression::wildcardToRegularExpression(filter)); + nameRegExps.append( + QRegularExpression(re, (filters & QDir::CaseSensitive) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption)); + } #endif QFileSystemMetaData metaData; if (resolveEngine) @@ -334,19 +351,23 @@ bool QDirIteratorPrivate::matchesFilters(const QString &fileName, const QFileInf return false; // name filter -#ifndef QT_NO_REGEXP +#if QT_CONFIG(regularexpression) || defined(QT_BOOTSTRAPPED) // Pass all entries through name filters, except dirs if the AllDirs if (!nameFilters.isEmpty() && !((filters & QDir::AllDirs) && fi.isDir())) { bool matched = false; - for (QVector<QRegExp>::const_iterator iter = nameRegExps.constBegin(), - end = nameRegExps.constEnd(); - iter != end; ++iter) { - - QRegExp copy = *iter; + for (const auto &re : nameRegExps) { +#if defined(QT_BOOTSTRAPPED) + QRegExp copy = re; if (copy.exactMatch(fileName)) { matched = true; break; } +#else + if (re.match(fileName).hasMatch()) { + matched = true; + break; + } +#endif } if (!matched) return false; @@ -416,7 +437,7 @@ bool QDirIteratorPrivate::matchesFilters(const QString &fileName, const QFileInf QDirIterator::QDirIterator(const QDir &dir, IteratorFlags flags) { const QDirPrivate *other = dir.d_ptr.constData(); - d.reset(new QDirIteratorPrivate(other->dirEntry, other->nameFilters, other->filters, flags, !other->fileEngine.isNull())); + d.reset(new QDirIteratorPrivate(other->dirEntry, other->nameFilters, other->filters, flags, bool(other->fileEngine))); } /*! diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index 37de4450cc..95f03ef816 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -55,12 +55,21 @@ # include "qcoreapplication.h" #endif +#include <private/qmemory_p.h> + #ifdef QT_NO_QOBJECT #define tr(X) QString::fromLatin1(X) #endif QT_BEGIN_NAMESPACE +Q_DECL_COLD_FUNCTION +static bool file_already_open(QFile &file, const char *where = nullptr) +{ + qWarning("QFile::%s: File (%ls) already open", where ? where : "open", qUtf16Printable(file.fileName())); + return false; +} + //************* QFilePrivate QFilePrivate::QFilePrivate() { @@ -78,10 +87,9 @@ QFilePrivate::openExternalFile(int flags, int fd, QFile::FileHandleFlags handleF Q_UNUSED(fd); return false; #else - delete fileEngine; - fileEngine = 0; - QFSFileEngine *fe = new QFSFileEngine; - fileEngine = fe; + auto fs = qt_make_unique<QFSFileEngine>(); + auto fe = fs.get(); + fileEngine = std::move(fs); return fe->open(QIODevice::OpenMode(flags), fd, handleFlags); #endif } @@ -94,10 +102,9 @@ QFilePrivate::openExternalFile(int flags, FILE *fh, QFile::FileHandleFlags handl Q_UNUSED(fh); return false; #else - delete fileEngine; - fileEngine = 0; - QFSFileEngine *fe = new QFSFileEngine; - fileEngine = fe; + auto fs = qt_make_unique<QFSFileEngine>(); + auto fe = fs.get(); + fileEngine = std::move(fs); return fe->open(QIODevice::OpenMode(flags), fh, handleFlags); #endif } @@ -105,8 +112,8 @@ QFilePrivate::openExternalFile(int flags, FILE *fh, QFile::FileHandleFlags handl QAbstractFileEngine *QFilePrivate::engine() const { if (!fileEngine) - fileEngine = QAbstractFileEngine::create(fileName); - return fileEngine; + fileEngine.reset(QAbstractFileEngine::create(fileName)); + return fileEngine.get(); } //************* QFile @@ -324,14 +331,10 @@ QFile::setFileName(const QString &name) { Q_D(QFile); if (isOpen()) { - qWarning("QFile::setFileName: File (%s) is already opened", - qPrintable(fileName())); + file_already_open(*this, "setFileName"); close(); } - if(d->fileEngine) { //get a new file engine later - delete d->fileEngine; - d->fileEngine = 0; - } + d->fileEngine.reset(); //get a new file engine later d->fileName = name; } @@ -804,7 +807,7 @@ QFile::copy(const QString &newName) error = true; d->setError(QFile::CopyError, tr("Cannot open %1 for input").arg(d->fileName)); } else { - QString fileTemplate = QLatin1String("%1/qt_temp.XXXXXX"); + const auto fileTemplate = QLatin1String("%1/qt_temp.XXXXXX"); #ifdef QT_NO_TEMPORARYFILE QFile out(fileTemplate.arg(QFileInfo(newName).path())); if (!out.open(QIODevice::ReadWrite)) @@ -910,10 +913,8 @@ QFile::copy(const QString &fileName, const QString &newName) bool QFile::open(OpenMode mode) { Q_D(QFile); - if (isOpen()) { - qWarning("QFile::open: File (%s) already open", qPrintable(fileName())); - return false; - } + if (isOpen()) + return file_already_open(*this); // Either Append or NewOnly implies WriteOnly if (mode & (Append | NewOnly)) mode |= WriteOnly; @@ -982,10 +983,8 @@ bool QFile::open(OpenMode mode) bool QFile::open(FILE *fh, OpenMode mode, FileHandleFlags handleFlags) { Q_D(QFile); - if (isOpen()) { - qWarning("QFile::open: File (%s) already open", qPrintable(fileName())); - return false; - } + if (isOpen()) + return file_already_open(*this); // Either Append or NewOnly implies WriteOnly if (mode & (Append | NewOnly)) mode |= WriteOnly; @@ -1041,10 +1040,8 @@ bool QFile::open(FILE *fh, OpenMode mode, FileHandleFlags handleFlags) bool QFile::open(int fd, OpenMode mode, FileHandleFlags handleFlags) { Q_D(QFile); - if (isOpen()) { - qWarning("QFile::open: File (%s) already open", qPrintable(fileName())); - return false; - } + if (isOpen()) + return file_already_open(*this); // Either Append or NewOnly implies WriteOnly if (mode & (Append | NewOnly)) mode |= WriteOnly; diff --git a/src/corelib/io/qfiledevice.cpp b/src/corelib/io/qfiledevice.cpp index 0689118f3e..ee619d99cc 100644 --- a/src/corelib/io/qfiledevice.cpp +++ b/src/corelib/io/qfiledevice.cpp @@ -42,6 +42,8 @@ #include "qfiledevice_p.h" #include "qfsfileengine_p.h" +#include <private/qmemory_p.h> + #ifdef QT_NO_QOBJECT #define tr(X) QString::fromLatin1(X) #endif @@ -53,24 +55,20 @@ QT_BEGIN_NAMESPACE #endif QFileDevicePrivate::QFileDevicePrivate() - : fileEngine(0), - cachedSize(0), + : cachedSize(0), error(QFile::NoError), lastWasWrite(false) { writeBufferChunkSize = QFILE_WRITEBUFFER_SIZE; } QFileDevicePrivate::~QFileDevicePrivate() -{ - delete fileEngine; - fileEngine = 0; -} + = default; QAbstractFileEngine * QFileDevicePrivate::engine() const { if (!fileEngine) - fileEngine = new QFSFileEngine; - return fileEngine; + fileEngine = qt_make_unique<QFSFileEngine>(); + return fileEngine.get(); } void QFileDevicePrivate::setError(QFileDevice::FileError err) diff --git a/src/corelib/io/qfiledevice_p.h b/src/corelib/io/qfiledevice_p.h index 47053d01b7..aef3fca811 100644 --- a/src/corelib/io/qfiledevice_p.h +++ b/src/corelib/io/qfiledevice_p.h @@ -53,6 +53,8 @@ #include "private/qiodevice_p.h" +#include <memory> + QT_BEGIN_NAMESPACE class QAbstractFileEngine; @@ -75,7 +77,7 @@ protected: void setError(QFileDevice::FileError err, const QString &errorString); void setError(QFileDevice::FileError err, int errNum); - mutable QAbstractFileEngine *fileEngine; + mutable std::unique_ptr<QAbstractFileEngine> fileEngine; mutable qint64 cachedSize; QFileDevice::FileHandleFlags handleFlags; diff --git a/src/corelib/io/qfileinfo.cpp b/src/corelib/io/qfileinfo.cpp index 998382021d..a5a3bc8b3e 100644 --- a/src/corelib/io/qfileinfo.cpp +++ b/src/corelib/io/qfileinfo.cpp @@ -52,7 +52,7 @@ QString QFileInfoPrivate::getFileName(QAbstractFileEngine::FileName name) const return fileNames[(int)name]; QString ret; - if (fileEngine == 0) { // local file; use the QFileSystemEngine directly + if (fileEngine == nullptr) { // local file; use the QFileSystemEngine directly switch (name) { case QAbstractFileEngine::CanonicalName: case QAbstractFileEngine::CanonicalPathName: { @@ -103,7 +103,7 @@ QString QFileInfoPrivate::getFileOwner(QAbstractFileEngine::FileOwner own) const if (cache_enabled && !fileOwners[(int)own].isNull()) return fileOwners[(int)own]; QString ret; - if (fileEngine == 0) { + if (fileEngine == nullptr) { switch (own) { case QAbstractFileEngine::OwnerUser: ret = QFileSystemEngine::resolveUserName(fileEntry, metaData); @@ -134,7 +134,7 @@ uint QFileInfoPrivate::getFileFlags(QAbstractFileEngine::FileFlags request) cons // extra syscall. Bundle detecton on Mac can be slow, expecially on network // paths, so we separate out that as well. - QAbstractFileEngine::FileFlags req = 0; + QAbstractFileEngine::FileFlags req = nullptr; uint cachedFlags = 0; if (request & (QAbstractFileEngine::FlagsMask | QAbstractFileEngine::TypesMask)) { @@ -434,7 +434,7 @@ bool QFileInfo::operator==(const QFileInfo &fileinfo) const return true; Qt::CaseSensitivity sensitive; - if (d->fileEngine == 0 || fileinfo.d_ptr->fileEngine == 0) { + if (d->fileEngine == nullptr || fileinfo.d_ptr->fileEngine == nullptr) { if (d->fileEngine != fileinfo.d_ptr->fileEngine) // one is native, the other is a custom file-engine return false; @@ -649,7 +649,7 @@ bool QFileInfo::isRelative() const Q_D(const QFileInfo); if (d->isDefaultConstructed) return true; - if (d->fileEngine == 0) + if (d->fileEngine == nullptr) return d->fileEntry.isRelative(); return d->fileEngine->isRelativePath(); } @@ -682,7 +682,7 @@ bool QFileInfo::exists() const Q_D(const QFileInfo); if (d->isDefaultConstructed) return false; - if (d->fileEngine == 0) { + if (d->fileEngine == nullptr) { if (!d->cache_enabled || !d->metaData.hasFlags(QFileSystemMetaData::ExistsAttribute)) QFileSystemEngine::fillMetaData(d->fileEntry, d->metaData, QFileSystemMetaData::ExistsAttribute); return d->metaData.exists(); @@ -707,11 +707,11 @@ bool QFileInfo::exists(const QString &file) return false; QFileSystemEntry entry(file); QFileSystemMetaData data; - QAbstractFileEngine *engine = - QFileSystemEngine::resolveEntryAndCreateLegacyEngine(entry, data); + std::unique_ptr<QAbstractFileEngine> engine + {QFileSystemEngine::resolveEntryAndCreateLegacyEngine(entry, data)}; // Expensive fallback to non-QFileSystemEngine implementation if (engine) - return QFileInfo(new QFileInfoPrivate(entry, data, engine)).exists(); + return QFileInfo(new QFileInfoPrivate(entry, data, std::move(engine))).exists(); QFileSystemEngine::fillMetaData(entry, data, QFileSystemMetaData::ExistsAttribute); return data.exists(); @@ -982,7 +982,7 @@ bool QFileInfo::isNativePath() const Q_D(const QFileInfo); if (d->isDefaultConstructed) return false; - if (d->fileEngine == 0) + if (d->fileEngine == nullptr) return true; return d->getFileFlags(QAbstractFileEngine::LocalDiskFlag); } @@ -1075,7 +1075,7 @@ bool QFileInfo::isRoot() const Q_D(const QFileInfo); if (d->isDefaultConstructed) return false; - if (d->fileEngine == 0) { + if (d->fileEngine == nullptr) { if (d->fileEntry.isRoot()) { #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) //the path is a drive root, but the drive may not exist diff --git a/src/corelib/io/qfileinfo.h b/src/corelib/io/qfileinfo.h index baea18fab1..111517325d 100644 --- a/src/corelib/io/qfileinfo.h +++ b/src/corelib/io/qfileinfo.h @@ -67,11 +67,9 @@ public: ~QFileInfo(); QFileInfo &operator=(const QFileInfo &fileinfo); -#ifdef Q_COMPILER_RVALUE_REFS - QFileInfo &operator=(QFileInfo &&other) Q_DECL_NOTHROW { swap(other); return *this; } -#endif + QFileInfo &operator=(QFileInfo &&other) noexcept { swap(other); return *this; } - void swap(QFileInfo &other) Q_DECL_NOTHROW + void swap(QFileInfo &other) noexcept { qSwap(d_ptr, other.d_ptr); } bool operator==(const QFileInfo &fileinfo) const; diff --git a/src/corelib/io/qfileinfo_p.h b/src/corelib/io/qfileinfo_p.h index e4b28f4519..333ea70adc 100644 --- a/src/corelib/io/qfileinfo_p.h +++ b/src/corelib/io/qfileinfo_p.h @@ -61,6 +61,8 @@ #include <QtCore/private/qfilesystementry_p.h> #include <QtCore/private/qfilesystemmetadata_p.h> +#include <memory> + QT_BEGIN_NAMESPACE class QFileInfoPrivate : public QSharedData @@ -80,7 +82,7 @@ public: }; inline QFileInfoPrivate() - : QSharedData(), fileEngine(0), + : QSharedData(), fileEngine(nullptr), cachedFlags(0), isDefaultConstructed(true), cache_enabled(true), fileFlags(0), fileSize(0) @@ -126,10 +128,10 @@ public: metaData = QFileSystemMetaData(); } - inline QFileInfoPrivate(const QFileSystemEntry &file, const QFileSystemMetaData &data, QAbstractFileEngine *engine) + inline QFileInfoPrivate(const QFileSystemEntry &file, const QFileSystemMetaData &data, std::unique_ptr<QAbstractFileEngine> engine) : fileEntry(file), metaData(data), - fileEngine(engine), + fileEngine{std::move(engine)}, cachedFlags(0), #ifndef QT_NO_FSFILEENGINE isDefaultConstructed(false), @@ -163,7 +165,7 @@ public: QFileSystemEntry fileEntry; mutable QFileSystemMetaData metaData; - QScopedPointer<QAbstractFileEngine> const fileEngine; + std::unique_ptr<QAbstractFileEngine> const fileEngine; mutable QString fileNames[QAbstractFileEngine::NFileNames]; mutable QString fileOwners[2]; // QAbstractFileEngine::FileOwner: OwnerUser and OwnerGroup diff --git a/src/corelib/io/qfilesystemengine.cpp b/src/corelib/io/qfilesystemengine.cpp index 7abdf90bf5..21847c2a7c 100644 --- a/src/corelib/io/qfilesystemengine.cpp +++ b/src/corelib/io/qfilesystemengine.cpp @@ -124,7 +124,7 @@ static inline bool _q_checkEntry(QAbstractFileEngine *&engine, bool resolvingEnt if (resolvingEntry) { if (!(engine->fileFlags(QAbstractFileEngine::FlagsMask) & QAbstractFileEngine::ExistsFlag)) { delete engine; - engine = 0; + engine = nullptr; return false; } } @@ -191,7 +191,7 @@ static bool _q_resolveEntryAndCreateLegacyEngine_recursive(QFileSystemEntry &ent QAbstractFileEngine *QFileSystemEngine::resolveEntryAndCreateLegacyEngine( QFileSystemEntry &entry, QFileSystemMetaData &data) { QFileSystemEntry copy = entry; - QAbstractFileEngine *engine = 0; + QAbstractFileEngine *engine = nullptr; if (_q_resolveEntryAndCreateLegacyEngine_recursive(copy, data, engine)) // Reset entry to resolved copy. diff --git a/src/corelib/io/qfilesystemengine_p.h b/src/corelib/io/qfilesystemengine_p.h index 09ec2d6a10..e44837747c 100644 --- a/src/corelib/io/qfilesystemengine_p.h +++ b/src/corelib/io/qfilesystemengine_p.h @@ -130,7 +130,7 @@ public: static bool removeFile(const QFileSystemEntry &entry, QSystemError &error); static bool setPermissions(const QFileSystemEntry &entry, QFile::Permissions permissions, QSystemError &error, - QFileSystemMetaData *data = 0); + QFileSystemMetaData *data = nullptr); // unused, therefore not implemented static bool setFileTime(const QFileSystemEntry &entry, const QDateTime &newDate, diff --git a/src/corelib/io/qfilesystemengine_unix.cpp b/src/corelib/io/qfilesystemengine_unix.cpp index b78e037865..74865fe31f 100644 --- a/src/corelib/io/qfilesystemengine_unix.cpp +++ b/src/corelib/io/qfilesystemengine_unix.cpp @@ -813,7 +813,7 @@ QString QFileSystemEngine::resolveUserName(uint userId) #endif #if !defined(Q_OS_INTEGRITY) && !defined(Q_OS_WASM) - struct passwd *pw = 0; + struct passwd *pw = nullptr; #if QT_CONFIG(thread) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_VXWORKS) struct passwd entry; getpwuid_r(userId, &entry, buf.data(), buf.size(), &pw); @@ -822,6 +822,8 @@ QString QFileSystemEngine::resolveUserName(uint userId) #endif if (pw) return QFile::decodeName(QByteArray(pw->pw_name)); +#else // Integrity || WASM + Q_UNUSED(userId); #endif return QString(); } @@ -837,7 +839,7 @@ QString QFileSystemEngine::resolveGroupName(uint groupId) #endif #if !defined(Q_OS_INTEGRITY) && !defined(Q_OS_WASM) - struct group *gr = 0; + struct group *gr = nullptr; #if QT_CONFIG(thread) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_VXWORKS) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID) && (__ANDROID_API__ >= 24)) size_max = sysconf(_SC_GETGR_R_SIZE_MAX); if (size_max == -1) @@ -859,6 +861,8 @@ QString QFileSystemEngine::resolveGroupName(uint groupId) #endif if (gr) return QFile::decodeName(QByteArray(gr->gr_name)); +#else // Integrity || WASM + Q_UNUSED(groupId); #endif return QString(); } diff --git a/src/corelib/io/qfilesystemiterator_unix.cpp b/src/corelib/io/qfilesystemiterator_unix.cpp index 92ebdf0341..2d09c277eb 100644 --- a/src/corelib/io/qfilesystemiterator_unix.cpp +++ b/src/corelib/io/qfilesystemiterator_unix.cpp @@ -91,15 +91,15 @@ static bool checkNameDecodable(const char *d_name, qsizetype len) QFileSystemIterator::QFileSystemIterator(const QFileSystemEntry &entry, QDir::Filters filters, const QStringList &nameFilters, QDirIterator::IteratorFlags flags) : nativePath(entry.nativeFilePath()) - , dir(0) - , dirEntry(0) + , dir(nullptr) + , dirEntry(nullptr) , lastError(0) { Q_UNUSED(filters) Q_UNUSED(nameFilters) Q_UNUSED(flags) - if ((dir = QT_OPENDIR(nativePath.constData())) == 0) { + if ((dir = QT_OPENDIR(nativePath.constData())) == nullptr) { lastError = errno; } else { if (!nativePath.endsWith('/')) diff --git a/src/corelib/io/qfilesystemmetadata_p.h b/src/corelib/io/qfilesystemmetadata_p.h index 4d2a5acb9b..81f4b3ba13 100644 --- a/src/corelib/io/qfilesystemmetadata_p.h +++ b/src/corelib/io/qfilesystemmetadata_p.h @@ -76,7 +76,7 @@ class Q_AUTOTEST_EXPORT QFileSystemMetaData { public: QFileSystemMetaData() - : knownFlagsMask(0), + : knownFlagsMask(nullptr), size_(-1) { } @@ -184,7 +184,7 @@ public: void clear() { - knownFlagsMask = 0; + knownFlagsMask = nullptr; } void clearFlags(MetaDataFlags flags = AllMetaDataFlags) diff --git a/src/corelib/io/qfilesystemwatcher.cpp b/src/corelib/io/qfilesystemwatcher.cpp index f40e166d9f..64c422c55a 100644 --- a/src/corelib/io/qfilesystemwatcher.cpp +++ b/src/corelib/io/qfilesystemwatcher.cpp @@ -47,7 +47,7 @@ #include <qset.h> #include <qtimer.h> -#if defined(Q_OS_LINUX) || (defined(Q_OS_QNX) && !defined(QT_NO_INOTIFY)) +#if (defined(Q_OS_LINUX) || defined(Q_OS_QNX)) && QT_CONFIG(inotify) #define USE_INOTIFY #endif @@ -311,6 +311,17 @@ bool QFileSystemWatcher::addPath(const QString &path) return paths.isEmpty(); } +static QStringList empty_paths_pruned(const QStringList &paths) +{ + QStringList p; + p.reserve(paths.size()); + const auto isEmpty = [](const QString &s) { return s.isEmpty(); }; + std::remove_copy_if(paths.begin(), paths.end(), + std::back_inserter(p), + isEmpty); + return p; +} + /*! Adds each path in \a paths to the file system watcher. Paths are not added if they not exist, or if they are already being @@ -338,47 +349,41 @@ QStringList QFileSystemWatcher::addPaths(const QStringList &paths) { Q_D(QFileSystemWatcher); - QStringList p = paths; - QMutableListIterator<QString> it(p); - - while (it.hasNext()) { - const QString &path = it.next(); - if (path.isEmpty()) - it.remove(); - } + QStringList p = empty_paths_pruned(paths); if (p.isEmpty()) { qWarning("QFileSystemWatcher::addPaths: list is empty"); - return QStringList(); + return p; } - QFileSystemWatcherEngine *engine = 0; - - const QString on = objectName(); - - if (!on.startsWith(QLatin1String("_qt_autotest_force_engine_"))) { + const auto selectEngine = [this, d]() -> QFileSystemWatcherEngine* { +#ifdef QT_BUILD_INTERNAL + const QString on = objectName(); + + if (Q_UNLIKELY(on.startsWith(QLatin1String("_qt_autotest_force_engine_")))) { + // 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"); + d_func()->initPollerEngine(); + return d->poller; + } else if (forceName == QLatin1String("native")) { + qDebug("QFileSystemWatcher: skipping polling engine, using only native engine"); + return d->native; + } + return nullptr; + } +#endif // Normal runtime case - search intelligently for best engine if(d->native) { - engine = d->native; + return d->native; } else { d_func()->initPollerEngine(); - engine = d->poller; - } - - } else { - // 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"); - d_func()->initPollerEngine(); - engine = d->poller; - } else if(forceName == QLatin1String("native")) { - qDebug("QFileSystemWatcher: skipping polling engine, using only native engine"); - engine = d->native; + return d->poller; } - } + }; - if(engine) + if (auto engine = selectEngine()) p = engine->addPaths(p, &d->files, &d->directories); return p; @@ -420,18 +425,11 @@ QStringList QFileSystemWatcher::removePaths(const QStringList &paths) { Q_D(QFileSystemWatcher); - QStringList p = paths; - QMutableListIterator<QString> it(p); - - while (it.hasNext()) { - const QString &path = it.next(); - if (path.isEmpty()) - it.remove(); - } + QStringList p = empty_paths_pruned(paths); if (p.isEmpty()) { qWarning("QFileSystemWatcher::removePaths: list is empty"); - return QStringList(); + return p; } if (d->native) diff --git a/src/corelib/io/qfilesystemwatcher_fsevents.mm b/src/corelib/io/qfilesystemwatcher_fsevents.mm index f594fad803..6194bf7c71 100644 --- a/src/corelib/io/qfilesystemwatcher_fsevents.mm +++ b/src/corelib/io/qfilesystemwatcher_fsevents.mm @@ -50,6 +50,7 @@ #include <qfile.h> #include <qfileinfo.h> #include <qvarlengtharray.h> +#include <qscopeguard.h> #undef FSEVENT_DEBUG #ifdef FSEVENT_DEBUG @@ -338,10 +339,10 @@ QStringList QFseventsFileSystemWatcherEngine::addPaths(const QStringList &paths, bool needsRestart = false; WatchingState oldState = watchingState; - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString origPath = it.next().normalized(QString::NormalizationForm_C); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&]{ unhandled.push_back(path); }); + QString origPath = path.normalized(QString::NormalizationForm_C); QString realPath = origPath; if (realPath.endsWith(QDir::separator())) realPath = realPath.mid(0, realPath.size() - 1); @@ -362,17 +363,17 @@ QStringList QFseventsFileSystemWatcherEngine::addPaths(const QStringList &paths, continue; directories->append(origPath); watchedPath = realPath; - it.remove(); } else { if (files->contains(origPath)) continue; files->append(origPath); - it.remove(); watchedPath = fi.path(); parentPath = watchedPath; } + sg.dismiss(); + for (PathRefCounts::const_iterator i = watchingState.watchedPaths.begin(), ei = watchingState.watchedPaths.end(); i != ei; ++i) { if (watchedPath.startsWith(i.key() % QDir::separator())) { @@ -407,16 +408,16 @@ QStringList QFseventsFileSystemWatcherEngine::addPaths(const QStringList &paths, stopStream(); if (!startStream()) { // ok, something went wrong, let's try to restore the previous state - watchingState = qMove(oldState); + watchingState = std::move(oldState); // and because we don't know which path caused the issue (if any), fail on all of them - p = paths; + unhandled = paths; if (wasRunning) startStream(); } } - return p; + return unhandled; } QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &paths, @@ -430,10 +431,9 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat bool needsRestart = false; WatchingState oldState = watchingState; - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString origPath = it.next(); + QStringList unhandled; + for (const QString &origPath : paths) { + auto sg = qScopeGuard([&]{ unhandled.push_back(origPath); }); QString realPath = origPath; if (realPath.endsWith(QDir::separator())) realPath = realPath.mid(0, realPath.size() - 1); @@ -447,7 +447,7 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat needsRestart |= derefPath(dirIt->dirInfo.watchedPath); watchingState.watchedDirectories.erase(dirIt); directories->removeAll(origPath); - it.remove(); + sg.dismiss(); DEBUG("Removed directory '%s'", qPrintable(realPath)); } } else { @@ -463,7 +463,7 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat if (filesInDir.isEmpty()) watchingState.watchedFiles.erase(pIt); files->removeAll(origPath); - it.remove(); + sg.dismiss(); DEBUG("Removed file '%s'", qPrintable(realPath)); } } @@ -474,12 +474,12 @@ QStringList QFseventsFileSystemWatcherEngine::removePaths(const QStringList &pat if (needsRestart) { if (!restartStream()) { - watchingState = qMove(oldState); + watchingState = std::move(oldState); startStream(); } } - return p; + return unhandled; } // Returns false if FSEventStream* calls failed for some mysterious reason, true if things got a diff --git a/src/corelib/io/qfilesystemwatcher_inotify.cpp b/src/corelib/io/qfilesystemwatcher_inotify.cpp index a5e629b646..ca1f6cc359 100644 --- a/src/corelib/io/qfilesystemwatcher_inotify.cpp +++ b/src/corelib/io/qfilesystemwatcher_inotify.cpp @@ -46,6 +46,7 @@ #include <qdebug.h> #include <qfile.h> #include <qfileinfo.h> +#include <qscopeguard.h> #include <qsocketnotifier.h> #include <qvarlengtharray.h> @@ -268,12 +269,11 @@ QStringList QInotifyFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { QFileInfo fi(path); bool isDir = fi.isDir(); + auto sg = qScopeGuard([&]{ unhandled.push_back(path); }); if (isDir) { if (directories->contains(path)) continue; @@ -305,7 +305,7 @@ QStringList QInotifyFileSystemWatcherEngine::addPaths(const QStringList &paths, continue; } - it.remove(); + sg.dismiss(); int id = isDir ? -wd : wd; if (id < 0) { @@ -318,19 +318,19 @@ QStringList QInotifyFileSystemWatcherEngine::addPaths(const QStringList &paths, idToPath.insert(id, path); } - return p; + return unhandled; } QStringList QInotifyFileSystemWatcherEngine::removePaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { int id = pathToID.take(path); + auto sg = qScopeGuard([&]{ unhandled.push_back(path); }); + // Multiple paths could be associated to the same watch descriptor // when a file is moved and added with the new name. // So we should find and delete the correct one by using @@ -349,7 +349,8 @@ QStringList QInotifyFileSystemWatcherEngine::removePaths(const QStringList &path inotify_rm_watch(inotifyFd, wd); } - it.remove(); + sg.dismiss(); + if (id < 0) { directories->removeAll(path); } else { @@ -357,7 +358,7 @@ QStringList QInotifyFileSystemWatcherEngine::removePaths(const QStringList &path } } - return p; + return unhandled; } void QInotifyFileSystemWatcherEngine::readFromInotify() @@ -388,7 +389,7 @@ void QInotifyFileSystemWatcherEngine::readFromInotify() const inotify_event &event = **it; ++it; - // qDebug() << "inotify event, wd" << event.wd << "mask" << hex << event.mask; + // qDebug() << "inotify event, wd" << event.wd << "mask" << Qt::hex << event.mask; int id = event.wd; QString path = getPathFromID(id); @@ -421,16 +422,27 @@ void QInotifyFileSystemWatcherEngine::readFromInotify() } } -QString QInotifyFileSystemWatcherEngine::getPathFromID(int id) const +template <typename Hash, typename Key> +typename Hash::const_iterator +find_last_in_equal_range(const Hash &c, const Key &key) { - QHash<int, QString>::const_iterator i = idToPath.find(id); - while (i != idToPath.constEnd() && i.key() == id) { - if ((i + 1) == idToPath.constEnd() || (i + 1).key() != id) { - return i.value(); - } + // find c.equal_range(key).second - 1 without backwards iteration: + auto i = c.find(key); + const auto end = c.cend(); + if (i == end) + return end; + decltype(i) prev; + do { + prev = i; ++i; - } - return QString(); + } while (i != end && i.key() == key); + return prev; +} + +QString QInotifyFileSystemWatcherEngine::getPathFromID(int id) const +{ + auto i = find_last_in_equal_range(idToPath, id); + return i == idToPath.cend() ? QString() : i.value() ; } QT_END_NAMESPACE diff --git a/src/corelib/io/qfilesystemwatcher_kqueue.cpp b/src/corelib/io/qfilesystemwatcher_kqueue.cpp index 423b88cb7f..c2028e3641 100644 --- a/src/corelib/io/qfilesystemwatcher_kqueue.cpp +++ b/src/corelib/io/qfilesystemwatcher_kqueue.cpp @@ -45,6 +45,7 @@ #include <qdebug.h> #include <qfile.h> +#include <qscopeguard.h> #include <qsocketnotifier.h> #include <qvarlengtharray.h> @@ -94,10 +95,9 @@ QStringList QKqueueFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&]{unhandled.push_back(path);}); int fd; #if defined(O_EVTONLY) fd = qt_safe_open(QFile::encodeName(path), O_EVTONLY); @@ -149,7 +149,8 @@ QStringList QKqueueFileSystemWatcherEngine::addPaths(const QStringList &paths, continue; } - it.remove(); + sg.dismiss(); + if (id < 0) { DEBUG() << "QKqueueFileSystemWatcherEngine: added directory path" << path; directories->append(path); @@ -162,20 +163,19 @@ QStringList QKqueueFileSystemWatcherEngine::addPaths(const QStringList &paths, idToPath.insert(id, path); } - return p; + return unhandled; } QStringList QKqueueFileSystemWatcherEngine::removePaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; if (pathToID.isEmpty()) - return p; + return paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&]{unhandled.push_back(path);}); int id = pathToID.take(path); QString x = idToPath.take(id); if (x.isEmpty() || x != path) @@ -183,14 +183,15 @@ QStringList QKqueueFileSystemWatcherEngine::removePaths(const QStringList &paths ::close(id < 0 ? -id : id); - it.remove(); + sg.dismiss(); + if (id < 0) directories->removeAll(path); else files->removeAll(path); } - return p; + return unhandled; } void QKqueueFileSystemWatcherEngine::readFromKqueue() diff --git a/src/corelib/io/qfilesystemwatcher_polling.cpp b/src/corelib/io/qfilesystemwatcher_polling.cpp index 903c15f4a9..e07b02f7c2 100644 --- a/src/corelib/io/qfilesystemwatcher_polling.cpp +++ b/src/corelib/io/qfilesystemwatcher_polling.cpp @@ -38,6 +38,7 @@ ****************************************************************************/ #include "qfilesystemwatcher_polling_p.h" +#include <QtCore/qscopeguard.h> #include <QtCore/qtimer.h> QT_BEGIN_NAMESPACE @@ -53,10 +54,9 @@ QStringList QPollingFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&]{ unhandled.push_back(path); }); QFileInfo fi(path); if (!fi.exists()) continue; @@ -73,7 +73,7 @@ QStringList QPollingFileSystemWatcherEngine::addPaths(const QStringList &paths, files->append(path); this->files.insert(path, fi); } - it.remove(); + sg.dismiss(); } if ((!this->files.isEmpty() || @@ -82,23 +82,21 @@ QStringList QPollingFileSystemWatcherEngine::addPaths(const QStringList &paths, timer.start(PollingInterval); } - return p; + return unhandled; } QStringList QPollingFileSystemWatcherEngine::removePaths(const QStringList &paths, QStringList *files, QStringList *directories) { - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { if (this->directories.remove(path)) { directories->removeAll(path); - it.remove(); } else if (this->files.remove(path)) { files->removeAll(path); - it.remove(); + } else { + unhandled.push_back(path); } } @@ -107,38 +105,37 @@ QStringList QPollingFileSystemWatcherEngine::removePaths(const QStringList &path timer.stop(); } - return p; + return unhandled; } void QPollingFileSystemWatcherEngine::timeout() { - QMutableHashIterator<QString, FileInfo> fit(files); - while (fit.hasNext()) { - QHash<QString, FileInfo>::iterator x = fit.next(); + for (auto it = files.begin(), end = files.end(); it != end; /*erasing*/) { + auto x = it++; QString path = x.key(); QFileInfo fi(path); if (!fi.exists()) { - fit.remove(); + files.erase(x); emit fileChanged(path, true); } else if (x.value() != fi) { x.value() = fi; emit fileChanged(path, false); } } - QMutableHashIterator<QString, FileInfo> dit(directories); - while (dit.hasNext()) { - QHash<QString, FileInfo>::iterator x = dit.next(); + + for (auto it = directories.begin(), end = directories.end(); it != end; /*erasing*/) { + auto x = it++; QString path = x.key(); QFileInfo fi(path); if (!path.endsWith(QLatin1Char('/'))) fi = QFileInfo(path + QLatin1Char('/')); if (!fi.exists()) { - dit.remove(); + directories.erase(x); emit directoryChanged(path, true); } else if (x.value() != fi) { fi.refresh(); if (!fi.exists()) { - dit.remove(); + directories.erase(x); emit directoryChanged(path, true); } else { x.value() = fi; diff --git a/src/corelib/io/qfilesystemwatcher_win.cpp b/src/corelib/io/qfilesystemwatcher_win.cpp index 66985f8982..c22a003931 100644 --- a/src/corelib/io/qfilesystemwatcher_win.cpp +++ b/src/corelib/io/qfilesystemwatcher_win.cpp @@ -44,6 +44,7 @@ #include <qfileinfo.h> #include <qstringlist.h> #include <qset.h> +#include <qscopeguard.h> #include <qdatetime.h> #include <qdir.h> #include <qtextstream.h> @@ -79,7 +80,7 @@ static Qt::HANDLE createChangeNotification(const QString &path, uint flags) nativePath.append(QLatin1Char('\\')); const HANDLE result = FindFirstChangeNotification(reinterpret_cast<const wchar_t *>(nativePath.utf16()), FALSE, flags); - DEBUG() << __FUNCTION__ << nativePath << hex <<showbase << flags << "returns" << result; + DEBUG() << __FUNCTION__ << nativePath << Qt::hex <<showbase << flags << "returns" << result; return result; } @@ -108,7 +109,11 @@ public: // Call from QFileSystemWatcher::addPaths() to set up notifications on drives void addPath(const QString &path); +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + bool nativeEventFilter(const QByteArray &, void *messageIn, qintptr *) override; +#else bool nativeEventFilter(const QByteArray &, void *messageIn, long *) override; +#endif signals: void driveAdded(); @@ -255,7 +260,11 @@ inline void QWindowsRemovableDriveListener::handleDbtDriveArrivalRemoval(const M } } +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +bool QWindowsRemovableDriveListener::nativeEventFilter(const QByteArray &, void *messageIn, qintptr *) +#else bool QWindowsRemovableDriveListener::nativeEventFilter(const QByteArray &, void *messageIn, long *) +#endif { const MSG *msg = reinterpret_cast<const MSG *>(messageIn); if (msg->message == WM_DEVICECHANGE) { @@ -297,8 +306,7 @@ void QWindowsRemovableDriveListener::addPath(const QString &p) OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, // Volume requires BACKUP_SEMANTICS 0); if (volumeHandle == INVALID_HANDLE_VALUE) { - qErrnoWarning("CreateFile %s failed.", - qPrintable(QString::fromWCharArray(devicePath))); + qErrnoWarning("CreateFile %ls failed.", devicePath); return; } @@ -315,8 +323,7 @@ void QWindowsRemovableDriveListener::addPath(const QString &p) // closed. Do it here to avoid having to close/reopen in lock message handling. CloseHandle(volumeHandle); if (!re.devNotify) { - qErrnoWarning("RegisterDeviceNotification %s failed.", - qPrintable(QString::fromWCharArray(devicePath))); + qErrnoWarning("RegisterDeviceNotification %ls failed.", devicePath); return; } @@ -369,10 +376,9 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *directories) { DEBUG() << "Adding" << paths.count() << "to existing" << (files->count() + directories->count()) << "watchers"; - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&] { unhandled.push_back(path); }); QString normalPath = path; if ((normalPath.endsWith(QLatin1Char('/')) && !normalPath.endsWith(QLatin1String(":/"))) || (normalPath.endsWith(QLatin1Char('\\')) && !normalPath.endsWith(QLatin1String(":\\")))) { @@ -424,7 +430,7 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, // Requesting to add a file whose directory has been added previously. // Recreate the notification handle to add the missing notification attributes // for files (FILE_NOTIFY_CHANGE_ATTRIBUTES...) - DEBUG() << "recreating" << absolutePath << hex << showbase << hit.value().flags + DEBUG() << "recreating" << absolutePath << Qt::hex << Qt::showbase << hit.value().flags << "->" << flags; const Qt::HANDLE fileHandle = createChangeNotification(absolutePath, flags); if (fileHandle != INVALID_HANDLE_VALUE) { @@ -455,7 +461,7 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, else files->append(path); } - it.remove(); + sg.dismiss(); thread->wakeup(); break; } @@ -485,7 +491,7 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, else files->append(path); - it.remove(); + sg.dismiss(); found = true; thread->wakeup(); break; @@ -511,7 +517,7 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, thread->msg = '@'; thread->start(); threads.append(thread); - it.remove(); + sg.dismiss(); } } } @@ -519,12 +525,12 @@ QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths, #ifndef Q_OS_WINRT if (Q_LIKELY(m_driveListener)) { for (const QString &path : paths) { - if (!p.contains(path)) + if (!unhandled.contains(path)) m_driveListener->addPath(path); } } #endif // !Q_OS_WINRT - return p; + return unhandled; } QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &paths, @@ -532,10 +538,9 @@ QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &path QStringList *directories) { DEBUG() << "removePaths" << paths; - QStringList p = paths; - QMutableListIterator<QString> it(p); - while (it.hasNext()) { - QString path = it.next(); + QStringList unhandled; + for (const QString &path : paths) { + auto sg = qScopeGuard([&] { unhandled.push_back(path); }); QString normalPath = path; if (normalPath.endsWith(QLatin1Char('/')) || normalPath.endsWith(QLatin1Char('\\'))) normalPath.chop(1); @@ -564,7 +569,7 @@ QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &path // ### files->removeAll(path); directories->removeAll(path); - it.remove(); + sg.dismiss(); if (h.isEmpty()) { DEBUG() << "Closing handle" << handle.handle; @@ -605,7 +610,7 @@ QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &path } threads.removeAll(0); - return p; + return unhandled; } /////////// @@ -634,15 +639,15 @@ QWindowsFileSystemWatcherEngineThread::~QWindowsFileSystemWatcherEngineThread() } } -static inline QString msgFindNextFailed(const QWindowsFileSystemWatcherEngineThread::PathInfoHash &pathInfos) +Q_DECL_COLD_FUNCTION +static QString msgFindNextFailed(const QWindowsFileSystemWatcherEngineThread::PathInfoHash &pathInfos) { - QString result; - QTextStream str(&result); - str << "QFileSystemWatcher: FindNextChangeNotification failed for"; + QString str; + str += QLatin1String("QFileSystemWatcher: FindNextChangeNotification failed for"); for (const QWindowsFileSystemWatcherEngine::PathInfo &pathInfo : pathInfos) - str << " \"" << QDir::toNativeSeparators(pathInfo.absolutePath) << '"'; - str << ' '; - return result; + str += QLatin1String(" \"") + QDir::toNativeSeparators(pathInfo.absolutePath) + QLatin1Char('"'); + str += QLatin1Char(' '); + return str; } void QWindowsFileSystemWatcherEngineThread::run() @@ -688,11 +693,10 @@ void QWindowsFileSystemWatcherEngineThread::run() fakeRemove = true; } - qErrnoWarning(error, "%s", qPrintable(msgFindNextFailed(h))); + qErrnoWarning(error, "%ls", qUtf16Printable(msgFindNextFailed(h))); } - QMutableHashIterator<QFileSystemWatcherPathKey, QWindowsFileSystemWatcherEngine::PathInfo> it(h); - while (it.hasNext()) { - QWindowsFileSystemWatcherEngineThread::PathInfoHash::iterator x = it.next(); + for (auto it = h.begin(), end = h.end(); it != end; /*erasing*/ ) { + auto x = it++; QString absolutePath = x.value().absolutePath; QFileInfo fileInfo(x.value().path); DEBUG() << "checking" << x.key(); @@ -718,6 +722,7 @@ void QWindowsFileSystemWatcherEngineThread::run() handleForDir.remove(QFileSystemWatcherPathKey(absolutePath)); // h is now invalid + break; } } else if (x.value().isDir) { DEBUG() << x.key() << "directory changed!"; diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index 5d3bef9e70..0d73839f8d 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -127,7 +127,7 @@ void QFSFileEnginePrivate::init() is_link = 0; openMode = QIODevice::NotOpen; fd = -1; - fh = 0; + fh = nullptr; lastIOCommand = IOFlushCommand; lastFlushFailed = false; closeFileHandle = false; @@ -247,7 +247,7 @@ bool QFSFileEngine::open(QIODevice::OpenMode openMode) d->openMode = res.openMode; d->lastFlushFailed = false; d->tried_stat = 0; - d->fh = 0; + d->fh = nullptr; d->fd = -1; return d->nativeOpen(d->openMode); @@ -309,7 +309,7 @@ bool QFSFileEnginePrivate::openFh(QIODevice::OpenMode openMode, FILE *fh) QSystemError::stdString()); this->openMode = QIODevice::NotOpen; - this->fh = 0; + this->fh = nullptr; return false; } @@ -341,7 +341,7 @@ bool QFSFileEngine::open(QIODevice::OpenMode openMode, int fd, QFile::FileHandle d->lastFlushFailed = false; d->closeFileHandle = (handleFlags & QFile::AutoCloseHandle); d->fileEntry.clear(); - d->fh = 0; + d->fh = nullptr; d->fd = -1; d->tried_stat = 0; @@ -357,7 +357,7 @@ bool QFSFileEnginePrivate::openFd(QIODevice::OpenMode openMode, int fd) { Q_Q(QFSFileEngine); this->fd = fd; - fh = 0; + fh = nullptr; // Seek to the end when in Append mode. if (openMode & QFile::Append) { @@ -418,7 +418,7 @@ bool QFSFileEnginePrivate::closeFdFh() // We must reset these guys regardless; calling close again after a // failed close causes crashes on some systems. - fh = 0; + fh = nullptr; fd = -1; closed = (ret == 0); } @@ -835,7 +835,7 @@ QAbstractFileEngine::Iterator *QFSFileEngine::beginEntryList(QDir::Filters filte */ QAbstractFileEngine::Iterator *QFSFileEngine::endEntryList() { - return 0; + return nullptr; } #endif // QT_NO_FILESYSTEMITERATOR @@ -883,7 +883,7 @@ bool QFSFileEngine::extension(Extension extension, const ExtensionOption *option const MapExtensionOption *options = (const MapExtensionOption*)(option); MapExtensionReturn *returnValue = static_cast<MapExtensionReturn*>(output); returnValue->address = d->map(options->offset, options->size, options->flags); - return (returnValue->address != 0); + return (returnValue->address != nullptr); } if (extension == UnMapExtension) { const UnMapExtensionOption *options = (const UnMapExtensionOption*)option; diff --git a/src/corelib/io/qfsfileengine_p.h b/src/corelib/io/qfsfileengine_p.h index 5231b4fe6f..79593a3e1c 100644 --- a/src/corelib/io/qfsfileengine_p.h +++ b/src/corelib/io/qfsfileengine_p.h @@ -122,7 +122,7 @@ public: virtual bool isUnnamedFile() const { return false; } - bool extension(Extension extension, const ExtensionOption *option = 0, ExtensionReturn *output = 0) override; + bool extension(Extension extension, const ExtensionOption *option = nullptr, ExtensionReturn *output = nullptr) override; bool supportsExtension(Extension extension) const override; //FS only!! diff --git a/src/corelib/io/qfsfileengine_unix.cpp b/src/corelib/io/qfsfileengine_unix.cpp index 90ad0126d6..d4983c72af 100644 --- a/src/corelib/io/qfsfileengine_unix.cpp +++ b/src/corelib/io/qfsfileengine_unix.cpp @@ -153,7 +153,7 @@ bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode) } } - fh = 0; + fh = nullptr; } closeFileHandle = true; @@ -451,14 +451,14 @@ QAbstractFileEngine::FileFlags QFSFileEngine::fileFlags(FileFlags type) const if (type & Refresh) d->metaData.clear(); - QAbstractFileEngine::FileFlags ret = 0; + QAbstractFileEngine::FileFlags ret = { }; if (type & FlagsMask) ret |= LocalDiskFlag; bool exists; { - QFileSystemMetaData::MetaDataFlags queryFlags = 0; + QFileSystemMetaData::MetaDataFlags queryFlags = { }; queryFlags |= QFileSystemMetaData::MetaDataFlags(uint(type)) & QFileSystemMetaData::Permissions; @@ -590,9 +590,9 @@ bool QFSFileEngine::setPermissions(uint perms) QSystemError error; bool ok; if (d->fd != -1) - ok = QFileSystemEngine::setPermissions(d->fd, QFile::Permissions(perms), error, 0); + ok = QFileSystemEngine::setPermissions(d->fd, QFile::Permissions(perms), error); else - ok = QFileSystemEngine::setPermissions(d->fileEntry, QFile::Permissions(perms), error, 0); + ok = QFileSystemEngine::setPermissions(d->fileEntry, QFile::Permissions(perms), error); if (!ok) { setError(QFile::PermissionsError, error.toString()); return false; @@ -651,13 +651,13 @@ uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFla Q_Q(QFSFileEngine); if (openMode == QIODevice::NotOpen) { q->setError(QFile::PermissionsError, qt_error_string(int(EACCES))); - return 0; + return nullptr; } if (offset < 0 || offset > maxFileOffset || size < 0 || quint64(size) > quint64(size_t(-1))) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); - return 0; + return nullptr; } // If we know the mapping will extend beyond EOF, fail early to avoid @@ -685,14 +685,14 @@ uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFla if (quint64(size + extra) > quint64((size_t)-1)) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); - return 0; + return nullptr; } size_t realSize = (size_t)size + extra; QT_OFF_T realOffset = QT_OFF_T(offset); realOffset &= ~(QT_OFF_T(pageSize - 1)); - void *mapAddress = QT_MMAP((void*)0, realSize, + void *mapAddress = QT_MMAP((void*)nullptr, realSize, access, sharemode, nativeHandle(), realOffset); if (MAP_FAILED != mapAddress) { uchar *address = extra + static_cast<uchar*>(mapAddress); @@ -714,7 +714,7 @@ uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFla q->setError(QFile::UnspecifiedError, qt_error_string(int(errno))); break; } - return 0; + return nullptr; } bool QFSFileEnginePrivate::unmap(uchar *ptr) diff --git a/src/corelib/io/qiodevice.cpp b/src/corelib/io/qiodevice.cpp index 74df0f71ef..e26508e631 100644 --- a/src/corelib/io/qiodevice.cpp +++ b/src/corelib/io/qiodevice.cpp @@ -169,7 +169,7 @@ QIODevicePrivate::QIODevicePrivate() , baseReadLineDataCalled(false) , accessMode(Unset) #ifdef QT_NO_QOBJECT - , q_ptr(0) + , q_ptr(nullptr) #endif { } diff --git a/src/corelib/io/qipaddress.cpp b/src/corelib/io/qipaddress.cpp index 039e291b43..ddc5b6607f 100644 --- a/src/corelib/io/qipaddress.cpp +++ b/src/corelib/io/qipaddress.cpp @@ -67,7 +67,7 @@ static const QChar *checkedToAscii(Buffer &buffer, const QChar *begin, const QCh *dst++ = *src++; } *dst = '\0'; - return 0; + return nullptr; } static bool parseIp4Internal(IPv4Address &address, const char *ptr, bool acceptLeadingZero); @@ -175,7 +175,7 @@ const QChar *parseIp6(IPv6Address &address, const QChar *begin, const QChar *end memset(address, 0, sizeof address); if (colonCount == 2 && end - begin == 2) // "::" - return 0; + return nullptr; // if there's a double colon ("::"), this is how many zeroes it means int zeroWordsToFill; @@ -236,7 +236,7 @@ const QChar *parseIp6(IPv6Address &address, const QChar *begin, const QChar *end address[13] = ip4 >> 16; address[14] = ip4 >> 8; address[15] = ip4; - return 0; + return nullptr; } address[pos++] = x >> 8; @@ -248,15 +248,15 @@ const QChar *parseIp6(IPv6Address &address, const QChar *begin, const QChar *end return begin + (endptr - buffer.data()); ptr = endptr + 1; } - return pos == 16 ? 0 : end; + return pos == 16 ? nullptr : end; } static inline QChar toHex(uchar c) { - return QtMiscUtils::toHexLower(c); + return QChar::fromLatin1(QtMiscUtils::toHexLower(c)); } -void toString(QString &appendTo, IPv6Address address) +void toString(QString &appendTo, const IPv6Address address) { // the longest IPv6 address possible is: // "1111:2222:3333:4444:5555:6666:255.255.255.255" @@ -312,7 +312,7 @@ void toString(QString &appendTo, IPv6Address address) } } - const QChar colon = ushort(':'); + const QChar colon = u':'; if (zeroRunLength < 4) zeroRunOffset = -1; else if (zeroRunOffset == 0) diff --git a/src/corelib/io/qipaddress_p.h b/src/corelib/io/qipaddress_p.h index d95cccb3bd..ea31e5883d 100644 --- a/src/corelib/io/qipaddress_p.h +++ b/src/corelib/io/qipaddress_p.h @@ -64,7 +64,7 @@ typedef quint8 IPv6Address[16]; Q_CORE_EXPORT bool parseIp4(IPv4Address &address, const QChar *begin, const QChar *end); Q_CORE_EXPORT const QChar *parseIp6(IPv6Address &address, const QChar *begin, const QChar *end); Q_CORE_EXPORT void toString(QString &appendTo, IPv4Address address); -Q_CORE_EXPORT void toString(QString &appendTo, IPv6Address address); +Q_CORE_EXPORT void toString(QString &appendTo, const IPv6Address address); } // namespace diff --git a/src/corelib/io/qlockfile_unix.cpp b/src/corelib/io/qlockfile_unix.cpp index 418b7d22ba..b2bf77c0da 100644 --- a/src/corelib/io/qlockfile_unix.cpp +++ b/src/corelib/io/qlockfile_unix.cpp @@ -58,6 +58,11 @@ #include <sys/file.h> // flock #endif +#if defined(Q_OS_RTEMS) +# undef LOCK_EX +# undef LOCK_NB +#endif + #include <sys/types.h> // kill #include <signal.h> // kill #include <unistd.h> // gethostname @@ -169,7 +174,7 @@ QLockFile::LockError QLockFilePrivate::tryLock_sys() if (qt_write_loop(fd, fileData.constData(), fileData.size()) < fileData.size()) { qt_safe_close(fd); if (!QFile::remove(fileName)) - qWarning("QLockFile: Could not remove our own lock file %s.", qPrintable(fileName)); + qWarning("QLockFile: Could not remove our own lock file %ls.", qUtf16Printable(fileName)); return QLockFile::UnknownError; // partition full } diff --git a/src/corelib/io/qloggingcategory.cpp b/src/corelib/io/qloggingcategory.cpp index 33253429a2..f6ff56c83c 100644 --- a/src/corelib/io/qloggingcategory.cpp +++ b/src/corelib/io/qloggingcategory.cpp @@ -214,8 +214,8 @@ static void setBoolLane(QBasicAtomicInt *atomic, bool enable, int shift) Note that \a category must be kept valid during the lifetime of this object. */ QLoggingCategory::QLoggingCategory(const char *category) - : d(0), - name(0) + : d(nullptr), + name(nullptr) { init(category, QtDebugMsg); } @@ -231,15 +231,15 @@ QLoggingCategory::QLoggingCategory(const char *category) \since 5.4 */ QLoggingCategory::QLoggingCategory(const char *category, QtMsgType enableForLevel) - : d(0), - name(0) + : d(nullptr), + name(nullptr) { init(category, enableForLevel); } void QLoggingCategory::init(const char *category, QtMsgType severityLevel) { - enabled.store(0x01010101); // enabledDebug = enabledWarning = enabledCritical = true; + enabled.storeRelaxed(0x01010101); // enabledDebug = enabledWarning = enabledCritical = true; if (category) name = category; @@ -342,10 +342,10 @@ void QLoggingCategory::setEnabled(QtMsgType type, bool enable) { switch (type) { #ifdef Q_ATOMIC_INT8_IS_SUPPORTED - case QtDebugMsg: bools.enabledDebug.store(enable); break; - case QtInfoMsg: bools.enabledInfo.store(enable); break; - case QtWarningMsg: bools.enabledWarning.store(enable); break; - case QtCriticalMsg: bools.enabledCritical.store(enable); break; + case QtDebugMsg: bools.enabledDebug.storeRelaxed(enable); break; + case QtInfoMsg: bools.enabledInfo.storeRelaxed(enable); break; + case QtWarningMsg: bools.enabledWarning.storeRelaxed(enable); break; + case QtCriticalMsg: bools.enabledCritical.storeRelaxed(enable); break; #else case QtDebugMsg: setBoolLane(&enabled, enable, DebugShift); break; case QtInfoMsg: setBoolLane(&enabled, enable, InfoShift); break; diff --git a/src/corelib/io/qloggingcategory.h b/src/corelib/io/qloggingcategory.h index 91e3144300..1c3e10b493 100644 --- a/src/corelib/io/qloggingcategory.h +++ b/src/corelib/io/qloggingcategory.h @@ -58,15 +58,15 @@ public: void setEnabled(QtMsgType type, bool enable); #ifdef Q_ATOMIC_INT8_IS_SUPPORTED - bool isDebugEnabled() const { return bools.enabledDebug.load(); } - bool isInfoEnabled() const { return bools.enabledInfo.load(); } - bool isWarningEnabled() const { return bools.enabledWarning.load(); } - bool isCriticalEnabled() const { return bools.enabledCritical.load(); } + bool isDebugEnabled() const { return bools.enabledDebug.loadRelaxed(); } + bool isInfoEnabled() const { return bools.enabledInfo.loadRelaxed(); } + bool isWarningEnabled() const { return bools.enabledWarning.loadRelaxed(); } + bool isCriticalEnabled() const { return bools.enabledCritical.loadRelaxed(); } #else - bool isDebugEnabled() const { return enabled.load() >> DebugShift & 1; } - bool isInfoEnabled() const { return enabled.load() >> InfoShift & 1; } - bool isWarningEnabled() const { return enabled.load() >> WarningShift & 1; } - bool isCriticalEnabled() const { return enabled.load() >> CriticalShift & 1; } + bool isDebugEnabled() const { return enabled.loadRelaxed() >> DebugShift & 1; } + bool isInfoEnabled() const { return enabled.loadRelaxed() >> InfoShift & 1; } + bool isWarningEnabled() const { return enabled.loadRelaxed() >> WarningShift & 1; } + bool isCriticalEnabled() const { return enabled.loadRelaxed() >> CriticalShift & 1; } #endif const char *categoryName() const { return name; } @@ -111,8 +111,6 @@ private: #define Q_DECLARE_LOGGING_CATEGORY(name) \ extern const QLoggingCategory &name(); -#if defined(Q_COMPILER_VARIADIC_MACROS) || defined(Q_MOC_RUN) - #define Q_LOGGING_CATEGORY(name, ...) \ const QLoggingCategory &name() \ { \ @@ -148,39 +146,6 @@ private: for (bool qt_category_enabled = category().isCriticalEnabled(); qt_category_enabled; qt_category_enabled = false) \ QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, category().categoryName()).critical(__VA_ARGS__) -#else // defined(Q_COMPILER_VARIADIC_MACROS) || defined(Q_MOC_RUN) - -// Optional msgType argument not supported -#define Q_LOGGING_CATEGORY(name, string) \ - const QLoggingCategory &name() \ - { \ - static const QLoggingCategory category(string); \ - return category; \ - } - -// check for enabled category inside QMessageLogger. -#if !defined(QT_NO_DEBUG_OUTPUT) -# define qCDebug qDebug -#else -# define qCDebug(category) QT_NO_QDEBUG_MACRO() -#endif - -#if !defined(QT_NO_INFO_OUTPUT) -# define qCInfo qInfo -#else -# define qCInfo(category) QT_NO_QDEBUG_MACRO() -#endif - -#if !defined(QT_NO_WARNING_OUTPUT) -# define qCWarning qWarning -#else -# define qCWarning(category) QT_NO_QDEBUG_MACRO() -#endif - -#define qCCritical qCritical - -#endif // Q_COMPILER_VARIADIC_MACROS || defined(Q_MOC_RUN) - QT_END_NAMESPACE #endif // QLOGGINGCATEGORY_H diff --git a/src/corelib/io/qloggingregistry.cpp b/src/corelib/io/qloggingregistry.cpp index 9792d956cc..7849dfd14c 100644 --- a/src/corelib/io/qloggingregistry.cpp +++ b/src/corelib/io/qloggingregistry.cpp @@ -165,7 +165,7 @@ void QLoggingRule::parse(const QStringRef &pattern) p = QStringRef(p.string(), p.position() + 1, p.length() - 1); } if (p.contains(QLatin1Char('*'))) // '*' only supported at start/end - flags = 0; + flags = PatternFlags(); } category = p.toString(); @@ -415,7 +415,7 @@ QLoggingRegistry::installFilter(QLoggingCategory::CategoryFilter filter) { QMutexLocker locker(®istryMutex); - if (filter == 0) + if (!filter) filter = defaultCategoryFilter; QLoggingCategory::CategoryFilter old = categoryFilter; diff --git a/src/corelib/io/qnoncontiguousbytedevice.cpp b/src/corelib/io/qnoncontiguousbytedevice.cpp index beca6ccbf7..d1806aa12b 100644 --- a/src/corelib/io/qnoncontiguousbytedevice.cpp +++ b/src/corelib/io/qnoncontiguousbytedevice.cpp @@ -534,7 +534,7 @@ QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QSharedPointer */ QSharedPointer<QNonContiguousByteDevice> QNonContiguousByteDeviceFactory::createShared(QSharedPointer<QRingBuffer> ringBuffer) { - return QSharedPointer<QNonContiguousByteDeviceRingBufferImpl>::create(qMove(ringBuffer)); + return QSharedPointer<QNonContiguousByteDeviceRingBufferImpl>::create(std::move(ringBuffer)); } /*! diff --git a/src/corelib/io/qprocess.cpp b/src/corelib/io/qprocess.cpp index 9557a1d24b..35ca2542f7 100644 --- a/src/corelib/io/qprocess.cpp +++ b/src/corelib/io/qprocess.cpp @@ -42,6 +42,7 @@ #include <qdebug.h> #include <qdir.h> +#include <qscopedvaluerollback.h> #if defined(Q_OS_WIN) #include <qtimer.h> #endif @@ -201,6 +202,7 @@ void QProcessEnvironmentPrivate::insert(const QProcessEnvironmentPrivate &other) vars.insert(it.key(), it.value()); #ifdef Q_OS_UNIX + const OrderedNameMapMutexLocker locker(this, &other); auto nit = other.nameMap.constBegin(); const auto nend = other.nameMap.constEnd(); for ( ; nit != nend; ++nit) @@ -274,7 +276,6 @@ bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const return true; if (d) { if (other.d) { - QProcessEnvironmentPrivate::OrderedMutexLocker locker(d, other.d); return d->vars == other.d->vars; } else { return isEmpty(); @@ -321,7 +322,6 @@ bool QProcessEnvironment::contains(const QString &name) const { if (!d) return false; - QProcessEnvironmentPrivate::MutexLocker locker(d); return d->vars.contains(d->prepareName(name)); } @@ -372,7 +372,6 @@ QString QProcessEnvironment::value(const QString &name, const QString &defaultVa if (!d) return defaultValue; - QProcessEnvironmentPrivate::MutexLocker locker(d); const auto it = d->vars.constFind(d->prepareName(name)); if (it == d->vars.constEnd()) return defaultValue; @@ -397,7 +396,6 @@ QStringList QProcessEnvironment::toStringList() const { if (!d) return QStringList(); - QProcessEnvironmentPrivate::MutexLocker locker(d); return d->toList(); } @@ -411,7 +409,6 @@ QStringList QProcessEnvironment::keys() const { if (!d) return QStringList(); - QProcessEnvironmentPrivate::MutexLocker locker(d); return d->keys(); } @@ -428,7 +425,6 @@ void QProcessEnvironment::insert(const QProcessEnvironment &e) return; // our re-impl of detach() detaches from null - QProcessEnvironmentPrivate::MutexLocker locker(e.d); d->insert(*e.d); } @@ -1068,9 +1064,8 @@ bool QProcessPrivate::tryReadFromChannel(Channel *channel) if (currentReadChannel == channelIdx) { didRead = true; if (!emittedReadyRead) { - emittedReadyRead = true; + QScopedValueRollback<bool> guard(emittedReadyRead, true); emit q->readyRead(); - emittedReadyRead = false; } } emit q->channelReadyRead(int(channelIdx)); diff --git a/src/corelib/io/qprocess.h b/src/corelib/io/qprocess.h index a2e3c01f7c..9fda5fba11 100644 --- a/src/corelib/io/qprocess.h +++ b/src/corelib/io/qprocess.h @@ -72,12 +72,10 @@ public: QProcessEnvironment(); QProcessEnvironment(const QProcessEnvironment &other); ~QProcessEnvironment(); -#ifdef Q_COMPILER_RVALUE_REFS - QProcessEnvironment &operator=(QProcessEnvironment && other) Q_DECL_NOTHROW { swap(other); return *this; } -#endif + QProcessEnvironment &operator=(QProcessEnvironment && other) noexcept { swap(other); return *this; } QProcessEnvironment &operator=(const QProcessEnvironment &other); - void swap(QProcessEnvironment &other) Q_DECL_NOTHROW { qSwap(d, other.d); } + void swap(QProcessEnvironment &other) noexcept { qSwap(d, other.d); } bool operator==(const QProcessEnvironment &other) const; inline bool operator!=(const QProcessEnvironment &other) const diff --git a/src/corelib/io/qprocess_p.h b/src/corelib/io/qprocess_p.h index eb2d1ed048..2587530c09 100644 --- a/src/corelib/io/qprocess_p.h +++ b/src/corelib/io/qprocess_p.h @@ -146,16 +146,22 @@ public: inline QString nameToString(const Key &name) const { return name; } inline Value prepareValue(const QString &value) const { return value; } inline QString valueToString(const Value &value) const { return value; } - struct MutexLocker { - MutexLocker(const QProcessEnvironmentPrivate *) {} +#else + struct NameMapMutexLocker : public QMutexLocker + { + NameMapMutexLocker(const QProcessEnvironmentPrivate *d) : QMutexLocker(&d->nameMapMutex) {} }; - struct OrderedMutexLocker { - OrderedMutexLocker(const QProcessEnvironmentPrivate *, - const QProcessEnvironmentPrivate *) {} + struct OrderedNameMapMutexLocker : public QOrderedMutexLocker + { + OrderedNameMapMutexLocker(const QProcessEnvironmentPrivate *d1, + const QProcessEnvironmentPrivate *d2) + : QOrderedMutexLocker(&d1->nameMapMutex, &d2->nameMapMutex) + {} }; -#else + inline Key prepareName(const QString &name) const { + const NameMapMutexLocker locker(this); Key &ent = nameMap[name]; if (ent.isEmpty()) ent = name.toLocal8Bit(); @@ -164,40 +170,27 @@ public: inline QString nameToString(const Key &name) const { const QString sname = QString::fromLocal8Bit(name); - nameMap[sname] = name; + { + const NameMapMutexLocker locker(this); + nameMap[sname] = name; + } return sname; } inline Value prepareValue(const QString &value) const { return Value(value); } inline QString valueToString(const Value &value) const { return value.string(); } - struct MutexLocker : public QMutexLocker - { - MutexLocker(const QProcessEnvironmentPrivate *d) : QMutexLocker(&d->mutex) {} - }; - struct OrderedMutexLocker : public QOrderedMutexLocker - { - OrderedMutexLocker(const QProcessEnvironmentPrivate *d1, - const QProcessEnvironmentPrivate *d2) : - QOrderedMutexLocker(&d1->mutex, &d2->mutex) - {} - }; - QProcessEnvironmentPrivate() : QSharedData() {} QProcessEnvironmentPrivate(const QProcessEnvironmentPrivate &other) : - QSharedData() + QSharedData(), vars(other.vars) { - // This being locked ensures that the functions that only assign - // d pointers don't need explicit locking. // We don't need to lock our own mutex, as this object is new and // consequently not shared. For the same reason, non-const methods // do not need a lock, as they detach objects (however, we need to // ensure that they really detach before using prepareName()). - MutexLocker locker(&other); - vars = other.vars; + NameMapMutexLocker locker(&other); nameMap = other.nameMap; - // We need to detach our members, so that our mutex can protect them. - // As we are being detached, they likely would be detached a moment later anyway. - vars.detach(); + // We need to detach our nameMap, so that our mutex can protect it. + // As we are being detached, it likely would be detached a moment later anyway. nameMap.detach(); } #endif @@ -208,8 +201,7 @@ public: #ifdef Q_OS_UNIX typedef QHash<QString, Key> NameHash; mutable NameHash nameMap; - - mutable QMutex mutex; + mutable QMutex nameMapMutex; #endif static QProcessEnvironment fromList(const QStringList &list); @@ -220,7 +212,7 @@ public: template<> Q_INLINE_TEMPLATE void QSharedDataPointer<QProcessEnvironmentPrivate>::detach() { - if (d && d->ref.load() == 1) + if (d && d->ref.loadRelaxed() == 1) return; QProcessEnvironmentPrivate *x = (d ? new QProcessEnvironmentPrivate(*d) : new QProcessEnvironmentPrivate); @@ -246,7 +238,7 @@ public: // if you add "= 4" here, increase the number of bits below }; - Channel() : process(0), notifier(0), type(Normal), closed(false), append(false) + Channel() : process(nullptr), notifier(nullptr), type(Normal), closed(false), append(false) { pipe[0] = INVALID_Q_PIPE; pipe[1] = INVALID_Q_PIPE; diff --git a/src/corelib/io/qprocess_unix.cpp b/src/corelib/io/qprocess_unix.cpp index 7a2daa2a57..951fc4ccaa 100644 --- a/src/corelib/io/qprocess_unix.cpp +++ b/src/corelib/io/qprocess_unix.cpp @@ -202,8 +202,7 @@ static int qt_create_pipe(int *pipe) qt_safe_close(pipe[1]); int pipe_ret = qt_safe_pipe(pipe); if (pipe_ret != 0) { - qWarning("QProcessPrivate::createPipe: Cannot create pipe %p: %s", - pipe, qPrintable(qt_error_string(errno))); + qErrnoWarning("QProcessPrivate::createPipe: Cannot create pipe %p", pipe); } return pipe_ret; } @@ -439,7 +438,6 @@ void QProcessPrivate::startProcess() int envc = 0; char **envp = 0; if (environment.d.constData()) { - QProcessEnvironmentPrivate::MutexLocker locker(environment.d); envp = _q_dupEnvironment(environment.d.constData()->vars, &envc); } @@ -473,7 +471,7 @@ void QProcessPrivate::startProcess() if (forkfd == -1) { // Cleanup, report error and return #if defined (QPROCESS_DEBUG) - qDebug("fork failed: %s", qPrintable(qt_error_string(lastForkErrno))); + qDebug("fork failed: %ls", qUtf16Printable(qt_error_string(lastForkErrno))); #endif q->setProcessState(QProcess::NotRunning); setErrorAndEmit(QProcess::FailedToStart, @@ -518,7 +516,7 @@ void QProcessPrivate::startProcess() if (stderrChannel.pipe[0] != -1) ::fcntl(stderrChannel.pipe[0], F_SETFL, ::fcntl(stderrChannel.pipe[0], F_GETFL) | O_NONBLOCK); - if (threadData->eventDispatcher) { + if (threadData->eventDispatcher.loadAcquire()) { deathNotifier = new QSocketNotifier(forkfd, QSocketNotifier::Read, q); QObject::connect(deathNotifier, SIGNAL(activated(int)), q, SLOT(_q_processDied())); @@ -652,7 +650,7 @@ bool QProcessPrivate::writeToStdin() qDebug("QProcessPrivate::writeToStdin(), write(%p \"%s\", %lld) == %lld", data, qt_prettyDebug(data, bytesToWrite, 16).constData(), bytesToWrite, written); if (written == -1) - qDebug("QProcessPrivate::writeToStdin(), failed to write (%s)", qPrintable(qt_error_string(errno))); + qDebug("QProcessPrivate::writeToStdin(), failed to write (%ls)", qUtf16Printable(qt_error_string(errno))); #endif if (written == -1) { // If the O_NONBLOCK flag is set and If some data can be written without blocking @@ -971,7 +969,6 @@ bool QProcessPrivate::startDetached(qint64 *pid) int envc = 0; char **envp = nullptr; if (environment.d.constData()) { - QProcessEnvironmentPrivate::MutexLocker locker(environment.d); envp = _q_dupEnvironment(environment.d.constData()->vars, &envc); } diff --git a/src/corelib/io/qresource.cpp b/src/corelib/io/qresource.cpp index b3533397d4..11d117c990 100644 --- a/src/corelib/io/qresource.cpp +++ b/src/corelib/io/qresource.cpp @@ -1,7 +1,7 @@ /**************************************************************************** ** ** Copyright (C) 2018 The Qt Company Ltd. -** Copyright (C) 2018 Intel Corporation. +** Copyright (C) 2019 Intel Corporation. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. @@ -147,7 +147,7 @@ private: public: mutable QAtomicInt ref; - inline QResourceRoot(): tree(0), names(0), payloads(0), version(0) {} + inline QResourceRoot(): tree(nullptr), names(nullptr), payloads(nullptr), version(0) {} inline QResourceRoot(int version, const uchar *t, const uchar *n, const uchar *d) { setSource(version, t, n, d); } virtual ~QResourceRoot() { } int findNode(const QString &path, const QLocale &locale=QLocale()) const; @@ -165,7 +165,7 @@ public: quint64 lastModified(int node) const; QStringList children(int node) const; virtual QString mappingRoot() const { return QString(); } - bool mappingRootSubdir(const QString &path, QString *match=0) const; + bool mappingRootSubdir(const QString &path, QString *match = nullptr) const; inline bool operator==(const QResourceRoot &other) const { return tree == other.tree && names == other.names && payloads == other.payloads && version == other.version; } inline bool operator!=(const QResourceRoot &other) const @@ -197,13 +197,13 @@ Q_DECLARE_TYPEINFO(QResourceRoot, Q_MOVABLE_TYPE); typedef QList<QResourceRoot*> ResourceList; struct QResourceGlobalData { - QMutex resourceMutex{QMutex::Recursive}; + QRecursiveMutex resourceMutex; ResourceList resourceList; QStringList resourceSearchPaths; }; Q_GLOBAL_STATIC(QResourceGlobalData, resourceGlobalData) -static inline QMutex *resourceMutex() +static inline QRecursiveMutex *resourceMutex() { return &resourceGlobalData->resourceMutex; } static inline ResourceList *resourceList() @@ -279,14 +279,14 @@ static inline QStringList *resourceSearchPaths() This enum is used by compressionAlgorithm() to indicate which algorithm the RCC tool used to compress the payload. - \value NoCompression Contents are not compressed (isCompressed() is false). + \value NoCompression Contents are not compressed \value ZlibCompression Contents are compressed using \l{zlib}{https://zlib.net} and can be decompressed using the qUncompress() function. \value ZstdCompression Contents are compressed using \l{zstd}{https://zstd.net}. To decompress, use the \c{ZSTD_decompress} function from the zstd library. - \sa compressionAlgorithm(), isCompressed() + \sa compressionAlgorithm() */ class QResourcePrivate { @@ -320,7 +320,7 @@ QResourcePrivate::clear() { absoluteFilePath.clear(); compressionAlgo = QResource::NoCompression; - data = 0; + data = nullptr; size = 0; children.clear(); lastModified = 0; @@ -551,13 +551,20 @@ bool QResource::isValid() const \sa isDir() */ - +#if QT_DEPRECATED_SINCE(5, 13) /*! + \obsolete + Returns \c true if the resource represents a file and the data backing it is in a compressed format, false otherwise. If the data is compressed, check compressionAlgorithm() to verify what algorithm to use to decompress the data. + \note This function is deprecated and can be replaced with + \code + compressionAlgorithm() != NoCompression + \endcode + \sa data(), compressionAlgorithm(), isFile() */ @@ -565,6 +572,7 @@ bool QResource::isCompressed() const { return compressionAlgorithm() != NoCompression; } +#endif /*! \since 5.13 @@ -582,7 +590,7 @@ bool QResource::isCompressed() const See \l{http://facebook.github.io/zstd/zstd_manual.html}{Zstandard manual}. - \sa isCompressed(), data(), isFile() + \sa data(), isFile() */ QResource::Compression QResource::compressionAlgorithm() const { @@ -606,11 +614,11 @@ qint64 QResource::size() const /*! Returns direct access to a read only segment of data that this resource - represents. If the resource is compressed the data returns is - compressed and qUncompress() must be used to access the data. If the - resource is a directory \nullptr is returned. + represents. If the resource is compressed the data returned is compressed + and the appropriate library functions must be used to access the data. If + the resource is a directory \nullptr is returned. - \sa size(), isCompressed(), isFile() + \sa size(), compressionAlgorithm(), isFile() */ const uchar *QResource::data() const @@ -864,7 +872,7 @@ const uchar *QResourceRoot::data(int node, qint64 *size) const { if(node == -1) { *size = 0; - return 0; + return nullptr; } int offset = findOffset(node) + 4; //jump past name @@ -881,7 +889,7 @@ const uchar *QResourceRoot::data(int node, qint64 *size) const return ret; } *size = 0; - return 0; + return nullptr; } quint64 QResourceRoot::lastModified(int node) const @@ -993,7 +1001,7 @@ class QDynamicBufferResourceRoot: public QResourceRoot const uchar *buffer; public: - inline QDynamicBufferResourceRoot(const QString &_root) : root(_root), buffer(0) { } + inline QDynamicBufferResourceRoot(const QString &_root) : root(_root), buffer(nullptr) { } inline ~QDynamicBufferResourceRoot() { } inline const uchar *mappingBuffer() const { return buffer; } QString mappingRoot() const override { return root; } @@ -1065,12 +1073,14 @@ class QDynamicFileResourceRoot: public QDynamicBufferResourceRoot qsizetype unmapLength; public: - inline QDynamicFileResourceRoot(const QString &_root) : QDynamicBufferResourceRoot(_root), unmapPointer(0), unmapLength(0) { } + QDynamicFileResourceRoot(const QString &_root) + : QDynamicBufferResourceRoot(_root), unmapPointer(nullptr), unmapLength(0) + { } ~QDynamicFileResourceRoot() { #if defined(QT_USE_MMAP) if (unmapPointer) { munmap((char*)unmapPointer, unmapLength); - unmapPointer = 0; + unmapPointer = nullptr; unmapLength = 0; } else #endif @@ -1366,9 +1376,15 @@ bool QResourceFileEngine::open(QIODevice::OpenMode flags) qWarning("QResourceFileEngine::open: Missing file name"); return false; } - if(flags & QIODevice::WriteOnly) + if (flags & QIODevice::WriteOnly) return false; - d->uncompress(); + if (d->resource.compressionAlgorithm() != QResource::NoCompression) { + d->uncompress(); + if (d->uncompressed.isNull()) { + d->errorString = QSystemError::stdString(EIO); + return false; + } + } if (!d->resource.isValid()) { d->errorString = QSystemError::stdString(ENOENT); return false; @@ -1395,7 +1411,7 @@ qint64 QResourceFileEngine::read(char *data, qint64 len) len = size()-d->offset; if(len <= 0) return 0; - if(d->resource.isCompressed()) + if (!d->uncompressed.isNull()) memcpy(data, d->uncompressed.constData()+d->offset, len); else memcpy(data, d->resource.data()+d->offset, len); @@ -1431,9 +1447,9 @@ bool QResourceFileEngine::link(const QString &) qint64 QResourceFileEngine::size() const { Q_D(const QResourceFileEngine); - if(!d->resource.isValid()) + if (!d->resource.isValid()) return 0; - if (d->resource.isCompressed()) { + if (d->resource.compressionAlgorithm() != QResource::NoCompression) { d->uncompress(); return d->uncompressed.size(); } @@ -1596,7 +1612,7 @@ uchar *QResourceFileEnginePrivate::map(qint64 offset, qint64 size, QFile::Memory Q_UNUSED(flags); qint64 max = resource.size(); - if (resource.isCompressed()) { + if (resource.compressionAlgorithm() != QResource::NoCompression) { uncompress(); max = uncompressed.size(); } @@ -1609,7 +1625,7 @@ uchar *QResourceFileEnginePrivate::map(qint64 offset, qint64 size, QFile::Memory } const uchar *address = resource.data(); - if (resource.isCompressed()) + if (resource.compressionAlgorithm() != QResource::NoCompression) address = reinterpret_cast<const uchar *>(uncompressed.constData()); return const_cast<uchar *>(address) + offset; diff --git a/src/corelib/io/qresource.h b/src/corelib/io/qresource.h index 5e798de436..5ee8d5d266 100644 --- a/src/corelib/io/qresource.h +++ b/src/corelib/io/qresource.h @@ -72,7 +72,6 @@ public: bool isValid() const; - bool isCompressed() const; Compression compressionAlgorithm() const; qint64 size() const; const uchar *data() const; @@ -84,6 +83,10 @@ public: QT_DEPRECATED_X("Use QDir::searchPaths() instead") static QStringList searchPaths(); #endif +#if QT_DEPRECATED_SINCE(5, 15) + QT_DEPRECATED_VERSION_X_5_15("Use QResource::compressionAlgorithm() instead") + bool isCompressed() const; +#endif static bool registerResource(const QString &rccFilename, const QString &resourceRoot=QString()); static bool unregisterResource(const QString &rccFilename, const QString &resourceRoot=QString()); diff --git a/src/corelib/io/qresource_p.h b/src/corelib/io/qresource_p.h index 7451de8809..fedf95bb33 100644 --- a/src/corelib/io/qresource_p.h +++ b/src/corelib/io/qresource_p.h @@ -108,7 +108,7 @@ public: Iterator *beginEntryList(QDir::Filters filters, const QStringList &filterNames) override; Iterator *endEntryList() override; - bool extension(Extension extension, const ExtensionOption *option = 0, ExtensionReturn *output = 0) override; + bool extension(Extension extension, const ExtensionOption *option = nullptr, ExtensionReturn *output = nullptr) override; bool supportsExtension(Extension extension) const override; }; diff --git a/src/corelib/io/qsavefile.cpp b/src/corelib/io/qsavefile.cpp index fac8892da2..f41e6302a2 100644 --- a/src/corelib/io/qsavefile.cpp +++ b/src/corelib/io/qsavefile.cpp @@ -150,8 +150,7 @@ QSaveFile::~QSaveFile() QFileDevice::close(); if (d->fileEngine) { d->fileEngine->remove(); - delete d->fileEngine; - d->fileEngine = 0; + d->fileEngine.reset(); } } @@ -193,7 +192,7 @@ bool QSaveFile::open(OpenMode mode) { Q_D(QSaveFile); if (isOpen()) { - qWarning("QSaveFile::open: File (%s) already open", qPrintable(fileName())); + qWarning("QSaveFile::open: File (%ls) already open", qUtf16Printable(fileName())); return false; } unsetError(); @@ -235,7 +234,7 @@ bool QSaveFile::open(OpenMode mode) } auto openDirectly = [&]() { - d->fileEngine = QAbstractFileEngine::create(d->finalFileName); + d->fileEngine.reset(QAbstractFileEngine::create(d->finalFileName)); if (d->fileEngine->open(mode | QIODevice::Unbuffered)) { d->useTemporaryFile = false; QFileDevice::open(mode); @@ -252,8 +251,7 @@ bool QSaveFile::open(OpenMode mode) if (openDirectly()) return true; d->setError(d->fileEngine->error(), d->fileEngine->errorString()); - delete d->fileEngine; - d->fileEngine = 0; + d->fileEngine.reset(); } else { QString msg = QSaveFile::tr("QSaveFile cannot open '%1' without direct write fallback " @@ -265,18 +263,17 @@ bool QSaveFile::open(OpenMode mode) } #endif - d->fileEngine = new QTemporaryFileEngine(&d->finalFileName, QTemporaryFileEngine::Win32NonShared); + d->fileEngine.reset(new QTemporaryFileEngine(&d->finalFileName, QTemporaryFileEngine::Win32NonShared)); // if the target file exists, we'll copy its permissions below, // but until then, let's ensure the temporary file is not accessible // to a third party int perm = (existingFile.exists() ? 0600 : 0666); - static_cast<QTemporaryFileEngine *>(d->fileEngine)->initialize(d->finalFileName, perm); + static_cast<QTemporaryFileEngine *>(d->fileEngine.get())->initialize(d->finalFileName, perm); // Same as in QFile: QIODevice provides the buffering, so there's no need to request it from the file engine. if (!d->fileEngine->open(mode | QIODevice::Unbuffered)) { QFileDevice::FileError err = d->fileEngine->error(); #ifdef Q_OS_UNIX if (d->directWriteFallback && err == QFileDevice::OpenError && errno == EACCES) { - delete d->fileEngine; if (openDirectly()) return true; err = d->fileEngine->error(); @@ -285,8 +282,7 @@ bool QSaveFile::open(OpenMode mode) if (err == QFileDevice::UnspecifiedError) err = QFileDevice::OpenError; d->setError(err, d->fileEngine->errorString()); - delete d->fileEngine; - d->fileEngine = 0; + d->fileEngine.reset(); return false; } @@ -327,35 +323,31 @@ bool QSaveFile::commit() return false; if (!isOpen()) { - qWarning("QSaveFile::commit: File (%s) is not open", qPrintable(fileName())); + qWarning("QSaveFile::commit: File (%ls) is not open", qUtf16Printable(fileName())); return false; } QFileDevice::close(); // calls flush() + const auto fe = std::move(d->fileEngine); + // Sync to disk if possible. Ignore errors (e.g. not supported). - d->fileEngine->syncToDisk(); + fe->syncToDisk(); if (d->useTemporaryFile) { if (d->writeError != QFileDevice::NoError) { - d->fileEngine->remove(); + fe->remove(); d->writeError = QFileDevice::NoError; - delete d->fileEngine; - d->fileEngine = 0; return false; } // atomically replace old file with new file // Can't use QFile::rename for that, must use the file engine directly - Q_ASSERT(d->fileEngine); - if (!d->fileEngine->renameOverwrite(d->finalFileName)) { - d->setError(d->fileEngine->error(), d->fileEngine->errorString()); - d->fileEngine->remove(); - delete d->fileEngine; - d->fileEngine = 0; + Q_ASSERT(fe); + if (!fe->renameOverwrite(d->finalFileName)) { + d->setError(fe->error(), fe->errorString()); + fe->remove(); return false; } } - delete d->fileEngine; - d->fileEngine = 0; return true; } diff --git a/src/corelib/io/qsettings.cpp b/src/corelib/io/qsettings.cpp index 9234a23f3a..accde01f16 100644 --- a/src/corelib/io/qsettings.cpp +++ b/src/corelib/io/qsettings.cpp @@ -2048,8 +2048,8 @@ void QConfFileSettingsPrivate::ensureSectionParsed(QConfFile *confFile, QPixmap, which are part of Qt GUI. In other words, there is no \c toColor(), \c toImage(), or \c toPixmap() functions in QVariant. - Instead, you can use the QVariant::value() or the qVariantValue() - template function. For example: + Instead, you can use the QVariant::value() template function. + For example: \snippet code/src_corelib_io_qsettings.cpp 0 diff --git a/src/corelib/io/qsettings_win.cpp b/src/corelib/io/qsettings_win.cpp index dd3468e1f8..679212ea21 100644 --- a/src/corelib/io/qsettings_win.cpp +++ b/src/corelib/io/qsettings_win.cpp @@ -166,8 +166,8 @@ static HKEY createOrOpenKey(HKEY parentHandle, REGSAM perms, const QString &rSub if (res == ERROR_SUCCESS) return resultHandle; - //qWarning("QSettings: Failed to create subkey \"%s\": %s", - // qPrintable(rSubKey), qPrintable(qt_error_string(int(res)))); + //qErrnoWarning(int(res), "QSettings: Failed to create subkey \"%ls\"", + // qUtf16Printable(rSubKey)); return 0; } @@ -207,7 +207,7 @@ static QStringList childKeysOrGroups(HKEY parentHandle, QSettingsPrivate::ChildS &numKeys, &maxKeySize, 0, 0, 0); if (res != ERROR_SUCCESS) { - qWarning("QSettings: RegQueryInfoKey() failed: %s", qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: RegQueryInfoKey() failed"); return result; } @@ -241,7 +241,7 @@ static QStringList childKeysOrGroups(HKEY parentHandle, QSettingsPrivate::ChildS item = QString::fromWCharArray((const wchar_t *)buff.constData(), l); if (res != ERROR_SUCCESS) { - qWarning("QSettings: RegEnumValue failed: %s", qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: RegEnumValue failed"); continue; } if (item.isEmpty()) @@ -295,8 +295,8 @@ static void deleteChildGroups(HKEY parentHandle, REGSAM access = 0) // delete group itself LONG res = RegDeleteKey(parentHandle, reinterpret_cast<const wchar_t *>(group.utf16())); if (res != ERROR_SUCCESS) { - qWarning("QSettings: RegDeleteKey failed on subkey \"%s\": %s", - qPrintable(group), qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: RegDeleteKey failed on subkey \"%ls\"", + qUtf16Printable(group)); return; } } @@ -596,8 +596,8 @@ QWinSettingsPrivate::~QWinSettingsPrivate() QString emptyKey; DWORD res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(emptyKey.utf16())); if (res != ERROR_SUCCESS) { - qWarning("QSettings: Failed to delete key \"%s\": %s", - qPrintable(regList.at(0).key()), qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: Failed to delete key \"%ls\"", + qUtf16Printable(regList.constFirst().key())); } } @@ -633,16 +633,16 @@ void QWinSettingsPrivate::remove(const QString &uKey) for (const QString &group : childKeys) { LONG res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(group.utf16())); if (res != ERROR_SUCCESS) { - qWarning("QSettings: RegDeleteValue failed on subkey \"%s\": %s", - qPrintable(group), qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: RegDeleteValue failed on subkey \"%ls\"", + qUtf16Printable(group)); } } } else { res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(rKey.utf16())); if (res != ERROR_SUCCESS) { - qWarning("QSettings: RegDeleteKey failed on key \"%s\": %s", - qPrintable(rKey), qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: RegDeleteKey failed on key \"%ls\"", + qUtf16Printable(rKey)); } } RegCloseKey(handle); @@ -739,8 +739,8 @@ void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value) if (res == ERROR_SUCCESS) { deleteWriteHandleOnExit = false; } else { - qWarning("QSettings: failed to set subkey \"%s\": %s", - qPrintable(rKey), qPrintable(qt_error_string(int(res)))); + qErrnoWarning(int(res), "QSettings: failed to set subkey \"%ls\"", + qUtf16Printable(rKey)); setStatus(QSettings::AccessError); } diff --git a/src/corelib/io/qstandardpaths_android.cpp b/src/corelib/io/qstandardpaths_android.cpp index 83108e4387..1f4e0de1e7 100644 --- a/src/corelib/io/qstandardpaths_android.cpp +++ b/src/corelib/io/qstandardpaths_android.cpp @@ -136,7 +136,7 @@ static QString getExternalStoragePublicDirectory(const char *directoryField) */ static QString getExternalFilesDir(const char *directoryField = 0) { - QString &path = (*androidDirCache)[QString(QLatin1String("APPNAME_%1")).arg(QLatin1String(directoryField))]; + QString &path = (*androidDirCache)[QLatin1String("APPNAME_%1").arg(QLatin1String(directoryField))]; if (!path.isEmpty()) return path; diff --git a/src/corelib/io/qstandardpaths_unix.cpp b/src/corelib/io/qstandardpaths_unix.cpp index eaa545b4fd..6425890e3f 100644 --- a/src/corelib/io/qstandardpaths_unix.cpp +++ b/src/corelib/io/qstandardpaths_unix.cpp @@ -71,6 +71,28 @@ static void appendOrganizationAndApp(QString &path) #endif } +#if QT_CONFIG(regularexpression) +static QLatin1String xdg_key_name(QStandardPaths::StandardLocation type) +{ + switch (type) { + case QStandardPaths::DesktopLocation: + return QLatin1String("DESKTOP"); + case QStandardPaths::DocumentsLocation: + return QLatin1String("DOCUMENTS"); + case QStandardPaths::PicturesLocation: + return QLatin1String("PICTURES"); + case QStandardPaths::MusicLocation: + return QLatin1String("MUSIC"); + case QStandardPaths::MoviesLocation: + return QLatin1String("VIDEOS"); + case QStandardPaths::DownloadLocation: + return QLatin1String("DOWNLOAD"); + default: + return QLatin1String(); + } +} +#endif + QString QStandardPaths::writableLocation(StandardLocation type) { switch (type) { @@ -130,29 +152,31 @@ QString QStandardPaths::writableLocation(StandardLocation type) fileInfo.setFile(xdgRuntimeDir); if (!fileInfo.isDir()) { if (!QDir().mkdir(xdgRuntimeDir)) { - qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno))); + qErrnoWarning("QStandardPaths: error creating runtime directory %ls", + qUtf16Printable(xdgRuntimeDir)); return QString(); } } #ifndef Q_OS_WASM - qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%s'", qPrintable(xdgRuntimeDir)); + qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%ls'", qUtf16Printable(xdgRuntimeDir)); #endif } else { fileInfo.setFile(xdgRuntimeDir); if (!fileInfo.exists()) { - qWarning("QStandardPaths: XDG_RUNTIME_DIR points to non-existing path '%s', " - "please create it with 0700 permissions.", qPrintable(xdgRuntimeDir)); + qWarning("QStandardPaths: XDG_RUNTIME_DIR points to non-existing path '%ls', " + "please create it with 0700 permissions.", qUtf16Printable(xdgRuntimeDir)); return QString(); } if (!fileInfo.isDir()) { - qWarning("QStandardPaths: XDG_RUNTIME_DIR points to '%s' which is not a directory", - qPrintable(xdgRuntimeDir)); + qWarning("QStandardPaths: XDG_RUNTIME_DIR points to '%ls' which is not a directory", + qUtf16Printable(xdgRuntimeDir)); return QString(); } } // "The directory MUST be owned by the user" if (fileInfo.ownerId() != myUid) { - qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir), + qWarning("QStandardPaths: wrong ownership on runtime directory %ls, %d instead of %d", + qUtf16Printable(xdgRuntimeDir), fileInfo.ownerId(), myUid); return QString(); } @@ -163,8 +187,8 @@ QString QStandardPaths::writableLocation(StandardLocation type) if (fileInfo.permissions() != wantedPerms) { QFile file(xdgRuntimeDir); if (!file.setPermissions(wantedPerms)) { - qWarning("QStandardPaths: could not set correct permissions on runtime directory %s: %s", - qPrintable(xdgRuntimeDir), qPrintable(file.errorString())); + qWarning("QStandardPaths: could not set correct permissions on runtime directory %ls: %ls", + qUtf16Printable(xdgRuntimeDir), qUtf16Printable(file.errorString())); return QString(); } } @@ -180,61 +204,32 @@ QString QStandardPaths::writableLocation(StandardLocation type) if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs")); - if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) { - QHash<QString, QString> lines; + const QLatin1String key = xdg_key_name(type); + if (!key.isEmpty() && !isTestModeEnabled() && file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop" QRegularExpression exp(QLatin1String("^XDG_(.*)_DIR=(.*)$")); + QString result; while (!stream.atEnd()) { const QString &line = stream.readLine(); QRegularExpressionMatch match = exp.match(line); - if (match.hasMatch()) { - const QStringList lst = match.capturedTexts(); - const QString key = lst.at(1); - QString value = lst.at(2); + if (match.hasMatch() && match.capturedView(1) == key) { + QStringView value = match.capturedView(2); if (value.length() > 2 && value.startsWith(QLatin1Char('\"')) && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); - // Store the key and value: "DESKTOP", "$HOME/Desktop" - lines[key] = value; - } - } - - QString key; - switch (type) { - case DesktopLocation: - key = QLatin1String("DESKTOP"); - break; - case DocumentsLocation: - key = QLatin1String("DOCUMENTS"); - break; - case PicturesLocation: - key = QLatin1String("PICTURES"); - break; - case MusicLocation: - key = QLatin1String("MUSIC"); - break; - case MoviesLocation: - key = QLatin1String("VIDEOS"); - break; - case DownloadLocation: - key = QLatin1String("DOWNLOAD"); - break; - default: - break; - } - if (!key.isEmpty()) { - QString value = lines.value(key); - if (!value.isEmpty()) { // value can start with $HOME if (value.startsWith(QLatin1String("$HOME"))) - value = QDir::homePath() + value.midRef(5); - if (value.length() > 1 && value.endsWith(QLatin1Char('/'))) - value.chop(1); - return value; + result = QDir::homePath() + value.mid(5); + else + result = value.toString(); + if (result.length() > 1 && result.endsWith(QLatin1Char('/'))) + result.chop(1); } } + if (!result.isNull()) + return result; } #endif // QT_CONFIG(regularexpression) @@ -284,16 +279,12 @@ static QStringList xdgDataDirs() dirs.append(QString::fromLatin1("/usr/local/share")); dirs.append(QString::fromLatin1("/usr/share")); } else { - dirs = xdgDataDirsEnv.split(QLatin1Char(':'), QString::SkipEmptyParts); + const auto parts = xdgDataDirsEnv.splitRef(QLatin1Char(':'), QString::SkipEmptyParts); // Normalize paths, skip relative paths - QMutableListIterator<QString> it(dirs); - while (it.hasNext()) { - const QString dir = it.next(); - if (!dir.startsWith(QLatin1Char('/'))) - it.remove(); - else - it.setValue(QDir::cleanPath(dir)); + for (const QStringRef &dir : parts) { + if (dir.startsWith(QLatin1Char('/'))) + dirs.push_back(QDir::cleanPath(dir.toString())); } // Remove duplicates from the list, there's no use for duplicated diff --git a/src/corelib/io/qstorageinfo.h b/src/corelib/io/qstorageinfo.h index 4ab7a353ef..237e68d2a1 100644 --- a/src/corelib/io/qstorageinfo.h +++ b/src/corelib/io/qstorageinfo.h @@ -62,11 +62,9 @@ public: ~QStorageInfo(); QStorageInfo &operator=(const QStorageInfo &other); -#ifdef Q_COMPILER_RVALUE_REFS - QStorageInfo &operator=(QStorageInfo &&other) Q_DECL_NOTHROW { swap(other); return *this; } -#endif + QStorageInfo &operator=(QStorageInfo &&other) noexcept { swap(other); return *this; } - inline void swap(QStorageInfo &other) Q_DECL_NOTHROW + inline void swap(QStorageInfo &other) noexcept { qSwap(d, other.d); } void setPath(const QString &path); diff --git a/src/corelib/io/qstorageinfo_unix.cpp b/src/corelib/io/qstorageinfo_unix.cpp index 07c80dda7c..1e72241e68 100644 --- a/src/corelib/io/qstorageinfo_unix.cpp +++ b/src/corelib/io/qstorageinfo_unix.cpp @@ -822,7 +822,7 @@ void QStorageInfoPrivate::retrieveVolumeInfo() valid = true; ready = true; -#if defined(Q_OS_INTEGRITY) || (defined(Q_OS_BSD4) && !defined(Q_OS_NETBSD)) +#if defined(Q_OS_INTEGRITY) || (defined(Q_OS_BSD4) && !defined(Q_OS_NETBSD)) || defined(Q_OS_RTEMS) bytesTotal = statfs_buf.f_blocks * statfs_buf.f_bsize; bytesFree = statfs_buf.f_bfree * statfs_buf.f_bsize; bytesAvailable = statfs_buf.f_bavail * statfs_buf.f_bsize; @@ -832,7 +832,7 @@ void QStorageInfoPrivate::retrieveVolumeInfo() bytesAvailable = statfs_buf.f_bavail * statfs_buf.f_frsize; #endif blockSize = statfs_buf.f_bsize; -#if defined(Q_OS_ANDROID) || defined(Q_OS_BSD4) || defined(Q_OS_INTEGRITY) +#if defined(Q_OS_ANDROID) || defined(Q_OS_BSD4) || defined(Q_OS_INTEGRITY) || defined(Q_OS_RTEMS) #if defined(_STATFS_F_FLAGS) readOnly = (statfs_buf.f_flags & ST_RDONLY) != 0; #endif diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index ced08a9a87..acd31f4d84 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -327,7 +327,7 @@ bool QTemporaryFileEngine::isReallyOpen() const { Q_D(const QFSFileEngine); - if (!((0 == d->fh) && (-1 == d->fd) + if (!((nullptr == d->fh) && (-1 == d->fd) #if defined Q_OS_WIN && (INVALID_HANDLE_VALUE == d->fileHandle) #endif @@ -544,10 +544,10 @@ QTemporaryFilePrivate::~QTemporaryFilePrivate() QAbstractFileEngine *QTemporaryFilePrivate::engine() const { if (!fileEngine) { - fileEngine = new QTemporaryFileEngine(&templateName); + fileEngine.reset(new QTemporaryFileEngine(&templateName)); resetFileEngine(); } - return fileEngine; + return fileEngine.get(); } void QTemporaryFilePrivate::resetFileEngine() const @@ -555,7 +555,7 @@ void QTemporaryFilePrivate::resetFileEngine() const if (!fileEngine) return; - QTemporaryFileEngine *tef = static_cast<QTemporaryFileEngine *>(fileEngine); + QTemporaryFileEngine *tef = static_cast<QTemporaryFileEngine *>(fileEngine.get()); if (fileName.isEmpty()) tef->initialize(templateName, 0600); else @@ -568,7 +568,7 @@ void QTemporaryFilePrivate::materializeUnnamedFile() if (!fileName.isEmpty() || !fileEngine) return; - auto *tef = static_cast<QTemporaryFileEngine *>(fileEngine); + auto *tef = static_cast<QTemporaryFileEngine *>(fileEngine.get()); fileName = tef->fileName(QAbstractFileEngine::DefaultName); #endif } @@ -792,7 +792,7 @@ void QTemporaryFile::setAutoRemove(bool b) QString QTemporaryFile::fileName() const { Q_D(const QTemporaryFile); - auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine); + auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine.get()); if (tef && tef->isReallyOpen()) const_cast<QTemporaryFilePrivate *>(d)->materializeUnnamedFile(); @@ -841,7 +841,7 @@ void QTemporaryFile::setFileTemplate(const QString &name) bool QTemporaryFile::rename(const QString &newName) { Q_D(QTemporaryFile); - auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine); + auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine.get()); if (!tef || !tef->isReallyOpen() || !tef->filePathWasTemplate) return QFile::rename(newName); @@ -902,7 +902,7 @@ QTemporaryFile *QTemporaryFile::createNativeFile(QFile &file) { if (QAbstractFileEngine *engine = file.d_func()->engine()) { if(engine->fileFlags(QAbstractFileEngine::FlagsMask) & QAbstractFileEngine::LocalDiskFlag) - return 0; //native already + return nullptr; // native already //cache bool wasOpen = file.isOpen(); qint64 old_off = 0; @@ -934,7 +934,7 @@ QTemporaryFile *QTemporaryFile::createNativeFile(QFile &file) //done return ret; } - return 0; + return nullptr; } /*! @@ -947,7 +947,7 @@ QTemporaryFile *QTemporaryFile::createNativeFile(QFile &file) bool QTemporaryFile::open(OpenMode flags) { Q_D(QTemporaryFile); - auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine); + auto tef = static_cast<QTemporaryFileEngine *>(d->fileEngine.get()); if (tef && tef->isReallyOpen()) { setOpenMode(flags); return true; @@ -961,7 +961,7 @@ bool QTemporaryFile::open(OpenMode flags) d->resetFileEngine(); if (QFile::open(flags)) { - tef = static_cast<QTemporaryFileEngine *>(d->fileEngine); + tef = static_cast<QTemporaryFileEngine *>(d->fileEngine.get()); if (tef->isUnnamedFile()) d->fileName.clear(); else diff --git a/src/corelib/io/qtemporaryfile_p.h b/src/corelib/io/qtemporaryfile_p.h index 0fec88d3cd..6bcff936b4 100644 --- a/src/corelib/io/qtemporaryfile_p.h +++ b/src/corelib/io/qtemporaryfile_p.h @@ -145,10 +145,10 @@ public: bool isUnnamedFile() const override final; const QString &templateName; - quint32 fileMode; + quint32 fileMode = 0; int flags = 0; - bool filePathIsTemplate; - bool filePathWasTemplate; + bool filePathIsTemplate = true; + bool filePathWasTemplate = true; bool unnamedFile = false; }; diff --git a/src/corelib/io/qtldurl.cpp b/src/corelib/io/qtldurl.cpp index a934d19fa2..912609ec91 100644 --- a/src/corelib/io/qtldurl.cpp +++ b/src/corelib/io/qtldurl.cpp @@ -59,9 +59,9 @@ enum TLDMatchType { static bool containsTLDEntry(QStringView entry, TLDMatchType match) { const QStringView matchSymbols[] = { - QStringViewLiteral(""), - QStringViewLiteral("*"), - QStringViewLiteral("!"), + u"", + u"*", + u"!", }; const auto symbol = matchSymbols[match]; int index = qt_hash(entry, qt_hash(symbol)) % tldCount; diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp index 6d82981fd6..878e007fb0 100644 --- a/src/corelib/io/qurl.cpp +++ b/src/corelib/io/qurl.cpp @@ -421,6 +421,7 @@ #include "private/qipaddress_p.h" #include "qurlquery.h" #include "private/qdir_p.h" +#include <private/qmemory_p.h> QT_BEGIN_NAMESPACE @@ -520,10 +521,10 @@ public: bool isEmpty() const { return sectionIsPresent == 0 && port == -1 && path.isEmpty(); } - Error *cloneError() const; + std::unique_ptr<Error> cloneError() const; void clearError(); void setError(ErrorCode errorCode, const QString &source, int supplement = -1); - ErrorCode validityError(QString *source = 0, int *position = 0) const; + ErrorCode validityError(QString *source = nullptr, int *position = nullptr) const; bool validateComponent(Section section, const QString &input, int begin, int end); bool validateComponent(Section section, const QString &input) { return validateComponent(section, input, 0, uint(input.length())); } @@ -576,7 +577,7 @@ public: QString query; QString fragment; - Error *error; + std::unique_ptr<Error> error; // not used for: // - Port (port == -1 means absence) @@ -591,7 +592,6 @@ public: inline QUrlPrivate::QUrlPrivate() : ref(1), port(-1), - error(0), sectionIsPresent(0), flags(0) { @@ -613,19 +613,16 @@ inline QUrlPrivate::QUrlPrivate(const QUrlPrivate ©) } inline QUrlPrivate::~QUrlPrivate() -{ - delete error; -} + = default; -inline QUrlPrivate::Error *QUrlPrivate::cloneError() const +std::unique_ptr<QUrlPrivate::Error> QUrlPrivate::cloneError() const { - return error ? new Error(*error) : 0; + return error ? qt_make_unique<Error>(*error) : nullptr; } inline void QUrlPrivate::clearError() { - delete error; - error = 0; + error.reset(); } inline void QUrlPrivate::setError(ErrorCode errorCode, const QString &source, int supplement) @@ -634,7 +631,7 @@ inline void QUrlPrivate::setError(ErrorCode errorCode, const QString &source, in // don't overwrite an error set in a previous section during parsing return; } - error = new Error; + error = qt_make_unique<Error>(); error->code = errorCode; error->source = source; error->position = supplement; @@ -826,7 +823,7 @@ recodeFromUser(const QString &input, const ushort *actions, int from, int to) QString output; const QChar *begin = input.constData() + from; const QChar *end = input.constData() + to; - if (qt_urlRecode(output, begin, end, 0, actions)) + if (qt_urlRecode(output, begin, end, nullptr, actions)) return output; return input.mid(from, to - from); @@ -954,7 +951,7 @@ inline void QUrlPrivate::appendFragment(QString &appendTo, QUrl::FormattingOptio { appendToUser(appendTo, fragment, options, options & QUrl::EncodeDelimiters ? fragmentInUrl : - appendingTo == FullUrl ? 0 : fragmentInIsolation); + appendingTo == FullUrl ? nullptr : fragmentInIsolation); } inline void QUrlPrivate::appendQuery(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const @@ -1013,7 +1010,7 @@ inline bool QUrlPrivate::setScheme(const QString &value, int len, bool doSetErro for (int i = needsLowercasing; i >= 0; --i) { ushort c = schemeData[i].unicode(); if (c >= 'A' && c <= 'Z') - schemeData[i] = c + 0x20; + schemeData[i] = QChar(c + 0x20); } } @@ -1179,7 +1176,7 @@ inline void QUrlPrivate::appendHost(QString &appendTo, QUrl::FormattingOptions o if (host.at(0).unicode() == '[') { // IPv6 addresses might contain a zone-id which needs to be recoded if (options != 0) - if (qt_urlRecode(appendTo, host.constBegin(), host.constEnd(), options, 0)) + if (qt_urlRecode(appendTo, host.constBegin(), host.constEnd(), options, nullptr)) return; appendTo += host; } else { @@ -1221,7 +1218,7 @@ static const QChar *parseIpFuture(QString &host, const QChar *begin, const QChar --end; QString decoded; - if (mode == QUrl::TolerantMode && qt_urlRecode(decoded, begin, end, QUrl::FullyDecoded, 0)) { + if (mode == QUrl::TolerantMode && qt_urlRecode(decoded, begin, end, QUrl::FullyDecoded, nullptr)) { begin = decoded.constBegin(); end = decoded.constEnd(); } @@ -1233,13 +1230,13 @@ static const QChar *parseIpFuture(QString &host, const QChar *begin, const QChar host += *begin; else if (begin->unicode() >= '0' && begin->unicode() <= '9') host += *begin; - else if (begin->unicode() < 0x80 && strchr(acceptable, begin->unicode()) != 0) + else if (begin->unicode() < 0x80 && strchr(acceptable, begin->unicode()) != nullptr) host += *begin; else return decoded.isEmpty() ? begin : &origBegin[2]; } host += QLatin1Char(']'); - return 0; + return nullptr; } return &origBegin[2]; } @@ -1286,7 +1283,7 @@ static const QChar *parseIp6(QString &host, const QChar *begin, const QChar *end host += zoneId; } host += QLatin1Char(']'); - return 0; + return nullptr; } inline bool QUrlPrivate::setHost(const QString &value, int from, int iend, QUrl::ParsingMode mode) @@ -1352,7 +1349,7 @@ inline bool QUrlPrivate::setHost(const QString &value, int from, int iend, QUrl: // check for percent-encoding first QString s; - if (mode == QUrl::TolerantMode && qt_urlRecode(s, begin, end, 0, 0)) { + if (mode == QUrl::TolerantMode && qt_urlRecode(s, begin, end, { }, nullptr)) { // something was decoded // anything encoded left? int pos = s.indexOf(QChar(0x25)); // '%' @@ -1837,7 +1834,7 @@ inline void QUrlPrivate::validate() const \sa setUrl(), fromEncoded(), TolerantMode */ -QUrl::QUrl(const QString &url, ParsingMode parsingMode) : d(0) +QUrl::QUrl(const QString &url, ParsingMode parsingMode) : d(nullptr) { setUrl(url, parsingMode); } @@ -1845,7 +1842,7 @@ QUrl::QUrl(const QString &url, ParsingMode parsingMode) : d(0) /*! Constructs an empty QUrl object. */ -QUrl::QUrl() : d(0) +QUrl::QUrl() : d(nullptr) { } @@ -1879,7 +1876,7 @@ QUrl::~QUrl() bool QUrl::isValid() const { if (isEmpty()) { - // also catches d == 0 + // also catches d == nullptr return false; } return d->validityError() == QUrlPrivate::NoError; @@ -1907,7 +1904,7 @@ void QUrl::clear() { if (d && !d->ref.deref()) delete d; - d = 0; + d = nullptr; } /*! @@ -3266,10 +3263,10 @@ QUrl QUrl::resolved(const QUrl &relative) const removeDotsFromPath(&t.d->path); #if defined(QURL_DEBUG) - qDebug("QUrl(\"%s\").resolved(\"%s\") = \"%s\"", - qPrintable(url()), - qPrintable(relative.url()), - qPrintable(t.url())); + qDebug("QUrl(\"%ls\").resolved(\"%ls\") = \"%ls\"", + qUtf16Printable(url()), + qUtf16Printable(relative.url()), + qUtf16Printable(t.url())); #endif return t; } @@ -3805,7 +3802,7 @@ void QUrl::detach() */ bool QUrl::isDetached() const { - return !d || d->ref.load() == 1; + return !d || d->ref.loadRelaxed() == 1; } @@ -3994,21 +3991,21 @@ static QString errorMessage(QUrlPrivate::ErrorCode errorCode, const QString &err return QString(); case QUrlPrivate::InvalidSchemeError: { - QString msg = QStringLiteral("Invalid scheme (character '%1' not permitted)"); + auto msg = QLatin1String("Invalid scheme (character '%1' not permitted)"); return msg.arg(c); } case QUrlPrivate::InvalidUserNameError: - return QString(QStringLiteral("Invalid user name (character '%1' not permitted)")) + return QLatin1String("Invalid user name (character '%1' not permitted)") .arg(c); case QUrlPrivate::InvalidPasswordError: - return QString(QStringLiteral("Invalid password (character '%1' not permitted)")) + return QLatin1String("Invalid password (character '%1' not permitted)") .arg(c); case QUrlPrivate::InvalidRegNameError: if (errorPosition != -1) - return QString(QStringLiteral("Invalid hostname (character '%1' not permitted)")) + return QLatin1String("Invalid hostname (character '%1' not permitted)") .arg(c); else return QStringLiteral("Invalid hostname (contains invalid characters)"); @@ -4017,9 +4014,9 @@ static QString errorMessage(QUrlPrivate::ErrorCode errorCode, const QString &err case QUrlPrivate::InvalidIPv6AddressError: return QStringLiteral("Invalid IPv6 address"); case QUrlPrivate::InvalidCharacterInIPv6Error: - return QStringLiteral("Invalid IPv6 address (character '%1' not permitted)").arg(c); + return QLatin1String("Invalid IPv6 address (character '%1' not permitted)").arg(c); case QUrlPrivate::InvalidIPvFutureError: - return QStringLiteral("Invalid IPvFuture address (character '%1' not permitted)").arg(c); + return QLatin1String("Invalid IPvFuture address (character '%1' not permitted)").arg(c); case QUrlPrivate::HostMissingEndBracket: return QStringLiteral("Expected ']' to match '[' in hostname"); @@ -4029,15 +4026,15 @@ static QString errorMessage(QUrlPrivate::ErrorCode errorCode, const QString &err return QStringLiteral("Port field was empty"); case QUrlPrivate::InvalidPathError: - return QString(QStringLiteral("Invalid path (character '%1' not permitted)")) + return QLatin1String("Invalid path (character '%1' not permitted)") .arg(c); case QUrlPrivate::InvalidQueryError: - return QString(QStringLiteral("Invalid query (character '%1' not permitted)")) + return QLatin1String("Invalid query (character '%1' not permitted)") .arg(c); case QUrlPrivate::InvalidFragmentError: - return QString(QStringLiteral("Invalid fragment (character '%1' not permitted)")) + return QLatin1String("Invalid fragment (character '%1' not permitted)") .arg(c); case QUrlPrivate::AuthorityPresentAndPathIsRelative: @@ -4159,7 +4156,7 @@ QList<QUrl> QUrl::fromStringList(const QStringList &urls, ParsingMode mode) \relates QHash \since 5.0 */ -uint qHash(const QUrl &url, uint seed) Q_DECL_NOTHROW +uint qHash(const QUrl &url, uint seed) noexcept { if (!url.d) return qHash(-1, seed); // the hash of an unset port (-1) @@ -4187,7 +4184,7 @@ static QUrl adjustFtpPath(QUrl url) static bool isIp6(const QString &text) { QIPAddressUtils::IPv6Address address; - return !text.isEmpty() && QIPAddressUtils::parseIp6(address, text.begin(), text.end()) == 0; + return !text.isEmpty() && QIPAddressUtils::parseIp6(address, text.begin(), text.end()) == nullptr; } /*! diff --git a/src/corelib/io/qurl.h b/src/corelib/io/qurl.h index 5062ef7905..94269e4369 100644 --- a/src/corelib/io/qurl.h +++ b/src/corelib/io/qurl.h @@ -119,7 +119,7 @@ class QTypeInfo<QUrlTwoFlags<E1, E2> > : public QTypeInfoMerger<QUrlTwoFlags<E1, class QUrl; // qHash is a friend, but we can't use default arguments for friends (ยง8.3.6.4) -Q_CORE_EXPORT uint qHash(const QUrl &url, uint seed = 0) Q_DECL_NOTHROW; +Q_CORE_EXPORT uint qHash(const QUrl &url, uint seed = 0) noexcept; class Q_CORE_EXPORT QUrl { @@ -182,15 +182,13 @@ public: QUrl(const QString &url, ParsingMode mode = TolerantMode); QUrl &operator=(const QString &url); #endif -#ifdef Q_COMPILER_RVALUE_REFS - QUrl(QUrl &&other) Q_DECL_NOTHROW : d(other.d) + QUrl(QUrl &&other) noexcept : d(other.d) { other.d = nullptr; } - inline QUrl &operator=(QUrl &&other) Q_DECL_NOTHROW + inline QUrl &operator=(QUrl &&other) noexcept { qSwap(d, other.d); return *this; } -#endif ~QUrl(); - inline void swap(QUrl &other) Q_DECL_NOTHROW { qSwap(d, other.d); } + inline void swap(QUrl &other) noexcept { qSwap(d, other.d); } void setUrl(const QString &url, ParsingMode mode = TolerantMode); QString url(FormattingOptions options = FormattingOptions(PrettyDecoded)) const; @@ -361,7 +359,7 @@ public: static QList<QUrl> fromStringList(const QStringList &uris, ParsingMode mode = TolerantMode); static void setIdnWhitelist(const QStringList &); - friend Q_CORE_EXPORT uint qHash(const QUrl &url, uint seed) Q_DECL_NOTHROW; + friend Q_CORE_EXPORT uint qHash(const QUrl &url, uint seed) noexcept; private: QUrlPrivate *d; diff --git a/src/corelib/io/qurl_p.h b/src/corelib/io/qurl_p.h index 1b9237e58a..e75de32e03 100644 --- a/src/corelib/io/qurl_p.h +++ b/src/corelib/io/qurl_p.h @@ -59,7 +59,7 @@ QT_BEGIN_NAMESPACE // in qurlrecode.cpp extern Q_AUTOTEST_EXPORT int qt_urlRecode(QString &appendTo, const QChar *begin, const QChar *end, - QUrl::ComponentFormattingOptions encoding, const ushort *tableModifications = 0); + QUrl::ComponentFormattingOptions encoding, const ushort *tableModifications = nullptr); // in qurlidna.cpp enum AceLeadingDot { AllowLeadingDot, ForbidLeadingDot }; diff --git a/src/corelib/io/qurlidna.cpp b/src/corelib/io/qurlidna.cpp index 2305e66407..a2f0caa606 100644 --- a/src/corelib/io/qurlidna.cpp +++ b/src/corelib/io/qurlidna.cpp @@ -1444,7 +1444,7 @@ static void mapToLowerCase(QString *str, int from) { int N = sizeof(NameprepCaseFolding) / sizeof(NameprepCaseFolding[0]); - ushort *d = 0; + ushort *d = nullptr; for (int i = from; i < str->size(); ++i) { uint uc = str->at(i).unicode(); if (uc < 0x80) { @@ -1474,7 +1474,7 @@ static void mapToLowerCase(QString *str, int from) else str->replace(--i, 2, reinterpret_cast<const QChar *>(&entry->mapping[0]), l); i += l - 1; - d = 0; + d = nullptr; } else { if (!d) d = reinterpret_cast<ushort *>(str->data()); @@ -2220,9 +2220,8 @@ Q_AUTOTEST_EXPORT void qt_punycodeEncoder(const QChar *s, int ucLength, QString bool skipped = false; // copy all basic code points verbatim to output. for (uint j = 0; j < (uint) ucLength; ++j) { - ushort js = s[j].unicode(); - if (js < 0x80) - *d++ = js; + if (s[j].unicode() < 0x80) + *d++ = s[j]; else skipped = true; } @@ -2404,7 +2403,7 @@ static const char * const idn_whitelist[] = { }; static const size_t idn_whitelist_size = sizeof idn_whitelist / sizeof *idn_whitelist; -static QStringList *user_idn_whitelist = 0; +static QStringList *user_idn_whitelist = nullptr; static bool lessThan(const QChar *a, int l, const char *c) { diff --git a/src/corelib/io/qurlquery.cpp b/src/corelib/io/qurlquery.cpp index 73a94cd5d5..8d80a2d8bd 100644 --- a/src/corelib/io/qurlquery.cpp +++ b/src/corelib/io/qurlquery.cpp @@ -189,7 +189,7 @@ public: template<> void QSharedDataPointer<QUrlQueryPrivate>::detach() { - if (d && d->ref.load() == 1) + if (d && d->ref.loadRelaxed() == 1) return; QUrlQueryPrivate *x = (d ? new QUrlQueryPrivate(*d) : new QUrlQueryPrivate); @@ -262,7 +262,7 @@ inline QString QUrlQueryPrivate::recodeToUser(const QString &input, QUrl::Compon if (!(encoding & QUrl::EncodeDelimiters)) { QString output; if (qt_urlRecode(output, input.constData(), input.constData() + input.length(), - encoding, 0)) + encoding, nullptr)) return output; return input; } @@ -290,12 +290,12 @@ void QUrlQueryPrivate::setQuery(const QString &query) const QChar *const end = pos + query.size(); while (pos != end) { const QChar *begin = pos; - const QChar *delimiter = 0; + const QChar *delimiter = nullptr; while (pos != end) { // scan for the component parts of this pair - if (!delimiter && pos->unicode() == valueDelimiter) + if (!delimiter && *pos == valueDelimiter) delimiter = pos; - if (pos->unicode() == pairDelimiter) + if (*pos == pairDelimiter) break; ++pos; } @@ -345,7 +345,7 @@ QSharedDataPointer<QUrlQueryPrivate>::clone() \sa setQuery(), addQueryItem() */ QUrlQuery::QUrlQuery() - : d(0) + : d(nullptr) { } @@ -356,7 +356,7 @@ QUrlQuery::QUrlQuery() set the query with setQuery(). */ QUrlQuery::QUrlQuery(const QString &queryString) - : d(queryString.isEmpty() ? 0 : new QUrlQueryPrivate(queryString)) + : d(queryString.isEmpty() ? nullptr : new QUrlQueryPrivate(queryString)) { } @@ -369,7 +369,7 @@ QUrlQuery::QUrlQuery(const QString &queryString) \sa QUrl::query() */ QUrlQuery::QUrlQuery(const QUrl &url) - : d(0) + : d(nullptr) { // use internals to avoid unnecessary recoding // ### FIXME: actually do it @@ -434,7 +434,7 @@ bool QUrlQuery::operator ==(const QUrlQuery &other) const Returns the hash value for \a key, using \a seed to seed the calculation. */ -uint qHash(const QUrlQuery &key, uint seed) Q_DECL_NOTHROW +uint qHash(const QUrlQuery &key, uint seed) noexcept { if (const QUrlQueryPrivate *d = key.d) { QtPrivate::QHashCombine hash; @@ -462,7 +462,7 @@ bool QUrlQuery::isEmpty() const */ bool QUrlQuery::isDetached() const { - return d && d->ref.load() == 1; + return d && d->ref.loadRelaxed() == 1; } /*! @@ -584,8 +584,8 @@ QString QUrlQuery::query(QUrl::ComponentFormattingOptions encoding) const */ void QUrlQuery::setQueryDelimiters(QChar valueDelimiter, QChar pairDelimiter) { - d->valueDelimiter = valueDelimiter.unicode(); - d->pairDelimiter = pairDelimiter.unicode(); + d->valueDelimiter = valueDelimiter; + d->pairDelimiter = pairDelimiter; } /*! diff --git a/src/corelib/io/qurlquery.h b/src/corelib/io/qurlquery.h index e3688aae2c..89d0f88059 100644 --- a/src/corelib/io/qurlquery.h +++ b/src/corelib/io/qurlquery.h @@ -52,7 +52,7 @@ QT_BEGIN_NAMESPACE -Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed = 0) Q_DECL_NOTHROW; +Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed = 0) noexcept; class QUrlQueryPrivate; class Q_CORE_EXPORT QUrlQuery @@ -70,16 +70,14 @@ public: QUrlQuery(const QUrlQuery &other); QUrlQuery &operator=(const QUrlQuery &other); -#ifdef Q_COMPILER_RVALUE_REFS - QUrlQuery &operator=(QUrlQuery &&other) Q_DECL_NOTHROW { swap(other); return *this; } -#endif + QUrlQuery &operator=(QUrlQuery &&other) noexcept { swap(other); return *this; } ~QUrlQuery(); bool operator==(const QUrlQuery &other) const; bool operator!=(const QUrlQuery &other) const { return !(*this == other); } - void swap(QUrlQuery &other) Q_DECL_NOTHROW { qSwap(d, other.d); } + void swap(QUrlQuery &other) noexcept { qSwap(d, other.d); } bool isEmpty() const; bool isDetached() const; @@ -111,7 +109,7 @@ public: private: friend class QUrl; - friend Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed) Q_DECL_NOTHROW; + friend Q_CORE_EXPORT uint qHash(const QUrlQuery &key, uint seed) noexcept; QSharedDataPointer<QUrlQueryPrivate> d; public: typedef QSharedDataPointer<QUrlQueryPrivate> DataPtr; diff --git a/src/corelib/io/qurlrecode.cpp b/src/corelib/io/qurlrecode.cpp index 443ae18b21..35ede8d078 100644 --- a/src/corelib/io/qurlrecode.cpp +++ b/src/corelib/io/qurlrecode.cpp @@ -377,7 +377,7 @@ static int recode(QString &result, const ushort *begin, const ushort *end, QUrl: { const int origSize = result.size(); const ushort *input = begin; - ushort *output = 0; + ushort *output = nullptr; EncodingAction action = EncodeCharacter; for ( ; input != end; ++input) { @@ -692,7 +692,7 @@ qt_urlRecode(QString &appendTo, const QChar *begin, const QChar *end, } // qstring.cpp -bool qt_is_ascii(const char *&ptr, const char *end) Q_DECL_NOTHROW; +bool qt_is_ascii(const char *&ptr, const char *end) noexcept; /*! \internal diff --git a/src/corelib/io/qwindowspipereader.cpp b/src/corelib/io/qwindowspipereader.cpp index 15c9f52cf3..1f03ac5d5a 100644 --- a/src/corelib/io/qwindowspipereader.cpp +++ b/src/corelib/io/qwindowspipereader.cpp @@ -40,6 +40,7 @@ #include "qwindowspipereader_p.h" #include "qiodevice_p.h" #include <qelapsedtimer.h> +#include <qscopedvaluerollback.h> QT_BEGIN_NAMESPACE @@ -301,9 +302,8 @@ void QWindowsPipeReader::emitPendingReadyRead() { if (readyReadPending) { readyReadPending = false; - inReadyRead = true; + QScopedValueRollback<bool> guard(inReadyRead, true); emit readyRead(); - inReadyRead = false; } } diff --git a/src/corelib/io/qwindowspipewriter.cpp b/src/corelib/io/qwindowspipewriter.cpp index 92e8b6db52..32536f495b 100644 --- a/src/corelib/io/qwindowspipewriter.cpp +++ b/src/corelib/io/qwindowspipewriter.cpp @@ -39,6 +39,7 @@ #include "qwindowspipewriter_p.h" #include "qiodevice_p.h" +#include <qscopedvaluerollback.h> QT_BEGIN_NAMESPACE @@ -111,9 +112,8 @@ void QWindowsPipeWriter::emitPendingBytesWrittenValue() emit canWrite(); if (!inBytesWritten) { - inBytesWritten = true; + QScopedValueRollback<bool> guard(inBytesWritten, true); emit bytesWritten(bytes); - inBytesWritten = false; } } } |