From 6b1d26d555e644895b9e9bf8c7b8653038827e9f Mon Sep 17 00:00:00 2001 From: thalieht Date: Sun, 18 Nov 2018 20:40:37 +0200 Subject: [PATCH] Convert all foreach() to range-based for() --- src/app/application.cpp | 2 +- src/app/cmdoptions.cpp | 3 +- src/app/filelogger.cpp | 5 +- src/app/upgrade.h | 10 +-- src/base/bittorrent/magneturi.cpp | 4 +- src/base/bittorrent/session.cpp | 60 ++++++++-------- src/base/bittorrent/torrentcreatorthread.cpp | 4 +- src/base/bittorrent/torrenthandle.cpp | 31 ++++---- src/base/bittorrent/torrenthandle.h | 2 +- src/base/bittorrent/torrentinfo.cpp | 4 +- src/base/http/connection.cpp | 2 +- src/base/http/server.cpp | 4 +- src/base/net/downloadmanager.cpp | 9 +-- src/base/net/smtp.cpp | 3 +- src/base/preferences.cpp | 13 ++-- src/base/rss/rss_autodownloader.cpp | 8 +-- src/base/rss/rss_autodownloadrule.cpp | 4 +- src/base/rss/rss_feed.cpp | 12 ++-- src/base/rss/rss_folder.cpp | 14 ++-- src/base/rss/rss_session.cpp | 5 +- src/base/scanfoldersmodel.cpp | 9 +-- src/base/search/searchhandler.cpp | 3 +- src/base/search/searchpluginmanager.cpp | 7 +- src/base/settingsstorage.cpp | 3 +- src/base/utils/fs.cpp | 2 +- src/base/utils/misc.cpp | 6 +- src/base/utils/string.h | 2 +- src/gui/addnewtorrentdialog.cpp | 4 +- src/gui/advancedsettings.cpp | 7 +- src/gui/banlistoptionsdialog.cpp | 4 +- src/gui/categoryfiltermodel.cpp | 5 +- src/gui/cookiesdialog.cpp | 3 +- src/gui/executionlogwidget.cpp | 5 +- src/gui/loglistwidget.cpp | 3 +- src/gui/mainwindow.cpp | 18 ++--- src/gui/optionsdialog.cpp | 10 +-- src/gui/properties/peerlistwidget.cpp | 16 ++--- src/gui/properties/peersadditiondialog.cpp | 3 +- src/gui/properties/piecesbar.cpp | 2 +- src/gui/properties/propertieswidget.cpp | 10 +-- src/gui/properties/proptabbar.cpp | 3 +- src/gui/properties/speedplotview.cpp | 2 +- src/gui/properties/trackerlistwidget.cpp | 37 +++++----- src/gui/properties/trackersadditiondialog.cpp | 7 +- src/gui/rss/articlelistwidget.cpp | 3 +- src/gui/rss/automatedrssdownloader.cpp | 27 +++---- src/gui/rss/feedlistwidget.cpp | 5 +- src/gui/rss/rsswidget.cpp | 23 +++--- src/gui/search/pluginselectdialog.cpp | 20 +++--- src/gui/search/searchsortmodel.cpp | 4 +- src/gui/search/searchwidget.cpp | 9 +-- src/gui/statsdialog.cpp | 3 +- src/gui/tagfiltermodel.cpp | 9 +-- src/gui/tagfilterwidget.cpp | 3 +- src/gui/torrentcontentmodel.cpp | 7 +- src/gui/torrentcontentmodelfolder.cpp | 9 +-- src/gui/transferlistfilterswidget.cpp | 15 ++-- src/gui/transferlistmodel.cpp | 3 +- src/gui/transferlistwidget.cpp | 71 ++++++++++--------- src/webui/api/logcontroller.cpp | 5 +- src/webui/api/searchcontroller.cpp | 2 +- src/webui/api/synccontroller.cpp | 11 +-- src/webui/api/torrentscontroller.cpp | 16 ++--- src/webui/webapplication.cpp | 3 +- 64 files changed, 326 insertions(+), 292 deletions(-) diff --git a/src/app/application.cpp b/src/app/application.cpp index 3b1df76af..6367efe14 100644 --- a/src/app/application.cpp +++ b/src/app/application.cpp @@ -428,7 +428,7 @@ void Application::processParams(const QStringList ¶ms) BitTorrent::AddTorrentParams torrentParams; TriStateBool skipTorrentDialog; - foreach (QString param, params) { + for (QString param : params) { param = param.trimmed(); // Process strings indicating options specified by the user. diff --git a/src/app/cmdoptions.cpp b/src/app/cmdoptions.cpp index 8c305f825..7ae889915 100644 --- a/src/app/cmdoptions.cpp +++ b/src/app/cmdoptions.cpp @@ -41,6 +41,7 @@ #include #endif +#include "base/global.h" #include "base/utils/misc.h" #include "base/utils/string.h" @@ -497,7 +498,7 @@ QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN QStringList lines = {words.first()}; int currentLineMaxLength = wrapAtColumn - initialIndentation; - foreach (const QString &word, words.mid(1)) { + for (const QString &word : copyAsConst(words.mid(1))) { if (lines.last().length() + word.length() + 1 < currentLineMaxLength) { lines.last().append(' ' + word); } diff --git a/src/app/filelogger.cpp b/src/app/filelogger.cpp index 9d61f5d28..bb6c6a34a 100644 --- a/src/app/filelogger.cpp +++ b/src/app/filelogger.cpp @@ -33,6 +33,7 @@ #include #include +#include "base/global.h" #include "base/logger.h" #include "base/utils/fs.h" @@ -50,7 +51,7 @@ FileLogger::FileLogger(const QString &path, const bool backup, const int maxSize this->deleteOld(age, ageType); const Logger *const logger = Logger::instance(); - foreach (const Log::Msg &msg, logger->getMessages()) + for (const Log::Msg &msg : copyAsConst(logger->getMessages())) addLogMessage(msg); connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage); @@ -87,7 +88,7 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType) QDateTime date = QDateTime::currentDateTime(); QDir dir(Utils::Fs::branchPath(m_path)); - foreach (const QFileInfo file, dir.entryInfoList(QStringList("qbittorrent.log.bak*"), QDir::Files | QDir::Writable, QDir::Time | QDir::Reversed)) { + for (const QFileInfo &file : copyAsConst(dir.entryInfoList(QStringList("qbittorrent.log.bak*"), QDir::Files | QDir::Writable, QDir::Time | QDir::Reversed))) { QDateTime modificationDate = file.lastModified(); switch (ageType) { case DAYS: diff --git a/src/app/upgrade.h b/src/app/upgrade.h index b22f8d872..3e18c8c46 100644 --- a/src/app/upgrade.h +++ b/src/app/upgrade.h @@ -179,9 +179,9 @@ bool upgrade(bool ask = true) // **************************************************************************************** // Silently converts old v3.3.x .fastresume files - QStringList backupFiles_3_3 = backupFolderDir.entryList( + const QStringList backupFiles_3_3 = backupFolderDir.entryList( QStringList(QLatin1String("*.fastresume.*")), QDir::Files, QDir::Unsorted); - foreach (const QString &backupFile, backupFiles_3_3) + for (const QString &backupFile : backupFiles_3_3) upgradeResumeFile(backupFolderDir.absoluteFilePath(backupFile)); // **************************************************************************************** @@ -197,10 +197,10 @@ bool upgrade(bool ask = true) if (ask && !userAcceptsUpgrade()) return false; - QStringList backupFiles = backupFolderDir.entryList( + const QStringList backupFiles = backupFolderDir.entryList( QStringList(QLatin1String("*.fastresume")), QDir::Files, QDir::Unsorted); const QRegularExpression rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$")); - foreach (QString backupFile, backupFiles) { + for (const QString &backupFile : backupFiles) { const QRegularExpressionMatch rxMatch = rx.match(backupFile); if (rxMatch.hasMatch()) { const QString hashStr = rxMatch.captured(1); @@ -265,7 +265,7 @@ void migratePlistToIni(const QString &application) plistFile->setFallbacksEnabled(false); const QStringList plist = plistFile->allKeys(); if (!plist.isEmpty()) { - foreach (const QString &key, plist) + for (const QString &key : plist) iniFile.setValue(key, plistFile->value(key)); plistFile->clear(); } diff --git a/src/base/bittorrent/magneturi.cpp b/src/base/bittorrent/magneturi.cpp index 0c37eb139..a1b76bfd5 100644 --- a/src/base/bittorrent/magneturi.cpp +++ b/src/base/bittorrent/magneturi.cpp @@ -83,10 +83,10 @@ MagnetUri::MagnetUri(const QString &source) m_hash = m_addTorrentParams.info_hash; m_name = QString::fromStdString(m_addTorrentParams.name); - foreach (const std::string &tracker, m_addTorrentParams.trackers) + for (const std::string &tracker : m_addTorrentParams.trackers) m_trackers.append(QString::fromStdString(tracker)); - foreach (const std::string &urlSeed, m_addTorrentParams.url_seeds) + for (const std::string &urlSeed : m_addTorrentParams.url_seeds) m_urlSeeds.append(QUrl(urlSeed.c_str())); } diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 0084dbcbc..78a898456 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -199,7 +199,7 @@ namespace for (auto i = categories.cbegin(); i != categories.cend(); ++i) { const QString &category = i.key(); - foreach (const QString &subcat, Session::expandCategory(category)) { + for (const QString &subcat : copyAsConst(Session::expandCategory(category))) { if (!expanded.contains(subcat)) expanded[subcat] = ""; } @@ -610,7 +610,7 @@ void Session::setTempPathEnabled(bool enabled) { if (enabled != isTempPathEnabled()) { m_isTempPathEnabled = enabled; - foreach (TorrentHandle *const torrent, m_torrents) + for (TorrentHandle *const torrent : qAsConst(m_torrents)) torrent->handleTempPathChanged(); } } @@ -624,7 +624,7 @@ void Session::setAppendExtensionEnabled(bool enabled) { if (isAppendExtensionEnabled() != enabled) { // append or remove .!qB extension for incomplete files - foreach (TorrentHandle *const torrent, m_torrents) + for (TorrentHandle *const torrent : qAsConst(m_torrents)) torrent->handleAppendExtensionToggled(); m_isAppendExtensionEnabled = enabled; @@ -752,7 +752,7 @@ bool Session::addCategory(const QString &name, const QString &savePath) return false; if (isSubcategoriesEnabled()) { - foreach (const QString &parent, expandCategory(name)) { + for (const QString &parent : copyAsConst(expandCategory(name))) { if ((parent != name) && !m_categories.contains(parent)) { m_categories[parent] = ""; emit categoryAdded(parent); @@ -775,12 +775,12 @@ bool Session::editCategory(const QString &name, const QString &savePath) m_categories[name] = savePath; m_storedCategories = map_cast(m_categories); if (isDisableAutoTMMWhenCategorySavePathChanged()) { - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) if (torrent->category() == name) torrent->setAutoTMMEnabled(false); } else { - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) if (torrent->category() == name) torrent->handleCategorySavePathChanged(); } @@ -790,7 +790,7 @@ bool Session::editCategory(const QString &name, const QString &savePath) bool Session::removeCategory(const QString &name) { - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) if (torrent->belongsToCategory(name)) torrent->setCategory(""); @@ -877,7 +877,7 @@ bool Session::addTag(const QString &tag) bool Session::removeTag(const QString &tag) { if (m_tags.remove(tag)) { - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) torrent->removeTag(tag); m_storedTags = m_tags.toList(); emit tagRemoved(tag); @@ -1085,7 +1085,7 @@ void Session::configure() void Session::processBannedIPs(libt::ip_filter &filter) { // First, import current filter - foreach (const QString &ip, m_bannedIPs.value()) { + for (const QString &ip : copyAsConst(m_bannedIPs.value())) { boost::system::error_code ec; libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec); Q_ASSERT(!ec); @@ -1204,7 +1204,7 @@ void Session::configure(libtorrent::settings_pack &settingsPack) const ushort port = this->port(); std::pair ports(port, port); settingsPack.set_int(libt::settings_pack::max_retry_port_bind, ports.second - ports.first); - foreach (QString ip, getListeningIPs()) { + for (QString ip : getListeningIPs()) { libt::error_code ec; std::string interfacesStr; @@ -1770,7 +1770,7 @@ void Session::enableBandwidthScheduler() void Session::populateAdditionalTrackers() { m_additionalTrackerList.clear(); - foreach (QString tracker, additionalTrackers().split('\n')) { + for (QString tracker : copyAsConst(additionalTrackers().split('\n'))) { tracker = tracker.trimmed(); if (!tracker.isEmpty()) m_additionalTrackerList << tracker; @@ -1781,7 +1781,7 @@ void Session::processShareLimits() { qDebug("Processing share limits..."); - foreach (TorrentHandle *const torrent, m_torrents) { + for (TorrentHandle *const torrent : copyAsConst(torrents())) { if (torrent->isSeed() && !torrent->isForced()) { if (torrent->ratioLimit() != TorrentHandle::NO_RATIO_LIMIT) { const qreal ratio = torrent->realRatio(); @@ -1934,7 +1934,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles) m_nativeSession->remove_torrent(torrent->nativeHandle(), libt::session::delete_partfile); #endif // Remove unwanted and incomplete files - foreach (const QString &unwantedFile, unwantedFiles) { + for (const QString &unwantedFile : qAsConst(unwantedFiles)) { qDebug("Removing unwanted file: %s", qUtf8Printable(unwantedFile)); Utils::Fs::forceRemove(unwantedFile); const QString parentFolder = Utils::Fs::branchPath(unwantedFile); @@ -1948,7 +1948,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles) QStringList filters; filters << QString("%1.*").arg(torrent->hash()); const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted); - foreach (const QString &file, files) + for (const QString &file : files) Utils::Fs::forceRemove(resumeDataDir.absoluteFilePath(file)); delete torrent; @@ -1983,7 +1983,7 @@ void Session::increaseTorrentsPriority(const QStringList &hashes) std::greater>> torrentQueue; // Sort torrents by priority - foreach (const InfoHash &infoHash, hashes) { + for (const InfoHash infoHash : hashes) { TorrentHandle *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.push(qMakePair(torrent->queuePosition(), torrent)); @@ -2006,7 +2006,7 @@ void Session::decreaseTorrentsPriority(const QStringList &hashes) std::less>> torrentQueue; // Sort torrents by priority - foreach (const InfoHash &infoHash, hashes) { + for (const InfoHash infoHash : hashes) { TorrentHandle *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.push(qMakePair(torrent->queuePosition(), torrent)); @@ -2032,7 +2032,7 @@ void Session::topTorrentsPriority(const QStringList &hashes) std::greater>> torrentQueue; // Sort torrents by priority - foreach (const InfoHash &infoHash, hashes) { + for (const InfoHash infoHash : hashes) { TorrentHandle *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.push(qMakePair(torrent->queuePosition(), torrent)); @@ -2055,7 +2055,7 @@ void Session::bottomTorrentsPriority(const QStringList &hashes) std::less>> torrentQueue; // Sort torrents by priority - foreach (const InfoHash &infoHash, hashes) { + for (const InfoHash infoHash : hashes) { TorrentHandle *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.push(qMakePair(torrent->queuePosition(), torrent)); @@ -2367,7 +2367,7 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde void Session::generateResumeData(bool final) { - foreach (TorrentHandle *const torrent, m_torrents) { + for (TorrentHandle *const torrent : qAsConst(m_torrents)) { if (!torrent->isValid()) continue; if (torrent->isChecking() || torrent->isPaused()) continue; if (!final && !torrent->needSaveResumeData()) continue; @@ -2444,10 +2444,10 @@ void Session::setDefaultSavePath(QString path) m_defaultSavePath = path; if (isDisableAutoTMMWhenDefaultSavePathChanged()) - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) torrent->setAutoTMMEnabled(false); else - foreach (TorrentHandle *const torrent, torrents()) + for (TorrentHandle *const torrent : copyAsConst(torrents())) torrent->handleCategorySavePathChanged(); } @@ -2458,7 +2458,7 @@ void Session::setTempPath(QString path) m_tempPath = path; - foreach (TorrentHandle *const torrent, m_torrents) + for (TorrentHandle *const torrent : qAsConst(m_torrents)) torrent->handleTempPathChanged(); } @@ -2532,7 +2532,7 @@ const QStringList Session::getListeningIPs() QHostAddress ip; QString ipString; QAbstractSocket::NetworkLayerProtocol protocol; - foreach (const QNetworkAddressEntry &entry, addresses) { + for (const QNetworkAddressEntry &entry : addresses) { ip = entry.ip(); ipString = ip.toString(); protocol = ip.protocol(); @@ -2578,7 +2578,7 @@ void Session::configureListeningInterface() libt::error_code ec; const QStringList IPs = getListeningIPs(); - foreach (const QString ip, IPs) { + for (const QString ip : IPs) { if (ip.isEmpty()) { logger->addMessage(tr("qBittorrent is trying to listen on any interface port: %1", "e.g: qBittorrent is trying to listen on any interface port: TCP/6881").arg(QString::number(port)), Log::INFO); m_nativeSession->listen_on(ports, ec, 0, libt::session::listen_no_system_port); @@ -3776,7 +3776,7 @@ void Session::handleTorrentTrackerWarning(TorrentHandle *const torrent, const QS bool Session::hasPerTorrentRatioLimit() const { - foreach (TorrentHandle *const torrent, m_torrents) + for (TorrentHandle *const torrent : qAsConst(m_torrents)) if (torrent->ratioLimit() >= 0) return true; return false; @@ -3784,7 +3784,7 @@ bool Session::hasPerTorrentRatioLimit() const bool Session::hasPerTorrentSeedingTimeLimit() const { - foreach (TorrentHandle *const torrent, m_torrents) + for (TorrentHandle *const torrent : qAsConst(m_torrents)) if (torrent->seedingTimeLimit() >= 0) return true; return false; @@ -3928,7 +3928,7 @@ void Session::startUpTorrents() QMap queuedResumeData; int nextQueuePosition = 1; int numOfRemappedFiles = 0; - foreach (const QString &fastresumeName, fastresumes) { + for (const QString &fastresumeName : qAsConst(fastresumes)) { const QRegularExpressionMatch rxMatch = rx.match(fastresumeName); if (!rxMatch.hasMatch()) continue; @@ -3967,7 +3967,7 @@ void Session::startUpTorrents() } // starting up downloading torrents (queue position > 0) - foreach (const TorrentResumeData &torrentResumeData, queuedResumeData) + for (const TorrentResumeData &torrentResumeData : qAsConst(queuedResumeData)) startupTorrent(torrentResumeData); return; @@ -4547,14 +4547,14 @@ void Session::handleStateUpdateAlert(libt::state_update_alert *p) updateStats(); #endif - foreach (const libt::torrent_status &status, p->status) { + for (const libt::torrent_status &status : p->status) { TorrentHandle *const torrent = m_torrents.value(status.info_hash); if (torrent) torrent->handleStateUpdate(status); } m_torrentStatusReport = TorrentStatusReport(); - foreach (TorrentHandle *const torrent, m_torrents) { + for (TorrentHandle *const torrent : qAsConst(m_torrents)) { if (torrent->isDownloading()) ++m_torrentStatusReport.nbDownloading; if (torrent->isUploading()) diff --git a/src/base/bittorrent/torrentcreatorthread.cpp b/src/base/bittorrent/torrentcreatorthread.cpp index 30a05dee6..d5eb6dd5e 100644 --- a/src/base/bittorrent/torrentcreatorthread.cpp +++ b/src/base/bittorrent/torrentcreatorthread.cpp @@ -141,14 +141,14 @@ void TorrentCreatorThread::run() #endif // Add url seeds - foreach (QString seed, m_params.urlSeeds) { + for (QString seed : qAsConst(m_params.urlSeeds)) { seed = seed.trimmed(); if (!seed.isEmpty()) newTorrent.add_url_seed(seed.toStdString()); } int tier = 0; - foreach (const QString &tracker, m_params.trackers) { + for (const QString &tracker : qAsConst(m_params.trackers)) { if (tracker.isEmpty()) ++tier; else diff --git a/src/base/bittorrent/torrenthandle.cpp b/src/base/bittorrent/torrenthandle.cpp index 7f8022d9a..79d1c5287 100644 --- a/src/base/bittorrent/torrenthandle.cpp +++ b/src/base/bittorrent/torrenthandle.cpp @@ -55,6 +55,7 @@ #include #endif +#include "base/global.h" #include "base/logger.h" #include "base/preferences.h" #include "base/profile.h" @@ -77,7 +78,7 @@ namespace ListType setToEntryList(const QSet &input) { ListType entryList; - foreach (const QString &setValue, input) + for (const QString &setValue : input) entryList.emplace_back(setValue.toStdString()); return entryList; } @@ -374,10 +375,9 @@ QString TorrentHandle::nativeActualSavePath() const QList TorrentHandle::trackers() const { QList entries; - std::vector announces; + const std::vector announces = m_nativeHandle.trackers(); - announces = m_nativeHandle.trackers(); - foreach (const libt::announce_entry &tracker, announces) + for (const libt::announce_entry &tracker : announces) entries << tracker; return entries; @@ -391,7 +391,7 @@ QHash TorrentHandle::trackerInfos() const void TorrentHandle::addTrackers(const QList &trackers) { QList addedTrackers; - foreach (const TrackerEntry &tracker, trackers) { + for (const TrackerEntry &tracker : trackers) { if (addTracker(tracker)) addedTrackers << tracker; } @@ -400,13 +400,13 @@ void TorrentHandle::addTrackers(const QList &trackers) m_session->handleTorrentTrackersAdded(this, addedTrackers); } -void TorrentHandle::replaceTrackers(QList trackers) +void TorrentHandle::replaceTrackers(const QList &trackers) { QList existingTrackers = this->trackers(); QList addedTrackers; std::vector announces; - foreach (const TrackerEntry &tracker, trackers) { + for (const TrackerEntry &tracker : trackers) { announces.push_back(tracker.nativeEntry()); if (!existingTrackers.contains(tracker)) addedTrackers << tracker; @@ -438,9 +438,9 @@ bool TorrentHandle::addTracker(const TrackerEntry &tracker) QList TorrentHandle::urlSeeds() const { QList urlSeeds; - std::set seeds = m_nativeHandle.url_seeds(); + const std::set seeds = m_nativeHandle.url_seeds(); - foreach (const std::string &urlSeed, seeds) + for (const std::string &urlSeed : seeds) urlSeeds.append(QUrl(urlSeed.c_str())); return urlSeeds; @@ -449,7 +449,7 @@ QList TorrentHandle::urlSeeds() const void TorrentHandle::addUrlSeeds(const QList &urlSeeds) { QList addedUrlSeeds; - foreach (const QUrl &urlSeed, urlSeeds) { + for (const QUrl &urlSeed : urlSeeds) { if (addUrlSeed(urlSeed)) addedUrlSeeds << urlSeed; } @@ -461,7 +461,7 @@ void TorrentHandle::addUrlSeeds(const QList &urlSeeds) void TorrentHandle::removeUrlSeeds(const QList &urlSeeds) { QList removedUrlSeeds; - foreach (const QUrl &urlSeed, urlSeeds) { + for (const QUrl &urlSeed : urlSeeds) { if (removeUrlSeed(urlSeed)) removedUrlSeeds << urlSeed; } @@ -596,8 +596,7 @@ bool TorrentHandle::removeTag(const QString &tag) void TorrentHandle::removeAllTags() { - // QT automatically copies the container in foreach, so it's safe to mutate it. - foreach (const QString &tag, m_tags) + for (const QString &tag : copyAsConst(tags())) removeTag(tag); } @@ -883,9 +882,9 @@ bool TorrentHandle::hasError() const bool TorrentHandle::hasFilteredPieces() const { - std::vector pp = m_nativeHandle.piece_priorities(); + const std::vector pp = m_nativeHandle.piece_priorities(); - foreach (const int priority, pp) + for (const int priority : pp) if (priority == 0) return true; return false; @@ -1087,7 +1086,7 @@ QList TorrentHandle::peers() const m_nativeHandle.get_peer_info(nativePeers); - foreach (const libt::peer_info &peer, nativePeers) + for (const libt::peer_info &peer : nativePeers) peers << PeerInfo(this, peer); return peers; diff --git a/src/base/bittorrent/torrenthandle.h b/src/base/bittorrent/torrenthandle.h index 882444c1a..03540fab9 100644 --- a/src/base/bittorrent/torrenthandle.h +++ b/src/base/bittorrent/torrenthandle.h @@ -356,7 +356,7 @@ namespace BitTorrent void setSuperSeeding(bool enable); void flushCache(); void addTrackers(const QList &trackers); - void replaceTrackers(QList trackers); + void replaceTrackers(const QList &trackers); void addUrlSeeds(const QList &urlSeeds); void removeUrlSeeds(const QList &urlSeeds); bool connectPeer(const PeerAddress &peerAddress); diff --git a/src/base/bittorrent/torrentinfo.cpp b/src/base/bittorrent/torrentinfo.cpp index f5db8fdcf..d2ad0255f 100644 --- a/src/base/bittorrent/torrentinfo.cpp +++ b/src/base/bittorrent/torrentinfo.cpp @@ -247,7 +247,7 @@ QList TorrentInfo::trackers() const if (!isValid()) return QList(); QList trackers; - foreach (const libt::announce_entry &tracker, m_nativeInfo->trackers()) + for (const libt::announce_entry &tracker : m_nativeInfo->trackers()) trackers.append(tracker); return trackers; @@ -258,7 +258,7 @@ QList TorrentInfo::urlSeeds() const if (!isValid()) return QList(); QList urlSeeds; - foreach (const libt::web_seed_entry &webSeed, m_nativeInfo->web_seeds()) + for (const libt::web_seed_entry &webSeed : m_nativeInfo->web_seeds()) if (webSeed.type == libt::web_seed_entry::url_seed) urlSeeds.append(QUrl(webSeed.url.c_str())); diff --git a/src/base/http/connection.cpp b/src/base/http/connection.cpp index 1b98f3502..47ccf8f67 100644 --- a/src/base/http/connection.cpp +++ b/src/base/http/connection.cpp @@ -133,7 +133,7 @@ bool Connection::acceptsGzipEncoding(QString codings) const auto isCodingAvailable = [](const QStringList &list, const QString &encoding) -> bool { - foreach (const QString &str, list) { + for (const QString &str : list) { if (!str.startsWith(encoding)) continue; diff --git a/src/base/http/server.cpp b/src/base/http/server.cpp index 809f36a3e..778b94b39 100644 --- a/src/base/http/server.cpp +++ b/src/base/http/server.cpp @@ -146,9 +146,9 @@ QList Server::safeCipherList() const const QStringList badCiphers = {"idea", "rc4"}; const QList allCiphers = QSslSocket::supportedCiphers(); QList safeCiphers; - foreach (const QSslCipher &cipher, allCiphers) { + for (const QSslCipher &cipher : allCiphers) { bool isSafe = true; - foreach (const QString &badCipher, badCiphers) { + for (const QString &badCipher : badCiphers) { if (cipher.name().contains(badCipher, Qt::CaseInsensitive)) { isSafe = false; break; diff --git a/src/base/net/downloadmanager.cpp b/src/base/net/downloadmanager.cpp index 66a74bcc1..b933bcb22 100644 --- a/src/base/net/downloadmanager.cpp +++ b/src/base/net/downloadmanager.cpp @@ -39,6 +39,7 @@ #include #include +#include "base/global.h" #include "base/preferences.h" #include "downloadhandler.h" #include "proxyconfigurationmanager.h" @@ -56,7 +57,7 @@ namespace { QDateTime now = QDateTime::currentDateTime(); QList cookies = Preferences::instance()->getNetworkCookies(); - foreach (const QNetworkCookie &cookie, Preferences::instance()->getNetworkCookies()) { + for (const QNetworkCookie &cookie : copyAsConst(Preferences::instance()->getNetworkCookies())) { if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -68,7 +69,7 @@ namespace { QDateTime now = QDateTime::currentDateTime(); QList cookies = allCookies(); - foreach (const QNetworkCookie &cookie, allCookies()) { + for (const QNetworkCookie &cookie : copyAsConst(allCookies())) { if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -83,7 +84,7 @@ namespace { QDateTime now = QDateTime::currentDateTime(); QList cookies = QNetworkCookieJar::cookiesForUrl(url); - foreach (const QNetworkCookie &cookie, QNetworkCookieJar::cookiesForUrl(url)) { + for (const QNetworkCookie &cookie : copyAsConst(QNetworkCookieJar::cookiesForUrl(url))) { if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -95,7 +96,7 @@ namespace { QDateTime now = QDateTime::currentDateTime(); QList cookies = cookieList; - foreach (const QNetworkCookie &cookie, cookieList) { + for (const QNetworkCookie &cookie : cookieList) { if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } diff --git a/src/base/net/smtp.cpp b/src/base/net/smtp.cpp index c3a90f4e8..0127b3e14 100644 --- a/src/base/net/smtp.cpp +++ b/src/base/net/smtp.cpp @@ -43,6 +43,7 @@ #include #endif +#include "base/global.h" #include "base/logger.h" #include "base/preferences.h" @@ -291,7 +292,7 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, QTex if (!prefix.isEmpty()) line += prefix; if (!value.contains("=?") && latin1->canEncode(value)) { bool firstWord = true; - foreach (const QByteArray &word, value.toLatin1().split(' ')) { + for (const QByteArray &word : copyAsConst(value.toLatin1().split(' '))) { if (line.size() > 78) { rv = rv + line + "\r\n"; line.clear(); diff --git a/src/base/preferences.cpp b/src/base/preferences.cpp index c5febd7e5..094600f18 100644 --- a/src/base/preferences.cpp +++ b/src/base/preferences.cpp @@ -50,6 +50,7 @@ #include #endif +#include "global.h" #include "logger.h" #include "settingsstorage.h" #include "utils/fs.h" @@ -505,7 +506,7 @@ void Preferences::setWebUiAuthSubnetWhitelistEnabled(bool enabled) QList Preferences::getWebUiAuthSubnetWhitelist() const { QList subnets; - foreach (const QString &rawSubnet, value("Preferences/WebUI/AuthSubnetWhitelist").toStringList()) { + for (const QString &rawSubnet : copyAsConst(value("Preferences/WebUI/AuthSubnetWhitelist").toStringList())) { bool ok = false; const Utils::Net::Subnet subnet = Utils::Net::parseSubnet(rawSubnet.trimmed(), &ok); if (ok) @@ -1426,8 +1427,8 @@ void Preferences::setToolbarTextPosition(const int position) QList Preferences::getNetworkCookies() const { QList cookies; - QStringList rawCookies = value("Network/Cookies").toStringList(); - foreach (const QString &rawCookie, rawCookies) + const QStringList rawCookies = value("Network/Cookies").toStringList(); + for (const QString &rawCookie : rawCookies) cookies << QNetworkCookie::parseCookies(rawCookie.toUtf8()); return cookies; @@ -1436,7 +1437,7 @@ QList Preferences::getNetworkCookies() const void Preferences::setNetworkCookies(const QList &cookies) { QStringList rawCookies; - foreach (const QNetworkCookie &cookie, cookies) + for (const QNetworkCookie &cookie : cookies) rawCookies << cookie.toRawForm(); setValue("Network/Cookies", rawCookies); @@ -1477,10 +1478,10 @@ void Preferences::upgrade() { SettingsStorage *settingsStorage = SettingsStorage::instance(); - QStringList labels = value("TransferListFilters/customLabels").toStringList(); + const QStringList labels = value("TransferListFilters/customLabels").toStringList(); if (!labels.isEmpty()) { QVariantMap categories = value("BitTorrent/Session/Categories").toMap(); - foreach (const QString &label, labels) { + for (const QString &label : labels) { if (!categories.contains(label)) categories[label] = ""; } diff --git a/src/base/rss/rss_autodownloader.cpp b/src/base/rss/rss_autodownloader.cpp index 112d65286..7f3820885 100644 --- a/src/base/rss/rss_autodownloader.cpp +++ b/src/base/rss/rss_autodownloader.cpp @@ -435,8 +435,8 @@ void AutoDownloader::loadRules(const QByteArray &data) void AutoDownloader::loadRulesLegacy() { SettingsPtr settings = Profile::instance().applicationSettings(QStringLiteral("qBittorrent-rss")); - QVariantHash rules = settings->value(QStringLiteral("download_rules")).toHash(); - foreach (const QVariant &ruleVar, rules) { + const QVariantHash rules = settings->value(QStringLiteral("download_rules")).toHash(); + for (const QVariant &ruleVar : rules) { auto rule = AutoDownloadRule::fromLegacyDict(ruleVar.toHash()); if (!rule.name().isEmpty()) insertRule(rule); @@ -451,7 +451,7 @@ void AutoDownloader::store() m_savingTimer.stop(); QJsonObject jsonObj; - foreach (auto rule, m_rules) + for (const auto &rule : qAsConst(m_rules)) jsonObj.insert(rule.name(), rule.toJsonObject()); m_fileStorage->store(RulesFileName, QJsonDocument(jsonObj).toJson()); @@ -473,7 +473,7 @@ void AutoDownloader::resetProcessingQueue() m_processingQueue.clear(); if (!m_processingEnabled) return; - foreach (Article *article, Session::instance()->rootFolder()->articles()) { + for (Article *article : copyAsConst(Session::instance()->rootFolder()->articles())) { if (!article->isRead() && !article->torrentUrl().isEmpty()) addJobForArticle(article); } diff --git a/src/base/rss/rss_autodownloadrule.cpp b/src/base/rss/rss_autodownloadrule.cpp index e6cd5f8e5..cef689c1e 100644 --- a/src/base/rss/rss_autodownloadrule.cpp +++ b/src/base/rss/rss_autodownloadrule.cpp @@ -442,7 +442,7 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co QStringList feedURLs; if (feedsVal.isString()) feedURLs << feedsVal.toString(); - else foreach (const QJsonValue &urlVal, feedsVal.toArray()) + else for (const QJsonValue &urlVal : copyAsConst(feedsVal.toArray())) feedURLs << urlVal.toString(); rule.setFeedURLs(feedURLs); @@ -452,7 +452,7 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co previouslyMatched << previouslyMatchedVal.toString(); } else { - foreach (const QJsonValue &val, previouslyMatchedVal.toArray()) + for (const QJsonValue &val : copyAsConst(previouslyMatchedVal.toArray())) previouslyMatched << val.toString(); } rule.setPreviouslyMatchedEpisodes(previouslyMatched); diff --git a/src/base/rss/rss_feed.cpp b/src/base/rss/rss_feed.cpp index f4ebd0e20..58ea929ae 100644 --- a/src/base/rss/rss_feed.cpp +++ b/src/base/rss/rss_feed.cpp @@ -109,7 +109,7 @@ QList
Feed::articles() const void Feed::markAsRead() { auto oldUnreadCount = m_unreadCount; - foreach (Article *article, m_articles) { + for (Article *article : qAsConst(m_articles)) { if (!article->isRead()) { article->disconnect(this); article->markAsRead(); @@ -282,9 +282,9 @@ void Feed::loadArticles(const QByteArray &data) return; } - QJsonArray jsonArr = jsonDoc.array(); + const QJsonArray jsonArr = jsonDoc.array(); int i = -1; - foreach (const QJsonValue &jsonVal, jsonArr) { + for (const QJsonValue &jsonVal : jsonArr) { ++i; if (!jsonVal.isObject()) { LogMsg(tr("Couldn't load RSS article '%1#%2'. Invalid data format.").arg(m_url).arg(i) @@ -304,9 +304,9 @@ void Feed::loadArticles(const QByteArray &data) void Feed::loadArticlesLegacy() { SettingsPtr qBTRSSFeeds = Profile::instance().applicationSettings(QStringLiteral("qBittorrent-rss-feeds")); - QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash(); + const QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash(); - foreach (const QVariant &var, allOldItems.value(m_url).toList()) { + for (const QVariant &var : copyAsConst(allOldItems.value(m_url).toList())) { auto hash = var.toHash(); // update legacy keys hash[Article::KeyLink] = hash.take(QLatin1String("news_link")); @@ -329,7 +329,7 @@ void Feed::store() m_savingTimer.stop(); QJsonArray jsonArr; - foreach (Article *article, m_articles) + for (Article *article :qAsConst(m_articles)) jsonArr << article->toJsonObject(); m_session->dataFileStorage()->store(m_dataFileName, QJsonDocument(jsonArr).toJson()); diff --git a/src/base/rss/rss_folder.cpp b/src/base/rss/rss_folder.cpp index e52669811..580272c48 100644 --- a/src/base/rss/rss_folder.cpp +++ b/src/base/rss/rss_folder.cpp @@ -47,7 +47,7 @@ Folder::~Folder() { emit aboutToBeDestroyed(this); - foreach (auto item, items()) + for (auto item : copyAsConst(items())) delete item; } @@ -55,7 +55,7 @@ QList
Folder::articles() const { QList
news; - foreach (Item *item, items()) { + for (Item *item : copyAsConst(items())) { int n = news.size(); news << item->articles(); std::inplace_merge(news.begin(), news.begin() + n, news.end() @@ -70,20 +70,20 @@ QList
Folder::articles() const int Folder::unreadCount() const { int count = 0; - foreach (Item *item, items()) + for (Item *item : copyAsConst(items())) count += item->unreadCount(); return count; } void Folder::markAsRead() { - foreach (Item *item, items()) + for (Item *item : copyAsConst(items())) item->markAsRead(); } void Folder::refresh() { - foreach (Item *item, items()) + for (Item *item : copyAsConst(items())) item->refresh(); } @@ -95,7 +95,7 @@ QList Folder::items() const QJsonValue Folder::toJsonValue(bool withData) const { QJsonObject jsonObj; - foreach (Item *item, items()) + for (Item *item : copyAsConst(items())) jsonObj.insert(item->name(), item->toJsonValue(withData)); return jsonObj; @@ -108,7 +108,7 @@ void Folder::handleItemUnreadCountChanged() void Folder::cleanup() { - foreach (Item *item, items()) + for (Item *item : copyAsConst(items())) item->cleanup(); } diff --git a/src/base/rss/rss_session.cpp b/src/base/rss/rss_session.cpp index b8304500a..1564db247 100644 --- a/src/base/rss/rss_session.cpp +++ b/src/base/rss/rss_session.cpp @@ -41,6 +41,7 @@ #include #include "../asyncfilestorage.h" +#include "../global.h" #include "../logger.h" #include "../profile.h" #include "../settingsstorage.h" @@ -283,7 +284,7 @@ void Session::load() void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder) { bool updated = false; - foreach (const QString &key, jsonObj.keys()) { + for (const QString &key : copyAsConst(jsonObj.keys())) { const QJsonValue val {jsonObj[key]}; if (val.isString()) { // previous format (reduced form) doesn't contain UID @@ -355,7 +356,7 @@ void Session::loadLegacy() const QString parentFolderPath = Item::parentPath(legacyPath); const QString feedUrl = Item::relativeName(legacyPath); - foreach (const QString &folderPath, Item::expandPath(parentFolderPath)) + for (const QString &folderPath : copyAsConst(Item::expandPath(parentFolderPath))) addFolder(folderPath); const QString feedPath = feedAliases[i].isEmpty() diff --git a/src/base/scanfoldersmodel.cpp b/src/base/scanfoldersmodel.cpp index a5b00dbbf..20a399220 100644 --- a/src/base/scanfoldersmodel.cpp +++ b/src/base/scanfoldersmodel.cpp @@ -35,6 +35,7 @@ #include "bittorrent/session.h" #include "filesystemwatcher.h" +#include "global.h" #include "preferences.h" #include "utils/fs.h" @@ -254,7 +255,7 @@ void ScanFoldersModel::addToFSWatcher(const QStringList &watchPaths) if (!m_fsWatcher) return; // addPath() wasn't called before this - foreach (const QString &path, watchPaths) { + for (const QString &path : watchPaths) { QDir watchDir(path); const QString canonicalWatchPath = watchDir.canonicalPath(); m_fsWatcher->addPath(canonicalWatchPath); @@ -282,7 +283,7 @@ bool ScanFoldersModel::removePath(const QString &path, bool removeFromFSWatcher) void ScanFoldersModel::removeFromFSWatcher(const QStringList &watchPaths) { - foreach (const QString &path, watchPaths) + for (const QString &path : watchPaths) m_fsWatcher->removePath(path); } @@ -326,7 +327,7 @@ void ScanFoldersModel::makePersistent() { QVariantHash dirs; - foreach (const PathData *pathData, m_pathList) { + for (const PathData *pathData : qAsConst(m_pathList)) { if (pathData->downloadType == CUSTOM_LOCATION) dirs.insert(Utils::Fs::fromNativePath(pathData->watchPath), Utils::Fs::fromNativePath(pathData->downloadPath)); else @@ -350,7 +351,7 @@ void ScanFoldersModel::configure() void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList) { - foreach (const QString &file, pathList) { + for (const QString &file : pathList) { qDebug("File %s added", qUtf8Printable(file)); BitTorrent::AddTorrentParams params; diff --git a/src/base/search/searchhandler.cpp b/src/base/search/searchhandler.cpp index d2c518787..57f8e3bb4 100644 --- a/src/base/search/searchhandler.cpp +++ b/src/base/search/searchhandler.cpp @@ -32,6 +32,7 @@ #include #include +#include "../global.h" #include "../utils/foreignapps.h" #include "../utils/fs.h" #include "searchpluginmanager.h" @@ -138,7 +139,7 @@ void SearchHandler::readSearchOutput() m_searchResultLineTruncated = lines.takeLast().trimmed(); QList searchResultList; - foreach (const QByteArray &line, lines) { + for (const QByteArray &line : qAsConst(lines)) { SearchResult searchResult; if (parseSearchResult(QString::fromUtf8(line), searchResult)) searchResultList << searchResult; diff --git a/src/base/search/searchpluginmanager.cpp b/src/base/search/searchpluginmanager.cpp index 1b079b089..2a2d4484e 100644 --- a/src/base/search/searchpluginmanager.cpp +++ b/src/base/search/searchpluginmanager.cpp @@ -133,7 +133,7 @@ QStringList SearchPluginManager::supportedCategories() const QStringList result; for (const PluginInfo *plugin : qAsConst(m_plugins)) { if (plugin->enabled) { - foreach (QString cat, plugin->supportedCategories) { + for (const QString &cat : plugin->supportedCategories) { if (!result.contains(cat)) result << cat; } @@ -277,9 +277,8 @@ bool SearchPluginManager::uninstallPlugin(const QString &name) QDir pluginsFolder(pluginsLocation()); QStringList filters; filters << name + ".*"; - QStringList files = pluginsFolder.entryList(filters, QDir::Files, QDir::Unsorted); - QString file; - foreach (file, files) + const QStringList files = pluginsFolder.entryList(filters, QDir::Files, QDir::Unsorted); + for (const QString &file : files) Utils::Fs::forceRemove(pluginsFolder.absoluteFilePath(file)); // Remove it from supported engines delete m_plugins.take(name); diff --git a/src/base/settingsstorage.cpp b/src/base/settingsstorage.cpp index 17ec860e6..96146103b 100644 --- a/src/base/settingsstorage.cpp +++ b/src/base/settingsstorage.cpp @@ -33,6 +33,7 @@ #include #include +#include "global.h" #include "logger.h" #include "profile.h" #include "utils/fs.h" @@ -286,7 +287,7 @@ QString TransactionalSettings::deserialize(const QString &name, QVariantHash &da // Copy everything into memory. This means even keys inserted in the file manually // or that we don't touch directly in this code (eg disabled by ifdef). This ensures // that they will be copied over when save our settings to disk. - foreach (const QString &key, settings->allKeys()) + for (const QString &key : copyAsConst(settings->allKeys())) data.insert(key, settings->value(key)); return settings->fileName(); diff --git a/src/base/utils/fs.cpp b/src/base/utils/fs.cpp index f928a29cb..338acce99 100644 --- a/src/base/utils/fs.cpp +++ b/src/base/utils/fs.cpp @@ -141,7 +141,7 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const QString &path) // remove temp files on linux (file ends with '~'), e.g. `filename~` QDir dir(p); - QStringList tmpFileList = dir.entryList(QDir::Files); + const QStringList tmpFileList = dir.entryList(QDir::Files); for (const QString &f : tmpFileList) { if (f.endsWith('~')) forceRemove(p + f); diff --git a/src/base/utils/misc.cpp b/src/base/utils/misc.cpp index a00e10585..ec1078edc 100644 --- a/src/base/utils/misc.cpp +++ b/src/base/utils/misc.cpp @@ -391,7 +391,7 @@ QString Utils::Misc::getUserIDString() QStringList Utils::Misc::toStringList(const QList &l) { QStringList ret; - foreach (const bool &b, l) + for (const bool b : l) ret << (b ? "1" : "0"); return ret; } @@ -399,7 +399,7 @@ QStringList Utils::Misc::toStringList(const QList &l) QList Utils::Misc::intListfromStringList(const QStringList &l) { QList ret; - foreach (const QString &s, l) + for (const QString &s : l) ret << s.toInt(); return ret; } @@ -407,7 +407,7 @@ QList Utils::Misc::intListfromStringList(const QStringList &l) QList Utils::Misc::boolListfromStringList(const QStringList &l) { QList ret; - foreach (const QString &s, l) + for (const QString &s : l) ret << (s == "1"); return ret; } diff --git a/src/base/utils/string.h b/src/base/utils/string.h index 69eb7c020..5a1088622 100644 --- a/src/base/utils/string.h +++ b/src/base/utils/string.h @@ -60,7 +60,7 @@ namespace Utils { if (str.length() < 2) return str; - for (auto const quote : quotes) { + for (const auto "e : quotes) { if (str.startsWith(quote) && str.endsWith(quote)) return str.mid(1, str.length() - 2); } diff --git a/src/gui/addnewtorrentdialog.cpp b/src/gui/addnewtorrentdialog.cpp index 6b7e62943..9c1ea8c1a 100644 --- a/src/gui/addnewtorrentdialog.cpp +++ b/src/gui/addnewtorrentdialog.cpp @@ -143,7 +143,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(const BitTorrent::AddTorrentParams &inP m_ui->categoryComboBox->addItem(defaultCategory); m_ui->categoryComboBox->addItem(""); - foreach (const QString &category, categories) + for (const QString &category : qAsConst(categories)) if (category != defaultCategory && category != m_torrentParams.category) m_ui->categoryComboBox->addItem(category); @@ -631,7 +631,7 @@ void AddNewTorrentDialog::displayContentTreeMenu(const QPoint &) prio = prio::IGNORED; qDebug("Setting files priority"); - foreach (const QModelIndex &index, selectedRows) { + for (const QModelIndex &index : selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); m_contentModel->setData(m_contentModel->index(index.row(), PRIORITY, index.parent()), prio); } diff --git a/src/gui/advancedsettings.cpp b/src/gui/advancedsettings.cpp index 5342a1888..feb497e8c 100644 --- a/src/gui/advancedsettings.cpp +++ b/src/gui/advancedsettings.cpp @@ -36,6 +36,7 @@ #include #include "base/bittorrent/session.h" +#include "base/global.h" #include "base/preferences.h" #include "base/unicodestrings.h" #include "app/application.h" @@ -286,13 +287,13 @@ void AdvancedSettings::updateInterfaceAddressCombo() }; if (ifaceName.isEmpty()) { - foreach (const QHostAddress &ip, QNetworkInterface::allAddresses()) + for (const QHostAddress &ip : copyAsConst(QNetworkInterface::allAddresses())) populateCombo(ip.toString(), ip.protocol()); } else { const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName); const QList addresses = iface.addressEntries(); - foreach (const QNetworkAddressEntry &entry, addresses) { + for (const QNetworkAddressEntry &entry : addresses) { const QHostAddress ip = entry.ip(); populateCombo(ip.toString(), ip.protocol()); } @@ -425,7 +426,7 @@ void AdvancedSettings::loadAdvancedSettings() const QString currentInterface = session->networkInterface(); bool interfaceExists = currentInterface.isEmpty(); int i = 1; - foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) { + for (const QNetworkInterface &iface : copyAsConst(QNetworkInterface::allInterfaces())) { // This line fixes a Qt bug => https://bugreports.qt.io/browse/QTBUG-52633 // Tested in Qt 5.6.0. For more info see: // https://github.com/qbittorrent/qBittorrent/issues/5131 diff --git a/src/gui/banlistoptionsdialog.cpp b/src/gui/banlistoptionsdialog.cpp index 30c67ac03..171612055 100644 --- a/src/gui/banlistoptionsdialog.cpp +++ b/src/gui/banlistoptionsdialog.cpp @@ -107,8 +107,8 @@ void BanListOptionsDialog::on_buttonBanIP_clicked() void BanListOptionsDialog::on_buttonDeleteIP_clicked() { - QModelIndexList selection = m_ui->bannedIPList->selectionModel()->selectedIndexes(); - for (auto &i : selection) + const QModelIndexList selection = m_ui->bannedIPList->selectionModel()->selectedIndexes(); + for (const auto &i : selection) m_sortFilter->removeRow(i.row()); m_modified = true; diff --git a/src/gui/categoryfiltermodel.cpp b/src/gui/categoryfiltermodel.cpp index 118fd0421..ad4c84869 100644 --- a/src/gui/categoryfiltermodel.cpp +++ b/src/gui/categoryfiltermodel.cpp @@ -33,6 +33,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "guiiconprovider.h" class CategoryModelItem @@ -407,7 +408,7 @@ void CategoryFilterModel::populate() const QString &category = i.key(); if (m_isSubcategoriesEnabled) { CategoryModelItem *parent = m_rootItem; - foreach (const QString &subcat, session->expandCategory(category)) { + for (const QString &subcat : copyAsConst(session->expandCategory(category))) { const QString subcatName = shortName(subcat); if (!parent->hasChild(subcatName)) { new CategoryModelItem( @@ -436,7 +437,7 @@ CategoryModelItem *CategoryFilterModel::findItem(const QString &fullName) const return m_rootItem->child(fullName); CategoryModelItem *item = m_rootItem; - foreach (const QString &subcat, BitTorrent::Session::expandCategory(fullName)) { + for (const QString &subcat : copyAsConst(BitTorrent::Session::expandCategory(fullName))) { const QString subcatName = shortName(subcat); if (!item->hasChild(subcatName)) return nullptr; item = item->child(subcatName); diff --git a/src/gui/cookiesdialog.cpp b/src/gui/cookiesdialog.cpp index 23bf4a767..0d6af6721 100644 --- a/src/gui/cookiesdialog.cpp +++ b/src/gui/cookiesdialog.cpp @@ -30,6 +30,7 @@ #include +#include "base/global.h" #include "base/net/downloadmanager.h" #include "base/settingsstorage.h" #include "cookiesmodel.h" @@ -100,6 +101,6 @@ void CookiesDialog::onButtonDeleteClicked() } ); - for (const QModelIndex &idx : idxs) + for (const QModelIndex &idx : qAsConst(idxs)) m_cookiesModel->removeRow(idx.row()); } diff --git a/src/gui/executionlogwidget.cpp b/src/gui/executionlogwidget.cpp index 2a74213c5..fb90aa63f 100644 --- a/src/gui/executionlogwidget.cpp +++ b/src/gui/executionlogwidget.cpp @@ -32,6 +32,7 @@ #include #include +#include "base/global.h" #include "guiiconprovider.h" #include "loglistwidget.h" #include "ui_executionlogwidget.h" @@ -52,9 +53,9 @@ ExecutionLogWidget::ExecutionLogWidget(QWidget *parent, const Log::MsgTypes &typ m_ui->tabBan->layout()->addWidget(m_peerList); const Logger *const logger = Logger::instance(); - foreach (const Log::Msg &msg, logger->getMessages()) + for (const Log::Msg &msg : copyAsConst(logger->getMessages())) addLogMessage(msg); - foreach (const Log::Peer &peer, logger->getPeers()) + for (const Log::Peer &peer : copyAsConst(logger->getPeers())) addPeerMessage(peer); connect(logger, &Logger::newLogMessage, this, &ExecutionLogWidget::addLogMessage); connect(logger, &Logger::newLogPeer, this, &ExecutionLogWidget::addPeerMessage); diff --git a/src/gui/loglistwidget.cpp b/src/gui/loglistwidget.cpp index 572fa5fb1..93abc8ae0 100644 --- a/src/gui/loglistwidget.cpp +++ b/src/gui/loglistwidget.cpp @@ -36,6 +36,7 @@ #include #include +#include "base/global.h" #include "guiiconprovider.h" LogListWidget::LogListWidget(int maxLines, const Log::MsgTypes &types, QWidget *parent) @@ -97,7 +98,7 @@ void LogListWidget::copySelection() { static const QRegularExpression htmlTag("<[^>]+>"); QStringList strings; - foreach (QListWidgetItem* it, selectedItems()) + for (QListWidgetItem* it : copyAsConst(selectedItems())) strings << static_cast(itemWidget(it))->text().remove(htmlTag); QApplication::clipboard()->setText(strings.join('\n')); diff --git a/src/gui/mainwindow.cpp b/src/gui/mainwindow.cpp index b53ef50ca..842e57c34 100644 --- a/src/gui/mainwindow.cpp +++ b/src/gui/mainwindow.cpp @@ -284,7 +284,7 @@ MainWindow::MainWindow(QWidget *parent) m_prioSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopPriority); #ifdef Q_OS_MAC - foreach (QAction *action, m_ui->toolBar->actions()) { + for (QAction *action : copyAsConst(m_ui->toolBar->actions())) { if (action->isSeparator()) { QWidget *spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -1239,7 +1239,7 @@ bool MainWindow::event(QEvent *e) qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr); // Check if there is a modal window bool hasModalWindow = false; - foreach (QWidget *widget, QApplication::allWidgets()) { + for (QWidget *widget : copyAsConst(QApplication::allWidgets())) { if (widget->isModal()) { hasModalWindow = true; break; @@ -1285,7 +1285,7 @@ void MainWindow::dropEvent(QDropEvent *event) // remove scheme QStringList files; if (event->mimeData()->hasUrls()) { - foreach (const QUrl &url, event->mimeData()->urls()) { + for (const QUrl &url : copyAsConst(event->mimeData()->urls())) { if (url.isEmpty()) continue; @@ -1300,7 +1300,7 @@ void MainWindow::dropEvent(QDropEvent *event) // differentiate ".torrent" files/links & magnet links from others QStringList torrentFiles, otherFiles; - foreach (const QString &file, files) { + for (const QString &file : qAsConst(files)) { const bool isTorrentLink = (file.startsWith("magnet:", Qt::CaseInsensitive) || file.endsWith(C_TORRENT_FILE_EXTENSION, Qt::CaseInsensitive) || Utils::Misc::isUrl(file)); @@ -1312,7 +1312,7 @@ void MainWindow::dropEvent(QDropEvent *event) // Download torrents const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); - foreach (const QString &file, torrentFiles) { + for (const QString &file : qAsConst(torrentFiles)) { if (useTorrentAdditionDialog) AddNewTorrentDialog::show(file, this); else @@ -1321,7 +1321,7 @@ void MainWindow::dropEvent(QDropEvent *event) if (!torrentFiles.isEmpty()) return; // Create torrent - foreach (const QString &file, otherFiles) { + for (const QString &file : qAsConst(otherFiles)) { createTorrentTriggered(file); // currently only hande the first entry @@ -1333,7 +1333,7 @@ void MainWindow::dropEvent(QDropEvent *event) // Decode if we accept drag 'n drop or not void MainWindow::dragEnterEvent(QDragEnterEvent *event) { - foreach (const QString &mime, event->mimeData()->formats()) + for (const QString &mime : copyAsConst(event->mimeData()->formats())) qDebug("mimeData: %s", mime.toLocal8Bit().data()); if (event->mimeData()->hasFormat("text/plain") || event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); @@ -1382,7 +1382,7 @@ void MainWindow::on_actionOpen_triggered() const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); if (!pathsList.isEmpty()) { - foreach (QString file, pathsList) { + for (const QString &file : pathsList) { qDebug("Dropped file %s on download list", qUtf8Printable(file)); if (useTorrentAdditionDialog) AddNewTorrentDialog::show(file, this); @@ -1635,7 +1635,7 @@ void MainWindow::showNotificationBaloon(QString title, QString msg) const void MainWindow::downloadFromURLList(const QStringList &urlList) { const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); - foreach (QString url, urlList) { + for (QString url : urlList) { if (((url.size() == 40) && !url.contains(QRegularExpression("[^0-9A-Fa-f]"))) || ((url.size() == 32) && !url.contains(QRegularExpression("[^2-7A-Za-z]")))) url = "magnet:?xt=urn:btih:" + url; diff --git a/src/gui/optionsdialog.cpp b/src/gui/optionsdialog.cpp index 27126fb6b..07e8cdfc9 100644 --- a/src/gui/optionsdialog.cpp +++ b/src/gui/optionsdialog.cpp @@ -145,8 +145,8 @@ OptionsDialog::OptionsDialog(QWidget *parent) m_ui->hsplitter->setCollapsible(0, false); m_ui->hsplitter->setCollapsible(1, false); // Get apply button in button box - QList buttons = m_ui->buttonBox->buttons(); - foreach (QAbstractButton *button, buttons) { + const QList buttons = m_ui->buttonBox->buttons(); + for (QAbstractButton *button : buttons) { if (m_ui->buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole) { m_applyButton = button; break; @@ -455,7 +455,7 @@ void OptionsDialog::initializeLanguageCombo() // List language files const QDir langDir(":/lang"); const QStringList langFiles = langDir.entryList(QStringList("qbittorrent_*.qm"), QDir::Files); - foreach (const QString langFile, langFiles) { + for (const QString &langFile : langFiles) { QString localeStr = langFile.mid(12); // remove "qbittorrent_" localeStr.chop(3); // Remove ".qm" QString languageName; @@ -479,7 +479,7 @@ OptionsDialog::~OptionsDialog() saveWindowState(); - foreach (const QString &path, m_addedScanDirs) + for (const QString &path : qAsConst(m_addedScanDirs)) ScanFoldersModel::instance()->removePath(path); ScanFoldersModel::instance()->configure(); // reloads "removed" paths delete m_ui; @@ -1490,7 +1490,7 @@ void OptionsDialog::on_removeScanFolderButton_clicked() if (selected.isEmpty()) return; Q_ASSERT(selected.count() == ScanFoldersModel::instance()->columnCount()); - foreach (const QModelIndex &index, selected) { + for (const QModelIndex &index : selected) { if (index.column() == ScanFoldersModel::WATCH) m_removedScanDirs << index.data().toString(); } diff --git a/src/gui/properties/peerlistwidget.cpp b/src/gui/properties/peerlistwidget.cpp index 94b77bb19..eab083c15 100644 --- a/src/gui/properties/peerlistwidget.cpp +++ b/src/gui/properties/peerlistwidget.cpp @@ -248,9 +248,9 @@ void PeerListWidget::showPeerListMenu(const QPoint &) if (!act) return; if (act == addPeerAct) { - QList peersList = PeersAdditionDialog::askForPeers(this); + const QList peersList = PeersAdditionDialog::askForPeers(this); int peerCount = 0; - foreach (const BitTorrent::PeerAddress &addr, peersList) { + for (const BitTorrent::PeerAddress &addr : peersList) { if (torrent->connectPeer(addr)) { qDebug("Adding peer %s...", qUtf8Printable(addr.ip.toString())); Logger::instance()->addMessage(tr("Manually adding peer '%1'...").arg(addr.ip.toString())); @@ -284,8 +284,8 @@ void PeerListWidget::banSelectedPeers() QString(), 0, 1); if (ret) return; - QModelIndexList selectedIndexes = selectionModel()->selectedRows(); - foreach (const QModelIndex &index, selectedIndexes) { + const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); + for (const QModelIndex &index : selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); qDebug("Banning peer %s...", ip.toLocal8Bit().data()); @@ -298,9 +298,9 @@ void PeerListWidget::banSelectedPeers() void PeerListWidget::copySelectedPeers() { - QModelIndexList selectedIndexes = selectionModel()->selectedRows(); + const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QStringList selectedPeers; - foreach (const QModelIndex &index, selectedIndexes) { + for (const QModelIndex &index : selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); QString myport = m_listModel->data(m_listModel->index(row, PeerListDelegate::PORT)).toString(); @@ -339,10 +339,10 @@ void PeerListWidget::loadPeers(BitTorrent::TorrentHandle *const torrent, bool fo { if (!torrent) return; - QList peers = torrent->peers(); + const QList peers = torrent->peers(); QSet oldPeersSet = m_peerItems.keys().toSet(); - foreach (const BitTorrent::PeerInfo &peer, peers) { + for (const BitTorrent::PeerInfo &peer : peers) { BitTorrent::PeerAddress addr = peer.address(); if (addr.ip.isNull()) continue; diff --git a/src/gui/properties/peersadditiondialog.cpp b/src/gui/properties/peersadditiondialog.cpp index 68d3f8905..6ae13a79f 100644 --- a/src/gui/properties/peersadditiondialog.cpp +++ b/src/gui/properties/peersadditiondialog.cpp @@ -31,6 +31,7 @@ #include #include +#include "base/global.h" #include "ui_peersadditiondialog.h" PeersAdditionDialog::PeersAdditionDialog(QWidget *parent) @@ -61,7 +62,7 @@ void PeersAdditionDialog::validateInput() QMessageBox::Ok); return; } - foreach (const QString &peer, m_ui->textEditPeers->toPlainText().trimmed().split('\n')) { + for (const QString &peer : copyAsConst(m_ui->textEditPeers->toPlainText().trimmed().split('\n'))) { BitTorrent::PeerAddress addr = parsePeer(peer); if (!addr.ip.isNull()) { m_peersList.append(addr); diff --git a/src/gui/properties/piecesbar.cpp b/src/gui/properties/piecesbar.cpp index 34047f442..8ecb45548 100644 --- a/src/gui/properties/piecesbar.cpp +++ b/src/gui/properties/piecesbar.cpp @@ -259,7 +259,7 @@ void PiecesBar::showToolTip(const QHelpEvent *e) stream << ""; PieceIndexToImagePos transform {m_torrent->info(), m_image}; int pieceIndex = transform.pieceIndex(imagePos); - QVector files {m_torrent->info().fileIndicesForPiece(pieceIndex)}; + const QVector files {m_torrent->info().fileIndicesForPiece(pieceIndex)}; QString tooltipTitle; if (files.count() > 1) { diff --git a/src/gui/properties/propertieswidget.cpp b/src/gui/properties/propertieswidget.cpp index 2d4942ef3..f85f57e42 100644 --- a/src/gui/properties/propertieswidget.cpp +++ b/src/gui/properties/propertieswidget.cpp @@ -511,7 +511,7 @@ void PropertiesWidget::loadUrlSeeds() qDebug("Loading URL seeds"); const QList hcSeeds = m_torrent->urlSeeds(); // Add url seeds - foreach (const QUrl &hcSeed, hcSeeds) { + for (const QUrl &hcSeed : hcSeeds) { qDebug("Loading URL seed: %s", qUtf8Printable(hcSeed.toString())); new QListWidgetItem(hcSeed.toString(), m_ui->listWebSeeds); } @@ -582,7 +582,7 @@ void PropertiesWidget::displayFilesListMenu(const QPoint &) { if (!m_torrent) return; - QModelIndexList selectedRows = m_ui->filesList->selectionModel()->selectedRows(0); + const QModelIndexList selectedRows = m_ui->filesList->selectionModel()->selectedRows(0); if (selectedRows.empty()) return; QMenu myFilesLlistMenu; @@ -630,7 +630,7 @@ void PropertiesWidget::displayFilesListMenu(const QPoint &) prio = prio::IGNORED; qDebug("Setting files priority"); - foreach (QModelIndex index, selectedRows) { + for (const QModelIndex &index : selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); m_propListModel->setData(m_propListModel->index(index.row(), PRIORITY, index.parent()), prio); } @@ -847,7 +847,7 @@ void PropertiesWidget::deleteSelectedUrlSeeds() if (selectedItems.isEmpty()) return; QList urlSeeds; - foreach (const QListWidgetItem *item, selectedItems) + for (const QListWidgetItem *item : selectedItems) urlSeeds << item->text(); m_torrent->removeUrlSeeds(urlSeeds); @@ -861,7 +861,7 @@ void PropertiesWidget::copySelectedWebSeedsToClipboard() const if (selectedItems.isEmpty()) return; QStringList urlsToCopy; - foreach (QListWidgetItem *item, selectedItems) + for (const QListWidgetItem *item : selectedItems) urlsToCopy << item->text(); QApplication::clipboard()->setText(urlsToCopy.join('\n')); diff --git a/src/gui/properties/proptabbar.cpp b/src/gui/properties/proptabbar.cpp index 779283b3b..6d972c999 100644 --- a/src/gui/properties/proptabbar.cpp +++ b/src/gui/properties/proptabbar.cpp @@ -33,6 +33,7 @@ #include #include +#include "base/global.h" #include "guiiconprovider.h" PropTabBar::PropTabBar(QWidget *parent) @@ -102,7 +103,7 @@ PropTabBar::PropTabBar(QWidget *parent) connect(m_btnGroup, static_cast(&QButtonGroup::buttonClicked) , this, &PropTabBar::setCurrentIndex); // Disable buttons focus - foreach (QAbstractButton *btn, m_btnGroup->buttons()) + for (QAbstractButton *btn : copyAsConst(m_btnGroup->buttons())) btn->setFocusPolicy(Qt::NoFocus); } diff --git a/src/gui/properties/speedplotview.cpp b/src/gui/properties/speedplotview.cpp index 354c28297..313388c45 100644 --- a/src/gui/properties/speedplotview.cpp +++ b/src/gui/properties/speedplotview.cpp @@ -274,7 +274,7 @@ void SpeedPlotView::paintEvent(QPaintEvent *) rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text // draw Y axis speed labels - QVector speedLabels = { + const QVector speedLabels = { formatLabel(niceScale.arg, niceScale.unit), formatLabel((0.75 * niceScale.arg), niceScale.unit), formatLabel((0.50 * niceScale.arg), niceScale.unit), diff --git a/src/gui/properties/trackerlistwidget.cpp b/src/gui/properties/trackerlistwidget.cpp index 986412ae4..510399190 100644 --- a/src/gui/properties/trackerlistwidget.cpp +++ b/src/gui/properties/trackerlistwidget.cpp @@ -45,6 +45,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/trackerentry.h" +#include "base/global.h" #include "base/preferences.h" #include "base/utils/misc.h" #include "autoexpandabledialog.h" @@ -140,7 +141,7 @@ QList TrackerListWidget::getSelectedTrackerItems() const { const QList selectedTrackerItems = selectedItems(); QList selectedTrackers; - foreach (QTreeWidgetItem *item, selectedTrackerItems) { + for (QTreeWidgetItem *item : selectedTrackerItems) { if (indexOfTopLevelItem(item) >= NB_STICKY_ITEM) // Ignore STICKY ITEMS selectedTrackers << item; } @@ -163,11 +164,11 @@ void TrackerListWidget::moveSelectionUp() clear(); return; } - QList selectedTrackerItems = getSelectedTrackerItems(); + const QList selectedTrackerItems = getSelectedTrackerItems(); if (selectedTrackerItems.isEmpty()) return; bool change = false; - foreach (QTreeWidgetItem *item, selectedTrackerItems) { + for (QTreeWidgetItem *item : selectedTrackerItems) { int index = indexOfTopLevelItem(item); if (index > NB_STICKY_ITEM) { insertTopLevelItem(index - 1, takeTopLevelItem(index)); @@ -178,7 +179,7 @@ void TrackerListWidget::moveSelectionUp() // Restore selection QItemSelectionModel *selection = selectionModel(); - foreach (QTreeWidgetItem *item, selectedTrackerItems) + for (QTreeWidgetItem *item : selectedTrackerItems) selection->select(indexFromItem(item), (QItemSelectionModel::Rows | QItemSelectionModel::Select)); setSelectionModel(selection); @@ -204,7 +205,7 @@ void TrackerListWidget::moveSelectionDown() clear(); return; } - QList selectedTrackerItems = getSelectedTrackerItems(); + const QList selectedTrackerItems = getSelectedTrackerItems(); if (selectedTrackerItems.isEmpty()) return; bool change = false; @@ -219,7 +220,7 @@ void TrackerListWidget::moveSelectionDown() // Restore selection QItemSelectionModel *selection = selectionModel(); - foreach (QTreeWidgetItem *item, selectedTrackerItems) + for (QTreeWidgetItem *item : selectedTrackerItems) selection->select(indexFromItem(item), (QItemSelectionModel::Rows | QItemSelectionModel::Select)); setSelectionModel(selection); @@ -289,7 +290,7 @@ void TrackerListWidget::loadStickyItems(BitTorrent::TorrentHandle *const torrent // XXX: libtorrent should provide this info... // Count peers from DHT, PeX, LSD uint seedsDHT = 0, seedsPeX = 0, seedsLSD = 0, peersDHT = 0, peersPeX = 0, peersLSD = 0; - foreach (const BitTorrent::PeerInfo &peer, torrent->peers()) { + for (const BitTorrent::PeerInfo &peer : copyAsConst(torrent->peers())) { if (peer.isConnecting()) continue; if (peer.fromDHT()) { @@ -331,7 +332,7 @@ void TrackerListWidget::loadTrackers() // Load actual trackers information QHash trackerData = torrent->trackerInfos(); QStringList oldTrackerURLs = m_trackerItems.keys(); - foreach (const BitTorrent::TrackerEntry &entry, torrent->trackers()) { + for (const BitTorrent::TrackerEntry &entry : copyAsConst(torrent->trackers())) { QString trackerURL = entry.url(); QTreeWidgetItem *item = m_trackerItems.value(trackerURL, nullptr); if (!item) { @@ -383,7 +384,7 @@ void TrackerListWidget::loadTrackers() item->setTextAlignment(COL_DOWNLOADED, (Qt::AlignRight | Qt::AlignVCenter)); } // Remove old trackers - foreach (const QString &tracker, oldTrackerURLs) + for (const QString &tracker : qAsConst(oldTrackerURLs)) delete m_trackerItems.take(tracker); } @@ -394,7 +395,7 @@ void TrackerListWidget::askForTrackers() if (!torrent) return; QList trackers; - foreach (const QString &tracker, TrackersAdditionDialog::askForTrackers(this, torrent)) + for (const QString &tracker : copyAsConst(TrackersAdditionDialog::askForTrackers(this, torrent))) trackers << tracker; torrent->addTrackers(trackers); @@ -402,11 +403,11 @@ void TrackerListWidget::askForTrackers() void TrackerListWidget::copyTrackerUrl() { - QList selectedTrackerItems = getSelectedTrackerItems(); + const QList selectedTrackerItems = getSelectedTrackerItems(); if (selectedTrackerItems.isEmpty()) return; QStringList urlsToCopy; - foreach (QTreeWidgetItem *item, selectedTrackerItems) { + for (const QTreeWidgetItem *item : selectedTrackerItems) { QString trackerURL = item->data(COL_URL, Qt::DisplayRole).toString(); qDebug() << QString("Copy: ") + trackerURL; urlsToCopy << trackerURL; @@ -423,11 +424,11 @@ void TrackerListWidget::deleteSelectedTrackers() return; } - QList selectedTrackerItems = getSelectedTrackerItems(); + const QList selectedTrackerItems = getSelectedTrackerItems(); if (selectedTrackerItems.isEmpty()) return; QStringList urlsToRemove; - foreach (QTreeWidgetItem *item, selectedTrackerItems) { + for (const QTreeWidgetItem *item : selectedTrackerItems) { QString trackerURL = item->data(COL_URL, Qt::DisplayRole).toString(); urlsToRemove << trackerURL; m_trackerItems.remove(trackerURL); @@ -436,8 +437,8 @@ void TrackerListWidget::deleteSelectedTrackers() // Iterate over the trackers and remove the selected ones QList remainingTrackers; - QList trackers = torrent->trackers(); - foreach (const BitTorrent::TrackerEntry &entry, trackers) { + const QList trackers = torrent->trackers(); + for (const BitTorrent::TrackerEntry &entry : trackers) { if (!urlsToRemove.contains(entry.url())) remainingTrackers.push_back(entry); } @@ -493,7 +494,7 @@ void TrackerListWidget::editSelectedTracker() void TrackerListWidget::reannounceSelected() { - QList selItems = selectedItems(); + const QList selItems = selectedItems(); if (selItems.isEmpty()) return; BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); @@ -501,7 +502,7 @@ void TrackerListWidget::reannounceSelected() QList trackers = torrent->trackers(); - foreach (QTreeWidgetItem* item, selItems) { + for (const QTreeWidgetItem *item : selItems) { // DHT case if (item == m_DHTItem) { torrent->forceDHTAnnounce(); diff --git a/src/gui/properties/trackersadditiondialog.cpp b/src/gui/properties/trackersadditiondialog.cpp index 235db43f4..884dee8ee 100644 --- a/src/gui/properties/trackersadditiondialog.cpp +++ b/src/gui/properties/trackersadditiondialog.cpp @@ -34,6 +34,7 @@ #include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/trackerentry.h" +#include "base/global.h" #include "base/net/downloadhandler.h" #include "base/net/downloadmanager.h" #include "base/utils/fs.h" @@ -59,7 +60,7 @@ TrackersAdditionDialog::~TrackersAdditionDialog() QStringList TrackersAdditionDialog::newTrackers() const { QStringList cleanTrackers; - foreach (QString url, m_ui->textEditTrackersList->toPlainText().split('\n')) { + for (QString url : copyAsConst(m_ui->textEditTrackersList->toPlainText().split('\n'))) { url = url.trimmed(); if (!url.isEmpty()) cleanTrackers << url; @@ -83,8 +84,8 @@ void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray // Load from torrent handle QList existingTrackers = m_torrent->trackers(); // Load from current user list - QStringList tmp = m_ui->textEditTrackersList->toPlainText().split('\n'); - foreach (const QString &userURL, tmp) { + const QStringList tmp = m_ui->textEditTrackersList->toPlainText().split('\n'); + for (const QString &userURL : tmp) { BitTorrent::TrackerEntry userTracker(userURL); if (!existingTrackers.contains(userTracker)) existingTrackers << userTracker; diff --git a/src/gui/rss/articlelistwidget.cpp b/src/gui/rss/articlelistwidget.cpp index cef67b943..8e39ca815 100644 --- a/src/gui/rss/articlelistwidget.cpp +++ b/src/gui/rss/articlelistwidget.cpp @@ -30,6 +30,7 @@ #include +#include "base/global.h" #include "base/rss/rss_article.h" #include "base/rss/rss_item.h" @@ -68,7 +69,7 @@ void ArticleListWidget::setRSSItem(RSS::Item *rssItem, bool unreadOnly) connect(m_rssItem, &RSS::Item::articleRead, this, &ArticleListWidget::handleArticleRead); connect(m_rssItem, &RSS::Item::articleAboutToBeRemoved, this, &ArticleListWidget::handleArticleAboutToBeRemoved); - foreach (auto article, rssItem->articles()) { + for (const auto article : copyAsConst(rssItem->articles())) { if (!(m_unreadOnly && article->isRead())) { auto item = createItem(article); addItem(item); diff --git a/src/gui/rss/automatedrssdownloader.cpp b/src/gui/rss/automatedrssdownloader.cpp index 12124f1ad..239745539 100644 --- a/src/gui/rss/automatedrssdownloader.cpp +++ b/src/gui/rss/automatedrssdownloader.cpp @@ -41,6 +41,7 @@ #include #include "base/bittorrent/session.h" +#include "base/global.h" #include "base/preferences.h" #include "base/rss/rss_article.h" #include "base/rss/rss_autodownloader.h" @@ -131,7 +132,7 @@ AutomatedRssDownloader::AutomatedRssDownloader(QWidget *parent) loadFeedList(); m_ui->listRules->blockSignals(true); - foreach (const RSS::AutoDownloadRule &rule, RSS::AutoDownloader::instance()->rules()) + for (const RSS::AutoDownloadRule &rule : copyAsConst(RSS::AutoDownloader::instance()->rules())) createRuleItem(rule); m_ui->listRules->blockSignals(false); @@ -181,7 +182,7 @@ void AutomatedRssDownloader::loadFeedList() { const QSignalBlocker feedListSignalBlocker(m_ui->listFeeds); - foreach (auto feed, RSS::Session::instance()->feeds()) { + for (const auto feed : copyAsConst(RSS::Session::instance()->feeds())) { QListWidgetItem *item = new QListWidgetItem(feed->name(), m_ui->listFeeds); item->setData(Qt::UserRole, feed->url()); item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsTristate); @@ -211,7 +212,7 @@ void AutomatedRssDownloader::updateFeedList() bool allEnabled = true; bool anyEnabled = false; - foreach (const QListWidgetItem *ruleItem, selection) { + for (const QListWidgetItem *ruleItem : qAsConst(selection)) { auto rule = RSS::AutoDownloader::instance()->ruleByName(ruleItem->text()); if (rule.feedURLs().contains(feedURL)) anyEnabled = true; @@ -384,7 +385,7 @@ void AutomatedRssDownloader::on_removeRuleBtn_clicked() if (QMessageBox::question(this, tr("Rule deletion confirmation"), confirmText, QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes) return; - foreach (QListWidgetItem *item, selection) + for (const QListWidgetItem *item : selection) RSS::AutoDownloader::instance()->removeRule(item->text()); } @@ -548,7 +549,7 @@ void AutomatedRssDownloader::clearSelectedRuleDownloadedEpisodeList() void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feedItem) { const QString feedURL = feedItem->data(Qt::UserRole).toString(); - foreach (QListWidgetItem *ruleItem, m_ui->listRules->selectedItems()) { + for (QListWidgetItem *ruleItem : copyAsConst(m_ui->listRules->selectedItems())) { RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem ? m_currentRule : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); @@ -572,16 +573,16 @@ void AutomatedRssDownloader::updateMatchingArticles() { m_ui->treeMatchingArticles->clear(); - foreach (const QListWidgetItem *ruleItem, m_ui->listRules->selectedItems()) { + for (const QListWidgetItem *ruleItem : copyAsConst(m_ui->listRules->selectedItems())) { RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem ? m_currentRule : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); - foreach (const QString &feedURL, rule.feedURLs()) { + for (const QString &feedURL : copyAsConst(rule.feedURLs())) { auto feed = RSS::Session::instance()->feedByURL(feedURL); if (!feed) continue; // feed doesn't exist QStringList matchingArticles; - foreach (auto article, feed->articles()) + for (const auto article : copyAsConst(feed->articles())) if (rule.matches(article->data())) matchingArticles << article->title(); if (!matchingArticles.isEmpty()) @@ -620,7 +621,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(RSS::Feed *feed, const QStrin } // Insert the articles - foreach (const QString &article, articles) { + for (const QString &article : articles) { QPair key(feed->name(), article); if (!m_treeListEntries.contains(key)) { @@ -675,10 +676,10 @@ void AutomatedRssDownloader::updateMustLineValidity() if (isRegex) tokens << text; else - foreach (const QString &token, text.split('|')) + for (const QString &token : copyAsConst(text.split('|'))) tokens << Utils::String::wildcardToRegex(token); - foreach (const QString &token, tokens) { + for (const QString &token : qAsConst(tokens)) { QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); if (!reg.isValid()) { if (isRegex) @@ -713,10 +714,10 @@ void AutomatedRssDownloader::updateMustNotLineValidity() if (isRegex) tokens << text; else - foreach (const QString &token, text.split('|')) + for (const QString &token : copyAsConst(text.split('|'))) tokens << Utils::String::wildcardToRegex(token); - foreach (const QString &token, tokens) { + for (const QString &token : qAsConst(tokens)) { QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); if (!reg.isValid()) { if (isRegex) diff --git a/src/gui/rss/feedlistwidget.cpp b/src/gui/rss/feedlistwidget.cpp index 40754a8a2..8be6c9ee2 100644 --- a/src/gui/rss/feedlistwidget.cpp +++ b/src/gui/rss/feedlistwidget.cpp @@ -33,6 +33,7 @@ #include #include +#include "base/global.h" #include "base/rss/rss_article.h" #include "base/rss/rss_feed.h" #include "base/rss/rss_folder.h" @@ -219,7 +220,7 @@ void FeedListWidget::dropEvent(QDropEvent *event) : RSS::Session::instance()->rootFolder()); // move as much items as possible - foreach (QTreeWidgetItem *srcItem, selectedItems()) { + for (QTreeWidgetItem *srcItem : copyAsConst(selectedItems())) { auto rssItem = getRSSItem(srcItem); RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(destFolder->path(), rssItem->name())); } @@ -264,7 +265,7 @@ QTreeWidgetItem *FeedListWidget::createItem(RSS::Item *rssItem, QTreeWidgetItem void FeedListWidget::fill(QTreeWidgetItem *parent, RSS::Folder *rssParent) { - foreach (auto rssItem, rssParent->items()) { + for (const auto rssItem : copyAsConst(rssParent->items())) { QTreeWidgetItem *item = createItem(rssItem, parent); // Recursive call if this is a folder. if (auto folder = qobject_cast(rssItem)) diff --git a/src/gui/rss/rsswidget.cpp b/src/gui/rss/rsswidget.cpp index a772978a3..03145bcdb 100644 --- a/src/gui/rss/rsswidget.cpp +++ b/src/gui/rss/rsswidget.cpp @@ -41,6 +41,7 @@ #include #include "base/bittorrent/session.h" +#include "base/global.h" #include "base/net/downloadmanager.h" #include "base/preferences.h" #include "base/rss/rss_article.h" @@ -186,7 +187,7 @@ void RSSWidget::displayItemsListMenu(const QPoint &) { bool hasTorrent = false; bool hasLink = false; - foreach (const QListWidgetItem *item, m_articleListWidget->selectedItems()) { + for (const QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); @@ -286,7 +287,7 @@ void RSSWidget::on_newFeedButton_clicked() void RSSWidget::deleteSelectedItems() { - QList selectedItems = m_feedListWidget->selectedItems(); + const QList selectedItems = m_feedListWidget->selectedItems(); if (selectedItems.isEmpty()) return; if ((selectedItems.size() == 1) && (selectedItems.first() == m_feedListWidget->stickyUnreadItem())) @@ -298,7 +299,7 @@ void RSSWidget::deleteSelectedItems() if (answer == QMessageBox::No) return; - foreach (QTreeWidgetItem *item, selectedItems) + for (QTreeWidgetItem *item : selectedItems) if (item != m_feedListWidget->stickyUnreadItem()) RSS::Session::instance()->removeItem(m_feedListWidget->itemPath(item)); } @@ -306,9 +307,9 @@ void RSSWidget::deleteSelectedItems() void RSSWidget::loadFoldersOpenState() { const QStringList openedFolders = Preferences::instance()->getRssOpenFolders(); - foreach (const QString &varPath, openedFolders) { + for (const QString &varPath : openedFolders) { QTreeWidgetItem *parent = nullptr; - foreach (const QString &name, varPath.split('\\')) { + for (const QString &name : copyAsConst(varPath.split('\\'))) { int nbChildren = (parent ? parent->childCount() : m_feedListWidget->topLevelItemCount()); for (int i = 0; i < nbChildren; ++i) { QTreeWidgetItem *child = (parent ? parent->child(i) : m_feedListWidget->topLevelItem(i)); @@ -325,7 +326,7 @@ void RSSWidget::loadFoldersOpenState() void RSSWidget::saveFoldersOpenState() { QStringList openedFolders; - foreach (QTreeWidgetItem *item, m_feedListWidget->getAllOpenedFolders()) + for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->getAllOpenedFolders())) openedFolders << m_feedListWidget->itemPath(item); Preferences::instance()->setRssOpenFolders(openedFolders); } @@ -337,7 +338,7 @@ void RSSWidget::refreshAllFeeds() void RSSWidget::downloadSelectedTorrents() { - foreach (QListWidgetItem *item, m_articleListWidget->selectedItems()) { + for (QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); @@ -356,7 +357,7 @@ void RSSWidget::downloadSelectedTorrents() // open the url of the selected RSS articles in the Web browser void RSSWidget::openSelectedArticlesUrls() { - foreach (QListWidgetItem *item, m_articleListWidget->selectedItems()) { + for (QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); @@ -397,7 +398,7 @@ void RSSWidget::renameSelectedRSSItem() void RSSWidget::refreshSelectedItems() { - foreach (QTreeWidgetItem *item, m_feedListWidget->selectedItems()) { + for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { if (item == m_feedListWidget->stickyUnreadItem()) { refreshAllFeeds(); return; @@ -410,7 +411,7 @@ void RSSWidget::refreshSelectedItems() void RSSWidget::copySelectedFeedsURL() { QStringList URLs; - foreach (QTreeWidgetItem *item, m_feedListWidget->selectedItems()) { + for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { if (auto feed = qobject_cast(m_feedListWidget->getRSSItem(item))) URLs << feed->url(); } @@ -425,7 +426,7 @@ void RSSWidget::handleCurrentFeedItemChanged(QTreeWidgetItem *currentItem) void RSSWidget::on_markReadButton_clicked() { - foreach (QTreeWidgetItem *item, m_feedListWidget->selectedItems()) { + for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { m_feedListWidget->getRSSItem(item)->markAsRead(); if (item == m_feedListWidget->stickyUnreadItem()) break; // all items was read diff --git a/src/gui/search/pluginselectdialog.cpp b/src/gui/search/pluginselectdialog.cpp index e2dcd9915..995a37c52 100644 --- a/src/gui/search/pluginselectdialog.cpp +++ b/src/gui/search/pluginselectdialog.cpp @@ -39,6 +39,7 @@ #include #include +#include "base/global.h" #include "base/net/downloadhandler.h" #include "base/net/downloadmanager.h" #include "base/utils/fs.h" @@ -110,7 +111,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event) QStringList files; if (event->mimeData()->hasUrls()) { - foreach (const QUrl &url, event->mimeData()->urls()) { + for (const QUrl &url : copyAsConst(event->mimeData()->urls())) { if (!url.isEmpty()) { if (url.scheme().compare("file", Qt::CaseInsensitive) == 0) files << url.toLocalFile(); @@ -125,7 +126,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event) if (files.isEmpty()) return; - foreach (QString file, files) { + for (const QString &file : qAsConst(files)) { qDebug("dropped %s", qUtf8Printable(file)); startAsyncOp(); m_pluginManager->installPlugin(file); @@ -135,8 +136,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event) // Decode if we accept drag 'n drop or not void PluginSelectDialog::dragEnterEvent(QDragEnterEvent *event) { - QString mime; - foreach (mime, event->mimeData()->formats()) { + for (const QString &mime : copyAsConst(event->mimeData()->formats())) { qDebug("mimeData: %s", qUtf8Printable(mime)); } @@ -188,7 +188,7 @@ void PluginSelectDialog::on_closeButton_clicked() void PluginSelectDialog::on_actionUninstall_triggered() { bool error = false; - foreach (QTreeWidgetItem *item, m_ui->pluginsTree->selectedItems()) { + for (QTreeWidgetItem *item : copyAsConst(m_ui->pluginsTree->selectedItems())) { int index = m_ui->pluginsTree->indexOfTopLevelItem(item); Q_ASSERT(index != -1); QString id = item->text(PLUGIN_ID); @@ -212,7 +212,7 @@ void PluginSelectDialog::on_actionUninstall_triggered() void PluginSelectDialog::enableSelection(bool enable) { - foreach (QTreeWidgetItem *item, m_ui->pluginsTree->selectedItems()) { + for (QTreeWidgetItem *item : copyAsConst(m_ui->pluginsTree->selectedItems())) { int index = m_ui->pluginsTree->indexOfTopLevelItem(item); Q_ASSERT(index != -1); QString id = item->text(PLUGIN_ID); @@ -265,7 +265,7 @@ void PluginSelectDialog::loadSupportedSearchPlugins() { // Some clean up first m_ui->pluginsTree->clear(); - foreach (QString name, m_pluginManager->allPlugins()) + for (const QString &name : copyAsConst(m_pluginManager->allPlugins())) addNewPlugin(name); } @@ -360,11 +360,11 @@ void PluginSelectDialog::askForPluginUrl() void PluginSelectDialog::askForLocalPlugin() { - QStringList pathsList = QFileDialog::getOpenFileNames( + const QStringList pathsList = QFileDialog::getOpenFileNames( nullptr, tr("Select search plugins"), QDir::homePath(), tr("qBittorrent search plugin") + QLatin1String(" (*.py)") ); - foreach (QString path, pathsList) { + for (const QString &path : pathsList) { startAsyncOp(); m_pluginManager->installPlugin(path); } @@ -380,7 +380,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath) QList sizes = icon.availableSizes(); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); if (!invalid) { - foreach (QTreeWidgetItem *item, findItemsWithUrl(url)) { + for (QTreeWidgetItem *item : copyAsConst(findItemsWithUrl(url))) { QString id = item->text(PLUGIN_ID); PluginInfo *plugin = m_pluginManager->pluginInfo(id); if (!plugin) continue; diff --git a/src/gui/search/searchsortmodel.cpp b/src/gui/search/searchsortmodel.cpp index 2fe8e3234..3357ed4a6 100644 --- a/src/gui/search/searchsortmodel.cpp +++ b/src/gui/search/searchsortmodel.cpp @@ -28,6 +28,8 @@ #include "searchsortmodel.h" +#include "base/global.h" + SearchSortModel::SearchSortModel(QObject *parent) : base(parent) , m_isNameFilterEnabled(false) @@ -126,7 +128,7 @@ bool SearchSortModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceP const QAbstractItemModel *const sourceModel = this->sourceModel(); if (m_isNameFilterEnabled && !m_searchTerm.isEmpty()) { QString name = sourceModel->data(sourceModel->index(sourceRow, NAME, sourceParent)).toString(); - for (const QString &word : m_searchTermWords) { + for (const QString &word : qAsConst(m_searchTermWords)) { int i = name.indexOf(word, 0, Qt::CaseInsensitive); if (i == -1) { return false; diff --git a/src/gui/search/searchwidget.cpp b/src/gui/search/searchwidget.cpp index 32eea1cdd..cb253c7c5 100644 --- a/src/gui/search/searchwidget.cpp +++ b/src/gui/search/searchwidget.cpp @@ -49,6 +49,7 @@ #include #include "base/bittorrent/session.h" +#include "base/global.h" #include "base/preferences.h" #include "base/search/searchpluginmanager.h" #include "base/search/searchhandler.h" @@ -166,11 +167,11 @@ void SearchWidget::fillCatCombobox() using QStrPair = QPair; QList tmpList; - foreach (const QString &cat, SearchPluginManager::instance()->getPluginCategories(selectedPlugin())) + for (const QString &cat : copyAsConst(SearchPluginManager::instance()->getPluginCategories(selectedPlugin()))) tmpList << qMakePair(SearchPluginManager::categoryFullName(cat), cat); std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (QString::localeAwareCompare(l.first, r.first) < 0); }); - foreach (const QStrPair &p, tmpList) { + for (const QStrPair &p : qAsConst(tmpList)) { qDebug("Supported category: %s", qUtf8Printable(p.second)); m_ui->comboCategory->addItem(p.first, QVariant(p.second)); } @@ -188,11 +189,11 @@ void SearchWidget::fillPluginComboBox() using QStrPair = QPair; QList tmpList; - foreach (const QString &name, SearchPluginManager::instance()->enabledPlugins()) + for (const QString &name : copyAsConst(SearchPluginManager::instance()->enabledPlugins())) tmpList << qMakePair(SearchPluginManager::instance()->pluginFullName(name), name); std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (l.first < r.first); } ); - foreach (const QStrPair &p, tmpList) + for (const QStrPair &p : qAsConst(tmpList)) m_ui->selectPlugin->addItem(p.first, QVariant(p.second)); if (m_ui->selectPlugin->count() > 3) diff --git a/src/gui/statsdialog.cpp b/src/gui/statsdialog.cpp index f02f5aa90..2c465ee0e 100644 --- a/src/gui/statsdialog.cpp +++ b/src/gui/statsdialog.cpp @@ -32,6 +32,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/sessionstatus.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "base/utils/misc.h" #include "base/utils/string.h" #include "ui_statsdialog.h" @@ -89,7 +90,7 @@ void StatsDialog::update() // num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake) quint32 peers = 0; - foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) peers += torrent->peersCount(); m_ui->labelWriteStarve->setText(QString("%1%") diff --git a/src/gui/tagfiltermodel.cpp b/src/gui/tagfiltermodel.cpp index 8ffb934b8..27eab14d4 100644 --- a/src/gui/tagfiltermodel.cpp +++ b/src/gui/tagfiltermodel.cpp @@ -33,6 +33,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "guiiconprovider.h" namespace @@ -236,7 +237,7 @@ void TagFilterModel::torrentAdded(BitTorrent::TorrentHandle *const torrent) if (items.isEmpty()) untaggedItem()->increaseTorrentsCount(); - foreach (TagModelItem *item, items) + for (TagModelItem *item : items) item->increaseTorrentsCount(); } @@ -247,7 +248,7 @@ void TagFilterModel::torrentAboutToBeRemoved(BitTorrent::TorrentHandle *const to if (torrent->tags().isEmpty()) untaggedItem()->decreaseTorrentsCount(); - foreach (TagModelItem *item, findItems(torrent->tags())) + for (TagModelItem *item : copyAsConst(findItems(torrent->tags()))) item->decreaseTorrentsCount(); } @@ -274,7 +275,7 @@ void TagFilterModel::populate() [](Torrent *torrent) { return torrent->tags().isEmpty(); }); addToModel(getSpecialUntaggedTag(), untaggedCount); - foreach (const QString &tag, session->tags()) { + for (const QString &tag : copyAsConst(session->tags())) { const int count = std::count_if(torrents.begin(), torrents.end(), [tag](Torrent *torrent) { return torrent->hasTag(tag); }); addToModel(tag, count); @@ -313,7 +314,7 @@ QVector TagFilterModel::findItems(const QSet &tags) { QVector items; items.reserve(tags.size()); - foreach (const QString &tag, tags) { + for (const QString &tag : tags) { TagModelItem *item = findItem(tag); if (item) items.push_back(item); diff --git a/src/gui/tagfilterwidget.cpp b/src/gui/tagfilterwidget.cpp index dea898840..304116c92 100644 --- a/src/gui/tagfilterwidget.cpp +++ b/src/gui/tagfilterwidget.cpp @@ -35,6 +35,7 @@ #include #include "base/bittorrent/session.h" +#include "base/global.h" #include "autoexpandabledialog.h" #include "guiiconprovider.h" #include "tagfiltermodel.h" @@ -222,7 +223,7 @@ void TagFilterWidget::removeTag() void TagFilterWidget::removeUnusedTags() { auto session = BitTorrent::Session::instance(); - foreach (const QString &tag, session->tags()) + for (const QString &tag : copyAsConst(session->tags())) if (model()->data(static_cast(model())->index(tag), Qt::UserRole) == 0) session->removeTag(tag); updateGeometry(); diff --git a/src/gui/torrentcontentmodel.cpp b/src/gui/torrentcontentmodel.cpp index 242c913eb..1c38e38f3 100644 --- a/src/gui/torrentcontentmodel.cpp +++ b/src/gui/torrentcontentmodel.cpp @@ -48,6 +48,7 @@ #include #endif +#include "base/global.h" #include "base/utils/misc.h" #include "base/utils/fs.h" #include "guiiconprovider.h" @@ -266,14 +267,14 @@ QVector TorrentContentModel::getFilePriorities() const { QVector prio; prio.reserve(m_filesIndex.size()); - foreach (const TorrentContentModelFile *file, m_filesIndex) + for (const TorrentContentModelFile *file : qAsConst(m_filesIndex)) prio.push_back(file->priority()); return prio; } bool TorrentContentModel::allFiltered() const { - foreach (const TorrentContentModelFile *fileItem, m_filesIndex) + for (const TorrentContentModelFile *fileItem : qAsConst(m_filesIndex)) if (fileItem->priority() != prio::IGNORED) return false; return true; @@ -476,7 +477,7 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info) // Iterate of parts of the path to create necessary folders QStringList pathFolders = path.split('/', QString::SkipEmptyParts); pathFolders.removeLast(); - foreach (const QString &pathPart, pathFolders) { + for (const QString &pathPart : qAsConst(pathFolders)) { if (pathPart == ".unwanted") continue; TorrentContentModelFolder* newParent = currentParent->childFolderWithName(pathPart); diff --git a/src/gui/torrentcontentmodelfolder.cpp b/src/gui/torrentcontentmodelfolder.cpp index cf72971d0..dc0874529 100644 --- a/src/gui/torrentcontentmodelfolder.cpp +++ b/src/gui/torrentcontentmodelfolder.cpp @@ -29,6 +29,7 @@ #include "torrentcontentmodelfolder.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" TorrentContentModelFolder::TorrentContentModelFolder(const QString &name, TorrentContentModelFolder *parent) : TorrentContentModelItem(parent) @@ -85,7 +86,7 @@ TorrentContentModelItem *TorrentContentModelFolder::child(int row) const TorrentContentModelFolder *TorrentContentModelFolder::childFolderWithName(const QString &name) const { - foreach (TorrentContentModelItem *child, m_childItems) + for (TorrentContentModelItem *child : qAsConst(m_childItems)) if ((child->itemType() == FolderType) && (child->name() == name)) return static_cast(child); return nullptr; @@ -132,7 +133,7 @@ void TorrentContentModelFolder::setPriority(int newPriority, bool updateParent) // Update children if (m_priority != prio::MIXED) - foreach (TorrentContentModelItem *child, m_childItems) + for (TorrentContentModelItem *child : qAsConst(m_childItems)) child->setPriority(m_priority, false); } @@ -141,7 +142,7 @@ void TorrentContentModelFolder::recalculateProgress() qreal tProgress = 0; qulonglong tSize = 0; qulonglong tRemaining = 0; - foreach (TorrentContentModelItem *child, m_childItems) { + for (TorrentContentModelItem *child : qAsConst(m_childItems)) { if (child->priority() == prio::IGNORED) continue; @@ -164,7 +165,7 @@ void TorrentContentModelFolder::recalculateAvailability() qreal tAvailability = 0; qulonglong tSize = 0; bool foundAnyData = false; - foreach (TorrentContentModelItem *child, m_childItems) { + for (TorrentContentModelItem *child : qAsConst(m_childItems)) { if (child->priority() == prio::IGNORED) continue; diff --git a/src/gui/transferlistfilterswidget.cpp b/src/gui/transferlistfilterswidget.cpp index 96ba93523..aedf94ddf 100644 --- a/src/gui/transferlistfilterswidget.cpp +++ b/src/gui/transferlistfilterswidget.cpp @@ -40,6 +40,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/trackerentry.h" +#include "base/global.h" #include "base/logger.h" #include "base/net/downloadhandler.h" #include "base/net/downloadmanager.h" @@ -219,7 +220,7 @@ TrackerFiltersList::TrackerFiltersList(QWidget *parent, TransferListWidget *tran TrackerFiltersList::~TrackerFiltersList() { - foreach (const QString &iconPath, m_iconPaths) + for (const QString &iconPath : qAsConst(m_iconPaths)) Utils::Fs::forceRemove(iconPath); } @@ -487,8 +488,8 @@ void TrackerFiltersList::applyFilter(int row) void TrackerFiltersList::handleNewTorrent(BitTorrent::TorrentHandle *const torrent) { QString hash = torrent->hash(); - QList trackers = torrent->trackers(); - foreach (const BitTorrent::TrackerEntry &tracker, trackers) + const QList trackers = torrent->trackers(); + for (const BitTorrent::TrackerEntry &tracker : trackers) addItem(tracker.url(), hash); //Check for trackerless torrent @@ -501,8 +502,8 @@ void TrackerFiltersList::handleNewTorrent(BitTorrent::TorrentHandle *const torre void TrackerFiltersList::torrentAboutToBeDeleted(BitTorrent::TorrentHandle *const torrent) { QString hash = torrent->hash(); - QList trackers = torrent->trackers(); - foreach (const BitTorrent::TrackerEntry &tracker, trackers) + const QList trackers = torrent->trackers(); + for (const BitTorrent::TrackerEntry &tracker : trackers) removeItem(tracker.url(), hash); //Check for trackerless torrent @@ -662,13 +663,13 @@ void TransferListFiltersWidget::setDownloadTrackerFavicon(bool value) void TransferListFiltersWidget::addTrackers(BitTorrent::TorrentHandle *const torrent, const QList &trackers) { - foreach (const BitTorrent::TrackerEntry &tracker, trackers) + for (const BitTorrent::TrackerEntry &tracker : trackers) m_trackerFilters->addItem(tracker.url(), torrent->hash()); } void TransferListFiltersWidget::removeTrackers(BitTorrent::TorrentHandle *const torrent, const QList &trackers) { - foreach (const BitTorrent::TrackerEntry &tracker, trackers) + for (const BitTorrent::TrackerEntry &tracker : trackers) m_trackerFilters->removeItem(tracker.url(), torrent->hash()); } diff --git a/src/gui/transferlistmodel.cpp b/src/gui/transferlistmodel.cpp index 3c5304257..ae2ac5d0e 100644 --- a/src/gui/transferlistmodel.cpp +++ b/src/gui/transferlistmodel.cpp @@ -36,6 +36,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "base/torrentfilter.h" #include "base/utils/fs.h" @@ -61,7 +62,7 @@ TransferListModel::TransferListModel(QObject *parent) { // Load the torrents using namespace BitTorrent; - foreach (TorrentHandle *const torrent, Session::instance()->torrents()) + for (TorrentHandle *const torrent : copyAsConst(Session::instance()->torrents())) addTorrent(torrent); // Listen for torrent changes diff --git a/src/gui/transferlistwidget.cpp b/src/gui/transferlistwidget.cpp index 6782d70ad..1251ea319 100644 --- a/src/gui/transferlistwidget.cpp +++ b/src/gui/transferlistwidget.cpp @@ -43,6 +43,7 @@ #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "base/logger.h" #include "base/preferences.h" #include "base/torrentfilter.h" @@ -72,7 +73,7 @@ namespace QStringList extractHashes(const QList &torrents) { QStringList hashes; - foreach (BitTorrent::TorrentHandle *const torrent, torrents) + for (BitTorrent::TorrentHandle *const torrent : torrents) hashes << torrent->hash(); return hashes; @@ -381,7 +382,7 @@ void TransferListWidget::torrentDoubleClicked() QList TransferListWidget::getSelectedTorrents() const { QList torrents; - foreach (const QModelIndex &index, selectionModel()->selectedRows()) + for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) torrents << m_listModel->torrentHandle(mapToSource(index)); return torrents; @@ -401,7 +402,7 @@ void TransferListWidget::setSelectedTorrentsLocation() qDebug("New location is %s", qUtf8Printable(newLocation)); // Actually move storage - foreach (BitTorrent::TorrentHandle *const torrent, torrents) { + for (BitTorrent::TorrentHandle *const torrent : torrents) { Logger::instance()->addMessage(tr("Set location: moving \"%1\", from \"%2\" to \"%3\"" , "Set location: moving \"ubuntu_16_04.iso\", from \"/home/dir1\" to \"/home/dir2\"") .arg(torrent->name(), Utils::Fs::toNativePath(torrent->savePath()) @@ -412,25 +413,25 @@ void TransferListWidget::setSelectedTorrentsLocation() void TransferListWidget::pauseAllTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) torrent->pause(); } void TransferListWidget::resumeAllTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) torrent->resume(); } void TransferListWidget::startSelectedTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->resume(); } void TransferListWidget::forceStartSelectedTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->resume(true); } @@ -445,7 +446,7 @@ void TransferListWidget::startVisibleTorrents() void TransferListWidget::pauseSelectedTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->pause(); } @@ -478,7 +479,7 @@ void TransferListWidget::deleteSelectedTorrents(bool deleteLocalFiles) if (Preferences::instance()->confirmTorrentDeletion() && !DeletionConfirmationDialog::askForDeletionConfirmation(this, deleteLocalFiles, torrents.size(), torrents[0]->name())) return; - foreach (BitTorrent::TorrentHandle *const torrent, torrents) + for (BitTorrent::TorrentHandle *const torrent : torrents) BitTorrent::Session::instance()->deleteTorrent(torrent->hash(), deleteLocalFiles); } @@ -495,7 +496,7 @@ void TransferListWidget::deleteVisibleTorrents() && !DeletionConfirmationDialog::askForDeletionConfirmation(this, deleteLocalFiles, torrents.size(), torrents[0]->name())) return; - foreach (BitTorrent::TorrentHandle *const torrent, torrents) + for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrents)) BitTorrent::Session::instance()->deleteTorrent(torrent->hash(), deleteLocalFiles); } @@ -528,7 +529,7 @@ void TransferListWidget::bottomPrioSelectedTorrents() void TransferListWidget::copySelectedMagnetURIs() const { QStringList magnetUris; - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) magnetUris << torrent->toMagnetUri(); qApp->clipboard()->setText(magnetUris.join('\n')); @@ -537,7 +538,7 @@ void TransferListWidget::copySelectedMagnetURIs() const void TransferListWidget::copySelectedNames() const { QStringList torrentNames; - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrentNames << torrent->name(); qApp->clipboard()->setText(torrentNames.join('\n')); @@ -546,7 +547,7 @@ void TransferListWidget::copySelectedNames() const void TransferListWidget::copySelectedHashes() const { QStringList torrentHashes; - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrentHashes << torrent->hash(); qApp->clipboard()->setText(torrentHashes.join('\n')); @@ -566,13 +567,13 @@ void TransferListWidget::openSelectedTorrentsFolder() const #ifdef Q_OS_MAC // On macOS you expect both the files and folders to be opened in their parent // folders prehilighted for opening, so we use a custom method. - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { QString path = torrent->contentPath(true); pathsList.insert(path); } MacUtils::openFiles(pathsList); #else - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { QString path = torrent->contentPath(true); if (!pathsList.contains(path)) { if (torrent->filesCount() == 1) @@ -587,7 +588,7 @@ void TransferListWidget::openSelectedTorrentsFolder() const void TransferListWidget::previewSelectedTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { if (torrent->hasMetadata()) new PreviewSelectDialog(this, torrent); } @@ -596,7 +597,7 @@ void TransferListWidget::previewSelectedTorrents() void TransferListWidget::setDlLimitSelectedTorrents() { QList torrentsList; - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { if (torrent->isSeed()) continue; torrentsList += torrent; @@ -604,7 +605,7 @@ void TransferListWidget::setDlLimitSelectedTorrents() if (torrentsList.empty()) return; int oldLimit = torrentsList.first()->downloadLimit(); - foreach (BitTorrent::TorrentHandle *const torrent, torrentsList) { + for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { if (torrent->downloadLimit() != oldLimit) { oldLimit = -1; break; @@ -617,7 +618,7 @@ void TransferListWidget::setDlLimitSelectedTorrents() , BitTorrent::Session::instance()->globalDownloadSpeedLimit()); if (!ok) return; - foreach (BitTorrent::TorrentHandle *const torrent, torrentsList) { + for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); torrent->setDownloadLimit(newLimit); } @@ -629,7 +630,7 @@ void TransferListWidget::setUpLimitSelectedTorrents() if (torrentsList.empty()) return; int oldLimit = torrentsList.first()->uploadLimit(); - foreach (BitTorrent::TorrentHandle *const torrent, torrentsList) { + for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { if (torrent->uploadLimit() != oldLimit) { oldLimit = -1; break; @@ -642,7 +643,7 @@ void TransferListWidget::setUpLimitSelectedTorrents() , BitTorrent::Session::instance()->globalUploadSpeedLimit()); if (!ok) return; - foreach (BitTorrent::TorrentHandle *const torrent, torrentsList) { + for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); torrent->setUploadLimit(newLimit); } @@ -670,7 +671,7 @@ void TransferListWidget::setMaxRatioSelectedTorrents() currentMaxSeedingTime, BitTorrent::TorrentHandle::MAX_SEEDING_TIME, this); if (dlg.exec() != QDialog::Accepted) return; - foreach (BitTorrent::TorrentHandle *const torrent, torrents) { + for (BitTorrent::TorrentHandle *const torrent : torrents) { qreal ratio = (dlg.useDefault() ? BitTorrent::TorrentHandle::USE_GLOBAL_RATIO : dlg.ratio()); torrent->setRatioLimit(ratio); @@ -686,13 +687,13 @@ void TransferListWidget::recheckSelectedTorrents() if (ret != QMessageBox::Yes) return; } - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->forceRecheck(); } void TransferListWidget::reannounceSelectedTorrents() { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->forceReannounce(); } @@ -738,7 +739,7 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&) void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { if (torrent->hasMetadata()) torrent->setSuperSeeding(!torrent->superSeeding()); } @@ -746,19 +747,19 @@ void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->toggleSequentialDownload(); } void TransferListWidget::toggleSelectedFirstLastPiecePrio() const { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->toggleFirstLastPiecePriority(); } void TransferListWidget::setSelectedAutoTMMEnabled(bool enabled) const { - foreach (BitTorrent::TorrentHandle *const torrent, getSelectedTorrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) torrent->setAutoTMMEnabled(enabled); } @@ -772,7 +773,7 @@ void TransferListWidget::askNewCategoryForSelection() void TransferListWidget::askAddTagsForSelection() { const QStringList tags = askTagsForSelection(tr("Add Tags")); - foreach (const QString &tag, tags) + for (const QString &tag : tags) addSelectionTag(tag); } @@ -811,7 +812,7 @@ QStringList TransferListWidget::askTagsForSelection(const QString &dialogTitle) void TransferListWidget::applyToSelectedTorrents(const std::function &fn) { - foreach (const QModelIndex &index, selectionModel()->selectedRows()) { + for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) { BitTorrent::TorrentHandle *const torrent = m_listModel->torrentHandle(mapToSource(index)); Q_ASSERT(torrent); fn(torrent); @@ -839,7 +840,7 @@ void TransferListWidget::renameSelectedTorrent() void TransferListWidget::setSelectionCategory(QString category) { - foreach (const QModelIndex &index, selectionModel()->selectedRows()) + for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) m_listModel->setData(m_listModel->index(mapToSource(index).row(), TransferListModel::TR_CATEGORY), category, Qt::DisplayRole); } @@ -860,7 +861,7 @@ void TransferListWidget::clearSelectionTags() void TransferListWidget::displayListMenu(const QPoint&) { - QModelIndexList selectedIndexes = selectionModel()->selectedRows(); + const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); if (selectedIndexes.size() == 0) return; // Create actions @@ -936,7 +937,7 @@ void TransferListWidget::displayListMenu(const QPoint&) BitTorrent::TorrentHandle *torrent; qDebug("Displaying menu"); - foreach (const QModelIndex &index, selectedIndexes) { + for (const QModelIndex &index : selectedIndexes) { // Get the file name // Get handle and pause the torrent torrent = m_listModel->torrentHandle(mapToSource(index)); @@ -1022,7 +1023,7 @@ void TransferListWidget::displayListMenu(const QPoint&) categoryActions << categoryMenu->addAction(GuiIconProvider::instance()->getIcon("list-add"), tr("New...", "New category...")); categoryActions << categoryMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset category")); categoryMenu->addSeparator(); - foreach (QString category, categories) { + for (QString category : qAsConst(categories)) { category.replace('&', "&&"); // avoid '&' becomes accelerator key QAction *cat = new QAction(GuiIconProvider::instance()->getIcon("inode-directory"), category, categoryMenu); if (allSameCategory && (category == firstCategory)) { @@ -1041,7 +1042,7 @@ void TransferListWidget::displayListMenu(const QPoint&) tagsActions << tagsMenu->addAction(GuiIconProvider::instance()->getIcon("list-add"), tr("Add...", "Add / assign multiple tags...")); tagsActions << tagsMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Remove All", "Remove all tags")); tagsMenu->addSeparator(); - foreach (QString tag, tags) { + for (const QString &tag : qAsConst(tags)) { const Qt::CheckState initialState = tagsInAll.contains(tag) ? Qt::Checked : tagsInAny.contains(tag) ? Qt::PartiallyChecked : Qt::Unchecked; diff --git a/src/webui/api/logcontroller.cpp b/src/webui/api/logcontroller.cpp index 0ca60c5dd..9d15a82a6 100644 --- a/src/webui/api/logcontroller.cpp +++ b/src/webui/api/logcontroller.cpp @@ -30,6 +30,7 @@ #include +#include "base/global.h" #include "base/logger.h" #include "base/utils/string.h" @@ -71,7 +72,7 @@ void LogController::mainAction() Logger *const logger = Logger::instance(); QVariantList msgList; - foreach (const Log::Msg &msg, logger->getMessages(lastKnownId)) { + for (const Log::Msg &msg : copyAsConst(logger->getMessages(lastKnownId))) { if (!((msg.type == Log::NORMAL && isNormal) || (msg.type == Log::INFO && isInfo) || (msg.type == Log::WARNING && isWarning) @@ -110,7 +111,7 @@ void LogController::peersAction() Logger *const logger = Logger::instance(); QVariantList peerList; - foreach (const Log::Peer &peer, logger->getPeers(lastKnownId)) { + for (const Log::Peer &peer : copyAsConst(logger->getPeers(lastKnownId))) { QVariantMap map; map[KEY_LOG_ID] = peer.id; map[KEY_LOG_TIMESTAMP] = peer.timestamp; diff --git a/src/webui/api/searchcontroller.cpp b/src/webui/api/searchcontroller.cpp index 015d08467..716a6bd8a 100644 --- a/src/webui/api/searchcontroller.cpp +++ b/src/webui/api/searchcontroller.cpp @@ -263,7 +263,7 @@ void SearchController::checkForUpdatesFinished(const QHashupdatePlugin(pluginName); } diff --git a/src/webui/api/synccontroller.cpp b/src/webui/api/synccontroller.cpp index 86f4ccec8..17b12276b 100644 --- a/src/webui/api/synccontroller.cpp +++ b/src/webui/api/synccontroller.cpp @@ -35,6 +35,7 @@ #include "base/bittorrent/peerinfo.h" #include "base/bittorrent/session.h" #include "base/bittorrent/torrenthandle.h" +#include "base/global.h" #include "base/net/geoipmanager.h" #include "base/preferences.h" #include "base/utils/fs.h" @@ -133,7 +134,7 @@ namespace // num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake) quint32 peers = 0; - foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) peers += torrent->peersCount(); map[KEY_TRANSFER_WRITE_CACHE_OVERLOAD] = ((sessionStatus.diskWriteQueue > 0) && (peers > 0)) ? Utils::String::fromDouble((100. * sessionStatus.diskWriteQueue) / peers, 2) : "0"; map[KEY_TRANSFER_READ_CACHE_OVERLOAD] = ((sessionStatus.diskReadQueue > 0) && (peers > 0)) ? Utils::String::fromDouble((100. * sessionStatus.diskReadQueue) / peers, 2) : "0"; @@ -268,7 +269,7 @@ namespace syncData = data; } else { - foreach (QVariant item, data) { + for (const QVariant &item : data) { if (!prevData.contains(item)) // new list item found - append it to syncData syncData.append(item); @@ -409,7 +410,7 @@ void SyncController::maindataAction() BitTorrent::Session *const session = BitTorrent::Session::instance(); - foreach (BitTorrent::TorrentHandle *const torrent, session->torrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(session->torrents())) { QVariantMap map = serialize(*torrent); map.remove(KEY_TORRENT_HASH); @@ -468,7 +469,7 @@ void SyncController::torrentPeersAction() QVariantMap data; QVariantHash peers; - QList peersList = torrent->peers(); + const QList peersList = torrent->peers(); #ifndef DISABLE_COUNTRIES_RESOLUTION bool resolvePeerCountries = Preferences::instance()->resolvePeerCountries(); #else @@ -477,7 +478,7 @@ void SyncController::torrentPeersAction() data[KEY_SYNC_TORRENT_PEERS_SHOW_FLAGS] = resolvePeerCountries; - foreach (const BitTorrent::PeerInfo &pi, peersList) { + for (const BitTorrent::PeerInfo &pi : peersList) { if (pi.address().ip.isNull()) continue; QVariantMap peer; #ifndef DISABLE_COUNTRIES_RESOLUTION diff --git a/src/webui/api/torrentscontroller.cpp b/src/webui/api/torrentscontroller.cpp index 660bcab8c..0f4383443 100644 --- a/src/webui/api/torrentscontroller.cpp +++ b/src/webui/api/torrentscontroller.cpp @@ -113,7 +113,7 @@ namespace void applyToTorrents(const QStringList &hashes, const std::function &func) { if ((hashes.size() == 1) && (hashes[0] == QLatin1String("all"))) { - foreach (BitTorrent::TorrentHandle *torrent, BitTorrent::Session::instance()->torrents()) + for (BitTorrent::TorrentHandle *torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) func(torrent); } else { @@ -167,7 +167,7 @@ void TorrentsController::infoAction() QVariantList torrentList; TorrentFilter torrentFilter(filter, (hashSet.isEmpty() ? TorrentFilter::AnyHash : hashSet), category); - foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) { + for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) { if (torrentFilter.match(torrent)) torrentList.append(serialize(*torrent)); } @@ -307,7 +307,7 @@ void TorrentsController::trackersAction() throw APIError(APIErrorType::NotFound); QHash trackersData = torrent->trackerInfos(); - foreach (const BitTorrent::TrackerEntry &tracker, torrent->trackers()) { + for (const BitTorrent::TrackerEntry &tracker : copyAsConst(torrent->trackers())) { QVariantMap trackerDict; trackerDict[KEY_TRACKER_URL] = tracker.url(); const BitTorrent::TrackerInfo data = trackersData.value(tracker.url()); @@ -346,7 +346,7 @@ void TorrentsController::webseedsAction() if (!torrent) throw APIError(APIErrorType::NotFound); - foreach (const QUrl &webseed, torrent->urlSeeds()) { + for (const QUrl &webseed : copyAsConst(torrent->urlSeeds())) { QVariantMap webSeedDict; webSeedDict[KEY_WEBSEED_URL] = webseed.toString(); webSeedList.append(webSeedDict); @@ -419,7 +419,7 @@ void TorrentsController::pieceHashesAction() const QVector hashes = torrent->info().pieceHashes(); pieceHashes.reserve(hashes.size()); - foreach (const QByteArray &hash, hashes) + for (const QByteArray &hash : hashes) pieceHashes.append(hash.toHex()); setResult(QJsonArray::fromVariantList(pieceHashes)); @@ -531,7 +531,7 @@ void TorrentsController::addTrackersAction() BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) { QList trackers; - foreach (QString url, params()["urls"].split('\n')) { + for (QString url : copyAsConst(params()["urls"].split('\n'))) { url = url.trimmed(); if (!url.isEmpty()) trackers << url; @@ -575,7 +575,7 @@ void TorrentsController::uploadLimitAction() const QStringList hashes {params()["hashes"].split('|')}; QVariantMap map; - foreach (const QString &hash, hashes) { + for (const QString &hash : hashes) { int limit = -1; BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) @@ -592,7 +592,7 @@ void TorrentsController::downloadLimitAction() const QStringList hashes {params()["hashes"].split('|')}; QVariantMap map; - foreach (const QString &hash, hashes) { + for (const QString &hash : hashes) { int limit = -1; BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) diff --git a/src/webui/webapplication.cpp b/src/webui/webapplication.cpp index 252d1a945..64eb1e3b2 100644 --- a/src/webui/webapplication.cpp +++ b/src/webui/webapplication.cpp @@ -649,7 +649,8 @@ void WebApplication::sessionStart() // remove outdated sessions const qint64 now = QDateTime::currentMSecsSinceEpoch() / 1000; - foreach (const auto session, m_sessions) { + const QMap sessionsCopy {m_sessions}; + for (const auto session : sessionsCopy) { if ((now - session->timestamp()) > INACTIVE_TIME) delete m_sessions.take(session->id()); }